1
Fork 0

use TypingEnv when no infcx is available

the behavior of the type system not only depends on the current
assumptions, but also the currentnphase of the compiler. This is
mostly necessary as we need to decide whether and how to reveal
opaque types. We track this via the `TypingMode`.
This commit is contained in:
lcnr 2024-11-15 13:53:31 +01:00
parent bf6adec108
commit 9cba14b95b
240 changed files with 1739 additions and 1340 deletions

View file

@ -25,7 +25,7 @@ use rustc_index::{IndexSlice, IndexVec};
use rustc_middle::mir::*;
use rustc_middle::span_bug;
use rustc_middle::thir::*;
use rustc_middle::ty::{ParamEnv, Ty, TyCtxt};
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_span::Span;
mod parse;
@ -77,7 +77,7 @@ pub(super) fn build_custom_mir<'tcx>(
let mut pctxt = ParseCtxt {
tcx,
param_env: tcx.param_env(did),
typing_env: body.typing_env(tcx),
thir,
source_scope: OUTERMOST_SOURCE_SCOPE,
body: &mut body,
@ -136,7 +136,7 @@ fn parse_attribute(attr: &Attribute) -> MirPhase {
struct ParseCtxt<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
param_env: ParamEnv<'tcx>,
typing_env: ty::TypingEnv<'tcx>,
thir: &'a Thir<'tcx>,
source_scope: SourceScope,
body: &'a mut Body<'tcx>,

View file

@ -151,7 +151,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> {
expected: "constant pattern".to_string(),
});
};
values.push(value.eval_bits(self.tcx, self.param_env));
values.push(value.eval_bits(self.tcx, self.typing_env));
targets.push(self.parse_block(arm.body)?);
}
@ -385,7 +385,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> {
| ExprKind::NonHirLiteral { .. }
| ExprKind::ConstBlock { .. } => Ok({
let value = as_constant_inner(expr, |_| None, self.tcx);
value.const_.eval_bits(self.tcx, self.param_env)
value.const_.eval_bits(self.tcx, self.typing_env)
}),
)
}

View file

