Skip to content

Commit b149c48

Browse files
authored
Rollup merge of #102021 - lcnr:tyConst-fun, r=b-naber,BoxyUwU
some post-valtree cleanup r? project-const-generics cc ```@b-naber```
2 parents 08b369a + c54c5a3 commit b149c48

File tree

12 files changed

+58
-122
lines changed

12 files changed

+58
-122
lines changed

compiler/rustc_const_eval/src/const_eval/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -100,10 +100,10 @@ pub(crate) fn try_destructure_mir_constant<'tcx>(
100100
tcx: TyCtxt<'tcx>,
101101
param_env: ty::ParamEnv<'tcx>,
102102
val: mir::ConstantKind<'tcx>,
103-
) -> InterpResult<'tcx, mir::DestructuredMirConstant<'tcx>> {
103+
) -> InterpResult<'tcx, mir::DestructuredConstant<'tcx>> {
104104
trace!("destructure_mir_constant: {:?}", val);
105105
let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
106-
let op = ecx.mir_const_to_op(&val, None)?;
106+
let op = ecx.const_to_op(&val, None)?;
107107

108108
// We go to `usize` as we cannot allocate anything bigger anyway.
109109
let (field_count, variant, down) = match val.ty().kind() {
@@ -129,7 +129,7 @@ pub(crate) fn try_destructure_mir_constant<'tcx>(
129129
.collect::<InterpResult<'tcx, Vec<_>>>()?;
130130
let fields = tcx.arena.alloc_from_iter(fields_iter);
131131

132-
Ok(mir::DestructuredMirConstant { variant, fields })
132+
Ok(mir::DestructuredConstant { variant, fields })
133133
}
134134

135135
#[instrument(skip(tcx), level = "debug")]
@@ -139,7 +139,7 @@ pub(crate) fn deref_mir_constant<'tcx>(
139139
val: mir::ConstantKind<'tcx>,
140140
) -> mir::ConstantKind<'tcx> {
141141
let ecx = mk_eval_cx(tcx, DUMMY_SP, param_env, false);
142-
let op = ecx.mir_const_to_op(&val, None).unwrap();
142+
let op = ecx.const_to_op(&val, None).unwrap();
143143
let mplace = ecx.deref_operand(&op).unwrap();
144144
if let Some(alloc_id) = mplace.ptr.provenance {
145145
assert_eq!(

compiler/rustc_const_eval/src/interpret/eval_context.rs

+4-5
Original file line numberDiff line numberDiff line change
@@ -683,11 +683,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
683683
self.stack_mut().push(frame);
684684

685685
// Make sure all the constants required by this frame evaluate successfully (post-monomorphization check).
686-
for const_ in &body.required_consts {
687-
let span = const_.span;
688-
let const_ =
689-
self.subst_from_current_frame_and_normalize_erasing_regions(const_.literal)?;
690-
self.mir_const_to_op(&const_, None).map_err(|err| {
686+
for ct in &body.required_consts {
687+
let span = ct.span;
688+
let ct = self.subst_from_current_frame_and_normalize_erasing_regions(ct.literal)?;
689+
self.const_to_op(&ct, None).map_err(|err| {
691690
// If there was an error, set the span of the current frame to this constant.
692691
// Avoiding doing this when evaluation succeeds.
693692
self.frame_mut().loc = Err(span);

compiler/rustc_const_eval/src/interpret/operand.rs

+31-39
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
534534
// * During ConstProp, with `TooGeneric` or since the `required_consts` were not all
535535
// checked yet.
536536
// * During CTFE, since promoteds in `const`/`static` initializer bodies can fail.
537-
self.mir_const_to_op(&val, layout)?
537+
self.const_to_op(&val, layout)?
538538
}
539539
};
540540
trace!("{:?}: {:?}", mir_op, *op);
@@ -549,50 +549,42 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
549549
ops.iter().map(|op| self.eval_operand(op, None)).collect()
550550
}
551551

552-
// Used when the miri-engine runs into a constant and for extracting information from constants
553-
// in patterns via the `const_eval` module
554-
/// The `val` and `layout` are assumed to already be in our interpreter
555-
/// "universe" (param_env).
556552
pub fn const_to_op(
557-
&self,
558-
c: ty::Const<'tcx>,
559-
layout: Option<TyAndLayout<'tcx>>,
560-
) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
561-
match c.kind() {
562-
ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(..) => throw_inval!(TooGeneric),
563-
ty::ConstKind::Error(DelaySpanBugEmitted { reported, .. }) => {
564-
throw_inval!(AlreadyReported(reported))
565-
}
566-
ty::ConstKind::Unevaluated(uv) => {
567-
// NOTE: We evaluate to a `ValTree` here as a check to ensure
568-
// we're working with valid constants, even though we never need it.
569-
let instance = self.resolve(uv.def, uv.substs)?;
570-
let cid = GlobalId { instance, promoted: None };
571-
let _valtree = self
572-
.tcx
573-
.eval_to_valtree(self.param_env.and(cid))?
574-
.unwrap_or_else(|| bug!("unable to create ValTree for {:?}", uv));
575-
576-
Ok(self.eval_to_allocation(cid)?.into())
577-
}
578-
ty::ConstKind::Bound(..) | ty::ConstKind::Infer(..) => {
579-
span_bug!(self.cur_span(), "const_to_op: Unexpected ConstKind {:?}", c)
580-
}
581-
ty::ConstKind::Value(valtree) => {
582-
let ty = c.ty();
583-
let const_val = self.tcx.valtree_to_const_val((ty, valtree));
584-
self.const_val_to_op(const_val, ty, layout)
585-
}
586-
}
587-
}
588-
589-
pub fn mir_const_to_op(
590553
&self,
591554
val: &mir::ConstantKind<'tcx>,
592555
layout: Option<TyAndLayout<'tcx>>,
593556
) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
594557
match val {
595-
mir::ConstantKind::Ty(ct) => self.const_to_op(*ct, layout),
558+
mir::ConstantKind::Ty(ct) => {
559+
match ct.kind() {
560+
ty::ConstKind::Param(_) | ty::ConstKind::Placeholder(..) => {
561+
throw_inval!(TooGeneric)
562+
}
563+
ty::ConstKind::Error(DelaySpanBugEmitted { reported, .. }) => {
564+
throw_inval!(AlreadyReported(reported))
565+
}
566+
ty::ConstKind::Unevaluated(uv) => {
567+
// NOTE: We evaluate to a `ValTree` here as a check to ensure
568+
// we're working with valid constants, even though we never need it.
569+
let instance = self.resolve(uv.def, uv.substs)?;
570+
let cid = GlobalId { instance, promoted: None };
571+
let _valtree = self
572+
.tcx
573+
.eval_to_valtree(self.param_env.and(cid))?
574+
.unwrap_or_else(|| bug!("unable to create ValTree for {uv:?}"));
575+
576+
Ok(self.eval_to_allocation(cid)?.into())
577+
}
578+
ty::ConstKind::Bound(..) | ty::ConstKind::Infer(..) => {
579+
span_bug!(self.cur_span(), "unexpected ConstKind in ctfe: {ct:?}")
580+
}
581+
ty::ConstKind::Value(valtree) => {
582+
let ty = ct.ty();
583+
let const_val = self.tcx.valtree_to_const_val((ty, valtree));
584+
self.const_val_to_op(const_val, ty, layout)
585+
}
586+
}
587+
}
596588
mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, *ty, layout),
597589
mir::ConstantKind::Unevaluated(uv, _) => {
598590
let instance = self.resolve(uv.def, uv.substs)?;

compiler/rustc_middle/src/mir/interpret/queries.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ impl<'tcx> TyCtxt<'tcx> {
211211
self,
212212
param_env: ty::ParamEnv<'tcx>,
213213
constant: mir::ConstantKind<'tcx>,
214-
) -> mir::DestructuredMirConstant<'tcx> {
214+
) -> mir::DestructuredConstant<'tcx> {
215215
self.try_destructure_mir_constant(param_env.and(constant)).unwrap()
216216
}
217217
}

compiler/rustc_middle/src/mir/query.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -392,16 +392,9 @@ pub enum ClosureOutlivesSubject<'tcx> {
392392
Region(ty::RegionVid),
393393
}
394394

395-
/// The constituent parts of a type level constant of kind ADT or array.
396-
#[derive(Copy, Clone, Debug, HashStable)]
397-
pub struct DestructuredConst<'tcx> {
398-
pub variant: Option<VariantIdx>,
399-
pub fields: &'tcx [ty::Const<'tcx>],
400-
}
401-
402395
/// The constituent parts of a mir constant of kind ADT or array.
403396
#[derive(Copy, Clone, Debug, HashStable)]
404-
pub struct DestructuredMirConstant<'tcx> {
397+
pub struct DestructuredConstant<'tcx> {
405398
pub variant: Option<VariantIdx>,
406399
pub fields: &'tcx [ConstantKind<'tcx>],
407400
}

