Skip to content
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

Fix const-generics ICE related to binding #86795

Merged
merged 5 commits into from
Jul 3, 2021
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
82 changes: 0 additions & 82 deletions compiler/rustc_middle/src/ty/fold.rs
Original file line number Diff line number Diff line change
Expand Up @@ -754,88 +754,6 @@ impl<'tcx> TyCtxt<'tcx> {
}
}

pub struct BoundVarsCollector<'tcx> {
binder_index: ty::DebruijnIndex,
vars: BTreeMap<u32, ty::BoundVariableKind>,
// We may encounter the same variable at different levels of binding, so
// this can't just be `Ty`
visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
}

impl<'tcx> BoundVarsCollector<'tcx> {
pub fn new() -> Self {
BoundVarsCollector {
binder_index: ty::INNERMOST,
vars: BTreeMap::new(),
visited: SsoHashSet::default(),
}
}

pub fn into_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx ty::List<ty::BoundVariableKind> {
let max = self.vars.iter().map(|(k, _)| *k).max().unwrap_or_else(|| 0);
for i in 0..max {
if let None = self.vars.get(&i) {
panic!("Unknown variable: {:?}", i);
}
}

tcx.mk_bound_variable_kinds(self.vars.into_iter().map(|(_, v)| v))
}
}

impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
type BreakTy = ();

fn visit_binder<T: TypeFoldable<'tcx>>(
&mut self,
t: &Binder<'tcx, T>,
) -> ControlFlow<Self::BreakTy> {
self.binder_index.shift_in(1);
let result = t.super_visit_with(self);
self.binder_index.shift_out(1);
result
}

fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
if t.outer_exclusive_binder < self.binder_index
|| !self.visited.insert((self.binder_index, t))
{
return ControlFlow::CONTINUE;
}
use std::collections::btree_map::Entry;
match *t.kind() {
ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
match self.vars.entry(bound_ty.var.as_u32()) {
Entry::Vacant(entry) => {
entry.insert(ty::BoundVariableKind::Ty(bound_ty.kind));
}
Entry::Occupied(entry) => match entry.get() {
ty::BoundVariableKind::Ty(_) => {}
_ => bug!("Conflicting bound vars"),
},
}
}

_ => (),
};

t.super_visit_with(self)
}

fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
match r {
ty::ReLateBound(index, _br) if *index == self.binder_index => {
// If you hit this, you should be using `Binder::bind_with_vars` or `Binder::rebind`
bug!("Trying to collect bound vars with a bound region: {:?} {:?}", index, _br)
}

_ => (),
};

r.super_visit_with(self)
}
}

pub struct ValidateBoundVars<'tcx> {
bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
binder_index: ty::DebruijnIndex,
Expand Down
8 changes: 0 additions & 8 deletions compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use self::TyKind::*;

use crate::infer::canonical::Canonical;
use crate::ty::fold::BoundVarsCollector;
use crate::ty::fold::ValidateBoundVars;
use crate::ty::subst::{GenericArg, InternalSubsts, Subst, SubstsRef};
use crate::ty::InferTy::{self, *};
Expand Down Expand Up @@ -970,13 +969,6 @@ where
Binder(value, ty::List::empty())
}

