rust/crates/hir-ty/src/chalk_db.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

779 lines
31 KiB
Rust
Raw Normal View History

2021-04-09 07:15:26 -05:00
//! The implementation of `RustIrDatabase` for Chalk, which provides information
//! about the code that Chalk needs.
2020-05-22 10:14:53 -05:00
use std::sync::Arc;
use cov_mark::hit;
2021-12-10 13:01:24 -06:00
use syntax::SmolStr;
2021-08-15 07:46:13 -05:00
use tracing::debug;
2019-05-01 13:50:49 -05:00
2021-04-09 07:18:58 -05:00
use chalk_ir::{cast::Cast, fold::shift::Shift, CanonicalVarKinds};
use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait};
2021-04-09 07:18:58 -05:00
use base_db::CrateId;
use hir_def::{
2020-05-22 08:55:15 -05:00
lang_item::{lang_attr, LangItemTarget},
2021-12-07 10:31:26 -06:00
AssocItemId, GenericDefId, HasModule, ItemContainerId, Lookup, ModuleId, TypeAliasId,
2019-11-26 09:00:36 -06:00
};
2020-09-10 07:01:23 -05:00
use hir_expand::name::name;
2021-04-09 07:15:26 -05:00
use crate::{
db::HirDatabase,
display::HirDisplay,
2022-03-09 12:50:24 -06:00
from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, make_binders,
make_single_type_binders,
2021-04-09 07:18:58 -05:00
mapping::{from_chalk, ToChalk, TypeAliasAsValue},
method_resolution::{TraitImpls, TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
2021-04-09 07:15:26 -05:00
to_assoc_type_id, to_chalk_trait_id,
traits::ChalkContext,
utils::generics,
AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId, Interner, ProjectionTy,
2021-04-09 07:18:58 -05:00
ProjectionTyExt, QuantifiedWhereClause, Substitution, TraitRef, TraitRefExt, Ty, TyBuilder,
TyExt, TyKind, WhereClause,
2021-04-09 07:15:26 -05:00
};
pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>;
pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>;
pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
pub(crate) type Variances = chalk_ir::Variances<Interner>;
impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
self.db.associated_ty_data(id)
}
fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> {
self.db.trait_datum(self.krate, trait_id)
}
fn adt_datum(&self, struct_id: AdtId) -> Arc<StructDatum> {
self.db.struct_datum(self.krate, struct_id)
}
2020-12-23 03:41:03 -06:00
fn adt_repr(&self, _struct_id: AdtId) -> Arc<rust_ir::AdtRepr<Interner>> {
// FIXME: keep track of these
Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None })
}
fn discriminant_type(&self, _ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner> {
// FIXME: keep track of this
2021-12-19 10:58:39 -06:00
chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U32)).intern(Interner)
2020-06-22 06:18:10 -05:00
}
fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
self.db.impl_datum(self.krate, impl_id)
}
fn fn_def_datum(
&self,
fn_def_id: chalk_ir::FnDefId<Interner>,
) -> Arc<rust_ir::FnDefDatum<Interner>> {
self.db.fn_def_datum(self.krate, fn_def_id)
}
2019-09-24 11:27:31 -05:00
fn impls_for_trait(
&self,
trait_id: TraitId,
parameters: &[chalk_ir::GenericArg<Interner>],
binders: &CanonicalVarKinds<Interner>,
) -> Vec<ImplId> {
2019-05-01 13:50:49 -05:00
debug!("impls_for_trait {:?}", trait_id);
2021-04-09 07:28:04 -05:00
let trait_: hir_def::TraitId = from_chalk_trait_id(trait_id);
2021-12-19 10:58:39 -06:00
let ty: Ty = parameters[0].assert_ty_ref(Interner).clone();
fn binder_kind(
ty: &Ty,
binders: &CanonicalVarKinds<Interner>,
) -> Option<chalk_ir::TyVariableKind> {
2021-12-19 10:58:39 -06:00
if let TyKind::BoundVar(bv) = ty.kind(Interner) {
let binders = binders.as_slice(Interner);
if bv.debruijn == DebruijnIndex::INNERMOST {
if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind {
return Some(tk);
}
}
}
None
}
let self_ty_fp = TyFingerprint::for_trait_impl(&ty);
let fps: &[TyFingerprint] = match binder_kind(&ty, binders) {
Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS,
Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS,
_ => self_ty_fp.as_ref().map(std::slice::from_ref).unwrap_or(&[]),
};
fn local_impls(db: &dyn HirDatabase, module: ModuleId) -> Option<Arc<TraitImpls>> {
let block = module.containing_block()?;
hit!(block_local_impls);
db.trait_impls_in_block(block)
}
// Note: Since we're using impls_for_trait, only impls where the trait
// can be resolved should ever reach Chalk. impl_datum relies on that
// and will panic if the trait can't be resolved.
let in_deps = self.db.trait_impls_in_deps(self.krate);
let in_self = self.db.trait_impls_in_crate(self.krate);
let trait_module = trait_.module(self.db.upcast());
let type_module = match self_ty_fp {
Some(TyFingerprint::Adt(adt_id)) => Some(adt_id.module(self.db.upcast())),
Some(TyFingerprint::ForeignType(type_id)) => {
Some(from_foreign_def_id(type_id).module(self.db.upcast()))
}
Some(TyFingerprint::Dyn(trait_id)) => Some(trait_id.module(self.db.upcast())),
_ => None,
};
let impl_maps = [
Some(in_deps),
Some(in_self),
local_impls(self.db, trait_module),
type_module.and_then(|m| local_impls(self.db, m)),
];
2020-07-12 08:26:02 -05:00
let id_to_chalk = |id: hir_def::ImplId| id.to_chalk(self.db);
2020-07-12 08:26:02 -05:00
let result: Vec<_> = if fps.is_empty() {
debug!("Unrestricted search for {:?} impls...", trait_);
impl_maps
.iter()
.filter_map(|o| o.as_ref())
.flat_map(|impls| impls.for_trait(trait_).map(id_to_chalk))
.collect()
} else {
impl_maps
.iter()
.filter_map(|o| o.as_ref())
.flat_map(|impls| {
fps.iter().flat_map(move |fp| {
impls.for_trait_and_self_ty(trait_, *fp).map(id_to_chalk)
})
})
.collect()
};
2019-09-09 15:10:58 -05:00
debug!("impls_for_trait returned {} impls", result.len());
result
}
fn impl_provided_for(&self, auto_trait_id: TraitId, kind: &chalk_ir::TyKind<Interner>) -> bool {
debug!("impl_provided_for {:?}, {:?}", auto_trait_id, kind);
false // FIXME
}
fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> {
self.db.associated_ty_value(self.krate, id)
}
fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<Interner>> {
2019-05-01 16:26:42 -05:00
vec![]
}
fn local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec<ImplId> {
2019-09-23 13:33:47 -05:00
// We don't do coherence checking (yet)
unimplemented!()
2019-05-01 16:26:42 -05:00
}
2021-12-19 10:58:39 -06:00
fn interner(&self) -> Interner {
Interner
2020-03-02 16:01:16 -06:00
}
2020-04-10 10:44:29 -05:00
fn well_known_trait_id(
&self,
well_known_trait: rust_ir::WellKnownTrait,
2020-04-16 05:39:00 -05:00
) -> Option<chalk_ir::TraitId<Interner>> {
2020-05-22 08:55:15 -05:00
let lang_attr = lang_attr_from_well_known_trait(well_known_trait);
2020-06-22 06:18:10 -05:00
let trait_ = match self.db.lang_item(self.krate, lang_attr.into()) {
2020-05-22 08:55:15 -05:00
Some(LangItemTarget::TraitId(trait_)) => trait_,
_ => return None,
};
2021-04-09 07:28:04 -05:00
Some(to_chalk_trait_id(trait_))
2020-04-10 10:44:29 -05:00
}
fn program_clauses_for_env(
&self,
environment: &chalk_ir::Environment<Interner>,
) -> chalk_ir::ProgramClauses<Interner> {
self.db.program_clauses_for_chalk_env(self.krate, environment.clone())
}
fn opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum> {
2021-03-13 13:05:47 -06:00
let full_id = self.db.lookup_intern_impl_trait_id(id.into());
2020-09-10 07:01:23 -05:00
let bound = match full_id {
2021-03-13 13:05:47 -06:00
crate::ImplTraitId::ReturnTypeImplTrait(func, idx) => {
2020-09-10 07:01:23 -05:00
let datas = self
.db
.return_type_impl_traits(func)
.expect("impl trait id without impl traits");
2021-04-05 10:45:18 -05:00
let (datas, binders) = (*datas).as_ref().into_value_and_skipped_binders();
let data = &datas.impl_traits[idx as usize];
2020-09-10 07:01:23 -05:00
let bound = OpaqueTyDatumBound {
2022-03-09 12:50:24 -06:00
bounds: make_single_type_binders(data.bounds.skip_binders().to_vec()),
where_clauses: chalk_ir::Binders::empty(Interner, vec![]),
2020-09-10 07:01:23 -05:00
};
2021-04-05 10:45:18 -05:00
chalk_ir::Binders::new(binders, bound)
2020-09-10 07:01:23 -05:00
}
2021-03-13 13:05:47 -06:00
crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
2020-09-10 07:01:23 -05:00
if let Some((future_trait, future_output)) = self
.db
2021-12-10 13:01:24 -06:00
.lang_item(self.krate, SmolStr::new_inline("future_trait"))
2020-09-10 07:01:23 -05:00
.and_then(|item| item.as_trait())
.and_then(|trait_| {
let alias =
self.db.trait_data(trait_).associated_type_by_name(&name![Output])?;
Some((trait_, alias))
})
{
// Making up Symbols value as variable is void: AsyncBlock<T>:
2020-09-11 11:12:42 -05:00
//
// |--------------------OpaqueTyDatum-------------------|
// |-------------OpaqueTyDatumBound--------------|
// for<T> <Self> [Future<Self>, Future::Output<Self> = T]
// ^1 ^0 ^0 ^0 ^1
2021-03-20 04:46:36 -05:00
let impl_bound = WhereClause::Implemented(TraitRef {
2021-03-18 15:53:19 -05:00
trait_id: to_chalk_trait_id(future_trait),
2020-09-10 07:01:23 -05:00
// Self type as the first parameter.
2021-04-05 14:17:35 -05:00
substitution: Substitution::from1(
2021-12-19 10:58:39 -06:00
Interner,
TyKind::BoundVar(BoundVar {
debruijn: DebruijnIndex::INNERMOST,
index: 0,
})
2021-12-19 10:58:39 -06:00
.intern(Interner),
),
2020-09-10 07:01:23 -05:00
});
2021-03-20 04:46:36 -05:00
let proj_bound = WhereClause::AliasEq(AliasEq {
alias: AliasTy::Projection(ProjectionTy {
associated_ty_id: to_assoc_type_id(future_output),
2020-09-10 07:01:23 -05:00
// Self type as the first parameter.
2021-04-05 14:17:35 -05:00
substitution: Substitution::from1(
2021-12-19 10:58:39 -06:00
Interner,
TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
2021-12-19 10:58:39 -06:00
.intern(Interner),
),
}),
// The parameter of the opaque type.
ty: TyKind::BoundVar(BoundVar { debruijn: DebruijnIndex::ONE, index: 0 })
2021-12-19 10:58:39 -06:00
.intern(Interner),
2020-09-10 07:01:23 -05:00
});
let bound = OpaqueTyDatumBound {
2022-03-09 12:50:24 -06:00
bounds: make_single_type_binders(vec![
crate::wrap_empty_binders(impl_bound),
crate::wrap_empty_binders(proj_bound),
]),
where_clauses: chalk_ir::Binders::empty(Interner, vec![]),
2020-09-10 07:01:23 -05:00
};
// The opaque type has 1 parameter.
2022-03-09 12:50:24 -06:00
make_single_type_binders(bound)
2020-09-10 07:01:23 -05:00
} else {
// If failed to find Symbols value as variable is void: Future::Output, return empty bounds as fallback.
2020-09-10 07:01:23 -05:00
let bound = OpaqueTyDatumBound {
2022-03-09 12:50:24 -06:00
bounds: chalk_ir::Binders::empty(Interner, vec![]),
where_clauses: chalk_ir::Binders::empty(Interner, vec![]),
2020-09-10 07:01:23 -05:00
};
// The opaque type has 1 parameter.
2022-03-09 12:50:24 -06:00
make_single_type_binders(bound)
2020-09-10 07:01:23 -05:00
}
}
};
2020-09-10 07:01:23 -05:00
Arc::new(OpaqueTyDatum { opaque_ty_id: id, bound })
}
fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> {
// FIXME: actually provide the hidden type; it is relevant for auto traits
2021-12-19 10:58:39 -06:00
TyKind::Error.intern(Interner)
}
2020-05-16 03:49:43 -05:00
fn is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool {
// FIXME: implement actual object safety
true
}
2020-06-22 06:18:10 -05:00
fn closure_kind(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
) -> rust_ir::ClosureKind {
2020-07-12 08:26:02 -05:00
// Fn is the closure kind that implements all three traits
rust_ir::ClosureKind::Fn
2020-06-22 06:18:10 -05:00
}
fn closure_inputs_and_output(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
2020-07-12 08:26:02 -05:00
substs: &chalk_ir::Substitution<Interner>,
2020-06-22 06:18:10 -05:00
) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> {
2021-12-19 10:58:39 -06:00
let sig_ty = substs.at(Interner, 0).assert_ty_ref(Interner).clone();
2021-03-24 17:07:54 -05:00
let sig = &sig_ty.callable_sig(self.db).expect("first closure param should be fn ptr");
2020-07-12 08:26:02 -05:00
let io = rust_ir::FnDefInputsAndOutputDatum {
2021-09-03 09:00:50 -05:00
argument_types: sig.params().to_vec(),
2021-04-08 07:16:05 -05:00
return_type: sig.ret().clone(),
2020-07-12 08:26:02 -05:00
};
2022-03-09 12:50:24 -06:00
chalk_ir::Binders::empty(Interner, io.shifted_in(Interner))
2020-06-22 06:18:10 -05:00
}
fn closure_upvars(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> {
2021-04-08 07:16:05 -05:00
let ty = TyBuilder::unit();
2022-03-09 12:50:24 -06:00
chalk_ir::Binders::empty(Interner, ty)
2020-06-22 06:18:10 -05:00
}
fn closure_fn_substitution(
&self,
_closure_id: chalk_ir::ClosureId<Interner>,
_substs: &chalk_ir::Substitution<Interner>,
) -> chalk_ir::Substitution<Interner> {
2021-12-19 10:58:39 -06:00
Substitution::empty(Interner)
2020-06-22 06:18:10 -05:00
}
2020-07-11 08:22:46 -05:00
2020-07-13 15:03:26 -05:00
fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String {
2021-04-09 07:28:04 -05:00
let id = from_chalk_trait_id(trait_id);
2020-07-13 15:03:26 -05:00
self.db.trait_data(id).name.to_string()
2020-07-11 08:22:46 -05:00
}
2021-03-01 14:57:39 -06:00
fn adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String {
match adt_id {
hir_def::AdtId::StructId(id) => self.db.struct_data(id).name.to_string(),
hir_def::AdtId::EnumId(id) => self.db.enum_data(id).name.to_string(),
hir_def::AdtId::UnionId(id) => self.db.union_data(id).name.to_string(),
}
2020-07-11 08:22:46 -05:00
}
2022-03-22 11:36:41 -05:00
fn adt_size_align(&self, _id: chalk_ir::AdtId<Interner>) -> Arc<rust_ir::AdtSizeAlign> {
// FIXME
Arc::new(rust_ir::AdtSizeAlign::from_one_zst(false))
}
2020-07-13 15:03:26 -05:00
fn assoc_type_name(&self, assoc_ty_id: chalk_ir::AssocTypeId<Interner>) -> String {
let id = self.db.associated_ty_data(assoc_ty_id).name;
self.db.type_alias_data(id).name.to_string()
2020-07-11 08:22:46 -05:00
}
2020-07-13 15:03:26 -05:00
fn opaque_type_name(&self, opaque_ty_id: chalk_ir::OpaqueTyId<Interner>) -> String {
format!("Opaque_{}", opaque_ty_id.0)
2020-07-11 08:22:46 -05:00
}
2020-07-13 15:03:26 -05:00
fn fn_def_name(&self, fn_def_id: chalk_ir::FnDefId<Interner>) -> String {
format!("fn_{}", fn_def_id.0)
2020-07-11 08:22:46 -05:00
}
fn generator_datum(
&self,
_: chalk_ir::GeneratorId<Interner>,
) -> std::sync::Arc<chalk_solve::rust_ir::GeneratorDatum<Interner>> {
// FIXME
unimplemented!()
}
fn generator_witness_datum(
&self,
_: chalk_ir::GeneratorId<Interner>,
) -> std::sync::Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<Interner>> {
// FIXME
unimplemented!()
}
fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<Interner> {
&self.db
}
}
impl<'a> chalk_ir::UnificationDatabase<Interner> for &'a dyn HirDatabase {
fn fn_def_variance(
&self,
fn_def_id: chalk_ir::FnDefId<Interner>,
) -> chalk_ir::Variances<Interner> {
HirDatabase::fn_def_variance(*self, fn_def_id)
}
fn adt_variance(&self, adt_id: chalk_ir::AdtId<Interner>) -> chalk_ir::Variances<Interner> {
HirDatabase::adt_variance(*self, adt_id)
}
}
pub(crate) fn program_clauses_for_chalk_env_query(
db: &dyn HirDatabase,
krate: CrateId,
environment: chalk_ir::Environment<Interner>,
) -> chalk_ir::ProgramClauses<Interner> {
chalk_solve::program_clauses_for_env(&ChalkContext { db, krate }, &environment)
}
pub(crate) fn associated_ty_data_query(
db: &dyn HirDatabase,
id: AssocTypeId,
) -> Arc<AssociatedTyDatum> {
debug!("associated_ty_data {:?}", id);
2021-03-13 10:36:07 -06:00
let type_alias: TypeAliasId = from_assoc_type_id(id);
let trait_ = match type_alias.lookup(db.upcast()).container {
2021-12-07 10:31:26 -06:00
ItemContainerId::TraitId(t) => t,
_ => panic!("associated type not in trait"),
};
// Lower bounds -- we could/should maybe move this to a separate query in `lower`
let type_alias_data = db.type_alias_data(type_alias);
let generic_params = generics(db.upcast(), type_alias.into());
// let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast());
let ctx = crate::TyLoweringContext::new(db, &resolver)
2022-03-09 12:50:24 -06:00
.with_type_param_mode(crate::lower::ParamLoweringMode::Variable);
let self_ty =
2021-12-19 10:58:39 -06:00
TyKind::BoundVar(BoundVar::new(crate::DebruijnIndex::INNERMOST, 0)).intern(Interner);
let mut bounds: Vec<_> = type_alias_data
.bounds
.iter()
.flat_map(|bound| ctx.lower_type_bound(bound, self_ty.clone(), false))
.filter_map(|pred| generic_predicate_to_inline_bound(db, &pred, &self_ty))
.collect();
if !ctx.unsized_types.borrow().contains(&self_ty) {
let sized_trait = db
.lang_item(resolver.krate(), SmolStr::new_inline("sized"))
.and_then(|lang_item| lang_item.as_trait().map(to_chalk_trait_id));
let sized_bound = sized_trait.into_iter().map(|sized_trait| {
let trait_bound =
rust_ir::TraitBound { trait_id: sized_trait, args_no_self: Default::default() };
let inline_bound = rust_ir::InlineBound::TraitBound(trait_bound);
2021-12-19 10:58:39 -06:00
chalk_ir::Binders::empty(Interner, inline_bound)
});
bounds.extend(sized_bound);
bounds.shrink_to_fit();
}
// FIXME: Re-enable where clauses on associated types when an upstream chalk bug is fixed.
// (rust-analyzer#9052)
// let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars);
let bound_data = rust_ir::AssociatedTyDatumBound { bounds, where_clauses: vec![] };
let datum = AssociatedTyDatum {
2021-04-08 07:16:05 -05:00
trait_id: to_chalk_trait_id(trait_),
id,
2020-03-02 23:57:16 -06:00
name: type_alias,
2022-03-09 12:50:24 -06:00
binders: make_binders(db, &generic_params, bound_data),
};
Arc::new(datum)
}
pub(crate) fn trait_datum_query(
db: &dyn HirDatabase,
2019-11-27 00:42:55 -06:00
krate: CrateId,
trait_id: TraitId,
) -> Arc<TraitDatum> {
debug!("trait_datum {:?}", trait_id);
2021-04-09 07:28:04 -05:00
let trait_ = from_chalk_trait_id(trait_id);
2019-11-26 09:00:36 -06:00
let trait_data = db.trait_data(trait_);
debug!("trait {:?} = {:?}", trait_id, trait_data.name);
let generic_params = generics(db.upcast(), trait_.into());
2022-03-09 12:50:24 -06:00
let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
let flags = rust_ir::TraitFlags {
2021-03-15 11:05:03 -05:00
auto: trait_data.is_auto,
2021-03-09 12:09:02 -06:00
upstream: trait_.lookup(db.upcast()).container.krate() != krate,
non_enumerable: true,
coinductive: false, // only relevant for Chalk testing
2020-06-22 06:18:10 -05:00
// FIXME: set these flags correctly
marker: false,
fundamental: false,
};
2019-11-26 09:00:36 -06:00
let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
2021-06-12 23:18:15 -05:00
let associated_ty_ids = trait_data.associated_types().map(to_assoc_type_id).collect();
let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
2020-05-22 08:55:15 -05:00
let well_known =
lang_attr(db.upcast(), trait_).and_then(|name| well_known_trait_from_lang_attr(&name));
let trait_datum = TraitDatum {
id: trait_id,
2022-03-09 12:50:24 -06:00
binders: make_binders(db, &generic_params, trait_datum_bound),
flags,
associated_ty_ids,
well_known,
};
Arc::new(trait_datum)
}
2020-05-22 08:55:15 -05:00
fn well_known_trait_from_lang_attr(name: &str) -> Option<WellKnownTrait> {
Some(match name {
2020-06-22 06:18:10 -05:00
"clone" => WellKnownTrait::Clone,
2022-03-22 11:36:41 -05:00
"coerce_unsized" => WellKnownTrait::CoerceUnsized,
"copy" => WellKnownTrait::Copy,
"discriminant_kind" => WellKnownTrait::DiscriminantKind,
"dispatch_from_dyn" => WellKnownTrait::DispatchFromDyn,
2020-06-22 06:18:10 -05:00
"drop" => WellKnownTrait::Drop,
"fn" => WellKnownTrait::Fn,
2022-03-22 11:36:41 -05:00
"fn_mut" => WellKnownTrait::FnMut,
"fn_once" => WellKnownTrait::FnOnce,
"generator" => WellKnownTrait::Generator,
"sized" => WellKnownTrait::Sized,
"unpin" => WellKnownTrait::Unpin,
2020-06-22 06:18:10 -05:00
"unsize" => WellKnownTrait::Unsize,
2020-05-22 08:55:15 -05:00
_ => return None,
})
}
fn lang_attr_from_well_known_trait(attr: WellKnownTrait) -> &'static str {
match attr {
2020-06-22 06:18:10 -05:00
WellKnownTrait::Clone => "clone",
2020-09-25 06:59:18 -05:00
WellKnownTrait::CoerceUnsized => "coerce_unsized",
2022-03-22 11:36:41 -05:00
WellKnownTrait::Copy => "copy",
2020-12-23 03:41:03 -06:00
WellKnownTrait::DiscriminantKind => "discriminant_kind",
2022-03-22 11:36:41 -05:00
WellKnownTrait::DispatchFromDyn => "dispatch_from_dyn",
WellKnownTrait::Drop => "drop",
WellKnownTrait::Fn => "fn",
WellKnownTrait::FnMut => "fn_mut",
WellKnownTrait::FnOnce => "fn_once",
2021-09-09 13:12:38 -05:00
WellKnownTrait::Generator => "generator",
2022-03-22 11:36:41 -05:00
WellKnownTrait::Sized => "sized",
WellKnownTrait::Unpin => "unpin",
WellKnownTrait::Unsize => "unsize",
2020-05-22 08:55:15 -05:00
}
}
pub(crate) fn struct_datum_query(
db: &dyn HirDatabase,
2019-11-27 00:42:55 -06:00
krate: CrateId,
struct_id: AdtId,
) -> Arc<StructDatum> {
debug!("struct_datum {:?}", struct_id);
2021-03-01 14:57:39 -06:00
let chalk_ir::AdtId(adt_id) = struct_id;
2022-03-09 12:50:24 -06:00
let generic_params = generics(db.upcast(), adt_id.into());
2021-02-28 12:13:37 -06:00
let upstream = adt_id.module(db.upcast()).krate() != krate;
2021-03-12 13:51:08 -06:00
let where_clauses = {
let generic_params = generics(db.upcast(), adt_id.into());
2022-03-09 12:50:24 -06:00
let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
2021-03-12 13:51:08 -06:00
convert_where_clauses(db, adt_id.into(), &bound_vars)
};
let flags = rust_ir::AdtFlags {
upstream,
2020-06-22 06:18:10 -05:00
// FIXME set fundamental and phantom_data flags correctly
fundamental: false,
2020-06-22 06:18:10 -05:00
phantom_data: false,
};
2020-07-11 08:22:46 -05:00
// FIXME provide enum variants properly (for auto traits)
let variant = rust_ir::AdtVariantDatum {
fields: Vec::new(), // FIXME add fields (only relevant for auto traits),
};
2020-07-10 11:30:32 -05:00
let struct_datum_bound = rust_ir::AdtDatumBound { variants: vec![variant], where_clauses };
2020-07-11 08:22:46 -05:00
let struct_datum = StructDatum {
// FIXME set ADT kind
kind: rust_ir::AdtKind::Struct,
id: struct_id,
2022-03-09 12:50:24 -06:00
binders: make_binders(db, &generic_params, struct_datum_bound),
2020-07-10 11:30:32 -05:00
flags,
2020-07-11 08:22:46 -05:00
};
Arc::new(struct_datum)
}
pub(crate) fn impl_datum_query(
db: &dyn HirDatabase,
2019-11-27 00:42:55 -06:00
krate: CrateId,
impl_id: ImplId,
) -> Arc<ImplDatum> {
2020-08-12 09:32:36 -05:00
let _p = profile::span("impl_datum");
debug!("impl_datum {:?}", impl_id);
2020-07-12 08:26:02 -05:00
let impl_: hir_def::ImplId = from_chalk(db, impl_id);
impl_def_datum(db, krate, impl_id, impl_)
2019-09-09 15:10:58 -05:00
}
2020-02-29 14:24:40 -06:00
fn impl_def_datum(
db: &dyn HirDatabase,
2019-11-27 00:42:55 -06:00
krate: CrateId,
chalk_id: ImplId,
impl_id: hir_def::ImplId,
) -> Arc<ImplDatum> {
let trait_ref = db
.impl_trait(impl_id)
// ImplIds for impls where the trait ref can't be resolved should never reach Chalk
2020-01-31 09:52:43 -06:00
.expect("invalid impl passed to Chalk")
2021-04-05 10:13:50 -05:00
.into_value_and_skipped_binders()
.0;
2019-11-27 03:47:18 -06:00
let impl_data = db.impl_data(impl_id);
let generic_params = generics(db.upcast(), impl_id.into());
2022-03-09 12:50:24 -06:00
let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
2021-03-18 15:53:19 -05:00
let trait_ = trait_ref.hir_trait_id();
2021-03-09 12:09:02 -06:00
let impl_type = if impl_id.lookup(db.upcast()).container.krate() == krate {
rust_ir::ImplType::Local
} else {
rust_ir::ImplType::External
};
2019-11-27 03:47:18 -06:00
let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars);
let negative = impl_data.is_negative;
debug!(
"impl {:?}: {}{} where {:?}",
2019-11-27 03:47:18 -06:00
chalk_id,
if negative { "!" } else { "" },
trait_ref.display(db),
where_clauses
);
let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive };
2019-10-10 13:51:50 -05:00
let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses };
2019-11-26 09:00:36 -06:00
let trait_data = db.trait_data(trait_);
2019-11-27 03:47:18 -06:00
let associated_ty_value_ids = impl_data
.items
.iter()
.filter_map(|item| match item {
2019-11-27 03:47:18 -06:00
AssocItemId::TypeAliasId(type_alias) => Some(*type_alias),
_ => None,
})
2019-11-27 03:47:18 -06:00
.filter(|&type_alias| {
// don't include associated types that don't exist in the trait
2019-11-27 03:47:18 -06:00
let name = &db.type_alias_data(type_alias).name;
trait_data.associated_type_by_name(name).is_some()
})
2020-07-12 08:26:02 -05:00
.map(|type_alias| TypeAliasAsValue(type_alias).to_chalk(db))
.collect();
debug!("impl_datum: {:?}", impl_datum_bound);
2019-10-10 13:51:50 -05:00
let impl_datum = ImplDatum {
2022-03-09 12:50:24 -06:00
binders: make_binders(db, &generic_params, impl_datum_bound),
2019-10-10 13:51:50 -05:00
impl_type,
polarity,
associated_ty_value_ids,
2019-10-10 13:51:50 -05:00
};
2019-09-09 15:10:58 -05:00
Arc::new(impl_datum)
}
pub(crate) fn associated_ty_value_query(
db: &dyn HirDatabase,
2019-11-27 00:42:55 -06:00
krate: CrateId,
2019-12-21 07:46:15 -06:00
id: AssociatedTyValueId,
) -> Arc<AssociatedTyValue> {
2020-07-12 08:26:02 -05:00
let type_alias: TypeAliasAsValue = from_chalk(db, id);
type_alias_associated_ty_value(db, krate, type_alias.0)
}
fn type_alias_associated_ty_value(
db: &dyn HirDatabase,
2019-11-27 00:42:55 -06:00
_krate: CrateId,
2019-11-27 02:40:10 -06:00
type_alias: TypeAliasId,
) -> Arc<AssociatedTyValue> {
2019-11-27 02:40:10 -06:00
let type_alias_data = db.type_alias_data(type_alias);
let impl_id = match type_alias.lookup(db.upcast()).container {
2021-12-07 10:31:26 -06:00
ItemContainerId::ImplId(it) => it,
2019-11-27 02:40:10 -06:00
_ => panic!("assoc ty value should be in impl"),
};
2021-04-05 10:13:50 -05:00
let trait_ref = db
.impl_trait(impl_id)
.expect("assoc ty value should not exist")
.into_value_and_skipped_binders()
.0; // we don't return any assoc ty values if the impl'd trait can't be resolved
2019-11-27 02:40:10 -06:00
2019-11-26 08:21:29 -06:00
let assoc_ty = db
2021-03-18 15:53:19 -05:00
.trait_data(trait_ref.hir_trait_id())
2019-11-27 02:40:10 -06:00
.associated_type_by_name(&type_alias_data.name)
2019-11-26 08:21:29 -06:00
.expect("assoc ty value should not exist"); // validated when building the impl data as well
2021-04-05 10:13:50 -05:00
let (ty, binders) = db.ty(type_alias.into()).into_value_and_skipped_binders();
2021-04-08 07:16:05 -05:00
let value_bound = rust_ir::AssociatedTyValueBound { ty };
let value = rust_ir::AssociatedTyValue {
2020-07-12 08:26:02 -05:00
impl_id: impl_id.to_chalk(db),
2021-03-13 10:36:07 -06:00
associated_ty_id: to_assoc_type_id(assoc_ty),
2021-04-05 10:45:18 -05:00
value: chalk_ir::Binders::new(binders, value_bound),
};
Arc::new(value)
}
pub(crate) fn fn_def_datum_query(
db: &dyn HirDatabase,
_krate: CrateId,
fn_def_id: FnDefId,
) -> Arc<FnDefDatum> {
let callable_def: CallableDefId = from_chalk(db, fn_def_id);
let generic_params = generics(db.upcast(), callable_def.into());
2021-04-05 10:13:50 -05:00
let (sig, binders) = db.callable_item_signature(callable_def).into_value_and_skipped_binders();
2022-03-09 12:50:24 -06:00
let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars);
let bound = rust_ir::FnDefDatumBound {
// Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway
2022-03-09 12:50:24 -06:00
inputs_and_output: chalk_ir::Binders::empty(
Interner,
2020-06-22 06:18:10 -05:00
rust_ir::FnDefInputsAndOutputDatum {
2021-09-03 09:00:50 -05:00
argument_types: sig.params().to_vec(),
2021-04-08 07:16:05 -05:00
return_type: sig.ret().clone(),
2020-06-22 06:18:10 -05:00
}
2021-12-19 10:58:39 -06:00
.shifted_in(Interner),
2020-06-22 06:18:10 -05:00
),
where_clauses,
};
2020-07-30 12:37:28 -05:00
let datum = FnDefDatum {
id: fn_def_id,
2021-04-05 10:13:50 -05:00
sig: chalk_ir::FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: sig.is_varargs },
2021-04-05 10:45:18 -05:00
binders: chalk_ir::Binders::new(binders, bound),
2020-07-30 12:37:28 -05:00
};
Arc::new(datum)
}
pub(crate) fn fn_def_variance_query(db: &dyn HirDatabase, fn_def_id: FnDefId) -> Variances {
let callable_def: CallableDefId = from_chalk(db, fn_def_id);
let generic_params = generics(db.upcast(), callable_def.into());
2021-02-02 09:07:10 -06:00
Variances::from_iter(
2021-12-19 10:58:39 -06:00
Interner,
std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
)
}
pub(crate) fn adt_variance_query(
db: &dyn HirDatabase,
2021-03-01 14:57:39 -06:00
chalk_ir::AdtId(adt_id): AdtId,
) -> Variances {
2021-03-01 14:57:39 -06:00
let generic_params = generics(db.upcast(), adt_id.into());
2021-02-02 09:07:10 -06:00
Variances::from_iter(
2021-12-19 10:58:39 -06:00
Interner,
std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
)
}
2021-04-09 07:18:58 -05:00
pub(super) fn convert_where_clauses(
db: &dyn HirDatabase,
def: GenericDefId,
substs: &Substitution,
) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
let generic_predicates = db.generic_predicates(def);
let mut result = Vec::with_capacity(generic_predicates.len());
for pred in generic_predicates.iter() {
2021-12-19 10:58:39 -06:00
result.push(pred.clone().substitute(Interner, substs));
2021-04-09 07:18:58 -05:00
}
result
}
2021-04-09 07:18:58 -05:00
pub(super) fn generic_predicate_to_inline_bound(
db: &dyn HirDatabase,
pred: &QuantifiedWhereClause,
self_ty: &Ty,
) -> Option<chalk_ir::Binders<rust_ir::InlineBound<Interner>>> {
// An InlineBound is like a GenericPredicate, except the self type is left out.
// We don't have a special type for this, but Chalk does.
2021-12-19 10:58:39 -06:00
let self_ty_shifted_in = self_ty.clone().shifted_in_from(Interner, DebruijnIndex::ONE);
2021-04-09 07:18:58 -05:00
let (pred, binders) = pred.as_ref().into_value_and_skipped_binders();
match pred {
WhereClause::Implemented(trait_ref) => {
2021-12-19 10:58:39 -06:00
if trait_ref.self_type_parameter(Interner) != self_ty_shifted_in {
2021-04-09 07:18:58 -05:00
// we can only convert predicates back to type bounds if they
// have the expected self type
return None;
}
2021-12-19 10:58:39 -06:00
let args_no_self = trait_ref.substitution.as_slice(Interner)[1..]
2021-04-09 07:18:58 -05:00
.iter()
2021-12-19 10:58:39 -06:00
.map(|ty| ty.clone().cast(Interner))
2021-04-09 07:18:58 -05:00
.collect();
let trait_bound = rust_ir::TraitBound { trait_id: trait_ref.trait_id, args_no_self };
Some(chalk_ir::Binders::new(binders, rust_ir::InlineBound::TraitBound(trait_bound)))
}
WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
2021-12-19 10:58:39 -06:00
if projection_ty.self_type_parameter(Interner) != self_ty_shifted_in {
2021-04-09 07:18:58 -05:00
return None;
}
let trait_ = projection_ty.trait_(db);
2021-12-19 10:58:39 -06:00
let args_no_self = projection_ty.substitution.as_slice(Interner)[1..]
2021-04-09 07:18:58 -05:00
.iter()
2021-12-19 10:58:39 -06:00
.map(|ty| ty.clone().cast(Interner))
2021-04-09 07:18:58 -05:00
.collect();
let alias_eq_bound = rust_ir::AliasEqBound {
value: ty.clone(),
2021-04-09 07:28:04 -05:00
trait_bound: rust_ir::TraitBound {
trait_id: to_chalk_trait_id(trait_),
args_no_self,
},
2021-04-09 07:18:58 -05:00
associated_ty_id: projection_ty.associated_ty_id,
parameters: Vec::new(), // FIXME we don't support generic associated types yet
};
Some(chalk_ir::Binders::new(
binders,
rust_ir::InlineBound::AliasEqBound(alias_eq_bound),
))
}
_ => None,
}
}