compiler/rustc_middle/src/query/mod.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1007,7 +1007,9 @@ rustc_queries! {
10071007

10081008
/// Tries to destructure an `mir::ConstantKind` ADT or array into its variant index
10091009
/// and its field values.
1010-
query try_destructure_mir_constant(key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>>) -> Option<mir::DestructuredMirConstant<'tcx>> {
1010+
query try_destructure_mir_constant(
1011+
key: ty::ParamEnvAnd<'tcx, mir::ConstantKind<'tcx>>
1012+
) -> Option<mir::DestructuredConstant<'tcx>> {
10111013
desc { "destructuring mir constant"}
10121014
remap_env_constness
10131015
}

compiler/rustc_middle/src/ty/consts.rs

+1-44
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
use crate::mir::interpret::LitToConstInput;
22
use crate::mir::ConstantKind;
3-
use crate::ty::{
4-
self, InlineConstSubsts, InlineConstSubstsParts, InternalSubsts, ParamEnv, ParamEnvAnd, Ty,
5-
TyCtxt, TypeVisitable,
6-
};
3+
use crate::ty::{self, InternalSubsts, ParamEnv, ParamEnvAnd, Ty, TyCtxt};
74
use rustc_data_structures::intern::Interned;
85
use rustc_errors::ErrorGuaranteed;
96
use rustc_hir as hir;
@@ -151,46 +148,6 @@ impl<'tcx> Const<'tcx> {
151148
}
152149
}
153150

