// MACRO_RULES ITEM self.parse_item_macro_rules(vis, has_bang)? } else if self.isnt_macro_invocation() <del> && (self.token.is_ident_named(sym::import) || self.token.is_ident_named(sym::using)) </del> <ins> && (self.token.is_ident_named(sym::import) || self.token.is_ident_named(sym::using) || self.token.is_ident_named(sym::include) || self.token.is_ident_named(sym::require)) </ins> { return self.recover_import_as_use(); } else if self.isnt_macro_invocation() && vis.kind.is_pub() {


repr_packed, repr_simd, repr_transparent, <ins> require, </ins> residual, result, rhs,


rc::Rc, }; <ins> use std::time::Duration; //~^ ERROR expected item, found `require` use std::time::Instant; //~^ ERROR expected item, found `include` </ins> pub use std::io; //~^ ERROR expected item, found `using` fn main() { let x = Rc::new(1); let _ = write!(io::stdout(), "{:?}", x); <ins> let _ = Duration::new(5, 0); let _ = Instant::now(); </ins> }


rc::Rc, }; <ins> require std::time::Duration; //~^ ERROR expected item, found `require` include std::time::Instant; //~^ ERROR expected item, found `include` </ins> pub using std::io; //~^ ERROR expected item, found `using` fn main() { let x = Rc::new(1); let _ = write!(io::stdout(), "{:?}", x); <ins> let _ = Duration::new(5, 0); let _ = Instant::now(); </ins> }


LL | import std::{ | ^^^^^^ help: items are imported using the `use` keyword <ins> error: expected item, found `require` --> $DIR/use_instead_of_import.rs:9:1 | LL | require std::time::Duration; | ^^^^^^^ help: items are imported using the `use` keyword error: expected item, found `include` --> $DIR/use_instead_of_import.rs:12:1 | LL | include std::time::Instant; | ^^^^^^^ help: items are imported using the `use` keyword </ins> error: expected item, found `using` <del> --> $DIR/use_instead_of_import.rs:9:5 </del> <ins> --> $DIR/use_instead_of_import.rs:15:5 </ins> | LL | pub using std::io; |     ^^^^^ help: items are imported using the `use` keyword <del> error: aborting due to 2 previous errors </del> <ins> error: aborting due to 4 previous errors </ins>


evaluation_cache: self.evaluation_cache.clone(), reported_trait_errors: self.reported_trait_errors.clone(), reported_closure_mismatch: self.reported_closure_mismatch.clone(), <del> tainted_by_errors_flag: self.tainted_by_errors_flag.clone(), </del> <ins> tainted_by_errors: self.tainted_by_errors.clone(), </ins> err_count_on_creation: self.err_count_on_creation, in_snapshot: self.in_snapshot.clone(), universe: self.universe.clone(),


use rustc_middle::ty::{self, GenericParamDefKind, InferConst, Ty, TyCtxt}; use rustc_middle::ty::{ConstVid, FloatVid, IntVid, TyVid}; use rustc_span::symbol::Symbol; <del> use rustc_span::Span; </del> <ins> use rustc_span::{Span, DUMMY_SP}; </ins> use std::cell::{Cell, Ref, RefCell}; use std::fmt;


/// /// Don't read this flag directly, call `is_tainted_by_errors()` /// and `set_tainted_by_errors()`. <del> tainted_by_errors_flag: Cell<bool>, </del> <ins> tainted_by_errors: Cell<Option<ErrorGuaranteed>>, </ins> /// Track how many errors were reported when this infcx is created. /// If the number of errors increases, that's also a sign (line /// `tainted_by_errors`) to avoid reporting certain kinds of errors. <del> // FIXME(matthewjasper) Merge into `tainted_by_errors_flag` </del> <ins> // FIXME(matthewjasper) Merge into `tainted_by_errors` </ins> err_count_on_creation: usize, /// This flag is true while there is an active snapshot.


evaluation_cache: Default::default(), reported_trait_errors: Default::default(), reported_closure_mismatch: Default::default(), <del> tainted_by_errors_flag: Cell::new(false), </del> <ins> tainted_by_errors: Cell::new(None), </ins> err_count_on_creation: tcx.sess.err_count(), in_snapshot: Cell::new(false), skip_leak_check: Cell::new(false),


pub fn is_tainted_by_errors(&self) -> bool { debug!( "is_tainted_by_errors(err_count={}, err_count_on_creation={},  <del> tainted_by_errors_flag={})", </del> <ins> tainted_by_errors={})", </ins> self.tcx.sess.err_count(), self.err_count_on_creation, <del> self.tainted_by_errors_flag.get() </del> <ins> self.tainted_by_errors.get().is_some() </ins> ); if self.tcx.sess.err_count() > self.err_count_on_creation { return true; // errors reported since this infcx was made } <del> self.tainted_by_errors_flag.get() </del> <ins> self.tainted_by_errors.get().is_some() </ins> } /// Set the "tainted by errors" flag to true. We call this when we /// observe an error from a prior pass. pub fn set_tainted_by_errors(&self) { debug!("set_tainted_by_errors()"); <del> self.tainted_by_errors_flag.set(true) </del> <ins> self.tainted_by_errors.set(Some( self.tcx.sess.delay_span_bug(DUMMY_SP, "`InferCtxt` incorrectly tainted by errors"), )); </ins> } pub fn skip_region_resolution(&self) {


debug!("impossible_predicates(predicates={:?})", predicates); let result = tcx.infer_ctxt().enter(|infcx| { <del> // HACK: Set tainted by errors to gracefully exit in case of overflow. infcx.set_tainted_by_errors(); </del> let param_env = ty::ParamEnv::reveal_all(); let ocx = ObligationCtxt::new(&infcx); let predicates = ocx.normalize(ObligationCause::dummy(), param_env, predicates);


) -> io::Result<(Process, StdioPipes)> { let maybe_env = self.env.capture_if_changed(); <del> let mut si = zeroed_startupinfo(); si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD; si.dwFlags = c::STARTF_USESTDHANDLES; </del> let child_paths = if let Some(env) = maybe_env.as_ref() { env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str()) } else {


let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?; let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?; let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?; <del> si.hStdInput = stdin.as_raw_handle(); si.hStdOutput = stdout.as_raw_handle(); si.hStdError = stderr.as_raw_handle(); </del> <ins> let mut si = zeroed_startupinfo(); si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD; // If at least one of stdin, stdout or stderr are set (i.e. are non null) // then set the `hStd` fields in `STARTUPINFO`. // Otherwise skip this and allow the OS to apply its default behaviour. // This provides more consistent behaviour between Win7 and Win8+. let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null(); if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) { si.dwFlags |= c::STARTF_USESTDHANDLES; si.hStdInput = stdin.as_raw_handle(); si.hStdOutput = stdout.as_raw_handle(); si.hStdError = stderr.as_raw_handle(); } </ins> unsafe { cvt(c::CreateProcessW(


impl Stdio { fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> { match *self { <del> // If no stdio handle is available, then inherit means that it // should still be unavailable so propagate the // INVALID_HANDLE_VALUE. </del> Stdio::Inherit => match stdio::get_handle(stdio_id) { Ok(io) => unsafe { let io = Handle::from_raw_handle(io);


io.into_raw_handle(); ret }, <del> Err(..) => unsafe { Ok(Handle::from_raw_handle(c::INVALID_HANDLE_VALUE)) }, </del> <ins> // If no stdio handle is available, then propagate the null value. Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) }, </ins> }, Stdio::MakePipe => {


wShowWindow: 0, cbReserved2: 0, lpReserved2: ptr::null_mut(), <del> hStdInput: c::INVALID_HANDLE_VALUE, hStdOutput: c::INVALID_HANDLE_VALUE, hStdError: c::INVALID_HANDLE_VALUE, </del> <ins> hStdInput: ptr::null_mut(), hStdOutput: ptr::null_mut(), hStdError: ptr::null_mut(), </ins> } }


<ins> #![feature(type_alias_impl_trait)] // check-pass trait Trait {} type TAIT = impl Trait; struct Concrete; impl Trait for Concrete {} fn tait() -> TAIT { Concrete } trait OuterTrait { type Item; } struct Dummy<T> { t: T, } impl<T> OuterTrait for Dummy<T> { type Item = T; } fn tait_and_impl_trait() -> impl OuterTrait<Item = (TAIT, impl Trait)> { Dummy { t: (tait(), Concrete), } } fn tait_and_dyn_trait() -> impl OuterTrait<Item = (TAIT, Box<dyn Trait>)> { let b: Box<dyn Trait> = Box::new(Concrete); Dummy { t: (tait(), b) } } fn main() {} </ins>


/// For more, see [this pull request](https://github.com/rust-lang/rust/pull/100591). pub const VERSION_": &str = "CURRENT_RUSTC_VERSION"; <ins> pub fn rust_version_symbol() -> Symbol { let version = option_env!("CFG_VERSION").unwrap_or("<current>"); let version = version.split(' ').next().unwrap(); Symbol::intern(&version) } </ins> pub fn is_builtin_attr(attr: &Attribute) -> bool { attr.is_doc_comment() || attr.ident().filter(|ident| is_builtin_attr_name(ident.name)).is_some() }


} if let Some(s) = since && s.as_str() == VERSION_" { <del> let version = option_env!("CFG_VERSION").unwrap_or("<current>"); let version = version.split(' ').next().unwrap(); since = Some(Symbol::intern(&version)); </del> <ins> since = Some(rust_version_symbol()); </ins> } match (feature, since) {


//! collect them instead. use rustc_ast::{Attribute, MetaItemKind}; <del> use rustc_attr::VERSION_"; </del> <ins> use rustc_attr::{rust_version_symbol, VERSION_"}; </ins> use rustc_errors::struct_span_err; use rustc_hir::intravisit::Visitor; use rustc_middle::hir::nested_filter;


} if let Some(s) = since && s.as_str() == VERSION_" { <del> let version = option_env!("CFG_VERSION").unwrap_or("<current>"); let version = version.split(' ').next().unwrap(); since = Some(Symbol::intern(&version)); </del> <ins> since = Some(rust_version_symbol()); </ins> } if let Some(feature) = feature {


//! propagating default levels lexically from parent to children ast nodes. use rustc_attr::{ <del> self as attr, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason, </del> <ins> self as attr, rust_version_symbol, ConstStability, Stability, StabilityLevel, Unstable, UnstableReason, VERSION_", </ins> }; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap}; use rustc_errors::{struct_span_err, Applicability};


}); } <del> fn unnecessary_stable_feature_lint(tcx: TyCtxt<'_>, span: Span, feature: Symbol, since: Symbol) { </del> <ins> fn unnecessary_stable_feature_lint( tcx: TyCtxt<'_>, span: Span, feature: Symbol, mut since: Symbol, ) { if since.as_str() == VERSION_" { since = rust_version_symbol(); } </ins> tcx.struct_span_lint_hir(lint::builtin::STABLE_FEATURES, hir::CRATE_HIR_ID, span, |lint| { lint.build(&format!( "the feature `{feature}` has been stable since {since} and no longer requires an


use rustc_middle::ty::layout::{LayoutError, LayoutOf}; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::GenericArgKind; <ins> use rustc_middle::ty::ToPredicate; </ins> use rustc_middle::ty::TypeVisitableExt; use rustc_middle::ty::{self, Instance, Ty, TyCtxt, VariantDef}; use rustc_session::config::ExpectedValues;


use rustc_span::{BytePos, InnerSpan, Span}; use rustc_target::abi::{Abi, FIRST_VARIANT}; use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt}; <ins> use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; </ins> use rustc_trait_selection::traits::{self, misc::type_allowed_to_implement_copy}; use crate::nonstandard_style::{method_context, MethodLateContext};


if ty.is_copy_modulo_regions(cx.tcx, param_env) { return; } <ins> if type_implements_negative_copy_modulo_regions(cx.tcx, ty, param_env) { return; } </ins> // We shouldn't recommend implementing `Copy` on stateful things, // such as iterators.


} } <ins> /// Check whether a `ty` has a negative `Copy` implementation, ignoring outlives constraints. fn type_implements_negative_copy_modulo_regions<'tcx>( tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, param_env: ty::ParamEnv<'tcx>, ) -> bool { let trait_ref = ty::TraitRef::new(tcx, tcx.require_lang_item(hir::LangItem::Copy, None), [ty]); let pred = ty::TraitPredicate { trait_ref, polarity: ty::ImplPolarity::Negative }; let obligation = traits::Obligation { cause: traits::ObligationCause::dummy(), param_env, recursion_depth: 0, predicate: ty::Binder::dummy(pred).to_predicate(tcx), }; tcx.infer_ctxt().build().predicate_must_hold_modulo_regions(&obligation) } </ins> declare_lint! { /// The `missing_debug_implementations` lint detects missing /// implementations of [`fmt::Debug`] for public types.