/// Wraps `value` in a binder, binding higher-ranked vars (if any).
pub fn bind(value: T, tcx: TyCtxt<'tcx>) -> Binder<'tcx, T> {
let mut collector = BoundVarsCollector::new();
value.visit_with(&mut collector);
Binder(value, collector.into_vars(tcx))
}

pub fn bind_with_vars(value: T, vars: &'tcx List<BoundVariableKind>) -> Binder<'tcx, T> {
if cfg!(debug_assertions) {
let mut validator = ValidateBoundVars::new(vars);
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_middle/src/ty/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::ty::layout::IntegerExt;
use crate::ty::query::TyCtxtAt;
use crate::ty::subst::{GenericArgKind, Subst, SubstsRef};
use crate::ty::TyKind::*;
use crate::ty::{self, DefIdTree, List, Ty, TyCtxt, TypeFoldable};
use crate::ty::{self, DebruijnIndex, DefIdTree, List, Ty, TyCtxt, TypeFoldable};
use rustc_apfloat::Float as _;
use rustc_ast as ast;
use rustc_attr::{self as attr, SignedInt, UnsignedInt};
Expand Down Expand Up @@ -905,6 +905,10 @@ impl<'tcx> ty::TyS<'tcx> {
}
ty
}

pub fn outer_exclusive_binder(&'tcx self) -> DebruijnIndex {
self.outer_exclusive_binder
}
}

pub enum ExplicitSelf<'tcx> {
Expand Down
7 changes: 1 addition & 6 deletions compiler/rustc_mir/src/transform/check_consts/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -822,12 +822,7 @@ impl Visitor<'tcx> for Validator<'mir, 'tcx> {
let obligation = Obligation::new(
ObligationCause::dummy(),
param_env,
Binder::bind(
TraitPredicate {
trait_ref: TraitRef::from_method(tcx, trait_id, substs),
},
tcx,
),
Binder::dummy(TraitPredicate { trait_ref }),
);

let implsrc = tcx.infer_ctxt().enter(|infcx| {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/traits/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1301,7 +1301,7 @@ fn confirm_pointee_candidate<'cx, 'tcx>(
ty: self_ty.ptr_metadata_ty(tcx),
};

confirm_param_env_candidate(selcx, obligation, ty::Binder::bind(predicate, tcx), false)
confirm_param_env_candidate(selcx, obligation, ty::Binder::dummy(predicate), false)
}

fn confirm_fn_pointer_candidate<'cx, 'tcx>(
Expand Down
109 changes: 107 additions & 2 deletions compiler/rustc_ty_utils/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,114 @@ use rustc_errors::ErrorReported;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_infer::infer::TyCtxtInferExt;
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Instance, TyCtxt, TypeFoldable};
use rustc_middle::ty::{self, Binder, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitor};
use rustc_span::{sym, DUMMY_SP};
use rustc_target::spec::abi::Abi;
use rustc_trait_selection::traits;
use traits::{translate_substs, Reveal};

use rustc_data_structures::sso::SsoHashSet;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::ops::ControlFlow;

use tracing::debug;

// FIXME(#86795): `BoundVarsCollector` here should **NOT** be used
// outside of `resolve_associated_item`. It's just to address #64494,
// #83765, and #85848 which are creating bound types/regions that lose
// their `Binder` *unintentionally*.
// It's ideal to remove `BoundVarsCollector` and just use
// `ty::Binder::*` methods but we use this stopgap until we figure out
// the "real" fix.
struct BoundVarsCollector<'tcx> {
binder_index: ty::DebruijnIndex,
vars: BTreeMap<u32, ty::BoundVariableKind>,
// We may encounter the same variable at different levels of binding, so
// this can't just be `Ty`
visited: SsoHashSet<(ty::DebruijnIndex, Ty<'tcx>)>,
}

impl<'tcx> BoundVarsCollector<'tcx> {
fn new() -> Self {
BoundVarsCollector {
binder_index: ty::INNERMOST,
vars: BTreeMap::new(),
visited: SsoHashSet::default(),
}
}

fn into_vars(self, tcx: TyCtxt<'tcx>) -> &'tcx ty::List<ty::BoundVariableKind> {
let max = self.vars.iter().map(|(k, _)| *k).max().unwrap_or(0);
for i in 0..max {
if let None = self.vars.get(&i) {
panic!("Unknown variable: {:?}", i);
}
}

tcx.mk_bound_variable_kinds(self.vars.into_iter().map(|(_, v)| v))
}
}

impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector<'tcx> {
type BreakTy = ();

fn visit_binder<T: TypeFoldable<'tcx>>(
&mut self,
t: &Binder<'tcx, T>,
) -> ControlFlow<Self::BreakTy> {
self.binder_index.shift_in(1);
let result = t.super_visit_with(self);
self.binder_index.shift_out(1);
result
}

fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
if t.outer_exclusive_binder() < self.binder_index
|| !self.visited.insert((self.binder_index, t))
{
return ControlFlow::CONTINUE;
}
match *t.kind() {
ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => {
match self.vars.entry(bound_ty.var.as_u32()) {
Entry::Vacant(entry) => {
entry.insert(ty::BoundVariableKind::Ty(bound_ty.kind));
}
Entry::Occupied(entry) => match entry.get() {
ty::BoundVariableKind::Ty(_) => {}
_ => bug!("Conflicting bound vars"),
},
}
}

_ => (),
};

t.super_visit_with(self)
}

fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
jackh726 marked this conversation as resolved.
Show resolved Hide resolved
match r {
ty::ReLateBound(index, br) if *index == self.binder_index => {
match self.vars.entry(br.var.as_u32()) {
Entry::Vacant(entry) => {
entry.insert(ty::BoundVariableKind::Region(br.kind));
}
Entry::Occupied(entry) => match entry.get() {
ty::BoundVariableKind::Region(_) => {}
_ => bug!("Conflicting bound vars"),
},
}
}

_ => (),
};

r.super_visit_with(self)
}
}

#[instrument(level = "debug", skip(tcx))]
fn resolve_instance<'tcx>(
tcx: TyCtxt<'tcx>,
Expand Down Expand Up @@ -115,7 +215,12 @@ fn resolve_associated_item<'tcx>(
);

let trait_ref = ty::TraitRef::from_method(tcx, trait_id, rcvr_substs);
let vtbl = tcx.codegen_fulfill_obligation((param_env, ty::Binder::bind(trait_ref, tcx)))?;

// See FIXME on `BoundVarsCollector`.
let mut bound_vars_collector = BoundVarsCollector::new();
trait_ref.visit_with(&mut bound_vars_collector);
let trait_binder = ty::Binder::bind_with_vars(trait_ref, bound_vars_collector.into_vars(tcx));
let vtbl = tcx.codegen_fulfill_obligation((param_env, trait_binder))?;

