Auto merge of #137163 - matthiaskrgr:rollup-ovgfkns, r=matthiaskrgr

Rollup of 7 pull requests

Successful merges:

 - #136466 (Start removing `rustc_middle::hir::map::Map`)
 - #136671 (Overhaul `rustc_middle::limits`)
 - #136817 (Pattern Migration 2024: clean up and comment)
 - #136844 (Use `const_error!` when possible)
 - #137080 (bootstrap: add more tracing to compiler/std/llvm flows)
 - #137101 (`invalid_from_utf8[_unchecked]`: also lint inherent methods)
 - #137140 (Fix const items not being allowed to be called `r#move` or `r#static`)

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2025-02-17 08:10:13 +00:00
commit 273465e1f2
295 changed files with 1845 additions and 1098 deletions

View file

@ -407,7 +407,7 @@ fn compute_hir_hash(
.iter_enumerated()
.filter_map(|(def_id, info)| {
let info = info.as_owner()?;
let def_path_hash = tcx.hir().def_path_hash(def_id);
let def_path_hash = tcx.hir_def_path_hash(def_id);
Some((def_path_hash, info))
})
.collect();
@ -497,7 +497,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
"adding a def'n for node-id {:?} and def kind {:?} but a previous def'n exists: {:?}",
node_id,
def_kind,
self.tcx.hir().def_key(self.local_def_id(node_id)),
self.tcx.hir_def_key(self.local_def_id(node_id)),
);
let def_id = self.tcx.at(span).create_def(parent, name, def_kind).def_id();

View file

