From e21b82e035050570a8d8e77ebe8b50f7d34ad251 Mon Sep 17 00:00:00 2001 From: Florian Diebold Date: Fri, 15 Nov 2019 20:32:58 +0100 Subject: Upgrade Chalk Associated type values (in impls) are now a separate entity in Chalk, so we have to intern separate IDs for them. --- crates/ra_hir/src/ty/traits.rs | 13 +- crates/ra_hir/src/ty/traits/chalk.rs | 286 ++++++++++++++++++++++------------- 2 files changed, 191 insertions(+), 108 deletions(-) (limited to 'crates/ra_hir/src/ty') diff --git a/crates/ra_hir/src/ty/traits.rs b/crates/ra_hir/src/ty/traits.rs index 4f1eab150..771525deb 100644 --- a/crates/ra_hir/src/ty/traits.rs +++ b/crates/ra_hir/src/ty/traits.rs @@ -8,7 +8,7 @@ use ra_prof::profile; use rustc_hash::FxHashSet; use super::{Canonical, GenericPredicate, HirDisplay, ProjectionTy, TraitRef, Ty, TypeWalk}; -use crate::{db::HirDatabase, expr::ExprId, Crate, DefWithBody, ImplBlock, Trait}; +use crate::{db::HirDatabase, expr::ExprId, Crate, DefWithBody, ImplBlock, Trait, TypeAlias}; use self::chalk::{from_chalk, ToChalk}; @@ -300,3 +300,14 @@ pub enum Impl { /// Closure types implement the Fn traits synthetically. ClosureFnTraitImpl(ClosureFnTraitImplData), } + +/// An associated type value. Usually this comes from a `type` declaration +/// inside an impl block, but for built-in impls we have to synthesize it. +/// (We only need this because Chalk wants a unique ID for each of these.) +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub enum AssocTyValue { + /// A normal assoc type value from an impl block. + TypeAlias(TypeAlias), + /// The output type of the Fn trait implementation. + ClosureFnTraitImplOutput(ClosureFnTraitImplData), +} diff --git a/crates/ra_hir/src/ty/traits/chalk.rs b/crates/ra_hir/src/ty/traits/chalk.rs index 68304b950..e39e8aaca 100644 --- a/crates/ra_hir/src/ty/traits/chalk.rs +++ b/crates/ra_hir/src/ty/traits/chalk.rs @@ -7,22 +7,19 @@ use chalk_ir::{ cast::Cast, family::ChalkIr, Identifier, ImplId, Parameter, PlaceholderIndex, TypeId, TypeKindId, TypeName, UniverseIndex, }; -use chalk_rust_ir::{AssociatedTyDatum, ImplDatum, StructDatum, TraitDatum}; +use chalk_rust_ir::{AssociatedTyDatum, AssociatedTyValue, ImplDatum, StructDatum, TraitDatum}; use hir_expand::name; use ra_db::salsa::{InternId, InternKey}; -use super::{Canonical, ChalkContext, Impl, Obligation}; +use super::{AssocTyValue, Canonical, ChalkContext, Impl, Obligation}; use crate::{ db::HirDatabase, generics::{GenericDef, HasGenericParams}, ty::display::HirDisplay, - ty::{ - ApplicationTy, GenericPredicate, Namespace, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, - TypeWalk, - }, - AssocItem, Crate, HasBody, ImplBlock, Trait, TypeAlias, + ty::{ApplicationTy, GenericPredicate, ProjectionTy, Substs, TraitRef, Ty, TypeCtor, TypeWalk}, + Crate, HasBody, ImplBlock, Trait, TypeAlias, }; /// This represents a trait whose name we could not resolve. @@ -59,29 +56,29 @@ impl ToChalk for Ty { } }; let parameters = apply_ty.parameters.to_chalk(db); - chalk_ir::ApplicationTy { name, parameters }.cast() + chalk_ir::ApplicationTy { name, parameters }.cast().intern() } Ty::Projection(proj_ty) => { let associated_ty_id = proj_ty.associated_ty.to_chalk(db); let parameters = proj_ty.parameters.to_chalk(db); - chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast() + chalk_ir::ProjectionTy { associated_ty_id, parameters }.cast().intern() } Ty::Param { idx, .. } => { PlaceholderIndex { ui: UniverseIndex::ROOT, idx: idx as usize }.to_ty::() } - Ty::Bound(idx) => chalk_ir::Ty::BoundVar(idx as usize), + Ty::Bound(idx) => chalk_ir::TyData::BoundVar(idx as usize).intern(), Ty::Infer(_infer_ty) => panic!("uncanonicalized infer ty"), // FIXME use Chalk's Dyn/Opaque once the bugs with that are fixed Ty::Unknown | Ty::Dyn(_) | Ty::Opaque(_) => { let parameters = Vec::new(); let name = TypeName::Error; - chalk_ir::ApplicationTy { name, parameters }.cast() + chalk_ir::ApplicationTy { name, parameters }.cast().intern() } } } fn from_chalk(db: &impl HirDatabase, chalk: chalk_ir::Ty) -> Self { - match chalk { - chalk_ir::Ty::Apply(apply_ty) => { + match chalk.data().clone() { + chalk_ir::TyData::Apply(apply_ty) => { // FIXME this is kind of hacky due to the fact that // TypeName::Placeholder is a Ty::Param on our side match apply_ty.name { @@ -104,21 +101,21 @@ impl ToChalk for Ty { } } } - chalk_ir::Ty::Projection(proj) => { + chalk_ir::TyData::Projection(proj) => { let associated_ty = from_chalk(db, proj.associated_ty_id); let parameters = from_chalk(db, proj.parameters); Ty::Projection(ProjectionTy { associated_ty, parameters }) } - chalk_ir::Ty::ForAll(_) => unimplemented!(), - chalk_ir::Ty::BoundVar(idx) => Ty::Bound(idx as u32), - chalk_ir::Ty::InferenceVar(_iv) => Ty::Unknown, - chalk_ir::Ty::Dyn(where_clauses) => { + chalk_ir::TyData::ForAll(_) => unimplemented!(), + chalk_ir::TyData::BoundVar(idx) => Ty::Bound(idx as u32), + chalk_ir::TyData::InferenceVar(_iv) => Ty::Unknown, + chalk_ir::TyData::Dyn(where_clauses) => { assert_eq!(where_clauses.binders.len(), 1); let predicates = where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); Ty::Dyn(predicates) } - chalk_ir::Ty::Opaque(where_clauses) => { + chalk_ir::TyData::Opaque(where_clauses) => { assert_eq!(where_clauses.binders.len(), 1); let predicates = where_clauses.value.into_iter().map(|c| from_chalk(db, c)).collect(); @@ -211,6 +208,21 @@ impl ToChalk for TypeAlias { } } +impl ToChalk for AssocTyValue { + type Chalk = chalk_rust_ir::AssociatedTyValueId; + + fn to_chalk(self, db: &impl HirDatabase) -> chalk_rust_ir::AssociatedTyValueId { + db.intern_assoc_ty_value(self).into() + } + + fn from_chalk( + db: &impl HirDatabase, + assoc_ty_value_id: chalk_rust_ir::AssociatedTyValueId, + ) -> AssocTyValue { + db.lookup_intern_assoc_ty_value(assoc_ty_value_id.into()) + } +} + impl ToChalk for GenericPredicate { type Chalk = chalk_ir::QuantifiedWhereClause; @@ -462,13 +474,11 @@ where fn type_name(&self, _id: TypeKindId) -> Identifier { unimplemented!() } - fn split_projection<'p>( + fn associated_ty_value( &self, - projection: &'p chalk_ir::ProjectionTy, - ) -> (Arc, &'p [Parameter], &'p [Parameter]) { - debug!("split_projection {:?}", projection); - // we don't support GATs, so I think this should always be correct currently - (self.db.associated_ty_data(projection.associated_ty_id), &projection.parameters, &[]) + id: chalk_rust_ir::AssociatedTyValueId, + ) -> Arc { + self.db.associated_ty_value(self.krate, id) } fn custom_clauses(&self) -> Vec> { vec![] @@ -493,19 +503,16 @@ pub(crate) fn associated_ty_data_query( _ => panic!("associated type not in trait"), }; let generic_params = type_alias.generic_params(db); - let parameter_kinds = generic_params - .params_including_parent() - .into_iter() - .map(|p| chalk_ir::ParameterKind::Ty(lalrpop_intern::intern(&p.name.to_string()))) - .collect(); + let bound_data = chalk_rust_ir::AssociatedTyDatumBound { + // FIXME add bounds and where clauses + bounds: vec![], + where_clauses: vec![], + }; let datum = AssociatedTyDatum { trait_id: trait_.to_chalk(db), id, name: lalrpop_intern::intern(&type_alias.name(db).to_string()), - parameter_kinds, - // FIXME add bounds and where clauses - bounds: vec![], - where_clauses: vec![], + binders: make_binders(bound_data, generic_params.count_params_including_parent()), }; Arc::new(datum) } @@ -517,14 +524,7 @@ pub(crate) fn trait_datum_query( ) -> Arc { debug!("trait_datum {:?}", trait_id); if trait_id == UNKNOWN_TRAIT { - let trait_datum_bound = chalk_rust_ir::TraitDatumBound { - trait_ref: chalk_ir::TraitRef { - trait_id: UNKNOWN_TRAIT, - parameters: vec![chalk_ir::Ty::BoundVar(0).cast()], - }, - associated_ty_ids: Vec::new(), - where_clauses: Vec::new(), - }; + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses: Vec::new() }; let flags = chalk_rust_ir::TraitFlags { auto: false, @@ -532,18 +532,24 @@ pub(crate) fn trait_datum_query( upstream: true, fundamental: false, non_enumerable: true, + coinductive: false, }; - return Arc::new(TraitDatum { binders: make_binders(trait_datum_bound, 1), flags }); + return Arc::new(TraitDatum { + id: trait_id, + binders: make_binders(trait_datum_bound, 1), + flags, + associated_ty_ids: vec![], + }); } let trait_: Trait = from_chalk(db, trait_id); debug!("trait {:?} = {:?}", trait_id, trait_.name(db)); let generic_params = trait_.generic_params(db); let bound_vars = Substs::bound_vars(&generic_params); - let trait_ref = trait_.trait_ref(db).subst(&bound_vars).to_chalk(db); let flags = chalk_rust_ir::TraitFlags { auto: trait_.is_auto(db), upstream: trait_.module(db).krate() != krate, non_enumerable: true, + coinductive: false, // only relevant for Chalk testing // FIXME set these flags correctly marker: false, fundamental: false, @@ -558,10 +564,13 @@ pub(crate) fn trait_datum_query( }) .map(|type_alias| type_alias.to_chalk(db)) .collect(); - let trait_datum_bound = - chalk_rust_ir::TraitDatumBound { trait_ref, where_clauses, associated_ty_ids }; - let trait_datum = - TraitDatum { binders: make_binders(trait_datum_bound, bound_vars.len()), flags }; + let trait_datum_bound = chalk_rust_ir::TraitDatumBound { where_clauses }; + let trait_datum = TraitDatum { + id: trait_id, + binders: make_binders(trait_datum_bound, bound_vars.len()), + flags, + associated_ty_ids, + }; Arc::new(trait_datum) } @@ -588,17 +597,12 @@ pub(crate) fn struct_datum_query( // FIXME set fundamental flag correctly fundamental: false, }; - let self_ty = chalk_ir::ApplicationTy { - name: TypeName::TypeKindId(type_ctor.to_chalk(db).into()), - parameters: (0..num_params).map(|i| chalk_ir::Ty::BoundVar(i).cast()).collect(), - }; let struct_datum_bound = chalk_rust_ir::StructDatumBound { - self_ty, fields: Vec::new(), // FIXME add fields (only relevant for auto traits) where_clauses, - flags, }; - let struct_datum = StructDatum { binders: make_binders(struct_datum_bound, num_params) }; + let struct_datum = + StructDatum { id: struct_id, binders: make_binders(struct_datum_bound, num_params), flags }; Arc::new(struct_datum) } @@ -612,10 +616,9 @@ pub(crate) fn impl_datum_query( let impl_: Impl = from_chalk(db, impl_id); match impl_ { Impl::ImplBlock(impl_block) => impl_block_datum(db, krate, impl_id, impl_block), - Impl::ClosureFnTraitImpl(data) => { - closure_fn_trait_impl_datum(db, krate, impl_id, data).unwrap_or_else(invalid_impl_datum) - } + Impl::ClosureFnTraitImpl(data) => closure_fn_trait_impl_datum(db, krate, data), } + .unwrap_or_else(invalid_impl_datum) } fn impl_block_datum( @@ -623,13 +626,11 @@ fn impl_block_datum( krate: Crate, impl_id: ImplId, impl_block: ImplBlock, -) -> Arc { +) -> Option> { let generic_params = impl_block.generic_params(db); let bound_vars = Substs::bound_vars(&generic_params); - let trait_ref = impl_block - .target_trait_ref(db) - .expect("FIXME handle unresolved impl block trait ref") - .subst(&bound_vars); + let trait_ref = impl_block.target_trait_ref(db)?.subst(&bound_vars); + let trait_ = trait_ref.trait_; let impl_type = if impl_block.krate(db) == krate { chalk_rust_ir::ImplType::Local } else { @@ -644,28 +645,7 @@ fn impl_block_datum( trait_ref.display(db), where_clauses ); - let trait_ = trait_ref.trait_; let trait_ref = trait_ref.to_chalk(db); - let associated_ty_values = impl_block - .items(db) - .into_iter() - .filter_map(|item| match item { - AssocItem::TypeAlias(t) => Some(t), - _ => None, - }) - .filter_map(|t| { - let assoc_ty = trait_.associated_type_by_name(db, &t.name(db))?; - let ty = db.type_for_def(t.into(), Namespace::Types).subst(&bound_vars); - Some(chalk_rust_ir::AssociatedTyValue { - impl_id, - associated_ty_id: assoc_ty.to_chalk(db), - value: chalk_ir::Binders { - value: chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) }, - binders: vec![], // we don't support GATs yet - }, - }) - }) - .collect(); let polarity = if negative { chalk_rust_ir::Polarity::Negative @@ -673,31 +653,41 @@ fn impl_block_datum( chalk_rust_ir::Polarity::Positive }; - let impl_datum_bound = - chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses, associated_ty_values }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses }; + let associated_ty_value_ids = impl_block + .items(db) + .into_iter() + .filter_map(|item| match item { + crate::AssocItem::TypeAlias(type_alias) => Some(type_alias), + _ => None, + }) + .filter(|type_alias| { + // don't include associated types that don't exist in the trait + trait_.associated_type_by_name(db, &type_alias.name(db)).is_some() + }) + .map(|type_alias| AssocTyValue::TypeAlias(type_alias).to_chalk(db)) + .collect(); debug!("impl_datum: {:?}", impl_datum_bound); let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, bound_vars.len()), impl_type, polarity, + associated_ty_value_ids, }; - Arc::new(impl_datum) + Some(Arc::new(impl_datum)) } fn invalid_impl_datum() -> Arc { let trait_ref = chalk_ir::TraitRef { trait_id: UNKNOWN_TRAIT, - parameters: vec![chalk_ir::Ty::BoundVar(0).cast()], - }; - let impl_datum_bound = chalk_rust_ir::ImplDatumBound { - trait_ref, - where_clauses: Vec::new(), - associated_ty_values: Vec::new(), + parameters: vec![chalk_ir::TyData::BoundVar(0).cast().intern().cast()], }; + let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref, where_clauses: Vec::new() }; let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, 1), impl_type: chalk_rust_ir::ImplType::External, polarity: chalk_rust_ir::Polarity::Positive, + associated_ty_value_ids: Vec::new(), }; Arc::new(impl_datum) } @@ -705,15 +695,19 @@ fn invalid_impl_datum() -> Arc { fn closure_fn_trait_impl_datum( db: &impl HirDatabase, krate: Crate, - impl_id: ImplId, data: super::ClosureFnTraitImplData, ) -> Option> { // for some closure |X, Y| -> Z: // impl Fn<(T, U)> for closure V> { Output = V } - let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?; let trait_ = get_fn_trait(db, krate, data.fn_trait)?; // get corresponding fn trait + // validate FnOnce trait, since we need it in the assoc ty value definition + // and don't want to return a valid value only to find out later that FnOnce + // is broken + let fn_once_trait = get_fn_trait(db, krate, super::FnTrait::FnOnce)?; + fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?; + let num_args: u16 = match &data.def.body(db)[data.expr] { crate::expr::Expr::Lambda { args, .. } => args.len() as u16, _ => { @@ -726,7 +720,6 @@ fn closure_fn_trait_impl_datum( TypeCtor::Tuple { cardinality: num_args }, Substs::builder(num_args as usize).fill_with_bound_vars(0).build(), ); - let output_ty = Ty::Bound(num_args.into()); let sig_ty = Ty::apply( TypeCtor::FnPtr { num_args }, Substs::builder(num_args as usize + 1).fill_with_bound_vars(0).build(), @@ -739,32 +732,99 @@ fn closure_fn_trait_impl_datum( substs: Substs::build_for_def(db, trait_).push(self_ty).push(arg_ty).build(), }; - let output_ty_id = fn_once_trait.associated_type_by_name(db, &name::OUTPUT_TYPE)?; - - let output_ty_value = chalk_rust_ir::AssociatedTyValue { - associated_ty_id: output_ty_id.to_chalk(db), - impl_id, - value: make_binders( - chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) }, - 0, - ), - }; + let output_ty_id = AssocTyValue::ClosureFnTraitImplOutput(data.clone()).to_chalk(db); let impl_type = chalk_rust_ir::ImplType::External; let impl_datum_bound = chalk_rust_ir::ImplDatumBound { trait_ref: trait_ref.to_chalk(db), where_clauses: Vec::new(), - associated_ty_values: vec![output_ty_value], }; let impl_datum = ImplDatum { binders: make_binders(impl_datum_bound, num_args as usize + 1), impl_type, polarity: chalk_rust_ir::Polarity::Positive, + associated_ty_value_ids: vec![output_ty_id], }; Some(Arc::new(impl_datum)) } +pub(crate) fn associated_ty_value_query( + db: &impl HirDatabase, + krate: Crate, + id: chalk_rust_ir::AssociatedTyValueId, +) -> Arc { + let data: AssocTyValue = from_chalk(db, id); + match data { + AssocTyValue::TypeAlias(type_alias) => { + type_alias_associated_ty_value(db, krate, type_alias) + } + AssocTyValue::ClosureFnTraitImplOutput(data) => { + closure_fn_trait_output_assoc_ty_value(db, krate, data) + } + } +} + +fn type_alias_associated_ty_value( + db: &impl HirDatabase, + _krate: Crate, + type_alias: TypeAlias, +) -> Arc { + let impl_block = type_alias.impl_block(db).expect("assoc ty value should be in impl"); + let impl_id = Impl::ImplBlock(impl_block).to_chalk(db); + let trait_ = impl_block + .target_trait_ref(db) + .expect("assoc ty value should not exist") // we don't return any assoc ty values if the impl'd trait can't be resolved + .trait_; + let assoc_ty = trait_ + .associated_type_by_name(db, &type_alias.name(db)) + .expect("assoc ty value should not exist"); // validated when building the impl data as well + let generic_params = impl_block.generic_params(db); + let bound_vars = Substs::bound_vars(&generic_params); + let ty = db.type_for_def(type_alias.into(), crate::ty::Namespace::Types).subst(&bound_vars); + let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: ty.to_chalk(db) }; + let value = chalk_rust_ir::AssociatedTyValue { + impl_id, + associated_ty_id: assoc_ty.to_chalk(db), + value: make_binders(value_bound, bound_vars.len()), + }; + Arc::new(value) +} + +fn closure_fn_trait_output_assoc_ty_value( + db: &impl HirDatabase, + krate: Crate, + data: super::ClosureFnTraitImplData, +) -> Arc { + let impl_id = Impl::ClosureFnTraitImpl(data.clone()).to_chalk(db); + + let num_args: u16 = match &data.def.body(db)[data.expr] { + crate::expr::Expr::Lambda { args, .. } => args.len() as u16, + _ => { + log::warn!("closure for closure type {:?} not found", data); + 0 + } + }; + + let output_ty = Ty::Bound(num_args.into()); + + let fn_once_trait = + get_fn_trait(db, krate, super::FnTrait::FnOnce).expect("assoc ty value should not exist"); + + let output_ty_id = fn_once_trait + .associated_type_by_name(db, &name::OUTPUT_TYPE) + .expect("assoc ty value should not exist"); + + let value_bound = chalk_rust_ir::AssociatedTyValueBound { ty: output_ty.to_chalk(db) }; + + let value = chalk_rust_ir::AssociatedTyValue { + associated_ty_id: output_ty_id.to_chalk(db), + impl_id, + value: make_binders(value_bound, num_args as usize + 1), + }; + Arc::new(value) +} + fn get_fn_trait(db: &impl HirDatabase, krate: Crate, fn_trait: super::FnTrait) -> Option { let target = db.lang_item(krate, fn_trait.lang_item_name().into())?; match target { @@ -803,3 +863,15 @@ impl From for chalk_ir::ImplId { chalk_ir::ImplId(id_to_chalk(impl_id)) } } + +impl From for crate::ids::AssocTyValueId { + fn from(id: chalk_rust_ir::AssociatedTyValueId) -> Self { + id_from_chalk(id.0) + } +} + +impl From for chalk_rust_ir::AssociatedTyValueId { + fn from(assoc_ty_value_id: crate::ids::AssocTyValueId) -> Self { + chalk_rust_ir::AssociatedTyValueId(id_to_chalk(assoc_ty_value_id)) + } +} -- cgit v1.2.3