Skip to content

stop using ty::UnevaluatedConst directly #103227

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion compiler/rustc_hir_analysis/src/check/dropck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ fn ensure_drop_predicates_are_implied_by_item_defn<'tcx>(
(
ty::PredicateKind::ConstEvaluatable(a),
ty::PredicateKind::ConstEvaluatable(b),
) => tcx.try_unify_abstract_consts(self_param_env.and((a, b))),
) => relator.relate(predicate.rebind(a), predicate.rebind(b)).is_ok(),
(
ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_a, lt_a)),
ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty_b, lt_b)),
Expand Down
7 changes: 1 addition & 6 deletions compiler/rustc_hir_analysis/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1101,8 +1101,6 @@ fn check_type_defn<'tcx, F>(

// Explicit `enum` discriminant values must const-evaluate successfully.
if let Some(discr_def_id) = variant.explicit_discr {
let discr_substs = InternalSubsts::identity_for_item(tcx, discr_def_id.to_def_id());

let cause = traits::ObligationCause::new(
tcx.def_span(discr_def_id),
wfcx.body_id,
Expand All @@ -1112,10 +1110,7 @@ fn check_type_defn<'tcx, F>(
cause,
wfcx.param_env,
ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(
ty::UnevaluatedConst::new(
ty::WithOptConstParam::unknown(discr_def_id.to_def_id()),
discr_substs,
),
ty::Const::from_anon_const(tcx, discr_def_id),
))
.to_predicate(tcx),
));
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/collect/predicates_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,10 @@ fn const_evaluatable_predicates_of<'tcx>(
fn visit_anon_const(&mut self, c: &'tcx hir::AnonConst) {
let def_id = self.tcx.hir().local_def_id(c.hir_id);
let ct = ty::Const::from_anon_const(self.tcx, def_id);
if let ty::ConstKind::Unevaluated(uv) = ct.kind() {
if let ty::ConstKind::Unevaluated(_) = ct.kind() {
let span = self.tcx.hir().span(c.hir_id);
self.preds.insert((
ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(uv))
ty::Binder::dummy(ty::PredicateKind::ConstEvaluatable(ct))
.to_predicate(self.tcx),
span,
));
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_middle/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
#![feature(drain_filter)]
#![feature(intra_doc_pointers)]
#![feature(yeet_expr)]
#![feature(result_option_inspect)]
#![feature(const_option)]
#![recursion_limit = "512"]
#![allow(rustc::potential_query_instability)]
Expand Down
26 changes: 25 additions & 1 deletion compiler/rustc_middle/src/mir/interpret/queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use crate::mir;
use crate::ty::subst::InternalSubsts;
use crate::ty::visit::TypeVisitable;
use crate::ty::{self, query::TyCtxtAt, query::TyCtxtEnsure, TyCtxt};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_session::lint;
use rustc_span::{Span, DUMMY_SP};

impl<'tcx> TyCtxt<'tcx> {
Expand Down Expand Up @@ -83,7 +85,29 @@ impl<'tcx> TyCtxt<'tcx> {
match ty::Instance::resolve_opt_const_arg(self, param_env, ct.def, ct.substs) {
Ok(Some(instance)) => {
let cid = GlobalId { instance, promoted: None };
self.const_eval_global_id_for_typeck(param_env, cid, span)
self.const_eval_global_id_for_typeck(param_env, cid, span).inspect(|_| {
// We are emitting the lint here instead of in `is_const_evaluatable`
// as we normalize obligations before checking them, and normalization
// uses this function to evaluate this constant.
//
// @lcnr believes that successfully evaluating even though there are
// used generic parameters is a bug of evaluation, so checking for it
// here does feel somewhat sensible.
if !self.features().generic_const_exprs && ct.substs.has_non_region_param() {
assert!(matches!(self.def_kind(ct.def.did), DefKind::AnonConst));
let mir_body = self.mir_for_ctfe_opt_const_arg(ct.def);
if mir_body.is_polymorphic {
let Some(local_def_id) = ct.def.did.as_local() else { return };
self.struct_span_lint_hir(
lint::builtin::CONST_EVALUATABLE_UNCHECKED,
self.hir().local_def_id_to_hir_id(local_def_id),
self.def_span(ct.def.did),
"cannot use constants which depend on generic parameters in types",
|err| err,
)
}
}
})
}
Ok(None) => Err(ErrorHandled::TooGeneric),
Err(error_reported) => Err(ErrorHandled::Reported(error_reported)),
Expand Down
4 changes: 4 additions & 0 deletions compiler/rustc_middle/src/ty/consts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,10 @@ impl<'tcx> Const<'tcx> {
self.try_eval_usize(tcx, param_env)
.unwrap_or_else(|| bug!("expected usize, got {:#?}", self))
}

pub fn is_ct_infer(self) -> bool {
matches!(self.kind(), ty::ConstKind::Infer(_))
}
}

pub fn const_param_default<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> Const<'tcx> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/consts/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use super::ScalarInt;

/// An unevaluated (potentially generic) constant used in the type-system.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)]
#[derive(Hash, HashStable)]
#[derive(Hash, HashStable, TypeFoldable, TypeVisitable)]
pub struct UnevaluatedConst<'tcx> {
pub def: ty::WithOptConstParam<DefId>,
pub substs: SubstsRef<'tcx>,
Expand Down
18 changes: 5 additions & 13 deletions compiler/rustc_middle/src/ty/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,6 @@ impl FlagComputation {
result.flags
}

pub fn for_unevaluated_const(uv: ty::UnevaluatedConst<'_>) -> TypeFlags {
let mut result = FlagComputation::new();
result.add_unevaluated_const(uv);
result.flags
}

fn add_flags(&mut self, flags: TypeFlags) {
self.flags = self.flags | flags;
}
Expand Down Expand Up @@ -256,7 +250,7 @@ impl FlagComputation {
self.add_substs(substs);
}
ty::PredicateKind::ConstEvaluatable(uv) => {
self.add_unevaluated_const(uv);
self.add_const(uv);
}
ty::PredicateKind::ConstEquate(expected, found) => {
self.add_const(expected);
Expand Down Expand Up @@ -289,7 +283,10 @@ impl FlagComputation {
fn add_const(&mut self, c: ty::Const<'_>) {
self.add_ty(c.ty());
match c.kind() {
ty::ConstKind::Unevaluated(unevaluated) => self.add_unevaluated_const(unevaluated),
ty::ConstKind::Unevaluated(uv) => {
self.add_substs(uv.substs);
self.add_flags(TypeFlags::HAS_CT_PROJECTION);
}
ty::ConstKind::Infer(infer) => {
self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE);
match infer {
Expand All @@ -313,11 +310,6 @@ impl FlagComputation {
}
}

fn add_unevaluated_const(&mut self, ct: ty::UnevaluatedConst<'_>) {
self.add_substs(ct.substs);
self.add_flags(TypeFlags::HAS_CT_PROJECTION);
}

fn add_existential_projection(&mut self, projection: &ty::ExistentialProjection<'_>) {
self.add_substs(projection.substs);
match projection.term.unpack() {
Expand Down
21 changes: 0 additions & 21 deletions compiler/rustc_middle/src/ty/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,13 +126,6 @@ pub trait TypeFolder<'tcx>: FallibleTypeFolder<'tcx, Error = !> {
c.super_fold_with(self)
}

fn fold_ty_unevaluated(
&mut self,
uv: ty::UnevaluatedConst<'tcx>,
) -> ty::UnevaluatedConst<'tcx> {
uv.super_fold_with(self)
}

fn fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> ty::Predicate<'tcx> {
p.super_fold_with(self)
}
Expand Down Expand Up @@ -169,13 +162,6 @@ pub trait FallibleTypeFolder<'tcx>: Sized {
c.try_super_fold_with(self)
}

fn try_fold_ty_unevaluated(
&mut self,
c: ty::UnevaluatedConst<'tcx>,
) -> Result<ty::UnevaluatedConst<'tcx>, Self::Error> {
c.try_super_fold_with(self)
}

fn try_fold_predicate(
&mut self,
p: ty::Predicate<'tcx>,
Expand Down Expand Up @@ -215,13 +201,6 @@ where
Ok(self.fold_const(c))
}

fn try_fold_ty_unevaluated(
&mut self,
c: ty::UnevaluatedConst<'tcx>,
) -> Result<ty::UnevaluatedConst<'tcx>, !> {
Ok(self.fold_ty_unevaluated(c))
}

fn try_fold_predicate(&mut self, p: ty::Predicate<'tcx>) -> Result<ty::Predicate<'tcx>, !> {
Ok(self.fold_predicate(p))
}
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -682,7 +682,7 @@ pub enum PredicateKind<'tcx> {
Coerce(CoercePredicate<'tcx>),

/// Constant initializer must evaluate successfully.
ConstEvaluatable(ty::UnevaluatedConst<'tcx>),
ConstEvaluatable(ty::Const<'tcx>),

/// Constants must be equal. The first component is the const that is expected.
ConstEquate(Const<'tcx>, Const<'tcx>),
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2702,8 +2702,8 @@ define_print_and_forward_display! {
print_value_path(closure_def_id, &[]),
write("` implements the trait `{}`", kind))
}
ty::PredicateKind::ConstEvaluatable(uv) => {
p!("the constant `", print_value_path(uv.def.did, uv.substs), "` can be evaluated")
ty::PredicateKind::ConstEvaluatable(ct) => {
p!("the constant `", print(ct), "` can be evaluated")
}
ty::PredicateKind::ConstEquate(c1, c2) => {
p!("the constant `", print(c1), "` equals `", print(c2), "`")
Expand Down
25 changes: 2 additions & 23 deletions compiler/rustc_middle/src/ty/structural_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,8 @@ impl<'tcx> fmt::Debug for ty::PredicateKind<'tcx> {
ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
write!(f, "ClosureKind({:?}, {:?}, {:?})", closure_def_id, closure_substs, kind)
}
ty::PredicateKind::ConstEvaluatable(uv) => {
write!(f, "ConstEvaluatable({:?}, {:?})", uv.def, uv.substs)
ty::PredicateKind::ConstEvaluatable(ct) => {
write!(f, "ConstEvaluatable({ct:?})")
}
ty::PredicateKind::ConstEquate(c1, c2) => write!(f, "ConstEquate({:?}, {:?})", c1, c2),
ty::PredicateKind::TypeWellFormedFromEnv(ty) => {
Expand Down Expand Up @@ -832,27 +832,6 @@ impl<'tcx> TypeVisitable<'tcx> for InferConst<'tcx> {
}
}

impl<'tcx> TypeFoldable<'tcx> for ty::UnevaluatedConst<'tcx> {
fn try_fold_with<F: FallibleTypeFolder<'tcx>>(self, folder: &mut F) -> Result<Self, F::Error> {
folder.try_fold_ty_unevaluated(self)
}
}

impl<'tcx> TypeVisitable<'tcx> for ty::UnevaluatedConst<'tcx> {
fn visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
visitor.visit_ty_unevaluated(*self)
}
}

impl<'tcx> TypeSuperFoldable<'tcx> for ty::UnevaluatedConst<'tcx> {
fn try_super_fold_with<F: FallibleTypeFolder<'tcx>>(
self,
folder: &mut F,
) -> Result<Self, F::Error> {
Ok(ty::UnevaluatedConst { def: self.def, substs: self.substs.try_fold_with(folder)? })
}
}

impl<'tcx> TypeSuperVisitable<'tcx> for ty::UnevaluatedConst<'tcx> {
fn super_visit_with<V: TypeVisitor<'tcx>>(&self, visitor: &mut V) -> ControlFlow<V::BreakTy> {
self.substs.visit_with(visitor)
Expand Down
8 changes: 8 additions & 0 deletions compiler/rustc_middle/src/ty/subst.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ impl<'tcx> GenericArg<'tcx> {
_ => bug!("expected a const, but found another kind"),
}
}

pub fn is_non_region_infer(self) -> bool {
match self.unpack() {
GenericArgKind::Lifetime(_) => false,
GenericArgKind::Type(ty) => ty.is_ty_infer(),
GenericArgKind::Const(ct) => ct.is_ct_infer(),
}
}
}

impl<'a, 'tcx> Lift<'tcx> for GenericArg<'a> {
Expand Down
22 changes: 0 additions & 22 deletions compiler/rustc_middle/src/ty/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,13 +197,6 @@ pub trait TypeVisitor<'tcx>: Sized {
c.super_visit_with(self)
}

fn visit_ty_unevaluated(
&mut self,
uv: ty::UnevaluatedConst<'tcx>,
) -> ControlFlow<Self::BreakTy> {
uv.super_visit_with(self)
}

fn visit_predicate(&mut self, p: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
p.super_visit_with(self)
}
Expand Down Expand Up @@ -592,21 +585,6 @@ impl<'tcx> TypeVisitor<'tcx> for HasTypeFlagsVisitor {
}
}

#[inline]
#[instrument(level = "trace", ret)]
fn visit_ty_unevaluated(
&mut self,
uv: ty::UnevaluatedConst<'tcx>,
) -> ControlFlow<Self::BreakTy> {
let flags = FlagComputation::for_unevaluated_const(uv);
trace!(r.flags=?flags);
if flags.intersects(self.flags) {
ControlFlow::Break(FoundFlags)
} else {
ControlFlow::CONTINUE
}
}

#[inline]
#[instrument(level = "trace", ret)]
fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow<Self::BreakTy> {
Expand Down
16 changes: 16 additions & 0 deletions compiler/rustc_middle/src/ty/walk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,22 @@ impl<'tcx> Ty<'tcx> {
}
}

impl<'tcx> ty::Const<'tcx> {
/// Iterator that walks `self` and any types reachable from
/// `self`, in depth-first order. Note that just walks the types
/// that appear in `self`, it does not descend into the fields of
/// structs or variants. For example:
///
/// ```text
/// isize => { isize }
/// Foo<Bar<isize>> => { Foo<Bar<isize>>, Bar<isize>, isize }
/// [isize] => { [isize], isize }
/// ```
pub fn walk(self) -> TypeWalker<'tcx> {
TypeWalker::new(self.into())
}
}