<ins> // Regression test for issue #101980. // Ensure that we don't suggest impl'ing `Copy` for a type if it already impl's `!Copy`. // check-pass #![feature(negative_impls)] #![deny(missing_copy_implementations)] pub struct Struct { pub field: i32, } impl !Copy for Struct {} fn main() {} </ins>


sig.decl.has_self(), sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)), &sig.decl.output, <del> ) </del> <ins> ); this.record_lifetime_params_for_async( fn_id, sig.header.asyncness.opt_return_id(), ); </ins> }, ); return;


}, ); <del> // Construct the list of in-scope lifetime parameters for async lowering. // We include all lifetime parameters, either named or "Fresh". // The order of those parameters does not matter, as long as it is // deterministic. if let Some((async_node_id, _)) = async_node_id { let mut extra_lifetime_params = this .r .extra_lifetime_params_map .get(&fn_id) .cloned() .unwrap_or_default(); for rib in this.lifetime_ribs.iter().rev() { extra_lifetime_params.extend( rib.bindings .iter() .map(|(&ident, &(node_id, res))| (ident, node_id, res)), ); match rib.kind { LifetimeRibKind::Item => break, LifetimeRibKind::AnonymousCreateParameter { binder, .. } => { if let Some(earlier_fresh) = this.r.extra_lifetime_params_map.get(&binder) { extra_lifetime_params.extend(earlier_fresh); } } _ => {} } } this.r .extra_lifetime_params_map .insert(async_node_id, extra_lifetime_params); } </del> <ins> this.record_lifetime_params_for_async(fn_id, async_node_id); </ins> if let Some(body) = body { // Ignore errors in function bodies if this is rustdoc


Some((ident.name, ns)), ) } <ins> /// Construct the list of in-scope lifetime parameters for async lowering. /// We include all lifetime parameters, either named or "Fresh". /// The order of those parameters does not matter, as long as it is /// deterministic. fn record_lifetime_params_for_async( &mut self, fn_id: NodeId, async_node_id: Option<(NodeId, Span)>, ) { if let Some((async_node_id, _)) = async_node_id { let mut extra_lifetime_params = self.r.extra_lifetime_params_map.get(&fn_id).cloned().unwrap_or_default(); for rib in self.lifetime_ribs.iter().rev() { extra_lifetime_params.extend( rib.bindings.iter().map(|(&ident, &(node_id, res))| (ident, node_id, res)), ); match rib.kind { LifetimeRibKind::Item => break, LifetimeRibKind::AnonymousCreateParameter { binder, .. } => { if let Some(earlier_fresh) = self.r.extra_lifetime_params_map.get(&binder) { extra_lifetime_params.extend(earlier_fresh); } } _ => {} } } self.r.extra_lifetime_params_map.insert(async_node_id, extra_lifetime_params); } } </ins> } struct LifetimeCountVisitor<'a, 'b> {


<ins> // check-pass // edition:2021 #![feature(async_fn_in_trait)] #![allow(incomplete_features)] use std::future::Future; async fn yield_now() {} trait AsyncIterator { type Item; async fn next(&mut self) -> Option<Self::Item>; } struct YieldingRange { counter: u32, stop: u32, } impl AsyncIterator for YieldingRange { type Item = u32; async fn next(&mut self) -> Option<Self::Item> { if self.counter == self.stop { None } else { let c = self.counter; self.counter += 1; yield_now().await; Some(c) } } } async fn async_main() { let mut x = YieldingRange { counter: 0, stop: 10 }; while let Some(v) = x.next().await { println!("Hi: {v}"); } } fn main() { let _ = async_main(); } </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>


ObligationCauseCode::BinOp { rhs_span: Some(span), is_lit, .. } if *is_lit => span, _ => return, }; <del> match ( trait_ref.skip_binder().self_ty().kind(), trait_ref.skip_binder().substs.type_at(1).kind(), ) { (ty::Float(_), ty::Infer(InferTy::IntVar(_))) => { err.span_suggestion_verbose( rhs_span.shrink_to_hi(), "consider using a floating-point literal by writing it with `.0`", ".0", Applicability::MaybeIncorrect, ); } _ => {} </del> <ins> if let ty::Float(_) = trait_ref.skip_binder().self_ty().kind() && let ty::Infer(InferTy::IntVar(_)) = trait_ref.skip_binder().substs.type_at(1).kind() { err.span_suggestion_verbose( rhs_span.shrink_to_hi(), "consider using a floating-point literal by writing it with `.0`", ".0", Applicability::MaybeIncorrect, ); </ins> } }


<ins> // normalize-stderr-test "loaded from .*libcore-.*.rlib" -> "loaded from SYSROOT/libcore-*.rlib" #![feature(lang_items)] #[lang="sized"] trait Sized { } //~ ERROR found duplicate lang item `sized` fn ref_Struct(self: &Struct, f: &u32) -> &u32 { //~^ ERROR `self` parameter is only allowed in associated functions //~| ERROR cannot find type `Struct` in this scope //~| ERROR mismatched types let x = x << 1; //~^ ERROR the size for values of type `{integer}` cannot be known at compilation time //~| ERROR cannot find value `x` in this scope } fn main() {} </ins>


<ins> error: `self` parameter is only allowed in associated functions --> $DIR/issue-102989.rs:7:15 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { |               ^^^^ not semantically valid as function parameter | = note: associated functions are those in `impl` or `trait` definitions error[E0412]: cannot find type `Struct` in this scope --> $DIR/issue-102989.rs:7:22 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { |                      ^^^^^^ not found in this scope error[E0425]: cannot find value `x` in this scope --> $DIR/issue-102989.rs:11:13 | LL |     let x = x << 1; |             ^ help: a local variable with a similar name exists: `f` error[E0152]: found duplicate lang item `sized` --> $DIR/issue-102989.rs:5:1 | LL | trait Sized { } | ^^^^^^^^^^^ | = note: the lang item is first defined in crate `core` (which `std` depends on) = note: first definition in `core` loaded from SYSROOT/libcore-*.rlib = note: second definition in the local crate (`issue_102989`) error[E0277]: the size for values of type `{integer}` cannot be known at compilation time --> $DIR/issue-102989.rs:11:15 | LL |     let x = x << 1; |               ^^ doesn't have a size known at compile-time | = help: the trait `std::marker::Sized` is not implemented for `{integer}` error[E0308]: mismatched types --> $DIR/issue-102989.rs:7:42 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { |    ----------                            ^^^^ expected `&u32`, found `()` |    | |    implicitly returns `()` as its body has no tail or `return` expression | note: consider returning one of these bindings --> $DIR/issue-102989.rs:7:30 | LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 { |                              ^ ... LL |     let x = x << 1; |         ^ error: aborting due to 6 previous errors Some errors have detailed explanations: E0152, E0277, E0308, E0412, E0425. For more information about an error, try `rustc --explain E0152`. </ins>


if self.eat(&token::ModSep) { self.parse_use_tree_glob_or_nested()? } else { <ins> // Recover from using a colon as path separator. while self.eat_noexpect(&token::Colon) { self.struct_span_err(self.prev_token.span, "expected `::`, found `:`") .span_suggestion_short( self.prev_token.span, "use double colon", "::", Applicability::MachineApplicable, ) .note_once("import paths are delimited using `::`") .emit(); // We parse the rest of the path and append it to the original prefix. self.parse_path_segments(&mut prefix.segments, PathStyle::Mod, None)?; prefix.span = lo.to(self.prev_token.span); } </ins> UseTreeKind::Simple(self.parse_rename()?, DUMMY_NODE_ID, DUMMY_NODE_ID) } };


<ins> // Recover from using a colon as a path separator. use std::process:Command; //~^ ERROR expected `::`, found `:` use std:fs::File; //~^ ERROR expected `::`, found `:` use std:collections:HashMap; //~^ ERROR expected `::`, found `:` //~| ERROR expected `::`, found `:` fn main() { } </ins>


<ins> error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:3:17 | LL | use std::process:Command; |                 ^ help: use double colon | = note: import paths are delimited using `::` error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:5:8 | LL | use std:fs::File; |        ^ help: use double colon error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:7:8 | LL | use std:collections:HashMap; |        ^ help: use double colon error: expected `::`, found `:` --> $DIR/use-colon-as-mod-sep.rs:7:20 | LL | use std:collections:HashMap; |                    ^ help: use double colon error: aborting due to 4 previous errors </ins>


#include_next <winsock2.h> <ins> // mingw 4.0.x has broken headers (#9246) but mingw-w64 does not. #if defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION == 4 </ins> typedef struct pollfd { SOCKET fd; short  events;


} WSAPOLLFD, *PWSAPOLLFD, *LPWSAPOLLFD; #endif <ins> #endif // _FIX_WINSOCK2_H </ins>


use smallvec::{smallvec, SmallVec}; use rustc_span::source_map::{respan, Spanned}; <ins> use std::assert_matches::debug_assert_matches; </ins> use std::collections::{hash_map::Entry, BTreeSet}; use std::mem::{replace, take};


/// They will be used to determine the correct lifetime for the fn return type. /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named /// lifetimes. <del> lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>, </del> <ins> lifetime_elision_candidates: Option<Vec<(LifetimeRes, LifetimeElisionCandidate)>>, </ins> /// The trait that the current context can refer to. current_trait_ref: Option<(Module<'a>, TraitRef)>,


match res { LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => { if let Some(ref mut candidates) = self.lifetime_elision_candidates { <del> candidates.insert(res, candidate); </del> <ins> candidates.push((res, candidate)); </ins> } } LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}


has_self: bool, inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>, ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> { <del> let outer_candidates = replace(&mut self.lifetime_elision_candidates, Some(Default::default())); </del> <ins> enum Elision { /// We have not found any candidate. None, /// We have a candidate bound to `self`. Self_(LifetimeRes), /// We have a candidate bound to a parameter. Param(LifetimeRes), /// We failed elision. Err, } </ins> <del> let mut elision_lifetime = None; let mut lifetime_count = 0; </del> <ins> // Save elision state to reinstate it later. let outer_candidates = self.lifetime_elision_candidates.take(); // Result of elision. let mut elision_lifetime = Elision::None; // Information for diagnostics. </ins> let mut parameter_info = Vec::new(); <ins> let mut all_candidates = Vec::new(); </ins> let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; for (index, (pat, ty)) in inputs.enumerate() {


this.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); } }); <ins> // Record elision candidates only for this parameter. debug_assert_matches!(self.lifetime_elision_candidates, None); self.lifetime_elision_candidates = Some(Default::default()); </ins> self.visit_ty(ty); <ins> let local_candidates = self.lifetime_elision_candidates.take(); </ins> <del> if let Some(ref candidates) = self.lifetime_elision_candidates { let new_count = candidates.len(); let local_count = new_count - lifetime_count; if local_count != 0 { </del> <ins> if let Some(candidates) = local_candidates { let distinct: FxHashSet<_> = candidates.iter().map(|(res, _)| *res).collect(); let lifetime_count = distinct.len(); if lifetime_count != 0 { </ins> parameter_info.push(ElisionFnParameter { index, ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {


} else { None }, <del> lifetime_count: local_count, </del> <ins> lifetime_count, </ins> span: ty.span, }); <ins> all_candidates.extend(candidates.into_iter().filter_map(|(_, candidate)| { match candidate { LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => { None } LifetimeElisionCandidate::Missing(missing) => Some(missing), } })); } let mut distinct_iter = distinct.into_iter(); if let Some(res) = distinct_iter.next() { match elision_lifetime { // We are the first parameter to bind lifetimes. Elision::None => { if distinct_iter.next().is_none() { // We have a single lifetime => success. elision_lifetime = Elision::Param(res) } else { // We have have multiple lifetimes => error. elision_lifetime = Elision::Err; } } // We have 2 parameters that bind lifetimes => error. Elision::Param(_) => elision_lifetime = Elision::Err, // `self` elision takes precedence over everything else. Elision::Self_(_) | Elision::Err => {} } </ins> } <del> lifetime_count = new_count; </del> } // Handle `self` specially. if index == 0 && has_self { let self_lifetime = self.find_lifetime_for_self(ty); if let Set1::One(lifetime) = self_lifetime { <del> elision_lifetime = Some(lifetime); self.lifetime_elision_candidates = None; </del> <ins> // We found `self` elision. elision_lifetime = Elision::Self_(lifetime); </ins> } else { <del> self.lifetime_elision_candidates = Some(Default::default()); lifetime_count = 0; </del> <ins> // We do not have `self` elision: disregard the `Elision::Param` that we may // have found. elision_lifetime = Elision::None; </ins> } } debug!("(resolving function / closure) recorded parameter"); } <del> let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates); debug!(?all_candidates); </del> <ins> // Reinstate elision state. debug_assert_matches!(self.lifetime_elision_candidates, None); self.lifetime_elision_candidates = outer_candidates; </ins> <del> if let Some(res) = elision_lifetime { </del> <ins> if let Elision::Param(res) | Elision::Self_(res) = elision_lifetime { </ins> return Ok(res); } <del> // We do not have a `self` candidate, look at the full list. let all_candidates = all_candidates.unwrap(); if all_candidates.len() == 1 { Ok(*all_candidates.first().unwrap().0) } else { let all_candidates = all_candidates .into_iter() .filter_map(|(_, candidate)| match candidate { LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None, LifetimeElisionCandidate::Missing(missing) => Some(missing), }) .collect(); Err((all_candidates, parameter_info)) } </del> <ins> // We do not have a candidate. Err((all_candidates, parameter_info)) </ins> } /// List all the lifetimes that appear in the provided type.


// Do not account for the parameters we just bound for function lifetime elision. if let Some(ref mut candidates) = self.lifetime_elision_candidates { for (_, res) in function_lifetime_rib.bindings.values() { <del> candidates.remove(res); </del> <ins> candidates.retain(|(r, _)| r != res); </ins> } }


//! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`. #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")] <ins> #![feature(assert_matches)] </ins> #![feature(box_patterns)] #![feature(drain_filter)] #![feature(if_let_guard)]


panic!() } <ins> fn l<'a>(_: &'a str, _: &'a str) -> &str { "" } //~^ ERROR missing lifetime specifier // This is ok because both `'a` are for the same parameter. fn m<'a>(_: &'a Foo<'a>) -> &str { "" } </ins> fn main() {}


LL | fn k<'a, T: WithLifetime<'a>>(_x: T::Output) -> &'a isize { |                                                  ++ <del> error: aborting due to 6 previous errors </del> <ins> error[E0106]: missing lifetime specifier --> $DIR/lifetime-elision-return-type-requires-explicit-lifetime.rs:45:37 | LL | fn l<'a>(_: &'a str, _: &'a str) -> &str { "" } |             -------     -------     ^ expected named lifetime parameter | = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments help: consider using the `'a` lifetime | LL | fn l<'a>(_: &'a str, _: &'a str) -> &'a str { "" } |                                      ++ error: aborting due to 7 previous errors </ins> For more information about this error, try `rustc --explain E0106`.


// FIXME(#75598): Direct use of these intrinsics improves codegen significantly at opt-level <= // 1, where the method versions of these operations are not inlined. use intrinsics::{ <del> cttz_nonzero, exact_div, unchecked_rem, unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, </del> <ins> cttz_nonzero, exact_div, mul_with_overflow, unchecked_rem, unchecked_shl, unchecked_shr, unchecked_sub, wrapping_add, wrapping_mul, wrapping_sub, </ins> }; /// Calculate multiplicative modular inverse of `x` modulo `m`.


const INV_TABLE_MOD_16: [u8; 8] = [1, 11, 13, 7, 9, 3, 5, 15]; /// Modulo for which the `INV_TABLE_MOD_16` is intended. const INV_TABLE_MOD: usize = 16; <del> /// INV_TABLE_MOD² const INV_TABLE_MOD_SQUARED: usize = INV_TABLE_MOD * INV_TABLE_MOD; let table_inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize; </del> // SAFETY: `m` is required to be a power-of-two, hence non-zero. let m_minus_one = unsafe { unchecked_sub(m, 1) }; <del> if m <= INV_TABLE_MOD { table_inverse & m_minus_one } else { // We iterate "up" using the following formula: // // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$ </del> <ins> let mut inverse = INV_TABLE_MOD_16[(x & (INV_TABLE_MOD - 1)) >> 1] as usize; let mut mod_gate = INV_TABLE_MOD; // We iterate "up" using the following formula: // // $$ xy ≡ 1 (mod 2ⁿ) → xy (2 - xy) ≡ 1 (mod 2²ⁿ) $$ // // This application needs to be applied at least until `2²ⁿ ≥ m`, at which point we can // finally reduce the computation to our desired `m` by taking `inverse mod m`. // // This computation is `O(log log m)`, which is to say, that on 64-bit machines this loop // will always finish in at most 4 iterations. loop { // y = y * (2 - xy) mod n </ins> // <del> // until 2²ⁿ ≥ m. Then we can reduce to our desired `m` by taking the result `mod m`. let mut inverse = table_inverse; let mut going_mod = INV_TABLE_MOD_SQUARED; loop { // y = y * (2 - xy) mod n // // Note, that we use wrapping operations here intentionally – the original formula // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod // usize::MAX` instead, because we take the result `mod n` at the end // anyway. inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse))); if going_mod >= m { return inverse & m_minus_one; } going_mod = wrapping_mul(going_mod, going_mod); </del> <ins> // Note, that we use wrapping operations here intentionally – the original formula // uses e.g., subtraction `mod n`. It is entirely fine to do them `mod // usize::MAX` instead, because we take the result `mod n` at the end // anyway. if mod_gate >= m { break; } inverse = wrapping_mul(inverse, wrapping_sub(2usize, wrapping_mul(x, inverse))); let (new_gate, overflow) = mul_with_overflow(mod_gate, mod_gate); if overflow { break; </ins> } <ins> mod_gate = new_gate; </ins> } <ins> inverse & m_minus_one </ins> } let addr = p.addr();


} #[test] <ins> fn align_offset_issue_103361() { #[cfg(target_pointer_width = "64")] const SIZE: usize = 1 << 47; #[cfg(target_pointer_width = "32")] const SIZE: usize = 1 << 30; #[cfg(target_pointer_width = "16")] const SIZE: usize = 1 << 13; struct HugeSize([u8; SIZE - 1]); let _ = (SIZE as *const HugeSize).align_offset(SIZE); } #[test] </ins> fn offset_from() { let mut a = [0; 5]; let ptr1: *mut i32 = &mut a[1];


