diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index 7e62bb9793d50..2f366001d4b3c 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -18,7 +18,7 @@ use rustc_middle::mir::{ PlaceRef, ProjectionElem, Rvalue, Statement, StatementKind, Terminator, TerminatorKind, VarBindingForm, }; -use rustc_middle::ty::{self, suggest_constraining_type_params, PredicateKind, Ty}; +use rustc_middle::ty::{self, suggest_constraining_type_params, PredicateKind, Ty, TyCtxt}; use rustc_middle::util::CallKind; use rustc_mir_dataflow::move_paths::{InitKind, MoveOutIndex, MovePathIndex}; use rustc_span::def_id::LocalDefId; @@ -398,7 +398,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { } let typeck = self.infcx.tcx.typeck(self.mir_def_id()); let hir_id = hir.parent_id(expr.hir_id); - if let Some(parent) = hir.find(hir_id) { + if let Some(parent) = self.infcx.tcx.opt_hir_node(hir_id) { let (def_id, args, offset) = if let hir::Node::Expr(parent_expr) = parent && let hir::ExprKind::MethodCall(_, _, args, _) = parent_expr.kind && let Some(def_id) = typeck.type_dependent_def_id(parent_expr.hir_id) @@ -413,7 +413,10 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { (None, &[][..], 0) }; if let Some(def_id) = def_id - && let Some(node) = hir.find(self.infcx.tcx.local_def_id_to_hir_id(def_id)) + && let Some(node) = self + .infcx + .tcx + .opt_hir_node(self.infcx.tcx.local_def_id_to_hir_id(def_id)) && let Some(fn_sig) = node.fn_sig() && let Some(ident) = node.ident() && let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id) @@ -1317,7 +1320,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let tcx = self.infcx.tcx; let hir = tcx.hir(); - let Some(body_id) = hir.get(self.mir_hir_id()).body_id() else { return }; + let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return }; let typeck_results = tcx.typeck(self.mir_def_id()); struct ExprFinder<'hir> { @@ -1509,7 +1512,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let local_ty = self.body.local_decls[local].ty; // Get the body the error happens in - let Some(body_id) = hir.get(self.mir_hir_id()).body_id() else { return }; + let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return }; let body_expr = hir.body(body_id).value; @@ -1558,7 +1561,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { // Check that the parent of the closure is a method call, // with receiver matching with local's type (modulo refs) let parent = hir.parent_id(closure_expr.hir_id); - if let hir::Node::Expr(parent) = hir.get(parent) { + if let hir::Node::Expr(parent) = tcx.hir_node(parent) { if let hir::ExprKind::MethodCall(_, recv, ..) = parent.kind { let recv_ty = typeck_results.expr_ty(recv); @@ -1635,15 +1638,14 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { issued_spans: &UseSpans<'tcx>, ) { let UseSpans::ClosureUse { capture_kind_span, .. } = issued_spans else { return }; - let hir = self.infcx.tcx.hir(); - struct ExpressionFinder<'hir> { + struct ExpressionFinder<'tcx> { capture_span: Span, closure_change_spans: Vec, closure_arg_span: Option, in_closure: bool, suggest_arg: String, - hir: rustc_middle::hir::map::Map<'hir>, + tcx: TyCtxt<'tcx>, closure_local_id: Option, closure_call_changes: Vec<(Span, String)>, } @@ -1657,7 +1659,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { fn_decl: hir::FnDecl { inputs, .. }, .. }) = e.kind - && let Some(hir::Node::Expr(body)) = self.hir.find(body.hir_id) + && let Some(hir::Node::Expr(body)) = self.tcx.opt_hir_node(body.hir_id) { self.suggest_arg = "this: &Self".to_string(); if inputs.len() > 0 { @@ -1722,8 +1724,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { if let Some(hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(_fn_sig, body_id), .. - })) = hir.find(self.mir_hir_id()) - && let Some(hir::Node::Expr(expr)) = hir.find(body_id.hir_id) + })) = self.infcx.tcx.opt_hir_node(self.mir_hir_id()) + && let Some(hir::Node::Expr(expr)) = self.infcx.tcx.opt_hir_node(body_id.hir_id) { let mut finder = ExpressionFinder { capture_span: *capture_kind_span, @@ -1733,7 +1735,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { suggest_arg: String::new(), closure_local_id: None, closure_call_changes: vec![], - hir, + tcx: self.infcx.tcx, }; finder.visit_expr(expr); @@ -2294,7 +2296,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> { let proper_span = proper_span.source_callsite(); if let Some(scope) = self.body.source_scopes.get(source_info.scope) && let ClearCrossCrate::Set(scope_data) = &scope.local_data - && let Some(node) = self.infcx.tcx.hir().find(scope_data.lint_root) + && let Some(node) = self.infcx.tcx.opt_hir_node(scope_data.lint_root) && let Some(id) = node.body_id() && let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir().body(id).value.kind { diff --git a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs index bed3df4809ddd..f1e712d814a10 100644 --- a/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs +++ b/compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs @@ -87,7 +87,7 @@ impl<'tcx> BorrowExplanation<'tcx> { if let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind && let [hir::PathSegment { ident, args: None, .. }] = p.segments && let hir::def::Res::Local(hir_id) = p.res - && let Some(hir::Node::Pat(pat)) = tcx.hir().find(hir_id) + && let Some(hir::Node::Pat(pat)) = tcx.opt_hir_node(hir_id) { err.span_label(pat.span, format!("binding `{ident}` declared here")); } diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 8fe552708ed9c..c3c1f1293d2ab 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -396,7 +396,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let upvar_hir_id = captured_place.get_root_variable(); - if let Some(Node::Pat(pat)) = self.infcx.tcx.hir().find(upvar_hir_id) + if let Some(Node::Pat(pat)) = self.infcx.tcx.opt_hir_node(upvar_hir_id) && let hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, upvar_ident, _) = pat.kind { @@ -661,7 +661,6 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if self.body.local_kind(local) != LocalKind::Arg { return (false, None); } - let hir_map = self.infcx.tcx.hir(); let my_def = self.body.source.def_id(); let my_hir = self.infcx.tcx.local_def_id_to_hir_id(my_def.as_local().unwrap()); let Some(td) = @@ -671,7 +670,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }; ( true, - td.as_local().and_then(|tld| match hir_map.find_by_def_id(tld) { + td.as_local().and_then(|tld| match self.infcx.tcx.opt_hir_node_by_def_id(tld) { Some(Node::Item(hir::Item { kind: hir::ItemKind::Trait(_, _, _, _, items), .. @@ -682,25 +681,27 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if !matches!(k, hir::AssocItemKind::Fn { .. }) { continue; } - if hir_map.name(hi) != hir_map.name(my_hir) { + if self.infcx.tcx.hir().name(hi) != self.infcx.tcx.hir().name(my_hir) { continue; } f_in_trait_opt = Some(hi); break; } - f_in_trait_opt.and_then(|f_in_trait| match hir_map.find(f_in_trait) { - Some(Node::TraitItem(hir::TraitItem { - kind: - hir::TraitItemKind::Fn( - hir::FnSig { decl: hir::FnDecl { inputs, .. }, .. }, - _, - ), - .. - })) => { - let hir::Ty { span, .. } = inputs[local.index() - 1]; - Some(span) + f_in_trait_opt.and_then(|f_in_trait| { + match self.infcx.tcx.opt_hir_node(f_in_trait) { + Some(Node::TraitItem(hir::TraitItem { + kind: + hir::TraitItemKind::Fn( + hir::FnSig { decl: hir::FnDecl { inputs, .. }, .. }, + _, + ), + .. + })) => { + let hir::Ty { span, .. } = inputs[local.index() - 1]; + Some(span) + } + _ => None, } - _ => None, }) } _ => None, @@ -741,12 +742,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { } } - let hir_map = self.infcx.tcx.hir(); let def_id = self.body.source.def_id(); let hir_id = if let Some(local_def_id) = def_id.as_local() - && let Some(body_id) = hir_map.maybe_body_owned_by(local_def_id) + && let Some(body_id) = self.infcx.tcx.hir().maybe_body_owned_by(local_def_id) { - let body = hir_map.body(body_id); + let body = self.infcx.tcx.hir().body(body_id); let mut v = BindingFinder { span: pat_span, hir_id: None }; v.visit_body(body); v.hir_id @@ -762,7 +762,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { && let Some(hir::Node::Local(hir::Local { pat: hir::Pat { kind: hir::PatKind::Ref(_, _), .. }, .. - })) = hir_map.find(hir_id) + })) = self.infcx.tcx.opt_hir_node(hir_id) && let Ok(name) = self.infcx.tcx.sess.source_map().span_to_snippet(local_decl.source_info.span) { @@ -942,7 +942,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { let closure_id = self.mir_hir_id(); let closure_span = self.infcx.tcx.def_span(self.mir_def_id()); let fn_call_id = hir.parent_id(closure_id); - let node = hir.get(fn_call_id); + let node = self.infcx.tcx.hir_node(fn_call_id); let def_id = hir.enclosing_body_owner(fn_call_id); let mut look_at_return = true; // If we can detect the expression to be an `fn` call where the closure was an argument, @@ -1001,7 +1001,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { if look_at_return && hir.get_return_block(closure_id).is_some() { // ...otherwise we are probably in the tail expression of the function, point at the // return type. - match hir.get_by_def_id(hir.get_parent_item(fn_call_id).def_id) { + match self.infcx.tcx.hir_node_by_def_id(hir.get_parent_item(fn_call_id).def_id) { hir::Node::Item(hir::Item { ident, kind: hir::ItemKind::Fn(sig, ..), .. }) | hir::Node::TraitItem(hir::TraitItem { ident, @@ -1199,12 +1199,11 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { hir::intravisit::walk_stmt(self, s); } } - let hir_map = self.infcx.tcx.hir(); let def_id = self.body.source.def_id(); let hir_id = if let Some(local_def_id) = def_id.as_local() - && let Some(body_id) = hir_map.maybe_body_owned_by(local_def_id) + && let Some(body_id) = self.infcx.tcx.hir().maybe_body_owned_by(local_def_id) { - let body = hir_map.body(body_id); + let body = self.infcx.tcx.hir().body(body_id); let mut v = BindingFinder { span: err_label_span, hir_id: None }; v.visit_body(body); v.hir_id @@ -1213,7 +1212,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }; if let Some(hir_id) = hir_id - && let Some(hir::Node::Local(local)) = hir_map.find(hir_id) + && let Some(hir::Node::Local(local)) = self.infcx.tcx.opt_hir_node(hir_id) { let tables = self.infcx.tcx.typeck(def_id.as_local().unwrap()); if let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait() @@ -1496,7 +1495,7 @@ fn get_mut_span_in_struct_field<'tcx>( && let ty::Adt(def, _) = ty.kind() && let field = def.all_fields().nth(field.index())? // Use the HIR types to construct the diagnostic message. - && let node = tcx.hir().find_by_def_id(field.did.as_local()?)? + && let node = tcx.opt_hir_node_by_def_id(field.did.as_local()?)? // Now we're dealing with the actual struct that we're going to suggest a change to, // we can expect a field that is an immutable reference to a type. && let hir::Node::Field(field) = node diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index a17c3bc3a78c5..4c3cef2e76315 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -672,7 +672,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { let mir_hir_id = self.mir_hir_id(); - let (return_span, mir_description, hir_ty) = match hir.get(mir_hir_id) { + let (return_span, mir_description, hir_ty) = match tcx.hir_node(mir_hir_id) { hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl, body, fn_decl_span, .. }), .. @@ -689,7 +689,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir::CoroutineSource::Closure => " of async closure", hir::CoroutineSource::Fn => { let parent_item = - hir.get_by_def_id(hir.get_parent_item(mir_hir_id).def_id); + tcx.hir_node_by_def_id(hir.get_parent_item(mir_hir_id).def_id); let output = &parent_item .fn_decl() .expect("coroutine lowered from async fn should be in fn") @@ -706,7 +706,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir::CoroutineSource::Closure => " of gen closure", hir::CoroutineSource::Fn => { let parent_item = - hir.get_by_def_id(hir.get_parent_item(mir_hir_id).def_id); + tcx.hir_node_by_def_id(hir.get_parent_item(mir_hir_id).def_id); let output = &parent_item .fn_decl() .expect("coroutine lowered from gen fn should be in fn") @@ -721,7 +721,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { hir::CoroutineSource::Closure => " of async gen closure", hir::CoroutineSource::Fn => { let parent_item = - hir.get_by_def_id(hir.get_parent_item(mir_hir_id).def_id); + tcx.hir_node_by_def_id(hir.get_parent_item(mir_hir_id).def_id); let output = &parent_item .fn_decl() .expect("coroutine lowered from async gen fn should be in fn") @@ -841,7 +841,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { let type_name = self.infcx.extract_inference_diagnostics_data(yield_ty.into(), Some(highlight)).name; - let yield_span = match tcx.hir().get(self.mir_hir_id()) { + let yield_span = match tcx.hir_node(self.mir_hir_id()) { hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }), .. diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index 9e992637f465b..dbc29e607eff9 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -33,7 +33,7 @@ pub fn is_parent_const_impl_raw(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { /// return if it has a `const` modifier. If it is an intrinsic, report whether said intrinsic /// has a `rustc_const_{un,}stable` attribute. Otherwise, return `Constness::NotConst`. fn constness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::Constness { - let node = tcx.hir().get_by_def_id(def_id); + let node = tcx.hir_node_by_def_id(def_id); match node { hir::Node::Ctor(_) diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index 20f251d5c91ad..07500f74477b4 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -227,7 +227,7 @@ impl<'rt, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> ValidityVisitor<'rt, 'mir, ' // Sometimes the index is beyond the number of upvars (seen // for a coroutine). let var_hir_id = captured_place.get_root_variable(); - let node = self.ecx.tcx.hir().get(var_hir_id); + let node = self.ecx.tcx.hir_node(var_hir_id); if let hir::Node::Pat(pat) = node { if let hir::PatKind::Binding(_, _, ident, _) = pat.kind { name = Some(ident.name); diff --git a/compiler/rustc_const_eval/src/interpret/visitor.rs b/compiler/rustc_const_eval/src/interpret/visitor.rs index 5c5a6e8db57a2..de0590a4b14de 100644 --- a/compiler/rustc_const_eval/src/interpret/visitor.rs +++ b/compiler/rustc_const_eval/src/interpret/visitor.rs @@ -21,7 +21,7 @@ pub trait ValueVisitor<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>>: Sized { /// `read_discriminant` can be hooked for better error messages. #[inline(always)] fn read_discriminant(&mut self, v: &Self::V) -> InterpResult<'tcx, VariantIdx> { - Ok(self.ecx().read_discriminant(&v.to_op(self.ecx())?)?) + self.ecx().read_discriminant(&v.to_op(self.ecx())?) } /// This function provides the chance to reorder the order in which fields are visited for diff --git a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs index 5bf9911269cbe..2de6362b9fe01 100644 --- a/compiler/rustc_const_eval/src/transform/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/transform/check_consts/ops.rs @@ -119,8 +119,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { match self_ty.kind() { Param(param_ty) => { debug!(?param_ty); - let caller_hir_id = tcx.local_def_id_to_hir_id(caller); - if let Some(generics) = tcx.hir().get(caller_hir_id).generics() { + if let Some(generics) = tcx.hir_node_by_def_id(caller).generics() { let constraint = with_no_trimmed_paths!(format!( "~const {}", trait_ref.print_only_trait_path() diff --git a/compiler/rustc_data_structures/src/tagged_ptr/impl_tag.rs b/compiler/rustc_data_structures/src/tagged_ptr/impl_tag.rs index cb7f7d318dc41..cafa91c8b8b32 100644 --- a/compiler/rustc_data_structures/src/tagged_ptr/impl_tag.rs +++ b/compiler/rustc_data_structures/src/tagged_ptr/impl_tag.rs @@ -81,6 +81,7 @@ /// E::A, /// } /// ``` +#[cfg(bootstrap)] #[macro_export] macro_rules! impl_tag { ( @@ -140,5 +141,148 @@ macro_rules! impl_tag { }; } +/// Implements [`Tag`] for a given type. +/// +/// You can use `impl_tag` on structs and enums. +/// You need to specify the type and all its possible values, +/// which can only be paths with optional fields. +/// +/// [`Tag`]: crate::tagged_ptr::Tag +/// +/// # Examples +/// +/// Basic usage: +/// +/// ``` +/// #![feature(macro_metavar_expr)] +/// use rustc_data_structures::{impl_tag, tagged_ptr::Tag}; +/// +/// #[derive(Copy, Clone, PartialEq, Debug)] +/// enum SomeTag { +/// A, +/// B, +/// X { v: bool }, +/// Y(bool, bool), +/// } +/// +/// impl_tag! { +/// // The type for which the `Tag` will be implemented +/// impl Tag for SomeTag; +/// // You need to specify all possible tag values: +/// SomeTag::A, // 0 +/// SomeTag::B, // 1 +/// // For variants with fields, you need to specify the fields: +/// SomeTag::X { v: true }, // 2 +/// SomeTag::X { v: false }, // 3 +/// // For tuple variants use named syntax: +/// SomeTag::Y { 0: true, 1: true }, // 4 +/// SomeTag::Y { 0: false, 1: true }, // 5 +/// SomeTag::Y { 0: true, 1: false }, // 6 +/// SomeTag::Y { 0: false, 1: false }, // 7 +/// } +/// +/// // Tag values are assigned in order: +/// assert_eq!(SomeTag::A.into_usize(), 0); +/// assert_eq!(SomeTag::X { v: false }.into_usize(), 3); +/// assert_eq!(SomeTag::Y(false, true).into_usize(), 5); +/// +/// assert_eq!(unsafe { SomeTag::from_usize(1) }, SomeTag::B); +/// assert_eq!(unsafe { SomeTag::from_usize(2) }, SomeTag::X { v: true }); +/// assert_eq!(unsafe { SomeTag::from_usize(7) }, SomeTag::Y(false, false)); +/// ``` +/// +/// Structs are supported: +/// +/// ``` +/// #![feature(macro_metavar_expr)] +/// # use rustc_data_structures::impl_tag; +/// #[derive(Copy, Clone)] +/// struct Flags { a: bool, b: bool } +/// +/// impl_tag! { +/// impl Tag for Flags; +/// Flags { a: true, b: true }, +/// Flags { a: false, b: true }, +/// Flags { a: true, b: false }, +/// Flags { a: false, b: false }, +/// } +/// ``` +/// +/// Not specifying all values results in a compile error: +/// +/// ```compile_fail,E0004 +/// #![feature(macro_metavar_expr)] +/// # use rustc_data_structures::impl_tag; +/// #[derive(Copy, Clone)] +/// enum E { +/// A, +/// B, +/// } +/// +/// impl_tag! { +/// impl Tag for E; +/// E::A, +/// } +/// ``` +#[cfg(not(bootstrap))] +#[macro_export] +macro_rules! impl_tag { + ( + impl Tag for $Self:ty; + $( + $($path:ident)::* $( { $( $fields:tt )* })?, + )* + ) => { + // Safety: + // `bits_for_tags` is called on the same `${index()}`-es as + // `into_usize` returns, thus `BITS` constant is correct. + unsafe impl $crate::tagged_ptr::Tag for $Self { + const BITS: u32 = $crate::tagged_ptr::bits_for_tags(&[ + $( + ${index()}, + $( ${ignore($path)} )* + )* + ]); + + #[inline] + fn into_usize(self) -> usize { + // This forbids use of repeating patterns (`Enum::V`&`Enum::V`, etc) + // (or at least it should, see ) + #[forbid(unreachable_patterns)] + match self { + // `match` is doing heavy lifting here, by requiring exhaustiveness + $( + $($path)::* $( { $( $fields )* } )? => ${index()}, + )* + } + } + + #[inline] + unsafe fn from_usize(tag: usize) -> Self { + match tag { + $( + ${index()} => $($path)::* $( { $( $fields )* } )?, + )* + + // Safety: + // `into_usize` only returns `${index()}` of the same + // repetition as we are filtering above, thus if this is + // reached, the safety contract of this function was + // already breached. + _ => unsafe { + debug_assert!( + false, + "invalid tag: {tag}\ + (this is a bug in the caller of `from_usize`)" + ); + std::hint::unreachable_unchecked() + }, + } + } + + } + }; +} + #[cfg(test)] mod tests; diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 8b7a4dbff9d58..e49db64536f16 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -587,10 +587,8 @@ fn show_md_content_with_pager(content: &str, color: ColorConfig) { let mut print_formatted = if pager_name == "less" { cmd.arg("-r"); true - } else if ["bat", "catbat", "delta"].iter().any(|v| *v == pager_name) { - true } else { - false + ["bat", "catbat", "delta"].iter().any(|v| *v == pager_name) }; if color == ColorConfig::Never { diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 47d4b802c0f45..89caf8aa23179 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -41,6 +41,7 @@ use std::path::PathBuf; use std::rc::Rc; use std::{iter, mem}; +#[cfg(bootstrap)] macro_rules! ast_fragments { ( $($Kind:ident($AstTy:ty) { @@ -165,6 +166,131 @@ macro_rules! ast_fragments { } } +#[cfg(not(bootstrap))] +macro_rules! ast_fragments { + ( + $($Kind:ident($AstTy:ty) { + $kind_name:expr; + $(one fn $mut_visit_ast:ident; fn $visit_ast:ident;)? + $(many fn $flat_map_ast_elt:ident; fn $visit_ast_elt:ident($($args:tt)*);)? + fn $make_ast:ident; + })* + ) => { + /// A fragment of AST that can be produced by a single macro expansion. + /// Can also serve as an input and intermediate result for macro expansion operations. + pub enum AstFragment { + OptExpr(Option>), + MethodReceiverExpr(P), + $($Kind($AstTy),)* + } + + /// "Discriminant" of an AST fragment. + #[derive(Copy, Clone, PartialEq, Eq)] + pub enum AstFragmentKind { + OptExpr, + MethodReceiverExpr, + $($Kind,)* + } + + impl AstFragmentKind { + pub fn name(self) -> &'static str { + match self { + AstFragmentKind::OptExpr => "expression", + AstFragmentKind::MethodReceiverExpr => "expression", + $(AstFragmentKind::$Kind => $kind_name,)* + } + } + + fn make_from<'a>(self, result: Box) -> Option { + match self { + AstFragmentKind::OptExpr => + result.make_expr().map(Some).map(AstFragment::OptExpr), + AstFragmentKind::MethodReceiverExpr => + result.make_expr().map(AstFragment::MethodReceiverExpr), + $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)* + } + } + } + + impl AstFragment { + pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { + if placeholders.is_empty() { + return; + } + match self { + $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| { + ${ignore($flat_map_ast_elt)} + placeholder(AstFragmentKind::$Kind, *id, None).$make_ast() + })),)?)* + _ => panic!("unexpected AST fragment kind") + } + } + + pub fn make_opt_expr(self) -> Option> { + match self { + AstFragment::OptExpr(expr) => expr, + _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), + } + } + + pub fn make_method_receiver_expr(self) -> P { + match self { + AstFragment::MethodReceiverExpr(expr) => expr, + _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), + } + } + + $(pub fn $make_ast(self) -> $AstTy { + match self { + AstFragment::$Kind(ast) => ast, + _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), + } + })* + + fn make_ast(self) -> T::OutputTy { + T::fragment_to_output(self) + } + + pub fn mut_visit_with(&mut self, vis: &mut F) { + match self { + AstFragment::OptExpr(opt_expr) => { + visit_clobber(opt_expr, |opt_expr| { + if let Some(expr) = opt_expr { + vis.filter_map_expr(expr) + } else { + None + } + }); + } + AstFragment::MethodReceiverExpr(expr) => vis.visit_method_receiver_expr(expr), + $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)* + $($(AstFragment::$Kind(ast) => + ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)* + } + } + + pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { + match self { + AstFragment::OptExpr(Some(expr)) => visitor.visit_expr(expr), + AstFragment::OptExpr(None) => {} + AstFragment::MethodReceiverExpr(expr) => visitor.visit_method_receiver_expr(expr), + $($(AstFragment::$Kind(ast) => visitor.$visit_ast(ast),)?)* + $($(AstFragment::$Kind(ast) => for ast_elt in &ast[..] { + visitor.$visit_ast_elt(ast_elt, $($args)*); + })?)* + } + } + } + + impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> { + $(fn $make_ast(self: Box>) + -> Option<$AstTy> { + Some(self.make(AstFragmentKind::$Kind).$make_ast()) + })* + } + } +} + ast_fragments! { Expr(P) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; } Pat(P) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; } diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index c29edc3dc9f29..4b8c6feb93eb2 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -10,9 +10,8 @@ use rustc_span::Span; /// A meta-variable expression, for expansions based on properties of meta-variables. #[derive(Debug, Clone, PartialEq, Encodable, Decodable)] pub(crate) enum MetaVarExpr { - /// The number of repetitions of an identifier, optionally limited to a number - /// of outer-most repetition depths. If the depth limit is `None` then the depth is unlimited. - Count(Ident, Option), + /// The number of repetitions of an identifier. + Count(Ident, usize), /// Ignore a meta-variable for repetition without expansion. Ignore(Ident), @@ -43,7 +42,10 @@ impl MetaVarExpr { let mut iter = args.trees(); let rslt = match ident.as_str() { "count" => parse_count(&mut iter, sess, ident.span)?, - "ignore" => MetaVarExpr::Ignore(parse_ident(&mut iter, sess, ident.span)?), + "ignore" => { + eat_dollar(&mut iter, sess, ident.span)?; + MetaVarExpr::Ignore(parse_ident(&mut iter, sess, ident.span)?) + } "index" => MetaVarExpr::Index(parse_depth(&mut iter, sess, ident.span)?), "length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?), _ => { @@ -92,6 +94,7 @@ fn parse_count<'sess>( sess: &'sess ParseSess, span: Span, ) -> PResult<'sess, MetaVarExpr> { + eat_dollar(iter, sess, span)?; let ident = parse_ident(iter, sess, span)?; let depth = if try_eat_comma(iter) { if iter.look_ahead(0).is_none() { @@ -100,9 +103,9 @@ fn parse_count<'sess>( "`count` followed by a comma must have an associated index indicating its depth", )); } - Some(parse_depth(iter, sess, span)?) + parse_depth(iter, sess, span)? } else { - None + 0 }; Ok(MetaVarExpr::Count(ident, depth)) } @@ -166,3 +169,20 @@ fn try_eat_comma(iter: &mut RefTokenTreeCursor<'_>) -> bool { } false } + +/// Expects that the next item is a dollar sign. +fn eat_dollar<'sess>( + iter: &mut RefTokenTreeCursor<'_>, + sess: &'sess ParseSess, + span: Span, +) -> PResult<'sess, ()> { + if let Some(TokenTree::Token(token::Token { kind: token::Dollar, .. }, _)) = iter.look_ahead(0) + { + let _ = iter.next(); + return Ok(()); + } + Err(sess.span_diagnostic.struct_span_err( + span, + "meta-variables within meta-variable expressions must be referenced using a dollar sign", + )) +} diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index 18707cebcd55a..80fd82e030289 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -440,7 +440,7 @@ fn lockstep_iter_size( /// declared inside a single repetition and the index `1` implies two nested repetitions. fn count_repetitions<'a>( cx: &ExtCtxt<'a>, - depth_opt: Option, + depth_user: usize, mut matched: &NamedMatch, repeats: &[(usize, usize)], sp: &DelimSpan, @@ -449,37 +449,45 @@ fn count_repetitions<'a>( // (or at the top-level of `matched` if no depth is given). fn count<'a>( cx: &ExtCtxt<'a>, - declared_lhs_depth: usize, - depth_opt: Option, + depth_curr: usize, + depth_max: usize, matched: &NamedMatch, sp: &DelimSpan, ) -> PResult<'a, usize> { match matched { - MatchedTokenTree(_) | MatchedNonterminal(_) => { - if declared_lhs_depth == 0 { - return Err(cx.create_err(CountRepetitionMisplaced { span: sp.entire() })); - } - match depth_opt { - None => Ok(1), - Some(_) => Err(out_of_bounds_err(cx, declared_lhs_depth, sp.entire(), "count")), - } - } + MatchedTokenTree(_) | MatchedNonterminal(_) => Ok(1), MatchedSeq(named_matches) => { - let new_declared_lhs_depth = declared_lhs_depth + 1; - match depth_opt { - None => named_matches - .iter() - .map(|elem| count(cx, new_declared_lhs_depth, None, elem, sp)) - .sum(), - Some(0) => Ok(named_matches.len()), - Some(depth) => named_matches + if depth_curr == depth_max { + Ok(named_matches.len()) + } else { + named_matches .iter() - .map(|elem| count(cx, new_declared_lhs_depth, Some(depth - 1), elem, sp)) - .sum(), + .map(|elem| count(cx, depth_curr + 1, depth_max, elem, sp)) + .sum() } } } } + + /// Maximum depth + fn depth(counter: usize, matched: &NamedMatch) -> usize { + match matched { + MatchedTokenTree(_) | MatchedNonterminal(_) => counter, + MatchedSeq(named_matches) => { + let rslt = counter + 1; + if let Some(elem) = named_matches.first() { depth(rslt, elem) } else { rslt } + } + } + } + + let depth_max = depth(0, matched) + .checked_sub(1) + .and_then(|el| el.checked_sub(repeats.len())) + .unwrap_or_default(); + if depth_user > depth_max { + return Err(out_of_bounds_err(cx, depth_max + 1, sp.entire(), "count")); + } + // `repeats` records all of the nested levels at which we are currently // matching meta-variables. The meta-var-expr `count($x)` only counts // matches that occur in this "subtree" of the `NamedMatch` where we @@ -491,7 +499,12 @@ fn count_repetitions<'a>( matched = &ads[idx]; } } - count(cx, 0, depth_opt, matched, sp) + + if let MatchedTokenTree(_) | MatchedNonterminal(_) = matched { + return Err(cx.create_err(CountRepetitionMisplaced { span: sp.entire() })); + } + + count(cx, depth_user, depth_max, matched, sp) } /// Returns a `NamedMatch` item declared on the LHS given an arbitrary [Ident] @@ -523,7 +536,7 @@ fn out_of_bounds_err<'a>( ) } else { format!( - "depth parameter on meta-variable expression `{ty}` \ + "depth parameter of meta-variable expression `{ty}` \ must be less than {max}" ) }; @@ -545,9 +558,9 @@ fn transcribe_metavar_expr<'a>( span }; match *expr { - MetaVarExpr::Count(original_ident, depth_opt) => { + MetaVarExpr::Count(original_ident, depth) => { let matched = matched_from_ident(cx, original_ident, interp)?; - let count = count_repetitions(cx, depth_opt, matched, repeats, sp)?; + let count = count_repetitions(cx, depth, matched, repeats, sp)?; let tt = TokenTree::token_alone( TokenKind::lit(token::Integer, sym::integer(count), None), visited_span(), diff --git a/compiler/rustc_hir_analysis/src/astconv/lint.rs b/compiler/rustc_hir_analysis/src/astconv/lint.rs index 14e810d133654..43d4248ab74e2 100644 --- a/compiler/rustc_hir_analysis/src/astconv/lint.rs +++ b/compiler/rustc_hir_analysis/src/astconv/lint.rs @@ -24,7 +24,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { .. }), .. - }) = tcx.hir().get_by_def_id(parent_id) + }) = tcx.hir_node_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id { if !of_trait_ref.trait_def_id().is_some_and(|def_id| def_id.is_local()) { diff --git a/compiler/rustc_hir_analysis/src/astconv/mod.rs b/compiler/rustc_hir_analysis/src/astconv/mod.rs index 20d36a1b0690c..caae6fa4f065e 100644 --- a/compiler/rustc_hir_analysis/src/astconv/mod.rs +++ b/compiler/rustc_hir_analysis/src/astconv/mod.rs @@ -2715,7 +2715,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let hir = tcx.hir(); let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) = - hir.get(fn_hir_id) + tcx.hir_node(fn_hir_id) else { return None; }; diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 6e18abf632ecf..e6245e4d0b146 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -504,7 +504,7 @@ fn check_item_type(tcx: TyCtxt<'_>, id: hir::ItemId) { let origin = tcx.opaque_type_origin(id.owner_id.def_id); if let hir::OpaqueTyOrigin::FnReturn(fn_def_id) | hir::OpaqueTyOrigin::AsyncFn(fn_def_id) = origin - && let hir::Node::TraitItem(trait_item) = tcx.hir().get_by_def_id(fn_def_id) + && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id) && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn() { // Skip opaques from RPIT in traits with no default body. @@ -1173,7 +1173,7 @@ fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) ty::VariantDiscr::Explicit(discr_def_id) => { // In the case the discriminant is both a duplicate and overflowed, let the user know if let hir::Node::AnonConst(expr) = - tcx.hir().get_by_def_id(discr_def_id.expect_local()) + tcx.hir_node_by_def_id(discr_def_id.expect_local()) && let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind && let rustc_ast::LitKind::Int(lit_value, _int_kind) = &lit.node && *lit_value != dis.val diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 1412fd1a987cb..82419d782cd98 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -2181,7 +2181,7 @@ pub(super) fn check_type_bounds<'tcx>( let impl_ty_span = if impl_ty.is_impl_trait_in_trait() { tcx.def_span(impl_ty_def_id) } else { - match tcx.hir().get_by_def_id(impl_ty_def_id) { + match tcx.hir_node_by_def_id(impl_ty_def_id) { hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(_, Some(ty)), .. diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index 86c38480d57c4..f866543dd0d63 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -278,7 +278,7 @@ fn report_mismatched_rpitit_signature<'tcx>( } let (span, impl_return_span, pre, post) = - match tcx.hir().get_by_def_id(impl_m_def_id.expect_local()).fn_decl().unwrap().output { + match tcx.hir_node_by_def_id(impl_m_def_id.expect_local()).fn_decl().unwrap().output { hir::FnRetTy::DefaultReturn(span) => (tcx.def_span(impl_m_def_id), span, "-> ", " "), hir::FnRetTy::Return(ty) => (ty.span, ty.span, "", ""), }; diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index 947e50d31610c..8f194ae88ab96 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -43,7 +43,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { return None; } let hir_id = tcx.local_def_id_to_hir_id(def_id.expect_local()); - match tcx.hir().find(hir_id) { + match tcx.opt_hir_node(hir_id) { Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })) => { generics.params.is_empty().not().then_some(generics.span) } @@ -58,7 +58,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { return None; } let hir_id = tcx.local_def_id_to_hir_id(def_id.expect_local()); - match tcx.hir().find(hir_id) { + match tcx.opt_hir_node(hir_id) { Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, generics, _), .. })) => { Some(generics.where_clause_span) } @@ -80,7 +80,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { return None; } let hir_id = tcx.local_def_id_to_hir_id(def_id.expect_local()); - match tcx.hir().find(hir_id) { + match tcx.opt_hir_node(hir_id) { Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(fn_sig, _, _), .. })) => { Some(fn_sig.decl.output.span()) } @@ -199,7 +199,7 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { let start_t = tcx.type_of(start_def_id).instantiate_identity(); match start_t.kind() { ty::FnDef(..) => { - if let Some(Node::Item(it)) = tcx.hir().find(start_id) { + if let Some(Node::Item(it)) = tcx.opt_hir_node(start_id) { if let hir::ItemKind::Fn(sig, generics, _) = &it.kind { let mut error = false; if !generics.params.is_empty() { diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index d08a83051059f..df17879a9676e 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -130,7 +130,7 @@ fn get_owner_return_paths( ) -> Option<(LocalDefId, ReturnsVisitor<'_>)> { let hir_id = tcx.local_def_id_to_hir_id(def_id); let parent_id = tcx.hir().get_parent_item(hir_id).def_id; - tcx.hir().find_by_def_id(parent_id).and_then(|node| node.body_id()).map(|body_id| { + tcx.opt_hir_node_by_def_id(parent_id).and_then(|node| node.body_id()).map(|body_id| { let body = tcx.hir().body(body_id); let mut visitor = ReturnsVisitor::default(); visitor.visit_body(body); diff --git a/compiler/rustc_hir_analysis/src/check/wfcheck.rs b/compiler/rustc_hir_analysis/src/check/wfcheck.rs index 3e805ab00b9c7..1686479bd0e5a 100644 --- a/compiler/rustc_hir_analysis/src/check/wfcheck.rs +++ b/compiler/rustc_hir_analysis/src/check/wfcheck.rs @@ -793,7 +793,7 @@ fn could_be_self(trait_def_id: LocalDefId, ty: &hir::Ty<'_>) -> bool { /// When this is done, suggest using `Self` instead. fn check_object_unsafe_self_trait_by_name(tcx: TyCtxt<'_>, item: &hir::TraitItem<'_>) { let (trait_name, trait_def_id) = - match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(item.hir_id()).def_id) { + match tcx.hir_node_by_def_id(tcx.hir().get_parent_item(item.hir_id()).def_id) { hir::Node::Item(item) => match item.kind { hir::ItemKind::Trait(..) => (item.ident, item.owner_id), _ => return, @@ -1019,7 +1019,7 @@ fn check_type_defn<'tcx>( for field in &variant.fields { let field_id = field.did.expect_local(); let hir::FieldDef { ty: hir_ty, .. } = - tcx.hir().get_by_def_id(field_id).expect_field(); + tcx.hir_node_by_def_id(field_id).expect_field(); let ty = wfcx.normalize( hir_ty.span, None, @@ -1057,7 +1057,7 @@ fn check_type_defn<'tcx>( let last = idx == variant.fields.len() - 1; let field_id = field.did.expect_local(); let hir::FieldDef { ty: hir_ty, .. } = - tcx.hir().get_by_def_id(field_id).expect_field(); + tcx.hir_node_by_def_id(field_id).expect_field(); let ty = wfcx.normalize( hir_ty.span, None, @@ -1882,7 +1882,7 @@ impl<'tcx> WfCheckingCtxt<'_, 'tcx> { // Match the existing behavior. if pred.is_global() && !pred.has_type_flags(TypeFlags::HAS_BINDER_VARS) { let pred = self.normalize(span, None, pred); - let hir_node = tcx.hir().find_by_def_id(self.body_def_id); + let hir_node = tcx.opt_hir_node_by_def_id(self.body_def_id); // only use the span of the predicate clause (#90869) diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index ae35d6ebd75ad..fdd6424a19e2d 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -221,7 +221,7 @@ pub(crate) fn placeholder_type_error_diag<'tcx>( // Check if parent is const or static let parent_id = tcx.hir().parent_id(hir_ty.hir_id); - let parent_node = tcx.hir().get(parent_id); + let parent_node = tcx.hir_node(parent_id); is_const_or_static = matches!( parent_node, @@ -354,7 +354,7 @@ impl<'tcx> ItemCtxt<'tcx> { } pub fn node(&self) -> hir::Node<'tcx> { - self.tcx.hir().get(self.hir_id()) + self.tcx.hir_node(self.hir_id()) } } @@ -835,8 +835,7 @@ fn convert_variant( fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> { use rustc_hir::*; - let hir_id = tcx.local_def_id_to_hir_id(def_id); - let Node::Item(item) = tcx.hir().get(hir_id) else { + let Node::Item(item) = tcx.hir_node_by_def_id(def_id) else { bug!(); }; @@ -1105,7 +1104,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder( } fn coroutine_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option { - match tcx.hir().get_by_def_id(def_id) { + match tcx.hir_node_by_def_id(def_id) { Node::Expr(&rustc_hir::Expr { kind: rustc_hir::ExprKind::Closure(&rustc_hir::Closure { body, .. }), .. @@ -1561,7 +1560,7 @@ fn coroutine_kind(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> bool { - match tcx.hir().get_by_def_id(def_id) { + match tcx.hir_node_by_def_id(def_id) { Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(opaque), .. }) => { matches!(opaque.origin, hir::OpaqueTyOrigin::TyAlias { .. }) } diff --git a/compiler/rustc_hir_analysis/src/collect/generics_of.rs b/compiler/rustc_hir_analysis/src/collect/generics_of.rs index 114c5147e1193..c1c2bb62c66e0 100644 --- a/compiler/rustc_hir_analysis/src/collect/generics_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/generics_of.rs @@ -16,7 +16,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics { let hir_id = tcx.local_def_id_to_hir_id(def_id); - let node = tcx.hir().get(hir_id); + let node = tcx.hir_node(hir_id); let parent_def_id = match node { Node::ImplItem(_) | Node::TraitItem(_) diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 4d0fd2b691a9e..0053af2b7dfe0 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -34,17 +34,14 @@ fn associated_type_bounds<'tcx>( let trait_def_id = tcx.local_parent(assoc_item_def_id); let trait_predicates = tcx.trait_explicit_predicates_and_bounds(trait_def_id); - let bounds_from_parent = trait_predicates - .predicates - .iter() - .copied() - .filter(|(pred, _)| match pred.kind().skip_binder() { + let bounds_from_parent = trait_predicates.predicates.iter().copied().filter(|(pred, _)| { + match pred.kind().skip_binder() { ty::ClauseKind::Trait(tr) => tr.self_ty() == item_ty, ty::ClauseKind::Projection(proj) => proj.projection_ty.self_ty() == item_ty, ty::ClauseKind::TypeOutlives(outlives) => outlives.0 == item_ty, _ => false, - }) - .map(|(clause, span)| (clause, span)); + } + }); let all_bounds = tcx.arena.alloc_from_iter(bounds.clauses().chain(bounds_from_parent)); debug!( @@ -86,7 +83,7 @@ pub(super) fn explicit_item_bounds( // RPITIT's bounds are the same as opaque type bounds, but with // a projection self type. Some(ty::ImplTraitInTraitData::Trait { opaque_def_id, .. }) => { - let item = tcx.hir().get_by_def_id(opaque_def_id.expect_local()).expect_item(); + let item = tcx.hir_node_by_def_id(opaque_def_id.expect_local()).expect_item(); let opaque_ty = item.expect_opaque_ty(); return ty::EarlyBinder::bind(opaque_type_bounds( tcx, @@ -105,8 +102,7 @@ pub(super) fn explicit_item_bounds( None => {} } - let hir_id = tcx.local_def_id_to_hir_id(def_id); - let bounds = match tcx.hir().get(hir_id) { + let bounds = match tcx.hir_node_by_def_id(def_id) { hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Type(bounds, _), span, diff --git a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs index ca9443225e294..de85a5d8626fa 100644 --- a/compiler/rustc_hir_analysis/src/collect/predicates_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/predicates_of.rs @@ -135,7 +135,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen } let hir_id = tcx.local_def_id_to_hir_id(def_id); - let node = tcx.hir().get(hir_id); + let node = tcx.hir_node(hir_id); let mut is_trait = None; let mut is_default_impl_trait = None; @@ -337,7 +337,7 @@ fn gather_explicit_predicates_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Gen // and the duplicated parameter, to ensure that they do not get out of sync. if let Node::Item(&Item { kind: ItemKind::OpaqueTy(..), .. }) = node { let opaque_ty_id = tcx.hir().parent_id(hir_id); - let opaque_ty_node = tcx.hir().get(opaque_ty_id); + let opaque_ty_node = tcx.hir_node(opaque_ty_id); let Node::Ty(&Ty { kind: TyKind::OpaqueDef(_, lifetimes, _), .. }) = opaque_ty_node else { bug!("unexpected {opaque_ty_node:?}") }; @@ -413,7 +413,7 @@ fn const_evaluatable_predicates_of( } let hir_id = tcx.local_def_id_to_hir_id(def_id); - let node = tcx.hir().get(hir_id); + let node = tcx.hir_node(hir_id); let mut collector = ConstCollector { tcx, preds: FxIndexSet::default() }; if let hir::Node::Item(item) = node @@ -633,7 +633,7 @@ pub(super) fn implied_predicates_with_filter( let trait_hir_id = tcx.local_def_id_to_hir_id(trait_def_id); - let Node::Item(item) = tcx.hir().get(trait_hir_id) else { + let Node::Item(item) = tcx.hir_node(trait_hir_id) else { bug!("trait_node_id {} is not an item", trait_hir_id); }; @@ -713,7 +713,7 @@ pub(super) fn type_param_predicates( let mut extend = None; let item_hir_id = tcx.local_def_id_to_hir_id(item_def_id); - let ast_generics = match tcx.hir().get(item_hir_id) { + let ast_generics = match tcx.hir_node(item_hir_id) { Node::TraitItem(item) => item.generics, Node::ImplItem(item) => item.generics, diff --git a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs index e939b7abd9031..a972c51e3eea0 100644 --- a/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs +++ b/compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs @@ -748,7 +748,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { } if let hir::Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy { .. }, .. - }) = self.tcx.hir().get(parent_id) + }) = self.tcx.hir_node(parent_id) { let mut err = self.tcx.sess.struct_span_err( lifetime.ident.span, @@ -1004,7 +1004,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> { fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectLifetimeDefault { debug_assert_eq!(tcx.def_kind(param_def_id), DefKind::TyParam); - let hir::Node::GenericParam(param) = tcx.hir().get_by_def_id(param_def_id) else { + let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(param_def_id) else { bug!("expected GenericParam for object_lifetime_default"); }; match param.source { @@ -1305,7 +1305,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> { def = ResolvedArg::Error(guar); } else if let Some(body_id) = outermost_body { let fn_id = self.tcx.hir().body_owner(body_id); - match self.tcx.hir().get(fn_id) { + match self.tcx.hir_node(fn_id) { Node::Item(hir::Item { owner_id, kind: hir::ItemKind::Fn(..), .. }) | Node::TraitItem(hir::TraitItem { owner_id, @@ -2122,7 +2122,7 @@ pub fn deny_non_region_late_bound( let mut first = true; for (var, arg) in bound_vars { - let Node::GenericParam(param) = tcx.hir().get_by_def_id(*var) else { + let Node::GenericParam(param) = tcx.hir_node_by_def_id(*var) else { bug!(); }; diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index c4fc4dda069aa..4b2ace748df3b 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -20,10 +20,10 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { use rustc_middle::ty::Ty; let hir_id = tcx.local_def_id_to_hir_id(def_id); - let Node::AnonConst(_) = tcx.hir().get(hir_id) else { panic!() }; + let Node::AnonConst(_) = tcx.hir_node(hir_id) else { panic!() }; let parent_node_id = tcx.hir().parent_id(hir_id); - let parent_node = tcx.hir().get(parent_node_id); + let parent_node = tcx.hir_node(parent_node_id); let (generics, arg_idx) = match parent_node { // Easy case: arrays repeat expressions. @@ -61,7 +61,7 @@ fn anon_const_type_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Ty<'tcx> { } Node::TypeBinding(binding @ &TypeBinding { hir_id: binding_id, .. }) - if let Node::TraitRef(trait_ref) = tcx.hir().get(tcx.hir().parent_id(binding_id)) => + if let Node::TraitRef(trait_ref) = tcx.hir_node(tcx.hir().parent_id(binding_id)) => { let Some(trait_def_id) = trait_ref.trait_def_id() else { return Ty::new_error_with_message( @@ -354,7 +354,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder match item.kind { TraitItemKind::Fn(..) => { let args = ty::GenericArgs::identity_for_item(tcx, def_id); @@ -517,8 +517,7 @@ pub(super) fn type_of_opaque( if let Some(def_id) = def_id.as_local() { use rustc_hir::*; - let hir_id = tcx.local_def_id_to_hir_id(def_id); - Ok(ty::EarlyBinder::bind(match tcx.hir().get(hir_id) { + Ok(ty::EarlyBinder::bind(match tcx.hir_node_by_def_id(def_id) { Node::Item(item) => match item.kind { ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias { .. }, diff --git a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs index f11a953536dcc..bf0d9d4856a57 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of/opaque.rs @@ -50,8 +50,8 @@ pub(super) fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: Local if scope == hir::CRATE_HIR_ID { tcx.hir().walk_toplevel_module(&mut locator); } else { - trace!("scope={:#?}", tcx.hir().get(scope)); - match tcx.hir().get(scope) { + trace!("scope={:#?}", tcx.hir_node(scope)); + match tcx.hir_node(scope) { // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods // This allows our visitor to process the defining item itself, causing // it to pick up any 'sibling' defining uses. @@ -95,7 +95,7 @@ pub(super) fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: Local let reported = tcx.sess.emit_err(UnconstrainedOpaqueType { span: tcx.def_span(def_id), name: tcx.item_name(parent_def_id.to_def_id()), - what: match tcx.hir().get(scope) { + what: match tcx.hir_node(scope) { _ if scope == hir::CRATE_HIR_ID => "module", Node::Item(hir::Item { kind: hir::ItemKind::Mod(_), .. }) => "module", Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. }) => "impl", @@ -282,7 +282,7 @@ pub(super) fn find_opaque_ty_constraints_for_rpit<'tcx>( debug!(?scope); let mut locator = RpitConstraintChecker { def_id, tcx, found: mir_opaque_ty }; - match tcx.hir().get(scope) { + match tcx.hir_node(scope) { Node::Item(it) => intravisit::walk_item(&mut locator, it), Node::ImplItem(it) => intravisit::walk_impl_item(&mut locator, it), Node::TraitItem(it) => intravisit::walk_trait_item(&mut locator, it), diff --git a/compiler/rustc_hir_analysis/src/hir_wf_check.rs b/compiler/rustc_hir_analysis/src/hir_wf_check.rs index 4ed1377e7fc8a..78745fe47abb6 100644 --- a/compiler/rustc_hir_analysis/src/hir_wf_check.rs +++ b/compiler/rustc_hir_analysis/src/hir_wf_check.rs @@ -122,7 +122,7 @@ fn diagnostic_hir_wf_check<'tcx>( // We will walk 'into' this type to try to find // a more precise span for our predicate. let tys = match loc { - WellFormedLoc::Ty(_) => match hir.get(hir_id) { + WellFormedLoc::Ty(_) => match tcx.hir_node(hir_id) { hir::Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Type(ty) => vec![ty], hir::ImplItemKind::Const(ty, _) => vec![ty], diff --git a/compiler/rustc_hir_analysis/src/outlives/mod.rs b/compiler/rustc_hir_analysis/src/outlives/mod.rs index c065f6e7e881e..9541e51070265 100644 --- a/compiler/rustc_hir_analysis/src/outlives/mod.rs +++ b/compiler/rustc_hir_analysis/src/outlives/mod.rs @@ -41,7 +41,7 @@ fn inferred_outlives_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId) -> &[(ty::Clau } } - match tcx.hir().get(id) { + match tcx.hir_node(id) { Node::Item(item) => match item.kind { hir::ItemKind::Struct(..) | hir::ItemKind::Enum(..) | hir::ItemKind::Union(..) => { let crate_map = tcx.inferred_outlives_crate(()); diff --git a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs index 76bd370a641b4..fab841e36792d 100644 --- a/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs +++ b/compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs @@ -137,10 +137,9 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { // is from the 'of_trait' field of the enclosing impl let parent = self.tcx.hir().get_parent(self.path_segment.hir_id); - let parent_item = self - .tcx - .hir() - .get_by_def_id(self.tcx.hir().get_parent_item(self.path_segment.hir_id).def_id); + let parent_item = self.tcx.hir_node_by_def_id( + self.tcx.hir().get_parent_item(self.path_segment.hir_id).def_id, + ); // Get the HIR id of the trait ref let hir::Node::TraitRef(hir::TraitRef { hir_ref_id: trait_ref_id, .. }) = parent else { @@ -774,7 +773,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> { ); if let Some(parent_node) = self.tcx.hir().opt_parent_id(self.path_segment.hir_id) - && let Some(parent_node) = self.tcx.hir().find(parent_node) + && let Some(parent_node) = self.tcx.opt_hir_node(parent_node) && let hir::Node::Expr(expr) = parent_node { match &expr.kind { diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index e7cbbc713353f..181de37284053 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -238,8 +238,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } // Next, make sure that we have no type expectation. - let Some(ret) = hir - .find_by_def_id(self.body_id) + let Some(ret) = self + .tcx + .opt_hir_node_by_def_id(self.body_id) .and_then(|owner| owner.fn_decl()) .map(|decl| decl.output.span()) else { @@ -317,7 +318,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir_id: hir::HirId, sp: Span, ) -> Option<(Span, String)> { - let node = self.tcx.hir().get(hir_id); + let node = self.tcx.hir_node(hir_id); if let hir::Node::Block(block) = node { // check that the body's parent is an fn let parent = self.tcx.hir().get_parent(self.tcx.hir().parent_id(block.hir_id)); diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index 512946cc5046a..baca2be06e619 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -295,7 +295,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ) { let hir = self.tcx.hir(); let parent_hir_id = hir.parent_id(hir_id); - let parent_node = hir.get(parent_hir_id); + let parent_node = self.tcx.hir_node(parent_hir_id); if let ( hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, body, .. }), @@ -313,7 +313,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { fn_decl_span, .. }), .. - }) = hir.get(async_closure) + }) = self.tcx.hir_node(async_closure) { fn_decl_span } else { @@ -343,7 +343,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { callee_expr: &'tcx hir::Expr<'tcx>, ) -> bool { let hir_id = self.tcx.hir().parent_id(call_expr.hir_id); - let parent_node = self.tcx.hir().get(hir_id); + let parent_node = self.tcx.hir_node(hir_id); if let ( hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Array(_), .. }), hir::ExprKind::Tup(exp), diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index f0bb18df48c94..fa087d0a4b0e2 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -483,8 +483,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { body: &hir::Body<'_>, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx> { - let hir = self.tcx.hir(); - let expr_map_node = hir.get_by_def_id(expr_def_id); + let expr_map_node = self.tcx.hir_node_by_def_id(expr_def_id); let expected_args: Vec<_> = expected_sig .sig .skip_binder() diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 0d3bb0f7e0ca9..70b4ab3f46134 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -1694,7 +1694,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let ret_msg = "return a value for the case when the loop has zero elements to iterate on"; let ret_ty_msg = "otherwise consider changing the return type to account for that possibility"; - if let Some(node) = hir.find(item.into()) + if let Some(node) = tcx.opt_hir_node(item.into()) && let Some(body_id) = node.body_id() && let Some(sig) = node.fn_sig() && let hir::ExprKind::Block(block, _) = hir.body(body_id).value.kind @@ -1776,7 +1776,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { let mut err = fcx.err_ctxt().report_mismatched_types(cause, expected, found, ty_err); let parent_id = fcx.tcx.hir().parent_id(id); - let parent = fcx.tcx.hir().get(parent_id); + let parent = fcx.tcx.hir_node(parent_id); if let Some(expr) = expression && let hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(&hir::Closure { body, .. }), @@ -1835,7 +1835,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> { } let parent_id = fcx.tcx.hir().get_parent_item(id); - let parent_item = fcx.tcx.hir().get_by_def_id(parent_id.def_id); + let parent_item = fcx.tcx.hir_node_by_def_id(parent_id.def_id); if let (Some(expr), Some(_), Some((fn_id, fn_decl, _, _))) = (expression, blk_id, fcx.get_node_fn_decl(parent_item)) diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 8f63383488531..ead9badabd041 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -289,7 +289,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir::def::Res::Local(local_hir_id) = p.res else { return false; }; - let hir::Node::Pat(pat) = hir.get(local_hir_id) else { + let hir::Node::Pat(pat) = self.tcx.hir_node(local_hir_id) else { return false; }; let (init_ty_hir_id, init) = match hir.get_parent(pat.hir_id) { @@ -557,7 +557,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::Node::Stmt(hir::Stmt { kind: hir::StmtKind::Semi(&ref p), .. }) | hir::Node::Block(hir::Block { expr: Some(&ref p), .. }) | hir::Node::Expr(&ref p), - ) = self.tcx.hir().find(parent_id) + ) = self.tcx.opt_hir_node(parent_id) else { break; }; @@ -570,7 +570,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut direct = false; loop { // Climb the HIR tree to find the (desugared) `loop` this `break` corresponds to. - let parent = match self.tcx.hir().find(parent_id) { + let parent = match self.tcx.opt_hir_node(parent_id) { Some(hir::Node::Expr(&ref parent)) => { parent_id = self.tcx.hir().parent_id(parent.hir_id); parent @@ -672,7 +672,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { error: Option>, ) { let parent = self.tcx.hir().parent_id(expr.hir_id); - match (self.tcx.hir().find(parent), error) { + match (self.tcx.opt_hir_node(parent), error) { (Some(hir::Node::Local(hir::Local { ty: Some(ty), init: Some(init), .. })), _) if init.hir_id == expr.hir_id => { @@ -717,7 +717,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None, hir::Path { res: hir::def::Res::Local(hir_id), .. }, )) => { - if let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(*hir_id) { + if let Some(hir::Node::Pat(pat)) = self.tcx.opt_hir_node(*hir_id) { primary_span = pat.span; secondary_span = pat.span; match self.tcx.hir().find_parent(pat.hir_id) { @@ -790,7 +790,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; }; let Some(hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Assign(lhs, rhs, _), .. })) = - self.tcx.hir().find(parent) + self.tcx.opt_hir_node(parent) else { return; }; @@ -1014,8 +1014,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir::Path { res: hir::def::Res::Local(bind_hir_id), .. }, )) = expr.kind { - let bind = self.tcx.hir().find(*bind_hir_id); - let parent = self.tcx.hir().find(self.tcx.hir().parent_id(*bind_hir_id)); + let bind = self.tcx.opt_hir_node(*bind_hir_id); + let parent = self.tcx.opt_hir_node(self.tcx.hir().parent_id(*bind_hir_id)); if let Some(hir::Node::Pat(hir::Pat { kind: hir::PatKind::Binding(_, _hir_id, _, _), .. diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 7c157c0eae01d..725f327d835dc 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -883,7 +883,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { kind: hir::ImplItemKind::Fn(..), span: encl_fn_span, .. - })) = self.tcx.hir().find_by_def_id(encl_item_id.def_id) + })) = self.tcx.opt_hir_node_by_def_id(encl_item_id.def_id) { // We are inside a function body, so reporting "return statement // outside of function body" needs an explanation. @@ -997,7 +997,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { then: impl FnOnce(&hir::Expr<'_>), ) { let mut parent = self.tcx.hir().parent_id(original_expr_id); - while let Some(node) = self.tcx.hir().find(parent) { + while let Some(node) = self.tcx.opt_hir_node(parent) { match node { hir::Node::Expr(hir::Expr { kind: diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index df840aaa57884..572a3312506c7 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -994,7 +994,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or // `while` before reaching it, as block tail returns are not available in them. self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| { - let parent = self.tcx.hir().get(blk_id); + let parent = self.tcx.hir_node(blk_id); self.get_node_fn_decl(parent) .map(|(fn_id, fn_decl, _, is_main)| (fn_id, fn_decl, is_main)) }) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index 9b5459529ffb1..76360239c454d 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -94,7 +94,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let hir = self.tcx.hir(); - let (expr, qpath) = match hir.get(hir_id) { + let (expr, qpath) = match self.tcx.hir_node(hir_id) { hir::Node::Expr(expr) => { if self.closure_span_overlaps_error(error, expr.span) { return false; @@ -454,7 +454,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .find_ancestor_in_same_ctxt(error.obligation.cause.span) .unwrap_or(arg.span); - if let hir::Node::Expr(arg_expr) = self.tcx.hir().get(arg.hir_id) { + if let hir::Node::Expr(arg_expr) = self.tcx.hir_node(arg.hir_id) { // This is more specific than pointing at the entire argument. self.blame_specific_expr_if_possible(error, arg_expr) } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index bb9b849f03bc7..bb393e27a5b01 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -1734,7 +1734,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } fn parent_item_span(&self, id: hir::HirId) -> Option { - let node = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(id).def_id); + let node = self.tcx.hir_node_by_def_id(self.tcx.hir().get_parent_item(id).def_id); match node { Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. }) | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => { @@ -1750,7 +1750,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise. fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident)> { - let parent = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(blk_id).def_id); + let parent = self.tcx.hir_node_by_def_id(self.tcx.hir().get_parent_item(blk_id).def_id); self.get_node_fn_decl(parent).map(|(_, fn_decl, ident, _)| (fn_decl, ident)) } @@ -2084,7 +2084,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let node = self .tcx .opt_local_def_id_to_hir_id(self.tcx.hir().get_parent_item(call_expr.hir_id)) - .and_then(|hir_id| self.tcx.hir().find(hir_id)); + .and_then(|hir_id| self.tcx.opt_hir_node(hir_id)); match node { Some(hir::Node::Item(item)) => call_finder.visit_item(item), Some(hir::Node::TraitItem(item)) => call_finder.visit_trait_item(item), diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 2c9942caab22f..28f377083f68f 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -677,7 +677,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // can suggest Box::pin. let parent = self.tcx.hir().parent_id(expr.hir_id); let Some(Node::Expr(Expr { kind: ExprKind::Call(fn_name, _), .. })) = - self.tcx.hir().find(parent) + self.tcx.opt_hir_node(parent) else { return false; }; @@ -824,7 +824,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let hir::TyKind::OpaqueDef(item_id, ..) = hir_ty.kind && let hir::Node::Item(hir::Item { kind: hir::ItemKind::OpaqueTy(op_ty), .. - }) = self.tcx.hir().get(item_id.hir_id()) + }) = self.tcx.hir_node(item_id.hir_id()) && let [ hir::GenericBound::LangItemTrait(hir::LangItem::Future, _, _, generic_args), ] = op_ty.bounds @@ -902,7 +902,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ty::Param(expected_ty_as_param) = expected.kind() else { return }; - let fn_node = self.tcx.hir().find(fn_id); + let fn_node = self.tcx.opt_hir_node(fn_id); let Some(hir::Node::Item(hir::Item { kind: @@ -1047,7 +1047,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; let ty = self.normalize(expr.span, ty); if self.can_coerce(found, ty) { - if let Some(node) = self.tcx.hir().find(fn_id) + if let Some(node) = self.tcx.opt_hir_node(fn_id) && let Some(owner_node) = node.as_owner() && let Some(span) = expr.span.find_ancestor_inside(owner_node.span()) { @@ -1545,12 +1545,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } fn is_loop(&self, id: hir::HirId) -> bool { - let node = self.tcx.hir().get(id); + let node = self.tcx.hir_node(id); matches!(node, Node::Expr(Expr { kind: ExprKind::Loop(..), .. })) } fn is_local_statement(&self, id: hir::HirId) -> bool { - let node = self.tcx.hir().get(id); + let node = self.tcx.hir_node(id); matches!(node, Node::Stmt(Stmt { kind: StmtKind::Local(..), .. })) } @@ -1677,11 +1677,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { None, hir::Path { segments: [_], res: crate::Res::Local(binding), .. }, )) => { - let Some(hir::Node::Pat(hir::Pat { hir_id, .. })) = self.tcx.hir().find(*binding) + let Some(hir::Node::Pat(hir::Pat { hir_id, .. })) = self.tcx.opt_hir_node(*binding) else { return expr; }; - let Some(parent) = self.tcx.hir().find(self.tcx.hir().parent_id(*hir_id)) else { + let Some(parent) = self.tcx.opt_hir_node(self.tcx.hir().parent_id(*hir_id)) else { return expr; }; @@ -1697,7 +1697,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .. }) => { let Some(hir::Node::Local(hir::Local { init: Some(init), .. })) = - self.tcx.hir().find(self.tcx.hir().parent_id(*pat_hir_id)) + self.tcx.opt_hir_node(self.tcx.hir().parent_id(*pat_hir_id)) else { return expr; }; @@ -1730,8 +1730,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let hir::Path { segments: [_], res: crate::Res::Local(binding), .. } = call_expr_path && let Some(hir::Node::Pat(hir::Pat { hir_id, .. })) = - self.tcx.hir().find(*binding) - && let Some(closure) = self.tcx.hir().find(self.tcx.hir().parent_id(*hir_id)) + self.tcx.opt_hir_node(*binding) + && let Some(closure) = self.tcx.opt_hir_node(self.tcx.hir().parent_id(*hir_id)) && let hir::Node::Local(hir::Local { init: Some(init), .. }) = closure && let Expr { kind: hir::ExprKind::Closure(hir::Closure { body: body_id, .. }), @@ -1985,7 +1985,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(hir::Node::Block(&hir::Block { span: block_span, expr: Some(e), .. - })) = self.tcx.hir().find(parent) + })) = self.tcx.opt_hir_node(parent) { if e.hir_id == id { if let Some(span) = expr.span.find_ancestor_inside(block_span) { @@ -2211,7 +2211,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let local_parent = self.tcx.hir().parent_id(local_id); let Some(Node::Param(hir::Param { hir_id: param_hir_id, .. })) = - self.tcx.hir().find(local_parent) + self.tcx.opt_hir_node(local_parent) else { return None; }; @@ -2221,13 +2221,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { hir_id: expr_hir_id, kind: hir::ExprKind::Closure(hir::Closure { fn_decl: closure_fn_decl, .. }), .. - })) = self.tcx.hir().find(param_parent) + })) = self.tcx.opt_hir_node(param_parent) else { return None; }; let expr_parent = self.tcx.hir().parent_id(*expr_hir_id); - let hir = self.tcx.hir().find(expr_parent); + let hir = self.tcx.opt_hir_node(expr_parent); let closure_params_len = closure_fn_decl.inputs.len(); let ( Some(Node::Expr(hir::Expr { @@ -2667,7 +2667,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Some(Node::Expr(hir::Expr { kind: hir::ExprKind::If(_, _, Some(else_expr)), .. - })) = self.tcx.hir().find(parent_id) + })) = self.tcx.opt_hir_node(parent_id) { return else_expr.hir_id == expr.hir_id; } @@ -3057,7 +3057,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { return; }; let parent = self.tcx.hir().parent_id(expr.hir_id); - if let Some(hir::Node::ExprField(_)) = self.tcx.hir().find(parent) { + if let Some(hir::Node::ExprField(_)) = self.tcx.opt_hir_node(parent) { // Ignore `Foo { field: a..Default::default() }` return; } @@ -3136,7 +3136,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let hir::def::Res::Local(hir_id) = path.res else { return; }; - let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else { + let Some(hir::Node::Pat(pat)) = self.tcx.opt_hir_node(hir_id) else { return; }; let Some(hir::Node::Local(hir::Local { ty: None, init: Some(init), .. })) = diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 6ad7b3010147c..f1f893623f687 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -127,7 +127,7 @@ fn has_typeck_results(tcx: TyCtxt<'_>, def_id: DefId) -> bool { } if let Some(def_id) = def_id.as_local() { - primary_body_of(tcx.hir().get_by_def_id(def_id)).is_some() + primary_body_of(tcx.hir_node_by_def_id(def_id)).is_some() } else { false } @@ -166,7 +166,7 @@ fn typeck_with_fallback<'tcx>( } let id = tcx.local_def_id_to_hir_id(def_id); - let node = tcx.hir().get(id); + let node = tcx.hir_node(id); let span = tcx.hir().span(id); // Figure out what primary body this item has. @@ -201,7 +201,7 @@ fn typeck_with_fallback<'tcx>( span, })) } else if let Node::AnonConst(_) = node { - match tcx.hir().get(tcx.hir().parent_id(id)) { + match tcx.hir_node(tcx.hir().parent_id(id)) { Node::Ty(&hir::Ty { kind: hir::TyKind::Typeof(ref anon_const), .. }) if anon_const.hir_id == id => { diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index b38a6ebd501e3..b86013cbec376 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -230,7 +230,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = kind && let hir::def::Res::Local(hir_id) = path.res - && let Some(hir::Node::Pat(b)) = self.tcx.hir().find(hir_id) + && let Some(hir::Node::Pat(b)) = self.tcx.opt_hir_node(hir_id) && let Some(hir::Node::Param(p)) = self.tcx.hir().find_parent(b.hir_id) && let Some(node) = self.tcx.hir().find_parent(p.hir_id) && let Some(decl) = node.fn_decl() @@ -605,16 +605,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let (ty::Param(_), ty::PredicateKind::Clause(ty::ClauseKind::Trait(p))) = (self_ty.kind(), parent_pred.kind().skip_binder()) { - let hir = self.tcx.hir(); let node = match p.trait_ref.self_ty().kind() { ty::Param(_) => { // Account for `fn` items like in `issue-35677.rs` to // suggest restricting its type params. - Some(hir.get_by_def_id(self.body_id)) - } - ty::Adt(def, _) => { - def.did().as_local().map(|def_id| hir.get_by_def_id(def_id)) + Some(self.tcx.hir_node_by_def_id(self.body_id)) } + ty::Adt(def, _) => def + .did() + .as_local() + .map(|def_id| self.tcx.hir_node_by_def_id(def_id)), _ => None, }; if let Some(hir::Node::Item(hir::Item { kind, .. })) = node @@ -1952,7 +1952,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { visitor.visit_body(body); let parent = self.tcx.hir().parent_id(seg1.hir_id); - if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) + if let Some(Node::Expr(call_expr)) = self.tcx.opt_hir_node(parent) && let Some(expr) = visitor.result && let Some(self_ty) = self.node_ty_opt(expr.hir_id) { @@ -2869,11 +2869,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let id = item .def_id .as_local() - .map(|def_id| self.tcx.local_def_id_to_hir_id(def_id)); + .map(|def_id| self.tcx.hir_node_by_def_id(def_id)); if let Some(hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(fn_sig, method), .. - })) = id.map(|id| self.tcx.hir().get(id)) + })) = id { let self_first_arg = match method { hir::TraitFn::Required([ident, ..]) => { @@ -2963,7 +2963,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Get the `hir::Param` to verify whether it already has any bounds. // We do this to avoid suggesting code that ends up as `T: FooBar`, // instead we suggest `T: Foo + Bar` in that case. - match hir.get(id) { + match self.tcx.hir_node(id) { Node::GenericParam(param) => { enum Introducer { Plus, @@ -3183,7 +3183,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } let parent = self.tcx.hir().parent_id(expr.hir_id); - if let Some(Node::Expr(call_expr)) = self.tcx.hir().find(parent) + if let Some(Node::Expr(call_expr)) = self.tcx.opt_hir_node(parent) && let hir::ExprKind::MethodCall( hir::PathSegment { ident: method_name, .. }, self_expr, diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index b63bb1e00cb55..165fc630787e7 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -720,7 +720,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let PatKind::Binding(_, _, binding, ..) = inner.kind { let binding_parent_id = tcx.hir().parent_id(pat.hir_id); - let binding_parent = tcx.hir().get(binding_parent_id); + let binding_parent = tcx.hir_node(binding_parent_id); debug!(?inner, ?pat, ?binding_parent); let mutability = match mutbl { @@ -941,7 +941,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, body_id), .. - })) => match self.tcx.hir().get(body_id.hir_id) { + })) => match self.tcx.hir_node(body_id.hir_id) { hir::Node::Expr(expr) => { if hir::is_range_literal(expr) { let span = self.tcx.hir().span(body_id.hir_id); diff --git a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs index 04d8410233633..b9b3ed53dae8f 100644 --- a/compiler/rustc_hir_typeck/src/rvalue_scopes.rs +++ b/compiler/rustc_hir_typeck/src/rvalue_scopes.rs @@ -69,12 +69,13 @@ pub fn resolve_rvalue_scopes<'a, 'tcx>( def_id: DefId, ) -> RvalueScopes { let tcx = &fcx.tcx; - let hir_map = tcx.hir(); let mut rvalue_scopes = RvalueScopes::new(); debug!("start resolving rvalue scopes, def_id={def_id:?}"); debug!("rvalue_scope: rvalue_candidates={:?}", scope_tree.rvalue_candidates); for (&hir_id, candidate) in &scope_tree.rvalue_candidates { - let Some(Node::Expr(expr)) = hir_map.find(hir_id) else { bug!("hir node does not exist") }; + let Some(Node::Expr(expr)) = tcx.opt_hir_node(hir_id) else { + bug!("hir node does not exist") + }; record_rvalue_scope(&mut rvalue_scopes, expr, candidate); } rvalue_scopes diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index c0a5818b9e5f9..f5bed834eba07 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -315,11 +315,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let final_tupled_upvars_type = Ty::new_tup(self.tcx, &final_upvar_tys); self.demand_suptype(span, args.tupled_upvars_ty(), final_tupled_upvars_type); - let fake_reads = delegate - .fake_reads - .into_iter() - .map(|(place, cause, hir_id)| (place, cause, hir_id)) - .collect(); + let fake_reads = delegate.fake_reads; + self.typeck_results.borrow_mut().closure_fake_reads.insert(closure_def_id, fake_reads); if self.tcx.sess.opts.unstable_opts.profile_closures { @@ -853,7 +850,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Looks like a macro fragment. Try to find the real block. if let Some(hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Block(block, ..), .. - })) = self.tcx.hir().find(body_id.hir_id) { + })) = self.tcx.opt_hir_node(body_id.hir_id) { // If the body is a block (with `{..}`), we use the span of that block. // E.g. with a `|| $body` expanded from a `m!({ .. })`, we use `{ .. }`, and not `$body`. // Since we know it's a block, we know we can insert the `let _ = ..` without @@ -1673,7 +1670,7 @@ fn apply_capture_kind_on_capture_ty<'tcx>( fn drop_location_span(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> Span { let owner_id = tcx.hir().get_enclosing_scope(hir_id).unwrap(); - let owner_node = tcx.hir().get(owner_id); + let owner_node = tcx.hir_node(owner_id); let owner_span = match owner_node { hir::Node::Item(item) => match item.kind { hir::ItemKind::Fn(_, _, owner_id) => tcx.hir().span(owner_id.hir_id), diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 0f2194139dfcf..8a7b97139ea0f 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -232,7 +232,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { /// Return all DepNode labels that should be asserted for this item. /// index=0 is the "name" used for error messages fn auto_labels(&mut self, item_id: LocalDefId, attr: &Attribute) -> (&'static str, Labels) { - let node = self.tcx.hir().get_by_def_id(item_id); + let node = self.tcx.hir_node_by_def_id(item_id); let (name, labels) = match node { HirNode::Item(item) => { match item.kind { diff --git a/compiler/rustc_infer/src/errors/mod.rs b/compiler/rustc_infer/src/errors/mod.rs index 6a220243266d2..a0768fc711546 100644 --- a/compiler/rustc_infer/src/errors/mod.rs +++ b/compiler/rustc_infer/src/errors/mod.rs @@ -363,9 +363,7 @@ impl AddToDiagnostic for AddLifetimeParamsSuggestion<'_> { return false; }; - let hir_id = self.tcx.local_def_id_to_hir_id(anon_reg.def_id); - - let node = self.tcx.hir().get(hir_id); + let node = self.tcx.hir_node_by_def_id(anon_reg.def_id); let is_impl = matches!(&node, hir::Node::ImplItem(_)); let generics = match node { hir::Node::Item(&hir::Item { diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 745c3d195ada7..e8d8ab8dea254 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -891,7 +891,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { } // don't suggest wrapping either blocks in `if .. {} else {}` let is_empty_arm = |id| { - let hir::Node::Block(blk) = self.tcx.hir().get(id) else { + let hir::Node::Block(blk) = self.tcx.hir_node(id) else { return false; }; if blk.expr.is_some() || !blk.stmts.is_empty() { @@ -2007,7 +2007,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { diag.span_note(span, "this closure does not fulfill the lifetime requirements"); self.suggest_for_all_lifetime_closure( span, - self.tcx.hir().get_by_def_id(def_id), + self.tcx.hir_node_by_def_id(def_id), &exp_found, diag, ); @@ -2121,7 +2121,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let TypeError::FixedArraySize(sz) = terr else { return None; }; - let tykind = match hir.find_by_def_id(trace.cause.body_id) { + let tykind = match self.tcx.opt_hir_node_by_def_id(trace.cause.body_id) { Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) => { let body = hir.body(*body_id); struct LetVisitor<'v> { @@ -2997,7 +2997,7 @@ impl<'tcx> InferCtxt<'tcx> { /// Given a [`hir::HirId`] for a block, get the span of its last expression /// or statement, peeling off any inner blocks. pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span { - match self.tcx.hir().get(hir_id) { + match self.tcx.hir_node(hir_id) { hir::Node::Block(blk) => self.find_block_span(blk), // The parser was in a weird state if either of these happen, but // it's better not to panic. diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs index ab928232d7451..4f74365d06c47 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/find_anon_type.rs @@ -26,8 +26,7 @@ pub fn find_anon_type<'tcx>( br: &ty::BoundRegionKind, ) -> Option<(&'tcx hir::Ty<'tcx>, &'tcx hir::FnSig<'tcx>)> { let anon_reg = tcx.is_suitable_region(region)?; - let hir_id = tcx.local_def_id_to_hir_id(anon_reg.def_id); - let fn_sig = tcx.hir().get(hir_id).fn_sig()?; + let fn_sig = tcx.hir_node_by_def_id(anon_reg.def_id).fn_sig()?; fn_sig .decl diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs index 81154415c1e54..01b43f7197d05 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/static_impl_trait.rs @@ -460,7 +460,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { tcx.hir().trait_impls(trait_did).iter().find_map(|&impl_did| { if let Node::Item(Item { kind: ItemKind::Impl(hir::Impl { self_ty, .. }), .. - }) = tcx.hir().find_by_def_id(impl_did)? + }) = tcx.opt_hir_node_by_def_id(impl_did)? && trait_objects.iter().all(|did| { // FIXME: we should check `self_ty` against the receiver // type in the `UnifyReceiver` context, but for now, use diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs index 155c03560256a..bfff00b948e96 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/util.rs @@ -50,11 +50,10 @@ pub fn find_param_with_region<'tcx>( let hir = &tcx.hir(); let def_id = id.as_local()?; - let hir_id = tcx.local_def_id_to_hir_id(def_id); // FIXME: use def_kind // Don't perform this on closures - match hir.get(hir_id) { + match tcx.hir_node_by_def_id(def_id) { hir::Node::Expr(&hir::Expr { kind: hir::ExprKind::Closure { .. }, .. }) => { return None; } diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index b93fe02aaeab0..afb3c5c1e5656 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -655,7 +655,7 @@ fn foo(&self) -> Self::T { String::new() } // When `body_owner` is an `impl` or `trait` item, look in its associated types for // `expected` and point at it. let parent_id = tcx.hir().get_parent_item(hir_id); - let item = tcx.hir().find_by_def_id(parent_id.def_id); + let item = tcx.opt_hir_node_by_def_id(parent_id.def_id); debug!("expected_projection parent item {:?}", item); diff --git a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs index aa5fe6d3f56cc..b762778122ba4 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/suggest.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/suggest.rs @@ -42,7 +42,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { ] .into_iter() .find_map(|(id, ty)| { - let hir::Node::Block(blk) = self.tcx.hir().get(id?) else { return None }; + let hir::Node::Block(blk) = self.tcx.hir_node(id?) else { return None }; self.could_remove_semicolon(blk, ty) }); match remove_semicolon { @@ -62,7 +62,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { let mut ret = None; for (id, ty) in [(first_id, second_ty), (second_id, first_ty)] { if let Some(id) = id - && let hir::Node::Block(blk) = self.tcx.hir().get(id) + && let hir::Node::Block(blk) = self.tcx.hir_node(id) && let Some(diag) = self.consider_returning_binding_diag(blk, ty) { ret = Some(diag); diff --git a/compiler/rustc_infer/src/infer/opaque_types.rs b/compiler/rustc_infer/src/infer/opaque_types.rs index 82ab19550536c..a492c6bf9bb4f 100644 --- a/compiler/rustc_infer/src/infer/opaque_types.rs +++ b/compiler/rustc_infer/src/infer/opaque_types.rs @@ -683,8 +683,8 @@ fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hi let res = hir_id == scope; trace!( "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}", - tcx.hir().find(hir_id), - tcx.hir().get(opaque_hir_id), + tcx.opt_hir_node(hir_id), + tcx.hir_node(opaque_hir_id), res ); res diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 823ede1222c82..53d99c7f7f348 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -34,7 +34,7 @@ declare_lint_pass!(DefaultHashTypes => [DEFAULT_HASH_TYPES]); impl LateLintPass<'_> for DefaultHashTypes { fn check_path(&mut self, cx: &LateContext<'_>, path: &Path<'_>, hir_id: HirId) { let Res::Def(rustc_hir::def::DefKind::Struct, def_id) = path.res else { return }; - if matches!(cx.tcx.hir().get(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) { + if matches!(cx.tcx.hir_node(hir_id), Node::Item(Item { kind: ItemKind::Use(..), .. })) { // don't lint imports, only actual usages return; } diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 810d691d16afd..6dade43a18357 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -202,7 +202,7 @@ fn lint_overflowing_range_endpoint<'tcx>( ) -> bool { // Look past casts to support cases like `0..256 as u8` let (expr, lit_span) = if let Node::Expr(par_expr) = - cx.tcx.hir().get(cx.tcx.hir().parent_id(expr.hir_id)) + cx.tcx.hir_node(cx.tcx.hir().parent_id(expr.hir_id)) && let ExprKind::Cast(_, _) = par_expr.kind { (par_expr, expr.span) @@ -213,7 +213,7 @@ fn lint_overflowing_range_endpoint<'tcx>( // We only want to handle exclusive (`..`) ranges, // which are represented as `ExprKind::Struct`. let par_id = cx.tcx.hir().parent_id(expr.hir_id); - let Node::ExprField(field) = cx.tcx.hir().get(par_id) else { return false }; + let Node::ExprField(field) = cx.tcx.hir_node(par_id) else { return false }; let Node::Expr(struct_expr) = cx.tcx.hir().get_parent(field.hir_id) else { return false }; if !is_range_literal(struct_expr) { return false; @@ -498,7 +498,7 @@ fn lint_uint_literal<'tcx>( }; if lit_val < min || lit_val > max { let parent_id = cx.tcx.hir().parent_id(e.hir_id); - if let Node::Expr(par_e) = cx.tcx.hir().get(parent_id) { + if let Node::Expr(par_e) = cx.tcx.hir_node(parent_id) { match par_e.kind { hir::ExprKind::Cast(..) => { if let ty::Char = cx.typeck_results().expr_ty(par_e).kind() { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index 143e439bd5710..ad3fea65e822f 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1144,7 +1144,7 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> let origin = tcx.opaque_type_origin(def_id); if let hir::OpaqueTyOrigin::FnReturn(fn_def_id) | hir::OpaqueTyOrigin::AsyncFn(fn_def_id) = origin - && let hir::Node::TraitItem(trait_item) = tcx.hir().get_by_def_id(fn_def_id) + && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id) && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn() { false @@ -1161,7 +1161,7 @@ fn should_encode_type(tcx: TyCtxt<'_>, def_id: LocalDefId, def_kind: DefKind) -> } } DefKind::TyParam => { - let hir::Node::GenericParam(param) = tcx.hir().get_by_def_id(def_id) else { bug!() }; + let hir::Node::GenericParam(param) = tcx.hir_node_by_def_id(def_id) else { bug!() }; let hir::GenericParamKind::Type { default, .. } = param.kind else { bug!() }; default.is_some() } @@ -1372,7 +1372,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { // anonymous constants will not work on them and panic. It's not clear whether it // can cause any observable issues or not. let anon_const_without_hir = def_kind == DefKind::AnonConst - && tcx.hir().find(tcx.local_def_id_to_hir_id(local_id)).is_none(); + && tcx.opt_hir_node(tcx.local_def_id_to_hir_id(local_id)).is_none(); if should_encode_generics(def_kind) && !anon_const_without_hir { let g = tcx.generics_of(def_id); record!(self.tables.generics_of[def_id] <- g); diff --git a/compiler/rustc_middle/src/hir/map/mod.rs b/compiler/rustc_middle/src/hir/map/mod.rs index 4af886a971855..598c26de23f1c 100644 --- a/compiler/rustc_middle/src/hir/map/mod.rs +++ b/compiler/rustc_middle/src/hir/map/mod.rs @@ -57,6 +57,10 @@ fn is_body_owner(node: Node<'_>, hir_id: HirId) -> bool { } } +// FIXME: the structure was necessary in the past but now it +// only serves as "namespace" for HIR-related methods, and can be +// removed if all the methods are reasonably renamed and moved to tcx +// (https://github.com/rust-lang/rust/pull/118256#issuecomment-1826442834). #[derive(Copy, Clone)] pub struct Map<'hir> { pub(super) tcx: TyCtxt<'hir>, @@ -128,6 +132,40 @@ impl<'hir> Iterator for ParentOwnerIterator<'hir> { } } +impl<'tcx> TyCtxt<'tcx> { + /// Retrieves the `hir::Node` corresponding to `id`, returning `None` if cannot be found. + pub fn opt_hir_node(self, id: HirId) -> Option> { + if id.local_id == ItemLocalId::from_u32(0) { + let owner = self.hir_owner(id.owner)?; + Some(owner.node.into()) + } else { + let owner = self.hir_owner_nodes(id.owner).as_owner()?; + let node = owner.nodes[id.local_id].as_ref()?; + Some(node.node) + } + } + + /// Retrieves the `hir::Node` corresponding to `id`, returning `None` if cannot be found. + #[inline] + pub fn opt_hir_node_by_def_id(self, id: LocalDefId) -> Option> { + self.opt_hir_node(self.opt_local_def_id_to_hir_id(id)?) + } + + /// Retrieves the `hir::Node` corresponding to `id`, panicking if it cannot be found. + #[track_caller] + pub fn hir_node(self, id: HirId) -> Node<'tcx> { + self.opt_hir_node(id).unwrap_or_else(|| bug!("couldn't find HIR node for hir id {id:?}")) + } + + /// Retrieves the `hir::Node` corresponding to `id`, panicking if it cannot be found. + #[inline] + #[track_caller] + pub fn hir_node_by_def_id(self, id: LocalDefId) -> Node<'tcx> { + self.opt_hir_node_by_def_id(id) + .unwrap_or_else(|| bug!("couldn't find HIR node for def id {id:?}")) + } +} + impl<'hir> Map<'hir> { #[inline] pub fn krate(self) -> &'hir Crate<'hir> { @@ -191,46 +229,15 @@ impl<'hir> Map<'hir> { } pub fn get_parent(self, hir_id: HirId) -> Node<'hir> { - self.get(self.parent_id(hir_id)) + self.tcx.hir_node(self.parent_id(hir_id)) } pub fn find_parent(self, hir_id: HirId) -> Option> { - self.find(self.opt_parent_id(hir_id)?) - } - - /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. - pub fn find(self, id: HirId) -> Option> { - if id.local_id == ItemLocalId::from_u32(0) { - let owner = self.tcx.hir_owner(id.owner)?; - Some(owner.node.into()) - } else { - let owner = self.tcx.hir_owner_nodes(id.owner).as_owner()?; - let node = owner.nodes[id.local_id].as_ref()?; - Some(node.node) - } - } - - /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. - #[inline] - pub fn find_by_def_id(self, id: LocalDefId) -> Option> { - self.find(self.tcx.opt_local_def_id_to_hir_id(id)?) - } - - /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. - #[track_caller] - pub fn get(self, id: HirId) -> Node<'hir> { - self.find(id).unwrap_or_else(|| bug!("couldn't find hir id {} in the HIR map", id)) - } - - /// Retrieves the `Node` corresponding to `id`, panicking if it cannot be found. - #[inline] - #[track_caller] - pub fn get_by_def_id(self, id: LocalDefId) -> Node<'hir> { - self.find_by_def_id(id).unwrap_or_else(|| bug!("couldn't find {:?} in the HIR map", id)) + self.tcx.opt_hir_node(self.opt_parent_id(hir_id)?) } pub fn get_if_local(self, id: DefId) -> Option> { - id.as_local().and_then(|id| self.find(self.tcx.opt_local_def_id_to_hir_id(id)?)) + id.as_local().and_then(|id| self.tcx.opt_hir_node(self.tcx.opt_local_def_id_to_hir_id(id)?)) } pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> { @@ -264,7 +271,7 @@ impl<'hir> Map<'hir> { #[track_caller] pub fn fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> { - if let Some(node) = self.find(hir_id) { + if let Some(node) = self.tcx.opt_hir_node(hir_id) { node.fn_decl() } else { bug!("no node for hir_id `{}`", hir_id) @@ -273,7 +280,7 @@ impl<'hir> Map<'hir> { #[track_caller] pub fn fn_sig_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnSig<'hir>> { - if let Some(node) = self.find(hir_id) { + if let Some(node) = self.tcx.opt_hir_node(hir_id) { node.fn_sig() } else { bug!("no node for hir_id `{}`", hir_id) @@ -296,19 +303,22 @@ impl<'hir> Map<'hir> { /// item (possibly associated), a closure, or a `hir::AnonConst`. pub fn body_owner(self, BodyId { hir_id }: BodyId) -> HirId { let parent = self.parent_id(hir_id); - assert!(self.find(parent).is_some_and(|n| is_body_owner(n, hir_id)), "{hir_id:?}"); + assert!( + self.tcx.opt_hir_node(parent).is_some_and(|n| is_body_owner(n, hir_id)), + "{hir_id:?}" + ); parent } pub fn body_owner_def_id(self, BodyId { hir_id }: BodyId) -> LocalDefId { let parent = self.parent_id(hir_id); - associated_body(self.get(parent)).unwrap().0 + associated_body(self.tcx.hir_node(parent)).unwrap().0 } /// Given a `LocalDefId`, returns the `BodyId` associated with it, /// if the node is a body owner, otherwise returns `None`. pub fn maybe_body_owned_by(self, id: LocalDefId) -> Option { - let node = self.find_by_def_id(id)?; + let node = self.tcx.opt_hir_node_by_def_id(id)?; let (_, body_id) = associated_body(node)?; Some(body_id) } @@ -548,7 +558,7 @@ impl<'hir> Map<'hir> { /// until the crate root is reached. Prefer this over your own loop using `parent_id`. #[inline] pub fn parent_iter(self, current_id: HirId) -> impl Iterator)> { - self.parent_id_iter(current_id).filter_map(move |id| Some((id, self.find(id)?))) + self.parent_id_iter(current_id).filter_map(move |id| Some((id, self.tcx.opt_hir_node(id)?))) } /// Returns an iterator for the nodes in the ancestor tree of the `current_id` @@ -600,7 +610,7 @@ impl<'hir> Map<'hir> { pub fn get_return_block(self, id: HirId) -> Option { let mut iter = self.parent_iter(id).peekable(); let mut ignore_tail = false; - if let Some(Node::Expr(Expr { kind: ExprKind::Ret(_), .. })) = self.find(id) { + if let Some(Node::Expr(Expr { kind: ExprKind::Ret(_), .. })) = self.tcx.opt_hir_node(id) { // When dealing with `return` statements, we don't care about climbing only tail // expressions. ignore_tail = true; @@ -708,7 +718,7 @@ impl<'hir> Map<'hir> { let mut scope = id; loop { scope = self.get_enclosing_scope(scope).unwrap_or(CRATE_HIR_ID); - if scope == CRATE_HIR_ID || !matches!(self.get(scope), Node::Block(_)) { + if scope == CRATE_HIR_ID || !matches!(self.tcx.hir_node(scope), Node::Block(_)) { return scope; } } @@ -764,7 +774,7 @@ impl<'hir> Map<'hir> { } pub fn expect_variant(self, id: HirId) -> &'hir Variant<'hir> { - match self.find(id) { + match self.tcx.opt_hir_node(id) { Some(Node::Variant(variant)) => variant, _ => bug!("expected variant, found {}", self.node_to_string(id)), } @@ -783,7 +793,7 @@ impl<'hir> Map<'hir> { } pub fn expect_expr(self, id: HirId) -> &'hir Expr<'hir> { - match self.find(id) { + match self.tcx.opt_hir_node(id) { Some(Node::Expr(expr)) => expr, _ => bug!("expected expr, found {}", self.node_to_string(id)), } @@ -791,7 +801,7 @@ impl<'hir> Map<'hir> { #[inline] fn opt_ident(self, id: HirId) -> Option { - match self.find(id)? { + match self.tcx.opt_hir_node(id)? { Node::Pat(&Pat { kind: PatKind::Binding(_, _, ident, _), .. }) => Some(ident), // A `Ctor` doesn't have an identifier itself, but its parent // struct/variant does. Compare with `hir::Map::opt_span`. @@ -860,7 +870,7 @@ impl<'hir> Map<'hir> { } } - let span = match self.find(hir_id)? { + let span = match self.tcx.opt_hir_node(hir_id)? { // Function-like. Node::Item(Item { kind: ItemKind::Fn(sig, ..), span: outer_span, .. }) | Node::TraitItem(TraitItem { @@ -950,7 +960,7 @@ impl<'hir> Map<'hir> { /// Like `hir.span()`, but includes the body of items /// (instead of just the item header) pub fn span_with_body(self, hir_id: HirId) -> Span { - match self.get(hir_id) { + match self.tcx.hir_node(hir_id) { Node::Param(param) => param.span, Node::Item(item) => item.span, Node::ForeignItem(foreign_item) => foreign_item.span, @@ -1045,7 +1055,7 @@ impl<'hir> Map<'hir> { impl<'hir> intravisit::Map<'hir> for Map<'hir> { fn find(&self, hir_id: HirId) -> Option> { - (*self).find(hir_id) + self.tcx.opt_hir_node(hir_id) } fn body(&self, id: BodyId) -> &'hir Body<'hir> { @@ -1159,7 +1169,7 @@ fn hir_id_to_string(map: Map<'_>, id: HirId) -> String { let span_str = || map.tcx.sess.source_map().span_to_snippet(map.span(id)).unwrap_or_default(); let node_str = |prefix| format!("{id} ({prefix} `{}`)", span_str()); - match map.find(id) { + match map.tcx.opt_hir_node(id) { Some(Node::Item(item)) => { let item_str = match item.kind { ItemKind::ExternCrate(..) => "extern crate", diff --git a/compiler/rustc_middle/src/hir/mod.rs b/compiler/rustc_middle/src/hir/mod.rs index a16317a0c670b..af99c7d55c37b 100644 --- a/compiler/rustc_middle/src/hir/mod.rs +++ b/compiler/rustc_middle/src/hir/mod.rs @@ -195,7 +195,7 @@ pub fn provide(providers: &mut Providers) { | Node::ForeignItem(&ForeignItem { kind: ForeignItemKind::Fn(_, idents, _), .. - }) = hir.get(hir_id) + }) = tcx.hir_node(hir_id) { idents } else { diff --git a/compiler/rustc_middle/src/middle/region.rs b/compiler/rustc_middle/src/middle/region.rs index 30f13afff9ae3..3f6dc2b9f1261 100644 --- a/compiler/rustc_middle/src/middle/region.rs +++ b/compiler/rustc_middle/src/middle/region.rs @@ -180,7 +180,7 @@ impl Scope { }; let span = tcx.hir().span(hir_id); if let ScopeData::Remainder(first_statement_index) = self.data { - if let Node::Block(blk) = tcx.hir().get(hir_id) { + if let Node::Block(blk) = tcx.hir_node(hir_id) { // Want span for scope starting after the // indexed statement and ending at end of // `blk`; reuse span of `blk` and shift `lo` diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 27d82f5fefc44..564a1fad14dad 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -219,7 +219,7 @@ fn late_report_deprecation( } let method_span = method_span.unwrap_or(span); tcx.struct_span_lint_hir(lint, hir_id, method_span, message, |diag| { - if let hir::Node::Expr(_) = tcx.hir().get(hir_id) { + if let hir::Node::Expr(_) = tcx.hir_node(hir_id) { let kind = tcx.def_descr(def_id); deprecation_suggestion(diag, kind, suggestion, method_span); } diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index b99e5a4f813dd..a3fa568114f50 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -167,7 +167,7 @@ impl<'tcx> Const<'tcx> { /// becomes `Unevaluated`. #[instrument(skip(tcx), level = "debug")] pub fn from_anon_const(tcx: TyCtxt<'tcx>, def: LocalDefId) -> Self { - let body_id = match tcx.hir().get_by_def_id(def) { + let body_id = match tcx.hir_node_by_def_id(def) { hir::Node::AnonConst(ac) => ac.body, _ => span_bug!( tcx.def_span(def.to_def_id()), @@ -443,7 +443,7 @@ impl<'tcx> Const<'tcx> { } pub fn const_param_default(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder> { - let default_def_id = match tcx.hir().get_by_def_id(def_id) { + let default_def_id = match tcx.hir_node_by_def_id(def_id) { hir::Node::GenericParam(hir::GenericParam { kind: hir::GenericParamKind::Const { default: Some(ac), .. }, .. diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index eb6fde83fcc8f..d027a193f6367 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1174,7 +1174,7 @@ impl<'tcx> TyCtxt<'tcx> { break (scope, ty::BrNamed(def_id.into(), self.item_name(def_id.into()))); }; - let is_impl_item = match self.hir().find_by_def_id(suitable_region_binding_scope) { + let is_impl_item = match self.opt_hir_node_by_def_id(suitable_region_binding_scope) { Some(Node::Item(..) | Node::TraitItem(..)) => false, Some(Node::ImplItem(..)) => { self.is_bound_region_in_impl_item(suitable_region_binding_scope) @@ -1217,8 +1217,8 @@ impl<'tcx> TyCtxt<'tcx> { None, hir::Path { res: hir::def::Res::Def(DefKind::TyAlias, def_id), .. }, )) = hir_output.kind && let Some(local_id) = def_id.as_local() - && let Some(alias_ty) = self.hir().get_by_def_id(local_id).alias_ty() // it is type alias - && let Some(alias_generics) = self.hir().get_by_def_id(local_id).generics() + && let Some(alias_ty) = self.hir_node_by_def_id(local_id).alias_ty() // it is type alias + && let Some(alias_generics) = self.hir_node_by_def_id(local_id).generics() { v.visit_ty(alias_ty); if !v.0.is_empty() { @@ -2137,7 +2137,7 @@ impl<'tcx> TyCtxt<'tcx> { loop { let parent = self.local_parent(rpit_lifetime_param_def_id); let hir::OpaqueTy { lifetime_mapping, .. } = - self.hir().get_by_def_id(parent).expect_item().expect_opaque_ty(); + self.hir_node_by_def_id(parent).expect_item().expect_opaque_ty(); let Some((lifetime, _)) = lifetime_mapping .iter() @@ -2221,8 +2221,7 @@ impl<'tcx> TyCtxt<'tcx> { /// Whether the trait impl is marked const. This does not consider stability or feature gates. pub fn is_const_trait_impl_raw(self, def_id: DefId) -> bool { let Some(local_def_id) = def_id.as_local() else { return false }; - let hir_id = self.local_def_id_to_hir_id(local_def_id); - let node = self.hir().get(hir_id); + let node = self.hir_node_by_def_id(local_def_id); matches!( node, diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index 8ccd3c1aba0cc..3224f2f26df5b 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -154,8 +154,9 @@ pub fn recursive_type_error( let (_, field_id) = item_and_field_ids[i]; let (next_item_id, _) = item_and_field_ids[(i + 1) % cycle_len]; // Find the span(s) that contain the next item in the cycle - let hir_id = tcx.local_def_id_to_hir_id(field_id); - let hir::Node::Field(field) = tcx.hir().get(hir_id) else { bug!("expected field") }; + let hir::Node::Field(field) = tcx.hir_node_by_def_id(field_id) else { + bug!("expected field") + }; let mut found = Vec::new(); find_item_ty_spans(tcx, field.ty, next_item_id, &mut found, representable_ids); diff --git a/compiler/rustc_mir_build/src/build/mod.rs b/compiler/rustc_mir_build/src/build/mod.rs index 19b6496b102ef..c63c7987f5efb 100644 --- a/compiler/rustc_mir_build/src/build/mod.rs +++ b/compiler/rustc_mir_build/src/build/mod.rs @@ -572,7 +572,7 @@ fn construct_const<'a, 'tcx>( let hir_id = tcx.local_def_id_to_hir_id(def); // Figure out what primary body this item has. - let (span, const_ty_span) = match tcx.hir().get(hir_id) { + let (span, const_ty_span) = match tcx.hir_node(hir_id) { Node::Item(hir::Item { kind: hir::ItemKind::Static(ty, _, _) | hir::ItemKind::Const(ty, _, _), span, diff --git a/compiler/rustc_mir_build/src/thir/cx/mod.rs b/compiler/rustc_mir_build/src/thir/cx/mod.rs index 4eba7103c0cda..fa3dd2afa85db 100644 --- a/compiler/rustc_mir_build/src/thir/cx/mod.rs +++ b/compiler/rustc_mir_build/src/thir/cx/mod.rs @@ -110,7 +110,7 @@ impl<'tcx> Cx<'tcx> { #[instrument(level = "debug", skip(self))] fn pattern_from_hir(&mut self, p: &hir::Pat<'_>) -> Box> { - let p = match self.tcx.hir().get(p.hir_id) { + let p = match self.tcx.hir_node(p.hir_id) { Node::Pat(p) => p, node => bug!("pattern became {:?}", node), }; diff --git a/compiler/rustc_mir_transform/src/coverage/mod.rs b/compiler/rustc_mir_transform/src/coverage/mod.rs index 796150f931581..580cbf7a3f80a 100644 --- a/compiler/rustc_mir_transform/src/coverage/mod.rs +++ b/compiler/rustc_mir_transform/src/coverage/mod.rs @@ -50,7 +50,7 @@ impl<'tcx> MirPass<'tcx> for InstrumentCoverage { } let is_fn_like = - tcx.hir().get_by_def_id(mir_source.def_id().expect_local()).fn_kind().is_some(); + tcx.hir_node_by_def_id(mir_source.def_id().expect_local()).fn_kind().is_some(); // Only instrument functions, methods, and closures (not constants since they are evaluated // at compile time by Miri). diff --git a/compiler/rustc_mir_transform/src/jump_threading.rs b/compiler/rustc_mir_transform/src/jump_threading.rs index 36a15f472761e..a41d8e212454e 100644 --- a/compiler/rustc_mir_transform/src/jump_threading.rs +++ b/compiler/rustc_mir_transform/src/jump_threading.rs @@ -649,7 +649,7 @@ impl OpportunitySet { // `succ` must be a successor of `current`. If it is not, this means this TO is not // satisfiable and a previous TO erased this edge, so we bail out. - if basic_blocks[current].terminator().successors().find(|s| *s == succ).is_none() { + if !basic_blocks[current].terminator().successors().any(|s| s == succ) { debug!("impossible"); return; } diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index 4910d63010c6e..c5073048be3e8 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -604,7 +604,7 @@ impl CheckAttrVisitor<'_> { && !self.tcx.sess.target.is_like_wasm && !self.tcx.sess.opts.actually_rustdoc { - let hir::Node::Item(item) = self.tcx.hir().get(hir_id) else { + let hir::Node::Item(item) = self.tcx.hir_node(hir_id) else { unreachable!(); }; let hir::ItemKind::Fn(sig, _, _) = item.kind else { @@ -820,7 +820,7 @@ impl CheckAttrVisitor<'_> { self.doc_attr_str_error(meta, "keyword"); return false; } - match self.tcx.hir().find(hir_id).and_then(|node| match node { + match self.tcx.opt_hir_node(hir_id).and_then(|node| match node { hir::Node::Item(item) => Some(&item.kind), _ => None, }) { @@ -846,7 +846,7 @@ impl CheckAttrVisitor<'_> { } fn check_doc_fake_variadic(&self, meta: &NestedMetaItem, hir_id: HirId) -> bool { - match self.tcx.hir().find(hir_id).and_then(|node| match node { + match self.tcx.opt_hir_node(hir_id).and_then(|node| match node { hir::Node::Item(item) => Some(&item.kind), _ => None, }) { @@ -1387,7 +1387,7 @@ impl CheckAttrVisitor<'_> { /// Checks if `#[link]` is applied to an item other than a foreign module. fn check_link(&self, hir_id: HirId, attr: &Attribute, span: Span, target: Target) { if target == Target::ForeignMod - && let hir::Node::Item(item) = self.tcx.hir().get(hir_id) + && let hir::Node::Item(item) = self.tcx.hir_node(hir_id) && let Item { kind: ItemKind::ForeignMod { abi, .. }, .. } = item && !matches!(abi, Abi::Rust | Abi::RustIntrinsic | Abi::PlatformIntrinsic) { @@ -1456,7 +1456,7 @@ impl CheckAttrVisitor<'_> { } fn is_impl_item(&self, hir_id: HirId) -> bool { - matches!(self.tcx.hir().get(hir_id), hir::Node::ImplItem(..)) + matches!(self.tcx.hir_node(hir_id), hir::Node::ImplItem(..)) } /// Checks if `#[export_name]` is applied to a function or static. Returns `true` if valid. @@ -2074,7 +2074,7 @@ impl CheckAttrVisitor<'_> { && let hir::Node::Item(Item { kind: ItemKind::ForeignMod { abi: Abi::RustIntrinsic | Abi::PlatformIntrinsic, .. }, .. - }) = hir.get(parent) + }) = self.tcx.hir_node(parent) { return true; } @@ -2222,7 +2222,7 @@ impl CheckAttrVisitor<'_> { } else { // special case when `#[macro_export]` is applied to a macro 2.0 let (macro_definition, _) = - self.tcx.hir().find(hir_id).unwrap().expect_item().expect_macro(); + self.tcx.opt_hir_node(hir_id).unwrap().expect_item().expect_macro(); let is_decl_macro = !macro_definition.macro_rules; if is_decl_macro { diff --git a/compiler/rustc_passes/src/dead.rs b/compiler/rustc_passes/src/dead.rs index 7d1cc81e21f65..d270794978b27 100644 --- a/compiler/rustc_passes/src/dead.rs +++ b/compiler/rustc_passes/src/dead.rs @@ -32,7 +32,7 @@ use crate::errors::{ // may need to be marked as live. fn should_explore(tcx: TyCtxt<'_>, def_id: LocalDefId) -> bool { matches!( - tcx.hir().find_by_def_id(def_id), + tcx.opt_hir_node_by_def_id(def_id), Some( Node::Item(..) | Node::ImplItem(..) @@ -297,7 +297,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> { // tuple struct constructor function let id = self.struct_constructors.get(&id).copied().unwrap_or(id); - if let Some(node) = self.tcx.hir().find_by_def_id(id) { + if let Some(node) = self.tcx.opt_hir_node_by_def_id(id) { // When using `#[allow]` or `#[expect]` of `dead_code`, we do a QOL improvement // by declaring fn calls, statics, ... within said items as live, as well as // the item itself, although technically this is not the case. diff --git a/compiler/rustc_passes/src/entry.rs b/compiler/rustc_passes/src/entry.rs index 2629b2817565c..7667fc21eee05 100644 --- a/compiler/rustc_passes/src/entry.rs +++ b/compiler/rustc_passes/src/entry.rs @@ -126,7 +126,7 @@ fn configure_main(tcx: TyCtxt<'_>, visitor: &EntryContext<'_>) -> Option<(DefId, { // non-local main imports are handled below if let Some(def_id) = def_id.as_local() - && matches!(tcx.hir().find_by_def_id(def_id), Some(Node::ForeignItem(_))) + && matches!(tcx.opt_hir_node_by_def_id(def_id), Some(Node::ForeignItem(_))) { tcx.sess.emit_err(ExternMain { span: tcx.def_span(def_id) }); return None; diff --git a/compiler/rustc_passes/src/lang_items.rs b/compiler/rustc_passes/src/lang_items.rs index d0b782ba4caca..83b7d8d71bc85 100644 --- a/compiler/rustc_passes/src/lang_items.rs +++ b/compiler/rustc_passes/src/lang_items.rs @@ -155,7 +155,7 @@ impl<'tcx> LanguageItemCollector<'tcx> { // have minimum requirements. if let hir::Node::Item(hir::Item { kind, span: item_span, .. }) = - self.tcx.hir().get_by_def_id(item_def_id) + self.tcx.hir_node_by_def_id(item_def_id) { let (actual_num, generics_span) = match kind.generics() { Some(generics) => ( diff --git a/compiler/rustc_passes/src/loops.rs b/compiler/rustc_passes/src/loops.rs index 8e6d580527564..bfaf4a5a95717 100644 --- a/compiler/rustc_passes/src/loops.rs +++ b/compiler/rustc_passes/src/loops.rs @@ -4,7 +4,6 @@ use rustc_hir as hir; use rustc_hir::def_id::{LocalDefId, LocalModDefId}; use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::{Destination, Movability, Node}; -use rustc_middle::hir::map::Map; use rustc_middle::hir::nested_filter; use rustc_middle::query::Providers; use rustc_middle::ty::TyCtxt; @@ -30,16 +29,16 @@ enum Context { } #[derive(Copy, Clone)] -struct CheckLoopVisitor<'a, 'hir> { +struct CheckLoopVisitor<'a, 'tcx> { sess: &'a Session, - hir_map: Map<'hir>, + tcx: TyCtxt<'tcx>, cx: Context, } fn check_mod_loops(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { tcx.hir().visit_item_likes_in_module( module_def_id, - &mut CheckLoopVisitor { sess: tcx.sess, hir_map: tcx.hir(), cx: Normal }, + &mut CheckLoopVisitor { sess: tcx.sess, tcx, cx: Normal }, ); } @@ -51,7 +50,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { type NestedFilter = nested_filter::OnlyBodies; fn nested_visit_map(&mut self) -> Self::Map { - self.hir_map + self.tcx.hir() } fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) { @@ -136,13 +135,13 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { Err(hir::LoopIdError::UnresolvedLabel) => None, }; - if let Some(Node::Block(_)) = loop_id.and_then(|id| self.hir_map.find(id)) { + if let Some(Node::Block(_)) = loop_id.and_then(|id| self.tcx.opt_hir_node(id)) { return; } if let Some(break_expr) = opt_expr { let (head, loop_label, loop_kind) = if let Some(loop_id) = loop_id { - match self.hir_map.expect_expr(loop_id).kind { + match self.tcx.hir().expect_expr(loop_id).kind { hir::ExprKind::Loop(_, label, source, sp) => { (Some(sp), label, Some(source)) } @@ -188,7 +187,7 @@ impl<'a, 'hir> Visitor<'hir> for CheckLoopVisitor<'a, 'hir> { match destination.target_id { Ok(loop_id) => { - if let Node::Block(block) = self.hir_map.find(loop_id).unwrap() { + if let Node::Block(block) = self.tcx.opt_hir_node(loop_id).unwrap() { self.sess.emit_err(ContinueLabeledBlock { span: e.span, block_span: block.span, diff --git a/compiler/rustc_passes/src/naked_functions.rs b/compiler/rustc_passes/src/naked_functions.rs index bd73fa7844222..25637f935fbdf 100644 --- a/compiler/rustc_passes/src/naked_functions.rs +++ b/compiler/rustc_passes/src/naked_functions.rs @@ -35,7 +35,7 @@ fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) { continue; } - let (fn_header, body_id) = match tcx.hir().get_by_def_id(def_id) { + let (fn_header, body_id) = match tcx.hir_node_by_def_id(def_id) { hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. }) | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)), diff --git a/compiler/rustc_passes/src/reachable.rs b/compiler/rustc_passes/src/reachable.rs index f89c1b0e47c67..f46f831ddd7c9 100644 --- a/compiler/rustc_passes/src/reachable.rs +++ b/compiler/rustc_passes/src/reachable.rs @@ -115,7 +115,7 @@ impl<'tcx> ReachableContext<'tcx> { return false; }; - match self.tcx.hir().find_by_def_id(def_id) { + match self.tcx.opt_hir_node_by_def_id(def_id) { Some(Node::Item(item)) => match item.kind { hir::ItemKind::Fn(..) => item_might_be_inlined(self.tcx, def_id.into()), _ => false, @@ -146,7 +146,7 @@ impl<'tcx> ReachableContext<'tcx> { continue; } - if let Some(ref item) = self.tcx.hir().find_by_def_id(search_item) { + if let Some(ref item) = self.tcx.opt_hir_node_by_def_id(search_item) { self.propagate_node(item, search_item); } } diff --git a/compiler/rustc_pattern_analysis/src/constructor.rs b/compiler/rustc_pattern_analysis/src/constructor.rs index 716ccdd4dcd00..3bca7894a2921 100644 --- a/compiler/rustc_pattern_analysis/src/constructor.rs +++ b/compiler/rustc_pattern_analysis/src/constructor.rs @@ -979,7 +979,8 @@ impl ConstructorSet { && !(pcx.is_top_level && matches!(self, Self::NoConstructors)) { // Treat all missing constructors as nonempty. - missing.extend(missing_empty.drain(..)); + // This clears `missing_empty`. + missing.append(&mut missing_empty); } SplitConstructorSet { present, missing, missing_empty } diff --git a/compiler/rustc_privacy/src/lib.rs b/compiler/rustc_privacy/src/lib.rs index e49282e638ab4..6a8e23d9a8f09 100644 --- a/compiler/rustc_privacy/src/lib.rs +++ b/compiler/rustc_privacy/src/lib.rs @@ -1783,7 +1783,7 @@ fn local_visibility(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Visibility { Some(vis) => *vis, None => { let hir_id = tcx.local_def_id_to_hir_id(def_id); - match tcx.hir().get(hir_id) { + match tcx.hir_node(hir_id) { // Unique types created for closures participate in type privacy checking. // They have visibilities inherited from the module they are defined in. Node::Expr(hir::Expr { kind: hir::ExprKind::Closure{..}, .. }) @@ -1800,7 +1800,7 @@ fn local_visibility(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Visibility { // Visibilities of trait impl items are inherited from their traits // and are not filled in resolve. Node::ImplItem(impl_item) => { - match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id).def_id) { + match tcx.hir_node_by_def_id(tcx.hir().get_parent_item(hir_id).def_id) { Node::Item(hir::Item { kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), .. diff --git a/compiler/rustc_query_system/src/dep_graph/serialized.rs b/compiler/rustc_query_system/src/dep_graph/serialized.rs index a70f4138cfb53..504763f6cdb38 100644 --- a/compiler/rustc_query_system/src/dep_graph/serialized.rs +++ b/compiler/rustc_query_system/src/dep_graph/serialized.rs @@ -70,7 +70,7 @@ const DEP_NODE_PAD: usize = DEP_NODE_SIZE - 1; const DEP_NODE_WIDTH_BITS: usize = DEP_NODE_SIZE / 2; /// Data for use when recompiling the **current crate**. -#[derive(Debug)] +#[derive(Debug, Default)] pub struct SerializedDepGraph { /// The set of all DepNodes in the graph nodes: IndexVec, @@ -89,18 +89,6 @@ pub struct SerializedDepGraph { index: Vec>, } -impl Default for SerializedDepGraph { - fn default() -> Self { - SerializedDepGraph { - nodes: Default::default(), - fingerprints: Default::default(), - edge_list_indices: Default::default(), - edge_list_data: Default::default(), - index: Default::default(), - } - } -} - impl SerializedDepGraph { #[inline] pub fn edge_targets_from( diff --git a/compiler/rustc_resolve/src/late/diagnostics.rs b/compiler/rustc_resolve/src/late/diagnostics.rs index 61c7846ea61a3..374ce1a528f01 100644 --- a/compiler/rustc_resolve/src/late/diagnostics.rs +++ b/compiler/rustc_resolve/src/late/diagnostics.rs @@ -2178,7 +2178,7 @@ impl<'a: 'ast, 'ast, 'tcx> LateResolutionVisitor<'a, '_, 'ast, 'tcx> { let (span, text) = match path.segments.first() { Some(seg) if let Some(name) = seg.ident.as_str().strip_prefix("let") => { // a special case for #117894 - let name = name.strip_prefix("_").unwrap_or(name); + let name = name.strip_prefix('_').unwrap_or(name); (ident_span, format!("let {name}")) } _ => (ident_span.shrink_to_lo(), "let ".to_string()), diff --git a/compiler/rustc_smir/src/rustc_smir/context.rs b/compiler/rustc_smir/src/rustc_smir/context.rs index 4ec5e2a538708..241a0c2231064 100644 --- a/compiler/rustc_smir/src/rustc_smir/context.rs +++ b/compiler/rustc_smir/src/rustc_smir/context.rs @@ -157,7 +157,7 @@ impl<'tcx> Context for TablesWrapper<'tcx> { (name == crate_name).then(|| smir_crate(tables.tcx, *crate_num)) }) .into_iter() - .filter_map(|c| c) + .flatten() .collect(); crates } diff --git a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs index e49d134659ec6..3d673f2f1ec04 100644 --- a/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs +++ b/compiler/rustc_symbol_mangling/src/typeid/typeid_itanium_cxx_abi.rs @@ -364,7 +364,7 @@ fn encode_ty_name(tcx: TyCtxt<'_>, def_id: DefId) -> String { // _ZTSFvu27NvNtC1234_5crate6Trait13fooIu22NtC1234_5crate7Struct1Iu3i32ES_EE // // The reason for not using v0's extended form of paths is to use a consistent and simpler - // encoding, as the reasoning for using it isn't relevand for type metadata identifiers (i.e., + // encoding, as the reasoning for using it isn't relevant for type metadata identifiers (i.e., // keep symbol names close to how methods are represented in error messages). See // https://rust-lang.github.io/rfcs/2603-rust-symbol-name-mangling-v0.html#methods. let mut s = String::new(); diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index c07db12b25b25..61e97dde5f866 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -103,7 +103,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { /// to be the enclosing (async) block/function/closure fn describe_enclosure(&self, hir_id: hir::HirId) -> Option<&'static str> { let hir = self.tcx.hir(); - let node = hir.find(hir_id)?; + let node = self.tcx.opt_hir_node(hir_id)?; match &node { hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. }) => { self.describe_coroutine(*body_id).or_else(|| { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index f7e8dc62a625d..1d12d7761e1d5 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -530,7 +530,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { // FIXME: Add check for trait bound that is already present, particularly `?Sized` so we // don't suggest `T: Sized + ?Sized`. - while let Some(node) = self.tcx.hir().find_by_def_id(body_id) { + while let Some(node) = self.tcx.opt_hir_node_by_def_id(body_id) { match node { hir::Node::Item(hir::Item { ident, @@ -732,7 +732,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let Some(typeck_results) = &self.typeck_results else { return false; }; - let hir::Node::Expr(expr) = self.tcx.hir().get(*arg_hir_id) else { + let hir::Node::Expr(expr) = self.tcx.hir_node(*arg_hir_id) else { return false; }; let Some(arg_ty) = typeck_results.expr_ty_adjusted_opt(expr) else { @@ -785,7 +785,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { kind: hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, expr), .. - })) = self.tcx.hir().find(*arg_hir_id) + })) = self.tcx.opt_hir_node(*arg_hir_id) { let derefs = "*".repeat(steps); err.span_suggestion_verbose( @@ -821,7 +821,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if self.predicate_may_hold(&obligation) && self.predicate_must_hold_modulo_regions(&sized_obligation) { - let call_node = self.tcx.hir().get(*call_hir_id); + let call_node = self.tcx.hir_node(*call_hir_id); let msg = "consider dereferencing here"; let is_receiver = matches!( call_node, @@ -1046,7 +1046,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let Res::Local(hir_id) = path.res else { return; }; - let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else { + let Some(hir::Node::Pat(pat)) = self.tcx.opt_hir_node(hir_id) else { return; }; let Some(hir::Node::Local(hir::Local { ty: None, init: Some(init), .. })) = @@ -1106,7 +1106,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { else { return false; }; - let arg_node = self.tcx.hir().get(*arg_hir_id); + let arg_node = self.tcx.hir_node(*arg_hir_id); let Node::Expr(Expr { kind: hir::ExprKind::Path(_), .. }) = arg_node else { return false }; let clone_trait = self.tcx.require_lang_item(LangItem::Clone, None); @@ -1628,7 +1628,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind && let Res::Local(hir_id) = path.res - && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(hir_id) + && let Some(hir::Node::Pat(binding)) = self.tcx.opt_hir_node(hir_id) && let Some(hir::Node::Local(local)) = self.tcx.hir().find_parent(binding.hir_id) && let None = local.ty && let Some(binding_expr) = local.init @@ -1644,7 +1644,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn suggest_remove_await(&self, obligation: &PredicateObligation<'tcx>, err: &mut Diagnostic) { let hir = self.tcx.hir(); if let ObligationCauseCode::AwaitableExpr(hir_id) = obligation.cause.code().peel_derives() - && let hir::Node::Expr(expr) = hir.get(*hir_id) + && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id) { // FIXME: use `obligation.predicate.kind()...trait_ref.self_ty()` to see if we have `()` // and if not maybe suggest doing something else? If we kept the expression around we @@ -1794,7 +1794,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { let hir = self.tcx.hir(); - let node = hir.find_by_def_id(obligation.cause.body_id); + let node = self.tcx.opt_hir_node_by_def_id(obligation.cause.body_id); if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, _, body_id), .. })) = node && let hir::ExprKind::Block(blk, _) = &hir.body(*body_id).value.kind && sig.decl.output.span().overlaps(span) @@ -1829,9 +1829,8 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } fn return_type_span(&self, obligation: &PredicateObligation<'tcx>) -> Option { - let hir = self.tcx.hir(); let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(sig, ..), .. })) = - hir.find_by_def_id(obligation.cause.body_id) + self.tcx.opt_hir_node_by_def_id(obligation.cause.body_id) else { return None; }; @@ -1923,7 +1922,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } let hir = self.tcx.hir(); - let node = hir.find_by_def_id(obligation.cause.body_id); + let node = self.tcx.opt_hir_node_by_def_id(obligation.cause.body_id); if let Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) = node { @@ -2041,7 +2040,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { let ty::FnPtr(found) = found.kind() else { return; }; - let Some(Node::Expr(arg)) = self.tcx.hir().find(*arg_hir_id) else { + let Some(Node::Expr(arg)) = self.tcx.opt_hir_node(*arg_hir_id) else { return; }; let hir::ExprKind::Path(path) = arg.kind else { @@ -2986,7 +2985,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } ObligationCauseCode::VariableType(hir_id) => { let parent_node = self.tcx.hir().parent_id(hir_id); - match self.tcx.hir().find(parent_node) { + match self.tcx.opt_hir_node(parent_node) { Some(Node::Local(hir::Local { ty: Some(ty), .. })) => { err.span_suggestion_verbose( ty.span.shrink_to_lo(), @@ -3130,7 +3129,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { "all values captured by value by a closure must have a statically known size", ); let hir::ExprKind::Closure(closure) = - self.tcx.hir().get_by_def_id(closure_def_id).expect_expr().kind + self.tcx.hir_node_by_def_id(closure_def_id).expect_expr().kind else { bug!("expected closure in SizedClosureCapture obligation"); }; @@ -3701,8 +3700,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { call_hir_id: HirId, ) { let tcx = self.tcx; - let hir = tcx.hir(); - if let Some(Node::Expr(expr)) = hir.find(arg_hir_id) + if let Some(Node::Expr(expr)) = tcx.opt_hir_node(arg_hir_id) && let Some(typeck_results) = &self.typeck_results { if let hir::Expr { kind: hir::ExprKind::Block(block, _), .. } = expr { @@ -3735,7 +3733,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { && let hir::ExprKind::Closure(hir::Closure { body, fn_decl_span, .. }) = value.kind - && let body = hir.body(*body) + && let body = tcx.hir().body(*body) && !matches!(body.value.kind, hir::ExprKind::Block(..)) { // Check if the failed predicate was an expectation of a closure type @@ -3818,9 +3816,9 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind && let hir::Path { res: Res::Local(hir_id), .. } = path - && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id) + && let Some(hir::Node::Pat(binding)) = self.tcx.opt_hir_node(*hir_id) && let parent_hir_id = self.tcx.hir().parent_id(binding.hir_id) - && let Some(hir::Node::Local(local)) = self.tcx.hir().find(parent_hir_id) + && let Some(hir::Node::Local(local)) = self.tcx.opt_hir_node(parent_hir_id) && let Some(binding_expr) = local.init { // If the expression we're calling on is a binding, we want to point at the @@ -3831,7 +3829,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { self.point_at_chain(expr, typeck_results, type_diffs, param_env, err); } } - let call_node = hir.find(call_hir_id); + let call_node = tcx.opt_hir_node(call_hir_id); if let Some(Node::Expr(hir::Expr { kind: hir::ExprKind::MethodCall(path, rcvr, ..), .. })) = call_node @@ -3841,7 +3839,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } - if let Some(Node::Expr(expr)) = hir.find(call_hir_id) { + if let Some(Node::Expr(expr)) = tcx.opt_hir_node(call_hir_id) { if let hir::ExprKind::Call(hir::Expr { span, .. }, _) | hir::ExprKind::MethodCall( hir::PathSegment { ident: Ident { span, .. }, .. }, @@ -4002,7 +4000,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { continue; }; let hir = tcx.hir(); - let node = hir.get_by_def_id(hir.get_parent_item(expr.hir_id).def_id); + let node = tcx.hir_node_by_def_id(hir.get_parent_item(expr.hir_id).def_id); let pred = ty::Binder::dummy(ty::TraitPredicate { trait_ref: ty::TraitRef::from_lang_item( @@ -4078,7 +4076,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind && let hir::Path { res: Res::Local(hir_id), .. } = path - && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id) + && let Some(hir::Node::Pat(binding)) = self.tcx.opt_hir_node(*hir_id) && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id) { // We've reached the root of the method call chain... @@ -4457,7 +4455,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } return; }; - let Some(hir::Node::TraitItem(item)) = self.tcx.hir().find_by_def_id(fn_def_id) else { + let Some(hir::Node::TraitItem(item)) = self.tcx.opt_hir_node_by_def_id(fn_def_id) else { return; }; @@ -4778,7 +4776,7 @@ pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>( return None; }; - let future = tcx.hir().get_by_def_id(opaque_def_id).expect_item().expect_opaque_ty(); + let future = tcx.hir_node_by_def_id(opaque_def_id).expect_item().expect_opaque_ty(); let Some(hir::GenericBound::LangItemTrait(_, _, _, generics)) = future.bounds.get(0) else { // `async fn` should always lower to a lang item bound... but don't ICE. return None; diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs index 4988222c135eb..1f7c662d50680 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs @@ -984,13 +984,13 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn fn_arg_obligation(&self, obligation: &PredicateObligation<'tcx>) -> bool { if let ObligationCauseCode::FunctionArgumentObligation { arg_hir_id, .. } = obligation.cause.code() - && let Some(Node::Expr(arg)) = self.tcx.hir().find(*arg_hir_id) + && let Some(Node::Expr(arg)) = self.tcx.opt_hir_node(*arg_hir_id) && let arg = arg.peel_borrows() && let hir::ExprKind::Path(hir::QPath::Resolved( None, hir::Path { res: hir::def::Res::Local(hir_id), .. }, )) = arg.kind - && let Some(Node::Pat(pat)) = self.tcx.hir().find(*hir_id) + && let Some(Node::Pat(pat)) = self.tcx.opt_hir_node(*hir_id) && let Some(preds) = self.reported_trait_errors.borrow().get(&pat.span) && preds.contains(&obligation.predicate) { @@ -1028,7 +1028,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { } } let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_id); - let body_id = match self.tcx.hir().find(hir_id) { + let body_id = match self.tcx.opt_hir_node(hir_id) { Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })) => { body_id } @@ -1069,7 +1069,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if !self.tcx.is_diagnostic_item(sym::Result, def.did()) { return None; } - Some(arg.as_type()?) + arg.as_type() }; let mut suggested = false; @@ -1154,7 +1154,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path - && let Some(hir::Node::Pat(binding)) = self.tcx.hir().find(*hir_id) + && let Some(hir::Node::Pat(binding)) = self.tcx.opt_hir_node(*hir_id) && let Some(parent) = self.tcx.hir().find_parent(binding.hir_id) { // We've reached the root of the method call chain... @@ -2499,7 +2499,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> { ident: trait_name, kind: hir::ItemKind::Trait(_, _, _, _, trait_item_refs), .. - })) = self.tcx.hir().find_by_def_id(local_def_id) + })) = self.tcx.opt_hir_node_by_def_id(local_def_id) && let Some(method_ref) = trait_item_refs .iter() .find(|item_ref| item_ref.ident == *assoc_item_name) diff --git a/compiler/rustc_ty_utils/src/assoc.rs b/compiler/rustc_ty_utils/src/assoc.rs index 7a81570e55b85..db37bec4b827c 100644 --- a/compiler/rustc_ty_utils/src/assoc.rs +++ b/compiler/rustc_ty_utils/src/assoc.rs @@ -345,8 +345,7 @@ fn associated_type_for_impl_trait_in_impl( let impl_local_def_id = tcx.local_parent(impl_fn_def_id); let decl = tcx - .hir() - .find_by_def_id(impl_fn_def_id) + .opt_hir_node_by_def_id(impl_fn_def_id) .expect("expected item") .fn_decl() .expect("expected decl"); diff --git a/compiler/rustc_ty_utils/src/implied_bounds.rs b/compiler/rustc_ty_utils/src/implied_bounds.rs index eef90dc6dac63..3f9bd509b087c 100644 --- a/compiler/rustc_ty_utils/src/implied_bounds.rs +++ b/compiler/rustc_ty_utils/src/implied_bounds.rs @@ -161,7 +161,7 @@ fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<' } fn fn_sig_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator + '_ { - let node = tcx.hir().get(tcx.local_def_id_to_hir_id(def_id)); + let node = tcx.hir_node_by_def_id(def_id); if let Some(decl) = node.fn_decl() { decl.inputs.iter().map(|ty| ty.span).chain(iter::once(decl.output.span())) } else { diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index d896873fadda9..7918965e04baa 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -831,7 +831,10 @@ fn coroutine_layout<'tcx>( Assigned(_) => bug!("assignment does not match variant"), Ineligible(_) => false, }) - .map(|local| subst_field(info.field_tys[*local].ty)); + .map(|local| { + let field_ty = subst_field(info.field_tys[*local].ty); + Ty::new_maybe_uninit(tcx, field_ty) + }); let mut variant = univariant_uninterned( cx, diff --git a/compiler/rustc_ty_utils/src/sig_types.rs b/compiler/rustc_ty_utils/src/sig_types.rs index 7c0261c818f55..b155a4ac87b9f 100644 --- a/compiler/rustc_ty_utils/src/sig_types.rs +++ b/compiler/rustc_ty_utils/src/sig_types.rs @@ -28,7 +28,7 @@ pub(crate) fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( // Walk over the signature of the function DefKind::AssocFn | DefKind::Fn => { let ty_sig = tcx.fn_sig(item).instantiate_identity(); - let hir_sig = tcx.hir().get_by_def_id(item).fn_decl().unwrap(); + let hir_sig = tcx.hir_node_by_def_id(item).fn_decl().unwrap(); // Walk over the inputs and outputs manually in order to get good spans for them. visitor.visit(hir_sig.output.span(), ty_sig.output()); for (hir, ty) in hir_sig.inputs.iter().zip(ty_sig.inputs().iter()) { @@ -42,7 +42,7 @@ pub(crate) fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( DefKind::TyAlias {..} | DefKind::AssocTy | // Walk over the type of the item DefKind::Static(_) | DefKind::Const | DefKind::AssocConst | DefKind::AnonConst => { - let span = match tcx.hir().get_by_def_id(item).ty() { + let span = match tcx.hir_node_by_def_id(item).ty() { Some(ty) => ty.span, _ => tcx.def_span(item), }; @@ -70,11 +70,11 @@ pub(crate) fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( DefKind::InlineConst | DefKind::Closure => {} DefKind::Impl { of_trait } => { if of_trait { - let span = tcx.hir().get_by_def_id(item).expect_item().expect_impl().of_trait.unwrap().path.span; + let span = tcx.hir_node_by_def_id(item).expect_item().expect_impl().of_trait.unwrap().path.span; let args = &tcx.impl_trait_ref(item).unwrap().instantiate_identity().args[1..]; visitor.visit(span, args)?; } - let span = match tcx.hir().get_by_def_id(item).ty() { + let span = match tcx.hir_node_by_def_id(item).ty() { Some(ty) => ty.span, _ => tcx.def_span(item), }; diff --git a/compiler/rustc_ty_utils/src/ty.rs b/compiler/rustc_ty_utils/src/ty.rs index 56e84b6015d46..2158aacab03d8 100644 --- a/compiler/rustc_ty_utils/src/ty.rs +++ b/compiler/rustc_ty_utils/src/ty.rs @@ -74,7 +74,7 @@ fn sized_constraint_for_ty<'tcx>( } fn defaultness(tcx: TyCtxt<'_>, def_id: LocalDefId) -> hir::Defaultness { - match tcx.hir().get_by_def_id(def_id) { + match tcx.hir_node_by_def_id(def_id) { hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(impl_), .. }) => impl_.defaultness, hir::Node::ImplItem(hir::ImplItem { defaultness, .. }) | hir::Node::TraitItem(hir::TraitItem { defaultness, .. }) => *defaultness, @@ -300,7 +300,7 @@ fn issue33140_self_ty(tcx: TyCtxt<'_>, def_id: DefId) -> Option, def_id: LocalDefId) -> ty::Asyncness { - let node = tcx.hir().get_by_def_id(def_id); + let node = tcx.hir_node_by_def_id(def_id); node.fn_sig().map_or(ty::Asyncness::No, |sig| match sig.header.asyncness { hir::IsAsync::Async(_) => ty::Asyncness::Yes, hir::IsAsync::NotAsync => ty::Asyncness::No, diff --git a/library/core/src/tuple.rs b/library/core/src/tuple.rs index 765f73636fb8e..3689312e6ae11 100644 --- a/library/core/src/tuple.rs +++ b/library/core/src/tuple.rs @@ -8,6 +8,7 @@ use crate::marker::{StructuralEq, StructuralPartialEq}; // // Also provides implementations for tuples with lesser arity. For example, tuple_impls!(A B C) // will implement everything for (A, B, C), (A, B) and (A,). +#[cfg(bootstrap)] macro_rules! tuple_impls { // Stopping criteria (1-ary tuple) ($T:ident) => { @@ -142,6 +143,148 @@ macro_rules! tuple_impls { } } +// Recursive macro for implementing n-ary tuple functions and operations +// +// Also provides implementations for tuples with lesser arity. For example, tuple_impls!(A B C) +// will implement everything for (A, B, C), (A, B) and (A,). +#[cfg(not(bootstrap))] +macro_rules! tuple_impls { + // Stopping criteria (1-ary tuple) + ($T:ident) => { + tuple_impls!(@impl $T); + }; + // Running criteria (n-ary tuple, with n >= 2) + ($T:ident $( $U:ident )+) => { + tuple_impls!($( $U )+); + tuple_impls!(@impl $T $( $U )+); + }; + // "Private" internal implementation + (@impl $( $T:ident )+) => { + maybe_tuple_doc! { + $($T)+ @ + #[stable(feature = "rust1", since = "1.0.0")] + impl<$($T: PartialEq),+> PartialEq for ($($T,)+) + where + last_type!($($T,)+): ?Sized + { + #[inline] + fn eq(&self, other: &($($T,)+)) -> bool { + $( ${ignore($T)} self.${index()} == other.${index()} )&&+ + } + #[inline] + fn ne(&self, other: &($($T,)+)) -> bool { + $( ${ignore($T)} self.${index()} != other.${index()} )||+ + } + } + } + + maybe_tuple_doc! { + $($T)+ @ + #[stable(feature = "rust1", since = "1.0.0")] + impl<$($T: Eq),+> Eq for ($($T,)+) + where + last_type!($($T,)+): ?Sized + {} + } + + maybe_tuple_doc! { + $($T)+ @ + #[unstable(feature = "structural_match", issue = "31434")] + impl<$($T: ConstParamTy),+> ConstParamTy for ($($T,)+) + {} + } + + maybe_tuple_doc! { + $($T)+ @ + #[unstable(feature = "structural_match", issue = "31434")] + impl<$($T),+> StructuralPartialEq for ($($T,)+) + {} + } + + maybe_tuple_doc! { + $($T)+ @ + #[unstable(feature = "structural_match", issue = "31434")] + impl<$($T),+> StructuralEq for ($($T,)+) + {} + } + + maybe_tuple_doc! { + $($T)+ @ + #[stable(feature = "rust1", since = "1.0.0")] + impl<$($T: PartialOrd),+> PartialOrd for ($($T,)+) + where + last_type!($($T,)+): ?Sized + { + #[inline] + fn partial_cmp(&self, other: &($($T,)+)) -> Option { + lexical_partial_cmp!($( ${ignore($T)} self.${index()}, other.${index()} ),+) + } + #[inline] + fn lt(&self, other: &($($T,)+)) -> bool { + lexical_ord!(lt, Less, $( ${ignore($T)} self.${index()}, other.${index()} ),+) + } + #[inline] + fn le(&self, other: &($($T,)+)) -> bool { + lexical_ord!(le, Less, $( ${ignore($T)} self.${index()}, other.${index()} ),+) + } + #[inline] + fn ge(&self, other: &($($T,)+)) -> bool { + lexical_ord!(ge, Greater, $( ${ignore($T)} self.${index()}, other.${index()} ),+) + } + #[inline] + fn gt(&self, other: &($($T,)+)) -> bool { + lexical_ord!(gt, Greater, $( ${ignore($T)} self.${index()}, other.${index()} ),+) + } + } + } + + maybe_tuple_doc! { + $($T)+ @ + #[stable(feature = "rust1", since = "1.0.0")] + impl<$($T: Ord),+> Ord for ($($T,)+) + where + last_type!($($T,)+): ?Sized + { + #[inline] + fn cmp(&self, other: &($($T,)+)) -> Ordering { + lexical_cmp!($( ${ignore($T)} self.${index()}, other.${index()} ),+) + } + } + } + + maybe_tuple_doc! { + $($T)+ @ + #[stable(feature = "rust1", since = "1.0.0")] + impl<$($T: Default),+> Default for ($($T,)+) { + #[inline] + fn default() -> ($($T,)+) { + ($({ let x: $T = Default::default(); x},)+) + } + } + } + + #[stable(feature = "array_tuple_conv", since = "1.71.0")] + impl From<[T; ${count($T)}]> for ($(${ignore($T)} T,)+) { + #[inline] + #[allow(non_snake_case)] + fn from(array: [T; ${count($T)}]) -> Self { + let [$($T,)+] = array; + ($($T,)+) + } + } + + #[stable(feature = "array_tuple_conv", since = "1.71.0")] + impl From<($(${ignore($T)} T,)+)> for [T; ${count($T)}] { + #[inline] + #[allow(non_snake_case)] + fn from(tuple: ($(${ignore($T)} T,)+)) -> Self { + let ($($T,)+) = tuple; + [$($T,)+] + } + } + } +} + // If this is a unary tuple, it adds a doc comment. // Otherwise, it hides the docs entirely. macro_rules! maybe_tuple_doc { diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 688751627f3ee..ff0bfda759cf2 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1596,7 +1596,6 @@ fn first_non_private<'tcx>( // Absolute paths are not. We start from the parent of the item. [.., parent, leaf] => (parent.res.opt_def_id()?.as_local()?, leaf.ident), }; - let hir = cx.tcx.hir(); // First we try to get the `DefId` of the item. for child in cx.tcx.module_children_local(parent_def_id).iter().filter(move |c| c.ident == ident) @@ -1612,7 +1611,8 @@ fn first_non_private<'tcx>( 'reexps: for reexp in child.reexport_chain.iter() { if let Some(use_def_id) = reexp.id() && let Some(local_use_def_id) = use_def_id.as_local() - && let Some(hir::Node::Item(item)) = hir.find_by_def_id(local_use_def_id) + && let Some(hir::Node::Item(item)) = + cx.tcx.opt_hir_node_by_def_id(local_use_def_id) && !item.ident.name.is_empty() && let hir::ItemKind::Use(path, _) = item.kind { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 82f4a38384dd1..bdfda07be096c 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -439,7 +439,7 @@ fn print_const_with_custom_print_scalar<'tcx>( } pub(crate) fn is_literal_expr(tcx: TyCtxt<'_>, hir_id: hir::HirId) -> bool { - if let hir::Node::Expr(expr) = tcx.hir().get(hir_id) { + if let hir::Node::Expr(expr) = tcx.hir_node(hir_id) { if let hir::ExprKind::Lit(_) = &expr.kind { return true; } @@ -641,7 +641,6 @@ pub(crate) fn inherits_doc_hidden( mut def_id: LocalDefId, stop_at: Option, ) -> bool { - let hir = tcx.hir(); while let Some(id) = tcx.opt_local_parent(def_id) { if let Some(stop_at) = stop_at && id == stop_at @@ -651,7 +650,7 @@ pub(crate) fn inherits_doc_hidden( def_id = id; if tcx.is_doc_hidden(def_id.to_def_id()) { return true; - } else if let Some(node) = hir.find_by_def_id(def_id) + } else if let Some(node) = tcx.opt_hir_node_by_def_id(def_id) && matches!(node, hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. }),) { // `impl` blocks stand a bit on their own: unless they have `#[doc(hidden)]` directly diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index abc27bcdf0782..dfad1ab10dbe0 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -27,7 +27,7 @@ //! ``` use rustc_data_structures::fx::FxHashMap; -use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage}; +use rustc_errors::{DiagnosticBuilder, DiagnosticMessage}; use rustc_hir::def_id::DefId; use rustc_middle::ty::TyCtxt; pub(crate) use rustc_resolve::rustdoc::main_body_opts; @@ -234,10 +234,6 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { fn next(&mut self) -> Option { let event = self.inner.next(); - let compile_fail; - let should_panic; - let ignore; - let edition; let Some(Event::Start(Tag::CodeBlock(kind))) = event else { return event; }; @@ -253,49 +249,44 @@ impl<'a, I: Iterator>> Iterator for CodeBlocks<'_, 'a, I> { } } - let parse_result = match kind { - CodeBlockKind::Fenced(ref lang) => { - let parse_result = LangString::parse_without_check( - lang, - self.check_error_codes, - false, - self.custom_code_classes_in_docs, - ); - if !parse_result.rust { - let added_classes = parse_result.added_classes; - let lang_string = if let Some(lang) = parse_result.unknown.first() { - format!("language-{}", lang) - } else { - String::new() - }; - let whitespace = if added_classes.is_empty() { "" } else { " " }; - return Some(Event::Html( - format!( - "
\ + let LangString { added_classes, compile_fail, should_panic, ignore, edition, .. } = + match kind { + CodeBlockKind::Fenced(ref lang) => { + let parse_result = LangString::parse_without_check( + lang, + self.check_error_codes, + false, + self.custom_code_classes_in_docs, + ); + if !parse_result.rust { + let added_classes = parse_result.added_classes; + let lang_string = if let Some(lang) = parse_result.unknown.first() { + format!("language-{}", lang) + } else { + String::new() + }; + let whitespace = if added_classes.is_empty() { "" } else { " " }; + return Some(Event::Html( + format!( + "
\
\
                                      {text}\
                                  
\
", - added_classes = added_classes.join(" "), - text = Escape(&original_text), - ) - .into(), - )); + added_classes = added_classes.join(" "), + text = Escape(&original_text), + ) + .into(), + )); + } + parse_result } - parse_result - } - CodeBlockKind::Indented => Default::default(), - }; + CodeBlockKind::Indented => Default::default(), + }; - let added_classes = parse_result.added_classes; let lines = original_text.lines().filter_map(|l| map_line(l).for_html()); let text = lines.intersperse("\n".into()).collect::(); - compile_fail = parse_result.compile_fail; - should_panic = parse_result.should_panic; - ignore = parse_result.ignore; - edition = parse_result.edition; - let explicit_edition = edition.is_some(); let edition = edition.unwrap_or(self.edition); @@ -852,7 +843,9 @@ impl<'tcx> ExtraInfo<'tcx> { fn error_invalid_codeblock_attr_with_help( &self, msg: impl Into, - help: impl Into, + f: impl for<'a, 'b> FnOnce( + &'b mut DiagnosticBuilder<'a, ()>, + ) -> &'b mut DiagnosticBuilder<'a, ()>, ) { if let Some(def_id) = self.def_id.as_local() { self.tcx.struct_span_lint_hir( @@ -860,7 +853,7 @@ impl<'tcx> ExtraInfo<'tcx> { self.tcx.local_def_id_to_hir_id(def_id), self.sp, msg, - |lint| lint.help(help), + f, ); } } @@ -1293,6 +1286,21 @@ impl LangString { LangStringToken::LangToken(x) if x.starts_with("edition") => { data.edition = x[7..].parse::().ok(); } + LangStringToken::LangToken(x) + if x.starts_with("rust") && x[4..].parse::().is_ok() => + { + if let Some(extra) = extra { + extra.error_invalid_codeblock_attr_with_help( + format!("unknown attribute `{x}`"), + |lint| { + lint.help(format!( + "there is an attribute with a similar name: `edition{}`", + &x[4..], + )) + }, + ); + } + } LangStringToken::LangToken(x) if allow_error_code_check && x.starts_with('E') && x.len() == 5 => { @@ -1337,8 +1345,13 @@ impl LangString { } { if let Some(extra) = extra { extra.error_invalid_codeblock_attr_with_help( - format!("unknown attribute `{x}`. Did you mean `{flag}`?"), - help, + format!("unknown attribute `{x}`"), + |lint| { + lint.help(format!( + "there is an attribute with a similar name: `{flag}`" + )) + .help(help) + }, ); } } diff --git a/src/librustdoc/html/render/span_map.rs b/src/librustdoc/html/render/span_map.rs index 5f130f1875aae..d1ece73374dc3 100644 --- a/src/librustdoc/html/render/span_map.rs +++ b/src/librustdoc/html/render/span_map.rs @@ -94,7 +94,7 @@ impl<'tcx> SpanMapVisitor<'tcx> { /// Used to generate links on items' definition to go to their documentation page. pub(crate) fn extract_info_from_hir_id(&mut self, hir_id: HirId) { - if let Some(Node::Item(item)) = self.tcx.hir().find(hir_id) { + if let Some(Node::Item(item)) = self.tcx.opt_hir_node(hir_id) { if let Some(span) = self.tcx.def_ident_span(item.owner_id) { let cspan = clean::Span::new(span); // If the span isn't from the current crate, we ignore it. @@ -177,7 +177,7 @@ impl<'tcx> Visitor<'tcx> for SpanMapVisitor<'tcx> { if !span.overlaps(m.spans.inner_span) { // Now that we confirmed it's a file import, we want to get the span for the module // name only and not all the "mod foo;". - if let Some(Node::Item(item)) = self.tcx.hir().find(id) { + if let Some(Node::Item(item)) = self.tcx.opt_hir_node(id) { self.matches.insert( item.ident.span, LinkFromSrc::Local(clean::Span::new(m.spans.inner_span)), diff --git a/src/librustdoc/html/render/type_layout.rs b/src/librustdoc/html/render/type_layout.rs index ee581173a4a11..738ea0aee7e9d 100644 --- a/src/librustdoc/html/render/type_layout.rs +++ b/src/librustdoc/html/render/type_layout.rs @@ -79,6 +79,7 @@ pub(crate) fn document_type_layout<'a, 'cx: 'a>( TypeLayoutSize { is_unsized, is_uninhabited, size } }); - Ok(TypeLayout { variants, type_layout_size }.render_into(f).unwrap()) + TypeLayout { variants, type_layout_size }.render_into(f).unwrap(); + Ok(()) }) } diff --git a/src/librustdoc/html/static/js/search.js b/src/librustdoc/html/static/js/search.js index f2875b7f01e45..5d348d3f17635 100644 --- a/src/librustdoc/html/static/js/search.js +++ b/src/librustdoc/html/static/js/search.js @@ -2100,8 +2100,6 @@ function initSearch(rawSearchIndex) { } function innerRunQuery() { - let elem, i, nSearchWords, in_returned, row; - let queryLen = 0; for (const elem of parsedQuery.elems) { queryLen += elem.name.length; @@ -2227,8 +2225,8 @@ function initSearch(rawSearchIndex) { if (parsedQuery.foundElems === 1) { if (parsedQuery.elems.length === 1) { - elem = parsedQuery.elems[0]; - for (i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) { + const elem = parsedQuery.elems[0]; + for (let i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) { // It means we want to check for this element everywhere (in names, args and // returned). handleSingleArg( @@ -2243,10 +2241,9 @@ function initSearch(rawSearchIndex) { } } else if (parsedQuery.returned.length === 1) { // We received one returned argument to check, so looking into returned values. - elem = parsedQuery.returned[0]; - for (i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) { - row = searchIndex[i]; - in_returned = row.type && unifyFunctionTypes( + for (let i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) { + const row = searchIndex[i]; + const in_returned = row.type && unifyFunctionTypes( row.type.output, parsedQuery.returned, row.type.where_clause @@ -2264,7 +2261,7 @@ function initSearch(rawSearchIndex) { } } } else if (parsedQuery.foundElems > 0) { - for (i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) { + for (let i = 0, nSearchWords = searchWords.length; i < nSearchWords; ++i) { handleArgs(searchIndex[i], i, results_others); } } @@ -2420,7 +2417,6 @@ function initSearch(rawSearchIndex) { const extraClass = display ? " active" : ""; const output = document.createElement("div"); - let length = 0; if (array.length > 0) { output.className = "search-results " + extraClass; @@ -2430,8 +2426,6 @@ function initSearch(rawSearchIndex) { const longType = longItemTypes[item.ty]; const typeName = longType.length !== 0 ? `${longType}` : "?"; - length += 1; - const link = document.createElement("a"); link.className = "result-" + type; link.href = item.href; @@ -2479,7 +2473,7 @@ ${item.displayPath}${name}\ "href=\"https://docs.rs\">Docs.rs for documentation of crates released on" + " crates.io."; } - return [output, length]; + return [output, array.length]; } function makeTabHeader(tabNb, text, nbElems) { diff --git a/src/librustdoc/passes/check_doc_test_visibility.rs b/src/librustdoc/passes/check_doc_test_visibility.rs index 21a31b9df9308..8d5b17f43cdcd 100644 --- a/src/librustdoc/passes/check_doc_test_visibility.rs +++ b/src/librustdoc/passes/check_doc_test_visibility.rs @@ -80,7 +80,7 @@ pub(crate) fn should_have_doc_example(cx: &DocContext<'_>, item: &clean::Item) - // check if parent is trait impl if let Some(parent_def_id) = cx.tcx.opt_local_parent(def_id) - && let Some(parent_node) = cx.tcx.hir().find_by_def_id(parent_def_id) + && let Some(parent_node) = cx.tcx.opt_hir_node_by_def_id(parent_def_id) && matches!( parent_node, hir::Node::Item(hir::Item { diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index bef151745d8f0..bbc7e5b48d1ef 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -275,7 +275,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { }; let is_private = !self.cx.cache.effective_visibilities.is_directly_public(tcx, ori_res_did); - let item = tcx.hir().get_by_def_id(res_did); + let item = tcx.hir_node_by_def_id(res_did); if !please_inline { let inherits_hidden = !document_hidden && inherits_doc_hidden(tcx, res_did, None); diff --git a/src/tools/clippy/clippy_lints/src/absolute_paths.rs b/src/tools/clippy/clippy_lints/src/absolute_paths.rs index 83d15c0c42520..3822b83b4bc64 100644 --- a/src/tools/clippy/clippy_lints/src/absolute_paths.rs +++ b/src/tools/clippy/clippy_lints/src/absolute_paths.rs @@ -62,7 +62,7 @@ impl LateLintPass<'_> for AbsolutePaths { } = self; if !path.span.from_expansion() - && let Some(node) = cx.tcx.hir().find(hir_id) + && let Some(node) = cx.tcx.opt_hir_node(hir_id) && !matches!(node, Node::Item(item) if matches!(item.kind, ItemKind::Use(_, _))) && let [first, rest @ ..] = path.segments // Handle `::std` diff --git a/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs b/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs index 2a9f7fec1722f..91bad8256ecb1 100644 --- a/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs +++ b/src/tools/clippy/clippy_lints/src/casts/cast_slice_different_sizes.rs @@ -69,7 +69,7 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>, msrv: &Msrv fn is_child_of_cast(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { let map = cx.tcx.hir(); if let Some(parent_id) = map.opt_parent_id(expr.hir_id) - && let Some(parent) = map.find(parent_id) + && let Some(parent) = cx.tcx.opt_hir_node(parent_id) { let expr = match parent { Node::Block(block) => { diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 854324f845b43..aaef163ad554b 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -1090,7 +1090,7 @@ fn report<'tcx>( if parent_id == data.first_expr.hir_id { return; } - (cx.tcx.hir().get(parent_id).expect_expr().span, true) + (cx.tcx.hir_node(parent_id).expect_expr().span, true) } else { (expr.span, false) }; diff --git a/src/tools/clippy/clippy_lints/src/derivable_impls.rs b/src/tools/clippy/clippy_lints/src/derivable_impls.rs index 53ef6d7e387e4..6b0423200d765 100644 --- a/src/tools/clippy/clippy_lints/src/derivable_impls.rs +++ b/src/tools/clippy/clippy_lints/src/derivable_impls.rs @@ -195,7 +195,7 @@ impl<'tcx> LateLintPass<'tcx> for DerivableImpls { && let Some(def_id) = trait_ref.trait_def_id() && cx.tcx.is_diagnostic_item(sym::Default, def_id) && let impl_item_hir = child.id.hir_id() - && let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir) + && let Some(Node::ImplItem(impl_item)) = cx.tcx.opt_hir_node(impl_item_hir) && let ImplItemKind::Fn(_, b) = &impl_item.kind && let Body { value: func_expr, .. } = cx.tcx.hir().body(*b) && let &Adt(adt_def, args) = cx.tcx.type_of(item.owner_id).instantiate_identity().kind() diff --git a/src/tools/clippy/clippy_lints/src/empty_drop.rs b/src/tools/clippy/clippy_lints/src/empty_drop.rs index e97030cc8b631..1d2b907b94821 100644 --- a/src/tools/clippy/clippy_lints/src/empty_drop.rs +++ b/src/tools/clippy/clippy_lints/src/empty_drop.rs @@ -42,7 +42,7 @@ impl LateLintPass<'_> for EmptyDrop { }) = item.kind && trait_ref.trait_def_id() == cx.tcx.lang_items().drop_trait() && let impl_item_hir = child.id.hir_id() - && let Some(Node::ImplItem(impl_item)) = cx.tcx.hir().find(impl_item_hir) + && let Some(Node::ImplItem(impl_item)) = cx.tcx.opt_hir_node(impl_item_hir) && let ImplItemKind::Fn(_, b) = &impl_item.kind && let Body { value: func_expr, .. } = cx.tcx.hir().body(*b) && let func_expr = peel_blocks(func_expr) diff --git a/src/tools/clippy/clippy_lints/src/escape.rs b/src/tools/clippy/clippy_lints/src/escape.rs index 3452f98c5aad9..b7776263060be 100644 --- a/src/tools/clippy/clippy_lints/src/escape.rs +++ b/src/tools/clippy/clippy_lints/src/escape.rs @@ -5,7 +5,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::mir::FakeReadCause; use rustc_middle::ty::layout::LayoutOf; -use rustc_middle::ty::{self, TraitRef, Ty}; +use rustc_middle::ty::{self, TraitRef, Ty, TyCtxt}; use rustc_session::impl_lint_pass; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::kw; @@ -76,7 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { .hir() .get_parent_item(cx.tcx.local_def_id_to_hir_id(fn_def_id)) .def_id; - let parent_node = cx.tcx.hir().find_by_def_id(parent_id); + let parent_node = cx.tcx.opt_hir_node_by_def_id(parent_id); let mut trait_self_ty = None; if let Some(Node::Item(item)) = parent_node { @@ -122,8 +122,8 @@ impl<'tcx> LateLintPass<'tcx> for BoxedLocal { } // TODO: Replace with Map::is_argument(..) when it's fixed -fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool { - match map.find(id) { +fn is_argument(tcx: TyCtxt<'_>, id: HirId) -> bool { + match tcx.opt_hir_node(id) { Some(Node::Pat(Pat { kind: PatKind::Binding(..), .. @@ -131,7 +131,7 @@ fn is_argument(map: rustc_middle::hir::map::Map<'_>, id: HirId) -> bool { _ => return false, } - matches!(map.find_parent(id), Some(Node::Param(_))) + matches!(tcx.hir().find_parent(id), Some(Node::Param(_))) } impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> { @@ -154,7 +154,7 @@ impl<'a, 'tcx> Delegate<'tcx> for EscapeDelegate<'a, 'tcx> { fn mutate(&mut self, cmt: &PlaceWithHirId<'tcx>, _: HirId) { if cmt.place.projections.is_empty() { let map = &self.cx.tcx.hir(); - if is_argument(*map, cmt.hir_id) { + if is_argument(self.cx.tcx, cmt.hir_id) { // Skip closure arguments let parent_id = map.parent_id(cmt.hir_id); if let Some(Node::Expr(..)) = map.find_parent(parent_id) { diff --git a/src/tools/clippy/clippy_lints/src/exit.rs b/src/tools/clippy/clippy_lints/src/exit.rs index a974c10bc7dc9..6603512c73cdf 100644 --- a/src/tools/clippy/clippy_lints/src/exit.rs +++ b/src/tools/clippy/clippy_lints/src/exit.rs @@ -46,7 +46,7 @@ impl<'tcx> LateLintPass<'tcx> for Exit { && let Some(def_id) = cx.qpath_res(path, path_expr.hir_id).opt_def_id() && cx.tcx.is_diagnostic_item(sym::process_exit, def_id) && let parent = cx.tcx.hir().get_parent_item(e.hir_id).def_id - && let Some(Node::Item(Item{kind: ItemKind::Fn(..), ..})) = cx.tcx.hir().find_by_def_id(parent) + && let Some(Node::Item(Item{kind: ItemKind::Fn(..), ..})) = cx.tcx.opt_hir_node_by_def_id(parent) // If the next item up is a function we check if it is an entry point // and only then emit a linter warning && !is_entrypoint_fn(cx, parent.to_def_id()) diff --git a/src/tools/clippy/clippy_lints/src/explicit_write.rs b/src/tools/clippy/clippy_lints/src/explicit_write.rs index 4e2e1d1724a58..f1366c434f4fb 100644 --- a/src/tools/clippy/clippy_lints/src/explicit_write.rs +++ b/src/tools/clippy/clippy_lints/src/explicit_write.rs @@ -111,7 +111,7 @@ fn look_in_block<'tcx, 'hir>(cx: &LateContext<'tcx>, kind: &'tcx ExprKind<'hir>) // Find id of the local that expr_end_of_block resolves to && let ExprKind::Path(QPath::Resolved(None, expr_path)) = expr_end_of_block.kind && let Res::Local(expr_res) = expr_path.res - && let Some(Node::Pat(res_pat)) = cx.tcx.hir().find(expr_res) + && let Some(Node::Pat(res_pat)) = cx.tcx.opt_hir_node(expr_res) // Find id of the local we found in the block && let PatKind::Binding(BindingAnnotation::NONE, local_hir_id, _ident, None) = local.pat.kind diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index 5e90fcd72ebea..f1200c2edc134 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -92,7 +92,7 @@ fn check_result_large_err<'tcx>(cx: &LateContext<'tcx>, err_ty: Ty<'tcx>, hir_ty .expect("already checked this is adt") .did() .as_local() - && let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_def_id(local_def_id) + && let Some(hir::Node::Item(item)) = cx.tcx.opt_hir_node_by_def_id(local_def_id) && let hir::ItemKind::Enum(ref def, _) = item.kind { let variants_size = AdtVariantInfo::new(cx, *adt, subst); diff --git a/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs b/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs index b6f9d8b81f821..5417c13d07967 100644 --- a/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs +++ b/src/tools/clippy/clippy_lints/src/index_refutable_slice.rs @@ -248,7 +248,7 @@ impl<'a, 'tcx> Visitor<'tcx> for SliceIndexLintingVisitor<'a, 'tcx> { // Checking for slice indexing && let parent_id = map.parent_id(expr.hir_id) - && let Some(hir::Node::Expr(parent_expr)) = map.find(parent_id) + && let Some(hir::Node::Expr(parent_expr)) = cx.tcx.opt_hir_node(parent_id) && let hir::ExprKind::Index(_, index_expr, _) = parent_expr.kind && let Some(Constant::Int(index_value)) = constant(cx, cx.typeck_results(), index_expr) && let Ok(index_value) = index_value.try_into() @@ -256,7 +256,7 @@ impl<'a, 'tcx> Visitor<'tcx> for SliceIndexLintingVisitor<'a, 'tcx> { // Make sure that this slice index is read only && let maybe_addrof_id = map.parent_id(parent_id) - && let Some(hir::Node::Expr(maybe_addrof_expr)) = map.find(maybe_addrof_id) + && let Some(hir::Node::Expr(maybe_addrof_expr)) = cx.tcx.opt_hir_node(maybe_addrof_id) && let hir::ExprKind::AddrOf(_kind, hir::Mutability::Not, _inner_expr) = maybe_addrof_expr.kind { use_info.index_use.push((index_value, map.span(parent_expr.hir_id))); diff --git a/src/tools/clippy/clippy_lints/src/inherent_impl.rs b/src/tools/clippy/clippy_lints/src/inherent_impl.rs index 5c926133c427b..e4781752e757b 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_impl.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_impl.rs @@ -122,7 +122,7 @@ fn get_impl_span(cx: &LateContext<'_>, id: LocalDefId) -> Option { kind: ItemKind::Impl(impl_item), span, .. - }) = cx.tcx.hir().get(id) + }) = cx.tcx.hir_node(id) { (!span.from_expansion() && impl_item.generics.params.is_empty() diff --git a/src/tools/clippy/clippy_lints/src/len_zero.rs b/src/tools/clippy/clippy_lints/src/len_zero.rs index e121da776b21e..83af551fcd3ca 100644 --- a/src/tools/clippy/clippy_lints/src/len_zero.rs +++ b/src/tools/clippy/clippy_lints/src/len_zero.rs @@ -147,7 +147,7 @@ impl<'tcx> LateLintPass<'tcx> for LenZero { && let Some(output) = parse_len_output(cx, cx.tcx.fn_sig(item.owner_id).instantiate_identity().skip_binder()) { - let (name, kind) = match cx.tcx.hir().find(ty_hir_id) { + let (name, kind) = match cx.tcx.opt_hir_node(ty_hir_id) { Some(Node::ForeignItem(x)) => (x.ident.name, "extern type"), Some(Node::Item(x)) => match x.kind { ItemKind::Struct(..) => (x.ident.name, "struct"), diff --git a/src/tools/clippy/clippy_lints/src/lifetimes.rs b/src/tools/clippy/clippy_lints/src/lifetimes.rs index 17ca48683b3c1..ffef84d1fadec 100644 --- a/src/tools/clippy/clippy_lints/src/lifetimes.rs +++ b/src/tools/clippy/clippy_lints/src/lifetimes.rs @@ -195,7 +195,7 @@ fn check_fn_inner<'tcx>( .iter() // In principle, the result of the call to `Node::ident` could be `unwrap`ped, as `DefId` should refer to a // `Node::GenericParam`. - .filter_map(|&def_id| cx.tcx.hir().get_by_def_id(def_id).ident()) + .filter_map(|&def_id| cx.tcx.hir_node_by_def_id(def_id).ident()) .map(|ident| ident.to_string()) .collect::>() .join(", "); diff --git a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs index 227096251a550..c4e60e98ad466 100644 --- a/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs +++ b/src/tools/clippy/clippy_lints/src/loops/mut_range_bound.rs @@ -40,7 +40,7 @@ fn mut_warn_with_span(cx: &LateContext<'_>, span: Option) { fn check_for_mutability(cx: &LateContext<'_>, bound: &Expr<'_>) -> Option { if let Some(hir_id) = path_to_local(bound) - && let Node::Pat(pat) = cx.tcx.hir().get(hir_id) + && let Node::Pat(pat) = cx.tcx.hir_node(hir_id) && let PatKind::Binding(BindingAnnotation::MUT, ..) = pat.kind { return Some(hir_id); diff --git a/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs b/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs index f4eaf649f77bf..c245eaf1ab44d 100644 --- a/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs +++ b/src/tools/clippy/clippy_lints/src/loops/same_item_push.rs @@ -58,12 +58,12 @@ pub(super) fn check<'tcx>( match cx.qpath_res(qpath, pushed_item.hir_id) { // immutable bindings that are initialized with literal or constant Res::Local(hir_id) => { - let node = cx.tcx.hir().get(hir_id); + let node = cx.tcx.hir_node(hir_id); if let Node::Pat(pat) = node && let PatKind::Binding(bind_ann, ..) = pat.kind && !matches!(bind_ann, BindingAnnotation(_, Mutability::Mut)) && let parent_node = cx.tcx.hir().parent_id(hir_id) - && let Some(Node::Local(parent_let_expr)) = cx.tcx.hir().find(parent_node) + && let Some(Node::Local(parent_let_expr)) = cx.tcx.opt_hir_node(parent_node) && let Some(init) = parent_let_expr.init { match init.kind { diff --git a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs index ee053ffe4ecad..eaaaea0be9f89 100644 --- a/src/tools/clippy/clippy_lints/src/manual_async_fn.rs +++ b/src/tools/clippy/clippy_lints/src/manual_async_fn.rs @@ -58,7 +58,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualAsyncFn { && block.stmts.is_empty() && let Some(closure_body) = desugared_async_block(cx, block) && let Node::Item(Item {vis_span, ..}) | Node::ImplItem(ImplItem {vis_span, ..}) = - cx.tcx.hir().get_by_def_id(def_id) + cx.tcx.hir_node_by_def_id(def_id) { let header_span = span.with_hi(ret_ty.span.hi()); diff --git a/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs b/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs index e006df7d66664..71a83a68db933 100644 --- a/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs +++ b/src/tools/clippy/clippy_lints/src/manual_rem_euclid.rs @@ -76,7 +76,7 @@ impl<'tcx> LateLintPass<'tcx> for ManualRemEuclid { // Also ensures the const is nonzero since zero can't be a divisor && const1 == const2 && const2 == const3 && let Some(hir_id) = path_to_local(expr3) - && let Some(Node::Pat(_)) = cx.tcx.hir().find(hir_id) + && let Some(Node::Pat(_)) = cx.tcx.opt_hir_node(hir_id) { // Apply only to params or locals with annotated types match cx.tcx.hir().find_parent(hir_id) { diff --git a/src/tools/clippy/clippy_lints/src/methods/filter_next.rs b/src/tools/clippy/clippy_lints/src/methods/filter_next.rs index ac7bc9bcca47f..9251130a30549 100644 --- a/src/tools/clippy/clippy_lints/src/methods/filter_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/filter_next.rs @@ -44,7 +44,7 @@ pub(super) fn check<'tcx>( // add note if not multi-line span_lint_and_then(cx, FILTER_NEXT, expr.span, msg, |diag| { let (applicability, pat) = if let Some(id) = path_to_local(recv) - && let Some(hir::Node::Pat(pat)) = cx.tcx.hir().find(id) + && let Some(hir::Node::Pat(pat)) = cx.tcx.opt_hir_node(id) && let hir::PatKind::Binding(BindingAnnotation(_, Mutability::Not), _, ident, _) = pat.kind { (Applicability::Unspecified, Some((pat.span, ident))) diff --git a/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs b/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs index fbe20dfe54ec8..d1215290dadab 100644 --- a/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs +++ b/src/tools/clippy/clippy_lints/src/methods/iter_skip_next.rs @@ -20,7 +20,7 @@ pub(super) fn check(cx: &LateContext<'_>, expr: &hir::Expr<'_>, recv: &hir::Expr "called `skip(..).next()` on an iterator", |diag| { if let Some(id) = path_to_local(recv) - && let Node::Pat(pat) = cx.tcx.hir().get(id) + && let Node::Pat(pat) = cx.tcx.hir_node(id) && let PatKind::Binding(ann, _, _, _) = pat.kind && ann != BindingAnnotation::MUT { diff --git a/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs b/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs index 826c3de1db5de..63e64a5b35d05 100644 --- a/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs +++ b/src/tools/clippy/clippy_lints/src/methods/option_map_unwrap_or.rs @@ -135,7 +135,7 @@ impl<'a, 'tcx> Visitor<'tcx> for UnwrapVisitor<'a, 'tcx> { fn visit_path(&mut self, path: &Path<'tcx>, _: HirId) { if let Res::Local(local_id) = path.res - && let Some(Node::Pat(pat)) = self.cx.tcx.hir().find(local_id) + && let Some(Node::Pat(pat)) = self.cx.tcx.opt_hir_node(local_id) && let PatKind::Binding(_, local_id, ..) = pat.kind { self.identifiers.insert(local_id); @@ -166,7 +166,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ReferenceVisitor<'a, 'tcx> { && let ExprKind::Path(ref path) = expr.kind && let QPath::Resolved(_, path) = path && let Res::Local(local_id) = path.res - && let Some(Node::Pat(pat)) = self.cx.tcx.hir().find(local_id) + && let Some(Node::Pat(pat)) = self.cx.tcx.opt_hir_node(local_id) && let PatKind::Binding(_, local_id, ..) = pat.kind && self.identifiers.contains(&local_id) { diff --git a/src/tools/clippy/clippy_lints/src/min_ident_chars.rs b/src/tools/clippy/clippy_lints/src/min_ident_chars.rs index f5b749c7f800a..34b8e0dbe6a7e 100644 --- a/src/tools/clippy/clippy_lints/src/min_ident_chars.rs +++ b/src/tools/clippy/clippy_lints/src/min_ident_chars.rs @@ -91,7 +91,7 @@ impl Visitor<'_> for IdentVisitor<'_, '_> { let node = if hir_id.local_id == ItemLocalId::from_u32(0) { // In this case, we can just use `find`, `Owner`'s `node` field is private anyway so we can't // reimplement it even if we wanted to - cx.tcx.hir().find(hir_id) + cx.tcx.opt_hir_node(hir_id) } else { let Some(owner) = cx.tcx.hir_owner_nodes(hir_id.owner).as_owner() else { return; diff --git a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs index 5f736898159db..acaa6be30092b 100644 --- a/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs +++ b/src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs @@ -137,7 +137,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingConstForFn { { let parent = cx.tcx.hir().get_parent_item(hir_id).def_id; if parent != CRATE_DEF_ID { - if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent) { + if let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(parent) { if let hir::ItemKind::Trait(..) = &item.kind { return; } diff --git a/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs b/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs index 8be45b8c2f352..88b331ddefdb7 100644 --- a/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs +++ b/src/tools/clippy/clippy_lints/src/missing_fields_in_debug.rs @@ -220,7 +220,7 @@ impl<'tcx> LateLintPass<'tcx> for MissingFieldsInDebug { && let self_ty = cx.tcx.type_of(self_path_did).skip_binder().peel_refs() && let Some(self_adt) = self_ty.ty_adt_def() && let Some(self_def_id) = self_adt.did().as_local() - && let Some(Node::Item(self_item)) = cx.tcx.hir().find_by_def_id(self_def_id) + && let Some(Node::Item(self_item)) = cx.tcx.opt_hir_node_by_def_id(self_def_id) // NB: can't call cx.typeck_results() as we are not in a body && let typeck_results = cx.tcx.typeck_body(*body_id) && should_lint(cx, typeck_results, block) diff --git a/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs b/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs index cd180754113fe..34119c6911c57 100644 --- a/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs +++ b/src/tools/clippy/clippy_lints/src/mixed_read_write_in_expression.rs @@ -213,7 +213,7 @@ fn check_for_unsequenced_reads(vis: &mut ReadVisitor<'_, '_>) { if parent_id == cur_id { break; } - let Some(parent_node) = map.find(parent_id) else { break }; + let Some(parent_node) = vis.cx.tcx.opt_hir_node(parent_id) else { break }; let stop_early = match parent_node { Node::Expr(expr) => check_expr(vis, expr), diff --git a/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs b/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs index 13b736cd9ad8a..64ef709e2fa2d 100644 --- a/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs +++ b/src/tools/clippy/clippy_lints/src/needless_pass_by_ref_mut.rs @@ -113,8 +113,9 @@ fn check_closures<'tcx>( } ctx.prev_bind = None; ctx.prev_move_to_closure.clear(); - if let Some(body) = hir - .find_by_def_id(closure) + if let Some(body) = cx + .tcx + .opt_hir_node_by_def_id(closure) .and_then(associated_body) .map(|(_, body_id)| hir.body(body_id)) { @@ -412,7 +413,7 @@ impl<'tcx> euv::Delegate<'tcx> for MutablyUsedVariablesCtxt<'tcx> { ], ), .. - }) = self.tcx.hir().get(cmt.hir_id) + }) = self.tcx.hir_node(cmt.hir_id) { self.async_closures.insert(*def_id); } @@ -521,7 +522,7 @@ impl<'tcx> Visitor<'tcx> for FnNeedsMutVisitor<'_, 'tcx> { let Self { cx, used_fn_def_ids } = self; // #11182; do not lint if mutability is required elsewhere - if let Node::Expr(expr) = cx.tcx.hir().get(hir_id) + if let Node::Expr(expr) = cx.tcx.hir_node(hir_id) && let Some(parent) = get_parent_node(cx.tcx, expr.hir_id) && let ty::FnDef(def_id, _) = cx .tcx diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index 4f8922aea1787..4013cb34561ae 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -454,7 +454,7 @@ impl<'tcx> LateLintPass<'tcx> for NonCopyConst { if parent_id == cur_expr.hir_id { break; } - if let Some(Node::Expr(parent_expr)) = cx.tcx.hir().find(parent_id) { + if let Some(Node::Expr(parent_expr)) = cx.tcx.opt_hir_node(parent_id) { match &parent_expr.kind { ExprKind::AddrOf(..) => { // `&e` => `e` must be referenced. diff --git a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs index 352540d70b52c..793a3a9545cd9 100644 --- a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs +++ b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs @@ -94,7 +94,6 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { { let mut non_send_fields = Vec::new(); - let hir_map = cx.tcx.hir(); for variant in adt_def.variants() { for field in &variant.fields { if let Some(field_hir_id) = field @@ -104,7 +103,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { && !is_lint_allowed(cx, NON_SEND_FIELDS_IN_SEND_TY, field_hir_id) && let field_ty = field.ty(cx.tcx, impl_trait_args) && !ty_allowed_in_send(cx, field_ty, send_trait) - && let Node::Field(field_def) = hir_map.get(field_hir_id) + && let Node::Field(field_def) = cx.tcx.hir_node(field_hir_id) { non_send_fields.push(NonSendField { def: field_def, diff --git a/src/tools/clippy/clippy_lints/src/redundant_locals.rs b/src/tools/clippy/clippy_lints/src/redundant_locals.rs index 8c374d7d6db75..2c511ee0bc029 100644 --- a/src/tools/clippy/clippy_lints/src/redundant_locals.rs +++ b/src/tools/clippy/clippy_lints/src/redundant_locals.rs @@ -59,7 +59,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantLocals { && last_segment.ident == ident // resolve the path to its defining binding pattern && let Res::Local(binding_id) = cx.qpath_res(&qpath, expr.hir_id) - && let Node::Pat(binding_pat) = cx.tcx.hir().get(binding_id) + && let Node::Pat(binding_pat) = cx.tcx.hir_node(binding_id) // the previous binding has the same mutability && find_binding(binding_pat, ident).is_some_and(|bind| bind.1 == mutability) // the local does not change the effect of assignments to the binding. see #11290 diff --git a/src/tools/clippy/clippy_lints/src/same_name_method.rs b/src/tools/clippy/clippy_lints/src/same_name_method.rs index 74193e0199f3f..1316343e0c2fb 100644 --- a/src/tools/clippy/clippy_lints/src/same_name_method.rs +++ b/src/tools/clippy/clippy_lints/src/same_name_method.rs @@ -77,7 +77,7 @@ impl<'tcx> LateLintPass<'tcx> for SameNameMethod { Some(trait_ref) => { let mut methods_in_trait: BTreeSet = if let Some(Node::TraitRef(TraitRef { path, .. - })) = cx.tcx.hir().find(trait_ref.hir_ref_id) + })) = cx.tcx.opt_hir_node(trait_ref.hir_ref_id) && let Res::Def(DefKind::Trait, did) = path.res { // FIXME: if diff --git a/src/tools/clippy/clippy_lints/src/self_named_constructors.rs b/src/tools/clippy/clippy_lints/src/self_named_constructors.rs index 935dd4a3630f5..98f3235af10a0 100644 --- a/src/tools/clippy/clippy_lints/src/self_named_constructors.rs +++ b/src/tools/clippy/clippy_lints/src/self_named_constructors.rs @@ -73,7 +73,7 @@ impl<'tcx> LateLintPass<'tcx> for SelfNamedConstructors { if let Some(self_def) = self_ty.ty_adt_def() && let Some(self_local_did) = self_def.did().as_local() && let self_id = cx.tcx.local_def_id_to_hir_id(self_local_did) - && let Some(Node::Item(x)) = cx.tcx.hir().find(self_id) + && let Some(Node::Item(x)) = cx.tcx.opt_hir_node(self_id) && let type_name = x.ident.name.as_str().to_lowercase() && (impl_item.ident.name.as_str() == type_name || impl_item.ident.name.as_str().replace('_', "") == type_name) diff --git a/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs b/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs index 268c0c1b2dfc4..8eab3f5874e18 100644 --- a/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs +++ b/src/tools/clippy/clippy_lints/src/suspicious_trait_impl.rs @@ -64,7 +64,7 @@ impl<'tcx> LateLintPass<'tcx> for SuspiciousImpl { // Check for more than one binary operation in the implemented function // Linting when multiple operations are involved can result in false positives && let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id).def_id - && let hir::Node::ImplItem(impl_item) = cx.tcx.hir().get_by_def_id(parent_fn) + && let hir::Node::ImplItem(impl_item) = cx.tcx.hir_node_by_def_id(parent_fn) && let hir::ImplItemKind::Fn(_, body_id) = impl_item.kind && let body = cx.tcx.hir().body(body_id) && let parent_fn = cx.tcx.hir().get_parent_item(expr.hir_id).def_id diff --git a/src/tools/clippy/clippy_lints/src/types/mod.rs b/src/tools/clippy/clippy_lints/src/types/mod.rs index 8e890b4df8894..81efec65343d1 100644 --- a/src/tools/clippy/clippy_lints/src/types/mod.rs +++ b/src/tools/clippy/clippy_lints/src/types/mod.rs @@ -321,7 +321,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { _: Span, def_id: LocalDefId, ) { - let is_in_trait_impl = if let Some(hir::Node::Item(item)) = cx.tcx.hir().find_by_def_id( + let is_in_trait_impl = if let Some(hir::Node::Item(item)) = cx.tcx.opt_hir_node_by_def_id( cx.tcx .hir() .get_parent_item(cx.tcx.local_def_id_to_hir_id(def_id)) @@ -368,8 +368,7 @@ impl<'tcx> LateLintPass<'tcx> for Types { ImplItemKind::Const(ty, _) => { let is_in_trait_impl = if let Some(hir::Node::Item(item)) = cx .tcx - .hir() - .find_by_def_id(cx.tcx.hir().get_parent_item(item.hir_id()).def_id) + .opt_hir_node_by_def_id(cx.tcx.hir().get_parent_item(item.hir_id()).def_id) { matches!(item.kind, ItemKind::Impl(hir::Impl { of_trait: Some(_), .. })) } else { diff --git a/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs b/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs index ed4d87ef8f8ae..333ea0c82df65 100644 --- a/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs +++ b/src/tools/clippy/clippy_lints/src/unnecessary_struct_initialization.rs @@ -82,7 +82,7 @@ impl LateLintPass<'_> for UnnecessaryStruct { fn is_mutable(cx: &LateContext<'_>, expr: &Expr<'_>) -> bool { if let Some(hir_id) = path_to_local(expr) - && let Node::Pat(pat) = cx.tcx.hir().get(hir_id) + && let Node::Pat(pat) = cx.tcx.hir_node(hir_id) { matches!(pat.kind, PatKind::Binding(BindingAnnotation::MUT, ..)) } else { diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index 2ab24f70ae0b4..2e0a0f6cb3e45 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -281,7 +281,7 @@ impl<'tcx> LateLintPass<'tcx> for UselessConversion { } if let Some(id) = path_to_local(recv) - && let Node::Pat(pat) = cx.tcx.hir().get(id) + && let Node::Pat(pat) = cx.tcx.hir_node(id) && let PatKind::Binding(ann, ..) = pat.kind && ann != BindingAnnotation::MUT { diff --git a/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs b/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs index 70ca1b206b439..31a81a5249709 100644 --- a/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs +++ b/src/tools/clippy/clippy_lints/src/utils/internal_lints/unnecessary_def_path.rs @@ -218,7 +218,7 @@ fn path_to_matched_type(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option match cx.qpath_res(qpath, expr.hir_id) { Res::Local(hir_id) => { let parent_id = cx.tcx.hir().parent_id(hir_id); - if let Some(Node::Local(Local { init: Some(init), .. })) = cx.tcx.hir().find(parent_id) { + if let Some(Node::Local(Local { init: Some(init), .. })) = cx.tcx.hir_node(parent_id) { path_to_matched_type(cx, init) } else { None diff --git a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs index fba3808261acf..b36c4ef91dc61 100644 --- a/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs +++ b/src/tools/clippy/clippy_lints/src/zero_sized_map_values.rs @@ -74,7 +74,7 @@ impl LateLintPass<'_> for ZeroSizedMapValues { fn in_trait_impl(cx: &LateContext<'_>, hir_id: HirId) -> bool { let parent_id = cx.tcx.hir().get_parent_item(hir_id); let second_parent_id = cx.tcx.hir().get_parent_item(parent_id.into()).def_id; - if let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(second_parent_id) { + if let Some(Node::Item(item)) = cx.tcx.opt_hir_node_by_def_id(second_parent_id) { if let ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) = item.kind { return true; } diff --git a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs index 3bac0626f8858..3f68b6d75b591 100644 --- a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs +++ b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs @@ -269,7 +269,7 @@ fn fn_kind_pat(tcx: TyCtxt<'_>, kind: &FnKind<'_>, body: &Body<'_>, hir_id: HirI FnKind::Method(.., sig) => (fn_header_search_pat(sig.header), Pat::Str("")), FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, body.value).1), }; - let start_pat = match tcx.hir().get(hir_id) { + let start_pat = match tcx.hir_node(hir_id) { Node::Item(Item { vis_span, .. }) | Node::ImplItem(ImplItem { vis_span, .. }) => { if vis_span.is_empty() { start_pat diff --git a/src/tools/clippy/clippy_utils/src/consts.rs b/src/tools/clippy/clippy_utils/src/consts.rs index 35a8a7920a9dd..727f93c832742 100644 --- a/src/tools/clippy/clippy_utils/src/consts.rs +++ b/src/tools/clippy/clippy_utils/src/consts.rs @@ -531,7 +531,7 @@ impl<'a, 'tcx> ConstEvalLateContext<'a, 'tcx> { kind: ExprKind::Lit(_), span, .. - }) = self.lcx.tcx.hir().get(body_id.hir_id) + }) = self.lcx.tcx.hir_node(body_id.hir_id) && is_direct_expn_of(*span, "cfg").is_some() { return None; diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index f3b63f1cdcf01..70a3c6f82c1cd 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -176,10 +176,10 @@ pub fn expr_or_init<'a, 'b, 'tcx: 'b>(cx: &LateContext<'tcx>, mut expr: &'a Expr /// canonical binding `HirId`. pub fn find_binding_init<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Option<&'tcx Expr<'tcx>> { let hir = cx.tcx.hir(); - if let Some(Node::Pat(pat)) = hir.find(hir_id) + if let Some(Node::Pat(pat)) = cx.tcx.opt_hir_node(hir_id) && matches!(pat.kind, PatKind::Binding(BindingAnnotation::NONE, ..)) && let parent = hir.parent_id(hir_id) - && let Some(Node::Local(local)) = hir.find(parent) + && let Some(Node::Local(local)) = cx.tcx.opt_hir_node(parent) { return local.init; } @@ -563,7 +563,7 @@ fn local_item_children_by_name(tcx: TyCtxt<'_>, local_id: LocalDefId, name: Symb let hir = tcx.hir(); let root_mod; - let item_kind = match hir.find_by_def_id(local_id) { + let item_kind = match tcx.opt_hir_node_by_def_id(local_id) { Some(Node::Crate(r#mod)) => { root_mod = ItemKind::Mod(r#mod); &root_mod @@ -712,7 +712,7 @@ pub fn trait_ref_of_method<'tcx>(cx: &LateContext<'tcx>, def_id: LocalDefId) -> let hir_id = cx.tcx.local_def_id_to_hir_id(def_id); let parent_impl = cx.tcx.hir().get_parent_item(hir_id); if parent_impl != hir::CRATE_OWNER_ID - && let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent_impl.def_id) + && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(parent_impl.def_id) && let hir::ItemKind::Impl(impl_) = &item.kind { return impl_.of_trait.as_ref(); @@ -1242,7 +1242,7 @@ pub fn is_in_panic_handler(cx: &LateContext<'_>, e: &Expr<'_>) -> bool { /// Gets the name of the item the expression is in, if available. pub fn get_item_name(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { let parent_id = cx.tcx.hir().get_parent_item(expr.hir_id).def_id; - match cx.tcx.hir().find_by_def_id(parent_id) { + match cx.tcx.opt_hir_node_by_def_id(parent_id) { Some( Node::Item(Item { ident, .. }) | Node::TraitItem(TraitItem { ident, .. }) @@ -1319,7 +1319,7 @@ pub fn get_enclosing_block<'tcx>(cx: &LateContext<'tcx>, hir_id: HirId) -> Optio let map = &cx.tcx.hir(); let enclosing_node = map .get_enclosing_scope(hir_id) - .and_then(|enclosing_id| map.find(enclosing_id)); + .and_then(|enclosing_id| cx.tcx.opt_hir_node(enclosing_id)); enclosing_node.and_then(|node| match node { Node::Block(block) => Some(block), Node::Item(&Item { @@ -2691,7 +2691,7 @@ impl<'tcx> ExprUseNode<'tcx> { if let Some(Node::Expr(Expr { kind: ExprKind::Closure(c), .. - })) = cx.tcx.hir().find(hir_id) + })) = cx.tcx.opt_hir_node(hir_id) { match c.fn_decl.output { FnRetTy::DefaultReturn(_) => None, @@ -2757,7 +2757,7 @@ pub fn expr_use_ctxt<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) -> Optio walk_to_expr_usage(cx, e, &mut |parent, child_id| { // LocalTableInContext returns the wrong lifetime, so go use `expr_adjustments` instead. if adjustments.is_empty() - && let Node::Expr(e) = cx.tcx.hir().get(child_id) + && let Node::Expr(e) = cx.tcx.hir_node(child_id) { adjustments = cx.typeck_results().expr_adjustments(e); } diff --git a/src/tools/miri/src/bin/miri.rs b/src/tools/miri/src/bin/miri.rs index 504b6bd140ec4..8390309889de1 100644 --- a/src/tools/miri/src/bin/miri.rs +++ b/src/tools/miri/src/bin/miri.rs @@ -144,7 +144,7 @@ impl rustc_driver::Callbacks for MiriBeRustCompilerCalls { // Otherwise it may cause unexpected behaviours and ICEs // (https://github.com/rust-lang/rust/issues/86261). let is_reachable_non_generic = matches!( - tcx.hir().get(tcx.local_def_id_to_hir_id(local_def_id)), + tcx.hir_node_by_def_id(local_def_id), Node::Item(&hir::Item { kind: hir::ItemKind::Static(..) | hir::ItemKind::Fn(..), .. diff --git a/tests/rustdoc-ui/doctest/check-attr-test.stderr b/tests/rustdoc-ui/doctest/check-attr-test.stderr index 01beba1ffc4a4..10f763a6f9d86 100644 --- a/tests/rustdoc-ui/doctest/check-attr-test.stderr +++ b/tests/rustdoc-ui/doctest/check-attr-test.stderr @@ -1,4 +1,4 @@ -error: unknown attribute `compile-fail`. Did you mean `compile_fail`? +error: unknown attribute `compile-fail` --> $DIR/check-attr-test.rs:5:1 | 5 | / /// foo @@ -8,6 +8,7 @@ error: unknown attribute `compile-fail`. Did you mean `compile_fail`? 9 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `compile_fail` = help: the code block will either not be tested if not marked as a rust one or won't fail if it compiles successfully note: the lint level is defined here --> $DIR/check-attr-test.rs:3:9 @@ -15,7 +16,7 @@ note: the lint level is defined here 3 | #![deny(rustdoc::invalid_codeblock_attributes)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: unknown attribute `compilefail`. Did you mean `compile_fail`? +error: unknown attribute `compilefail` --> $DIR/check-attr-test.rs:5:1 | 5 | / /// foo @@ -25,9 +26,10 @@ error: unknown attribute `compilefail`. Did you mean `compile_fail`? 9 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `compile_fail` = help: the code block will either not be tested if not marked as a rust one or won't fail if it compiles successfully -error: unknown attribute `comPile_fail`. Did you mean `compile_fail`? +error: unknown attribute `comPile_fail` --> $DIR/check-attr-test.rs:5:1 | 5 | / /// foo @@ -37,9 +39,10 @@ error: unknown attribute `comPile_fail`. Did you mean `compile_fail`? 9 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `compile_fail` = help: the code block will either not be tested if not marked as a rust one or won't fail if it compiles successfully -error: unknown attribute `should-panic`. Did you mean `should_panic`? +error: unknown attribute `should-panic` --> $DIR/check-attr-test.rs:12:1 | 12 | / /// bar @@ -49,9 +52,10 @@ error: unknown attribute `should-panic`. Did you mean `should_panic`? 16 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `should_panic` = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running -error: unknown attribute `shouldpanic`. Did you mean `should_panic`? +error: unknown attribute `shouldpanic` --> $DIR/check-attr-test.rs:12:1 | 12 | / /// bar @@ -61,9 +65,10 @@ error: unknown attribute `shouldpanic`. Did you mean `should_panic`? 16 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `should_panic` = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running -error: unknown attribute `shOuld_panic`. Did you mean `should_panic`? +error: unknown attribute `shOuld_panic` --> $DIR/check-attr-test.rs:12:1 | 12 | / /// bar @@ -73,9 +78,10 @@ error: unknown attribute `shOuld_panic`. Did you mean `should_panic`? 16 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `should_panic` = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running -error: unknown attribute `no-run`. Did you mean `no_run`? +error: unknown attribute `no-run` --> $DIR/check-attr-test.rs:19:1 | 19 | / /// foobar @@ -85,9 +91,10 @@ error: unknown attribute `no-run`. Did you mean `no_run`? 23 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `no_run` = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want) -error: unknown attribute `norun`. Did you mean `no_run`? +error: unknown attribute `norun` --> $DIR/check-attr-test.rs:19:1 | 19 | / /// foobar @@ -97,9 +104,10 @@ error: unknown attribute `norun`. Did you mean `no_run`? 23 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `no_run` = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want) -error: unknown attribute `nO_run`. Did you mean `no_run`? +error: unknown attribute `nO_run` --> $DIR/check-attr-test.rs:19:1 | 19 | / /// foobar @@ -109,9 +117,10 @@ error: unknown attribute `nO_run`. Did you mean `no_run`? 23 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `no_run` = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want) -error: unknown attribute `test-harness`. Did you mean `test_harness`? +error: unknown attribute `test-harness` --> $DIR/check-attr-test.rs:26:1 | 26 | / /// b @@ -121,9 +130,10 @@ error: unknown attribute `test-harness`. Did you mean `test_harness`? 30 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function -error: unknown attribute `testharness`. Did you mean `test_harness`? +error: unknown attribute `testharness` --> $DIR/check-attr-test.rs:26:1 | 26 | / /// b @@ -133,9 +143,10 @@ error: unknown attribute `testharness`. Did you mean `test_harness`? 30 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function -error: unknown attribute `tesT_harness`. Did you mean `test_harness`? +error: unknown attribute `tesT_harness` --> $DIR/check-attr-test.rs:26:1 | 26 | / /// b @@ -145,6 +156,7 @@ error: unknown attribute `tesT_harness`. Did you mean `test_harness`? 30 | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function error: aborting due to 12 previous errors diff --git a/tests/rustdoc-ui/lints/check-attr.rs b/tests/rustdoc-ui/lints/check-attr.rs index 0b3f7bedda5cf..3c06e6c076bf6 100644 --- a/tests/rustdoc-ui/lints/check-attr.rs +++ b/tests/rustdoc-ui/lints/check-attr.rs @@ -39,3 +39,20 @@ pub fn foobar() {} /// boo /// ``` pub fn b() {} + +/// b +//~^ ERROR +/// +/// ```rust2018 +/// boo +/// ``` +pub fn c() {} + +/// b +//~^ ERROR +//~| ERROR +/// +/// ```rust2018 shouldpanic +/// boo +/// ``` +pub fn d() {} diff --git a/tests/rustdoc-ui/lints/check-attr.stderr b/tests/rustdoc-ui/lints/check-attr.stderr index f66e63ab727ea..d640125ab5133 100644 --- a/tests/rustdoc-ui/lints/check-attr.stderr +++ b/tests/rustdoc-ui/lints/check-attr.stderr @@ -1,4 +1,4 @@ -error: unknown attribute `compile-fail`. Did you mean `compile_fail`? +error: unknown attribute `compile-fail` --> $DIR/check-attr.rs:3:1 | LL | / /// foo @@ -10,6 +10,7 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `compile_fail` = help: the code block will either not be tested if not marked as a rust one or won't fail if it compiles successfully note: the lint level is defined here --> $DIR/check-attr.rs:1:9 @@ -17,7 +18,7 @@ note: the lint level is defined here LL | #![deny(rustdoc::invalid_codeblock_attributes)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: unknown attribute `compilefail`. Did you mean `compile_fail`? +error: unknown attribute `compilefail` --> $DIR/check-attr.rs:3:1 | LL | / /// foo @@ -29,9 +30,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `compile_fail` = help: the code block will either not be tested if not marked as a rust one or won't fail if it compiles successfully -error: unknown attribute `comPile_fail`. Did you mean `compile_fail`? +error: unknown attribute `comPile_fail` --> $DIR/check-attr.rs:3:1 | LL | / /// foo @@ -43,9 +45,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `compile_fail` = help: the code block will either not be tested if not marked as a rust one or won't fail if it compiles successfully -error: unknown attribute `should-panic`. Did you mean `should_panic`? +error: unknown attribute `should-panic` --> $DIR/check-attr.rs:13:1 | LL | / /// bar @@ -57,9 +60,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `should_panic` = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running -error: unknown attribute `shouldpanic`. Did you mean `should_panic`? +error: unknown attribute `shouldpanic` --> $DIR/check-attr.rs:13:1 | LL | / /// bar @@ -71,9 +75,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `should_panic` = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running -error: unknown attribute `sHould_panic`. Did you mean `should_panic`? +error: unknown attribute `sHould_panic` --> $DIR/check-attr.rs:13:1 | LL | / /// bar @@ -85,9 +90,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `should_panic` = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running -error: unknown attribute `no-run`. Did you mean `no_run`? +error: unknown attribute `no-run` --> $DIR/check-attr.rs:23:1 | LL | / /// foobar @@ -99,9 +105,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `no_run` = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want) -error: unknown attribute `norun`. Did you mean `no_run`? +error: unknown attribute `norun` --> $DIR/check-attr.rs:23:1 | LL | / /// foobar @@ -113,9 +120,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `no_run` = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want) -error: unknown attribute `no_Run`. Did you mean `no_run`? +error: unknown attribute `no_Run` --> $DIR/check-attr.rs:23:1 | LL | / /// foobar @@ -127,9 +135,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `no_run` = help: the code block will either not be tested if not marked as a rust one or will be run (which you might not want) -error: unknown attribute `test-harness`. Did you mean `test_harness`? +error: unknown attribute `test-harness` --> $DIR/check-attr.rs:33:1 | LL | / /// b @@ -141,9 +150,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function -error: unknown attribute `testharness`. Did you mean `test_harness`? +error: unknown attribute `testharness` --> $DIR/check-attr.rs:33:1 | LL | / /// b @@ -155,9 +165,10 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function -error: unknown attribute `teSt_harness`. Did you mean `test_harness`? +error: unknown attribute `teSt_harness` --> $DIR/check-attr.rs:33:1 | LL | / /// b @@ -169,7 +180,50 @@ LL | | /// boo LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function -error: aborting due to 12 previous errors +error: unknown attribute `rust2018` + --> $DIR/check-attr.rs:43:1 + | +LL | / /// b +LL | | +LL | | /// +LL | | /// ```rust2018 +LL | | /// boo +LL | | /// ``` + | |_______^ + | + = help: there is an attribute with a similar name: `edition2018` + +error: unknown attribute `rust2018` + --> $DIR/check-attr.rs:51:1 + | +LL | / /// b +LL | | +LL | | +LL | | /// +LL | | /// ```rust2018 shouldpanic +LL | | /// boo +LL | | /// ``` + | |_______^ + | + = help: there is an attribute with a similar name: `edition2018` + +error: unknown attribute `shouldpanic` + --> $DIR/check-attr.rs:51:1 + | +LL | / /// b +LL | | +LL | | +LL | | /// +LL | | /// ```rust2018 shouldpanic +LL | | /// boo +LL | | /// ``` + | |_______^ + | + = help: there is an attribute with a similar name: `should_panic` + = help: the code block will either not be tested if not marked as a rust one or won't fail if it doesn't panic when running + +error: aborting due to 15 previous errors diff --git a/tests/rustdoc-ui/lints/check-fail.stderr b/tests/rustdoc-ui/lints/check-fail.stderr index f05e457af6452..99b01bac59882 100644 --- a/tests/rustdoc-ui/lints/check-fail.stderr +++ b/tests/rustdoc-ui/lints/check-fail.stderr @@ -22,7 +22,7 @@ note: the lint level is defined here LL | #![deny(rustdoc::missing_doc_code_examples)] | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -error: unknown attribute `testharness`. Did you mean `test_harness`? +error: unknown attribute `testharness` --> $DIR/check-fail.rs:8:1 | LL | / //! ```rust,testharness @@ -31,6 +31,7 @@ LL | | //! let x = 12; LL | | //! ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function note: the lint level is defined here --> $DIR/check-fail.rs:6:9 @@ -39,7 +40,7 @@ LL | #![deny(rustdoc::all)] | ^^^^^^^^^^^^ = note: `#[deny(rustdoc::invalid_codeblock_attributes)]` implied by `#[deny(rustdoc::all)]` -error: unknown attribute `testharness`. Did you mean `test_harness`? +error: unknown attribute `testharness` --> $DIR/check-fail.rs:17:1 | LL | / /// hello @@ -50,6 +51,7 @@ LL | | /// let x = 12; LL | | /// ``` | |_______^ | + = help: there is an attribute with a similar name: `test_harness` = help: the code block will either not be tested if not marked as a rust one or the code will be wrapped inside a main function error: aborting due to 4 previous errors diff --git a/tests/ui/async-await/future-sizes/async-awaiting-fut.stdout b/tests/ui/async-await/future-sizes/async-awaiting-fut.stdout index b0447a5826119..47b39e5246dde 100644 --- a/tests/ui/async-await/future-sizes/async-awaiting-fut.stdout +++ b/tests/ui/async-await/future-sizes/async-awaiting-fut.stdout @@ -52,10 +52,16 @@ print-type-size variant `Panicked`: 1024 bytes print-type-size upvar `.arg`: 1024 bytes print-type-size type: `std::mem::ManuallyDrop`: 1 bytes, alignment: 1 bytes print-type-size field `.value`: 1 bytes +print-type-size type: `std::mem::ManuallyDrop<{async fn body@$DIR/async-awaiting-fut.rs:6:17: 6:19}>`: 1 bytes, alignment: 1 bytes +print-type-size field `.value`: 1 bytes print-type-size type: `std::mem::MaybeUninit`: 1 bytes, alignment: 1 bytes print-type-size variant `MaybeUninit`: 1 bytes print-type-size field `.uninit`: 0 bytes print-type-size field `.value`: 1 bytes +print-type-size type: `std::mem::MaybeUninit<{async fn body@$DIR/async-awaiting-fut.rs:6:17: 6:19}>`: 1 bytes, alignment: 1 bytes +print-type-size variant `MaybeUninit`: 1 bytes +print-type-size field `.uninit`: 0 bytes +print-type-size field `.value`: 1 bytes print-type-size type: `std::task::Poll<()>`: 1 bytes, alignment: 1 bytes print-type-size discriminant: 1 bytes print-type-size variant `Ready`: 0 bytes diff --git a/tests/ui/async-await/in-trait/indirect-recursion-issue-112047.stderr b/tests/ui/async-await/in-trait/indirect-recursion-issue-112047.stderr index 95731b67ccf77..8e573b512ad43 100644 --- a/tests/ui/async-await/in-trait/indirect-recursion-issue-112047.stderr +++ b/tests/ui/async-await/in-trait/indirect-recursion-issue-112047.stderr @@ -1,7 +1,9 @@ -error[E0391]: cycle detected when computing layout of `{async fn body@$DIR/indirect-recursion-issue-112047.rs:33:27: 35:6}` +error[E0391]: cycle detected when computing layout of `core::mem::maybe_uninit::MaybeUninit<{async fn body@$DIR/indirect-recursion-issue-112047.rs:33:27: 35:6}>` | - = note: ...which requires computing layout of `<::Second as Second>::{opaque#0}`... - = note: ...which again requires computing layout of `{async fn body@$DIR/indirect-recursion-issue-112047.rs:33:27: 35:6}`, completing the cycle + = note: ...which requires computing layout of `core::mem::manually_drop::ManuallyDrop<{async fn body@$DIR/indirect-recursion-issue-112047.rs:33:27: 35:6}>`... + = note: ...which requires computing layout of `{async fn body@$DIR/indirect-recursion-issue-112047.rs:33:27: 35:6}`... + = note: ...which requires computing layout of `core::mem::maybe_uninit::MaybeUninit<<::Second as Second>::{opaque#0}>`... + = note: ...which again requires computing layout of `core::mem::maybe_uninit::MaybeUninit<{async fn body@$DIR/indirect-recursion-issue-112047.rs:33:27: 35:6}>`, completing the cycle = note: cycle used when computing layout of `{async block@$DIR/indirect-recursion-issue-112047.rs:6:13: 8:6}` = note: see https://rustc-dev-guide.rust-lang.org/overview.html#queries and https://rustc-dev-guide.rust-lang.org/query.html for more information diff --git a/tests/ui/coroutine/uninhabited-field.rs b/tests/ui/coroutine/uninhabited-field.rs new file mode 100644 index 0000000000000..d9570c2fed8d4 --- /dev/null +++ b/tests/ui/coroutine/uninhabited-field.rs @@ -0,0 +1,37 @@ +// Test that uninhabited saved local doesn't make the entire variant uninhabited. +// run-pass +#![allow(unused)] +#![feature(assert_matches)] +#![feature(coroutine_trait)] +#![feature(coroutines)] +#![feature(never_type)] +use std::assert_matches::assert_matches; +use std::ops::Coroutine; +use std::ops::CoroutineState; +use std::pin::Pin; + +fn conjure() -> T { loop {} } + +fn run(x: bool, y: bool) { + let mut c = || { + if x { + let a : T; + if y { + a = conjure::(); + } + yield (); + } else { + let a : T; + if y { + a = conjure::(); + } + yield (); + } + }; + assert_matches!(Pin::new(&mut c).resume(()), CoroutineState::Yielded(())); + assert_matches!(Pin::new(&mut c).resume(()), CoroutineState::Complete(())); +} + +fn main() { + run::(false, false); +} diff --git a/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs b/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs index ab8d95a41d0d7..1b8ce10ccce7d 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/count-and-length-are-distinct.rs @@ -10,11 +10,11 @@ fn main() { $( // inner-most repetition $( - ${ignore(l)} ${index()}, ${length()}, + ${ignore($l)} ${index()}, ${length()}, )* - ${count(l)}, ${index()}, ${length()}, + ${count($l)}, ${index()}, ${length()}, )* - ${count(l)}, + ${count($l)}, ] }; } @@ -72,30 +72,30 @@ fn main() { &[ $( $( $( &[ - ${ignore(i)} ${count(i, 0)}, + ${ignore($i)} ${count($i, 0)}, ][..], )* )* )* $( $( &[ - ${ignore(i)} ${count(i, 0)}, - ${ignore(i)} ${count(i, 1)}, + ${ignore($i)} ${count($i, 0)}, + ${ignore($i)} ${count($i, 1)}, ][..], )* )* $( &[ - ${ignore(i)} ${count(i, 0)}, - ${ignore(i)} ${count(i, 1)}, - ${ignore(i)} ${count(i, 2)}, + ${ignore($i)} ${count($i, 0)}, + ${ignore($i)} ${count($i, 1)}, + ${ignore($i)} ${count($i, 2)}, ][..], )* &[ - ${count(i, 0)}, - ${count(i, 1)}, - ${count(i, 2)}, - ${count(i, 3)}, + ${count($i, 0)}, + ${count($i, 1)}, + ${count($i, 2)}, + ${count($i, 3)}, ][..] ][..] } @@ -133,23 +133,23 @@ fn main() { &[7][..], // (a b c) (d e f) - &[2, 6][..], + &[6, 2][..], // (g h) (i j k l m) - &[2, 7][..], + &[7, 2][..], // (n) &[1, 1][..], // (o) (p q) (r s) - &[3, 5][..], + &[5, 3][..], // (t u v w x y z) - &[1, 7][..], + &[7, 1][..], // [ (a b c) (d e f) ] // [ (g h) (i j k l m) ] // [ (n) ] - &[3, 5, 14][..], + &[14, 5, 3][..], // [ (o) (p q) (r s) ] // [ (t u v w x y z) ] - &[2, 4, 12][..], + &[12, 4, 2][..], // { // [ (a b c) (d e f) ] @@ -160,7 +160,7 @@ fn main() { // [ (o) (p q) (r s) ] // [ (t u v w x y z) ] // } - &[2, 5, 9, 26][..] + &[26, 9, 5, 2][..] ][..] ); @@ -170,31 +170,31 @@ fn main() { &[ $( $( $( $( &[ - ${ignore(i)} ${length(3)}, - ${ignore(i)} ${length(2)}, - ${ignore(i)} ${length(1)}, - ${ignore(i)} ${length(0)}, + ${ignore($i)} ${length(3)}, + ${ignore($i)} ${length(2)}, + ${ignore($i)} ${length(1)}, + ${ignore($i)} ${length(0)}, ][..], )* )* )* )* $( $( $( &[ - ${ignore(i)} ${length(2)}, - ${ignore(i)} ${length(1)}, - ${ignore(i)} ${length(0)}, + ${ignore($i)} ${length(2)}, + ${ignore($i)} ${length(1)}, + ${ignore($i)} ${length(0)}, ][..], )* )* )* $( $( &[ - ${ignore(i)} ${length(1)}, - ${ignore(i)} ${length(0)}, + ${ignore($i)} ${length(1)}, + ${ignore($i)} ${length(0)}, ][..], )* )* $( &[ - ${ignore(i)} ${length(0)}, + ${ignore($i)} ${length(0)}, ][..], )* ][..] diff --git a/tests/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs b/tests/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs index d05cd1b31bc12..950e70153ba9c 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/feature-gate-macro_metavar_expr.rs @@ -5,14 +5,14 @@ /// Count the number of idents in a macro repetition. macro_rules! count_idents { ( $( $i:ident ),* ) => { - ${count(i)} + ${count($i)} }; } /// Count the number of idents in a 2-dimensional macro repetition. macro_rules! count_idents_2 { ( $( [ $( $i:ident ),* ] ),* ) => { - ${count(i)} + ${count($i)} }; } @@ -21,17 +21,17 @@ macro_rules! count_depth_limits { ( $( { $( [ $( $outer:ident : ( $( $inner:ident )* ) )* ] )* } )* ) => { ( ( - ${count(inner)}, - ${count(inner, 0)}, - ${count(inner, 1)}, - ${count(inner, 2)}, - ${count(inner, 3)}, + ${count($inner)}, + ${count($inner, 0)}, + ${count($inner, 1)}, + ${count($inner, 2)}, + ${count($inner, 3)}, ), ( - ${count(outer)}, - ${count(outer, 0)}, - ${count(outer, 1)}, - ${count(outer, 2)}, + ${count($outer)}, + ${count($outer, 0)}, + ${count($outer, 1)}, + ${count($outer, 2)}, ), ) }; @@ -43,7 +43,7 @@ macro_rules! count_depth_limits { /// repetition binding. macro_rules! enumerate_literals { ( $( ($l:stmt) ),* ) => { - [$( ${ignore(l)} (${index()}, ${length()}) ),*] + [$( ${ignore($l)} (${index()}, ${length()}) ),*] }; } @@ -77,7 +77,7 @@ macro_rules! make_count_adders { $( macro_rules! $i { ( $$( $$j:ident ),* ) => { - $b + $${count(j)} + $b + $${count($j)} }; } )* @@ -122,7 +122,7 @@ fn main() { [ T: (t u v w x y z) ] } }, - ((26, 2, 5, 9, 26), (9, 2, 5, 9)) + ((26, 26, 9, 5, 2), (9, 9, 5, 2)) ); assert_eq!(enumerate_literals![("foo"), ("bar")], [(0, 2), (1, 2)]); assert_eq!( diff --git a/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.rs b/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.rs index 9cc572c23a1ab..3000bfed6a887 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.rs @@ -1,7 +1,7 @@ #![feature(macro_metavar_expr)] macro_rules! foo { - ( $( $($t:ident),* );* ) => { ${count(t,)} } + ( $( $($t:ident),* );* ) => { ${count($t,)} } //~^ ERROR `count` followed by a comma must have an associated //~| ERROR expected expression, found `$` } diff --git a/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.stderr b/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.stderr index e9317a5c34772..fd53c1686cf14 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.stderr +++ b/tests/ui/macros/rfc-3086-metavar-expr/issue-111904.stderr @@ -1,13 +1,13 @@ error: `count` followed by a comma must have an associated index indicating its depth --> $DIR/issue-111904.rs:4:37 | -LL | ( $( $($t:ident),* );* ) => { ${count(t,)} } +LL | ( $( $($t:ident),* );* ) => { ${count($t,)} } | ^^^^^ error: expected expression, found `$` --> $DIR/issue-111904.rs:4:35 | -LL | ( $( $($t:ident),* );* ) => { ${count(t,)} } +LL | ( $( $($t:ident),* );* ) => { ${count($t,)} } | ^ expected expression ... LL | foo!(a, a; b, b); diff --git a/tests/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs b/tests/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs index b954967c4fe5a..04924f0efa6f9 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/macro-expansion.rs @@ -13,17 +13,17 @@ macro_rules! example { ( $( [ $( ( $( $x:ident )* ) )* ] )* ) => { Example { _indexes: &[], - _counts: &[${count(x, 0)}, ${count(x, 1)}, ${count(x, 2)}], + _counts: &[${count($x, 0)}, ${count($x, 1)}, ${count($x, 2)}], _nested: vec![ $( Example { _indexes: &[(${index()}, ${length()})], - _counts: &[${count(x, 0)}, ${count(x, 1)}], + _counts: &[${count($x, 0)}, ${count($x, 1)}], _nested: vec![ $( Example { _indexes: &[(${index(1)}, ${length(1)}), (${index()}, ${length()})], - _counts: &[${count(x)}], + _counts: &[${count($x)}], _nested: vec![ $( Example { @@ -34,7 +34,7 @@ macro_rules! example { ], _counts: &[], _nested: vec![], - ${ignore(x)} + ${ignore($x)} } ),* ] @@ -49,9 +49,9 @@ macro_rules! example { } static EXPECTED: &str = concat!( - "Example { _indexes: [], _counts: [2, 4, 13], _nested: [", + "Example { _indexes: [], _counts: [13, 4, 2], _nested: [", concat!( - "Example { _indexes: [(0, 2)], _counts: [3, 10], _nested: [", + "Example { _indexes: [(0, 2)], _counts: [10, 3], _nested: [", concat!( "Example { _indexes: [(0, 2), (0, 3)], _counts: [4], _nested: [", concat!( @@ -77,7 +77,7 @@ static EXPECTED: &str = concat!( "] }", ), "] }, ", - "Example { _indexes: [(1, 2)], _counts: [1, 3], _nested: [", + "Example { _indexes: [(1, 2)], _counts: [3, 1], _nested: [", concat!( "Example { _indexes: [(1, 2), (0, 1)], _counts: [3], _nested: [", concat!( diff --git a/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs b/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs index 6a0d68bd6b16a..d195506af3612 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.rs @@ -3,9 +3,9 @@ macro_rules! a { ( $( { $( [ $( ( $( $foo:ident )* ) )* ] )* } )* ) => { ( - ${count(foo, 0)}, - ${count(foo, 10)}, - //~^ ERROR depth parameter on meta-variable expression `count` must be less than 4 + ${count($foo, 0)}, + ${count($foo, 10)}, + //~^ ERROR depth parameter of meta-variable expression `count` must be less than 4 ) }; } @@ -14,10 +14,10 @@ macro_rules! b { ( $( { $( [ $( $foo:ident )* ] )* } )* ) => { ( $( $( $( - ${ignore(foo)} + ${ignore($foo)} ${index(0)}, ${index(10)}, - //~^ ERROR depth parameter on meta-variable expression `index` must be less than 3 + //~^ ERROR depth parameter of meta-variable expression `index` must be less than 3 )* )* )* ) }; @@ -27,10 +27,10 @@ macro_rules! c { ( $( { $( $foo:ident )* } )* ) => { ( $( $( - ${ignore(foo)} + ${ignore($foo)} ${length(0)} ${length(10)} - //~^ ERROR depth parameter on meta-variable expression `length` must be less than 2 + //~^ ERROR depth parameter of meta-variable expression `length` must be less than 2 )* )* ) }; diff --git a/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr b/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr index 236122b6465b2..f757b8af219fd 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr +++ b/tests/ui/macros/rfc-3086-metavar-expr/out-of-bounds-arguments.stderr @@ -1,16 +1,16 @@ -error: depth parameter on meta-variable expression `count` must be less than 4 +error: depth parameter of meta-variable expression `count` must be less than 4 --> $DIR/out-of-bounds-arguments.rs:7:14 | -LL | ${count(foo, 10)}, - | ^^^^^^^^^^^^^^^^ +LL | ${count($foo, 10)}, + | ^^^^^^^^^^^^^^^^^ -error: depth parameter on meta-variable expression `index` must be less than 3 +error: depth parameter of meta-variable expression `index` must be less than 3 --> $DIR/out-of-bounds-arguments.rs:19:18 | LL | ${index(10)}, | ^^^^^^^^^^^ -error: depth parameter on meta-variable expression `length` must be less than 2 +error: depth parameter of meta-variable expression `length` must be less than 2 --> $DIR/out-of-bounds-arguments.rs:32:18 | LL | ${length(10)} diff --git a/tests/ui/macros/rfc-3086-metavar-expr/required-feature.rs b/tests/ui/macros/rfc-3086-metavar-expr/required-feature.rs index b4fef11f1e29a..53d045700f9fe 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/required-feature.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/required-feature.rs @@ -1,6 +1,6 @@ macro_rules! count { ( $( $e:stmt ),* ) => { - ${ count(e) } + ${ count($e) } //~^ ERROR meta-variable expressions are unstable }; } @@ -19,7 +19,7 @@ macro_rules! dollar_dollar { macro_rules! index { ( $( $e:stmt ),* ) => { - $( ${ignore(e)} ${index()} )* + $( ${ignore($e)} ${index()} )* //~^ ERROR meta-variable expressions are unstable //~| ERROR meta-variable expressions are unstable }; @@ -27,14 +27,14 @@ macro_rules! index { macro_rules! ignore { ( $( $i:stmt ),* ) => {{ - 0 $( + 1 ${ignore(i)} )* + 0 $( + 1 ${ignore($i)} )* //~^ ERROR meta-variable expressions are unstable }}; } macro_rules! length { ( $( $e:stmt ),* ) => { - $( ${ignore(e)} ${length()} )* + $( ${ignore($e)} ${length()} )* //~^ ERROR meta-variable expressions are unstable //~| ERROR meta-variable expressions are unstable }; diff --git a/tests/ui/macros/rfc-3086-metavar-expr/required-feature.stderr b/tests/ui/macros/rfc-3086-metavar-expr/required-feature.stderr index ecf598b104d05..2c2cbb15b7288 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/required-feature.stderr +++ b/tests/ui/macros/rfc-3086-metavar-expr/required-feature.stderr @@ -1,8 +1,8 @@ error[E0658]: meta-variable expressions are unstable --> $DIR/required-feature.rs:3:10 | -LL | ${ count(e) } - | ^^^^^^^^^^^^ +LL | ${ count($e) } + | ^^^^^^^^^^^^^ | = note: see issue #83527 for more information = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable @@ -46,17 +46,17 @@ LL | ( $$( $$any:tt )* ) => { $$( $$any )* }; error[E0658]: meta-variable expressions are unstable --> $DIR/required-feature.rs:22:13 | -LL | $( ${ignore(e)} ${index()} )* - | ^^^^^^^^^^^ +LL | $( ${ignore($e)} ${index()} )* + | ^^^^^^^^^^^^ | = note: see issue #83527 for more information = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable error[E0658]: meta-variable expressions are unstable - --> $DIR/required-feature.rs:22:26 + --> $DIR/required-feature.rs:22:27 | -LL | $( ${ignore(e)} ${index()} )* - | ^^^^^^^^^ +LL | $( ${ignore($e)} ${index()} )* + | ^^^^^^^^^ | = note: see issue #83527 for more information = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable @@ -64,8 +64,8 @@ LL | $( ${ignore(e)} ${index()} )* error[E0658]: meta-variable expressions are unstable --> $DIR/required-feature.rs:30:19 | -LL | 0 $( + 1 ${ignore(i)} )* - | ^^^^^^^^^^^ +LL | 0 $( + 1 ${ignore($i)} )* + | ^^^^^^^^^^^^ | = note: see issue #83527 for more information = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable @@ -73,17 +73,17 @@ LL | 0 $( + 1 ${ignore(i)} )* error[E0658]: meta-variable expressions are unstable --> $DIR/required-feature.rs:37:13 | -LL | $( ${ignore(e)} ${length()} )* - | ^^^^^^^^^^^ +LL | $( ${ignore($e)} ${length()} )* + | ^^^^^^^^^^^^ | = note: see issue #83527 for more information = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable error[E0658]: meta-variable expressions are unstable - --> $DIR/required-feature.rs:37:26 + --> $DIR/required-feature.rs:37:27 | -LL | $( ${ignore(e)} ${length()} )* - | ^^^^^^^^^^ +LL | $( ${ignore($e)} ${length()} )* + | ^^^^^^^^^^ | = note: see issue #83527 for more information = help: add `#![feature(macro_metavar_expr)]` to the crate attributes to enable diff --git a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs index fdf16442d2aa5..05c65fe869073 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs +++ b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.rs @@ -5,24 +5,17 @@ // `round` = Left hand side round brackets macro_rules! curly__no_rhs_dollar__round { - ( $( $i:ident ),* ) => { ${ count(i) } }; + ( $( $i:ident ),* ) => { ${ count($i) } }; } macro_rules! curly__no_rhs_dollar__no_round { - ( $i:ident ) => { ${ count(i) } }; + ( $i:ident ) => { ${ count($i) } }; //~^ ERROR `count` can not be placed inside the inner-most repetition } -macro_rules! curly__rhs_dollar__round { - ( $( $i:ident ),* ) => { ${ count($i) } }; - //~^ ERROR expected identifier, found `$` - //~| ERROR expected expression, found `$` -} - macro_rules! curly__rhs_dollar__no_round { ( $i:ident ) => { ${ count($i) } }; - //~^ ERROR expected identifier, found `$` - //~| ERROR expected expression, found `$` + //~^ ERROR `count` can not be placed inside the inner-most repetition } macro_rules! no_curly__no_rhs_dollar__round { @@ -60,16 +53,16 @@ macro_rules! extra_garbage_after_metavar { ${count() a b c} //~^ ERROR unexpected token: a //~| ERROR expected expression, found `$` - ${count(i a b c)} + ${count($i a b c)} //~^ ERROR unexpected token: a - ${count(i, 1 a b c)} + ${count($i, 1 a b c)} //~^ ERROR unexpected token: a - ${count(i) a b c} + ${count($i) a b c} //~^ ERROR unexpected token: a - ${ignore(i) a b c} + ${ignore($i) a b c} //~^ ERROR unexpected token: a - ${ignore(i a b c)} + ${ignore($i a b c)} //~^ ERROR unexpected token: a ${index() a b c} @@ -100,8 +93,8 @@ macro_rules! metavar_in_the_lhs { macro_rules! metavar_token_without_ident { ( $( $i:ident ),* ) => { ${ ignore() } }; - //~^ ERROR expected identifier - //~| ERROR expected expression, found `$` + //~^ ERROR meta-variable expressions must be referenced using a dollar sign + //~| ERROR expected expression } macro_rules! metavar_with_literal_suffix { @@ -125,14 +118,16 @@ macro_rules! open_brackets_without_tokens { macro_rules! unknown_count_ident { ( $( $i:ident )* ) => { ${count(foo)} - //~^ ERROR variable `foo` is not recognized in meta-variable expression + //~^ ERROR meta-variable expressions must be referenced using a dollar sign + //~| ERROR expected expression }; } macro_rules! unknown_ignore_ident { ( $( $i:ident )* ) => { ${ignore(bar)} - //~^ ERROR variable `bar` is not recognized in meta-variable expression + //~^ ERROR meta-variable expressions must be referenced using a dollar sign + //~| ERROR expected expression }; } @@ -145,7 +140,6 @@ macro_rules! unknown_metavar { fn main() { curly__no_rhs_dollar__round!(a, b, c); curly__no_rhs_dollar__no_round!(a); - curly__rhs_dollar__round!(a, b, c); curly__rhs_dollar__no_round!(a); no_curly__no_rhs_dollar__round!(a, b, c); no_curly__no_rhs_dollar__no_round!(a); diff --git a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr index a6cff95fd9153..0dda38290ab6b 100644 --- a/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr +++ b/tests/ui/macros/rfc-3086-metavar-expr/syntax-errors.stderr @@ -1,197 +1,197 @@ -error: expected identifier, found `$` - --> $DIR/syntax-errors.rs:17:33 - | -LL | ( $( $i:ident ),* ) => { ${ count($i) } }; - | ^^^^^ - help: try removing `$` - -error: expected identifier, found `$` - --> $DIR/syntax-errors.rs:23:26 - | -LL | ( $i:ident ) => { ${ count($i) } }; - | ^^^^^ - help: try removing `$` - error: unexpected token: $ - --> $DIR/syntax-errors.rs:53:8 + --> $DIR/syntax-errors.rs:46:8 | LL | ( $$ $a:ident ) => { | ^ note: `$$` and meta-variable expressions are not allowed inside macro parameter definitions - --> $DIR/syntax-errors.rs:53:8 + --> $DIR/syntax-errors.rs:46:8 | LL | ( $$ $a:ident ) => { | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:60:19 + --> $DIR/syntax-errors.rs:53:19 | LL | ${count() a b c} | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:60:19 + --> $DIR/syntax-errors.rs:53:19 | LL | ${count() a b c} | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:63:19 + --> $DIR/syntax-errors.rs:56:20 | -LL | ${count(i a b c)} - | ^ +LL | ${count($i a b c)} + | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:63:19 + --> $DIR/syntax-errors.rs:56:20 | -LL | ${count(i a b c)} - | ^ +LL | ${count($i a b c)} + | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:65:22 + --> $DIR/syntax-errors.rs:58:23 | -LL | ${count(i, 1 a b c)} - | ^ +LL | ${count($i, 1 a b c)} + | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:65:22 + --> $DIR/syntax-errors.rs:58:23 | -LL | ${count(i, 1 a b c)} - | ^ +LL | ${count($i, 1 a b c)} + | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:67:20 + --> $DIR/syntax-errors.rs:60:21 | -LL | ${count(i) a b c} - | ^ +LL | ${count($i) a b c} + | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:67:20 + --> $DIR/syntax-errors.rs:60:21 | -LL | ${count(i) a b c} - | ^ +LL | ${count($i) a b c} + | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:70:21 + --> $DIR/syntax-errors.rs:63:22 | -LL | ${ignore(i) a b c} - | ^ +LL | ${ignore($i) a b c} + | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:70:21 + --> $DIR/syntax-errors.rs:63:22 | -LL | ${ignore(i) a b c} - | ^ +LL | ${ignore($i) a b c} + | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:72:20 + --> $DIR/syntax-errors.rs:65:21 | -LL | ${ignore(i a b c)} - | ^ +LL | ${ignore($i a b c)} + | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:72:20 + --> $DIR/syntax-errors.rs:65:21 | -LL | ${ignore(i a b c)} - | ^ +LL | ${ignore($i a b c)} + | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:75:19 + --> $DIR/syntax-errors.rs:68:19 | LL | ${index() a b c} | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:75:19 + --> $DIR/syntax-errors.rs:68:19 | LL | ${index() a b c} | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:77:19 + --> $DIR/syntax-errors.rs:70:19 | LL | ${index(1 a b c)} | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:77:19 + --> $DIR/syntax-errors.rs:70:19 | LL | ${index(1 a b c)} | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:80:19 + --> $DIR/syntax-errors.rs:73:19 | LL | ${index() a b c} | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:80:19 + --> $DIR/syntax-errors.rs:73:19 | LL | ${index() a b c} | ^ error: unexpected token: a - --> $DIR/syntax-errors.rs:82:19 + --> $DIR/syntax-errors.rs:75:19 | LL | ${index(1 a b c)} | ^ | note: meta-variable expression must not have trailing tokens - --> $DIR/syntax-errors.rs:82:19 + --> $DIR/syntax-errors.rs:75:19 | LL | ${index(1 a b c)} | ^ error: meta-variable expression depth must be a literal - --> $DIR/syntax-errors.rs:89:33 + --> $DIR/syntax-errors.rs:82:33 | LL | ( $( $i:ident ),* ) => { ${ index(IDX) } }; | ^^^^^ error: unexpected token: { - --> $DIR/syntax-errors.rs:95:8 + --> $DIR/syntax-errors.rs:88:8 | LL | ( ${ length() } ) => { | ^^^^^^^^^^^^ note: `$$` and meta-variable expressions are not allowed inside macro parameter definitions - --> $DIR/syntax-errors.rs:95:8 + --> $DIR/syntax-errors.rs:88:8 | LL | ( ${ length() } ) => { | ^^^^^^^^^^^^ error: expected one of: `*`, `+`, or `?` - --> $DIR/syntax-errors.rs:95:8 + --> $DIR/syntax-errors.rs:88:8 | LL | ( ${ length() } ) => { | ^^^^^^^^^^^^ -error: expected identifier - --> $DIR/syntax-errors.rs:102:33 +error: meta-variables within meta-variable expressions must be referenced using a dollar sign + --> $DIR/syntax-errors.rs:95:33 | LL | ( $( $i:ident ),* ) => { ${ ignore() } }; | ^^^^^^ error: only unsuffixes integer literals are supported in meta-variable expressions - --> $DIR/syntax-errors.rs:108:33 + --> $DIR/syntax-errors.rs:101:33 | LL | ( $( $i:ident ),* ) => { ${ index(1u32) } }; | ^^^^^ error: meta-variable expression parameter must be wrapped in parentheses - --> $DIR/syntax-errors.rs:114:33 + --> $DIR/syntax-errors.rs:107:33 | LL | ( $( $i:ident ),* ) => { ${ count{i} } }; | ^^^^^ error: expected identifier - --> $DIR/syntax-errors.rs:120:31 + --> $DIR/syntax-errors.rs:113:31 | LL | ( $( $i:ident ),* ) => { ${ {} } }; | ^^^^^^ +error: meta-variables within meta-variable expressions must be referenced using a dollar sign + --> $DIR/syntax-errors.rs:120:11 + | +LL | ${count(foo)} + | ^^^^^ + +error: meta-variables within meta-variable expressions must be referenced using a dollar sign + --> $DIR/syntax-errors.rs:128:11 + | +LL | ${ignore(bar)} + | ^^^^^^ + error: unrecognized meta-variable expression - --> $DIR/syntax-errors.rs:140:33 + --> $DIR/syntax-errors.rs:135:33 | LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; | ^^^^^^^^^^^^^^ help: supported expressions are count, ignore, index and length @@ -199,39 +199,23 @@ LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; error: `count` can not be placed inside the inner-most repetition --> $DIR/syntax-errors.rs:12:24 | -LL | ( $i:ident ) => { ${ count(i) } }; - | ^^^^^^^^^^^^ - -error: expected expression, found `$` - --> $DIR/syntax-errors.rs:17:30 - | -LL | ( $( $i:ident ),* ) => { ${ count($i) } }; - | ^ expected expression -... -LL | curly__rhs_dollar__round!(a, b, c); - | ---------------------------------- in this macro invocation - | - = note: this error originates in the macro `curly__rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) +LL | ( $i:ident ) => { ${ count($i) } }; + | ^^^^^^^^^^^^^ -error: expected expression, found `$` - --> $DIR/syntax-errors.rs:23:23 +error: `count` can not be placed inside the inner-most repetition + --> $DIR/syntax-errors.rs:17:24 | LL | ( $i:ident ) => { ${ count($i) } }; - | ^ expected expression -... -LL | curly__rhs_dollar__no_round!(a); - | ------------------------------- in this macro invocation - | - = note: this error originates in the macro `curly__rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) + | ^^^^^^^^^^^^^ error: variable 'i' is still repeating at this depth - --> $DIR/syntax-errors.rs:41:36 + --> $DIR/syntax-errors.rs:34:36 | LL | ( $( $i:ident ),* ) => { count($i) }; | ^^ error: expected expression, found `$` - --> $DIR/syntax-errors.rs:60:9 + --> $DIR/syntax-errors.rs:53:9 | LL | ${count() a b c} | ^ expected expression @@ -242,7 +226,7 @@ LL | extra_garbage_after_metavar!(a); = note: this error originates in the macro `extra_garbage_after_metavar` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected expression, found `$` - --> $DIR/syntax-errors.rs:89:30 + --> $DIR/syntax-errors.rs:82:30 | LL | ( $( $i:ident ),* ) => { ${ index(IDX) } }; | ^ expected expression @@ -253,7 +237,7 @@ LL | metavar_depth_is_not_literal!(a); = note: this error originates in the macro `metavar_depth_is_not_literal` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected expression, found `$` - --> $DIR/syntax-errors.rs:102:30 + --> $DIR/syntax-errors.rs:95:30 | LL | ( $( $i:ident ),* ) => { ${ ignore() } }; | ^ expected expression @@ -264,7 +248,7 @@ LL | metavar_token_without_ident!(a); = note: this error originates in the macro `metavar_token_without_ident` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected expression, found `$` - --> $DIR/syntax-errors.rs:108:30 + --> $DIR/syntax-errors.rs:101:30 | LL | ( $( $i:ident ),* ) => { ${ index(1u32) } }; | ^ expected expression @@ -275,7 +259,7 @@ LL | metavar_with_literal_suffix!(a); = note: this error originates in the macro `metavar_with_literal_suffix` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected expression, found `$` - --> $DIR/syntax-errors.rs:114:30 + --> $DIR/syntax-errors.rs:107:30 | LL | ( $( $i:ident ),* ) => { ${ count{i} } }; | ^ expected expression @@ -286,7 +270,7 @@ LL | metavar_without_parens!(a); = note: this error originates in the macro `metavar_without_parens` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected expression, found `$` - --> $DIR/syntax-errors.rs:120:30 + --> $DIR/syntax-errors.rs:113:30 | LL | ( $( $i:ident ),* ) => { ${ {} } }; | ^ expected expression @@ -296,20 +280,30 @@ LL | open_brackets_without_tokens!(a); | = note: this error originates in the macro `open_brackets_without_tokens` (in Nightly builds, run with -Z macro-backtrace for more info) -error: variable `foo` is not recognized in meta-variable expression - --> $DIR/syntax-errors.rs:127:17 +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:120:9 | LL | ${count(foo)} - | ^^^ + | ^ expected expression +... +LL | unknown_count_ident!(a); + | ----------------------- in this macro invocation + | + = note: this error originates in the macro `unknown_count_ident` (in Nightly builds, run with -Z macro-backtrace for more info) -error: variable `bar` is not recognized in meta-variable expression - --> $DIR/syntax-errors.rs:134:18 +error: expected expression, found `$` + --> $DIR/syntax-errors.rs:128:9 | LL | ${ignore(bar)} - | ^^^ + | ^ expected expression +... +LL | unknown_ignore_ident!(a); + | ------------------------ in this macro invocation + | + = note: this error originates in the macro `unknown_ignore_ident` (in Nightly builds, run with -Z macro-backtrace for more info) error: expected expression, found `$` - --> $DIR/syntax-errors.rs:140:30 + --> $DIR/syntax-errors.rs:135:30 | LL | ( $( $i:ident ),* ) => { ${ aaaaaaaaaaaaaa(i) } }; | ^ expected expression @@ -320,7 +314,7 @@ LL | unknown_metavar!(a); = note: this error originates in the macro `unknown_metavar` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0425]: cannot find value `i` in this scope - --> $DIR/syntax-errors.rs:29:36 + --> $DIR/syntax-errors.rs:22:36 | LL | ( $( $i:ident ),* ) => { count(i) }; | ^ not found in this scope @@ -331,7 +325,7 @@ LL | no_curly__no_rhs_dollar__round!(a, b, c); = note: this error originates in the macro `no_curly__no_rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0425]: cannot find value `i` in this scope - --> $DIR/syntax-errors.rs:35:29 + --> $DIR/syntax-errors.rs:28:29 | LL | ( $i:ident ) => { count(i) }; | ^ not found in this scope @@ -342,13 +336,13 @@ LL | no_curly__no_rhs_dollar__no_round!(a); = note: this error originates in the macro `no_curly__no_rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0425]: cannot find value `a` in this scope - --> $DIR/syntax-errors.rs:153:37 + --> $DIR/syntax-errors.rs:147:37 | LL | no_curly__rhs_dollar__no_round!(a); | ^ not found in this scope error[E0425]: cannot find function `count` in this scope - --> $DIR/syntax-errors.rs:29:30 + --> $DIR/syntax-errors.rs:22:30 | LL | ( $( $i:ident ),* ) => { count(i) }; | ^^^^^ not found in this scope @@ -359,7 +353,7 @@ LL | no_curly__no_rhs_dollar__round!(a, b, c); = note: this error originates in the macro `no_curly__no_rhs_dollar__round` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0425]: cannot find function `count` in this scope - --> $DIR/syntax-errors.rs:35:23 + --> $DIR/syntax-errors.rs:28:23 | LL | ( $i:ident ) => { count(i) }; | ^^^^^ not found in this scope @@ -370,7 +364,7 @@ LL | no_curly__no_rhs_dollar__no_round!(a); = note: this error originates in the macro `no_curly__no_rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) error[E0425]: cannot find function `count` in this scope - --> $DIR/syntax-errors.rs:46:23 + --> $DIR/syntax-errors.rs:39:23 | LL | ( $i:ident ) => { count($i) }; | ^^^^^ not found in this scope @@ -380,6 +374,6 @@ LL | no_curly__rhs_dollar__no_round!(a); | = note: this error originates in the macro `no_curly__rhs_dollar__no_round` (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 40 previous errors +error: aborting due to 39 previous errors For more information about this error, try `rustc --explain E0425`. diff --git a/tests/ui/print_type_sizes/coroutine_discr_placement.stdout b/tests/ui/print_type_sizes/coroutine_discr_placement.stdout index f34a8e9a706aa..71a7f3c63815c 100644 --- a/tests/ui/print_type_sizes/coroutine_discr_placement.stdout +++ b/tests/ui/print_type_sizes/coroutine_discr_placement.stdout @@ -9,3 +9,9 @@ print-type-size padding: 3 bytes print-type-size local `.z`: 4 bytes, alignment: 4 bytes print-type-size variant `Returned`: 0 bytes print-type-size variant `Panicked`: 0 bytes +print-type-size type: `std::mem::ManuallyDrop`: 4 bytes, alignment: 4 bytes +print-type-size field `.value`: 4 bytes +print-type-size type: `std::mem::MaybeUninit`: 4 bytes, alignment: 4 bytes +print-type-size variant `MaybeUninit`: 4 bytes +print-type-size field `.uninit`: 0 bytes +print-type-size field `.value`: 4 bytes