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

914 lines
38 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.
use core::ops;
use std::{iter, sync::Arc};
2021-08-15 07:46:13 -05:00
use tracing::debug;
2019-05-01 13:50:49 -05:00
use chalk_ir::{cast::Caster, 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::{
hir::Movability,
lang_item::{LangItem, LangItemTarget},
AssocItemId, BlockId, GenericDefId, HasModule, ItemContainerId, Lookup, 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, ClosureSubst},
2022-10-11 02:37:35 -05:00
wrap_empty_binders, AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId,
Interner, ProjectionTy, 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 chalk_solve::RustIrDatabase<Interner> for ChalkContext<'_> {
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> {
if let chalk_ir::TyKind::Adt(id, _) = ty.kind(Interner) {
if let hir_def::AdtId::EnumId(e) = id.0 {
let enum_data = self.db.enum_data(e);
let ty = enum_data.repr.unwrap_or_default().discr_type();
return chalk_ir::TyKind::Scalar(match ty {
hir_def::layout::IntegerType::Pointer(is_signed) => match is_signed {
true => chalk_ir::Scalar::Int(chalk_ir::IntTy::Isize),
false => chalk_ir::Scalar::Uint(chalk_ir::UintTy::Usize),
},
hir_def::layout::IntegerType::Fixed(size, is_signed) => match is_signed {
true => chalk_ir::Scalar::Int(match size {
hir_def::layout::Integer::I8 => chalk_ir::IntTy::I8,
hir_def::layout::Integer::I16 => chalk_ir::IntTy::I16,
hir_def::layout::Integer::I32 => chalk_ir::IntTy::I32,
hir_def::layout::Integer::I64 => chalk_ir::IntTy::I64,
hir_def::layout::Integer::I128 => chalk_ir::IntTy::I128,
}),
false => chalk_ir::Scalar::Uint(match size {
hir_def::layout::Integer::I8 => chalk_ir::UintTy::U8,
hir_def::layout::Integer::I16 => chalk_ir::UintTy::U16,
hir_def::layout::Integer::I32 => chalk_ir::UintTy::U32,
hir_def::layout::Integer::I64 => chalk_ir::UintTy::U64,
hir_def::layout::Integer::I128 => chalk_ir::UintTy::U128,
}),
},
})
.intern(Interner);
}
}
chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U8)).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(&[]),
};
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 mut def_blocks =
[trait_module.containing_block(), type_module.and_then(|it| it.containing_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 block_impls = iter::successors(self.block, |&block_id| {
cov_mark::hit!(block_local_impls);
self.db.block_def_map(block_id).parent().and_then(|module| module.containing_block())
})
.inspect(|&block_id| {
// make sure we don't search the same block twice
def_blocks.iter_mut().for_each(|block| {
if *block == Some(block_id) {
*block = None;
}
});
})
.map(|block_id| self.db.trait_impls_in_block(block_id));
let id_to_chalk = |id: hir_def::ImplId| id.to_chalk(self.db);
let mut result = vec![];
match fps {
[] => {
debug!("Unrestricted search for {:?} impls...", trait_);
let mut f = |impls: &TraitImpls| {
result.extend(impls.for_trait(trait_).map(id_to_chalk));
};
f(&in_self);
in_deps.iter().map(ops::Deref::deref).for_each(&mut f);
block_impls.for_each(|it| f(&it));
def_blocks
.into_iter()
.flatten()
.for_each(|it| f(&self.db.trait_impls_in_block(it)));
}
fps => {
let mut f =
|impls: &TraitImpls| {
result.extend(fps.iter().flat_map(|fp| {
impls.for_trait_and_self_ty(trait_, *fp).map(id_to_chalk)
}));
};
f(&in_self);
in_deps.iter().map(ops::Deref::deref).for_each(&mut f);
block_impls.for_each(|it| f(&it));
def_blocks
.into_iter()
.flatten()
.for_each(|it| f(&self.db.trait_impls_in_block(it)));
}
}
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>> {
2023-02-13 05:55:14 -06:00
let lang_attr = lang_item_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()) {
2023-02-13 05:55:14 -06:00
Some(LangItemTarget::Trait(trait_)) => trait_,
2020-05-22 08:55:15 -05:00
_ => 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, self.block, 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();
2023-02-13 05:55:14 -06:00
let data = &datas.impl_traits[idx];
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
2023-02-13 05:55:14 -06:00
.lang_item(self.krate, LangItem::Future)
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
});
let mut binder = vec![];
binder.push(crate::wrap_empty_binders(impl_bound));
let sized_trait = self
.db
2023-02-13 05:55:14 -06:00
.lang_item(self.krate, LangItem::Sized)
.and_then(|item| item.as_trait());
if let Some(sized_trait_) = sized_trait {
let sized_bound = WhereClause::Implemented(TraitRef {
trait_id: to_chalk_trait_id(sized_trait_),
// Self type as the first parameter.
substitution: Substitution::from1(
Interner,
TyKind::BoundVar(BoundVar {
debruijn: DebruijnIndex::INNERMOST,
index: 0,
})
.intern(Interner),
),
});
binder.push(crate::wrap_empty_binders(sized_bound));
}
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
});
binder.push(crate::wrap_empty_binders(proj_bound));
2020-09-10 07:01:23 -05:00
let bound = OpaqueTyDatumBound {
bounds: make_single_type_binders(binder),
2022-03-09 12:50:24 -06:00
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>> {
let sig_ty = ClosureSubst(substs).sig_ty();
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);
self.db.trait_data(id).name.display(self.db.upcast()).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.display(self.db.upcast()).to_string()
}
hir_def::AdtId::EnumId(id) => {
self.db.enum_data(id).name.display(self.db.upcast()).to_string()
}
hir_def::AdtId::UnionId(id) => {
self.db.union_data(id).name.display(self.db.upcast()).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.display(self.db.upcast()).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,
2022-10-11 02:37:35 -05:00
id: chalk_ir::GeneratorId<Interner>,
) -> Arc<chalk_solve::rust_ir::GeneratorDatum<Interner>> {
2022-10-11 02:37:35 -05:00
let (parent, expr) = self.db.lookup_intern_generator(id.into());
// We fill substitution with unknown type, because we only need to know whether the generic
// params are types or consts to build `Binders` and those being filled up are for
// `resume_type`, `yield_type`, and `return_type` of the generator in question.
let subst = TyBuilder::subst_for_generator(self.db, parent).fill_with_unknown().build();
let input_output = rust_ir::GeneratorInputOutputDatum {
resume_type: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
.intern(Interner),
yield_type: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 1))
.intern(Interner),
return_type: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 2))
.intern(Interner),
// FIXME: calculate upvars
upvars: vec![],
};
let it = subst
.iter(Interner)
.map(|it| it.constant(Interner).map(|c| c.data(Interner).ty.clone()));
let input_output = crate::make_type_and_const_binders(it, input_output);
let movability = match self.db.body(parent)[expr] {
hir_def::hir::Expr::Closure {
closure_kind: hir_def::hir::ClosureKind::Generator(movability),
2022-10-11 02:37:35 -05:00
..
} => movability,
_ => unreachable!("non generator expression interned as generator"),
};
let movability = match movability {
Movability::Static => rust_ir::Movability::Static,
Movability::Movable => rust_ir::Movability::Movable,
};
Arc::new(rust_ir::GeneratorDatum { movability, input_output })
}
fn generator_witness_datum(
&self,
2022-10-11 02:37:35 -05:00
id: chalk_ir::GeneratorId<Interner>,
) -> Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<Interner>> {
2022-10-11 02:37:35 -05:00
// FIXME: calculate inner types
let inner_types =
rust_ir::GeneratorWitnessExistential { types: wrap_empty_binders(vec![]) };
let (parent, _) = self.db.lookup_intern_generator(id.into());
// See the comment in `generator_datum()` for unknown types.
let subst = TyBuilder::subst_for_generator(self.db, parent).fill_with_unknown().build();
let it = subst
.iter(Interner)
.map(|it| it.constant(Interner).map(|c| c.data(Interner).ty.clone()));
let inner_types = crate::make_type_and_const_binders(it, inner_types);
Arc::new(rust_ir::GeneratorWitnessDatum { inner_types })
}
fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<Interner> {
&self.db
}
}
impl chalk_ir::UnificationDatabase<Interner> for &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,
block: Option<BlockId>,
environment: chalk_ir::Environment<Interner>,
) -> chalk_ir::ProgramClauses<Interner> {
chalk_solve::program_clauses_for_env(&ChalkContext { db, krate, block }, &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, type_alias.into())
2022-03-09 12:50:24 -06:00
.with_type_param_mode(crate::lower::ParamLoweringMode::Variable);
2022-10-11 02:37:35 -05:00
let trait_subst = TyBuilder::subst_for_def(db, trait_, None)
.fill_with_bound_vars(crate::DebruijnIndex::INNERMOST, generic_params.len_self())
.build();
let pro_ty = TyBuilder::assoc_type_projection(db, type_alias, Some(trait_subst))
2022-05-21 00:49:48 -05:00
.fill_with_bound_vars(crate::DebruijnIndex::INNERMOST, 0)
.build();
let self_ty = TyKind::Alias(AliasTy::Projection(pro_ty)).intern(Interner);
2022-10-11 02:37:35 -05:00
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
2023-02-13 05:55:14 -06:00
.lang_item(resolver.krate(), LangItem::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 };
let well_known = db.lang_attr(trait_.into()).and_then(well_known_trait_from_lang_item);
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)
}
2023-02-13 05:55:14 -06:00
fn well_known_trait_from_lang_item(item: LangItem) -> Option<WellKnownTrait> {
Some(match item {
LangItem::Clone => WellKnownTrait::Clone,
LangItem::CoerceUnsized => WellKnownTrait::CoerceUnsized,
LangItem::Copy => WellKnownTrait::Copy,
LangItem::DiscriminantKind => WellKnownTrait::DiscriminantKind,
LangItem::DispatchFromDyn => WellKnownTrait::DispatchFromDyn,
LangItem::Drop => WellKnownTrait::Drop,
LangItem::Fn => WellKnownTrait::Fn,
LangItem::FnMut => WellKnownTrait::FnMut,
LangItem::FnOnce => WellKnownTrait::FnOnce,
LangItem::Generator => WellKnownTrait::Generator,
LangItem::Sized => WellKnownTrait::Sized,
LangItem::Unpin => WellKnownTrait::Unpin,
LangItem::Unsize => WellKnownTrait::Unsize,
LangItem::Tuple => WellKnownTrait::Tuple,
LangItem::PointeeTrait => WellKnownTrait::Pointee,
LangItem::FnPtrTrait => WellKnownTrait::FnPtr,
2020-05-22 08:55:15 -05:00
_ => return None,
})
}
2023-02-13 05:55:14 -06:00
fn lang_item_from_well_known_trait(trait_: WellKnownTrait) -> LangItem {
match trait_ {
WellKnownTrait::Clone => LangItem::Clone,
WellKnownTrait::CoerceUnsized => LangItem::CoerceUnsized,
WellKnownTrait::Copy => LangItem::Copy,
WellKnownTrait::DiscriminantKind => LangItem::DiscriminantKind,
WellKnownTrait::DispatchFromDyn => LangItem::DispatchFromDyn,
WellKnownTrait::Drop => LangItem::Drop,
WellKnownTrait::Fn => LangItem::Fn,
WellKnownTrait::FnMut => LangItem::FnMut,
WellKnownTrait::FnOnce => LangItem::FnOnce,
WellKnownTrait::Generator => LangItem::Generator,
WellKnownTrait::Sized => LangItem::Sized,
WellKnownTrait::Tuple => LangItem::Tuple,
WellKnownTrait::Unpin => LangItem::Unpin,
WellKnownTrait::Unsize => LangItem::Unsize,
WellKnownTrait::Pointee => LangItem::PointeeTrait,
WellKnownTrait::FnPtr => LangItem::FnPtrTrait,
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()),
)
}
/// Returns instantiated predicates.
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>> {
db.generic_predicates(def)
.iter()
.cloned()
.map(|pred| pred.substitute(Interner, substs))
.collect()
}
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()
.cloned()
.casted(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 }) => {
let generics =
generics(db.upcast(), from_assoc_type_id(projection_ty.associated_ty_id).into());
let (assoc_args, trait_args) =
projection_ty.substitution.as_slice(Interner).split_at(generics.len_self());
let (self_ty, args_no_self) =
trait_args.split_first().expect("projection without trait self type");
if self_ty.assert_ty_ref(Interner) != &self_ty_shifted_in {
2021-04-09 07:18:58 -05:00
return None;
}
let args_no_self = args_no_self.iter().cloned().casted(Interner).collect();
let parameters = assoc_args.to_vec();
2021-04-09 07:18:58 -05:00
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(projection_ty.trait_(db)),
2021-04-09 07:28:04 -05:00
args_no_self,
},
2021-04-09 07:18:58 -05:00
associated_ty_id: projection_ty.associated_ty_id,
parameters,
2021-04-09 07:18:58 -05:00
};
Some(chalk_ir::Binders::new(
binders,
rust_ir::InlineBound::AliasEqBound(alias_eq_bound),
))
}
_ => None,
}
}