add_constraints(&infcx, region_bound_pairs); <ins> infcx.process_registered_region_obligations( outlives_environment.region_bound_pairs(), param_env, ); </ins> let errors = infcx.resolve_regions(&outlives_environment); debug!(?errors, "errors");


<ins> trait TraitA { type TypeA; } trait TraitD { type TypeD; } pub trait TraitB { type TypeB: TraitD; fn f(_: &<Self::TypeB as TraitD>::TypeD); } pub trait TraitC<E> { type TypeC<'a>: TraitB; fn g<'a>(_: &<<Self::TypeC<'a> as TraitB>::TypeB as TraitA>::TypeA); //~^ ERROR the trait bound `<<Self as TraitC<E>>::TypeC<'a> as TraitB>::TypeB: TraitA` is not satisfied } fn main() {} </ins>


<ins> error[E0277]: the trait bound `<<Self as TraitC<E>>::TypeC<'a> as TraitB>::TypeB: TraitA` is not satisfied --> $DIR/issue-103573.rs:18:5 | LL |     fn g<'a>(_: &<<Self::TypeC<'a> as TraitB>::TypeB as TraitA>::TypeA); |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `TraitA` is not implemented for `<<Self as TraitC<E>>::TypeC<'a> as TraitB>::TypeB` | help: consider further restricting the associated type | LL |     fn g<'a>(_: &<<Self::TypeC<'a> as TraitB>::TypeB as TraitA>::TypeA) where <<Self as TraitC<E>>::TypeC<'a> as TraitB>::TypeB: TraitA; |                                                                         +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. </ins>


}); if check_params && let Some(args) = path.segments.last().unwrap().args { let params_in_repr = tcx.params_in_repr(def_id); <del> for (i, arg) in args.args.iter().enumerate() { </del> <ins> // the domain size check is needed because the HIR may not be well-formed at this point for (i, arg) in args.args.iter().enumerate().take(params_in_repr.domain_size()) { </ins> if let hir::GenericArg::Type(ty) = arg && params_in_repr.contains(i as u32) { find_item_ty_spans(tcx, ty, needle, spans, seen_representable); }


<ins> #![crate_type = "lib"] struct Apple((Apple, Option(Banana ? Citron))); //~^ ERROR invalid `?` in type //~| ERROR expected one of `)` or `,`, found `Citron` //~| ERROR cannot find type `Citron` in this scope [E0412] //~| ERROR parenthesized type parameters may only be used with a `Fn` trait [E0214] //~| ERROR recursive type `Apple` has infinite size [E0072] </ins>


<ins> error: invalid `?` in type --> $DIR/issue-103748-ICE-wrong-braces.rs:3:36 | LL | struct Apple((Apple, Option(Banana ? Citron))); |                                    ^ `?` is only allowed on expressions, not types | help: if you meant to express that the type might not contain a value, use the `Option` wrapper type | LL | struct Apple((Apple, Option(Option<Banana > Citron))); |                             +++++++       ~ error: expected one of `)` or `,`, found `Citron` --> $DIR/issue-103748-ICE-wrong-braces.rs:3:38 | LL | struct Apple((Apple, Option(Banana ? Citron))); |                                     -^^^^^^ expected one of `)` or `,` |                                     | |                                     help: missing `,` error[E0412]: cannot find type `Citron` in this scope --> $DIR/issue-103748-ICE-wrong-braces.rs:3:38 | LL | struct Apple((Apple, Option(Banana ? Citron))); |                                      ^^^^^^ not found in this scope error[E0214]: parenthesized type parameters may only be used with a `Fn` trait --> $DIR/issue-103748-ICE-wrong-braces.rs:3:22 | LL | struct Apple((Apple, Option(Banana ? Citron))); |                      ^^^^^^^^^^^^^^^^^^^^^^^ only `Fn` traits may use parentheses | help: use angle brackets instead | LL | struct Apple((Apple, Option<Banana ? Citron>)); |                            ~               ~ error[E0072]: recursive type `Apple` has infinite size --> $DIR/issue-103748-ICE-wrong-braces.rs:3:1 | LL | struct Apple((Apple, Option(Banana ? Citron))); | ^^^^^^^^^^^^  ----- recursive without indirection | help: insert some indirection (e.g., a `Box`, `Rc`, or `&`) to break the cycle | LL | struct Apple((Box<Apple>, Option(Banana ? Citron))); |               ++++     + error: aborting due to 5 previous errors Some errors have detailed explanations: E0072, E0214, E0412. For more information about an error, try `rustc --explain E0072`. </ins>


[submodule "src/llvm-project"] path = src/llvm-project url = https://github.com/rust-lang/llvm-project.git <del> branch = rustc/15.0-2022-08-09 </del> <ins> branch = rustc/15.0-2022-12-07 </ins> [submodule "src/doc/embedded-book"] path = src/doc/embedded-book url = https://github.com/rust-embedded/book.git


<del> Subproject commit a1232c451fc27173f8718e05d174b2503ca0b607 </del> <ins> Subproject commit 3dfd4d93fa013e1c0578d3ceac5c8f4ebba4b6ec </ins>


<del> Subproject commit 3dfd4d93fa013e1c0578d3ceac5c8f4ebba4b6ec </del> <ins> Subproject commit 9ad24035fea8d309753f5e39e6eb53d1d0eb39ce </ins>


assert!(self_ty.is_some()); } } else { <del> assert!(self_ty.is_none() && parent_substs.is_empty()); </del> <ins> assert!(self_ty.is_none()); </ins> } let arg_count = Self::check_generic_arg_count(


// Check if we have an enum variant. let mut variant_resolution = None; <del> if let ty::Adt(adt_def, _) = qself_ty.kind() { </del> <ins> if let ty::Adt(adt_def, adt_substs) = qself_ty.kind() { </ins> if adt_def.is_enum() { let variant_def = adt_def .variants()


let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else { continue; }; <del> // FIXME(inherent_associated_types): This does not substitute parameters. let ty = tcx.type_of(assoc_ty_did); </del> <ins> let item_substs = self.create_substs_for_associated_item( span, assoc_ty_did, assoc_segment, adt_substs, ); let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs); </ins> return Ok((ty, DefKind::AssocTy, assoc_ty_did)); } }


<ins> // check-pass #![feature(inherent_associated_types)] #![allow(incomplete_features)] struct S<T>(T); impl<T> S<T> { type P = T; } fn main() { type A = S<()>::P; let _: A = (); } </ins>


} // see if we can satisfy using an inherent associated type <del> for impl_ in tcx.inherent_impls(adt_def.did()) { let assoc_ty = tcx.associated_items(impl_).find_by_name_and_kind( tcx, assoc_ident, ty::AssocKind::Type, *impl_, ); if let Some(assoc_ty) = assoc_ty { let ty = tcx.type_of(assoc_ty.def_id); return Ok((ty, DefKind::AssocTy, assoc_ty.def_id)); } </del> <ins> for &impl_ in tcx.inherent_impls(adt_def.did()) { let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else { continue; }; // FIXME(inherent_associated_types): This does not substitute parameters. let ty = tcx.type_of(assoc_ty_did); return Ok((ty, DefKind::AssocTy, assoc_ty_did)); </ins> } }


}; let trait_did = bound.def_id(); <del> let (assoc_ident, def_scope) = tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id); // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `filter_by_name_and_kind`. let item = tcx.associated_items(trait_did).in_definition_order().find(|i| { i.kind.namespace() == Namespace::TypeNS && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident }); // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. let Some(item) = item else { </del> <ins> let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else { // Assume that if it's not matched, there must be a const defined with the same name // but it was used in a type position. </ins> let msg = format!("found associated const `{assoc_ident}` when type was expected"); let guar = tcx.sess.struct_span_err(span, &msg).emit(); return Err(guar); }; <del> let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound); </del> <ins> let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound); </ins> let ty = self.normalize_ty(span, ty); <del> let kind = DefKind::AssocTy; if !item.visibility(tcx).is_accessible_from(def_scope, tcx) { let kind = kind.descr(item.def_id); let msg = format!("{} `{}` is private", kind, assoc_ident); tcx.sess .struct_span_err(span, &msg) .span_label(span, &format!("private {}", kind)) .emit(); } tcx.check_stability(item.def_id, Some(hir_ref_id), span, None); </del> if let Some(variant_def_id) = variant_resolution { tcx.struct_span_lint_hir( AMBIGUOUS_ASSOCIATED_ITEMS,


}; could_refer_to(DefKind::Variant, variant_def_id, ""); <del> could_refer_to(kind, item.def_id, " also"); </del> <ins> could_refer_to(DefKind::AssocTy, assoc_ty_did, " also"); </ins> lint.span_suggestion( span,


}, ); } <del> Ok((ty, kind, item.def_id)) </del> <ins> Ok((ty, DefKind::AssocTy, assoc_ty_did)) } fn lookup_assoc_ty( &self, ident: Ident, block: hir::HirId, span: Span, scope: DefId, ) -> Option<DefId> { let tcx = self.tcx(); let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block); // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `find_by_name_and_kind`. let item = tcx.associated_items(scope).in_definition_order().find(|i| { i.kind.namespace() == Namespace::TypeNS && i.ident(tcx).normalize_to_macros_2_0() == ident })?; let kind = DefKind::AssocTy; if !item.visibility(tcx).is_accessible_from(def_scope, tcx) { let kind = kind.descr(item.def_id); let msg = format!("{kind} `{ident}` is private"); let def_span = self.tcx().def_span(item.def_id); tcx.sess .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624)) .span_label(span, &format!("private {kind}")) .span_label(def_span, &format!("{kind} defined here")) .emit(); } tcx.check_stability(item.def_id, Some(block), span, None); Some(item.def_id) </ins> } fn qpath_to_ty(


<ins> #![feature(inherent_associated_types)] #![allow(incomplete_features)] mod m { pub struct T; impl T { type P = (); } } type U = m::T::P; //~ ERROR associated type `P` is private mod n { pub mod n { pub struct T; impl T { pub(super) type P = bool; } } type U = n::T::P; } type V = n::n::T::P; //~ ERROR associated type `P` is private fn main() {} </ins>


<ins> error[E0624]: associated type `P` is private --> $DIR/assoc-inherent-private.rs:10:10 | LL |         type P = (); |         ------ associated type defined here ... LL | type U = m::T::P; |          ^^^^^^^ private associated type error[E0624]: associated type `P` is private --> $DIR/assoc-inherent-private.rs:21:10 | LL |             pub(super) type P = bool; |             ----------------- associated type defined here ... LL | type V = n::n::T::P; |          ^^^^^^^^^^ private associated type error: aborting due to 2 previous errors For more information about this error, try `rustc --explain E0624`. </ins>


<ins> // aux-crate:aux=assoc-inherent-unstable.rs // edition: 2021 type Data = aux::Owner::Data; //~ ERROR use of unstable library feature 'data' fn main() {} </ins>


<ins> error[E0658]: use of unstable library feature 'data' --> $DIR/assoc-inherent-unstable.rs:4:13 | LL | type Data = aux::Owner::Data; |             ^^^^^^^^^^^^^^^^ | = help: add `#![feature(data)]` to the crate attributes to enable error: aborting due to previous error For more information about this error, try `rustc --explain E0658`. </ins>


