Skip to content

Commit

Permalink
Rollup merge of rust-lang#137305 - nnethercote:rustc_middle-2, r=lcnr
Browse files Browse the repository at this point in the history
Tweaks in and around `rustc_middle`

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

r? `@lcnr`
  • Loading branch information
workingjubilee authored Feb 20, 2025
2 parents 5643a93 + 2edaf68 commit faeb221
Show file tree
Hide file tree
Showing 21 changed files with 59 additions and 91 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/polonius/dump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ fn emit_polonius_mir<'tcx>(
regioncx,
closure_region_requirements,
borrow_set,
pass_where.clone(),
pass_where,
out,
)?;

Expand Down
1 change: 0 additions & 1 deletion compiler/rustc_infer/src/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
23 changes: 4 additions & 19 deletions compiler/rustc_middle/src/mir/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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" => {
Expand Down Expand Up @@ -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> {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/mir/terminator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
38 changes: 17 additions & 21 deletions compiler/rustc_middle/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
}
Expand Down Expand Up @@ -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)
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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.
Expand Down Expand Up @@ -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> {
Expand Down Expand Up @@ -584,17 +580,17 @@ 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)]
#[derive(TypeVisitable, TypeFoldable)]
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>,
Expand All @@ -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)]
Expand Down
6 changes: 0 additions & 6 deletions compiler/rustc_middle/src/traits/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>>>;

Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_mir_build/src/builder/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_build/src/builder/expr/as_operand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_build/src/builder/expr/as_temp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions compiler/rustc_mir_build/src/builder/expr/stmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_build/src/builder/matches/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 7 additions & 18 deletions compiler/rustc_mir_build/src/builder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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),
}
}

Expand All @@ -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,
}
}
}
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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);
}
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_mir_build/src/builder/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
Expand Down
Loading

0 comments on commit faeb221

Please sign in to comment.