154-
pub fn from_inline_const(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
155-
debug!("Const::from_inline_const(def_id={:?})", def_id);
156-
157-
let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
158-
159-
let body_id = match tcx.hir().get(hir_id) {
160-
hir::Node::AnonConst(ac) => ac.body,
161-
_ => span_bug!(
162-
tcx.def_span(def_id.to_def_id()),
163-
"from_inline_const can only process anonymous constants"
164-
),
165-
};
166-
167-
let expr = &tcx.hir().body(body_id).value;
168-
169-
let ty = tcx.typeck(def_id).node_type(hir_id);
170-
171-
let ret = match Self::try_eval_lit_or_param(tcx, ty, expr) {
172-
Some(v) => v,
173-
None => {
174-
let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id());
175-
let parent_substs =
176-
tcx.erase_regions(InternalSubsts::identity_for_item(tcx, typeck_root_def_id));
177-
let substs =
178-
InlineConstSubsts::new(tcx, InlineConstSubstsParts { parent_substs, ty })
179-
.substs;
180-
tcx.mk_const(ty::ConstS {
181-
kind: ty::ConstKind::Unevaluated(ty::Unevaluated {
182-
def: ty::WithOptConstParam::unknown(def_id).to_global(),
183-
substs,
184-
promoted: (),
185-
}),
186-
ty,
187-
})
188-
}
189-
};
190-
debug_assert!(!ret.has_free_regions());
191-
ret
192-
}
193-
194151
/// Interns the given value as a constant.
195152
#[inline]
196153
pub fn from_value(tcx: TyCtxt<'tcx>, val: ty::ValTree<'tcx>, ty: Ty<'tcx>) -> Self {

compiler/rustc_mir_build/src/thir/pattern/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -680,7 +680,7 @@ macro_rules! ClonePatternFoldableImpls {
680680
}
681681

682682
ClonePatternFoldableImpls! { <'tcx>
683-
Span, Field, Mutability, Symbol, LocalVarId, usize, ty::Const<'tcx>,
683+
Span, Field, Mutability, Symbol, LocalVarId, usize,
684684
Region<'tcx>, Ty<'tcx>, BindingMode, AdtDef<'tcx>,
685685
SubstsRef<'tcx>, &'tcx GenericArg<'tcx>, UserType<'tcx>,
686686
UserTypeProjection, CanonicalUserTypeAnnotation<'tcx>

compiler/rustc_mir_transform/src/const_prop.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
471471
return None;
472472
}
473473

474-
self.ecx.mir_const_to_op(&c.literal, None).ok()
474+
self.ecx.const_to_op(&c.literal, None).ok()
475475
}
476476