@ -14,7 +14,7 @@ use rustc_errors::codes::*;
use rustc_errors::{Applicability, Diag, MultiSpan, struct_span_code_err};
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::intravisit::{Map, Visitor, walk_block, walk_expr};
use rustc_hir::intravisit::{Visitor, walk_block, walk_expr};
use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, LangItem, PatField};
use rustc_middle::bug;
use rustc_middle::hir::nested_filter::OnlyBodies;
@ -348,13 +348,13 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
expr: Option<&'hir hir::Expr<'hir>>,
pat: Option<&'hir hir::Pat<'hir>>,
parent_pat: Option<&'hir hir::Pat<'hir>>,
hir: rustc_middle::hir::map::Map<'hir>,
tcx: TyCtxt<'hir>,
}
impl<'hir> Visitor<'hir> for ExpressionFinder<'hir> {
type NestedFilter = OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, e: &'hir hir::Expr<'hir>) {
@ -396,7 +396,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
expr: None,
pat: None,
parent_pat: None,
hir,
tcx: self.infcx.tcx,
};
finder.visit_expr(expr);
if let Some(span) = span
@ -1082,7 +1082,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
] {
for (destination, sp) in elements {
if let Ok(hir_id) = destination.target_id
&& let hir::Node::Expr(expr) = tcx.hir().hir_node(hir_id)
&& let hir::Node::Expr(expr) = tcx.hir_node(hir_id)
&& !matches!(
sp.desugaring_kind(),
Some(DesugaringKind::ForLoop | DesugaringKind::WhileLoop)
@ -1437,7 +1437,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let Some(hir_generics) = tcx
.typeck_root_def_id(self.mir_def_id().to_def_id())
.as_local()
.and_then(|def_id| tcx.hir().get_generics(def_id))
.and_then(|def_id| tcx.hir_get_generics(def_id))
else {
return;
};
@ -1889,7 +1889,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
fn suggest_copy_for_type_in_cloned_ref(&self, err: &mut Diag<'infcx>, place: Place<'tcx>) {
let tcx = self.infcx.tcx;
let hir = tcx.hir();
let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
struct FindUselessClone<'tcx> {
@ -1917,7 +1916,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let mut expr_finder = FindUselessClone::new(tcx, self.mir_def_id());
let body = hir.body(body_id).value;
let body = tcx.hir_body(body_id).value;
expr_finder.visit_expr(body);
struct Holds<'tcx> {
@ -2106,7 +2105,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let tcx = self.infcx.tcx;
let body_id = tcx.hir_node(self.mir_hir_id()).body_id()?;
let mut expr_finder = FindExprBySpan::new(span, tcx);
expr_finder.visit_expr(tcx.hir().body(body_id).value);
expr_finder.visit_expr(tcx.hir_body(body_id).value);
expr_finder.result
}
@ -2258,7 +2257,6 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
) {
let issue_span = issued_spans.args_or_use();
let tcx = self.infcx.tcx;
let hir = tcx.hir();
let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
let typeck_results = tcx.typeck(self.mir_def_id());
@ -2346,7 +2344,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
pat_span: None,
head: None,
};
finder.visit_expr(hir.body(body_id).value);
finder.visit_expr(tcx.hir_body(body_id).value);
if let Some(body_expr) = finder.body_expr
&& let Some(loop_span) = finder.loop_span
@ -2454,10 +2452,10 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Get the body the error happens in
let Some(body_id) = tcx.hir_node(self.mir_hir_id()).body_id() else { return };
let body_expr = hir.body(body_id).value;
let body_expr = tcx.hir_body(body_id).value;
struct ClosureFinder<'hir> {
hir: rustc_middle::hir::map::Map<'hir>,
tcx: TyCtxt<'hir>,
borrow_span: Span,
res: Option<(&'hir hir::Expr<'hir>, &'hir hir::Closure<'hir>)>,
/// The path expression with the `borrow_span` span
@ -2466,8 +2464,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
impl<'hir> Visitor<'hir> for ClosureFinder<'hir> {
type NestedFilter = OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'hir hir::Expr<'hir>) {
@ -2493,7 +2491,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Find the closure that most tightly wraps `capture_kind_span`
let mut finder =
ClosureFinder { hir, borrow_span: capture_kind_span, res: None, error_path: None };
ClosureFinder { tcx, borrow_span: capture_kind_span, res: None, error_path: None };
finder.visit_expr(body_expr);
let Some((closure_expr, closure)) = finder.res else { return };
@ -2558,7 +2556,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
}
let mut finder = VariableUseFinder { local_id, spans: Vec::new() };
finder.visit_expr(hir.body(closure.body).value);
finder.visit_expr(tcx.hir_body(closure.body).value);
spans = finder.spans;
} else {
@ -3211,7 +3209,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if let Some(scope) = self.body.source_scopes.get(source_info.scope)
&& let ClearCrossCrate::Set(scope_data) = &scope.local_data
&& let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
&& let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir().body(id).value.kind
&& let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir_body(id).value.kind
{
for stmt in block.stmts {
let mut visitor = NestedStatementVisitor {

View file

@ -75,10 +75,10 @@ impl<'tcx> BorrowExplanation<'tcx> {
if let Some(span) = borrow_span {
let def_id = body.source.def_id();
if let Some(node) = tcx.hir().get_if_local(def_id)
if let Some(node) = tcx.hir_get_if_local(def_id)
&& let Some(body_id) = node.body_id()
{
let body = tcx.hir().body(body_id);
let body = tcx.hir_body(body_id);
let mut expr_finder = FindExprBySpan::new(span, tcx);
expr_finder.visit_expr(body.value);
if let Some(mut expr) = expr_finder.result {
@ -256,8 +256,8 @@ impl<'tcx> BorrowExplanation<'tcx> {
impl<'hir> rustc_hir::intravisit::Visitor<'hir> for FindLetExpr<'hir> {
type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, expr: &'hir hir::Expr<'hir>) {
if let hir::ExprKind::If(cond, _conseq, _alt)
@ -308,9 +308,9 @@ impl<'tcx> BorrowExplanation<'tcx> {
suggest_rewrite_if_let(tcx, expr, &pat, init, conseq, alt, err);
} else if let Some((old, new)) = multiple_borrow_span
&& let def_id = body.source.def_id()
&& let Some(node) = tcx.hir().get_if_local(def_id)
&& let Some(node) = tcx.hir_get_if_local(def_id)
&& let Some(body_id) = node.body_id()
&& let hir_body = tcx.hir().body(body_id)
&& let hir_body = tcx.hir_body(body_id)
&& let mut expr_finder = (FindLetExpr { span: old, result: None, tcx })
&& let Some((let_expr_span, let_expr_pat, let_expr_init)) = {
expr_finder.visit_expr(hir_body.value);

View file

@ -1220,7 +1220,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.tcx
.typeck_root_def_id(self.mir_def_id().to_def_id())
.as_local()
.and_then(|def_id| self.infcx.tcx.hir().get_generics(def_id))
.and_then(|def_id| self.infcx.tcx.hir_get_generics(def_id))
&& let spans = hir_generics
.predicates
.iter()

View file

@ -7,7 +7,7 @@ use rustc_hir::intravisit::Visitor;
use rustc_hir::{self as hir, CaptureBy, ExprKind, HirId, Node};
use rustc_middle::bug;
use rustc_middle::mir::*;
use rustc_middle::ty::{self, Ty};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_mir_dataflow::move_paths::{LookupResult, MovePathIndex};
use rustc_span::{BytePos, ExpnKind, MacroKind, Span};
use rustc_trait_selection::error_reporting::traits::FindExprBySpan;
@ -347,7 +347,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
// Find the closure that captured the binding.
let mut expr_finder = FindExprBySpan::new(args_span, tcx);
expr_finder.include_closures = true;
expr_finder.visit_expr(tcx.hir().body(body_id).value);
expr_finder.visit_expr(tcx.hir_body(body_id).value);
let Some(closure_expr) = expr_finder.result else { return };
let ExprKind::Closure(closure) = closure_expr.kind else { return };
// We'll only suggest cloning the binding if it's a `move` closure.
@ -357,7 +357,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let use_span = use_spans.var_or_use();
let mut expr_finder = FindExprBySpan::new(use_span, tcx);
expr_finder.include_closures = true;
expr_finder.visit_expr(tcx.hir().body(body_id).value);
expr_finder.visit_expr(tcx.hir_body(body_id).value);
let Some(use_expr) = expr_finder.result else { return };
let parent = tcx.parent_hir_node(use_expr.hir_id);
if let Node::Expr(expr) = parent
@ -690,7 +690,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
/// make it bind by reference instead (if possible)
struct BindingFinder<'tcx> {
typeck_results: &'tcx ty::TypeckResults<'tcx>,
hir: rustc_middle::hir::map::Map<'tcx>,
tcx: TyCtxt<'tcx>,
/// Input: the span of the pattern we're finding bindings in
pat_span: Span,
/// Input: the spans of the bindings we're providing suggestions for
@ -709,8 +709,8 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
impl<'tcx> Visitor<'tcx> for BindingFinder<'tcx> {
type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
@ -782,7 +782,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
let typeck_results = self.infcx.tcx.typeck(self.mir_def_id());
let mut finder = BindingFinder {
typeck_results,
hir,
tcx: self.infcx.tcx,
pat_span,
binding_spans,
found_pat: false,

View file

@ -936,11 +936,12 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
fn expected_fn_found_fn_mut_call(&self, err: &mut Diag<'_>, sp: Span, act: &str) {
err.span_label(sp, format!("cannot {act}"));
let hir = self.infcx.tcx.hir();
let tcx = self.infcx.tcx;
let hir = tcx.hir();
let closure_id = self.mir_hir_id();
let closure_span = self.infcx.tcx.def_span(self.mir_def_id());
let fn_call_id = self.infcx.tcx.parent_hir_id(closure_id);
let node = self.infcx.tcx.hir_node(fn_call_id);
let closure_span = tcx.def_span(self.mir_def_id());
let fn_call_id = tcx.parent_hir_id(closure_id);
let node = tcx.hir_node(fn_call_id);
let def_id = hir.enclosing_body_owner(fn_call_id);
let mut look_at_return = true;
@ -951,7 +952,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
return None;
};
let typeck_results = self.infcx.tcx.typeck(def_id);
let typeck_results = tcx.typeck(def_id);
match kind {
hir::ExprKind::Call(expr, args) => {
@ -980,7 +981,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.map(|(pos, _)| pos)
.next();
let arg = match hir.get_if_local(callee_def_id) {
let arg = match tcx.hir_get_if_local(callee_def_id) {
Some(
hir::Node::Item(hir::Item {
ident, kind: hir::ItemKind::Fn { sig, .. }, ..
@ -1022,7 +1023,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if look_at_return && hir.get_fn_id_for_return_block(closure_id).is_some() {
// ...otherwise we are probably in the tail expression of the function, point at the
// return type.
match self.infcx.tcx.hir_node_by_def_id(hir.get_parent_item(fn_call_id).def_id) {
match 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, .. }, ..
})
@ -1050,9 +1051,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
fn suggest_using_iter_mut(&self, err: &mut Diag<'_>) {
let source = self.body.source;
let hir = self.infcx.tcx.hir();
if let InstanceKind::Item(def_id) = source.instance
&& let Some(Node::Expr(hir::Expr { hir_id, kind, .. })) = hir.get_if_local(def_id)
&& let Some(Node::Expr(hir::Expr { hir_id, kind, .. })) =
self.infcx.tcx.hir_get_if_local(def_id)
&& let ExprKind::Closure(hir::Closure { kind: hir::ClosureKind::Closure, .. }) = kind
&& let Node::Expr(expr) = self.infcx.tcx.parent_hir_node(*hir_id)
{

View file

@ -219,7 +219,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
lower_bound: RegionVid,
) {
let mut suggestions = vec![];
let hir = self.infcx.tcx.hir();
let tcx = self.infcx.tcx;
// find generic associated types in the given region 'lower_bound'
let gat_id_and_generics = self
@ -228,12 +228,9 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
.map(|placeholder| {
if let Some(id) = placeholder.bound.kind.get_id()
&& let Some(placeholder_id) = id.as_local()
&& let gat_hir_id = self.infcx.tcx.local_def_id_to_hir_id(placeholder_id)
&& let Some(generics_impl) = self
.infcx
.tcx
.parent_hir_node(self.infcx.tcx.parent_hir_id(gat_hir_id))
.generics()
&& let gat_hir_id = tcx.local_def_id_to_hir_id(placeholder_id)
&& let Some(generics_impl) =
tcx.parent_hir_node(tcx.parent_hir_id(gat_hir_id)).generics()
{
Some((gat_hir_id, generics_impl))
} else {
@ -254,7 +251,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
};
if bound_generic_params
.iter()
.rfind(|bgp| self.infcx.tcx.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id)
.rfind(|bgp| tcx.local_def_id_to_hir_id(bgp.def_id) == *gat_hir_id)
.is_some()
{
for bound in *bounds {
@ -270,7 +267,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
return;
};
diag.span_note(*trait_span, fluent::borrowck_limitations_implies_static);
let Some(generics_fn) = hir.get_generics(self.body.source.def_id().expect_local())
let Some(generics_fn) = tcx.hir_get_generics(self.body.source.def_id().expect_local())
else {
return;
};
@ -1162,7 +1159,7 @@ impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
if ocx.select_all_or_error().is_empty() && count > 0 {
diag.span_suggestion_verbose(
tcx.hir().body(*body).value.peel_blocks().span.shrink_to_lo(),
tcx.hir_body(*body).value.peel_blocks().span.shrink_to_lo(),
fluent::borrowck_dereference_suggestion,
"*".repeat(count),
Applicability::MachineApplicable,

View file

@ -124,7 +124,7 @@ pub(crate) fn run_jit(tcx: TyCtxt<'_>, codegen_mode: CodegenMode, jit_args: Vec<
crate::constant::codegen_static(tcx, &mut jit_module, def_id);
}
MonoItem::GlobalAsm(item_id) => {
let item = tcx.hir().item(item_id);
let item = tcx.hir_item(item_id);
tcx.dcx().span_fatal(item.span, "Global asm is not supported in JIT mode");
}
}

View file

@ -15,7 +15,7 @@ use rustc_target::asm::InlineAsmArch;
use crate::prelude::*;
pub(crate) fn codegen_global_asm_item(tcx: TyCtxt<'_>, global_asm: &mut String, item_id: ItemId) {
let item = tcx.hir().item(item_id);
let item = tcx.hir_item(item_id);
if let rustc_hir::ItemKind::GlobalAsm(asm) = item.kind {
let is_x86 =
matches!(tcx.sess.asm_arch.unwrap(), InlineAsmArch::X86 | InlineAsmArch::X86_64);

View file

@ -35,7 +35,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
cx.codegen_static(def_id);
}
MonoItem::GlobalAsm(item_id) => {
let item = cx.tcx().hir().item(item_id);
let item = cx.tcx().hir_item(item_id);
if let hir::ItemKind::GlobalAsm(asm) = item.kind {
let operands: Vec<_> = asm
.operands

View file

@ -273,7 +273,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
let attrs = |id| hir_map.attrs(id);
pprust_hir::print_crate(
sm,
hir_map.root_module(),
tcx.hir_root_module(),
src_name,
src,
&attrs,
@ -294,7 +294,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) {
}
HirTree => {
debug!("pretty printing HIR tree");
format!("{:#?}", ex.tcx().hir().krate())
format!("{:#?}", ex.tcx().hir_crate(()))
}
Mir => {
let mut out = Vec::new();

View file

@ -1149,7 +1149,7 @@ pub static BUILTIN_ATTRIBUTES: &[BuiltinAttribute] = &[
"the `#[omit_gdb_pretty_printer_section]` attribute is just used for the Rust test suite",
),
rustc_attr!(
TEST, pattern_complexity, CrateLevel, template!(NameValueStr: "N"),
TEST, pattern_complexity_limit, CrateLevel, template!(NameValueStr: "N"),
ErrorFollowing, EncodeCrossCrate::No,
),
];

View file

@ -227,7 +227,7 @@ declare_features! (
/// Allows using `#[omit_gdb_pretty_printer_section]`.
(internal, omit_gdb_pretty_printer_section, "1.5.0", None),
/// Set the maximum pattern complexity allowed (not limited by default).
(internal, pattern_complexity, "1.78.0", None),
(internal, pattern_complexity_limit, "1.78.0", None),
/// Allows using pattern types.
(internal, pattern_types, "1.79.0", Some(123646)),
/// Allows using `#[prelude_import]` on glob `use` items.

View file

@ -18,7 +18,7 @@
//! within one another.
//! - Example: Examine each expression to look for its type and do some check or other.
//! - How: Implement `intravisit::Visitor` and override the `NestedFilter` type to
//! `nested_filter::OnlyBodies` (and implement `nested_visit_map`), and use
//! `nested_filter::OnlyBodies` (and implement `maybe_tcx`), and use
//! `tcx.hir().visit_all_item_likes_in_crate(&mut visitor)`. Within your
//! `intravisit::Visitor` impl, implement methods like `visit_expr()` (don't forget to invoke
//! `intravisit::walk_expr()` to keep walking the subparts).
@ -30,7 +30,7 @@
//! - Example: Lifetime resolution, which wants to bring lifetimes declared on the
//! impl into scope while visiting the impl-items, and then back out again.
//! - How: Implement `intravisit::Visitor` and override the `NestedFilter` type to
//! `nested_filter::All` (and implement `nested_visit_map`). Walk your crate with
//! `nested_filter::All` (and implement `maybe_tcx`). Walk your crate with
//! `tcx.hir().walk_toplevel_module(visitor)` invoked on `tcx.hir().krate()`.
//! - Pro: Visitor methods for any kind of HIR node, not just item-like things.
//! - Pro: Preserves nesting information
@ -106,45 +106,43 @@ impl<'a> FnKind<'a> {
}
}
/// An abstract representation of the HIR `rustc_middle::hir::map::Map`.
pub trait Map<'hir> {
/// HIR things retrievable from `TyCtxt`, avoiding an explicit dependence on
/// `TyCtxt`. The only impls are for `!` (where these functions are never
/// called) and `TyCtxt` (in `rustc_middle`).
pub trait HirTyCtxt<'hir> {
/// Retrieves the `Node` corresponding to `id`.
fn hir_node(&self, hir_id: HirId) -> Node<'hir>;
fn hir_node_by_def_id(&self, def_id: LocalDefId) -> Node<'hir>;
fn body(&self, id: BodyId) -> &'hir Body<'hir>;
fn item(&self, id: ItemId) -> &'hir Item<'hir>;
fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir>;
fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir>;
fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir>;
fn hir_body(&self, id: BodyId) -> &'hir Body<'hir>;
fn hir_item(&self, id: ItemId) -> &'hir Item<'hir>;
fn hir_trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir>;
fn hir_impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir>;
fn hir_foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir>;
}
// Used when no map is actually available, forcing manual implementation of nested visitors.
impl<'hir> Map<'hir> for ! {
// Used when no tcx is actually available, forcing manual implementation of nested visitors.
impl<'hir> HirTyCtxt<'hir> for ! {
fn hir_node(&self, _: HirId) -> Node<'hir> {
*self;
unreachable!();
}
fn hir_node_by_def_id(&self, _: LocalDefId) -> Node<'hir> {
*self;
fn hir_body(&self, _: BodyId) -> &'hir Body<'hir> {
unreachable!();
}
fn body(&self, _: BodyId) -> &'hir Body<'hir> {
*self;
fn hir_item(&self, _: ItemId) -> &'hir Item<'hir> {
unreachable!();
}
fn item(&self, _: ItemId) -> &'hir Item<'hir> {
*self;
fn hir_trait_item(&self, _: TraitItemId) -> &'hir TraitItem<'hir> {
unreachable!();
}
fn trait_item(&self, _: TraitItemId) -> &'hir TraitItem<'hir> {
*self;
fn hir_impl_item(&self, _: ImplItemId) -> &'hir ImplItem<'hir> {
unreachable!();
}
fn impl_item(&self, _: ImplItemId) -> &'hir ImplItem<'hir> {
*self;
}
fn foreign_item(&self, _: ForeignItemId) -> &'hir ForeignItem<'hir> {
*self;
fn hir_foreign_item(&self, _: ForeignItemId) -> &'hir ForeignItem<'hir> {
unreachable!();
}
}
pub mod nested_filter {
use super::Map;
use super::HirTyCtxt;
/// Specifies what nested things a visitor wants to visit. By "nested
/// things", we are referring to bits of HIR that are not directly embedded
@ -159,7 +157,7 @@ pub mod nested_filter {
/// See the comments at [`rustc_hir::intravisit`] for more details on the overall
/// visit strategy.
pub trait NestedFilter<'hir> {
type Map: Map<'hir>;
type MaybeTyCtxt: HirTyCtxt<'hir>;
/// Whether the visitor visits nested "item-like" things.
/// E.g., item, impl-item.
@ -175,10 +173,10 @@ pub mod nested_filter {
///
/// Use this if you are only walking some particular kind of tree
/// (i.e., a type, or fn signature) and you don't want to thread a
/// HIR map around.
/// `tcx` around.
pub struct None(());
impl NestedFilter<'_> for None {
type Map = !;
type MaybeTyCtxt = !;
const INTER: bool = false;
const INTRA: bool = false;
}
@ -203,18 +201,18 @@ use nested_filter::NestedFilter;
/// to monitor future changes to `Visitor` in case a new method with a
/// new default implementation gets introduced.)
pub trait Visitor<'v>: Sized {
// this type should not be overridden, it exists for convenient usage as `Self::Map`
type Map: Map<'v> = <Self::NestedFilter as NestedFilter<'v>>::Map;
// This type should not be overridden, it exists for convenient usage as `Self::MaybeTyCtxt`.
type MaybeTyCtxt: HirTyCtxt<'v> = <Self::NestedFilter as NestedFilter<'v>>::MaybeTyCtxt;
///////////////////////////////////////////////////////////////////////////
// Nested items.
/// Override this type to control which nested HIR are visited; see
/// [`NestedFilter`] for details. If you override this type, you
/// must also override [`nested_visit_map`](Self::nested_visit_map).
/// must also override [`maybe_tcx`](Self::maybe_tcx).
///
/// **If for some reason you want the nested behavior, but don't
/// have a `Map` at your disposal:** then override the
/// have a `tcx` at your disposal:** then override the
/// `visit_nested_XXX` methods. If a new `visit_nested_XXX` variant is
/// added in the future, it will cause a panic which can be detected
/// and fixed appropriately.
@ -226,9 +224,9 @@ pub trait Visitor<'v>: Sized {
/// If `type NestedFilter` is set to visit nested items, this method
/// must also be overridden to provide a map to retrieve nested items.
fn nested_visit_map(&mut self) -> Self::Map {
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
panic!(
"nested_visit_map must be implemented or consider using \
"maybe_tcx must be implemented or consider using \
`type NestedFilter = nested_filter::None` (the default)"
);
}
@ -240,10 +238,10 @@ pub trait Visitor<'v>: Sized {
/// "deep" visit patterns described at
/// [`rustc_hir::intravisit`]. The only reason to override
/// this method is if you want a nested pattern but cannot supply a
/// [`Map`]; see `nested_visit_map` for advice.
/// `TyCtxt`; see `maybe_tcx` for advice.
fn visit_nested_item(&mut self, id: ItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().item(id);
let item = self.maybe_tcx().hir_item(id);
try_visit!(self.visit_item(item));
}
Self::Result::output()
@ -254,7 +252,7 @@ pub trait Visitor<'v>: Sized {
/// method.
fn visit_nested_trait_item(&mut self, id: TraitItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().trait_item(id);
let item = self.maybe_tcx().hir_trait_item(id);
try_visit!(self.visit_trait_item(item));
}
Self::Result::output()
@ -265,7 +263,7 @@ pub trait Visitor<'v>: Sized {
/// method.
fn visit_nested_impl_item(&mut self, id: ImplItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().impl_item(id);
let item = self.maybe_tcx().hir_impl_item(id);
try_visit!(self.visit_impl_item(item));
}
Self::Result::output()
@ -276,7 +274,7 @@ pub trait Visitor<'v>: Sized {
/// method.
fn visit_nested_foreign_item(&mut self, id: ForeignItemId) -> Self::Result {
if Self::NestedFilter::INTER {
let item = self.nested_visit_map().foreign_item(id);
let item = self.maybe_tcx().hir_foreign_item(id);
try_visit!(self.visit_foreign_item(item));
}
Self::Result::output()
@ -287,7 +285,7 @@ pub trait Visitor<'v>: Sized {
/// `Self::NestedFilter`.
fn visit_nested_body(&mut self, id: BodyId) -> Self::Result {
if Self::NestedFilter::INTRA {
let body = self.nested_visit_map().body(id);
let body = self.maybe_tcx().hir_body(id);
try_visit!(self.visit_body(body));
}
Self::Result::output()

View file

@ -124,7 +124,7 @@ fn check_union_fields(tcx: TyCtxt<'_>, span: Span, item_def_id: LocalDefId) -> b
for field in &def.non_enum_variant().fields {
if !allowed_union_or_unsafe_field(tcx, field.ty(tcx, args), typing_env, span) {
let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
let (field_span, ty_span) = match tcx.hir_get_if_local(field.did) {
// We are currently checking the type this field came from, so it must be local.
Some(Node::Field(field)) => (field.span, field.ty.span),
_ => unreachable!("mir field has to correspond to hir field"),
@ -435,8 +435,8 @@ fn best_definition_site_of_opaque<'tcx>(
impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
type NestedFilter = nested_filter::All;
type Result = ControlFlow<(Span, LocalDefId)>;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) -> Self::Result {
if let hir::ExprKind::Closure(closure) = ex.kind {
@ -880,7 +880,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) {
.emit();
}
let item = tcx.hir().foreign_item(item.id);
let item = tcx.hir_foreign_item(item.id);
match &item.kind {
hir::ForeignItemKind::Fn(sig, _, _) => {
require_c_abi_if_c_variadic(tcx, sig.decl, abi, item.span);
@ -1494,7 +1494,7 @@ fn detect_discriminant_duplicate<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
// In the case the discriminant is both a duplicate and overflowed, let the user know
if let hir::Node::AnonConst(expr) =
tcx.hir_node_by_def_id(discr_def_id.expect_local())
&& let hir::ExprKind::Lit(lit) = &tcx.hir().body(expr.body).value.kind
&& 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
{

View file

@ -658,11 +658,10 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
"method `{}` has an incompatible return type for trait",
trait_m.name
);
let hir = tcx.hir();
infcx.err_ctxt().note_type_err(
&mut diag,
&cause,
hir.get_if_local(impl_m.def_id)
tcx.hir_get_if_local(impl_m.def_id)
.and_then(|node| node.fn_decl())
.map(|decl| (decl.output.span(), Cow::from("return type in trait"), false)),
Some(param_env.and(infer::ValuePairs::Terms(ExpectedFound {
@ -1123,15 +1122,14 @@ fn check_region_bounds_on_impl_item<'tcx>(
// the moment, give a kind of vague error message.
if trait_params != impl_params {
let span = tcx
.hir()
.get_generics(impl_m.def_id.expect_local())
.hir_get_generics(impl_m.def_id.expect_local())
.expect("expected impl item to have generics or else we can't compare them")
.span;
let mut generics_span = None;
let mut bounds_span = vec![];
let mut where_span = None;
if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
if let Some(trait_node) = tcx.hir_get_if_local(trait_m.def_id)
&& let Some(trait_generics) = trait_node.generics()
{
generics_span = Some(trait_generics.span);
@ -1146,7 +1144,7 @@ fn check_region_bounds_on_impl_item<'tcx>(
}
}
}
if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
if let Some(impl_node) = tcx.hir_get_if_local(impl_m.def_id)
&& let Some(impl_generics) = impl_node.generics()
{
let mut impl_bounds = 0;

View file

@ -96,7 +96,7 @@ pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
// This opaque also needs to be from the impl method -- otherwise,
// it's a refinement to a TAIT.
if !tcx.hir().get_if_local(impl_opaque.def_id).is_some_and(|node| {
if !tcx.hir_get_if_local(impl_opaque.def_id).is_some_and(|node| {
matches!(
node.expect_opaque_ty().origin,
hir::OpaqueTyOrigin::AsyncFn { parent, .. } | hir::OpaqueTyOrigin::FnReturn { parent, .. }
@ -327,7 +327,7 @@ fn report_mismatched_rpitit_signature<'tcx>(
hir::FnRetTy::Return(ty) => (ty.span, ty.span, "", ""),
};
let trait_return_span =
tcx.hir().get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
tcx.hir_get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
hir::FnRetTy::DefaultReturn(_) => tcx.def_span(trait_m_def_id),
hir::FnRetTy::Return(ty) => ty.span,
});

View file

@ -129,7 +129,7 @@ fn get_owner_return_paths(
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_node_by_def_id(parent_id).body_id().map(|body_id| {
let body = tcx.hir().body(body_id);
let body = tcx.hir_body(body_id);
let mut visitor = ReturnsVisitor::default();
visitor.visit_body(body);
(parent_id, visitor)

View file

@ -424,7 +424,7 @@ fn resolve_expr<'tcx>(visitor: &mut ScopeResolutionVisitor<'tcx>, expr: &'tcx hi
// that share the parent environment. We handle const blocks in
// `visit_inline_const`.
hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
let body = visitor.tcx.hir().body(body);
let body = visitor.tcx.hir_body(body);
visitor.visit_body(body);
}
hir::ExprKind::AssignOp(_, left_expr, right_expr) => {
@ -906,7 +906,7 @@ impl<'tcx> Visitor<'tcx> for ScopeResolutionVisitor<'tcx> {
resolve_local(self, Some(l.pat), l.init)
}
fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
let body = self.tcx.hir().body(c.body);
let body = self.tcx.hir_body(c.body);
self.visit_body(body);
}
}

View file

@ -1163,7 +1163,7 @@ fn check_type_defn<'tcx>(
// be refactored to check the instantiate-ability of the code better.
if let Some(def_id) = def_id.as_local()
&& let hir::Node::AnonConst(anon) = tcx.hir_node_by_def_id(def_id)
&& let expr = &tcx.hir().body(anon.body).value
&& let expr = &tcx.hir_body(anon.body).value
&& let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
&& let Res::Def(DefKind::ConstParam, _def_id) = path.res
{

View file

@ -679,7 +679,7 @@ fn infringing_fields_error<'tcx>(
suggest_constraining_type_params(
tcx,
tcx.hir().get_generics(impl_did).expect("impls always have generics"),
tcx.hir_get_generics(impl_did).expect("impls always have generics"),
&mut err,
bounds
.iter()

View file

@ -25,7 +25,7 @@ pub(crate) fn crate_inherent_impls(
let mut collect = InherentCollect { tcx, impls_map: Default::default() };
let mut res = Ok(());
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
res = res.and(collect.check_item(id));
}

View file

@ -18,7 +18,7 @@ pub(crate) fn crate_inherent_impls_overlap_check(
) -> Result<(), ErrorGuaranteed> {
let mut inherent_overlap_checker = InherentOverlapChecker { tcx };
let mut res = Ok(());
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
res = res.and(inherent_overlap_checker.check_item(id));
}
res

View file

@ -277,8 +277,8 @@ fn reject_placeholder_type_signatures_in_item<'tcx>(
impl<'tcx> Visitor<'tcx> for CollectItemTypesVisitor<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {
@ -669,7 +669,7 @@ fn get_new_lifetime_name<'tcx>(
#[instrument(level = "debug", skip_all)]
fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
let it = tcx.hir().item(item_id);
let it = tcx.hir_item(item_id);
debug!(item = %it.ident, id = %it.hir_id());
let def_id = item_id.owner_id.def_id;
let icx = ItemCtxt::new(tcx, def_id);
@ -683,7 +683,7 @@ fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
| hir::ItemKind::GlobalAsm(_) => {}
hir::ItemKind::ForeignMod { items, .. } => {
for item in *items {
let item = tcx.hir().foreign_item(item.id);
let item = tcx.hir_foreign_item(item.id);
tcx.ensure_ok().generics_of(item.owner_id);
tcx.ensure_ok().type_of(item.owner_id);
tcx.ensure_ok().predicates_of(item.owner_id);
@ -790,7 +790,7 @@ fn lower_item(tcx: TyCtxt<'_>, item_id: hir::ItemId) {
}
fn lower_trait_item(tcx: TyCtxt<'_>, trait_item_id: hir::TraitItemId) {
let trait_item = tcx.hir().trait_item(trait_item_id);
let trait_item = tcx.hir_trait_item(trait_item_id);
let def_id = trait_item_id.owner_id;
tcx.ensure_ok().generics_of(def_id);
let icx = ItemCtxt::new(tcx, def_id.def_id);
@ -865,7 +865,7 @@ fn lower_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::ImplItemId) {
tcx.ensure_ok().generics_of(def_id);
tcx.ensure_ok().type_of(def_id);
tcx.ensure_ok().predicates_of(def_id);
let impl_item = tcx.hir().impl_item(impl_item_id);
let impl_item = tcx.hir_impl_item(impl_item_id);
let icx = ItemCtxt::new(tcx, def_id.def_id);
match impl_item.kind {
hir::ImplItemKind::Fn(..) => {
@ -1769,7 +1769,7 @@ fn coroutine_for_closure(tcx: TyCtxt<'_>, def_id: LocalDefId) -> DefId {
..
}),
..
} = tcx.hir().body(body).value
} = tcx.hir_body(body).value
else {
bug!()
};

View file

@ -52,7 +52,7 @@ pub(crate) fn predicates_and_item_bounds(tcx: TyCtxt<'_>) {
}
pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
for iid in tcx.hir().items() {
for iid in tcx.hir_free_items() {
let did = iid.owner_id.def_id;
if tcx.has_attr(did, sym::rustc_dump_def_parents) {
struct AnonConstFinder<'tcx> {
@ -63,8 +63,8 @@ pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
impl<'tcx> intravisit::Visitor<'tcx> for AnonConstFinder<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_anon_const(&mut self, c: &'tcx rustc_hir::AnonConst) {
@ -77,7 +77,7 @@ pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
// the `rustc_dump_def_parents` attribute to the anon const so it would not be possible
// to see what its def parent is.
let mut anon_ct_finder = AnonConstFinder { tcx, anon_consts: vec![] };
intravisit::walk_item(&mut anon_ct_finder, tcx.hir().item(iid));
intravisit::walk_item(&mut anon_ct_finder, tcx.hir_item(iid));
for did in [did].into_iter().chain(anon_ct_finder.anon_consts) {
let span = tcx.def_span(did);
@ -99,14 +99,14 @@ pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
}
pub(crate) fn vtables<'tcx>(tcx: TyCtxt<'tcx>) {
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
let def_id = id.owner_id.def_id;
let Some(attr) = tcx.get_attr(def_id, sym::rustc_dump_vtable) else {
continue;
};
let vtable_entries = match tcx.hir().item(id).kind {
let vtable_entries = match tcx.hir_item(id).kind {
hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
let trait_ref = tcx.impl_trait_ref(def_id).unwrap().instantiate_identity();
if trait_ref.has_non_region_param() {

View file

@ -422,12 +422,12 @@ enum NonLifetimeBinderAllowed {
impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_nested_body(&mut self, body: hir::BodyId) {
let body = self.tcx.hir().body(body);
let body = self.tcx.hir_body(body);
self.with(Scope::Body { id: body.id(), s: self.scope }, |this| {
this.visit_body(body);
});
@ -1049,7 +1049,7 @@ fn object_lifetime_default(tcx: TyCtxt<'_>, param_def_id: LocalDefId) -> ObjectL
match param.source {
hir::GenericParamSource::Generics => {
let parent_def_id = tcx.local_parent(param_def_id);
let generics = tcx.hir().get_generics(parent_def_id).unwrap();
let generics = tcx.hir_get_generics(parent_def_id).unwrap();
let param_hir_id = tcx.local_def_id_to_hir_id(param_def_id);
let param = generics.params.iter().find(|p| p.hir_id == param_hir_id).unwrap();
@ -1250,7 +1250,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
if let Some(hir::PredicateOrigin::ImplTrait) = where_bound_origin
&& let hir::LifetimeName::Param(param_id) = lifetime_ref.res
&& let Some(generics) =
self.tcx.hir().get_generics(self.tcx.local_parent(param_id))
self.tcx.hir_get_generics(self.tcx.local_parent(param_id))
&& let Some(param) = generics.params.iter().find(|p| p.def_id == param_id)
&& param.is_elided_lifetime()
&& !self.tcx.asyncness(lifetime_ref.hir_id.owner.def_id).is_async()
@ -1264,7 +1264,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
);
if let Some(generics) =
self.tcx.hir().get_generics(lifetime_ref.hir_id.owner.def_id)
self.tcx.hir_get_generics(lifetime_ref.hir_id.owner.def_id)
{
let new_param_sugg =
if let Some(span) = generics.span_for_lifetime_suggestion() {
@ -2266,7 +2266,7 @@ fn is_late_bound_map(
owner_id: hir::OwnerId,
) -> Option<&FxIndexSet<hir::ItemLocalId>> {
let sig = tcx.hir().fn_sig_by_hir_id(owner_id.into())?;
let generics = tcx.hir().get_generics(owner_id.def_id)?;
let generics = tcx.hir_get_generics(owner_id.def_id)?;
let mut late_bound = FxIndexSet::default();

View file

@ -451,7 +451,7 @@ fn infer_placeholder_type<'tcx>(
);
} else {
with_forced_trimmed_paths!(err.span_note(
tcx.hir().body(body_id).value.span,
tcx.hir_body(body_id).value.span,
format!("however, the inferred type `{ty}` cannot be named"),
));
}
@ -494,7 +494,7 @@ fn infer_placeholder_type<'tcx>(
);
} else {
with_forced_trimmed_paths!(diag.span_note(
tcx.hir().body(body_id).value.span,
tcx.hir_body(body_id).value.span,
format!("however, the inferred type `{ty}` cannot be named"),
));
}

View file

@ -298,8 +298,8 @@ impl TaitConstraintLocator<'_> {
impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let hir::ExprKind::Closure(closure) = ex.kind {
@ -441,8 +441,8 @@ impl RpitConstraintChecker<'_> {
impl<'tcx> intravisit::Visitor<'tcx> for RpitConstraintChecker<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
if let hir::ExprKind::Closure(closure) = ex.kind {

View file

@ -451,7 +451,7 @@ impl<'a, 'tcx> WrongNumberOfGenericArgs<'a, 'tcx> {
)
});
let fn_sig = self.tcx.hir().get_if_local(self.def_id).and_then(hir::Node::fn_sig);
let fn_sig = self.tcx.hir_get_if_local(self.def_id).and_then(hir::Node::fn_sig);
let is_used_in_input = |def_id| {
fn_sig.is_some_and(|fn_sig| {
fn_sig.decl.inputs.iter().any(|ty| match ty.kind {

View file

@ -225,7 +225,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
&& let item_def_id =
tcx.hir().get_parent_item(tcx.local_def_id_to_hir_id(ty_param_def_id))
// FIXME: ...which obviously won't have any generics.
&& let Some(generics) = tcx.hir().get_generics(item_def_id.def_id)
&& let Some(generics) = tcx.hir_get_generics(item_def_id.def_id)
{
// FIXME: Suggest adding supertrait bounds if we have a `Self` type param.
// FIXME(trait_alias): Suggest adding `Self: Trait` to

View file

@ -110,7 +110,7 @@ fn generic_arg_mismatch_err(
err.help(format!("`{}` is a function item, not a type", tcx.item_name(id)));
err.help("function item types cannot be named directly");
} else if let hir::ConstArgKind::Anon(anon) = cnst.kind
&& let body = tcx.hir().body(anon.body)
&& let body = tcx.hir_body(anon.body)
&& let rustc_hir::ExprKind::Path(rustc_hir::QPath::Resolved(_, path)) =
body.value.kind
&& let Res::Def(DefKind::Fn { .. }, id) = path.res

View file

@ -1976,7 +1976,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
if let Some(hir::Node::Item(&hir::Item {
kind: hir::ItemKind::Impl(impl_),
..
})) = tcx.hir().get_if_local(def_id)
})) = tcx.hir_get_if_local(def_id)
{
err.span_note(impl_.self_ty.span, "not a concrete type");
}
@ -2213,7 +2213,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
fn lower_anon_const(&self, anon: &AnonConst) -> Const<'tcx> {
let tcx = self.tcx();
let expr = &tcx.hir().body(anon.body).value;
let expr = &tcx.hir_body(anon.body).value;
debug!(?expr);
let ty = tcx

View file

@ -3,7 +3,7 @@ use rustc_middle::ty::{self, TyCtxt};
use rustc_span::sym;
pub(crate) fn inferred_outlives(tcx: TyCtxt<'_>) {
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
if !tcx.has_attr(id.owner_id, sym::rustc_outlives) {
continue;
}

View file

@ -28,7 +28,7 @@ pub(super) fn infer_predicates(
let mut predicates_added = false;
// Visit all the crates and infer predicates
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
let item_did = id.owner_id;
debug!("InferVisitor::visit_item(item={:?})", item_did);

View file

@ -24,8 +24,8 @@ use rustc_span::source_map::SourceMap;
use rustc_span::{FileName, Ident, Span, Symbol, kw};
use {rustc_ast as ast, rustc_hir as hir};
pub fn id_to_string(map: &dyn rustc_hir::intravisit::Map<'_>, hir_id: HirId) -> String {
to_string(&map, |s| s.print_node(map.hir_node(hir_id)))
pub fn id_to_string(cx: &dyn rustc_hir::intravisit::HirTyCtxt<'_>, hir_id: HirId) -> String {
to_string(&cx, |s| s.print_node(cx.hir_node(hir_id)))
}
pub enum AnnNode<'a> {
@ -54,15 +54,15 @@ pub trait PpAnn {
fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {}
}
impl PpAnn for &dyn rustc_hir::intravisit::Map<'_> {
impl PpAnn for &dyn rustc_hir::intravisit::HirTyCtxt<'_> {
fn nested(&self, state: &mut State<'_>, nested: Nested) {
match nested {
Nested::Item(id) => state.print_item(self.item(id)),
Nested::TraitItem(id) => state.print_trait_item(self.trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.impl_item(id)),
Nested::ForeignItem(id) => state.print_foreign_item(self.foreign_item(id)),
Nested::Body(id) => state.print_expr(self.body(id).value),
Nested::BodyParamPat(id, i) => state.print_pat(self.body(id).params[i].pat),
Nested::Item(id) => state.print_item(self.hir_item(id)),
Nested::TraitItem(id) => state.print_trait_item(self.hir_trait_item(id)),
Nested::ImplItem(id) => state.print_impl_item(self.hir_impl_item(id)),
Nested::ForeignItem(id) => state.print_foreign_item(self.hir_foreign_item(id)),
Nested::Body(id) => state.print_expr(self.hir_body(id).value),
Nested::BodyParamPat(id, i) => state.print_pat(self.hir_body(id).params[i].pat),
}
}
}

View file

@ -708,8 +708,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& let Res::Local(_) = path.res
&& let [segment] = &path.segments
{
for id in self.tcx.hir().items() {
if let Some(node) = self.tcx.hir().get_if_local(id.owner_id.into())
for id in self.tcx.hir_free_items() {
if let Some(node) = self.tcx.hir_get_if_local(id.owner_id.into())
&& let hir::Node::Item(item) = node
&& let hir::ItemKind::Fn { .. } = item.kind
&& item.ident.name == segment.ident.name

View file

@ -51,7 +51,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let tcx = self.tcx;
let body = tcx.hir().body(closure.body);
let body = tcx.hir_body(closure.body);
let expr_def_id = closure.def_id;
// It's always helpful for inference if we know the kind of

View file

@ -1891,7 +1891,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
kind: hir::ExprKind::Closure(&hir::Closure { body, .. }),
..
}) = parent
&& !matches!(fcx.tcx.hir().body(body).value.kind, hir::ExprKind::Block(..))
&& !matches!(fcx.tcx.hir_body(body).value.kind, hir::ExprKind::Block(..))
{
fcx.suggest_missing_semicolon(&mut err, expr, expected, true);
}

View file

@ -727,7 +727,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ident,
kind: hir::ItemKind::Static(ty, ..) | hir::ItemKind::Const(ty, ..),
..
})) = self.tcx.hir().get_if_local(*def_id)
})) = self.tcx.hir_get_if_local(*def_id)
{
primary_span = ty.span;
secondary_span = ident.span;
@ -1173,7 +1173,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some(hir::Node::Item(hir::Item {
kind: hir::ItemKind::Impl(hir::Impl { self_ty, .. }),
..
})) = self.tcx.hir().get_if_local(*alias_to)
})) = self.tcx.hir_get_if_local(*alias_to)
{
err.span_label(self_ty.span, "this is the type of the `Self` literal");
}

View file

@ -1801,7 +1801,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
block: &'tcx hir::ConstBlock,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let body = self.tcx.hir().body(block.body);
let body = self.tcx.hir_body(block.body);
// Create a new function context.
let def_id = block.def_id;

View file

@ -687,7 +687,7 @@ impl<'tcx> Visitor<'tcx> for AnnotateUnitFallbackVisitor<'_, 'tcx> {
if let hir::ExprKind::Closure(&hir::Closure { body, .. })
| hir::ExprKind::ConstBlock(hir::ConstBlock { body, .. }) = expr.kind
{
self.visit_body(self.fcx.tcx.hir().body(body))?;
self.visit_body(self.fcx.tcx.hir_body(body))?;
}
// Try to suggest adding an explicit qself `()` to a trait method path.

View file

@ -640,7 +640,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let witness = Ty::new_coroutine_witness(self.tcx, expr_def_id.to_def_id(), args);
// Unify `interior` with `witness` and collect all the resulting obligations.
let span = self.tcx.hir().body(body_id).value.span;
let span = self.tcx.hir_body(body_id).value.span;
let ty::Infer(ty::InferTy::TyVar(_)) = interior.kind() else {
span_bug!(span, "coroutine interior witness not infer: {:?}", interior.kind())
};

View file

@ -2056,7 +2056,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
match node {
Node::Item(&hir::Item { kind: hir::ItemKind::Fn { body: body_id, .. }, .. })
| Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => {
let body = self.tcx.hir().body(body_id);
let body = self.tcx.hir_body(body_id);
if let ExprKind::Block(block, _) = &body.value.kind {
return Some(block.span);
}
@ -2512,11 +2512,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}
err.span_note(spans, format!("{} defined here", self.tcx.def_descr(def_id)));
} else if let Some(hir::Node::Expr(e)) = self.tcx.hir().get_if_local(def_id)
} else if let Some(hir::Node::Expr(e)) = self.tcx.hir_get_if_local(def_id)
&& let hir::ExprKind::Closure(hir::Closure { body, .. }) = &e.kind
{
let param = expected_idx
.and_then(|expected_idx| self.tcx.hir().body(*body).params.get(expected_idx));
.and_then(|expected_idx| self.tcx.hir_body(*body).params.get(expected_idx));
let (kind, span) = if let Some(param) = param {
// Try to find earlier invocations of this closure to find if the type mismatch
// is because of inference. If we find one, point at them.
@ -2650,7 +2650,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
is_method: bool,
) -> Option<(IndexVec<ExpectedIdx, (Option<GenericIdx>, FnParam<'_>)>, &hir::Generics<'_>)>
{
let (sig, generics, body_id, param_names) = match self.tcx.hir().get_if_local(def_id)? {
let (sig, generics, body_id, param_names) = match self.tcx.hir_get_if_local(def_id)? {
hir::Node::TraitItem(&hir::TraitItem {
generics,
kind: hir::TraitItemKind::Fn(sig, trait_fn),
@ -2695,7 +2695,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
match (body_id, param_names) {
(Some(_), Some(_)) | (None, None) => unreachable!(),
(Some(body), None) => {
let params = self.tcx.hir().body(body).params;
let params = self.tcx.hir_body(body).params;
let params =
params.get(is_method as usize..params.len() - sig.decl.c_variadic as usize)?;
debug_assert_eq!(params.len(), fn_inputs.len());
@ -2725,8 +2725,8 @@ struct FindClosureArg<'tcx> {
impl<'tcx> Visitor<'tcx> for FindClosureArg<'tcx> {
type NestedFilter = rustc_middle::hir::nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) {

View file

@ -1813,7 +1813,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
);
let owner = self.tcx.hir().enclosing_body_owner(expr.hir_id);
if let ty::Param(param) = expected_ty.kind()
&& let Some(generics) = self.tcx.hir().get_generics(owner)
&& let Some(generics) = self.tcx.hir_get_generics(owner)
{
suggest_constraining_type_params(
self.tcx,
@ -1933,7 +1933,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
..
} = init
{
let hir::Body { value: body_expr, .. } = self.tcx.hir().body(*body_id);
let hir::Body { value: body_expr, .. } = self.tcx.hir_body(*body_id);
self.note_type_is_not_clone_inner_expr(body_expr)
} else {
expr

View file

@ -123,7 +123,7 @@ fn typeck_with_inspect<'tcx>(
let body_id = node.body_id().unwrap_or_else(|| {
span_bug!(span, "can't type-check body of {:?}", def_id);
});
let body = tcx.hir().body(body_id);
let body = tcx.hir_body(body_id);
let param_env = tcx.param_env(def_id);

View file

@ -1091,7 +1091,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
continue;
}
match self.tcx.hir().get_if_local(item_def_id) {
match self.tcx.hir_get_if_local(item_def_id) {
// Unmet obligation comes from a `derive` macro, point at it once to
// avoid multiple span labels pointing at the same place.
Some(Node::Item(hir::Item {
@ -3753,19 +3753,17 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
hir::TraitFn::Required([ident, ..]) => {
ident.name == kw::SelfLower
}
hir::TraitFn::Provided(body_id) => self
.tcx
.hir()
.body(*body_id)
.params
.first()
.is_some_and(|param| {
matches!(
param.pat.kind,
hir::PatKind::Binding(_, _, ident, _)
if ident.name == kw::SelfLower
)
}),
hir::TraitFn::Provided(body_id) => {
self.tcx.hir_body(*body_id).params.first().is_some_and(
|param| {
matches!(
param.pat.kind,
hir::PatKind::Binding(_, _, ident, _)
if ident.name == kw::SelfLower
)
},
)
}
_ => false,
};
@ -3833,20 +3831,20 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if let Some(param) = param_type {
let generics = self.tcx.generics_of(self.body_id.to_def_id());
let type_param = generics.type_param(param, self.tcx);
let hir = self.tcx.hir();
let tcx = self.tcx;
if let Some(def_id) = type_param.def_id.as_local() {
let id = self.tcx.local_def_id_to_hir_id(def_id);
let id = tcx.local_def_id_to_hir_id(def_id);
// 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 self.tcx.hir_node(id) {
match tcx.hir_node(id) {
Node::GenericParam(param) => {
enum Introducer {
Plus,
Colon,
Nothing,
}
let hir_generics = hir.get_generics(id.owner.def_id).unwrap();
let hir_generics = tcx.hir_get_generics(id.owner.def_id).unwrap();
let trait_def_ids: DefIdSet = hir_generics
.bounds_for_param(def_id)
.flat_map(|bp| bp.bounds.iter())
@ -3866,8 +3864,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let candidate_strs: Vec<_> = candidates
.iter()
.map(|cand| {
let cand_path = self.tcx.def_path_str(cand.def_id);
let cand_params = &self.tcx.generics_of(cand.def_id).own_params;
let cand_path = tcx.def_path_str(cand.def_id);
let cand_params = &tcx.generics_of(cand.def_id).own_params;
let cand_args: String = cand_params
.iter()
.skip(1)
@ -3960,9 +3958,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
err.span_suggestions(
sp,
message(format!("add {article} supertrait for")),
candidates.iter().map(|t| {
format!("{} {}", sep, self.tcx.def_path_str(t.def_id),)
}),
candidates
.iter()
.map(|t| format!("{} {}", sep, tcx.def_path_str(t.def_id),)),
Applicability::MaybeIncorrect,
);
return;

View file

@ -1231,7 +1231,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
ident: Ident,
) -> bool {
match opt_def_id {
Some(def_id) => match self.tcx.hir().get_if_local(def_id) {
Some(def_id) => match self.tcx.hir_get_if_local(def_id) {
Some(hir::Node::Item(hir::Item {
kind: hir::ItemKind::Const(_, _, body_id),
..

View file

@ -143,7 +143,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
match expr.kind {
hir::ExprKind::Closure(&hir::Closure { capture_clause, body: body_id, .. }) => {
let body = self.fcx.tcx.hir().body(body_id);
let body = self.fcx.tcx.hir_body(body_id);
self.visit_body(body);
self.fcx.analyze_closure(expr.hir_id, expr.span, body_id, body, capture_clause);
}
@ -154,7 +154,7 @@ impl<'a, 'tcx> Visitor<'tcx> for InferBorrowKindVisitor<'a, 'tcx> {
}
fn visit_inline_const(&mut self, c: &'tcx hir::ConstBlock) {
let body = self.fcx.tcx.hir().body(c.body);
let body = self.fcx.tcx.hir_body(c.body);
self.visit_body(body);
}
}

View file

@ -249,7 +249,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
fn visit_const_block(&mut self, span: Span, anon_const: &hir::ConstBlock) {
self.visit_node_id(span, anon_const.hir_id);
let body = self.tcx().hir().body(anon_const.body);
let body = self.tcx().hir_body(anon_const.body);
self.visit_body(body);
}
}
@ -266,7 +266,7 @@ impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
match e.kind {
hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
let body = self.fcx.tcx.hir().body(body);
let body = self.fcx.tcx.hir_body(body);
for param in body.params {
self.visit_node_id(e.span, param.hir_id);
}

View file

@ -174,8 +174,8 @@ impl<'tcx> IfThisChanged<'tcx> {
impl<'tcx> Visitor<'tcx> for IfThisChanged<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {

View file

@ -455,8 +455,8 @@ impl<'tcx> FindAllAttrs<'tcx> {
impl<'tcx> intravisit::Visitor<'tcx> for FindAllAttrs<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_attribute(&mut self, attr: &'tcx Attribute) {

View file

@ -33,6 +33,10 @@ interface_ignoring_out_dir = ignoring --out-dir flag due to -o flag
interface_input_file_would_be_overwritten =
the input file "{$path}" would be overwritten by the generated executable
interface_limit_invalid =
`limit` must be a non-negative integer
.label = {$error_str}
interface_mixed_bin_crate =
cannot mix `bin` crate type with others

View file

@ -127,3 +127,13 @@ pub(crate) struct AbiRequiredTargetFeature<'a> {
pub feature: &'a str,
pub enabled: &'a str,
}
#[derive(Diagnostic)]
#[diag(interface_limit_invalid)]
pub(crate) struct LimitInvalid<'a> {
#[primary_span]
pub span: Span,
#[label]
pub value_span: Span,
pub error_str: &'a str,
}

View file

@ -10,6 +10,7 @@
mod callbacks;
pub mod errors;
pub mod interface;
mod limits;
pub mod passes;
mod proc_macro_decls;
mod queries;

View file

@ -1,61 +1,58 @@
//! Registering limits:
//! * recursion_limit,
//! * move_size_limit, and
//! * type_length_limit
//! - recursion_limit: there are various parts of the compiler that must impose arbitrary limits
//! on how deeply they recurse to prevent stack overflow.
//! - move_size_limit
//! - type_length_limit
//! - pattern_complexity_limit
//!
//! There are various parts of the compiler that must impose arbitrary limits
//! on how deeply they recurse to prevent stack overflow. Users can override
//! this via an attribute on the crate like `#![recursion_limit="22"]`. This pass
//! just peeks and looks for that attribute.
//! Users can override these limits via an attribute on the crate like
//! `#![recursion_limit="22"]`. This pass just looks for those attributes.
use std::num::IntErrorKind;
use rustc_ast::attr::AttributeExt;
use rustc_middle::bug;
use rustc_middle::query::Providers;
use rustc_session::{Limit, Limits, Session};
use rustc_span::{Symbol, sym};
use crate::error::LimitInvalid;
use crate::query::Providers;
use crate::errors::LimitInvalid;
pub fn provide(providers: &mut Providers) {
pub(crate) fn provide(providers: &mut Providers) {
providers.limits = |tcx, ()| Limits {
recursion_limit: get_recursion_limit(tcx.hir().krate_attrs(), tcx.sess),
move_size_limit: get_limit(
tcx.hir().krate_attrs(),
tcx.sess,
sym::move_size_limit,
tcx.sess.opts.unstable_opts.move_size_limit.unwrap_or(0),
Limit::new(tcx.sess.opts.unstable_opts.move_size_limit.unwrap_or(0)),
),
type_length_limit: get_limit(
tcx.hir().krate_attrs(),
tcx.sess,
sym::type_length_limit,
2usize.pow(24),
Limit::new(2usize.pow(24)),
),
pattern_complexity_limit: get_limit(
tcx.hir().krate_attrs(),
tcx.sess,
sym::pattern_complexity_limit,
Limit::unlimited(),
),
}
}
pub fn get_recursion_limit(krate_attrs: &[impl AttributeExt], sess: &Session) -> Limit {
get_limit(krate_attrs, sess, sym::recursion_limit, 128)
// This one is separate because it must be read prior to macro expansion.
pub(crate) fn get_recursion_limit(krate_attrs: &[impl AttributeExt], sess: &Session) -> Limit {
get_limit(krate_attrs, sess, sym::recursion_limit, Limit::new(128))
}
fn get_limit(
krate_attrs: &[impl AttributeExt],
sess: &Session,
name: Symbol,
default: usize,
default: Limit,
) -> Limit {
match get_limit_size(krate_attrs, sess, name) {
Some(size) => Limit::new(size),
None => Limit::new(default),
}
}
pub fn get_limit_size(
krate_attrs: &[impl AttributeExt],
sess: &Session,
name: Symbol,
) -> Option<usize> {
for attr in krate_attrs {
if !attr.has_name(name) {
continue;
@ -63,7 +60,7 @@ pub fn get_limit_size(
if let Some(sym) = attr.value_str() {
match sym.as_str().parse() {
Ok(n) => return Some(n),
Ok(n) => return Limit::new(n),
Err(e) => {
let error_str = match e.kind() {
IntErrorKind::PosOverflow => "`limit` is too large",
@ -84,5 +81,5 @@ pub fn get_limit_size(
}
}
}
None
default
}

View file

@ -39,7 +39,7 @@ use rustc_trait_selection::traits;
use tracing::{info, instrument};
use crate::interface::Compiler;
use crate::{errors, proc_macro_decls, util};
use crate::{errors, limits, proc_macro_decls, util};
pub fn parse<'a>(sess: &'a Session) -> ast::Crate {
let krate = sess
@ -687,6 +687,7 @@ pub static DEFAULT_QUERY_PROVIDERS: LazyLock<Providers> = LazyLock::new(|| {
|tcx, _| tcx.arena.alloc_from_iter(tcx.resolutions(()).stripped_cfg_items.steal());
providers.resolutions = |tcx, ()| tcx.resolver_for_lowering_raw(()).1;
providers.early_lint_checks = early_lint_checks;
limits::provide(providers);
proc_macro_decls::provide(providers);
rustc_const_eval::provide(providers);
rustc_middle::hir::provide(providers);
@ -1134,7 +1135,7 @@ fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit
// because that would require expanding this while in the middle of expansion, which needs to
// know the limit before expanding.
let _ = validate_and_find_value_str_builtin_attr(sym::recursion_limit, sess, krate_attrs);
rustc_middle::middle::limits::get_recursion_limit(krate_attrs, sess)
crate::limits::get_recursion_limit(krate_attrs, sess)
}
/// Validate *all* occurrences of the given "[value-str]" built-in attribute and return the first find.

View file

@ -7,7 +7,7 @@ use rustc_span::sym;
fn proc_macro_decls_static(tcx: TyCtxt<'_>, (): ()) -> Option<LocalDefId> {
let mut decls = None;
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
let attrs = tcx.hir().attrs(id.hir_id());
if attr::contains_name(attrs, sym::rustc_proc_macro_decls) {
decls = Some(id.owner_id.def_id);

View file

@ -439,11 +439,11 @@ lint_invalid_crate_type_value = invalid `crate_type` value
.suggestion = did you mean
# FIXME: we should ordinalize $valid_up_to when we add support for doing so
lint_invalid_from_utf8_checked = calls to `{$method}` with a invalid literal always return an error
lint_invalid_from_utf8_checked = calls to `{$method}` with an invalid literal always return an error
.label = the literal was valid UTF-8 up to the {$valid_up_to} bytes
# FIXME: we should ordinalize $valid_up_to when we add support for doing so
lint_invalid_from_utf8_unchecked = calls to `{$method}` with a invalid literal are undefined behavior
lint_invalid_from_utf8_unchecked = calls to `{$method}` with an invalid literal are undefined behavior
.label = the literal was valid UTF-8 up to the {$valid_up_to} bytes
lint_invalid_nan_comparisons_eq_ne = incorrect NaN comparison, NaN cannot be directly compared to itself

View file

@ -68,7 +68,7 @@ impl<'tcx> LateLintPass<'tcx> for AsyncClosureUsage {
return;
};
let mut body = cx.tcx.hir().body(body).value;
let mut body = cx.tcx.hir_body(body).value;
// Only peel blocks that have no expressions.
while let hir::ExprKind::Block(&hir::Block { stmts: [], expr: Some(tail), .. }, None) =

View file

@ -1057,7 +1057,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
check_no_mangle_on_generic_fn(
no_mangle_attr,
Some(generics),
cx.tcx.hir().get_generics(it.id.owner_id.def_id).unwrap(),
cx.tcx.hir_get_generics(it.id.owner_id.def_id).unwrap(),
it.span,
);
}

View file

@ -928,7 +928,7 @@ impl<'tcx> LateContext<'tcx> {
while let hir::ExprKind::Path(ref qpath) = expr.kind
&& let Some(parent_node) = match self.qpath_res(qpath, expr.hir_id) {
Res::Local(hir_id) => Some(self.tcx.parent_hir_node(hir_id)),
Res::Def(_, def_id) => self.tcx.hir().get_if_local(def_id),
Res::Def(_, def_id) => self.tcx.hir_get_if_local(def_id),
_ => None,
}
&& let Some(init) = match parent_node {
@ -936,7 +936,7 @@ impl<'tcx> LateContext<'tcx> {
hir::Node::LetStmt(hir::LetStmt { init, .. }) => *init,
hir::Node::Item(item) => match item.kind {
hir::ItemKind::Const(.., body_id) | hir::ItemKind::Static(.., body_id) => {
Some(self.tcx.hir().body(body_id).value)
Some(self.tcx.hir_body(body_id).value)
}
_ => None,
},

View file

@ -76,10 +76,8 @@ impl<'tcx> LateLintPass<'tcx> for DefaultCouldBeDerived {
// We now know we have a manually written definition of a `<Type as Default>::default()`.
let hir = cx.tcx.hir();
let type_def_id = def.did();
let body = hir.body(body_id);
let body = cx.tcx.hir_body(body_id);
// FIXME: evaluate bodies with statements and evaluate bindings to see if they would be
// derivable.
@ -92,7 +90,7 @@ impl<'tcx> LateLintPass<'tcx> for DefaultCouldBeDerived {
// Keep a mapping of field name to `hir::FieldDef` for every field in the type. We'll use
// these to check for things like checking whether it has a default or using its span for
// suggestions.
let orig_fields = match hir.get_if_local(type_def_id) {
let orig_fields = match cx.tcx.hir_get_if_local(type_def_id) {
Some(hir::Node::Item(hir::Item {
kind:
hir::ItemKind::Struct(hir::VariantData::Struct { fields, recovered: _ }, _generics),
@ -183,7 +181,7 @@ fn mk_lint(
if removed_all_fields {
let msg = "to avoid divergence in behavior between `Struct { .. }` and \
`<Struct as Default>::default()`, derive the `Default`";
if let Some(hir::Node::Item(impl_)) = tcx.hir().get_if_local(impl_def_id) {
if let Some(hir::Node::Item(impl_)) = tcx.hir_get_if_local(impl_def_id) {
diag.multipart_suggestion_verbose(
msg,
vec![

View file

@ -155,7 +155,7 @@ fn suggest_question_mark<'tcx>(
// Check that the function/closure/constant we are in has a `Result` type.
// Otherwise suggesting using `?` may not be a good idea.
{
let ty = cx.typeck_results().expr_ty(cx.tcx.hir().body(body_id).value);
let ty = cx.typeck_results().expr_ty(cx.tcx.hir_body(body_id).value);
let ty::Adt(ret_adt, ..) = ty.kind() else { return false };
if !cx.tcx.is_diagnostic_item(sym::Result, ret_adt.did()) {
return false;

View file

@ -70,12 +70,20 @@ impl<'tcx> LateLintPass<'tcx> for InvalidFromUtf8 {
sym::str_from_utf8_mut,
sym::str_from_utf8_unchecked,
sym::str_from_utf8_unchecked_mut,
sym::str_inherent_from_utf8,
sym::str_inherent_from_utf8_mut,
sym::str_inherent_from_utf8_unchecked,
sym::str_inherent_from_utf8_unchecked_mut,
]
.contains(&diag_item)
{
let lint = |label, utf8_error: Utf8Error| {
let method = diag_item.as_str().strip_prefix("str_").unwrap();
let method = format!("std::str::{method}");
let method = if let Some(method) = method.strip_prefix("inherent_") {
format!("str::{method}")
} else {
format!("std::str::{method}")
};
let valid_up_to = utf8_error.valid_up_to();
let is_unchecked_variant = diag_item.as_str().contains("unchecked");

View file

@ -84,8 +84,8 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas
/// Because lints are scoped lexically, we want to walk nested
/// items in the context of the outer item, so enable
/// deep-walking.
fn nested_visit_map(&mut self) -> Self::Map {
self.context.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.context.tcx
}
fn visit_nested_body(&mut self, body_id: hir::BodyId) {
@ -99,7 +99,7 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas
self.context.cached_typeck_results.set(None);
}
let body = self.context.tcx.hir().body(body_id);
let body = self.context.tcx.hir_body(body_id);
self.visit_body(body);
self.context.enclosing_body = old_enclosing_body;
@ -191,7 +191,7 @@ impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPas
// in order for `check_fn` to be able to use them.
let old_enclosing_body = self.context.enclosing_body.replace(body_id);
let old_cached_typeck_results = self.context.cached_typeck_results.take();
let body = self.context.tcx.hir().body(body_id);
let body = self.context.tcx.hir_body(body_id);
lint_callback!(self, check_fn, fk, decl, body, span, id);
hir_visit::walk_fn(self, fk, decl, body_id, id);
self.context.enclosing_body = old_enclosing_body;

View file

@ -270,8 +270,8 @@ impl<'tcx> LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> {
impl<'tcx> Visitor<'tcx> for LintLevelsBuilder<'_, LintLevelQueryMap<'tcx>> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.provider.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.provider.tcx
}
fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) {
@ -365,8 +365,8 @@ impl<'tcx> LintLevelMaximum<'tcx> {
impl<'tcx> Visitor<'tcx> for LintLevelMaximum<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
/// FIXME(blyxyas): In a future revision, we should also graph #![allow]s,

View file

@ -10,13 +10,13 @@ pub(crate) fn collect(tcx: TyCtxt<'_>, LocalCrate: LocalCrate) -> FxIndexMap<Def
let mut modules = FxIndexMap::default();
// We need to collect all the `ForeignMod`, even if they are empty.
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
if !matches!(tcx.def_kind(id.owner_id), DefKind::ForeignMod) {
continue;
}
let def_id = id.owner_id.to_def_id();
let item = tcx.hir().item(id);
let item = tcx.hir_item(id);
if let hir::ItemKind::ForeignMod { abi, items } = item.kind {
let foreign_items = items.iter().map(|it| it.id.owner_id.to_def_id()).collect();

View file

@ -1940,7 +1940,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
bug!("Unknown proc-macro type for item {:?}", id);
};
let mut def_key = self.tcx.hir().def_key(id);
let mut def_key = self.tcx.hir_def_key(id);
def_key.disambiguated_data.data = DefPathData::MacroNs(name);
let def_id = id.to_def_id();
@ -2076,7 +2076,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
let mut trait_impls: FxIndexMap<DefId, Vec<(DefIndex, Option<SimplifiedType>)>> =
FxIndexMap::default();
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
let DefKind::Impl { of_trait } = tcx.def_kind(id.owner_id) else {
continue;
};
@ -2410,7 +2410,6 @@ pub(crate) fn provide(providers: &mut Providers) {
/// use a different method for pretty-printing. Ideally this function
/// should only ever be used as a fallback.
pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: LocalDefId) -> String {
let hir = tcx.hir();
let value = body.value;
#[derive(PartialEq, Eq)]
@ -2467,7 +2466,7 @@ pub fn rendered_const<'tcx>(tcx: TyCtxt<'tcx>, body: &hir::Body<'_>, def_id: Loc
// Otherwise we prefer pretty-printing to get rid of extraneous whitespace, comments and
// other formatting artifacts.
Literal | Simple => id_to_string(&hir, body.id().hir_id),
Literal | Simple => id_to_string(&tcx, body.id().hir_id),
// FIXME: Omit the curly braces if the enclosing expression is an array literal
// with a repeated element (an `ExprKind::Repeat`) as in such case it

View file

@ -81,10 +81,6 @@ middle_failed_writing_file =
middle_layout_references_error =
the type has an unknown layout
middle_limit_invalid =
`limit` must be a non-negative integer
.label = {$error_str}
middle_opaque_hidden_type_mismatch =
concrete type differs from previous defining opaque type use
.label = expected `{$self_ty}`, got `{$other_ty}`

View file

@ -67,16 +67,6 @@ pub enum TypeMismatchReason {
},
}
#[derive(Diagnostic)]
#[diag(middle_limit_invalid)]
pub(crate) struct LimitInvalid<'a> {
#[primary_span]
pub span: Span,
#[label]
pub value_span: Span,
pub error_str: &'a str,
}
#[derive(Diagnostic)]
#[diag(middle_recursion_limit_reached)]
#[help]

View file

@ -93,7 +93,7 @@ impl<'hir> Iterator for ParentOwnerIterator<'hir> {
return None;
}
let parent_id = self.map.def_key(self.current_id.owner.def_id).parent;
let parent_id = self.map.tcx.hir_def_key(self.current_id.owner.def_id).parent;
let parent_id = parent_id.map_or(CRATE_OWNER_ID, |local_def_index| {
let def_id = LocalDefId { local_def_index };
self.map.tcx.local_def_id_to_hir_id(def_id).owner
@ -164,76 +164,74 @@ impl<'tcx> TyCtxt<'tcx> {
pub fn parent_hir_node(self, hir_id: HirId) -> Node<'tcx> {
self.hir_node(self.parent_hir_id(hir_id))
}
}
impl<'hir> Map<'hir> {
#[inline]
pub fn krate(self) -> &'hir Crate<'hir> {
self.tcx.hir_crate(())
}
#[inline]
pub fn root_module(self) -> &'hir Mod<'hir> {
match self.tcx.hir_owner_node(CRATE_OWNER_ID) {
pub fn hir_root_module(self) -> &'tcx Mod<'tcx> {
match self.hir_owner_node(CRATE_OWNER_ID) {
OwnerNode::Crate(item) => item,
_ => bug!(),
}
}
#[inline]
pub fn items(self) -> impl Iterator<Item = ItemId> + 'hir {
self.tcx.hir_crate_items(()).free_items.iter().copied()
pub fn hir_free_items(self) -> impl Iterator<Item = ItemId> + 'tcx {
self.hir_crate_items(()).free_items.iter().copied()
}
#[inline]
pub fn module_items(self, module: LocalModDefId) -> impl Iterator<Item = ItemId> + 'hir {
self.tcx.hir_module_items(module).free_items()
pub fn hir_module_free_items(
self,
module: LocalModDefId,
) -> impl Iterator<Item = ItemId> + 'tcx {
self.hir_module_items(module).free_items()
}
pub fn def_key(self, def_id: LocalDefId) -> DefKey {
pub fn hir_def_key(self, def_id: LocalDefId) -> DefKey {
// Accessing the DefKey is ok, since it is part of DefPathHash.
self.tcx.definitions_untracked().def_key(def_id)
self.definitions_untracked().def_key(def_id)
}
pub fn def_path(self, def_id: LocalDefId) -> DefPath {
pub fn hir_def_path(self, def_id: LocalDefId) -> DefPath {
// Accessing the DefPath is ok, since it is part of DefPathHash.
self.tcx.definitions_untracked().def_path(def_id)
self.definitions_untracked().def_path(def_id)
}
#[inline]
pub fn def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
pub fn hir_def_path_hash(self, def_id: LocalDefId) -> DefPathHash {
// Accessing the DefPathHash is ok, it is incr. comp. stable.
self.tcx.definitions_untracked().def_path_hash(def_id)
self.definitions_untracked().def_path_hash(def_id)
}
pub fn get_if_local(self, id: DefId) -> Option<Node<'hir>> {
id.as_local().map(|id| self.tcx.hir_node_by_def_id(id))
pub fn hir_get_if_local(self, id: DefId) -> Option<Node<'tcx>> {
id.as_local().map(|id| self.hir_node_by_def_id(id))
}
pub fn get_generics(self, id: LocalDefId) -> Option<&'hir Generics<'hir>> {
self.tcx.opt_hir_owner_node(id)?.generics()
pub fn hir_get_generics(self, id: LocalDefId) -> Option<&'tcx Generics<'tcx>> {
self.opt_hir_owner_node(id)?.generics()
}
pub fn item(self, id: ItemId) -> &'hir Item<'hir> {
self.tcx.hir_owner_node(id.owner_id).expect_item()
pub fn hir_item(self, id: ItemId) -> &'tcx Item<'tcx> {
self.hir_owner_node(id.owner_id).expect_item()
}
pub fn trait_item(self, id: TraitItemId) -> &'hir TraitItem<'hir> {
self.tcx.hir_owner_node(id.owner_id).expect_trait_item()
pub fn hir_trait_item(self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
self.hir_owner_node(id.owner_id).expect_trait_item()
}
pub fn impl_item(self, id: ImplItemId) -> &'hir ImplItem<'hir> {
self.tcx.hir_owner_node(id.owner_id).expect_impl_item()
pub fn hir_impl_item(self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
self.hir_owner_node(id.owner_id).expect_impl_item()
}
pub fn foreign_item(self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
self.tcx.hir_owner_node(id.owner_id).expect_foreign_item()
pub fn hir_foreign_item(self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
self.hir_owner_node(id.owner_id).expect_foreign_item()
}
pub fn body(self, id: BodyId) -> &'hir Body<'hir> {
self.tcx.hir_owner_nodes(id.hir_id.owner).bodies[&id.hir_id.local_id]
pub fn hir_body(self, id: BodyId) -> &'tcx Body<'tcx> {
self.hir_owner_nodes(id.hir_id.owner).bodies[&id.hir_id.local_id]
}
}
impl<'hir> Map<'hir> {
#[track_caller]
pub fn fn_decl_by_hir_id(self, hir_id: HirId) -> Option<&'hir FnDecl<'hir>> {
self.tcx.hir_node(hir_id).fn_decl()
@ -271,7 +269,7 @@ impl<'hir> Map<'hir> {
/// 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<&'hir Body<'hir>> {
Some(self.body(self.tcx.hir_node_by_def_id(id).body_id()?))
Some(self.tcx.hir_body(self.tcx.hir_node_by_def_id(id).body_id()?))
}
/// Given a body owner's id, returns the `BodyId` associated with it.
@ -288,7 +286,7 @@ impl<'hir> Map<'hir> {
}
pub fn body_param_names(self, id: BodyId) -> impl Iterator<Item = Ident> + 'hir {
self.body(id).params.iter().map(|arg| match arg.pat.kind {
self.tcx.hir_body(id).params.iter().map(|arg| match arg.pat.kind {
PatKind::Binding(_, _, ident, _) => ident,
_ => Ident::empty(),
})
@ -410,7 +408,7 @@ impl<'hir> Map<'hir> {
where
V: Visitor<'hir>,
{
let krate = self.krate();
let krate = self.tcx.hir_crate(());
for info in krate.owners.iter() {
if let MaybeOwner::Owner(info) = info {
for attrs in info.attrs.map.values() {
@ -436,13 +434,21 @@ impl<'hir> Map<'hir> {
V: Visitor<'hir>,
{
let krate = self.tcx.hir_crate_items(());
walk_list!(visitor, visit_item, krate.free_items().map(|id| self.item(id)));
walk_list!(visitor, visit_trait_item, krate.trait_items().map(|id| self.trait_item(id)));
walk_list!(visitor, visit_impl_item, krate.impl_items().map(|id| self.impl_item(id)));
walk_list!(visitor, visit_item, krate.free_items().map(|id| self.tcx.hir_item(id)));
walk_list!(
visitor,
visit_trait_item,
krate.trait_items().map(|id| self.tcx.hir_trait_item(id))
);
walk_list!(
visitor,
visit_impl_item,
krate.impl_items().map(|id| self.tcx.hir_impl_item(id))
);
walk_list!(
visitor,
visit_foreign_item,
krate.foreign_items().map(|id| self.foreign_item(id))
krate.foreign_items().map(|id| self.tcx.hir_foreign_item(id))
);
V::Result::output()
}
@ -454,13 +460,21 @@ impl<'hir> Map<'hir> {
V: Visitor<'hir>,
{
let module = self.tcx.hir_module_items(module);
walk_list!(visitor, visit_item, module.free_items().map(|id| self.item(id)));
walk_list!(visitor, visit_trait_item, module.trait_items().map(|id| self.trait_item(id)));
walk_list!(visitor, visit_impl_item, module.impl_items().map(|id| self.impl_item(id)));
walk_list!(visitor, visit_item, module.free_items().map(|id| self.tcx.hir_item(id)));
walk_list!(
visitor,
visit_trait_item,
module.trait_items().map(|id| self.tcx.hir_trait_item(id))
);
walk_list!(
visitor,
visit_impl_item,
module.impl_items().map(|id| self.tcx.hir_impl_item(id))
);
walk_list!(
visitor,
visit_foreign_item,
module.foreign_items().map(|id| self.foreign_item(id))
module.foreign_items().map(|id| self.tcx.hir_foreign_item(id))
);
V::Result::output()
}
@ -921,7 +935,7 @@ impl<'hir> Map<'hir> {
Node::Variant(variant) => variant.span,
Node::Field(field) => field.span,
Node::AnonConst(constant) => constant.span,
Node::ConstBlock(constant) => self.body(constant.body).value.span,
Node::ConstBlock(constant) => self.tcx.hir_body(constant.body).value.span,
Node::ConstArg(const_arg) => const_arg.span(),
Node::Expr(expr) => expr.span,
Node::ExprField(field) => field.span,
@ -1014,39 +1028,35 @@ impl<'hir> Map<'hir> {
}
}
impl<'hir> intravisit::Map<'hir> for Map<'hir> {
fn hir_node(&self, hir_id: HirId) -> Node<'hir> {
self.tcx.hir_node(hir_id)
impl<'tcx> intravisit::HirTyCtxt<'tcx> for TyCtxt<'tcx> {
fn hir_node(&self, hir_id: HirId) -> Node<'tcx> {
(*self).hir_node(hir_id)
}
fn hir_node_by_def_id(&self, def_id: LocalDefId) -> Node<'hir> {
self.tcx.hir_node_by_def_id(def_id)
fn hir_body(&self, id: BodyId) -> &'tcx Body<'tcx> {
(*self).hir_body(id)
}
fn body(&self, id: BodyId) -> &'hir Body<'hir> {
(*self).body(id)
fn hir_item(&self, id: ItemId) -> &'tcx Item<'tcx> {
(*self).hir_item(id)
}
fn item(&self, id: ItemId) -> &'hir Item<'hir> {
(*self).item(id)
fn hir_trait_item(&self, id: TraitItemId) -> &'tcx TraitItem<'tcx> {
(*self).hir_trait_item(id)
}
fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir> {
(*self).trait_item(id)
fn hir_impl_item(&self, id: ImplItemId) -> &'tcx ImplItem<'tcx> {
(*self).hir_impl_item(id)
}
fn impl_item(&self, id: ImplItemId) -> &'hir ImplItem<'hir> {
(*self).impl_item(id)
}
fn foreign_item(&self, id: ForeignItemId) -> &'hir ForeignItem<'hir> {
(*self).foreign_item(id)
fn hir_foreign_item(&self, id: ForeignItemId) -> &'tcx ForeignItem<'tcx> {
(*self).hir_foreign_item(id)
}
}
impl<'tcx> pprust_hir::PpAnn for TyCtxt<'tcx> {
fn nested(&self, state: &mut pprust_hir::State<'_>, nested: pprust_hir::Nested) {
pprust_hir::PpAnn::nested(&(&self.hir() as &dyn intravisit::Map<'_>), state, nested)
pprust_hir::PpAnn::nested(&(self as &dyn intravisit::HirTyCtxt<'_>), state, nested)
}
}
@ -1333,8 +1343,8 @@ impl<'tcx> ItemCollector<'tcx> {
impl<'hir> Visitor<'hir> for ItemCollector<'hir> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'hir Item<'hir>) {

View file

@ -1,5 +1,7 @@
use rustc_hir::intravisit::nested_filter::NestedFilter;
use crate::ty::TyCtxt;
/// Do not visit nested item-like things, but visit nested things
/// that are inside of an item-like.
///
@ -12,8 +14,8 @@ use rustc_hir::intravisit::nested_filter::NestedFilter;
/// and to have the visitor that visits the contents of each item
/// using this setting.
pub struct OnlyBodies(());
impl<'hir> NestedFilter<'hir> for OnlyBodies {
type Map = crate::hir::map::Map<'hir>;
impl<'tcx> NestedFilter<'tcx> for OnlyBodies {
type MaybeTyCtxt = TyCtxt<'tcx>;
const INTER: bool = false;
const INTRA: bool = true;
}
@ -24,8 +26,8 @@ impl<'hir> NestedFilter<'hir> for OnlyBodies {
/// process everything within their lexical context. Typically you
/// kick off the visit by doing `walk_krate()`.
pub struct All(());
impl<'hir> NestedFilter<'hir> for All {
type Map = crate::hir::map::Map<'hir>;
impl<'tcx> NestedFilter<'tcx> for All {
type MaybeTyCtxt = TyCtxt<'tcx>;
const INTER: bool = true;
const INTRA: bool = true;
}

View file

@ -30,12 +30,7 @@ pub mod lib_features {
}
}
}
pub mod limits;
pub mod privacy;
pub mod region;
pub mod resolve_bound_vars;
pub mod stability;
pub fn provide(providers: &mut crate::query::Providers) {
limits::provide(providers);
}

View file

@ -2168,6 +2168,10 @@ impl<'tcx> TyCtxt<'tcx> {
self.limits(()).move_size_limit
}
pub fn pattern_complexity_limit(self) -> Limit {
self.limits(()).pattern_complexity_limit
}
/// All traits in the crate graph, including those not visible to the user.
pub fn all_traits(self) -> impl Iterator<Item = DefId> + 'tcx {
iter::once(LOCAL_CRATE)

View file

@ -2168,7 +2168,6 @@ pub fn provide(providers: &mut Providers) {
util::provide(providers);
print::provide(providers);
super::util::bug::provide(providers);
super::middle::provide(providers);
*providers = Providers {
trait_impls_of: trait_def::trait_impls_of_provider,
incoherent_impls: trait_def::incoherent_impls_provider,

View file

@ -3299,13 +3299,12 @@ define_print_and_forward_display! {
fn for_each_def(tcx: TyCtxt<'_>, mut collect_fn: impl for<'b> FnMut(&'b Ident, Namespace, DefId)) {
// Iterate all local crate items no matter where they are defined.
let hir = tcx.hir();
for id in hir.items() {
for id in tcx.hir_free_items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::Use) {
continue;
}
let item = hir.item(id);
let item = tcx.hir_item(id);
if item.ident.name == kw::Empty {
continue;
}

View file

@ -267,7 +267,7 @@ pub(super) fn incoherent_impls_provider(tcx: TyCtxt<'_>, simp: SimplifiedType) -
pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
let mut traits = Vec::new();
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::Trait | DefKind::TraitAlias) {
traits.push(id.owner_id.to_def_id())
}
@ -278,7 +278,7 @@ pub(super) fn traits_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
pub(super) fn trait_impls_in_crate_provider(tcx: TyCtxt<'_>, _: LocalCrate) -> &[DefId] {
let mut trait_impls = Vec::new();
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
if matches!(tcx.def_kind(id.owner_id), DefKind::Impl { .. })
&& tcx.impl_trait_ref(id.owner_id).is_some()
{

View file

@ -53,7 +53,7 @@ impl<'tcx> Value<TyCtxt<'tcx>> for ty::Binder<'_, ty::FnSig<'_>> {
let arity = if let Some(frame) = cycle_error.cycle.get(0)
&& frame.query.dep_kind == dep_kinds::fn_sig
&& let Some(def_id) = frame.query.def_id
&& let Some(node) = tcx.hir().get_if_local(def_id)
&& let Some(node) = tcx.hir_get_if_local(def_id)
&& let Some(sig) = node.fn_sig()
{
sig.decl.inputs.len()

View file

@ -759,7 +759,7 @@ impl UnsafeOpKind {
});
let unsafe_not_inherited_note = if should_suggest {
suggest_unsafe_block.then(|| {
let body_span = tcx.hir().body(parent_owner.body_id().unwrap()).value.span;
let body_span = tcx.hir_body(parent_owner.body_id().unwrap()).value.span;
UnsafeNotInheritedLintNote {
signature_span: tcx.def_span(parent_id.def_id),
body_span,

View file

@ -601,8 +601,7 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NonExhaustivePatternsTypeNo
let def_span = self
.cx
.tcx
.hir()
.get_if_local(def.did())
.hir_get_if_local(def.did())
.and_then(|node| node.ident())
.map(|ident| ident.span)
.unwrap_or_else(|| self.cx.tcx.def_span(def.did()));
@ -1113,9 +1112,6 @@ pub(crate) struct Rust2024IncompatiblePatSugg {
pub(crate) suggestion: Vec<(Span, String)>,
pub(crate) ref_pattern_count: usize,
pub(crate) binding_mode_count: usize,
/// Internal state: the ref-mutability of the default binding mode at the subpattern being
/// lowered, with the span where it was introduced. `None` for a by-value default mode.
pub(crate) default_mode_span: Option<(Span, ty::Mutability)>,
/// Labels for where incompatibility-causing by-ref default binding modes were introduced.
pub(crate) default_mode_labels: FxIndexMap<Span, ty::Mutability>,
}

View file

@ -10,7 +10,6 @@ use rustc_hir::{self as hir, BindingMode, ByRef, HirId};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::Level;
use rustc_middle::bug;
use rustc_middle::middle::limits::get_limit_size;
use rustc_middle::thir::visit::Visitor;
use rustc_middle::thir::*;
use rustc_middle::ty::print::with_no_trimmed_paths;
@ -25,7 +24,7 @@ use rustc_session::lint::builtin::{
};
use rustc_span::edit_distance::find_best_match_for_name;
use rustc_span::hygiene::DesugaringKind;
use rustc_span::{Ident, Span, sym};
use rustc_span::{Ident, Span};
use rustc_trait_selection::infer::InferCtxtExt;
use tracing::instrument;
@ -404,18 +403,11 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
arms: &[MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
let pattern_complexity_limit =
get_limit_size(cx.tcx.hir().krate_attrs(), cx.tcx.sess, sym::pattern_complexity);
let report = rustc_pattern_analysis::rustc::analyze_match(
&cx,
&arms,
scrut_ty,
pattern_complexity_limit,
)
.map_err(|err| {
self.error = Err(err);
err
})?;
let report =
rustc_pattern_analysis::rustc::analyze_match(&cx, &arms, scrut_ty).map_err(|err| {
self.error = Err(err);
err
})?;
// Warn unreachable subpatterns.
for (arm, is_useful) in report.arm_usefulness.iter() {
@ -1498,7 +1490,7 @@ fn report_adt_defined_here<'tcx>(
return None;
};
let adt_def_span =
tcx.hir().get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
tcx.hir_get_if_local(def.did()).and_then(|node| node.ident()).map(|ident| ident.span);
let adt_def_span = if point_at_non_local_ty {
adt_def_span.unwrap_or_else(|| tcx.def_span(def.did()))
} else {

View file

@ -0,0 +1,182 @@
//! Automatic migration of Rust 2021 patterns to a form valid in both Editions 2021 and 2024.
use rustc_data_structures::fx::FxIndexMap;
use rustc_errors::MultiSpan;
use rustc_hir::{BindingMode, ByRef, HirId, Mutability};
use rustc_lint as lint;
use rustc_middle::span_bug;
use rustc_middle::ty::{self, Rust2024IncompatiblePatInfo, Ty, TyCtxt};
use rustc_span::{Ident, Span};
use crate::errors::{Rust2024IncompatiblePat, Rust2024IncompatiblePatSugg};
use crate::fluent_generated as fluent;
/// For patterns flagged for migration during HIR typeck, this handles constructing and emitting
/// a diagnostic suggestion.
pub(super) struct PatMigration<'a> {
suggestion: Vec<(Span, String)>,
ref_pattern_count: usize,
binding_mode_count: usize,
/// Internal state: the ref-mutability of the default binding mode at the subpattern being
/// lowered, with the span where it was introduced. `None` for a by-value default mode.
default_mode_span: Option<(Span, ty::Mutability)>,
/// Labels for where incompatibility-causing by-ref default binding modes were introduced.
// FIXME(ref_pat_eat_one_layer_2024_structural): To track the default binding mode, we duplicate
// logic from HIR typeck (in order to avoid needing to store all changes to the dbm in
// TypeckResults). Since the default binding mode acts differently under this feature gate, the
// labels will be wrong.
default_mode_labels: FxIndexMap<Span, Mutability>,
/// Information collected from typeck, including spans for subpatterns invalid in Rust 2024.
info: &'a Rust2024IncompatiblePatInfo,
}
impl<'a> PatMigration<'a> {
pub(super) fn new(info: &'a Rust2024IncompatiblePatInfo) -> Self {
PatMigration {
suggestion: Vec::new(),
ref_pattern_count: 0,
binding_mode_count: 0,
default_mode_span: None,
default_mode_labels: Default::default(),
info,
}
}
/// On Rust 2024, this emits a hard error. On earlier Editions, this emits the
/// future-incompatibility lint `rust_2024_incompatible_pat`.
pub(super) fn emit<'tcx>(self, tcx: TyCtxt<'tcx>, pat_id: HirId) {
let mut spans =
MultiSpan::from_spans(self.info.primary_labels.iter().map(|(span, _)| *span).collect());
for (span, label) in self.info.primary_labels.iter() {
spans.push_span_label(*span, label.clone());
}
let sugg = Rust2024IncompatiblePatSugg {
suggest_eliding_modes: self.info.suggest_eliding_modes,
suggestion: self.suggestion,
ref_pattern_count: self.ref_pattern_count,
binding_mode_count: self.binding_mode_count,
default_mode_labels: self.default_mode_labels,
};
// If a relevant span is from at least edition 2024, this is a hard error.
let is_hard_error = spans.primary_spans().iter().any(|span| span.at_least_rust_2024());
if is_hard_error {
let mut err =
tcx.dcx().struct_span_err(spans, fluent::mir_build_rust_2024_incompatible_pat);
if let Some(info) = lint::builtin::RUST_2024_INCOMPATIBLE_PAT.future_incompatible {
// provide the same reference link as the lint
err.note(format!("for more information, see {}", info.reference));
}
err.arg("bad_modifiers", self.info.bad_modifiers);
err.arg("bad_ref_pats", self.info.bad_ref_pats);
err.arg("is_hard_error", true);
err.subdiagnostic(sugg);
err.emit();
} else {
tcx.emit_node_span_lint(
lint::builtin::RUST_2024_INCOMPATIBLE_PAT,
pat_id,
spans,
Rust2024IncompatiblePat {
sugg,
bad_modifiers: self.info.bad_modifiers,
bad_ref_pats: self.info.bad_ref_pats,
is_hard_error,
},
);
}
}
/// Tracks when we're lowering a pattern that implicitly dereferences the scrutinee.
/// This should only be called when the pattern type adjustments list `adjustments` is
/// non-empty. Returns the prior default binding mode; this should be followed by a call to
/// [`PatMigration::leave_ref`] to restore it when we leave the pattern.
pub(super) fn visit_implicit_derefs<'tcx>(
&mut self,
pat_span: Span,
adjustments: &[Ty<'tcx>],
) -> Option<(Span, Mutability)> {
let implicit_deref_mutbls = adjustments.iter().map(|ref_ty| {
let &ty::Ref(_, _, mutbl) = ref_ty.kind() else {
span_bug!(pat_span, "pattern implicitly dereferences a non-ref type");
};
mutbl
});
if !self.info.suggest_eliding_modes {
// If we can't fix the pattern by eliding modifiers, we'll need to make the pattern
// fully explicit. i.e. we'll need to suggest reference patterns for this.
let suggestion_str: String =
implicit_deref_mutbls.clone().map(|mutbl| mutbl.ref_prefix_str()).collect();
self.suggestion.push((pat_span.shrink_to_lo(), suggestion_str));
self.ref_pattern_count += adjustments.len();
}
// Remember if this changed the default binding mode, in case we want to label it.
let min_mutbl = implicit_deref_mutbls.min().unwrap();
if self.default_mode_span.is_none_or(|(_, old_mutbl)| min_mutbl < old_mutbl) {
// This changes the default binding mode to `ref` or `ref mut`. Return the old mode so
// it can be reinstated when we leave the pattern.
self.default_mode_span.replace((pat_span, min_mutbl))
} else {
// This does not change the default binding mode; it was already `ref` or `ref mut`.
self.default_mode_span
}
}
/// Tracks the default binding mode when we're lowering a `&` or `&mut` pattern.
/// Returns the prior default binding mode; this should be followed by a call to
/// [`PatMigration::leave_ref`] to restore it when we leave the pattern.
pub(super) fn visit_explicit_deref(&mut self) -> Option<(Span, Mutability)> {
if let Some((default_mode_span, default_ref_mutbl)) = self.default_mode_span {
// If this eats a by-ref default binding mode, label the binding mode.
self.default_mode_labels.insert(default_mode_span, default_ref_mutbl);
}
// Set the default binding mode to by-value and return the old default binding mode so it
// can be reinstated when we leave the pattern.
self.default_mode_span.take()
}
/// Restores the default binding mode after lowering a pattern that could change it.
/// This should follow a call to either [`PatMigration::visit_explicit_deref`] or
/// [`PatMigration::visit_implicit_derefs`].
pub(super) fn leave_ref(&mut self, old_mode_span: Option<(Span, Mutability)>) {
self.default_mode_span = old_mode_span
}
/// Determines if a binding is relevant to the diagnostic and adjusts the notes/suggestion if
/// so. Bindings are relevant if they have a modifier under a by-ref default mode (invalid in
/// Rust 2024) or if we need to suggest a binding modifier for them.
pub(super) fn visit_binding(
&mut self,
pat_span: Span,
mode: BindingMode,
explicit_ba: BindingMode,
ident: Ident,
) {
if explicit_ba != BindingMode::NONE
&& let Some((default_mode_span, default_ref_mutbl)) = self.default_mode_span
{
// If this overrides a by-ref default binding mode, label the binding mode.
self.default_mode_labels.insert(default_mode_span, default_ref_mutbl);
// If our suggestion is to elide redundnt modes, this will be one of them.
if self.info.suggest_eliding_modes {
self.suggestion.push((pat_span.with_hi(ident.span.lo()), String::new()));
self.binding_mode_count += 1;
}
}
if !self.info.suggest_eliding_modes
&& explicit_ba.0 == ByRef::No
&& let ByRef::Yes(mutbl) = mode.0
{
// If we can't fix the pattern by eliding modifiers, we'll need to make the pattern
// fully explicit. i.e. we'll need to suggest reference patterns for this.
let sugg_str = match mutbl {
Mutability::Not => "ref ",
Mutability::Mut => "ref mut ",
};
self.suggestion
.push((pat_span.with_lo(ident.span.lo()).shrink_to_lo(), sugg_str.to_owned()));
self.binding_mode_count += 1;
}
}
}

View file

@ -2,18 +2,17 @@
mod check_match;
mod const_to_pat;
mod migration;
use std::cmp::Ordering;
use std::sync::Arc;
use rustc_abi::{FieldIdx, Integer};
use rustc_errors::MultiSpan;
use rustc_errors::codes::*;
use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::pat_util::EnumerateAndAdjustIterator;
use rustc_hir::{self as hir, ByRef, Mutability, RangeEnd};
use rustc_hir::{self as hir, RangeEnd};
use rustc_index::Idx;
use rustc_lint as lint;
use rustc_middle::mir::interpret::LitToConstInput;
use rustc_middle::thir::{
Ascription, FieldPat, LocalVarId, Pat, PatKind, PatRange, PatRangeBoundary,
@ -26,8 +25,8 @@ use rustc_span::{ErrorGuaranteed, Span};
use tracing::{debug, instrument};
pub(crate) use self::check_match::check_match;
use self::migration::PatMigration;
use crate::errors::*;
use crate::fluent_generated as fluent;
struct PatCtxt<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
@ -35,7 +34,7 @@ struct PatCtxt<'a, 'tcx> {
typeck_results: &'a ty::TypeckResults<'tcx>,
/// Used by the Rust 2024 migration lint.
rust_2024_migration_suggestion: Option<Rust2024IncompatiblePatSugg>,
rust_2024_migration: Option<PatMigration<'a>>,
}
pub(super) fn pat_from_hir<'a, 'tcx>(
@ -44,59 +43,19 @@ pub(super) fn pat_from_hir<'a, 'tcx>(
typeck_results: &'a ty::TypeckResults<'tcx>,
pat: &'tcx hir::Pat<'tcx>,
) -> Box<Pat<'tcx>> {
let migration_info = typeck_results.rust_2024_migration_desugared_pats().get(pat.hir_id);
let mut pcx = PatCtxt {
tcx,
typing_env,
typeck_results,
rust_2024_migration_suggestion: migration_info.and_then(|info| {
Some(Rust2024IncompatiblePatSugg {
suggest_eliding_modes: info.suggest_eliding_modes,
suggestion: Vec::new(),
ref_pattern_count: 0,
binding_mode_count: 0,
default_mode_span: None,
default_mode_labels: Default::default(),
})
}),
rust_2024_migration: typeck_results
.rust_2024_migration_desugared_pats()
.get(pat.hir_id)
.map(PatMigration::new),
};
let result = pcx.lower_pattern(pat);
debug!("pat_from_hir({:?}) = {:?}", pat, result);
if let Some(info) = migration_info
&& let Some(sugg) = pcx.rust_2024_migration_suggestion
{
let mut spans =
MultiSpan::from_spans(info.primary_labels.iter().map(|(span, _)| *span).collect());
for (span, label) in &info.primary_labels {
spans.push_span_label(*span, label.clone());
}
// If a relevant span is from at least edition 2024, this is a hard error.
let is_hard_error = spans.primary_spans().iter().any(|span| span.at_least_rust_2024());
if is_hard_error {
let mut err =
tcx.dcx().struct_span_err(spans, fluent::mir_build_rust_2024_incompatible_pat);
if let Some(lint_info) = lint::builtin::RUST_2024_INCOMPATIBLE_PAT.future_incompatible {
// provide the same reference link as the lint
err.note(format!("for more information, see {}", lint_info.reference));
}
err.arg("bad_modifiers", info.bad_modifiers);
err.arg("bad_ref_pats", info.bad_ref_pats);
err.arg("is_hard_error", true);
err.subdiagnostic(sugg);
err.emit();
} else {
tcx.emit_node_span_lint(
lint::builtin::RUST_2024_INCOMPATIBLE_PAT,
pat.hir_id,
spans,
Rust2024IncompatiblePat {
sugg,
bad_modifiers: info.bad_modifiers,
bad_ref_pats: info.bad_ref_pats,
is_hard_error,
},
);
}
if let Some(m) = pcx.rust_2024_migration {
m.emit(tcx, pat.hir_id);
}
result
}
@ -106,31 +65,13 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
let adjustments: &[Ty<'tcx>] =
self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(&[], |v| &**v);
// Track the default binding mode for the Rust 2024 migration suggestion.
let mut opt_old_mode_span = None;
if let Some(s) = &mut self.rust_2024_migration_suggestion
if let Some(s) = &mut self.rust_2024_migration
&& !adjustments.is_empty()
{
let implicit_deref_mutbls = adjustments.iter().map(|ref_ty| {
let &ty::Ref(_, _, mutbl) = ref_ty.kind() else {
span_bug!(pat.span, "pattern implicitly dereferences a non-ref type");
};
mutbl
});
if !s.suggest_eliding_modes {
let suggestion_str: String =
implicit_deref_mutbls.clone().map(|mutbl| mutbl.ref_prefix_str()).collect();
s.suggestion.push((pat.span.shrink_to_lo(), suggestion_str));
s.ref_pattern_count += adjustments.len();
}
// Remember if this changed the default binding mode, in case we want to label it.
let min_mutbl = implicit_deref_mutbls.min().unwrap();
if s.default_mode_span.is_none_or(|(_, old_mutbl)| min_mutbl < old_mutbl) {
opt_old_mode_span = Some(s.default_mode_span);
s.default_mode_span = Some((pat.span, min_mutbl));
}
};
opt_old_mode_span = s.visit_implicit_derefs(pat.span, adjustments);
}
// When implicit dereferences have been inserted in this pattern, the unadjusted lowered
// pattern has the type that results *after* dereferencing. For example, in this code:
@ -169,10 +110,10 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
})
});
if let Some(s) = &mut self.rust_2024_migration_suggestion
&& let Some(old_mode_span) = opt_old_mode_span
if let Some(s) = &mut self.rust_2024_migration
&& !adjustments.is_empty()
{
s.default_mode_span = old_mode_span;
s.leave_ref(opt_old_mode_span);
}
adjusted_pat
@ -368,16 +309,11 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
}
hir::PatKind::Ref(subpattern, _) => {
// Track the default binding mode for the Rust 2024 migration suggestion.
let old_mode_span = self.rust_2024_migration_suggestion.as_mut().and_then(|s| {
if let Some((default_mode_span, default_ref_mutbl)) = s.default_mode_span {
// If this eats a by-ref default binding mode, label the binding mode.
s.default_mode_labels.insert(default_mode_span, default_ref_mutbl);
}
s.default_mode_span.take()
});
let opt_old_mode_span =
self.rust_2024_migration.as_mut().and_then(|s| s.visit_explicit_deref());
let subpattern = self.lower_pattern(subpattern);
if let Some(s) = &mut self.rust_2024_migration_suggestion {
s.default_mode_span = old_mode_span;
if let Some(s) = &mut self.rust_2024_migration {
s.leave_ref(opt_old_mode_span);
}
PatKind::Deref { subpattern }
}
@ -408,32 +344,8 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
.get(pat.hir_id)
.expect("missing binding mode");
if let Some(s) = &mut self.rust_2024_migration_suggestion {
if explicit_ba != hir::BindingMode::NONE
&& let Some((default_mode_span, default_ref_mutbl)) = s.default_mode_span
{
// If this overrides a by-ref default binding mode, label the binding mode.
s.default_mode_labels.insert(default_mode_span, default_ref_mutbl);
// If our suggestion is to elide redundnt modes, this will be one of them.
if s.suggest_eliding_modes {
s.suggestion.push((pat.span.with_hi(ident.span.lo()), String::new()));
s.binding_mode_count += 1;
}
}
if !s.suggest_eliding_modes
&& explicit_ba.0 == ByRef::No
&& let ByRef::Yes(mutbl) = mode.0
{
let sugg_str = match mutbl {
Mutability::Not => "ref ",
Mutability::Mut => "ref mut ",
};
s.suggestion.push((
pat.span.with_lo(ident.span.lo()).shrink_to_lo(),
sugg_str.to_owned(),
));
s.binding_mode_count += 1;
}
if let Some(s) = &mut self.rust_2024_migration {
s.visit_binding(pat.span, mode, explicit_ba, ident);
}
// A ref x pattern is the same node used for x, and as such it has

View file

@ -10,7 +10,6 @@ mod unexpand;
use rustc_hir as hir;
use rustc_hir::intravisit::{Visitor, walk_expr};
use rustc_middle::hir::map::Map;
use rustc_middle::hir::nested_filter;
use rustc_middle::mir::coverage::{
CoverageKind, DecisionInfo, FunctionCoverageInfo, Mapping, MappingKind,
@ -291,7 +290,7 @@ fn extract_hir_info<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> ExtractedHir
let hir_node = tcx.hir_node_by_def_id(def_id);
let fn_body_id = hir_node.body_id().expect("HIR node is a function with body");
let hir_body = tcx.hir().body(fn_body_id);
let hir_body = tcx.hir_body(fn_body_id);
let maybe_fn_sig = hir_node.fn_sig();
let is_async_fn = maybe_fn_sig.is_some_and(|fn_sig| fn_sig.header.is_async());
@ -348,7 +347,7 @@ fn extract_hole_spans_from_hir<'tcx>(
hir_body: &hir::Body<'tcx>,
) -> Vec<Span> {
struct HolesVisitor<'hir, F> {
hir: Map<'hir>,
tcx: TyCtxt<'hir>,
visit_hole_span: F,
}
@ -360,8 +359,8 @@ fn extract_hole_spans_from_hir<'tcx>(
/// items contained within them.
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.hir
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'hir hir::Item<'hir>) {
@ -388,7 +387,7 @@ fn extract_hole_spans_from_hir<'tcx>(
let mut hole_spans = vec![];
let mut visitor = HolesVisitor {
hir: tcx.hir(),
tcx,
visit_hole_span: |hole_span| {
// Discard any holes that aren't directly visible within the body span.
if body_span.contains(hole_span) && body_span.eq_ctxt(hole_span) {

View file

@ -478,7 +478,7 @@ fn collect_items_rec<'tcx>(
);
recursion_depth_reset = None;
let item = tcx.hir().item(item_id);
let item = tcx.hir_item(item_id);
if let hir::ItemKind::GlobalAsm(asm) = item.kind {
for (op, op_sp) in asm.operands {
match op {

View file

@ -754,9 +754,9 @@ impl<'a> Parser<'a> {
self.is_keyword_ahead(0, &[kw::Const])
&& self.look_ahead(1, |t| match &t.kind {
// async closures do not work with const closures, so we do not parse that here.
token::Ident(kw::Move | kw::Static, _) | token::OrOr | token::BinOp(token::Or) => {
true
}
token::Ident(kw::Move | kw::Static, IdentIsRaw::No)
| token::OrOr
| token::BinOp(token::Or) => true,
_ => false,
})
}

View file

@ -627,7 +627,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
fn check_object_lifetime_default(&self, hir_id: HirId) {
let tcx = self.tcx;
if let Some(owner_id) = hir_id.as_owner()
&& let Some(generics) = tcx.hir().get_generics(owner_id.def_id)
&& let Some(generics) = tcx.hir_get_generics(owner_id.def_id)
{
for p in generics.params {
let hir::GenericParamKind::Type { .. } = p.kind else { continue };
@ -2606,8 +2606,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'tcx Item<'tcx>) {
@ -2740,9 +2740,8 @@ fn check_invalid_crate_level_attr(tcx: TyCtxt<'_>, attrs: &[Attribute]) {
for attr_to_check in ATTRS_TO_CHECK {
if attr.has_name(*attr_to_check) {
let item = tcx
.hir()
.items()
.map(|id| tcx.hir().item(id))
.hir_free_items()
.map(|id| tcx.hir_item(id))
.find(|item| !item.span.is_dummy()) // Skip prelude `use`s
.map(|item| errors::ItemFollowingInnerAttr {
span: item.ident.span,

View file

@ -531,7 +531,7 @@ impl<'tcx> MarkSymbolVisitor<'tcx> {
fn impl_item_with_used_self(&mut self, impl_id: hir::ItemId, impl_item_id: LocalDefId) -> bool {
if let TyKind::Path(hir::QPath::Resolved(_, path)) =
self.tcx.hir().item(impl_id).expect_impl().self_ty.kind
self.tcx.hir_item(impl_id).expect_impl().self_ty.kind
&& let Res::Def(def_kind, def_id) = path.res
&& let Some(local_def_id) = def_id.as_local()
&& matches!(def_kind, DefKind::Struct | DefKind::Enum | DefKind::Union)
@ -559,7 +559,7 @@ impl<'tcx> Visitor<'tcx> for MarkSymbolVisitor<'tcx> {
fn visit_nested_body(&mut self, body: hir::BodyId) {
let old_maybe_typeck_results =
self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
let body = self.tcx.hir().body(body);
let body = self.tcx.hir_body(body);
self.visit_body(body);
self.maybe_typeck_results = old_maybe_typeck_results;
}
@ -750,7 +750,7 @@ fn check_item<'tcx>(
match tcx.def_kind(id.owner_id) {
DefKind::Enum => {
let item = tcx.hir().item(id);
let item = tcx.hir_item(id);
if let hir::ItemKind::Enum(ref enum_def, _) = item.kind {
if let Some(comes_from_allow) = allow_dead_code {
worklist.extend(
@ -772,7 +772,7 @@ fn check_item<'tcx>(
.iter()
.filter_map(|def_id| def_id.as_local());
let ty_is_pub = ty_ref_to_pub_struct(tcx, tcx.hir().item(id).expect_impl().self_ty);
let ty_is_pub = ty_ref_to_pub_struct(tcx, tcx.hir_item(id).expect_impl().self_ty);
// And we access the Map here to get HirId from LocalDefId
for local_def_id in local_def_ids {
@ -805,7 +805,7 @@ fn check_item<'tcx>(
}
}
DefKind::Struct => {
let item = tcx.hir().item(id);
let item = tcx.hir_item(id);
if let hir::ItemKind::Struct(ref variant_data, _) = item.kind
&& let Some(ctor_def_id) = variant_data.ctor_def_id()
{
@ -827,7 +827,7 @@ fn check_trait_item(
) {
use hir::TraitItemKind::{Const, Fn};
if matches!(tcx.def_kind(id.owner_id), DefKind::AssocConst | DefKind::AssocFn) {
let trait_item = tcx.hir().trait_item(id);
let trait_item = tcx.hir_trait_item(id);
if matches!(trait_item.kind, Const(_, Some(_)) | Fn(..))
&& let Some(comes_from_allow) =
has_allow_dead_code_or_lang_attr(tcx, trait_item.owner_id.def_id)

View file

@ -37,7 +37,7 @@ fn entry_fn(tcx: TyCtxt<'_>, (): ()) -> Option<(DefId, EntryFnType)> {
let mut ctxt = EntryContext { tcx, rustc_main_fn: None, non_main_fns: Vec::new() };
for id in tcx.hir().items() {
for id in tcx.hir_free_items() {
check_and_search_item(id, &mut ctxt);
}

View file

@ -61,7 +61,7 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> {
if max != self.hir_ids_seen.len() - 1 {
let hir = self.tcx.hir();
let pretty_owner = hir.def_path(owner.def_id).to_string_no_crate_verbose();
let pretty_owner = self.tcx.hir_def_path(owner.def_id).to_string_no_crate_verbose();
let missing_items: Vec<_> = (0..=max as u32)
.map(|i| ItemLocalId::from_u32(i))
@ -105,8 +105,8 @@ impl<'a, 'hir> HirIdValidator<'a, 'hir> {
impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_nested_item(&mut self, id: hir::ItemId) {
@ -138,8 +138,8 @@ impl<'a, 'hir> intravisit::Visitor<'hir> for HirIdValidator<'a, 'hir> {
format!(
"HirIdValidator: The recorded owner of {} is {} instead of {}",
self.tcx.hir().node_to_string(hir_id),
self.tcx.hir().def_path(hir_id.owner.def_id).to_string_no_crate_verbose(),
self.tcx.hir().def_path(owner.def_id).to_string_no_crate_verbose()
self.tcx.hir_def_path(hir_id.owner.def_id).to_string_no_crate_verbose(),
self.tcx.hir_def_path(owner.def_id).to_string_no_crate_verbose()
)
});
}

View file

@ -7,7 +7,6 @@ use rustc_ast::{self as ast, NodeId, visit as ast_visit};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::thousands::format_with_underscores;
use rustc_hir::{self as hir, AmbigArg, HirId, intravisit as hir_visit};
use rustc_middle::hir::map::Map;
use rustc_middle::ty::TyCtxt;
use rustc_span::Span;
use rustc_span::def_id::LocalDefId;
@ -56,17 +55,14 @@ impl Node {
/// a `visit_*` method for, and so we cannot measure these, which is
/// unfortunate.
struct StatCollector<'k> {
krate: Option<Map<'k>>,
tcx: Option<TyCtxt<'k>>,
nodes: FxHashMap<&'static str, Node>,
seen: FxHashSet<HirId>,
}
pub fn print_hir_stats(tcx: TyCtxt<'_>) {
let mut collector = StatCollector {
krate: Some(tcx.hir()),
nodes: FxHashMap::default(),
seen: FxHashSet::default(),
};
let mut collector =
StatCollector { tcx: Some(tcx), nodes: FxHashMap::default(), seen: FxHashSet::default() };
tcx.hir().walk_toplevel_module(&mut collector);
tcx.hir().walk_attributes(&mut collector);
collector.print("HIR STATS", "hir-stats");
@ -76,7 +72,7 @@ pub fn print_ast_stats(krate: &ast::Crate, title: &str, prefix: &str) {
use rustc_ast::visit::Visitor;
let mut collector =
StatCollector { krate: None, nodes: FxHashMap::default(), seen: FxHashSet::default() };
StatCollector { tcx: None, nodes: FxHashMap::default(), seen: FxHashSet::default() };
collector.visit_crate(krate);
collector.print(title, prefix);
}
@ -205,27 +201,27 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> {
}
fn visit_nested_item(&mut self, id: hir::ItemId) {
let nested_item = self.krate.unwrap().item(id);
let nested_item = self.tcx.unwrap().hir_item(id);
self.visit_item(nested_item)
}
fn visit_nested_trait_item(&mut self, trait_item_id: hir::TraitItemId) {
let nested_trait_item = self.krate.unwrap().trait_item(trait_item_id);
let nested_trait_item = self.tcx.unwrap().hir_trait_item(trait_item_id);
self.visit_trait_item(nested_trait_item)
}
fn visit_nested_impl_item(&mut self, impl_item_id: hir::ImplItemId) {
let nested_impl_item = self.krate.unwrap().impl_item(impl_item_id);
let nested_impl_item = self.tcx.unwrap().hir_impl_item(impl_item_id);
self.visit_impl_item(nested_impl_item)
}
fn visit_nested_foreign_item(&mut self, id: hir::ForeignItemId) {
let nested_foreign_item = self.krate.unwrap().foreign_item(id);
let nested_foreign_item = self.tcx.unwrap().hir_foreign_item(id);
self.visit_foreign_item(nested_foreign_item);
}
fn visit_nested_body(&mut self, body_id: hir::BodyId) {
let nested_body = self.krate.unwrap().body(body_id);
let nested_body = self.tcx.unwrap().hir_body(body_id);
self.visit_body(nested_body)
}

View file

@ -129,8 +129,8 @@ impl<'tcx> LibFeatureCollector<'tcx> {
impl<'tcx> Visitor<'tcx> for LibFeatureCollector<'tcx> {
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_attribute(&mut self, attr: &'tcx Attribute) {

View file

@ -87,8 +87,8 @@ pub(crate) fn provide(providers: &mut Providers) {
impl<'hir> Visitor<'hir> for CheckLoopVisitor<'hir> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_anon_const(&mut self, c: &'hir hir::AnonConst) {

View file

@ -45,7 +45,7 @@ fn check_mod_naked_functions(tcx: TyCtxt<'_>, module_def_id: LocalModDefId) {
_ => continue,
};
let body = tcx.hir().body(body_id);
let body = tcx.hir_body(body_id);
if tcx.has_attr(def_id, sym::naked) {
check_abi(tcx, def_id, fn_header.abi);
@ -259,8 +259,8 @@ struct CheckNakedAsmInNakedFn<'tcx> {
impl<'tcx> Visitor<'tcx> for CheckNakedAsmInNakedFn<'tcx> {
type NestedFilter = OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {

View file

@ -66,7 +66,7 @@ impl<'tcx> Visitor<'tcx> for ReachableContext<'tcx> {
fn visit_nested_body(&mut self, body: hir::BodyId) {
let old_maybe_typeck_results =
self.maybe_typeck_results.replace(self.tcx.typeck_body(body));
let body = self.tcx.hir().body(body);
let body = self.tcx.hir_body(body);
self.visit_body(body);
self.maybe_typeck_results = old_maybe_typeck_results;
}

View file

@ -394,8 +394,8 @@ impl<'a, 'tcx> Visitor<'tcx> for Annotator<'a, 'tcx> {
/// deep-walking.
type NestedFilter = nested_filter::All;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
@ -616,8 +616,8 @@ impl<'tcx> MissingStabilityAnnotations<'tcx> {
impl<'tcx> Visitor<'tcx> for MissingStabilityAnnotations<'tcx> {
type NestedFilter = nested_filter::OnlyBodies;
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, i: &'tcx Item<'tcx>) {
@ -756,8 +756,8 @@ impl<'tcx> Visitor<'tcx> for Checker<'tcx> {
/// Because stability levels are scoped lexically, we want to walk
/// nested items in the context of the outer item, so enable
/// deep-walking.
fn nested_visit_map(&mut self) -> Self::Map {
self.tcx.hir()
fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
self.tcx
}
fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) {

View file

@ -1084,12 +1084,16 @@ pub fn analyze_match<'p, 'tcx>(
tycx: &RustcPatCtxt<'p, 'tcx>,
arms: &[MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
pattern_complexity_limit: Option<usize>,
) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
let scrut_ty = tycx.reveal_opaque_ty(scrut_ty);
let scrut_validity = PlaceValidity::from_bool(tycx.known_valid_scrutinee);
let report =
compute_match_usefulness(tycx, arms, scrut_ty, scrut_validity, pattern_complexity_limit)?;
let report = compute_match_usefulness(
tycx,
arms,
scrut_ty,
scrut_validity,
tycx.tcx.pattern_complexity_limit().0,
)?;
// Run the non_exhaustive_omitted_patterns lint. Only run on refutable patterns to avoid hitting
// `if let`s. Only run if the match is exhaustive otherwise the error is redundant.

View file

@ -795,20 +795,21 @@ struct UsefulnessCtxt<'a, 'p, Cx: PatCx> {
/// Track information about the usefulness of branch patterns (see definition of "branch
/// pattern" at [`BranchPatUsefulness`]).
branch_usefulness: FxHashMap<PatId, BranchPatUsefulness<'p, Cx>>,
complexity_limit: Option<usize>,
// Ideally this field would have type `Limit`, but this crate is used by
// rust-analyzer which cannot have a dependency on `Limit`, because `Limit`
// is from crate `rustc_session` which uses unstable Rust features.
complexity_limit: usize,
complexity_level: usize,
}
impl<'a, 'p, Cx: PatCx> UsefulnessCtxt<'a, 'p, Cx> {
fn increase_complexity_level(&mut self, complexity_add: usize) -> Result<(), Cx::Error> {
self.complexity_level += complexity_add;
if self
.complexity_limit
.is_some_and(|complexity_limit| complexity_limit < self.complexity_level)
{
return self.tycx.complexity_exceeded();
if self.complexity_level <= self.complexity_limit {
Ok(())
} else {
self.tycx.complexity_exceeded()
}
Ok(())
}
}
@ -1834,7 +1835,7 @@ pub fn compute_match_usefulness<'p, Cx: PatCx>(
arms: &[MatchArm<'p, Cx>],
scrut_ty: Cx::Ty,
scrut_validity: PlaceValidity,
complexity_limit: Option<usize>,
complexity_limit: usize,
) -> Result<UsefulnessReport<'p, Cx>, Cx::Error> {
let mut cx = UsefulnessCtxt {
tycx,

View file

@ -124,7 +124,7 @@ pub fn compute_match_usefulness<'p>(
arms: &[MatchArm<'p, Cx>],
ty: Ty,
scrut_validity: PlaceValidity,
complexity_limit: Option<usize>,
complexity_limit: usize,
) -> Result<UsefulnessReport<'p, Cx>, ()> {
init_tracing();
rustc_pattern_analysis::usefulness::compute_match_usefulness(

View file

@ -14,7 +14,7 @@ fn check(patterns: &[DeconstructedPat<Cx>], complexity_limit: usize) -> Result<(
let ty = *patterns[0].ty();
let arms: Vec<_> =
patterns.iter().map(|pat| MatchArm { pat, has_guard: false, arm_data: () }).collect();
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, Some(complexity_limit))
compute_match_usefulness(arms.as_slice(), ty, PlaceValidity::ValidOnly, complexity_limit)
.map(|_report| ())
}

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