/// We push `GenericArg`s on the stack in reverse order so as to
/// maintain a pre-order traversal. As of the time of this
/// writing, the fact that the traversal is pre-order is not
Expand Down
35 changes: 10 additions & 25 deletions compiler/rustc_privacy/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,34 +159,12 @@ where
ty.visit_with(self)
}
ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE,
ty::PredicateKind::ConstEvaluatable(uv)
if self.def_id_visitor.tcx().features().generic_const_exprs =>
{
let tcx = self.def_id_visitor.tcx();
if let Ok(Some(ct)) = AbstractConst::new(tcx, uv) {
self.visit_abstract_const_expr(tcx, ct)?;
}
ControlFlow::CONTINUE
}
ty::PredicateKind::ConstEvaluatable(ct) => ct.visit_with(self),
ty::PredicateKind::WellFormed(arg) => arg.visit_with(self),
_ => bug!("unexpected predicate: {:?}", predicate),
}
}

fn visit_abstract_const_expr(
&mut self,
tcx: TyCtxt<'tcx>,
ct: AbstractConst<'tcx>,
) -> ControlFlow<V::BreakTy> {
walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
ACNode::Leaf(leaf) => self.visit_const(leaf),
ACNode::Cast(_, _, ty) => self.visit_ty(ty),
ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
ControlFlow::CONTINUE
}
})
}

fn visit_predicates(
&mut self,
predicates: ty::GenericPredicates<'tcx>,
Expand Down Expand Up @@ -309,9 +287,16 @@ where
self.visit_ty(c.ty())?;
let tcx = self.def_id_visitor.tcx();
if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) {
self.visit_abstract_const_expr(tcx, ct)?;
walk_abstract_const(tcx, ct, |node| match node.root(tcx) {
ACNode::Leaf(leaf) => self.visit_const(leaf),
ACNode::Cast(_, _, ty) => self.visit_ty(ty),
ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => {
ControlFlow::CONTINUE
}
})
} else {
ControlFlow::CONTINUE
}
ControlFlow::CONTINUE
}
}

Expand Down
Loading