@ -114,8 +114,7 @@ fn lit_to_mir_constant<'tcx>(
) -> Result<Const<'tcx>, LitToConstError> {
let LitToConstInput { lit, ty, neg } = lit_input;
let trunc = |n| {
let param_ty = ty::ParamEnv::reveal_all().and(ty);
let width = match tcx.layout_of(param_ty) {
let width = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
Ok(layout) => layout.size,
Err(_) => {
tcx.dcx().bug(format!("couldn't compute width of literal: {:?}", lit_input.lit))

View file

@ -123,7 +123,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
match category {
Category::Constant
if matches!(needs_temporary, NeedsTemporary::No)
|| !expr.ty.needs_drop(this.tcx, this.param_env) =>
|| !expr.ty.needs_drop(this.tcx, this.typing_env()) =>
{
let constant = this.as_constant(expr);
block.and(Operand::Constant(Box::new(constant)))

View file

@ -197,7 +197,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
{
let discr_ty = adt_def.repr().discr_type().to_ty(this.tcx);
let temp = unpack!(block = this.as_temp(block, scope, source, Mutability::Not));
let layout = this.tcx.layout_of(this.param_env.and(source_expr.ty));
let layout =
this.tcx.layout_of(this.typing_env().as_query_input(source_expr.ty));
let discr = this.temp(discr_ty, source_expr.span);
this.cfg.push_assign(
block,
@ -229,7 +230,8 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let range_val = Const::from_bits(
this.tcx,
range,
ty::ParamEnv::empty().and(unsigned_ty),
ty::TypingEnv::fully_monomorphized(),
unsigned_ty,
);
let lit_op = this.literal_operand(expr.span, range_val);
let is_bin_op = this.temp(bool_ty, expr_span);
@ -812,9 +814,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// Helper to get a `-1` value of the appropriate type
fn neg_1_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let param_ty = ty::ParamEnv::empty().and(ty);
let size = self.tcx.layout_of(param_ty).unwrap().size;
let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), param_ty);
let typing_env = ty::TypingEnv::fully_monomorphized();
let size = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size;
let literal = Const::from_bits(self.tcx, size.unsigned_int_max(), typing_env, ty);
self.literal_operand(span, literal)
}
@ -822,10 +824,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// Helper to get the minimum value of the appropriate type
fn minval_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
assert!(ty.is_signed());
let param_ty = ty::ParamEnv::empty().and(ty);
let bits = self.tcx.layout_of(param_ty).unwrap().size.bits();
let typing_env = ty::TypingEnv::fully_monomorphized();
let bits = self.tcx.layout_of(typing_env.as_query_input(ty)).unwrap().size.bits();
let n = 1 << (bits - 1);
let literal = Const::from_bits(self.tcx, n, param_ty);
let literal = Const::from_bits(self.tcx, n, typing_env, ty);
self.literal_operand(span, literal)
}

View file

@ -266,7 +266,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// that makes the call.
target: expr
.ty
.is_inhabited_from(this.tcx, this.parent_module, this.param_env)
.is_inhabited_from(
this.tcx,
this.parent_module,
this.infcx.typing_env(this.param_env),
)
.then_some(success),
call_source: if from_hir_call {
CallSource::Normal

View file

@ -42,7 +42,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// Generate better code for things that don't need to be
// dropped.
if lhs_expr.ty.needs_drop(this.tcx, this.param_env) {
if lhs_expr.ty.needs_drop(this.tcx, this.typing_env()) {
let rhs = unpack!(block = this.as_local_rvalue(block, rhs));
let lhs = unpack!(block = this.as_place(block, lhs));
block =

View file

@ -214,7 +214,7 @@ impl<'pat, 'tcx> MatchPairTree<'pat, 'tcx> {
|| !v
.inhabited_predicate(cx.tcx, adt_def)
.instantiate(cx.tcx, args)
.apply_ignore_module(cx.tcx, cx.param_env)
.apply_ignore_module(cx.tcx, cx.infcx.typing_env(cx.param_env))
}) && (adt_def.did().is_local()
|| !adt_def.is_variant_list_non_exhaustive());
if irrefutable {

View file

@ -567,7 +567,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
// not to add such values here.
let is_covering_range = |test_case: &TestCase<'_, 'tcx>| {
test_case.as_range().is_some_and(|range| {
matches!(range.contains(value, self.tcx, self.param_env), None | Some(true))
matches!(
range.contains(value, self.tcx, self.typing_env()),
None | Some(true)
)
})
};
let is_conflicting_candidate = |candidate: &&mut Candidate<'_, 'tcx>| {
@ -584,7 +587,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
None
} else {
fully_matched = true;
let bits = value.eval_bits(self.tcx, self.param_env);
let bits = value.eval_bits(self.tcx, self.typing_env());
Some(TestBranch::Constant(value, bits))
}
}
@ -596,7 +599,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
fully_matched = false;
let not_contained =
sorted_candidates.keys().filter_map(|br| br.as_constant()).copied().all(
|val| matches!(range.contains(val, self.tcx, self.param_env), Some(false)),
|val| {
matches!(range.contains(val, self.tcx, self.typing_env()), Some(false))
},
);
not_contained.then(|| {
@ -608,7 +613,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
(TestKind::If, TestCase::Constant { value }) => {
fully_matched = true;
let value = value.try_eval_bool(self.tcx, self.param_env).unwrap_or_else(|| {
let value = value.try_eval_bool(self.tcx, self.typing_env()).unwrap_or_else(|| {
span_bug!(test.span, "expected boolean value but got {value:?}")
});
Some(if value { TestBranch::Success } else { TestBranch::Failure })
@ -688,7 +693,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
fully_matched = false;
// If the testing range does not overlap with pattern range,
// the pattern can be matched only if this test fails.
if !test.overlaps(pat, self.tcx, self.param_env)? {
if !test.overlaps(pat, self.tcx, self.typing_env())? {
Some(TestBranch::Failure)
} else {
None
@ -697,7 +702,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
}
(TestKind::Range(range), &TestCase::Constant { value }) => {
fully_matched = false;
if !range.contains(value, self.tcx, self.param_env)? {
if !range.contains(value, self.tcx, self.typing_env())? {
// `value` is not contained in the testing range,
// so `value` can be matched only if this test fails.
Some(TestBranch::Failure)

View file

@ -32,7 +32,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Returns a zero literal operand for the appropriate type, works for
/// bool, char and integers.
pub(crate) fn zero_literal(&mut self, span: Span, ty: Ty<'tcx>) -> Operand<'tcx> {
let literal = Const::from_bits(self.tcx, 0, ty::ParamEnv::empty().and(ty));
let literal = Const::from_bits(self.tcx, 0, ty::TypingEnv::fully_monomorphized(), ty);
self.literal_operand(span, literal)
}

View file

@ -230,6 +230,10 @@ struct Capture<'tcx> {
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
fn typing_env(&self) -> ty::TypingEnv<'tcx> {
self.infcx.typing_env(self.param_env)
}
fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
}

View file

@ -1010,7 +1010,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
) {
let needs_drop = match drop_kind {
DropKind::Value => {
if !self.local_decls[local].ty.needs_drop(self.tcx, self.param_env) {
if !self.local_decls[local].ty.needs_drop(self.tcx, self.typing_env()) {
return;
}
true

View file

@ -566,7 +566,9 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
&& adt_def.is_union()
{
if let Some(assigned_ty) = self.assignment_info {
if assigned_ty.needs_drop(self.tcx, self.param_env) {
if assigned_ty
.needs_drop(self.tcx, ty::TypingEnv::from_param_env(self.param_env))
{
// This would be unsafe, but should be outright impossible since we
// reject such unions.
assert!(

View file

@ -528,7 +528,7 @@ impl<'a, G: EmissionGuarantee> Diagnostic<'a, G> for NonExhaustivePatternsTypeNo
}
if let ty::Ref(_, sub_ty, _) = self.ty.kind() {
if !sub_ty.is_inhabited_from(self.cx.tcx, self.cx.module, self.cx.param_env) {
if !sub_ty.is_inhabited_from(self.cx.tcx, self.cx.module, self.cx.typing_env()) {
diag.note(fluent::mir_build_reference_note);
}
}

View file

@ -136,12 +136,17 @@ impl<'tcx> TerminatorClassifier<'tcx> for CallRecursion<'tcx> {
let func_ty = func.ty(body, tcx);
if let ty::FnDef(callee, args) = *func_ty.kind() {
let Ok(normalized_args) = tcx.try_normalize_erasing_regions(param_env, args) else {
let Ok(normalized_args) =
tcx.try_normalize_erasing_regions(ty::TypingEnv::from_param_env(param_env), args)
else {
return false;
};
let (callee, call_args) = if let Ok(Some(instance)) =
Instance::try_resolve(tcx, param_env, callee, normalized_args)
{
let (callee, call_args) = if let Ok(Some(instance)) = Instance::try_resolve(
tcx,
ty::TypingEnv::from_param_env(param_env),
callee,
normalized_args,
) {
(instance.def_id(), instance.args)
} else {
(callee, normalized_args)

View file

@ -2,7 +2,7 @@ use rustc_ast as ast;
use rustc_hir::LangItem;
use rustc_middle::bug;
use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
use rustc_middle::ty::{self, ParamEnv, ScalarInt, TyCtxt};
use rustc_middle::ty::{self, ScalarInt, TyCtxt};
use tracing::trace;
use crate::build::parse_float_into_scalar;
@ -14,8 +14,7 @@ pub(crate) fn lit_to_const<'tcx>(
let LitToConstInput { lit, ty, neg } = lit_input;
let trunc = |n| {
let param_ty = ParamEnv::reveal_all().and(ty);
let width = match tcx.layout_of(param_ty) {
let width = match tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(ty)) {
Ok(layout) => layout.size,
Err(_) => {
tcx.dcx().bug(format!("couldn't compute width of literal: {:?}", lit_input.lit))

View file

@ -284,10 +284,9 @@ impl<'tcx> Cx<'tcx> {
let ty = adt_def.repr().discr_type();
let discr_ty = ty.to_ty(tcx);
let param_env_ty = self.param_env.and(discr_ty);
let size = tcx
.layout_of(param_env_ty)
.unwrap_or_else(|e| panic!("could not compute layout for {param_env_ty:?}: {e:?}"))
.layout_of(self.typing_env().as_query_input(discr_ty))
.unwrap_or_else(|e| panic!("could not compute layout for {discr_ty:?}: {e:?}"))
.size;
let (lit, overflowing) = ScalarInt::truncate_from_uint(discr_offset as u128, size);
@ -1025,7 +1024,7 @@ impl<'tcx> Cx<'tcx> {
// but distinguish between &STATIC and &THREAD_LOCAL as they have different semantics
Res::Def(DefKind::Static { .. }, id) => {
// this is &raw for extern static or static mut, and & for other statics
let ty = self.tcx.static_ptr_ty(id);
let ty = self.tcx.static_ptr_ty(id, self.typing_env());
let temp_lifetime = self
.rvalue_scopes
.temporary_scope(self.region_scope_tree, expr.hir_id.local_id);

View file

@ -12,6 +12,7 @@ use rustc_hir::lang_items::LangItem;
use rustc_middle::bug;
use rustc_middle::middle::region;
use rustc_middle::thir::*;
use rustc_middle::ty::solve::Reveal;
use rustc_middle::ty::{self, RvalueScopes, TyCtxt};
use tracing::instrument;
@ -109,6 +110,17 @@ impl<'tcx> Cx<'tcx> {
}
}
fn typing_mode(&self) -> ty::TypingMode<'tcx> {
debug_assert_eq!(self.param_env.reveal(), Reveal::UserFacing);
// FIXME(#132279): In case we're in a body, we should use a typing
// mode which reveals the opaque types defined by that body.
ty::TypingMode::non_body_analysis()
}
fn typing_env(&self) -> ty::TypingEnv<'tcx> {
ty::TypingEnv { typing_mode: self.typing_mode(), param_env: self.param_env }
}
#[instrument(level = "debug", skip(self))]
fn pattern_from_hir(&mut self, p: &'tcx hir::Pat<'tcx>) -> Box<Pat<'tcx>> {
pat_from_hir(self.tcx, self.param_env, self.typeck_results(), p)

View file

@ -721,8 +721,8 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
.variant(*variant_index)
.inhabited_predicate(self.tcx, *adt)
.instantiate(self.tcx, args);
variant_inhabited.apply(self.tcx, cx.param_env, cx.module)
&& !variant_inhabited.apply_ignore_module(self.tcx, cx.param_env)
variant_inhabited.apply(self.tcx, cx.typing_env(), cx.module)
&& !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env())
} else {
false
};
@ -1124,7 +1124,7 @@ fn report_non_exhaustive_match<'p, 'tcx>(
}
if let ty::Ref(_, sub_ty, _) = scrut_ty.kind() {
if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.param_env) {
if !sub_ty.is_inhabited_from(cx.tcx, cx.module, cx.typing_env()) {
err.note("references are always considered inhabited");
}
}

View file

@ -50,10 +50,10 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
struct ConstToPat<'tcx> {
span: Span,
param_env: ty::ParamEnv<'tcx>,
// inference context used for checking `T: Structural` bounds.
infcx: InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
treat_byte_string_as_slice: bool,
}
@ -81,6 +81,10 @@ impl<'tcx> ConstToPat<'tcx> {
self.infcx.tcx
}
fn typing_env(&self) -> ty::TypingEnv<'tcx> {
self.infcx.typing_env(self.param_env)
}
fn type_marked_structural(&self, ty: Ty<'tcx>) -> bool {
ty.is_structural_eq_shallow(self.infcx.tcx)
}
@ -100,13 +104,14 @@ impl<'tcx> ConstToPat<'tcx> {
//
// FIXME: `const_eval_resolve_for_typeck` should probably just set the env to `Reveal::All`
// instead of having this logic here
let param_env =
self.tcx().erase_regions(self.param_env).with_reveal_all_normalized(self.tcx());
let typing_env =
self.tcx().erase_regions(self.typing_env()).with_reveal_all_normalized(self.tcx());
let uv = self.tcx().erase_regions(uv);
// try to resolve e.g. associated constants to their definition on an impl, and then
// evaluate the const.
let valtree = match self.infcx.tcx.const_eval_resolve_for_typeck(param_env, uv, self.span) {
let valtree = match self.infcx.tcx.const_eval_resolve_for_typeck(typing_env, uv, self.span)
{
Ok(Ok(c)) => c,
Err(ErrorHandled::Reported(_, _)) => {
// Let's tell the use where this failing const occurs.
@ -187,7 +192,7 @@ impl<'tcx> ConstToPat<'tcx> {
.map(|(idx, (val, ty))| {
let field = FieldIdx::new(idx);
// Patterns can only use monomorphic types.
let ty = self.tcx().normalize_erasing_regions(self.param_env, ty);
let ty = self.tcx().normalize_erasing_regions(self.typing_env(), ty);
FieldPat { field, pattern: self.valtree_to_pat(val, ty) }
})
.collect()

View file

@ -242,7 +242,7 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
let lo = lo.unwrap_or(PatRangeBoundary::NegInfinity);
let hi = hi.unwrap_or(PatRangeBoundary::PosInfinity);
let cmp = lo.compare_with(hi, ty, self.tcx, self.param_env);
let cmp = lo.compare_with(hi, ty, self.tcx, ty::TypingEnv::from_param_env(self.param_env));
let mut kind = PatKind::Range(Box::new(PatRange { lo, hi, end, ty }));
match (end, cmp) {
// `x..y` where `x < y`.