477477
/// Returns the value, if any, of evaluating `place`.

compiler/rustc_mir_transform/src/const_prop_lint.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> {
292292
return None;
293293
}
294294

295-
match self.ecx.mir_const_to_op(&c.literal, None) {
295+
match self.ecx.const_to_op(&c.literal, None) {
296296
Ok(op) => Some(op),
297297
Err(error) => {
298298
let tcx = self.ecx.tcx.at(c.span);

compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs

+7-9
Original file line numberDiff line numberDiff line change
@@ -487,18 +487,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
487487
pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> ty::Const<'tcx> {
488488
match length {
489489
&hir::ArrayLen::Infer(_, span) => self.ct_infer(self.tcx.types.usize, None, span),
490-
hir::ArrayLen::Body(anon_const) => self.to_const(anon_const),
490+
hir::ArrayLen::Body(anon_const) => {
491+
let const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
492+
let span = self.tcx.hir().span(anon_const.hir_id);
493+
let c = ty::Const::from_anon_const(self.tcx, const_def_id);
494+
self.register_wf_obligation(c.into(), span, ObligationCauseCode::WellFormed(None));
495+
self.normalize_associated_types_in(span, c)
496+
}
491497
}
492498
}
493499

494-
pub fn to_const(&self, ast_c: &hir::AnonConst) -> ty::Const<'tcx> {
495-
let const_def_id = self.tcx.hir().local_def_id(ast_c.hir_id);
496-
let span = self.tcx.hir().span(ast_c.hir_id);
497-
let c = ty::Const::from_anon_const(self.tcx, const_def_id);
498-
self.register_wf_obligation(c.into(), span, ObligationCauseCode::WellFormed(None));
499-
self.normalize_associated_types_in(span, c)
500-
}
501-
502500
pub fn const_arg_to_const(
503501
&self,
504502
ast_c: &hir::AnonConst,

compiler/rustc_typeck/src/coherence/orphan.rs

+3-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use rustc_data_structures::fx::FxHashSet;
55
use rustc_errors::struct_span_err;
66
use rustc_errors::{Diagnostic, ErrorGuaranteed};
77
use rustc_hir as hir;
8-
use rustc_infer::infer::TyCtxtInferExt;
98
use rustc_middle::ty::subst::GenericArgKind;
109
use rustc_middle::ty::subst::InternalSubsts;
1110
use rustc_middle::ty::util::IgnoreRegions;
@@ -229,12 +228,8 @@ fn emit_orphan_check_error<'tcx>(
229228
"only traits defined in the current crate {msg}"
230229
);
231230
err.span_label(sp, "impl doesn't use only types from inside the current crate");
232-
for (ty, is_target_ty) in &tys {
233-
let mut ty = *ty;
234-
tcx.infer_ctxt().enter(|infcx| {
235-
// Remove the lifetimes unnecessary for this error.
236-
ty = infcx.freshen(ty);
237-
});
231+
for &(mut ty, is_target_ty) in &tys {
232+
ty = tcx.erase_regions(ty);
238233
ty = match ty.kind() {
239234
// Remove the type arguments from the output, as they are not relevant.
240235
// You can think of this as the reverse of `resolve_vars_if_possible`.
@@ -264,7 +259,7 @@ fn emit_orphan_check_error<'tcx>(
264259
};
265260

266261
let msg = format!("{} is not defined in the current crate{}", ty, postfix);
267-
if *is_target_ty {
262+
if is_target_ty {
268263
// Point at `D<A>` in `impl<A, B> for C<B> in D<A>`
269264
err.span_label(self_ty_span, &msg);
270265
} else {

0 commit comments

Comments
 (0)