<ins> #![feature(staged_api)] #![feature(inherent_associated_types)] #![stable(feature = "main", since = "1.0.0")] #[stable(feature = "main", since = "1.0.0")] pub struct Owner; impl Owner { #[unstable(feature = "data", issue = "none")] pub type Data = (); } </ins>


LL |     let _: S::C; |            ^^^^ help: use fully-qualified syntax: `<S as Trait>::C` <del> error: associated type `A` is private </del> <ins> error[E0624]: associated type `A` is private </ins> --> $DIR/item-privacy.rs:119:12 | <ins> LL |         type A = u8; |         ------ associated type defined here ... </ins> LL |     let _: T::A; |            ^^^^ private associated type


/// /// assert_eq!(n.leading_zeros(), 0); /// ``` <ins> #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")] </ins> #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")] #[must_use = "this returns the result of the operation,


/// Returns the number of leading zeros in the binary representation of `self`. /// <ins> /// Depending on what you're doing with the value, you might also be interested in the /// [`ilog2`] function which returns a consistent number, even if the type widens. /// </ins> /// # Examples /// /// Basic usage:


/// /// assert_eq!(n.leading_zeros(), 2); /// ``` <ins> #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")] </ins> #[stable(feature = "rust1", since = "1.0.0")] #[rustc_const_stable(feature = "const_math", since = "1.32.0")] #[must_use = "this returns the result of the operation,


}; e_flags } <del> Architecture::Riscv64 if sess.target.options.features.contains("+d") => { // copied from `riscv64-linux-gnu-gcc foo.c -c`, note though // that the `+d` target feature represents whether the double // float abi is enabled. let e_flags = elf::EF_RISCV_RVC | elf::EF_RISCV_FLOAT_ABI_DOUBLE; </del> <ins> Architecture::Riscv32 | Architecture::Riscv64 => { // Source: https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/079772828bd10933d34121117a222b4cc0ee2200/riscv-elf.adoc let mut e_flags: u32 = 0x0; let features = &sess.target.options.features; // Check if compressed is enabled if features.contains("+c") { e_flags |= elf::EF_RISCV_RVC; } // Select the appropriate floating-point ABI if features.contains("+d") { e_flags |= elf::EF_RISCV_FLOAT_ABI_DOUBLE; } else if features.contains("+f") { e_flags |= elf::EF_RISCV_FLOAT_ABI_SINGLE; } else { e_flags |= elf::EF_RISCV_FLOAT_ABI_SOFT; } </ins> e_flags } _ => 0,


// In the algorithm above, we can change // cast(relative_tag) + niche_variants.start() // into <del> // cast(tag) + (niche_variants.start() - niche_start) </del> <ins> // cast(tag + (niche_variants.start() - niche_start)) </ins> // if either the casted type is no larger than the original // type, or if the niche values are contiguous (in either the // signed or unsigned sense). <del> let can_incr_after_cast = cast_smaller || niches_ule || niches_sle; </del> <ins> let can_incr = cast_smaller || niches_ule || niches_sle; </ins> let data_for_boundary_niche = || -> Option<(IntPredicate, u128)> { <del> if !can_incr_after_cast { </del> <ins> if !can_incr { </ins> None } else if niche_start == low_unsigned { Some((IntPredicate::IntULE, niche_end))


// The algorithm is now this: // is_niche = tag <= niche_end // discr = if is_niche { <del> //     cast(tag) + (niche_variants.start() - niche_start) </del> <ins> //     cast(tag + (niche_variants.start() - niche_start)) </ins> // } else { //     untagged_variant // } // (the first line may instead be tag >= niche_start, // and may be a signed or unsigned comparison) <ins> // The arithmetic must be done before the cast, so we can // have the correct wrapping behavior. See issue #104519 for // the consequences of getting this wrong. </ins> let is_niche = bx.icmp(predicate, tag, bx.cx().const_uint_big(tag_llty, constant)); <ins> let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); let incr_tag = if delta == 0 { tag } else { bx.add(tag, bx.cx().const_uint_big(tag_llty, delta)) }; </ins> let cast_tag = if cast_smaller { <del> bx.intcast(tag, cast_to, false) </del> <ins> bx.intcast(incr_tag, cast_to, false) </ins> } else if niches_ule { <del> bx.zext(tag, cast_to) </del> <ins> bx.zext(incr_tag, cast_to) </ins> } else { <del> bx.sext(tag, cast_to) </del> <ins> bx.sext(incr_tag, cast_to) </ins> }; <del> let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start); (is_niche, cast_tag, delta) </del> <ins> (is_niche, cast_tag, 0) </ins> } else { // The special cases don't apply, so we'll have to go with // the general algorithm.


// CHECK: define i8 @match1{{.*}} // CHECK-NEXT: start: <del> // CHECK-NEXT: %1 = icmp ugt i8 %0, 1 // CHECK-NEXT: %2 = zext i8 %0 to i64 // CHECK-NEXT: %3 = add nsw i64 %2, -1 // CHECK-NEXT: %_2 = select i1 %1, i64 %3, i64 0 // CHECK-NEXT: switch i64 %_2, label {{.*}} [ </del> <ins> // CHECK-NEXT: %1 = {{.*}}call i8 @llvm.usub.sat.i8(i8 %0, i8 1) // CHECK-NEXT: switch i8 %1, label {{.*}} [ </ins> #[no_mangle] pub fn match1(e: Enum1) -> u8 { use Enum1::*;


<ins> // run-pass #![allow(dead_code)] enum OpenResult { Ok(()), Err(()), TransportErr(TransportErr), } #[repr(i32)] enum TransportErr { UnknownMethod = -2, } #[inline(never)] fn some_match(result: OpenResult) -> u8 { match result { OpenResult::Ok(()) => 0, _ => 1, } } fn main() { let result = OpenResult::Ok(()); assert_eq!(some_match(result), 0); let result = OpenResult::Ok(()); match result { OpenResult::Ok(()) => (), _ => unreachable!("message a"), } match result { OpenResult::Ok(()) => (), _ => unreachable!("message b"), } } </ins>


} } <del> /// Create an `Rc<[T]>` by reusing the underlying memory /// of a `Vec<T>`. This will return the vector if the existing allocation /// is not large enough. #[cfg(not(no_global_oom_handling))] fn try_from_vec_in_place(mut v: Vec<T>) -> Result<Rc<[T]>, Vec<T>> { let layout_elements = Layout::array::<T>(v.len()).unwrap(); let layout_allocation = Layout::array::<T>(v.capacity()).unwrap(); let layout_rcbox = rcbox_layout_for_value_layout(layout_elements); let mut ptr = NonNull::new(v.as_mut_ptr()).expect("`Vec<T>` stores `NonNull<T>`"); if layout_rcbox.size() > layout_allocation.size() || layout_rcbox.align() > layout_allocation.align() { // Can't fit - calling `grow` would involve `realloc` // (which copies the elements), followed by copying again. return Err(v); } if layout_rcbox.size() < layout_allocation.size() || layout_rcbox.align() < layout_allocation.align() { // We need to shrink the allocation so that it fits // https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html#memory-fitting // SAFETY: // - Vec allocates by requesting `Layout::array::<T>(capacity)`, so this capacity matches // - `layout_rcbox` is smaller // If this fails, the ownership has not been transferred if let Ok(p) = unsafe { Global.shrink(ptr.cast(), layout_allocation, layout_rcbox) } { ptr = p.cast(); } else { return Err(v); } } // Make sure the vec's memory isn't deallocated now let v = mem::ManuallyDrop::new(v); let ptr: *mut RcBox<[T]> = ptr::slice_from_raw_parts_mut(ptr.as_ptr(), v.len()) as _; unsafe { ptr::copy(ptr.cast::<T>(), &mut (*ptr).value as *mut [T] as *mut T, v.len()); ptr::write(&mut (*ptr).strong, Cell::new(1)); ptr::write(&mut (*ptr).weak, Cell::new(1)); Ok(Self::from_ptr(ptr)) } } </del> /// Constructs an `Rc<[T]>` from an iterator known to be of a certain size. /// /// Behavior is undefined should the size be wrong.


