1 //! The implementation of `RustIrDatabase` for Chalk, which provides information
2 //! about the code that Chalk needs.
7 use chalk_ir::{cast::Cast, fold::shift::Shift, CanonicalVarKinds};
8 use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait};
12 lang_item::{lang_attr, LangItemTarget},
13 AssocContainerId, AssocItemId, GenericDefId, HasModule, Lookup, ModuleId, TypeAliasId,
15 use hir_expand::name::name;
20 from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, make_only_type_binders,
21 mapping::{from_chalk, ToChalk, TypeAliasAsValue},
22 method_resolution::{TraitImpls, TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
23 to_assoc_type_id, to_chalk_trait_id,
26 AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId, Interner, ProjectionTy,
27 ProjectionTyExt, QuantifiedWhereClause, Substitution, TraitRef, TraitRefExt, Ty, TyBuilder,
28 TyExt, TyKind, WhereClause,
31 pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
32 pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
33 pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>;
34 pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
35 pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>;
37 pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
38 pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
39 pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
40 pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
41 pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
42 pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
43 pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
44 pub(crate) type Variances = chalk_ir::Variances<Interner>;
46 impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
47 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
48 self.db.associated_ty_data(id)
50 fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> {
51 self.db.trait_datum(self.krate, trait_id)
53 fn adt_datum(&self, struct_id: AdtId) -> Arc<StructDatum> {
54 self.db.struct_datum(self.krate, struct_id)
56 fn adt_repr(&self, _struct_id: AdtId) -> Arc<rust_ir::AdtRepr<Interner>> {
57 // FIXME: keep track of these
58 Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None })
60 fn discriminant_type(&self, _ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner> {
61 // FIXME: keep track of this
62 chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U32)).intern(&Interner)
64 fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
65 self.db.impl_datum(self.krate, impl_id)
70 fn_def_id: chalk_ir::FnDefId<Interner>,
71 ) -> Arc<rust_ir::FnDefDatum<Interner>> {
72 self.db.fn_def_datum(self.krate, fn_def_id)
78 parameters: &[chalk_ir::GenericArg<Interner>],
79 binders: &CanonicalVarKinds<Interner>,
81 debug!("impls_for_trait {:?}", trait_id);
82 let trait_: hir_def::TraitId = from_chalk_trait_id(trait_id);
84 let ty: Ty = parameters[0].assert_ty_ref(&Interner).clone();
88 binders: &CanonicalVarKinds<Interner>,
89 ) -> Option<chalk_ir::TyVariableKind> {
90 if let TyKind::BoundVar(bv) = ty.kind(&Interner) {
91 let binders = binders.as_slice(&Interner);
92 if bv.debruijn == DebruijnIndex::INNERMOST {
93 if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind {
101 let self_ty_fp = TyFingerprint::for_trait_impl(&ty);
102 let fps: &[TyFingerprint] = match binder_kind(&ty, binders) {
103 Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS,
104 Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS,
105 _ => self_ty_fp.as_ref().map(std::slice::from_ref).unwrap_or(&[]),
108 fn local_impls(db: &dyn HirDatabase, module: ModuleId) -> Option<Arc<TraitImpls>> {
109 db.trait_impls_in_block(module.containing_block()?)
112 // Note: Since we're using impls_for_trait, only impls where the trait
113 // can be resolved should ever reach Chalk. impl_datum relies on that
114 // and will panic if the trait can't be resolved.
115 let in_deps = self.db.trait_impls_in_deps(self.krate);
116 let in_self = self.db.trait_impls_in_crate(self.krate);
117 let trait_module = trait_.module(self.db.upcast());
118 let type_module = match self_ty_fp {
119 Some(TyFingerprint::Adt(adt_id)) => Some(adt_id.module(self.db.upcast())),
120 Some(TyFingerprint::ForeignType(type_id)) => {
121 Some(from_foreign_def_id(type_id).module(self.db.upcast()))
123 Some(TyFingerprint::Dyn(trait_id)) => Some(trait_id.module(self.db.upcast())),
129 local_impls(self.db, trait_module),
130 type_module.and_then(|m| local_impls(self.db, m)),
133 let id_to_chalk = |id: hir_def::ImplId| id.to_chalk(self.db);
135 let result: Vec<_> = if fps.is_empty() {
136 debug!("Unrestricted search for {:?} impls...", trait_);
139 .filter_map(|o| o.as_ref())
140 .flat_map(|impls| impls.for_trait(trait_).map(id_to_chalk))
145 .filter_map(|o| o.as_ref())
147 fps.iter().flat_map(move |fp| {
148 impls.for_trait_and_self_ty(trait_, *fp).map(id_to_chalk)
154 debug!("impls_for_trait returned {} impls", result.len());
157 fn impl_provided_for(&self, auto_trait_id: TraitId, kind: &chalk_ir::TyKind<Interner>) -> bool {
158 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, kind);
161 fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> {
162 self.db.associated_ty_value(self.krate, id)
165 fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<Interner>> {
168 fn local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec<ImplId> {
169 // We don't do coherence checking (yet)
172 fn interner(&self) -> &Interner {
175 fn well_known_trait_id(
177 well_known_trait: rust_ir::WellKnownTrait,
178 ) -> Option<chalk_ir::TraitId<Interner>> {
179 let lang_attr = lang_attr_from_well_known_trait(well_known_trait);
180 let trait_ = match self.db.lang_item(self.krate, lang_attr.into()) {
181 Some(LangItemTarget::TraitId(trait_)) => trait_,
184 Some(to_chalk_trait_id(trait_))
187 fn program_clauses_for_env(
189 environment: &chalk_ir::Environment<Interner>,
190 ) -> chalk_ir::ProgramClauses<Interner> {
191 self.db.program_clauses_for_chalk_env(self.krate, environment.clone())
194 fn opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum> {
195 let full_id = self.db.lookup_intern_impl_trait_id(id.into());
196 let bound = match full_id {
197 crate::ImplTraitId::ReturnTypeImplTrait(func, idx) => {
200 .return_type_impl_traits(func)
201 .expect("impl trait id without impl traits");
202 let (datas, binders) = (*datas).as_ref().into_value_and_skipped_binders();
203 let data = &datas.impl_traits[idx as usize];
204 let bound = OpaqueTyDatumBound {
205 bounds: make_only_type_binders(
207 data.bounds.skip_binders().iter().cloned().collect(),
209 where_clauses: make_only_type_binders(0, vec![]),
211 chalk_ir::Binders::new(binders, bound)
213 crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
214 if let Some((future_trait, future_output)) = self
216 .lang_item(self.krate, "future_trait".into())
217 .and_then(|item| item.as_trait())
220 self.db.trait_data(trait_).associated_type_by_name(&name![Output])?;
221 Some((trait_, alias))
224 // Making up Symbol’s value as variable is void: AsyncBlock<T>:
226 // |--------------------OpaqueTyDatum-------------------|
227 // |-------------OpaqueTyDatumBound--------------|
228 // for<T> <Self> [Future<Self>, Future::Output<Self> = T]
230 let impl_bound = WhereClause::Implemented(TraitRef {
231 trait_id: to_chalk_trait_id(future_trait),
232 // Self type as the first parameter.
233 substitution: Substitution::from1(
235 TyKind::BoundVar(BoundVar {
236 debruijn: DebruijnIndex::INNERMOST,
242 let proj_bound = WhereClause::AliasEq(AliasEq {
243 alias: AliasTy::Projection(ProjectionTy {
244 associated_ty_id: to_assoc_type_id(future_output),
245 // Self type as the first parameter.
246 substitution: Substitution::from1(
248 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
252 // The parameter of the opaque type.
253 ty: TyKind::BoundVar(BoundVar { debruijn: DebruijnIndex::ONE, index: 0 })
256 let bound = OpaqueTyDatumBound {
257 bounds: make_only_type_binders(
260 crate::wrap_empty_binders(impl_bound),
261 crate::wrap_empty_binders(proj_bound),
264 where_clauses: make_only_type_binders(0, vec![]),
266 // The opaque type has 1 parameter.
267 make_only_type_binders(1, bound)
269 // If failed to find Symbol’s value as variable is void: Future::Output, return empty bounds as fallback.
270 let bound = OpaqueTyDatumBound {
271 bounds: make_only_type_binders(0, vec![]),
272 where_clauses: make_only_type_binders(0, vec![]),
274 // The opaque type has 1 parameter.
275 make_only_type_binders(1, bound)
280 Arc::new(OpaqueTyDatum { opaque_ty_id: id, bound })
283 fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> {
284 // FIXME: actually provide the hidden type; it is relevant for auto traits
285 TyKind::Error.intern(&Interner)
288 fn is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool {
289 // FIXME: implement actual object safety
295 _closure_id: chalk_ir::ClosureId<Interner>,
296 _substs: &chalk_ir::Substitution<Interner>,
297 ) -> rust_ir::ClosureKind {
298 // Fn is the closure kind that implements all three traits
299 rust_ir::ClosureKind::Fn
301 fn closure_inputs_and_output(
303 _closure_id: chalk_ir::ClosureId<Interner>,
304 substs: &chalk_ir::Substitution<Interner>,
305 ) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> {
306 let sig_ty = substs.at(&Interner, 0).assert_ty_ref(&Interner).clone();
307 let sig = &sig_ty.callable_sig(self.db).expect("first closure param should be fn ptr");
308 let io = rust_ir::FnDefInputsAndOutputDatum {
309 argument_types: sig.params().iter().cloned().collect(),
310 return_type: sig.ret().clone(),
312 make_only_type_binders(0, io.shifted_in(&Interner))
316 _closure_id: chalk_ir::ClosureId<Interner>,
317 _substs: &chalk_ir::Substitution<Interner>,
318 ) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> {
319 let ty = TyBuilder::unit();
320 make_only_type_binders(0, ty)
322 fn closure_fn_substitution(
324 _closure_id: chalk_ir::ClosureId<Interner>,
325 _substs: &chalk_ir::Substitution<Interner>,
326 ) -> chalk_ir::Substitution<Interner> {
327 Substitution::empty(&Interner)
330 fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String {
331 let id = from_chalk_trait_id(trait_id);
332 self.db.trait_data(id).name.to_string()
334 fn adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String {
336 hir_def::AdtId::StructId(id) => self.db.struct_data(id).name.to_string(),
337 hir_def::AdtId::EnumId(id) => self.db.enum_data(id).name.to_string(),
338 hir_def::AdtId::UnionId(id) => self.db.union_data(id).name.to_string(),
341 fn assoc_type_name(&self, assoc_ty_id: chalk_ir::AssocTypeId<Interner>) -> String {
342 let id = self.db.associated_ty_data(assoc_ty_id).name;
343 self.db.type_alias_data(id).name.to_string()
345 fn opaque_type_name(&self, opaque_ty_id: chalk_ir::OpaqueTyId<Interner>) -> String {
346 format!("Opaque_{}", opaque_ty_id.0)
348 fn fn_def_name(&self, fn_def_id: chalk_ir::FnDefId<Interner>) -> String {
349 format!("fn_{}", fn_def_id.0)
353 _: chalk_ir::GeneratorId<Interner>,
354 ) -> std::sync::Arc<chalk_solve::rust_ir::GeneratorDatum<Interner>> {
358 fn generator_witness_datum(
360 _: chalk_ir::GeneratorId<Interner>,
361 ) -> std::sync::Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<Interner>> {
366 fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<Interner> {
371 impl<'a> chalk_ir::UnificationDatabase<Interner> for &'a dyn HirDatabase {
374 fn_def_id: chalk_ir::FnDefId<Interner>,
375 ) -> chalk_ir::Variances<Interner> {
376 HirDatabase::fn_def_variance(*self, fn_def_id)
379 fn adt_variance(&self, adt_id: chalk_ir::AdtId<Interner>) -> chalk_ir::Variances<Interner> {
380 HirDatabase::adt_variance(*self, adt_id)
384 pub(crate) fn program_clauses_for_chalk_env_query(
385 db: &dyn HirDatabase,
387 environment: chalk_ir::Environment<Interner>,
388 ) -> chalk_ir::ProgramClauses<Interner> {
389 chalk_solve::program_clauses_for_env(&ChalkContext { db, krate }, &environment)
392 pub(crate) fn associated_ty_data_query(
393 db: &dyn HirDatabase,
395 ) -> Arc<AssociatedTyDatum> {
396 debug!("associated_ty_data {:?}", id);
397 let type_alias: TypeAliasId = from_assoc_type_id(id);
398 let trait_ = match type_alias.lookup(db.upcast()).container {
399 AssocContainerId::TraitId(t) => t,
400 _ => panic!("associated type not in trait"),
403 // Lower bounds -- we could/should maybe move this to a separate query in `lower`
404 let type_alias_data = db.type_alias_data(type_alias);
405 let generic_params = generics(db.upcast(), type_alias.into());
406 // let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
407 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast());
408 let ctx = crate::TyLoweringContext::new(db, &resolver)
409 .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable);
411 TyKind::BoundVar(BoundVar::new(crate::DebruijnIndex::INNERMOST, 0)).intern(&Interner);
412 let bounds = type_alias_data
415 .flat_map(|bound| ctx.lower_type_bound(bound, self_ty.clone(), false))
416 .filter_map(|pred| generic_predicate_to_inline_bound(db, &pred, &self_ty))
419 // FIXME: Re-enable where clauses on associated types when an upstream chalk bug is fixed.
420 // (rust-analyzer#9052)
421 // let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars);
422 let bound_data = rust_ir::AssociatedTyDatumBound { bounds, where_clauses: vec![] };
423 let datum = AssociatedTyDatum {
424 trait_id: to_chalk_trait_id(trait_),
427 binders: make_only_type_binders(generic_params.len(), bound_data),
432 pub(crate) fn trait_datum_query(
433 db: &dyn HirDatabase,
436 ) -> Arc<TraitDatum> {
437 debug!("trait_datum {:?}", trait_id);
438 let trait_ = from_chalk_trait_id(trait_id);
439 let trait_data = db.trait_data(trait_);
440 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
441 let generic_params = generics(db.upcast(), trait_.into());
442 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
443 let flags = rust_ir::TraitFlags {
444 auto: trait_data.is_auto,
445 upstream: trait_.lookup(db.upcast()).container.krate() != krate,
446 non_enumerable: true,
447 coinductive: false, // only relevant for Chalk testing
448 // FIXME: set these flags correctly
452 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
453 let associated_ty_ids = trait_data.associated_types().map(to_assoc_type_id).collect();
454 let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
456 lang_attr(db.upcast(), trait_).and_then(|name| well_known_trait_from_lang_attr(&name));
457 let trait_datum = TraitDatum {
459 binders: make_only_type_binders(bound_vars.len(&Interner), trait_datum_bound),
464 Arc::new(trait_datum)
467 fn well_known_trait_from_lang_attr(name: &str) -> Option<WellKnownTrait> {
469 "sized" => WellKnownTrait::Sized,
470 "copy" => WellKnownTrait::Copy,
471 "clone" => WellKnownTrait::Clone,
472 "drop" => WellKnownTrait::Drop,
473 "fn_once" => WellKnownTrait::FnOnce,
474 "fn_mut" => WellKnownTrait::FnMut,
475 "fn" => WellKnownTrait::Fn,
476 "unsize" => WellKnownTrait::Unsize,
477 "coerce_unsized" => WellKnownTrait::CoerceUnsized,
478 "discriminant_kind" => WellKnownTrait::DiscriminantKind,
483 fn lang_attr_from_well_known_trait(attr: WellKnownTrait) -> &'static str {
485 WellKnownTrait::Sized => "sized",
486 WellKnownTrait::Copy => "copy",
487 WellKnownTrait::Clone => "clone",
488 WellKnownTrait::Drop => "drop",
489 WellKnownTrait::FnOnce => "fn_once",
490 WellKnownTrait::FnMut => "fn_mut",
491 WellKnownTrait::Fn => "fn",
492 WellKnownTrait::Unsize => "unsize",
493 WellKnownTrait::Unpin => "unpin",
494 WellKnownTrait::CoerceUnsized => "coerce_unsized",
495 WellKnownTrait::DiscriminantKind => "discriminant_kind",
499 pub(crate) fn struct_datum_query(
500 db: &dyn HirDatabase,
503 ) -> Arc<StructDatum> {
504 debug!("struct_datum {:?}", struct_id);
505 let chalk_ir::AdtId(adt_id) = struct_id;
506 let num_params = generics(db.upcast(), adt_id.into()).len();
507 let upstream = adt_id.module(db.upcast()).krate() != krate;
508 let where_clauses = {
509 let generic_params = generics(db.upcast(), adt_id.into());
510 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
511 convert_where_clauses(db, adt_id.into(), &bound_vars)
513 let flags = rust_ir::AdtFlags {
515 // FIXME set fundamental and phantom_data flags correctly
519 // FIXME provide enum variants properly (for auto traits)
520 let variant = rust_ir::AdtVariantDatum {
521 fields: Vec::new(), // FIXME add fields (only relevant for auto traits),
523 let struct_datum_bound = rust_ir::AdtDatumBound { variants: vec![variant], where_clauses };
524 let struct_datum = StructDatum {
525 // FIXME set ADT kind
526 kind: rust_ir::AdtKind::Struct,
528 binders: make_only_type_binders(num_params, struct_datum_bound),
531 Arc::new(struct_datum)
534 pub(crate) fn impl_datum_query(
535 db: &dyn HirDatabase,
538 ) -> Arc<ImplDatum> {
539 let _p = profile::span("impl_datum");
540 debug!("impl_datum {:?}", impl_id);
541 let impl_: hir_def::ImplId = from_chalk(db, impl_id);
542 impl_def_datum(db, krate, impl_id, impl_)
546 db: &dyn HirDatabase,
549 impl_id: hir_def::ImplId,
550 ) -> Arc<ImplDatum> {
553 // ImplIds for impls where the trait ref can't be resolved should never reach Chalk
554 .expect("invalid impl passed to Chalk")
555 .into_value_and_skipped_binders()
557 let impl_data = db.impl_data(impl_id);
559 let generic_params = generics(db.upcast(), impl_id.into());
560 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
561 let trait_ = trait_ref.hir_trait_id();
562 let impl_type = if impl_id.lookup(db.upcast()).container.krate() == krate {
563 rust_ir::ImplType::Local
565 rust_ir::ImplType::External
567 let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars);
568 let negative = impl_data.is_negative;
570 "impl {:?}: {}{} where {:?}",
572 if negative { "!" } else { "" },
573 trait_ref.display(db),
577 let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive };
579 let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses };
580 let trait_data = db.trait_data(trait_);
581 let associated_ty_value_ids = impl_data
584 .filter_map(|item| match item {
585 AssocItemId::TypeAliasId(type_alias) => Some(*type_alias),
588 .filter(|&type_alias| {
589 // don't include associated types that don't exist in the trait
590 let name = &db.type_alias_data(type_alias).name;
591 trait_data.associated_type_by_name(name).is_some()
593 .map(|type_alias| TypeAliasAsValue(type_alias).to_chalk(db))
595 debug!("impl_datum: {:?}", impl_datum_bound);
596 let impl_datum = ImplDatum {
597 binders: make_only_type_binders(bound_vars.len(&Interner), impl_datum_bound),
600 associated_ty_value_ids,
605 pub(crate) fn associated_ty_value_query(
606 db: &dyn HirDatabase,
608 id: AssociatedTyValueId,
609 ) -> Arc<AssociatedTyValue> {
610 let type_alias: TypeAliasAsValue = from_chalk(db, id);
611 type_alias_associated_ty_value(db, krate, type_alias.0)
614 fn type_alias_associated_ty_value(
615 db: &dyn HirDatabase,
617 type_alias: TypeAliasId,
618 ) -> Arc<AssociatedTyValue> {
619 let type_alias_data = db.type_alias_data(type_alias);
620 let impl_id = match type_alias.lookup(db.upcast()).container {
621 AssocContainerId::ImplId(it) => it,
622 _ => panic!("assoc ty value should be in impl"),
627 .expect("assoc ty value should not exist")
628 .into_value_and_skipped_binders()
629 .0; // we don't return any assoc ty values if the impl'd trait can't be resolved
632 .trait_data(trait_ref.hir_trait_id())
633 .associated_type_by_name(&type_alias_data.name)
634 .expect("assoc ty value should not exist"); // validated when building the impl data as well
635 let (ty, binders) = db.ty(type_alias.into()).into_value_and_skipped_binders();
636 let value_bound = rust_ir::AssociatedTyValueBound { ty };
637 let value = rust_ir::AssociatedTyValue {
638 impl_id: impl_id.to_chalk(db),
639 associated_ty_id: to_assoc_type_id(assoc_ty),
640 value: chalk_ir::Binders::new(binders, value_bound),
645 pub(crate) fn fn_def_datum_query(
646 db: &dyn HirDatabase,
649 ) -> Arc<FnDefDatum> {
650 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
651 let generic_params = generics(db.upcast(), callable_def.into());
652 let (sig, binders) = db.callable_item_signature(callable_def).into_value_and_skipped_binders();
653 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
654 let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars);
655 let bound = rust_ir::FnDefDatumBound {
656 // Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway
657 inputs_and_output: make_only_type_binders(
659 rust_ir::FnDefInputsAndOutputDatum {
660 argument_types: sig.params().iter().cloned().collect(),
661 return_type: sig.ret().clone(),
663 .shifted_in(&Interner),
667 let datum = FnDefDatum {
669 sig: chalk_ir::FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: sig.is_varargs },
670 binders: chalk_ir::Binders::new(binders, bound),
675 pub(crate) fn fn_def_variance_query(db: &dyn HirDatabase, fn_def_id: FnDefId) -> Variances {
676 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
677 let generic_params = generics(db.upcast(), callable_def.into());
678 Variances::from_iter(
680 std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
684 pub(crate) fn adt_variance_query(
685 db: &dyn HirDatabase,
686 chalk_ir::AdtId(adt_id): AdtId,
688 let generic_params = generics(db.upcast(), adt_id.into());
689 Variances::from_iter(
691 std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
695 pub(super) fn convert_where_clauses(
696 db: &dyn HirDatabase,
698 substs: &Substitution,
699 ) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
700 let generic_predicates = db.generic_predicates(def);
701 let mut result = Vec::with_capacity(generic_predicates.len());
702 for pred in generic_predicates.iter() {
703 result.push(pred.clone().substitute(&Interner, substs));
708 pub(super) fn generic_predicate_to_inline_bound(
709 db: &dyn HirDatabase,
710 pred: &QuantifiedWhereClause,
712 ) -> Option<chalk_ir::Binders<rust_ir::InlineBound<Interner>>> {
713 // An InlineBound is like a GenericPredicate, except the self type is left out.
714 // We don't have a special type for this, but Chalk does.
715 let self_ty_shifted_in = self_ty.clone().shifted_in_from(&Interner, DebruijnIndex::ONE);
716 let (pred, binders) = pred.as_ref().into_value_and_skipped_binders();
718 WhereClause::Implemented(trait_ref) => {
719 if trait_ref.self_type_parameter(&Interner) != self_ty_shifted_in {
720 // we can only convert predicates back to type bounds if they
721 // have the expected self type
724 let args_no_self = trait_ref.substitution.as_slice(&Interner)[1..]
726 .map(|ty| ty.clone().cast(&Interner))
728 let trait_bound = rust_ir::TraitBound { trait_id: trait_ref.trait_id, args_no_self };
729 Some(chalk_ir::Binders::new(binders, rust_ir::InlineBound::TraitBound(trait_bound)))
731 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
732 if projection_ty.self_type_parameter(&Interner) != self_ty_shifted_in {
735 let trait_ = projection_ty.trait_(db);
736 let args_no_self = projection_ty.substitution.as_slice(&Interner)[1..]
738 .map(|ty| ty.clone().cast(&Interner))
740 let alias_eq_bound = rust_ir::AliasEqBound {
742 trait_bound: rust_ir::TraitBound {
743 trait_id: to_chalk_trait_id(trait_),
746 associated_ty_id: projection_ty.associated_ty_id,
747 parameters: Vec::new(), // FIXME we don't support generic associated types yet
749 Some(chalk_ir::Binders::new(
751 rust_ir::InlineBound::AliasEqBound(alias_eq_bound),