// Now that we know which impl is being used, we can dispatch to
// the actual function:
Expand Down
1 change: 1 addition & 0 deletions compiler/rustc_ty_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
//! This API is completely unstable and subject to change.

#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
#![feature(control_flow_enum)]
#![feature(half_open_range_patterns)]
#![feature(exclusive_range_pattern)]
#![feature(nll)]
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_typeck/src/astconv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1694,7 +1694,7 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
};

self.one_bound_for_assoc_type(
|| traits::supertraits(tcx, ty::Binder::bind(trait_ref, tcx)),
|| traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
|| "Self".to_string(),
assoc_ident,
span,
Expand Down
11 changes: 3 additions & 8 deletions compiler/rustc_typeck/src/check/compare_method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,12 +222,7 @@ fn compare_predicate_entailment<'tcx>(
let mut selcx = traits::SelectionContext::new(&infcx);

let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
let (impl_m_own_bounds, _) = infcx.replace_bound_vars_with_fresh_vars(
impl_m_span,
infer::HigherRankedType,
ty::Binder::bind(impl_m_own_bounds.predicates, tcx),
);
for predicate in impl_m_own_bounds {
for predicate in impl_m_own_bounds.predicates {
let traits::Normalized { value: predicate, obligations } =
traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);

Expand Down Expand Up @@ -258,14 +253,14 @@ fn compare_predicate_entailment<'tcx>(
);
let impl_sig =
inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, impl_sig);
let impl_fty = tcx.mk_fn_ptr(ty::Binder::bind(impl_sig, tcx));
let impl_fty = tcx.mk_fn_ptr(ty::Binder::dummy(impl_sig));
debug!("compare_impl_method: impl_fty={:?}", impl_fty);

let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, tcx.fn_sig(trait_m.def_id));
let trait_sig = trait_sig.subst(tcx, trait_to_placeholder_substs);
let trait_sig =
inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, trait_sig);
let trait_fty = tcx.mk_fn_ptr(ty::Binder::bind(trait_sig, tcx));
let trait_fty = tcx.mk_fn_ptr(ty::Binder::dummy(trait_sig));

debug!("compare_impl_method: trait_fty={:?}", trait_fty);

Expand Down
10 changes: 7 additions & 3 deletions compiler/rustc_typeck/src/check/method/confirm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {

let (method_sig, method_predicates) =
self.normalize_associated_types_in(self.span, (method_sig, method_predicates));
let method_sig = ty::Binder::dummy(method_sig);

// Make sure nobody calls `drop()` explicitly.
self.enforce_illegal_method_limitations(&pick);
Expand All @@ -119,12 +120,15 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> {
// We won't add these if we encountered an illegal sized bound, so that we can use
// a custom error in that case.
if illegal_sized_bound.is_none() {
let method_ty = self.tcx.mk_fn_ptr(ty::Binder::bind(method_sig, self.tcx));
self.add_obligations(method_ty, all_substs, method_predicates);
self.add_obligations(self.tcx.mk_fn_ptr(method_sig), all_substs, method_predicates);
}

// Create the final `MethodCallee`.
let callee = MethodCallee { def_id: pick.item.def_id, substs: all_substs, sig: method_sig };
let callee = MethodCallee {
def_id: pick.item.def_id,
substs: all_substs,
sig: method_sig.skip_binder(),
};
ConfirmResult { callee, illegal_sized_bound }
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_typeck/src/check/method/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
obligations.extend(traits::predicates_for_generics(cause.clone(), self.param_env, bounds));

// Also add an obligation for the method type being well-formed.
let method_ty = tcx.mk_fn_ptr(ty::Binder::bind(fn_sig, tcx));
let method_ty = tcx.mk_fn_ptr(ty::Binder::dummy(fn_sig));
debug!(
"lookup_in_trait_adjusted: matched method method_ty={:?} obligation={:?}",
method_ty, obligation
Expand Down
5 changes: 0 additions & 5 deletions compiler/rustc_typeck/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1087,14 +1087,9 @@ fn check_method_receiver<'fcx, 'tcx>(
debug!("check_method_receiver: sig={:?}", sig);

let self_ty = fcx.normalize_associated_types_in(span, self_ty);
jackh726 marked this conversation as resolved.
Show resolved Hide resolved
let self_ty =
fcx.tcx.liberate_late_bound_regions(method.def_id, ty::Binder::bind(self_ty, fcx.tcx));

jackh726 marked this conversation as resolved.
Show resolved Hide resolved
let receiver_ty = sig.inputs()[0];

let receiver_ty = fcx.normalize_associated_types_in(span, receiver_ty);
let receiver_ty =
fcx.tcx.liberate_late_bound_regions(method.def_id, ty::Binder::bind(receiver_ty, fcx.tcx));

if fcx.tcx.features().arbitrary_self_types {
if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
Expand Down
Loading