/// assert_eq!(vec![1, 2, 3], *shared); /// ``` #[inline] <del> fn from(v: Vec<T>) -> Rc<[T]> { match Rc::try_from_vec_in_place(v) { Ok(rc) => rc, Err(mut v) => { unsafe { let rc = Rc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc } } </del> <ins> fn from(mut v: Vec<T>) -> Rc<[T]> { unsafe { let rc = Rc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc </ins> } } }


} } <del> /// Create an `Arc<[T]>` by reusing the underlying memory /// of a `Vec<T>`. This will return the vector if the existing allocation /// is not large enough. #[cfg(not(no_global_oom_handling))] fn try_from_vec_in_place(mut v: Vec<T>) -> Result<Arc<[T]>, Vec<T>> { let layout_elements = Layout::array::<T>(v.len()).unwrap(); let layout_allocation = Layout::array::<T>(v.capacity()).unwrap(); let layout_arcinner = arcinner_layout_for_value_layout(layout_elements); let mut ptr = NonNull::new(v.as_mut_ptr()).expect("`Vec<T>` stores `NonNull<T>`"); if layout_arcinner.size() > layout_allocation.size() || layout_arcinner.align() > layout_allocation.align() { // Can't fit - calling `grow` would involve `realloc` // (which copies the elements), followed by copying again. return Err(v); } if layout_arcinner.size() < layout_allocation.size() || layout_arcinner.align() < layout_allocation.align() { // We need to shrink the allocation so that it fits // https://doc.rust-lang.org/nightly/std/alloc/trait.Allocator.html#memory-fitting // SAFETY: // - Vec allocates by requesting `Layout::array::<T>(capacity)`, so this capacity matches // - `layout_arcinner` is smaller // If this fails, the ownership has not been transferred if let Ok(p) = unsafe { Global.shrink(ptr.cast(), layout_allocation, layout_arcinner) } { ptr = p.cast(); } else { return Err(v); } } // Make sure the vec's memory isn't deallocated now let v = mem::ManuallyDrop::new(v); let ptr: *mut ArcInner<[T]> = ptr::slice_from_raw_parts_mut(ptr.as_ptr(), v.len()) as _; unsafe { ptr::copy(ptr.cast::<T>(), &mut (*ptr).data as *mut [T] as *mut T, v.len()); ptr::write(&mut (*ptr).strong, atomic::AtomicUsize::new(1)); ptr::write(&mut (*ptr).weak, atomic::AtomicUsize::new(1)); Ok(Self::from_ptr(ptr)) } } </del> /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size. /// /// Behavior is undefined should the size be wrong.


/// assert_eq!(&[1, 2, 3], &shared[..]); /// ``` #[inline] <del> fn from(v: Vec<T>) -> Arc<[T]> { match Arc::try_from_vec_in_place(v) { Ok(rc) => rc, Err(mut v) => { unsafe { let rc = Arc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc } } </del> <ins> fn from(mut v: Vec<T>) -> Arc<[T]> { unsafe { let rc = Arc::copy_from_slice(&v); // Allow the Vec to free its memory, but not destroy its contents v.set_len(0); rc </ins> } } }


// `val` dropped here while still borrowed // borrow might be used here, when `val` is dropped and runs the `Drop` code for type `std::sync::Weak` } <del> #[test] fn arc_from_vec_opt() { let mut v = Vec::with_capacity(64); v.push(0usize); let addr = v.as_ptr().cast::<u8>(); let arc: Arc<[_]> = v.into(); unsafe { assert_eq!( arc.as_ptr().cast::<u8>().offset_from(addr), (std::mem::size_of::<usize>() * 2) as isize, "Vector allocation not reused" ); } } </del>


