1
Fork 0

Rollup merge of #137305 - nnethercote:rustc_middle-2, r=lcnr

Tweaks in and around `rustc_middle`

A bunch of tiny improvements I found while working on bigger things.

r? ```@lcnr```
This commit is contained in:
Matthias Krüger 2025-02-21 12:45:25 +01:00 committed by GitHub
commit 1f6c75e682
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
21 changed files with 59 additions and 91 deletions

View file

@ -226,7 +226,7 @@ fn emit_polonius_mir<'tcx>(
regioncx,
closure_region_requirements,
borrow_set,
pass_where.clone(),
pass_where,
out,
)?;

View file

@ -28,7 +28,6 @@ use rustc_middle::bug;
use rustc_middle::infer::canonical::{CanonicalQueryInput, CanonicalVarValues};
use rustc_middle::mir::ConstraintCategory;
use rustc_middle::traits::select;
pub use rustc_middle::ty::IntVarValue;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::fold::{
BoundVarReplacerDelegate, TypeFoldable, TypeFolder, TypeSuperFoldable, fold_regions,

View file

@ -30,7 +30,6 @@ use rustc_span::{DUMMY_SP, Span, Symbol};
use tracing::{debug, trace};
pub use self::query::*;
use self::visit::TyContext;
use crate::mir::interpret::{AllocRange, Scalar};
use crate::ty::codec::{TyDecoder, TyEncoder};
use crate::ty::print::{FmtPrinter, Printer, pretty_print_const, with_no_trimmed_paths};
@ -108,7 +107,7 @@ impl MirPhase {
}
}
/// Parses an `MirPhase` from a pair of strings. Panics if this isn't possible for any reason.
/// Parses a `MirPhase` from a pair of strings. Panics if this isn't possible for any reason.
pub fn parse(dialect: String, phase: Option<String>) -> Self {
match &*dialect.to_ascii_lowercase() {
"built" => {
@ -532,17 +531,6 @@ impl<'tcx> Body<'tcx> {
}
}
pub fn span_for_ty_context(&self, ty_context: TyContext) -> Span {
match ty_context {
TyContext::UserTy(span) => span,
TyContext::ReturnTy(source_info)
| TyContext::LocalDecl { source_info, .. }
| TyContext::YieldTy(source_info)
| TyContext::ResumeTy(source_info) => source_info.span,
TyContext::Location(loc) => self.source_info(loc).span,
}
}
/// Returns the return type; it always return first element from `local_decls` array.
#[inline]
pub fn return_ty(&self) -> Ty<'tcx> {
@ -784,7 +772,7 @@ impl<T> ClearCrossCrate<T> {
}
}
pub fn assert_crate_local(self) -> T {
pub fn unwrap_crate_local(self) -> T {
match self {
ClearCrossCrate::Clear => bug!("unwrapping cross-crate data"),
ClearCrossCrate::Set(v) => v,
@ -941,7 +929,7 @@ mod binding_form_impl {
/// involved in borrow_check errors, e.g., explanations of where the
/// temporaries come from, when their destructors are run, and/or how
/// one might revise the code to satisfy the borrow checker's rules.
#[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, TyEncodable, TyDecodable, HashStable)]
pub struct BlockTailInfo {
/// If `true`, then the value resulting from evaluating this tail
/// expression is ignored by the block's expression context.
@ -965,7 +953,6 @@ pub struct LocalDecl<'tcx> {
/// Temporaries and the return place are always mutable.
pub mutability: Mutability,
// FIXME(matthewjasper) Don't store in this in `Body`
pub local_info: ClearCrossCrate<Box<LocalInfo<'tcx>>>,
/// The type of this local.
@ -975,7 +962,6 @@ pub struct LocalDecl<'tcx> {
/// e.g., via `let x: T`, then we carry that type here. The MIR
/// borrow checker needs this information since it can affect
/// region inference.
// FIXME(matthewjasper) Don't store in this in `Body`
pub user_ty: Option<Box<UserTypeProjections>>,
/// The *syntactic* (i.e., not visibility) source scope the local is defined
@ -1083,7 +1069,6 @@ pub enum LocalInfo<'tcx> {
AggregateTemp,
/// A temporary created for evaluation of some subexpression of some block's tail expression
/// (with no intervening statement context).
// FIXME(matthewjasper) Don't store in this in `Body`
BlockTailTemp(BlockTailInfo),
/// A temporary created during evaluating `if` predicate, possibly for pattern matching for `let`s,
/// and subject to Edition 2024 temporary lifetime rules
@ -1098,7 +1083,7 @@ pub enum LocalInfo<'tcx> {
impl<'tcx> LocalDecl<'tcx> {
pub fn local_info(&self) -> &LocalInfo<'tcx> {
self.local_info.as_ref().assert_crate_local()
self.local_info.as_ref().unwrap_crate_local()
}
/// Returns `true` only if local is a binding that can itself be

View file

@ -22,7 +22,7 @@ pub(crate) const ALIGN: usize = 40;
/// An indication of where we are in the control flow graph. Used for printing
/// extra information in `dump_mir`
#[derive(Clone)]
#[derive(Clone, Copy)]
pub enum PassWhere {
/// We have not started dumping the control flow graph, but we are about to.
BeforeCFG,

View file

@ -86,7 +86,7 @@ impl SwitchTargets {
self.iter().find_map(|(v, t)| (v == value).then_some(t)).unwrap_or_else(|| self.otherwise())
}
/// Adds a new target to the switch. But You cannot add an already present value.
/// Adds a new target to the switch. Panics if you add an already present value.
#[inline]
pub fn add_target(&mut self, value: u128, bb: BasicBlock) {
let value = Pu128(value);

View file

@ -51,7 +51,7 @@ pub struct ObligationCause<'tcx> {
/// information.
pub body_id: LocalDefId,
code: InternedObligationCauseCode<'tcx>,
code: ObligationCauseCodeHandle<'tcx>,
}
// This custom hash function speeds up hashing for `Obligation` deduplication
@ -97,7 +97,7 @@ impl<'tcx> ObligationCause<'tcx> {
pub fn map_code(
&mut self,
f: impl FnOnce(InternedObligationCauseCode<'tcx>) -> ObligationCauseCode<'tcx>,
f: impl FnOnce(ObligationCauseCodeHandle<'tcx>) -> ObligationCauseCode<'tcx>,
) {
self.code = f(std::mem::take(&mut self.code)).into();
}
@ -152,15 +152,16 @@ pub struct UnifyReceiverContext<'tcx> {
pub args: GenericArgsRef<'tcx>,
}
/// A compact form of `ObligationCauseCode`.
#[derive(Clone, PartialEq, Eq, Default, HashStable)]
#[derive(TypeVisitable, TypeFoldable, TyEncodable, TyDecodable)]
pub struct InternedObligationCauseCode<'tcx> {
pub struct ObligationCauseCodeHandle<'tcx> {
/// `None` for `ObligationCauseCode::Misc` (a common case, occurs ~60% of
/// the time). `Some` otherwise.
code: Option<Arc<ObligationCauseCode<'tcx>>>,
}
impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> {
impl<'tcx> std::fmt::Debug for ObligationCauseCodeHandle<'tcx> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let cause: &ObligationCauseCode<'_> = self;
cause.fmt(f)
@ -169,14 +170,14 @@ impl<'tcx> std::fmt::Debug for InternedObligationCauseCode<'tcx> {
impl<'tcx> ObligationCauseCode<'tcx> {
#[inline(always)]
fn into(self) -> InternedObligationCauseCode<'tcx> {
InternedObligationCauseCode {
fn into(self) -> ObligationCauseCodeHandle<'tcx> {
ObligationCauseCodeHandle {
code: if let ObligationCauseCode::Misc = self { None } else { Some(Arc::new(self)) },
}
}
}
impl<'tcx> std::ops::Deref for InternedObligationCauseCode<'tcx> {
impl<'tcx> std::ops::Deref for ObligationCauseCodeHandle<'tcx> {
type Target = ObligationCauseCode<'tcx>;
fn deref(&self) -> &Self::Target {
@ -305,7 +306,7 @@ pub enum ObligationCauseCode<'tcx> {
/// The node of the function call.
call_hir_id: HirId,
/// The obligation introduced by this argument.
parent_code: InternedObligationCauseCode<'tcx>,
parent_code: ObligationCauseCodeHandle<'tcx>,
},
/// Error derived when checking an impl item is compatible with
@ -390,7 +391,8 @@ pub enum ObligationCauseCode<'tcx> {
/// `WellFormed(None)`.
WellFormed(Option<WellFormedLoc>),
/// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching against.
/// From `match_impl`. The cause for us having to match an impl, and the DefId we are matching
/// against.
MatchImpl(ObligationCause<'tcx>, DefId),
BinOp {
@ -413,7 +415,7 @@ pub enum ObligationCauseCode<'tcx> {
ConstParam(Ty<'tcx>),
/// Obligations emitted during the normalization of a weak type alias.
TypeAlias(InternedObligationCauseCode<'tcx>, Span, DefId),
TypeAlias(ObligationCauseCodeHandle<'tcx>, Span, DefId),
}
/// Whether a value can be extracted into a const.
@ -514,12 +516,6 @@ impl<'tcx> ObligationCauseCode<'tcx> {
#[cfg(target_pointer_width = "64")]
rustc_data_structures::static_assert_size!(ObligationCauseCode<'_>, 48);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum StatementAsExpression {
CorrectType,
NeedsBoxing,
}
#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
#[derive(TypeVisitable, TypeFoldable)]
pub struct MatchExpressionArmCause<'tcx> {
@ -584,7 +580,7 @@ pub struct DerivedCause<'tcx> {
pub parent_trait_pred: ty::PolyTraitPredicate<'tcx>,
/// The parent trait had this cause.
pub parent_code: InternedObligationCauseCode<'tcx>,
pub parent_code: ObligationCauseCodeHandle<'tcx>,
}
#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]
@ -592,9 +588,9 @@ pub struct DerivedCause<'tcx> {
pub struct ImplDerivedCause<'tcx> {
pub derived: DerivedCause<'tcx>,
/// The `DefId` of the `impl` that gave rise to the `derived` obligation.
/// If the `derived` obligation arose from a trait alias, which conceptually has a synthetic impl,
/// then this will be the `DefId` of that trait alias. Care should therefore be taken to handle
/// that exceptional case where appropriate.
/// If the `derived` obligation arose from a trait alias, which conceptually has a synthetic
/// impl, then this will be the `DefId` of that trait alias. Care should therefore be taken to
/// handle that exceptional case where appropriate.
pub impl_or_alias_def_id: DefId,
/// The index of the derived predicate in the parent impl's predicates.
pub impl_def_predicate_index: Option<usize>,
@ -611,7 +607,7 @@ pub struct DerivedHostCause<'tcx> {
pub parent_host_pred: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
/// The parent trait had this cause.
pub parent_code: InternedObligationCauseCode<'tcx>,
pub parent_code: ObligationCauseCodeHandle<'tcx>,
}
#[derive(Clone, Debug, PartialEq, Eq, HashStable, TyEncodable, TyDecodable)]

View file

@ -75,12 +75,6 @@ pub type CanonicalPredicateGoal<'tcx> =
pub type CanonicalTypeOpAscribeUserTypeGoal<'tcx> =
CanonicalQueryInput<'tcx, ty::ParamEnvAnd<'tcx, type_op::AscribeUserType<'tcx>>>;
pub type CanonicalTypeOpEqGoal<'tcx> =
CanonicalQueryInput<'tcx, ty::ParamEnvAnd<'tcx, type_op::Eq<'tcx>>>;
pub type CanonicalTypeOpSubtypeGoal<'tcx> =
CanonicalQueryInput<'tcx, ty::ParamEnvAnd<'tcx, type_op::Subtype<'tcx>>>;
pub type CanonicalTypeOpProvePredicateGoal<'tcx> =
CanonicalQueryInput<'tcx, ty::ParamEnvAnd<'tcx, type_op::ProvePredicate<'tcx>>>;

View file

@ -331,8 +331,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let expr = &this.thir[expr_id];
let tail_result_is_ignored =
destination_ty.is_unit() || this.block_context.currently_ignores_tail_results();
this.block_context
.push(BlockFrame::TailExpr { tail_result_is_ignored, span: expr.span });
this.block_context.push(BlockFrame::TailExpr {
info: BlockTailInfo { tail_result_is_ignored, span: expr.span },
});
block = this.expr_into_dest(destination, block, expr_id).into_block();
let popped = this.block_context.pop();

View file

@ -142,7 +142,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// Overwrite temp local info if we have something more interesting to record.
if !matches!(local_info, LocalInfo::Boring) {
let decl_info =
this.local_decls[operand].local_info.as_mut().assert_crate_local();
this.local_decls[operand].local_info.as_mut().unwrap_crate_local();
if let LocalInfo::Boring | LocalInfo::BlockTailTemp(_) = **decl_info {
**decl_info = local_info;
}

View file

@ -85,7 +85,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
_ => LocalInfo::Boring,
};
**local_decl.local_info.as_mut().assert_crate_local() = local_info;
**local_decl.local_info.as_mut().unwrap_crate_local() = local_info;
this.local_decls.push(local_decl)
};
debug!(?temp);

View file

@ -164,8 +164,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
}
}
this.block_context.push(BlockFrame::TailExpr {
tail_result_is_ignored: true,
span: expr.span,
info: BlockTailInfo { tail_result_is_ignored: true, span: expr.span },
});
Some(expr.span)
} else {

View file

@ -722,7 +722,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
if let LocalInfo::User(BindingForm::Var(VarBindingForm {
opt_match_place: Some((ref mut match_place, _)),
..
})) = **self.local_decls[local].local_info.as_mut().assert_crate_local()
})) = **self.local_decls[local].local_info.as_mut().unwrap_crate_local()
{
*match_place = Some(place);
} else {

View file

@ -112,16 +112,7 @@ enum BlockFrame {
/// Evaluation is currently within the tail expression of a block.
///
/// Example: `{ STMT_1; STMT_2; EXPR }`
TailExpr {
/// If true, then the surrounding context of the block ignores
/// the result of evaluating the block's tail expression.
///
/// Example: `let _ = { STMT_1; EXPR };`
tail_result_is_ignored: bool,
/// `Span` of the tail expression.
span: Span,
},
TailExpr { info: BlockTailInfo },
/// Generic mark meaning that the block occurred as a subexpression
/// where the result might be used.
@ -277,9 +268,7 @@ impl BlockContext {
match bf {
BlockFrame::SubExpr => continue,
BlockFrame::Statement { .. } => break,
&BlockFrame::TailExpr { tail_result_is_ignored, span } => {
return Some(BlockTailInfo { tail_result_is_ignored, span });
}
&BlockFrame::TailExpr { info } => return Some(info),
}
}
@ -302,9 +291,9 @@ impl BlockContext {
// otherwise: use accumulated is_ignored state.
Some(
BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
| BlockFrame::Statement { ignores_expr_result: ignored },
) => *ignored,
BlockFrame::TailExpr { info: BlockTailInfo { tail_result_is_ignored: ign, .. } }
| BlockFrame::Statement { ignores_expr_result: ign },
) => *ign,
}
}
}
@ -967,7 +956,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
} => {
self.local_decls[local].mutability = mutability;
self.local_decls[local].source_info.scope = self.source_scope;
**self.local_decls[local].local_info.as_mut().assert_crate_local() =
**self.local_decls[local].local_info.as_mut().unwrap_crate_local() =
if let Some(kind) = param.self_kind {
LocalInfo::User(BindingForm::ImplicitSelf(kind))
} else {
@ -1032,7 +1021,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let parent_id = self.source_scopes[original_source_scope]
.local_data
.as_ref()
.assert_crate_local()
.unwrap_crate_local()
.lint_root;
self.maybe_new_source_scope(pattern_span, arg_hir_id, parent_id);
}

View file

@ -604,7 +604,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let source_scope = self.source_scope;
if let LintLevel::Explicit(current_hir_id) = lint_level {
let parent_id =
self.source_scopes[source_scope].local_data.as_ref().assert_crate_local().lint_root;
self.source_scopes[source_scope].local_data.as_ref().unwrap_crate_local().lint_root;
self.maybe_new_source_scope(region_scope.1.span, current_hir_id, parent_id);
}
self.push_scope(region_scope);
@ -992,7 +992,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
lint_root: if let LintLevel::Explicit(lint_root) = lint_level {
lint_root
} else {
self.source_scopes[parent].local_data.as_ref().assert_crate_local().lint_root
self.source_scopes[parent].local_data.as_ref().unwrap_crate_local().lint_root
},
};
self.source_scopes.push(SourceScopeData {

View file

@ -79,7 +79,7 @@ impl<'tcx> ConstMutationChecker<'_, 'tcx> {
let lint_root = self.body.source_scopes[source_info.scope]
.local_data
.as_ref()
.assert_crate_local()
.unwrap_crate_local()
.lint_root;
Some((lint_root, source_info.span, self.tcx.def_span(const_item)))

View file

@ -945,7 +945,7 @@ fn compute_layout<'tcx>(
let decl = &body.local_decls[local];
debug!(?decl);
// Do not `assert_crate_local` here, as post-borrowck cleanup may have already cleared
// Do not `unwrap_crate_local` here, as post-borrowck cleanup may have already cleared
// the information. This is alright, since `ignore_for_traits` is only relevant when
// this code runs on pre-cleanup MIR, and `ignore_for_traits = false` is the safer
// default.

View file

@ -85,7 +85,7 @@ fn has_ffi_unwind_calls(tcx: TyCtxt<'_>, local_def_id: LocalDefId) -> bool {
let lint_root = body.source_scopes[terminator.source_info.scope]
.local_data
.as_ref()
.assert_crate_local()
.unwrap_crate_local()
.lint_root;
let span = terminator.source_info.span;

View file

@ -154,7 +154,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> {
let lint_root = self.body.source_scopes[source_info.scope]
.local_data
.as_ref()
.assert_crate_local()
.unwrap_crate_local()
.lint_root;
// FIXME: use existing printing routines to print the function signature
let fn_sig = self.tcx.fn_sig(fn_id).instantiate(self.tcx, fn_args);

View file

@ -158,7 +158,7 @@ impl<'tcx> MirPatch<'tcx> {
let index = self.next_local;
self.next_local += 1;
let mut new_decl = LocalDecl::new(ty, span);
**new_decl.local_info.as_mut().assert_crate_local() = local_info;
**new_decl.local_info.as_mut().unwrap_crate_local() = local_info;
self.new_locals.push(new_decl);
Local::new(index)
}

View file

@ -10,7 +10,6 @@ use rustc_hir::def::Res;
use rustc_hir::{MatchSource, Node};
use rustc_middle::traits::{
IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
StatementAsExpression,
};
use rustc_middle::ty::error::TypeError;
use rustc_middle::ty::print::with_no_trimmed_paths;
@ -26,8 +25,14 @@ use crate::errors::{
SuggestTuplePatternMany, SuggestTuplePatternOne, TypeErrorAdditionalDiags,
};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
enum StatementAsExpression {
CorrectType,
NeedsBoxing,
}
#[derive(Clone, Copy)]
pub enum SuggestAsRefKind {
enum SuggestAsRefKind {
Option,
Result,
}
@ -382,7 +387,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
}
}
pub fn suggest_function_pointers_impl(
pub(crate) fn suggest_function_pointers_impl(
&self,
span: Option<Span>,
exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
@ -518,7 +523,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
}
}
pub fn should_suggest_as_ref_kind(
fn should_suggest_as_ref_kind(
&self,
expected: Ty<'tcx>,
found: Ty<'tcx>,
@ -588,8 +593,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
) -> Option<TypeErrorAdditionalDiags> {
/// Find the if expression with given span
struct IfVisitor {
pub found_if: bool,
pub err_span: Span,
found_if: bool,
err_span: Span,
}
impl<'v> Visitor<'v> for IfVisitor {
@ -736,7 +741,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
impl<'tcx> TypeErrCtxt<'_, 'tcx> {
/// Be helpful when the user wrote `{... expr; }` and taking the `;` off
/// is enough to fix the error.
pub fn could_remove_semicolon(
fn could_remove_semicolon(
&self,
blk: &'tcx hir::Block<'tcx>,
expected_ty: Ty<'tcx>,
@ -816,7 +821,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
/// Suggest returning a local binding with a compatible type if the block
/// has no return expression.
pub fn consider_returning_binding_diag(
fn consider_returning_binding_diag(
&self,
blk: &'tcx hir::Block<'tcx>,
expected_ty: Ty<'tcx>,

View file

@ -205,7 +205,7 @@ impl<'tcx> LateLintPass<'tcx> for RedundantClone {
let node = mir.source_scopes[scope]
.local_data
.as_ref()
.assert_crate_local()
.unwrap_crate_local()
.lint_root;
if let Some(snip) = span.get_source_text(cx)