// `val` dropped here while still borrowed // borrow might be used here, when `val` is dropped and runs the `Drop` code for type `std::rc::Weak` } <del> #[test] fn rc_from_vec_opt() { let mut v = Vec::with_capacity(64); v.push(0usize); let addr = v.as_ptr().cast::<u8>(); let rc: Rc<[_]> = v.into(); unsafe { assert_eq!( rc.as_ptr().cast::<u8>().offset_from(addr), (std::mem::size_of::<usize>() * 2) as isize, "Vector allocation not reused" ); } } </del>


} ty::FnPtr(sig) => (sig, None), _ => { <ins> for arg in arg_exprs { self.check_expr(arg); } </ins> if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &callee_expr.kind && let [segment] = path.segments && let Some(mut diag) = self


expected: Expectation<'tcx>, ) -> Option<Ty<'tcx>> { if let [callee_expr, rest @ ..] = arg_exprs { <del> let callee_ty = self.check_expr(callee_expr); </del> <ins> let callee_ty = self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr)?; </ins> // First, do a probe with `IsSuggestion(true)` to avoid emitting // any strange errors. If it's successful, then we'll do a true // method lookup.


<ins> fn main() -> Result<(), ()> { a(b(c(d(e( //~^ ERROR cannot find function `a` in this scope //~| ERROR cannot find function `b` in this scope //~| ERROR cannot find function `c` in this scope //~| ERROR cannot find function `d` in this scope //~| ERROR cannot find function `e` in this scope z???????????????????????????????????????????????????????????????????????????????????????? ????????????????????????????????????????????????????????????????????????????????????????? ?????????????????????????????????????????????????????????????????? //~^^^ ERROR cannot find value `z` in this scope ))))) } </ins>


<ins> error[E0425]: cannot find value `z` in this scope --> $DIR/fn-to-method-deeply-nested.rs:8:9 | LL |         z???????????????????????????????????????????????????????????????????????????????????????? |         ^ not found in this scope error[E0425]: cannot find function `e` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:13 | LL |     a(b(c(d(e( |             ^ not found in this scope error[E0425]: cannot find function `d` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:11 | LL |     a(b(c(d(e( |           ^ not found in this scope error[E0425]: cannot find function `c` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:9 | LL |     a(b(c(d(e( |         ^ not found in this scope error[E0425]: cannot find function `b` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:7 | LL |     a(b(c(d(e( |       ^ not found in this scope error[E0425]: cannot find function `a` in this scope --> $DIR/fn-to-method-deeply-nested.rs:2:5 | LL |     a(b(c(d(e( |     ^ not found in this scope error: aborting due to 6 previous errors For more information about this error, try `rustc --explain E0425`. </ins>


<ins> fn main() { a((), 1i32 == 2u32); //~^ ERROR cannot find function `a` in this scope //~| ERROR mismatched types } </ins>


<ins> error[E0308]: mismatched types --> $DIR/check-args-on-fn-err-2.rs:2:19 | LL |     a((), 1i32 == 2u32); |           ----    ^^^^ expected `i32`, found `u32` |           | |           expected because this is `i32` | help: change the type of the numeric literal from `u32` to `i32` | LL |     a((), 1i32 == 2i32); |                    ~~~ error[E0425]: cannot find function `a` in this scope --> $DIR/check-args-on-fn-err-2.rs:2:5 | LL |     a((), 1i32 == 2u32); |     ^ not found in this scope error: aborting due to 2 previous errors Some errors have detailed explanations: E0308, E0425. For more information about an error, try `rustc --explain E0308`. </ins>


<ins> fn main() { unknown(1, |glyf| { //~^ ERROR: cannot find function `unknown` in this scope let actual = glyf; }); } </ins>


<ins> error[E0425]: cannot find function `unknown` in this scope --> $DIR/check-args-on-fn-err.rs:2:5 | LL |     unknown(1, |glyf| { |     ^^^^^^^ not found in this scope error: aborting due to previous error For more information about this error, try `rustc --explain E0425`. </ins>


_ => {} } } <del> let lines = origtext.lines().filter_map(|l| map_line(l).for_html()); let text = lines.intersperse("n".into()).collect::<String>(); </del> let parse_result = match kind { CodeBlockKind::Fenced(ref lang) => {


{}

", lang,  Escape(&text),   Escape(&origtext),  ) .into(), ));


CodeBlockKind::Indented => Default::default(), }; <ins> let lines = origtext.lines().filter_map(|l| map_line(l).for_html()); let text = lines.intersperse("n".into()).collect::<String>(); </ins> compile_fail = parse_result.compile_fail; should_panic = parse_result.should_panic; ignore = parse_result.ignore;


t("```rustn```n```rustn```", &[1, 3]); t("```rustn```n ```rustn```", &[1, 3]); }  #[test] fn test_ascii_with_prepending_hashtag() { fn t(input: &str, expect: &str) { let mut map = IdMap::new(); let output = Markdown { content: input, links: &[], ids: &mut map, error_codes: ErrorCodes::Yes, edition: DEFAULT_EDITION, playground: &None, heading_offset: HeadingOffset::H2, } .into_string(); assert_eq!(output, expect, "original: {}", input); } t( r#"```ascii #..#.####.#....#.....##.. #..#.#....#....#....#..#. ####.###..#....#....#..#. #..#.#....#....#....#..#. #..#.#....#....#....#..#. #..#.####.####.####..##.. ```"#, "

 #..#.####.#....#.....##.. #..#.#....#....#....#..#. ####.###..#....#....#..#. #..#.#....#....#....#..#. #..#.#....#....#....#..#. #..#.####.####.####..##..

", ); }


let entry = spanned_predicates.entry(spans); entry.or_insert_with(|| (path, tr_self_ty, Vec::new())).2.push(p); } <ins> Some(Node::Item(hir::Item { kind: hir::ItemKind::Trait(rustc_ast::ast::IsAuto::Yes, ..), span: item_span, .. })) => { tcx.sess.delay_span_bug( *item_span, "auto trait is invoked with no method error, but no error reported?", ); } </ins> Some(_) => unreachable!(), None => (), }


<ins> #![feature(auto_traits)] auto trait Foo { fn g(&self); //~ ERROR auto traits cannot have associated items } trait Bar { fn f(&self) { self.g(); //~ ERROR the method `g` exists for reference `&Self`, but its trait bounds were not satisfied } } fn main() {} </ins>


<ins> error[E0380]: auto traits cannot have associated items --> $DIR/issue-105732.rs:4:8 | LL | auto trait Foo { |            --- auto trait cannot have associated items LL |     fn g(&self); |     ---^-------- help: remove these associated items error[E0599]: the method `g` exists for reference `&Self`, but its trait bounds were not satisfied --> $DIR/issue-105732.rs:9:14 | LL |         self.g(); |              ^ | = note: the following trait bounds were not satisfied: `Self: Foo` which is required by `&Self: Foo` `&Self: Foo` = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `g`, perhaps you need to add a supertrait for it: | LL | trait Bar: Foo { |          +++++ error: aborting due to 2 previous errors Some errors have detailed explanations: E0380, E0599. For more information about an error, try `rustc --explain E0380`. </ins>


GenericParamKind, HirId, Node, }; use rustc_hir as hir; <ins> use rustc_hir::def::DefKind; </ins> use rustc_hir::def_id::DefId; use rustc_middle::ty::{self, TyCtxt}; use rustc_session::lint;


Some(tcx.typeck_root_def_id(def_id)) } Node::Item(item) => match item.kind { <del> ItemKind::OpaqueTy(hir::OpaqueTy { .. }) => { </del> <ins> ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(fn_def_id) | hir::OpaqueTyOrigin::AsyncFn(fn_def_id), in_trait, .. }) => { if in_trait { assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn)) } else { assert!(matches!(tcx.def_kind(fn_def_id), DefKind::AssocFn | DefKind::Fn)) } Some(fn_def_id.to_def_id()) } ItemKind::OpaqueTy(hir::OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => { </ins> let parent_id = tcx.hir().get_parent_item(hir_id); assert_ne!(parent_id, hir::CRATE_OWNER_ID); debug!("generics_of: parent of opaque ty {:?} is {:?}", def_id, parent_id);


<del> // check-pass </del> // edition: 2021 <ins> // known-bug: #105197 // failure-status:101 // dont-check-compiler-stderr </ins> #![feature(async_fn_in_trait)] #![feature(return_position_impl_trait_in_trait)]


self.typeck_results.borrow().qpath_res(qpath, callee_expr.hir_id) } hir::ExprKind::Call(ref inner_callee, _) => { <del> // If the call spans more than one line and the callee kind is // itself another `ExprCall`, that's a clue that we might just be // missing a semicolon (Issue #51055) let call_is_multiline = self.tcx.sess.source_map().is_multiline(call_expr.span); if call_is_multiline { err.span_suggestion( callee_expr.span.shrink_to_hi(), "consider using a semicolon here", ";", Applicability::MaybeIncorrect, ); } </del> if let hir::ExprKind::Path(ref inner_qpath) = inner_callee.kind { inner_callee_path = Some(inner_qpath); self.typeck_results.borrow().qpath_res(inner_qpath, inner_callee.hir_id)


}; if !self.maybe_suggest_bad_array_definition(&mut err, call_expr, callee_expr) { <ins> // If the call spans more than one line and the callee kind is // itself another `ExprCall`, that's a clue that we might just be // missing a semicolon (#51055, #106515). let call_is_multiline = self .tcx .sess .source_map() .is_multiline(call_expr.span.with_lo(callee_expr.span.hi())) && call_expr.span.ctxt() == callee_expr.span.ctxt(); if call_is_multiline { err.span_suggestion( callee_expr.span.shrink_to_hi(), "consider using a semicolon here to finish the statement", ";", Applicability::MaybeIncorrect, ); } </ins> if let Some((maybe_def, output_ty, _)) = self.extract_callable_info(callee_ty) && !self.type_is_sized_modulo_regions(self.param_env, output_ty) {


|   ----------------------- `vindictive` defined here returns `bool` ... LL |       vindictive() <del> |       -^^^^^^^^^^^- help: consider using a semicolon here: `;` </del> <ins> |       -^^^^^^^^^^^- help: consider using a semicolon here to finish the statement: `;` </ins> |  _____| | | LL | |     (1, 2)


<ins> // run-rustfix #![allow(dead_code, unused_variables, path_statements)] fn a() { let x = 5; let y = x; //~ ERROR expected function (); //~ ERROR expected `;`, found `}` } fn b() { let x = 5; let y = x; //~ ERROR expected function (); } fn c() { let x = 5; x; //~ ERROR expected function () } fn d() { // ok let x = || (); x () } fn e() { // ok let x = || (); x (); } fn f() { let y = 5; //~ ERROR expected function (); //~ ERROR expected `;`, found `}` } fn g() { 5; //~ ERROR expected function (); } fn main() {} </ins>


<ins> // run-rustfix #![allow(dead_code, unused_variables, path_statements)] fn a() { let x = 5; let y = x //~ ERROR expected function () //~ ERROR expected `;`, found `}` } fn b() { let x = 5; let y = x //~ ERROR expected function (); } fn c() { let x = 5; x //~ ERROR expected function () } fn d() { // ok let x = || (); x () } fn e() { // ok let x = || (); x (); } fn f() { let y = 5 //~ ERROR expected function () //~ ERROR expected `;`, found `}` } fn g() { 5 //~ ERROR expected function (); } fn main() {} </ins>


<ins> error: expected `;`, found `}` --> $DIR/missing-semicolon.rs:6:7 | LL |     () |       ^ help: add `;` here LL | } | - unexpected token error: expected `;`, found `}` --> $DIR/missing-semicolon.rs:32:7 | LL |     () |       ^ help: add `;` here LL | } | - unexpected token error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:5:13 | LL |       let x = 5; |           - `x` has type `{integer}` LL |       let y = x |               ^- help: consider using a semicolon here to finish the statement: `;` |  _____________| | | LL | |     () | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:11:13 | LL |       let x = 5; |           - `x` has type `{integer}` LL |       let y = x |               ^- help: consider using a semicolon here to finish the statement: `;` |  _____________| | | LL | |     (); | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:16:5 | LL |       let x = 5; |           - `x` has type `{integer}` LL |       x |       ^- help: consider using a semicolon here to finish the statement: `;` |  _____| | | LL | |     () | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:31:13 | LL |       let y = 5 |               ^- help: consider using a semicolon here to finish the statement: `;` |  _____________| | | LL | |     () | |______- call expression requires function error[E0618]: expected function, found `{integer}` --> $DIR/missing-semicolon.rs:35:5 | LL |       5 |       ^- help: consider using a semicolon here to finish the statement: `;` |  _____| | | LL | |     (); | |______- call expression requires function error: aborting due to 7 previous errors For more information about this error, try `rustc --explain E0618`. </ins>


note = "if you want to iterate between `start` until a value `end`, use the exclusive range  syntax `start..end` or the inclusive range syntax `start..=end`" ), <ins> on( _Self = "{float}", note = "if you want to iterate between `start` until a value `end`, use the exclusive range  syntax `start..end` or the inclusive range syntax `start..=end`" ), </ins> label = "`{Self}` is not an iterator", message = "`{Self}` is not an iterator" )]


<ins> // #106728 fn main() { for i in 0.2 { //~^ ERROR `{float}` is not an iterator //~| `{float}` is not an iterator //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE in this expansion of desugaring of `for` loop //~| NOTE if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` //~| NOTE required for `{float}` to implement `IntoIterator` println!(); } } </ins>


<ins> error[E0277]: `{float}` is not an iterator --> $DIR/float_iterator_hint.rs:4:14 | LL |     for i in 0.2 { |              ^^^ `{float}` is not an iterator | = help: the trait `Iterator` is not implemented for `{float}` = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` = note: required for `{float}` to implement `IntoIterator` error: aborting due to previous error For more information about this error, try `rustc --explain E0277`. </ins>


|              ^^^^ `{float}` is not an iterator | = help: the trait `Iterator` is not implemented for `{float}` <ins> = note: if you want to iterate between `start` until a value `end`, use the exclusive range syntax `start..end` or the inclusive range syntax `start..=end` </ins> = note: required for `{float}` to implement `IntoIterator` error: aborting due to 12 previous errors


if !check && paths.is_empty() { match get_modified_rs_files(build) { Ok(Some(files)) => { <ins> if files.len() <= 10 { for file in &files { println!("formatting modified file {file}"); } } else { println!("formatting {} modified files", files.len()); } </ins> for file in files { <del> println!("formatting modified file {file}"); </del> ignore_fmt.add(&format!("/{file}")).expect(&file); } }


sections[None] = [] section_order = [None] targets = {} <ins> top_level_keys = [] </ins> for line in open(rust_dir + '/config.toml.example').read().split("n"): <ins> if cur_section == None: if line.count('=') == 1: top_level_key = line.split('=')[0] top_level_key = top_level_key.strip(' #') top_level_keys.append(top_level_key) </ins> if line.startswith('['): cur_section = line[1:-1] if cur_section.startswith('target'):


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:


all(target_vendor = "fortanix", target_env = "sgx"), feature(slice_index_methods, coerce_unsized, sgx_platform) )] <ins> #![cfg_attr(windows, feature(round_char_boundary))] </ins> // // Language features: #![feature(alloc_error_handler)]


use crate::ffi::CStr; use crate::mem; <del> use crate::os::raw::{c_char, c_int, c_long, c_longlong, c_uint, c_ulong, c_ushort}; </del> <ins> use crate::os::raw::{c_char, c_long, c_longlong, c_uint, c_ulong, c_ushort}; </ins> use crate::os::windows::io::{BorrowedHandle, HandleOrInvalid, HandleOrNull}; use crate::ptr; use core::ffi::NonZero_c_ulong; use libc::{c_void, size_t, wchar_t}; <ins> pub use crate::os::raw::c_int; </ins> #[path = "c/errors.rs"] // c.rs is included from two places so we need to specify this mod errors; pub use errors::*;


pub type LPBOOL = *mut BOOL; pub type LPBYTE = *mut BYTE; <ins> pub type LPCCH = *const CHAR; </ins> pub type LPCSTR = *const CHAR; <ins> pub type LPCWCH = *const WCHAR; </ins> pub type LPCWSTR = *const WCHAR; <ins> pub type LPCVOID = *const c_void; </ins> pub type LPDWORD = *mut DWORD; pub type LPHANDLE = *mut HANDLE; pub type LPOVERLAPPED = *mut OVERLAPPED; pub type LPPROCESS_INFORMATION = *mut PROCESS_INFORMATION; pub type LPSECURITY_ATTRIBUTES = *mut SECURITY_ATTRIBUTES; pub type LPSTARTUPINFO = *mut STARTUPINFO; <ins> pub type LPSTR = *mut CHAR; </ins> pub type LPVOID = *mut c_void; <del> pub type LPCVOID = *const c_void; </del> pub type LPWCH = *mut WCHAR; pub type LPWIN32_FIND_DATAW = *mut WIN32_FIND_DATAW; pub type LPWSADATA = *mut WSADATA;


pub const FILE_TYPE_PIPE: u32 = 3; <ins> pub const CP_UTF8: DWORD = 65001; pub const MB_ERR_INVALID_CHARS: DWORD = 0x08; pub const WC_ERR_INVALID_CHARS: DWORD = 0x80; </ins> #[repr(C)] #[derive(Copy)] pub struct WIN32_FIND_DATAW {


lpFilePart: *mut LPWSTR, ) -> DWORD; pub fn GetFileAttributesW(lpFileName: LPCWSTR) -> DWORD; <ins> pub fn MultiByteToWideChar( CodePage: UINT, dwFlags: DWORD, lpMultiByteStr: LPCCH, cbMultiByte: c_int, lpWideCharStr: LPWSTR, cchWideChar: c_int, ) -> c_int; pub fn WideCharToMultiByte( CodePage: UINT, dwFlags: DWORD, lpWideCharStr: LPCWCH, cchWideChar: c_int, lpMultiByteStr: LPSTR, cbMultiByte: c_int, lpDefaultChar: LPCCH, lpUsedDefaultChar: LPBOOL, ) -> c_int; </ins> } #[link(name = "ws2_32")]


} fn write_valid_utf8_to_console(handle: c::HANDLE, utf8: &str) -> io::Result<usize> { <ins> debug_assert!(!utf8.is_empty()); </ins> let mut utf16 = [MaybeUninit::<u16>::uninit(); MAX_BUFFER_SIZE / 2]; <del> let mut len_utf16 = 0; for (chr, dest) in utf8.encode_utf16().zip(utf16.iter_mut()) { *dest = MaybeUninit::new(chr); len_utf16 += 1; } // Safety: We've initialized `len_utf16` values. let utf16: &[u16] = unsafe { MaybeUninit::slice_assume_init_ref(&utf16[..len_utf16]) }; </del> <ins> let utf8 = &utf8[..utf8.floor_char_boundary(utf16.len())]; let utf16: &[u16] = unsafe { // Note that this theoretically checks validity twice in the (most common) case // where the underlying byte sequence is valid utf-8 (given the check in `write()`). let result = c::MultiByteToWideChar( c::CP_UTF8,                      // CodePage c::MB_ERR_INVALID_CHARS,         // dwFlags utf8.as_ptr() as c::LPCCH,       // lpMultiByteStr utf8.len() as c::c_int,          // cbMultiByte utf16.as_mut_ptr() as c::LPWSTR, // lpWideCharStr utf16.len() as c::c_int,         // cchWideChar ); assert!(result != 0, "Unexpected error in MultiByteToWideChar"); // Safety: MultiByteToWideChar initializes `result` values. MaybeUninit::slice_assume_init_ref(&utf16[..result as usize]) }; </ins> let mut written = write_u16s(handle, &utf16)?;


// a missing surrogate can be produced (and also because of the UTF-8 validation above), // write the missing surrogate out now. // Buffering it would mean we have to lie about the number of bytes written. <del> let first_char_remaining = utf16[written]; if first_char_remaining >= 0xDCEE && first_char_remaining <= 0xDFFF { </del> <ins> let first_code_unit_remaining = utf16[written]; if first_code_unit_remaining >= 0xDCEE && first_code_unit_remaining <= 0xDFFF { </ins> // low surrogate // We just hope this works, and give up otherwise let _ = write_u16s(handle, &utf16[written..written + 1]);


} fn write_u16s(handle: c::HANDLE, data: &[u16]) -> io::Result<usize> { <ins> debug_assert!(data.len() < u32::MAX as usize); </ins> let mut written = 0; cvt(unsafe { c::WriteConsoleW(


Ok(amount as usize) } <del> #[allow(unused)] </del> fn utf16_to_utf8(utf16: &[u16], utf8: &mut [u8]) -> io::Result<usize> { <del> let mut written = 0; for chr in char::decode_utf16(utf16.iter().cloned()) { match chr { Ok(chr) => { chr.encode_utf8(&mut utf8[written..]); written += chr.len_utf8(); } Err(_) => { // We can't really do any better than forget all data and return an error. return Err(io::const_io_error!( io::ErrorKind::InvalidData, "Windows stdin in console mode does not support non-UTF-16 input;  encountered unpaired surrogate", )); } } </del> <ins> debug_assert!(utf16.len() <= c::c_int::MAX as usize); debug_assert!(utf8.len() <= c::c_int::MAX as usize); let result = unsafe { c::WideCharToMultiByte( c::CP_UTF8,                    // CodePage c::WC_ERR_INVALID_CHARS,       // dwFlags utf16.as_ptr(),                // lpWideCharStr utf16.len() as c::c_int,       // cchWideChar utf8.as_mut_ptr() as c::LPSTR, // lpMultiByteStr utf8.len() as c::c_int,        // cbMultiByte ptr::null(),                   // lpDefaultChar ptr::null_mut(),               // lpUsedDefaultChar ) }; if result == 0 { // We can't really do any better than forget all data and return an error. Err(io::const_io_error!( io::ErrorKind::InvalidData, "Windows stdin in console mode does not support non-UTF-16 input;  encountered unpaired surrogate", )) } else { Ok(result as usize) </ins> } <del> Ok(written) </del> } impl IncompleteUtf8 {


invalid monomorphization of `{$name}` intrinsic: unsupported {$name} from `{$in_ty}` with element `{$elem_ty}` to `{$ret_ty}` codegen_gcc_invalid_monomorphization_invalid_bitmask = <del> invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` </del> <ins> invalid monomorphization of `{$name}` intrinsic: invalid bitmask `{$ty}`, expected `u{$expected_int_bits}` or `[u8; {$expected_bytes}]` </ins> codegen_gcc_invalid_monomorphization_simd_shuffle = invalid monomorphization of `{$name}` intrinsic: simd_shuffle index must be an array of `u32`, got `{$ty}`


codegen_ssa_unsupported_arch = unsupported arch `{$arch}` for os `{$os}` <del> codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {error} </del> <ins> codegen_ssa_apple_sdk_error_sdk_path = failed to get {$sdk_name} SDK path: {$error} </ins> <del> codegen_ssa_read_file = failed to read file: {message} </del> <ins> codegen_ssa_read_file = failed to read file: {$message} </ins> codegen_ssa_unsupported_link_self_contained = option `-C link-self-contained` is not supported on this target


}; use fluent_bundle::{FluentBundle, FluentError, FluentResource}; use fluent_syntax::{ <del> ast::{Attribute, Entry, Identifier, Message}, </del> <ins> ast::{ Attribute, Entry, Expression, Identifier, InlineExpression, Message, Pattern, PatternElement, }, </ins> parser::ParserError, }; use proc_macro::{Diagnostic, Level, Span};


}; let mut constants = TokenStream::new(); <ins> let mut messagerefs = Vec::new(); </ins> for entry in resource.entries() { let span = res.krate.span(); <del> if let Entry::Message(Message { id: Identifier { name }, attributes, .. }) = entry { </del> <ins> if let Entry::Message(Message { id: Identifier { name }, attributes, value, .. }) = entry { </ins> let _ = previous_defns.entry(name.to_string()).or_insert(path_span); if name.contains('-') {


.emit(); } <ins> if let Some(Pattern { elements }) = value { for elt in elements { if let PatternElement::Placeable { expression: Expression::Inline(InlineExpression::MessageReference { id, .. }), } = elt { messagerefs.push((id.name, *name)); } } } </ins> // Require that the message name starts with the crate name // `hir_typeck_foo_bar` (in `hir_typeck.ftl`) // `const_eval_baz` (in `const_eval.ftl`)


} } <ins> for (mref, name) in messagerefs.into_iter() { if !previous_defns.contains_key(mref) { Diagnostic::spanned( path_span, Level::Error, format!("referenced message `{mref}` does not exist (in message `{name}`)"), ) .help(&format!("you may have meant to use a variable reference (`{{${mref}}}`)")) .emit(); } } </ins> if let Err(errs) = bundle.add_resource(resource) { for e in errs { match e {


use self::fluent_generated::{DEFAULT_LOCALE_RESOURCES, test_crate_foo, with_hyphens}; } <ins> mod missing_message_ref { use super::fluent_messages; fluent_messages! { missing => "./missing-message-ref.ftl" //~^ ERROR referenced message `message` does not exist } } </ins>


| = help: replace any '-'s with '_'s <del> error: aborting due to 10 previous errors </del> <ins> error: referenced message `message` does not exist (in message `missing_message_ref`) --> $DIR/test.rs:104:20 | LL |         missing => "./missing-message-ref.ftl" |                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: you may have meant to use a variable reference (`{$message}`) error: aborting due to 11 previous errors </ins> For more information about this error, try `rustc --explain E0428`.


"{place_name} {partially_str}moved due to this method call{loop_message}", ), ); let infcx = tcx.infer_ctxt().build(); <ins> // Erase and shadow everything that could be passed to the new infcx. </ins> let ty = tcx.erase_regions(moved_place.ty(self.body, tcx).ty); <ins> let method_substs = tcx.erase_regions(method_substs); </ins> if let ty::Adt(def, substs) = ty.kind() && Some(def.did()) == tcx.lang_items().pin_type() && let ty::Ref(_, _, hir::Mutability::Mut) = substs.type_at(0).kind()


<ins> // run-rustfix use std::pin::Pin; fn foo(_: &mut ()) {} fn main() { let mut uwu = (); let mut r = Pin::new(&mut uwu); foo(r.as_mut().get_mut()); foo(r.get_mut()); //~ ERROR use of moved value } </ins>


<ins> // run-rustfix use std::pin::Pin; fn foo(_: &mut ()) {} fn main() { let mut uwu = (); let mut r = Pin::new(&mut uwu); foo(r.get_mut()); foo(r.get_mut()); //~ ERROR use of moved value } </ins>


<ins> error[E0382]: use of moved value: `r` --> $DIR/pin-mut-reborrow-infer-var-issue-107419.rs:10:9 | LL |     let mut r = Pin::new(&mut uwu); |         ----- move occurs because `r` has type `Pin<&mut ()>`, which does not implement the `Copy` trait LL |     foo(r.get_mut()); |           --------- `r` moved due to this method call LL |     foo(r.get_mut()); |         ^ value used here after move | note: `Pin::<&'a mut T>::get_mut` takes ownership of the receiver `self`, which moves `r` --> $SRC_DIR/core/src/pin.rs:LL:COL help: consider reborrowing the `Pin` instead of moving it | LL |     foo(r.as_mut().get_mut()); |           +++++++++ error: aborting due to previous error For more information about this error, try `rustc --explain E0382`. </ins>


<ins> // Verify that move before the call of the function with noalias, nocapture, readonly. // #107436 // compile-flags: -O // min-llvm-version: 17 #![crate_type = "lib"] #[repr(C)] pub struct ThreeSlices<'a>(&'a [u32], &'a [u32], &'a [u32]); #[no_mangle] pub fn sum_slices(val: ThreeSlices) -> u32 { // CHECK-NOT: memcpy let val = val; sum(&val) } #[no_mangle] #[inline(never)] pub fn sum(val: &ThreeSlices) -> u32 { val.0.iter().sum::<u32>() + val.1.iter().sum::<u32>() + val.2.iter().sum::<u32>() } </ins>


self.mark_as_used_if_union(*adt, fields); } } <ins> hir::ExprKind::Closure(cls) => { self.insert_def_id(cls.def_id.to_def_id()); } </ins> _ => (), }


<ins> // edition: 2021 #![deny(dead_code)] pub fn foo() { let closure = || { fn a() {}   //~ ERROR function `a` is never used }; closure() } pub async fn async_foo() { const A: usize = 1; //~ ERROR constant `A` is never used } fn main() {} </ins>


<ins> error: function `a` is never used --> $DIR/in-closure.rs:7:12 | LL |         fn a() {} |            ^ | note: the lint level is defined here --> $DIR/in-closure.rs:3:9 | LL | #![deny(dead_code)] |         ^^^^^^^^^ error: constant `A` is never used --> $DIR/in-closure.rs:13:11 | LL |     const A: usize = 1; |           ^ error: aborting due to 2 previous errors </ins>


// through and constrain Pi. let mut subcomponents = smallvec![]; let mut subvisited = SsoHashSet::new(); <del> compute_components_recursive(tcx, ty.into(), &mut subcomponents, &mut subvisited); </del> <ins> compute_alias_components_recursive(tcx, ty, &mut subcomponents, &mut subvisited); </ins> out.push(Component::EscapingAlias(subcomponents.into_iter().collect())); } }


/// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. <del> pub(super) fn compute_components_recursive<'tcx>( </del> <ins> pub(super) fn compute_alias_components_recursive<'tcx>( tcx: TyCtxt<'tcx>, alias_ty: Ty<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>, visited: &mut SsoHashSet<GenericArg<'tcx>>, ) { let ty::Alias(kind, alias_ty) = alias_ty.kind() else { bug!() }; let opt_variances = if *kind == ty::Opaque { tcx.variances_of(alias_ty.def_id) } else { &[] }; for (index, child) in alias_ty.substs.iter().enumerate() { if opt_variances.get(index) == Some(&ty::Bivariant) { continue; } if !visited.insert(child) { continue; } match child.unpack() { GenericArgKind::Type(ty) => { compute_components(tcx, ty, out, visited); } GenericArgKind::Lifetime(lt) => { // Ignore late-bound regions. if !lt.is_late_bound() { out.push(Component::Region(lt)); } } GenericArgKind::Const(_) => { compute_components_recursive(tcx, child, out, visited); } } } } /// Collect [Component]s for *all* the substs of `parent`. /// /// This should not be used to get the components of `parent` itself. /// Use [push_outlives_components] instead. fn compute_components_recursive<'tcx>( </ins> tcx: TyCtxt<'tcx>, parent: GenericArg<'tcx>, out: &mut SmallVec<[Component<'tcx>; 4]>,


// the problem is to add `T: 'r`, which isn't true. So, if there are no // inference variables, we use a verify constraint instead of adding // edges, which winds up enforcing the same condition. <ins> let is_opaque = alias_ty.kind(self.tcx) == ty::Opaque; </ins> if approx_env_bounds.is_empty() && trait_bounds.is_empty() <del> && (alias_ty.needs_infer() || alias_ty.kind(self.tcx) == ty::Opaque) </del> <ins> && (alias_ty.needs_infer() || is_opaque) </ins> { debug!("no declared bounds"); <del> self.substs_must_outlive(alias_ty.substs, origin, region); </del> <ins> let opt_variances = is_opaque.then(|| self.tcx.variances_of(alias_ty.def_id)); self.substs_must_outlive(alias_ty.substs, origin, region, opt_variances); </ins> return; }


self.delegate.push_verify(origin, GenericKind::Alias(alias_ty), region, verify_bound); } <ins> #[instrument(level = "debug", skip(self))] </ins> fn substs_must_outlive( &mut self, substs: SubstsRef<'tcx>, origin: infer::SubregionOrigin<'tcx>, region: ty::Region<'tcx>, <ins> opt_variances: Option<&[ty::Variance]>, </ins> ) { let constraint = origin.to_constraint_category(); <del> for k in substs { </del> <ins> for (index, k) in substs.iter().enumerate() { </ins> match k.unpack() { GenericArgKind::Lifetime(lt) => { <del> self.delegate.push_sub_region_constraint( origin.clone(), region, lt, constraint, ); </del> <ins> let variance = if let Some(variances) = opt_variances { variances[index] } else { ty::Invariant }; if variance == ty::Invariant { self.delegate.push_sub_region_constraint( origin.clone(), region, lt, constraint, ); } </ins> } GenericArgKind::Type(ty) => { self.type_must_outlive(origin.clone(), ty, region, constraint);


<del> use crate::infer::outlives::components::{compute_components_recursive, Component}; </del> <ins> use crate::infer::outlives::components::{compute_alias_components_recursive, Component}; </ins> use crate::infer::outlives::env::RegionBoundPairs; use crate::infer::region_constraints::VerifyIfEq; use crate::infer::VerifyBound;


// see the extensive comment in projection_must_outlive let recursive_bound = { let mut components = smallvec![]; <del> compute_components_recursive(self.tcx, alias_ty_as_ty.into(), &mut components, visited); </del> <ins> compute_alias_components_recursive( self.tcx, alias_ty_as_ty.into(), &mut components, visited, ); </ins> self.bound_from_components(&components, visited) };


<ins> // check-pass #![feature(type_alias_impl_trait)] struct MyTy<'a>(Vec<u8>, &'a ()); impl MyTy<'_> { fn one(&mut self) -> &mut impl Sized { &mut self.0 } fn two(&mut self) -> &mut (impl Sized + 'static) { self.one() } } type Opaque<'a> = impl Sized; fn define<'a>() -> Opaque<'a> {} fn test<'a>() { None::<&'static Opaque<'a>>; } fn one<'a, 'b: 'b>() -> &'a impl Sized { &() } fn two<'a, 'b>() { one::<'a, 'b>(); } fn main() {} </ins>


<ins> // check-pass #![feature(type_alias_impl_trait)] fn opaque<'a: 'a>() -> impl Sized {} fn assert_static<T: 'static>(_: T) {} fn test_closure() { let closure = |_| { assert_static(opaque()); }; closure(&opaque()); } type Opaque<'a> = impl Sized; fn define<'a>() -> Opaque<'a> {} fn test_tait(_: &Opaque<'_>) { None::<&'static Opaque<'_>>; } fn main() {} </ins>


pub fn check_target_feature_trait_unsafe(tcx: TyCtxt<'_>, id: LocalDefId, attr_span: Span) { if let DefKind::AssocFn = tcx.def_kind(id) { let parent_id = tcx.local_parent(id); <del> if let DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) { </del> <ins> if let DefKind::Trait | DefKind::Impl { of_trait: true } = tcx.def_kind(parent_id) { </ins> tcx.sess .struct_span_err( attr_span,


unsafe fn unsf_foo(&self) {} } <ins> trait Qux { #[target_feature(enable = "sse2")] //~^ ERROR cannot be applied to safe trait method fn foo(&self) {} } </ins> fn main() {}


error: `#[target_feature(..)]` cannot be applied to safe trait method <ins> --> $DIR/trait-impl.rs:22:5 | LL |     #[target_feature(enable = "sse2")] |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot be applied to safe trait method LL | LL |     fn foo(&self) {} |     ------------- not an `unsafe` function error: `#[target_feature(..)]` cannot be applied to safe trait method </ins> --> $DIR/trait-impl.rs:13:5 | LL |     #[target_feature(enable = "sse2")]


LL |     fn foo(&self) {} |     ------------- not an `unsafe` function <del> error: aborting due to previous error </del> <ins> error: aborting due to 2 previous errors </ins>


false, ); <del> // HACK: This avoids putting the newly built artifacts in the sysroot if we're using // `download-rustc`, to avoid "multiple candidates for `rmeta`" errors. Technically, that's // not quite right: people can set `download-rustc = true` to download even if there are // changes to the compiler, and in that case ideally we would put the *new* artifacts in the // sysroot, in case there are API changes that should be used by tools.  In practice, // though, that should be very uncommon, and people can still disable download-rustc. if !builder.download_rustc() { let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); } </del> <ins> let libdir = builder.sysroot_libdir(compiler, target); let hostdir = builder.sysroot_libdir(compiler, compiler.host); add_to_sysroot(&builder, &libdir, &hostdir, &librustc_stamp(builder, compiler, target)); </ins> } }


use std::borrow::Cow; use std::collections::HashSet; use std::env; <ins> use std::ffi::OsStr; </ins> use std::fs; use std::io::prelude::*; use std::io::BufReader;


// so its artifacts can't be reused. if builder.download_rustc() && compiler.stage != 0 { // Copy the existing artifacts instead of rebuilding them. <del> // NOTE: this path is only taken for tools linking to rustc-dev. builder.ensure(Sysroot { compiler }); </del> <ins> // NOTE: this path is only taken for tools linking to rustc-dev (including ui-fulldeps tests). let sysroot = builder.ensure(Sysroot { compiler }); let ci_rustc_dir = builder.out.join(&*builder.build.build.triple).join("ci-rustc"); for file in builder.config.rustc_dev_contents() { let src = ci_rustc_dir.join(&file); let dst = sysroot.join(file); if src.is_dir() { t!(fs::create_dir_all(dst)); } else { builder.copy(&src, &dst); } } </ins> return; }


} // Copy the compiler into the correct sysroot. <del> builder.cp_r(&builder.ci_rustc_dir(builder.build.build), &sysroot); </del> <ins> // NOTE(#108767): We intentionally don't copy `rustc-dev` artifacts until they're requested with `builder.ensure(Rustc)`. // This fixes an issue where we'd have multiple copies of libc in the sysroot with no way to tell which to load. // There are a few quirks of bootstrap that interact to make this reliable: // 1. The order `Step`s are run is hard-coded in `builder.rs` and not configurable. This //    avoids e.g. reordering `test::UiFulldeps` before `test::Ui` and causing the latter to //    fail because of duplicate metadata. // 2. The sysroot is deleted and recreated between each invocation, so running `x test //    ui-fulldeps && x test ui` can't cause failures. let mut filtered_files = Vec::new(); // Don't trim directories or files that aren't loaded per-target; they can't cause conflicts. let suffix = format!("lib/rustlib/{}/lib", compiler.host); for path in builder.config.rustc_dev_contents() { let path = Path::new(&path); if path.parent().map_or(false, |parent| parent.ends_with(&suffix)) { filtered_files.push(path.file_name().unwrap().to_owned()); } } let filtered_extensions = [OsStr::new("rmeta"), OsStr::new("rlib"), OsStr::new("so")]; let ci_rustc_dir = builder.ci_rustc_dir(builder.config.build); builder.cp_filtered(&ci_rustc_dir, &sysroot, &|path| { if path.extension().map_or(true, |ext| !filtered_extensions.contains(&ext)) { return true; } if !path.parent().map_or(true, |p| p.ends_with(&suffix)) { return true; } if !filtered_files.iter().all(|f| f != path.file_name().unwrap()) { builder.verbose_than(1, &format!("ignoring {}", path.display())); false } else { true } }); </ins> return INTERNER.intern_path(sysroot); }


env, ffi::{OsStr, OsString}, fs::{self, File}, <del> io::{BufRead, BufReader, ErrorKind}, </del> <ins> io::{BufRead, BufReader, BufWriter, ErrorKind, Write}, </ins> path::{Path, PathBuf}, process::{Command, Stdio}, };


let directory_prefix = Path::new(Path::new(uncompressed_filename).file_stem().unwrap()); // decompress the file <del> let data = t!(File::open(tarball)); </del> <ins> let data = t!(File::open(tarball), format!("file {} not found", tarball.display())); </ins> let decompressor = XzDecoder::new(BufReader::new(data)); let mut tar = tar::Archive::new(decompressor); <ins> // `compile::Sysroot` needs to know the contents of the `rustc-dev` tarball to avoid adding // it to the sysroot unless it was explicitly requested. But parsing the 100 MB tarball is slow. // Cache the entries when we extract it so we only have to read it once. let mut recorded_entries = if dst.ends_with("ci-rustc") && pattern == "rustc-dev" { Some(BufWriter::new(t!(File::create(dst.join(".rustc-dev-contents"))))) } else { None }; </ins> for member in t!(tar.entries()) { let mut member = t!(member); let original_path = t!(member.path()).into_owned();


if !t!(member.unpack_in(dst)) { panic!("path traversal attack ??"); } <ins> if let Some(record) = &mut recorded_entries { t!(writeln!(record, "{}", short_path.to_str().unwrap())); } </ins> let src_path = dst.join(original_path); if src_path.is_dir() && dst_path.exists() { continue; } t!(fs::rename(src_path, dst_path)); } <del> t!(fs::remove_dir_all(dst.join(directory_prefix))); </del> <ins> let dst_dir = dst.join(directory_prefix); if dst_dir.exists() { t!(fs::remove_dir_all(&dst_dir), format!("failed to remove {}", dst_dir.display())); } </ins> } /// Returns whether the SHA256 checksum of `path` matches `expected`.


Some(rustfmt_path) } <ins> pub(crate) fn rustc_dev_contents(&self) -> Vec<String> { assert!(self.download_rustc()); let ci_rustc_dir = self.out.join(&*self.build.triple).join("ci-rustc"); let rustc_dev_contents_file = t!(File::open(ci_rustc_dir.join(".rustc-dev-contents"))); t!(BufReader::new(rustc_dev_contents_file).lines().collect()) } </ins> pub(crate) fn download_ci_rustc(&self, commit: &str) { self.verbose(&format!("using downloaded stage2 artifacts from CI (commit {commit})"));


<ins> // Test that `download-rustc` doesn't put duplicate copies of libc in the sysroot. // check-pass #![crate_type = "lib"] #![no_std] #![feature(rustc_private)] extern crate libc; </ins>


.iter() .enumerate() .map(|(i, ty)| Argument { <del> name: name_from_pat(&body.params[i].pat), </del> <ins> name: Symbol::intern(&rustc_hir_pretty::param_to_string(&body.params[i])), </ins> type_: ty.clean(cx), }) .collect(),


Path { global: path.global, res: path.res, segments } } <del> crate fn qpath_to_string(p: &hir::QPath<'_>) -> String { let segments = match *p { hir::QPath::Resolved(_, ref path) => &path.segments, hir::QPath::TypeRelative(_, ref segment) => return segment.ident.to_string(), hir::QPath::LangItem(lang_item, ..) => return lang_item.name().to_string(), }; let mut s = String::new(); for (i, seg) in segments.iter().enumerate() { if i > 0 { s.push_str("::"); } if seg.ident.name != kw::PathRoot { s.push_str(&seg.ident.as_str()); } } s } </del> crate fn build_deref_target_impls(cx: &DocContext<'_>, items: &[Item], ret: &mut Vec<Item>) { let tcx = cx.tcx;


} } <del> crate fn name_from_pat(p: &hir::Pat<'_>) -> Symbol { use rustc_hir::*; debug!("trying to get a name from pattern: {:?}", p); Symbol::intern(&match p.kind { PatKind::Wild => return kw::Underscore, PatKind::Binding(_, _, ident, _) => return ident.name, PatKind::TupleStruct(ref p, ..) | PatKind::Path(ref p) => qpath_to_string(p), PatKind::Struct(ref name, ref fields, etc) => format!( "{} {{ {}{} }}", qpath_to_string(name), fields .iter() .map(|fp| format!("{}: {}", fp.ident, name_from_pat(&fp.pat))) .collect::<Vec<String>>() .join(", "), if etc { ", .." } else { "" } ), PatKind::Or(ref pats) => pats .iter() .map(|p| name_from_pat(&**p).to_string()) .collect::<Vec<String>>() .join(" | "), PatKind::Tuple(ref elts, _) => format!( "({})", elts.iter() .map(|p| name_from_pat(&**p).to_string()) .collect::<Vec<String>>() .join(", ") ), PatKind::Box(ref p) => return name_from_pat(&**p), PatKind::Ref(ref p, _) => return name_from_pat(&**p), PatKind::Lit(..) => { warn!( "tried to get argument name from PatKind::Lit, which is silly in function arguments" ); return Symbol::intern("()"); } PatKind::Range(..) => panic!( "tried to get argument name from PatKind::Range,  which is not allowed in function arguments" ), PatKind::Slice(ref begin, ref mid, ref end) => { let begin = begin.iter().map(|p| name_from_pat(&**p).to_string()); let mid = mid.as_ref().map(|p| format!("..{}", name_from_pat(&**p))).into_iter(); let end = end.iter().map(|p| name_from_pat(&**p).to_string()); format!("[{}]", begin.chain(mid).chain(end).collect::<Vec<_>>().join(", ")) } }) } </del> crate fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String { match n.val { ty::ConstKind::Unevaluated(def, _, promoted) => {


<ins> // check-pass fn func(0u8..=255: u8) {} </ins>


<ins> #![crate_name = "foo"] // @has foo/fn.f.html // @has - '//*[@class="rust fn"]' 'pub fn f(0u8 ...255: u8)' pub fn f(0u8...255: u8) {} </ins>


<ins> error[E0637]: `&` without an explicit lifetime name cannot be used here --> $DIR/issue-109071.rs:8:17 | LL |     type Item = &[T]; |                 ^ explicit lifetime name needed here error[E0107]: missing generics for struct `Windows` --> $DIR/issue-109071.rs:7:9 | LL | impl<T> Windows { |         ^^^^^^^ expected 1 generic argument | note: struct defined here, with 1 generic parameter: `T` --> $DIR/issue-109071.rs:5:8 | LL | struct Windows<T> {} |        ^^^^^^^ - help: add missing generic argument | LL | impl<T> Windows<T> { |                +++ error[E0658]: inherent associated types are unstable --> $DIR/issue-109071.rs:8:5 | LL |     type Item = &[T]; |     ^^^^^^^^^^^^^^^^^ | = note: see issue #8995 <https://github.com/rust-lang/rust/issues/8995> for more information = help: add `#![feature(inherent_associated_types)]` to the crate attributes to enable error: aborting due to 3 previous errors Some errors have detailed explanations: E0107, E0637, E0658. For more information about an error, try `rustc --explain E0107`. </ins>


<ins> // revisions: with_gate no_gate #![cfg_attr(with_gate, feature(inherent_associated_types))] #![cfg_attr(with_gate, allow(incomplete_features))] struct Windows<T> {} impl<T> Windows { //~ ERROR: missing generics for struct `Windows` type Item = &[T]; //~ ERROR: `&` without an explicit lifetime name cannot be used here //[no_gate]~^ ERROR: inherent associated types are unstable fn next() -> Option<Self::Item> {} } impl<T> Windows<T> { fn T() -> Option<Self::Item> {} } fn main() {} </ins>