1 //! The implementation of `RustIrDatabase` for Chalk, which provides information
2 //! about the code that Chalk needs.
3 use core::ops;
4 use std::{iter, sync::Arc};
5
6 use tracing::debug;
7
8 use chalk_ir::{cast::Cast, fold::shift::Shift, CanonicalVarKinds};
9 use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait};
10
11 use base_db::CrateId;
12 use hir_def::{
13 hir::Movability,
14 lang_item::{lang_attr, LangItem, LangItemTarget},
15 AssocItemId, BlockId, GenericDefId, HasModule, ItemContainerId, Lookup, TypeAliasId,
16 };
17 use hir_expand::name::name;
18
19 use crate::{
20 db::HirDatabase,
21 display::HirDisplay,
22 from_assoc_type_id, from_chalk_trait_id, from_foreign_def_id, make_binders,
23 make_single_type_binders,
24 mapping::{from_chalk, ToChalk, TypeAliasAsValue},
25 method_resolution::{TraitImpls, TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
26 to_assoc_type_id, to_chalk_trait_id,
27 traits::ChalkContext,
28 utils::{generics, ClosureSubst},
29 wrap_empty_binders, AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId,
30 Interner, ProjectionTy, ProjectionTyExt, QuantifiedWhereClause, Substitution, TraitRef,
31 TraitRefExt, Ty, TyBuilder, TyExt, TyKind, WhereClause,
32 };
33
34 pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
35 pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
36 pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>;
37 pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
38 pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>;
39
40 pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
41 pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
42 pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
43 pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
44 pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
45 pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
46 pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
47 pub(crate) type Variances = chalk_ir::Variances<Interner>;
48
49 impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum>50 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
51 self.db.associated_ty_data(id)
52 }
trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum>53 fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> {
54 self.db.trait_datum(self.krate, trait_id)
55 }
adt_datum(&self, struct_id: AdtId) -> Arc<StructDatum>56 fn adt_datum(&self, struct_id: AdtId) -> Arc<StructDatum> {
57 self.db.struct_datum(self.krate, struct_id)
58 }
adt_repr(&self, _struct_id: AdtId) -> Arc<rust_ir::AdtRepr<Interner>>59 fn adt_repr(&self, _struct_id: AdtId) -> Arc<rust_ir::AdtRepr<Interner>> {
60 // FIXME: keep track of these
61 Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None })
62 }
discriminant_type(&self, _ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner>63 fn discriminant_type(&self, _ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner> {
64 // FIXME: keep track of this
65 chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U32)).intern(Interner)
66 }
impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum>67 fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
68 self.db.impl_datum(self.krate, impl_id)
69 }
70
fn_def_datum( &self, fn_def_id: chalk_ir::FnDefId<Interner>, ) -> Arc<rust_ir::FnDefDatum<Interner>>71 fn fn_def_datum(
72 &self,
73 fn_def_id: chalk_ir::FnDefId<Interner>,
74 ) -> Arc<rust_ir::FnDefDatum<Interner>> {
75 self.db.fn_def_datum(self.krate, fn_def_id)
76 }
77
impls_for_trait( &self, trait_id: TraitId, parameters: &[chalk_ir::GenericArg<Interner>], binders: &CanonicalVarKinds<Interner>, ) -> Vec<ImplId>78 fn impls_for_trait(
79 &self,
80 trait_id: TraitId,
81 parameters: &[chalk_ir::GenericArg<Interner>],
82 binders: &CanonicalVarKinds<Interner>,
83 ) -> Vec<ImplId> {
84 debug!("impls_for_trait {:?}", trait_id);
85 let trait_: hir_def::TraitId = from_chalk_trait_id(trait_id);
86
87 let ty: Ty = parameters[0].assert_ty_ref(Interner).clone();
88
89 fn binder_kind(
90 ty: &Ty,
91 binders: &CanonicalVarKinds<Interner>,
92 ) -> Option<chalk_ir::TyVariableKind> {
93 if let TyKind::BoundVar(bv) = ty.kind(Interner) {
94 let binders = binders.as_slice(Interner);
95 if bv.debruijn == DebruijnIndex::INNERMOST {
96 if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind {
97 return Some(tk);
98 }
99 }
100 }
101 None
102 }
103
104 let self_ty_fp = TyFingerprint::for_trait_impl(&ty);
105 let fps: &[TyFingerprint] = match binder_kind(&ty, binders) {
106 Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS,
107 Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS,
108 _ => self_ty_fp.as_ref().map(std::slice::from_ref).unwrap_or(&[]),
109 };
110
111 let trait_module = trait_.module(self.db.upcast());
112 let type_module = match self_ty_fp {
113 Some(TyFingerprint::Adt(adt_id)) => Some(adt_id.module(self.db.upcast())),
114 Some(TyFingerprint::ForeignType(type_id)) => {
115 Some(from_foreign_def_id(type_id).module(self.db.upcast()))
116 }
117 Some(TyFingerprint::Dyn(trait_id)) => Some(trait_id.module(self.db.upcast())),
118 _ => None,
119 };
120
121 let mut def_blocks =
122 [trait_module.containing_block(), type_module.and_then(|it| it.containing_block())];
123
124 // Note: Since we're using impls_for_trait, only impls where the trait
125 // can be resolved should ever reach Chalk. impl_datum relies on that
126 // and will panic if the trait can't be resolved.
127 let in_deps = self.db.trait_impls_in_deps(self.krate);
128 let in_self = self.db.trait_impls_in_crate(self.krate);
129
130 let block_impls = iter::successors(self.block, |&block_id| {
131 cov_mark::hit!(block_local_impls);
132 self.db.block_def_map(block_id).parent().and_then(|module| module.containing_block())
133 })
134 .inspect(|&block_id| {
135 // make sure we don't search the same block twice
136 def_blocks.iter_mut().for_each(|block| {
137 if *block == Some(block_id) {
138 *block = None;
139 }
140 });
141 })
142 .map(|block_id| self.db.trait_impls_in_block(block_id));
143
144 let id_to_chalk = |id: hir_def::ImplId| id.to_chalk(self.db);
145 let mut result = vec![];
146 match fps {
147 [] => {
148 debug!("Unrestricted search for {:?} impls...", trait_);
149 let mut f = |impls: &TraitImpls| {
150 result.extend(impls.for_trait(trait_).map(id_to_chalk));
151 };
152 f(&in_self);
153 in_deps.iter().map(ops::Deref::deref).for_each(&mut f);
154 block_impls.for_each(|it| f(&it));
155 def_blocks
156 .into_iter()
157 .flatten()
158 .for_each(|it| f(&self.db.trait_impls_in_block(it)));
159 }
160 fps => {
161 let mut f =
162 |impls: &TraitImpls| {
163 result.extend(fps.iter().flat_map(|fp| {
164 impls.for_trait_and_self_ty(trait_, *fp).map(id_to_chalk)
165 }));
166 };
167 f(&in_self);
168 in_deps.iter().map(ops::Deref::deref).for_each(&mut f);
169 block_impls.for_each(|it| f(&it));
170 def_blocks
171 .into_iter()
172 .flatten()
173 .for_each(|it| f(&self.db.trait_impls_in_block(it)));
174 }
175 }
176
177 debug!("impls_for_trait returned {} impls", result.len());
178 result
179 }
impl_provided_for(&self, auto_trait_id: TraitId, kind: &chalk_ir::TyKind<Interner>) -> bool180 fn impl_provided_for(&self, auto_trait_id: TraitId, kind: &chalk_ir::TyKind<Interner>) -> bool {
181 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, kind);
182 false // FIXME
183 }
associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue>184 fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> {
185 self.db.associated_ty_value(self.krate, id)
186 }
187
custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<Interner>>188 fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<Interner>> {
189 vec![]
190 }
local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec<ImplId>191 fn local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec<ImplId> {
192 // We don't do coherence checking (yet)
193 unimplemented!()
194 }
interner(&self) -> Interner195 fn interner(&self) -> Interner {
196 Interner
197 }
well_known_trait_id( &self, well_known_trait: rust_ir::WellKnownTrait, ) -> Option<chalk_ir::TraitId<Interner>>198 fn well_known_trait_id(
199 &self,
200 well_known_trait: rust_ir::WellKnownTrait,
201 ) -> Option<chalk_ir::TraitId<Interner>> {
202 let lang_attr = lang_item_from_well_known_trait(well_known_trait);
203 let trait_ = match self.db.lang_item(self.krate, lang_attr.into()) {
204 Some(LangItemTarget::Trait(trait_)) => trait_,
205 _ => return None,
206 };
207 Some(to_chalk_trait_id(trait_))
208 }
209
program_clauses_for_env( &self, environment: &chalk_ir::Environment<Interner>, ) -> chalk_ir::ProgramClauses<Interner>210 fn program_clauses_for_env(
211 &self,
212 environment: &chalk_ir::Environment<Interner>,
213 ) -> chalk_ir::ProgramClauses<Interner> {
214 self.db.program_clauses_for_chalk_env(self.krate, self.block, environment.clone())
215 }
216
opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum>217 fn opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum> {
218 let full_id = self.db.lookup_intern_impl_trait_id(id.into());
219 let bound = match full_id {
220 crate::ImplTraitId::ReturnTypeImplTrait(func, idx) => {
221 let datas = self
222 .db
223 .return_type_impl_traits(func)
224 .expect("impl trait id without impl traits");
225 let (datas, binders) = (*datas).as_ref().into_value_and_skipped_binders();
226 let data = &datas.impl_traits[idx];
227 let bound = OpaqueTyDatumBound {
228 bounds: make_single_type_binders(data.bounds.skip_binders().to_vec()),
229 where_clauses: chalk_ir::Binders::empty(Interner, vec![]),
230 };
231 chalk_ir::Binders::new(binders, bound)
232 }
233 crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
234 if let Some((future_trait, future_output)) = self
235 .db
236 .lang_item(self.krate, LangItem::Future)
237 .and_then(|item| item.as_trait())
238 .and_then(|trait_| {
239 let alias =
240 self.db.trait_data(trait_).associated_type_by_name(&name![Output])?;
241 Some((trait_, alias))
242 })
243 {
244 // Making up Symbol’s value as variable is void: AsyncBlock<T>:
245 //
246 // |--------------------OpaqueTyDatum-------------------|
247 // |-------------OpaqueTyDatumBound--------------|
248 // for<T> <Self> [Future<Self>, Future::Output<Self> = T]
249 // ^1 ^0 ^0 ^0 ^1
250 let impl_bound = WhereClause::Implemented(TraitRef {
251 trait_id: to_chalk_trait_id(future_trait),
252 // Self type as the first parameter.
253 substitution: Substitution::from1(
254 Interner,
255 TyKind::BoundVar(BoundVar {
256 debruijn: DebruijnIndex::INNERMOST,
257 index: 0,
258 })
259 .intern(Interner),
260 ),
261 });
262 let mut binder = vec![];
263 binder.push(crate::wrap_empty_binders(impl_bound));
264 let sized_trait = self
265 .db
266 .lang_item(self.krate, LangItem::Sized)
267 .and_then(|item| item.as_trait());
268 if let Some(sized_trait_) = sized_trait {
269 let sized_bound = WhereClause::Implemented(TraitRef {
270 trait_id: to_chalk_trait_id(sized_trait_),
271 // Self type as the first parameter.
272 substitution: Substitution::from1(
273 Interner,
274 TyKind::BoundVar(BoundVar {
275 debruijn: DebruijnIndex::INNERMOST,
276 index: 0,
277 })
278 .intern(Interner),
279 ),
280 });
281 binder.push(crate::wrap_empty_binders(sized_bound));
282 }
283 let proj_bound = WhereClause::AliasEq(AliasEq {
284 alias: AliasTy::Projection(ProjectionTy {
285 associated_ty_id: to_assoc_type_id(future_output),
286 // Self type as the first parameter.
287 substitution: Substitution::from1(
288 Interner,
289 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
290 .intern(Interner),
291 ),
292 }),
293 // The parameter of the opaque type.
294 ty: TyKind::BoundVar(BoundVar { debruijn: DebruijnIndex::ONE, index: 0 })
295 .intern(Interner),
296 });
297 binder.push(crate::wrap_empty_binders(proj_bound));
298 let bound = OpaqueTyDatumBound {
299 bounds: make_single_type_binders(binder),
300 where_clauses: chalk_ir::Binders::empty(Interner, vec![]),
301 };
302 // The opaque type has 1 parameter.
303 make_single_type_binders(bound)
304 } else {
305 // If failed to find Symbol’s value as variable is void: Future::Output, return empty bounds as fallback.
306 let bound = OpaqueTyDatumBound {
307 bounds: chalk_ir::Binders::empty(Interner, vec![]),
308 where_clauses: chalk_ir::Binders::empty(Interner, vec![]),
309 };
310 // The opaque type has 1 parameter.
311 make_single_type_binders(bound)
312 }
313 }
314 };
315
316 Arc::new(OpaqueTyDatum { opaque_ty_id: id, bound })
317 }
318
hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner>319 fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> {
320 // FIXME: actually provide the hidden type; it is relevant for auto traits
321 TyKind::Error.intern(Interner)
322 }
323
is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool324 fn is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool {
325 // FIXME: implement actual object safety
326 true
327 }
328
closure_kind( &self, _closure_id: chalk_ir::ClosureId<Interner>, _substs: &chalk_ir::Substitution<Interner>, ) -> rust_ir::ClosureKind329 fn closure_kind(
330 &self,
331 _closure_id: chalk_ir::ClosureId<Interner>,
332 _substs: &chalk_ir::Substitution<Interner>,
333 ) -> rust_ir::ClosureKind {
334 // Fn is the closure kind that implements all three traits
335 rust_ir::ClosureKind::Fn
336 }
closure_inputs_and_output( &self, _closure_id: chalk_ir::ClosureId<Interner>, substs: &chalk_ir::Substitution<Interner>, ) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>>337 fn closure_inputs_and_output(
338 &self,
339 _closure_id: chalk_ir::ClosureId<Interner>,
340 substs: &chalk_ir::Substitution<Interner>,
341 ) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> {
342 let sig_ty = ClosureSubst(substs).sig_ty();
343 let sig = &sig_ty.callable_sig(self.db).expect("first closure param should be fn ptr");
344 let io = rust_ir::FnDefInputsAndOutputDatum {
345 argument_types: sig.params().to_vec(),
346 return_type: sig.ret().clone(),
347 };
348 chalk_ir::Binders::empty(Interner, io.shifted_in(Interner))
349 }
closure_upvars( &self, _closure_id: chalk_ir::ClosureId<Interner>, _substs: &chalk_ir::Substitution<Interner>, ) -> chalk_ir::Binders<chalk_ir::Ty<Interner>>350 fn closure_upvars(
351 &self,
352 _closure_id: chalk_ir::ClosureId<Interner>,
353 _substs: &chalk_ir::Substitution<Interner>,
354 ) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> {
355 let ty = TyBuilder::unit();
356 chalk_ir::Binders::empty(Interner, ty)
357 }
closure_fn_substitution( &self, _closure_id: chalk_ir::ClosureId<Interner>, _substs: &chalk_ir::Substitution<Interner>, ) -> chalk_ir::Substitution<Interner>358 fn closure_fn_substitution(
359 &self,
360 _closure_id: chalk_ir::ClosureId<Interner>,
361 _substs: &chalk_ir::Substitution<Interner>,
362 ) -> chalk_ir::Substitution<Interner> {
363 Substitution::empty(Interner)
364 }
365
trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String366 fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String {
367 let id = from_chalk_trait_id(trait_id);
368 self.db.trait_data(id).name.display(self.db.upcast()).to_string()
369 }
adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String370 fn adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String {
371 match adt_id {
372 hir_def::AdtId::StructId(id) => {
373 self.db.struct_data(id).name.display(self.db.upcast()).to_string()
374 }
375 hir_def::AdtId::EnumId(id) => {
376 self.db.enum_data(id).name.display(self.db.upcast()).to_string()
377 }
378 hir_def::AdtId::UnionId(id) => {
379 self.db.union_data(id).name.display(self.db.upcast()).to_string()
380 }
381 }
382 }
adt_size_align(&self, _id: chalk_ir::AdtId<Interner>) -> Arc<rust_ir::AdtSizeAlign>383 fn adt_size_align(&self, _id: chalk_ir::AdtId<Interner>) -> Arc<rust_ir::AdtSizeAlign> {
384 // FIXME
385 Arc::new(rust_ir::AdtSizeAlign::from_one_zst(false))
386 }
assoc_type_name(&self, assoc_ty_id: chalk_ir::AssocTypeId<Interner>) -> String387 fn assoc_type_name(&self, assoc_ty_id: chalk_ir::AssocTypeId<Interner>) -> String {
388 let id = self.db.associated_ty_data(assoc_ty_id).name;
389 self.db.type_alias_data(id).name.display(self.db.upcast()).to_string()
390 }
opaque_type_name(&self, opaque_ty_id: chalk_ir::OpaqueTyId<Interner>) -> String391 fn opaque_type_name(&self, opaque_ty_id: chalk_ir::OpaqueTyId<Interner>) -> String {
392 format!("Opaque_{}", opaque_ty_id.0)
393 }
fn_def_name(&self, fn_def_id: chalk_ir::FnDefId<Interner>) -> String394 fn fn_def_name(&self, fn_def_id: chalk_ir::FnDefId<Interner>) -> String {
395 format!("fn_{}", fn_def_id.0)
396 }
generator_datum( &self, id: chalk_ir::GeneratorId<Interner>, ) -> Arc<chalk_solve::rust_ir::GeneratorDatum<Interner>>397 fn generator_datum(
398 &self,
399 id: chalk_ir::GeneratorId<Interner>,
400 ) -> Arc<chalk_solve::rust_ir::GeneratorDatum<Interner>> {
401 let (parent, expr) = self.db.lookup_intern_generator(id.into());
402
403 // We fill substitution with unknown type, because we only need to know whether the generic
404 // params are types or consts to build `Binders` and those being filled up are for
405 // `resume_type`, `yield_type`, and `return_type` of the generator in question.
406 let subst = TyBuilder::subst_for_generator(self.db, parent).fill_with_unknown().build();
407
408 let input_output = rust_ir::GeneratorInputOutputDatum {
409 resume_type: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
410 .intern(Interner),
411 yield_type: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 1))
412 .intern(Interner),
413 return_type: TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 2))
414 .intern(Interner),
415 // FIXME: calculate upvars
416 upvars: vec![],
417 };
418
419 let it = subst
420 .iter(Interner)
421 .map(|it| it.constant(Interner).map(|c| c.data(Interner).ty.clone()));
422 let input_output = crate::make_type_and_const_binders(it, input_output);
423
424 let movability = match self.db.body(parent)[expr] {
425 hir_def::hir::Expr::Closure {
426 closure_kind: hir_def::hir::ClosureKind::Generator(movability),
427 ..
428 } => movability,
429 _ => unreachable!("non generator expression interned as generator"),
430 };
431 let movability = match movability {
432 Movability::Static => rust_ir::Movability::Static,
433 Movability::Movable => rust_ir::Movability::Movable,
434 };
435
436 Arc::new(rust_ir::GeneratorDatum { movability, input_output })
437 }
generator_witness_datum( &self, id: chalk_ir::GeneratorId<Interner>, ) -> Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<Interner>>438 fn generator_witness_datum(
439 &self,
440 id: chalk_ir::GeneratorId<Interner>,
441 ) -> Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<Interner>> {
442 // FIXME: calculate inner types
443 let inner_types =
444 rust_ir::GeneratorWitnessExistential { types: wrap_empty_binders(vec![]) };
445
446 let (parent, _) = self.db.lookup_intern_generator(id.into());
447 // See the comment in `generator_datum()` for unknown types.
448 let subst = TyBuilder::subst_for_generator(self.db, parent).fill_with_unknown().build();
449 let it = subst
450 .iter(Interner)
451 .map(|it| it.constant(Interner).map(|c| c.data(Interner).ty.clone()));
452 let inner_types = crate::make_type_and_const_binders(it, inner_types);
453
454 Arc::new(rust_ir::GeneratorWitnessDatum { inner_types })
455 }
456
unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<Interner>457 fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<Interner> {
458 &self.db
459 }
460 }
461
462 impl chalk_ir::UnificationDatabase<Interner> for &dyn HirDatabase {
fn_def_variance( &self, fn_def_id: chalk_ir::FnDefId<Interner>, ) -> chalk_ir::Variances<Interner>463 fn fn_def_variance(
464 &self,
465 fn_def_id: chalk_ir::FnDefId<Interner>,
466 ) -> chalk_ir::Variances<Interner> {
467 HirDatabase::fn_def_variance(*self, fn_def_id)
468 }
469
adt_variance(&self, adt_id: chalk_ir::AdtId<Interner>) -> chalk_ir::Variances<Interner>470 fn adt_variance(&self, adt_id: chalk_ir::AdtId<Interner>) -> chalk_ir::Variances<Interner> {
471 HirDatabase::adt_variance(*self, adt_id)
472 }
473 }
474
program_clauses_for_chalk_env_query( db: &dyn HirDatabase, krate: CrateId, block: Option<BlockId>, environment: chalk_ir::Environment<Interner>, ) -> chalk_ir::ProgramClauses<Interner>475 pub(crate) fn program_clauses_for_chalk_env_query(
476 db: &dyn HirDatabase,
477 krate: CrateId,
478 block: Option<BlockId>,
479 environment: chalk_ir::Environment<Interner>,
480 ) -> chalk_ir::ProgramClauses<Interner> {
481 chalk_solve::program_clauses_for_env(&ChalkContext { db, krate, block }, &environment)
482 }
483
associated_ty_data_query( db: &dyn HirDatabase, id: AssocTypeId, ) -> Arc<AssociatedTyDatum>484 pub(crate) fn associated_ty_data_query(
485 db: &dyn HirDatabase,
486 id: AssocTypeId,
487 ) -> Arc<AssociatedTyDatum> {
488 debug!("associated_ty_data {:?}", id);
489 let type_alias: TypeAliasId = from_assoc_type_id(id);
490 let trait_ = match type_alias.lookup(db.upcast()).container {
491 ItemContainerId::TraitId(t) => t,
492 _ => panic!("associated type not in trait"),
493 };
494
495 // Lower bounds -- we could/should maybe move this to a separate query in `lower`
496 let type_alias_data = db.type_alias_data(type_alias);
497 let generic_params = generics(db.upcast(), type_alias.into());
498 // let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
499 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast());
500 let ctx = crate::TyLoweringContext::new(db, &resolver, type_alias.into())
501 .with_type_param_mode(crate::lower::ParamLoweringMode::Variable);
502
503 let trait_subst = TyBuilder::subst_for_def(db, trait_, None)
504 .fill_with_bound_vars(crate::DebruijnIndex::INNERMOST, generic_params.len_self())
505 .build();
506 let pro_ty = TyBuilder::assoc_type_projection(db, type_alias, Some(trait_subst))
507 .fill_with_bound_vars(crate::DebruijnIndex::INNERMOST, 0)
508 .build();
509 let self_ty = TyKind::Alias(AliasTy::Projection(pro_ty)).intern(Interner);
510
511 let mut bounds: Vec<_> = type_alias_data
512 .bounds
513 .iter()
514 .flat_map(|bound| ctx.lower_type_bound(bound, self_ty.clone(), false))
515 .filter_map(|pred| generic_predicate_to_inline_bound(db, &pred, &self_ty))
516 .collect();
517
518 if !ctx.unsized_types.borrow().contains(&self_ty) {
519 let sized_trait = db
520 .lang_item(resolver.krate(), LangItem::Sized)
521 .and_then(|lang_item| lang_item.as_trait().map(to_chalk_trait_id));
522 let sized_bound = sized_trait.into_iter().map(|sized_trait| {
523 let trait_bound =
524 rust_ir::TraitBound { trait_id: sized_trait, args_no_self: Default::default() };
525 let inline_bound = rust_ir::InlineBound::TraitBound(trait_bound);
526 chalk_ir::Binders::empty(Interner, inline_bound)
527 });
528 bounds.extend(sized_bound);
529 bounds.shrink_to_fit();
530 }
531
532 // FIXME: Re-enable where clauses on associated types when an upstream chalk bug is fixed.
533 // (rust-analyzer#9052)
534 // let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars);
535 let bound_data = rust_ir::AssociatedTyDatumBound { bounds, where_clauses: vec![] };
536 let datum = AssociatedTyDatum {
537 trait_id: to_chalk_trait_id(trait_),
538 id,
539 name: type_alias,
540 binders: make_binders(db, &generic_params, bound_data),
541 };
542 Arc::new(datum)
543 }
544
trait_datum_query( db: &dyn HirDatabase, krate: CrateId, trait_id: TraitId, ) -> Arc<TraitDatum>545 pub(crate) fn trait_datum_query(
546 db: &dyn HirDatabase,
547 krate: CrateId,
548 trait_id: TraitId,
549 ) -> Arc<TraitDatum> {
550 debug!("trait_datum {:?}", trait_id);
551 let trait_ = from_chalk_trait_id(trait_id);
552 let trait_data = db.trait_data(trait_);
553 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
554 let generic_params = generics(db.upcast(), trait_.into());
555 let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
556 let flags = rust_ir::TraitFlags {
557 auto: trait_data.is_auto,
558 upstream: trait_.lookup(db.upcast()).container.krate() != krate,
559 non_enumerable: true,
560 coinductive: false, // only relevant for Chalk testing
561 // FIXME: set these flags correctly
562 marker: false,
563 fundamental: false,
564 };
565 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
566 let associated_ty_ids = trait_data.associated_types().map(to_assoc_type_id).collect();
567 let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
568 let well_known = lang_attr(db.upcast(), trait_).and_then(well_known_trait_from_lang_item);
569 let trait_datum = TraitDatum {
570 id: trait_id,
571 binders: make_binders(db, &generic_params, trait_datum_bound),
572 flags,
573 associated_ty_ids,
574 well_known,
575 };
576 Arc::new(trait_datum)
577 }
578
well_known_trait_from_lang_item(item: LangItem) -> Option<WellKnownTrait>579 fn well_known_trait_from_lang_item(item: LangItem) -> Option<WellKnownTrait> {
580 Some(match item {
581 LangItem::Clone => WellKnownTrait::Clone,
582 LangItem::CoerceUnsized => WellKnownTrait::CoerceUnsized,
583 LangItem::Copy => WellKnownTrait::Copy,
584 LangItem::DiscriminantKind => WellKnownTrait::DiscriminantKind,
585 LangItem::DispatchFromDyn => WellKnownTrait::DispatchFromDyn,
586 LangItem::Drop => WellKnownTrait::Drop,
587 LangItem::Fn => WellKnownTrait::Fn,
588 LangItem::FnMut => WellKnownTrait::FnMut,
589 LangItem::FnOnce => WellKnownTrait::FnOnce,
590 LangItem::Generator => WellKnownTrait::Generator,
591 LangItem::Sized => WellKnownTrait::Sized,
592 LangItem::Unpin => WellKnownTrait::Unpin,
593 LangItem::Unsize => WellKnownTrait::Unsize,
594 LangItem::Tuple => WellKnownTrait::Tuple,
595 LangItem::PointeeTrait => WellKnownTrait::Pointee,
596 _ => return None,
597 })
598 }
599
lang_item_from_well_known_trait(trait_: WellKnownTrait) -> LangItem600 fn lang_item_from_well_known_trait(trait_: WellKnownTrait) -> LangItem {
601 match trait_ {
602 WellKnownTrait::Clone => LangItem::Clone,
603 WellKnownTrait::CoerceUnsized => LangItem::CoerceUnsized,
604 WellKnownTrait::Copy => LangItem::Copy,
605 WellKnownTrait::DiscriminantKind => LangItem::DiscriminantKind,
606 WellKnownTrait::DispatchFromDyn => LangItem::DispatchFromDyn,
607 WellKnownTrait::Drop => LangItem::Drop,
608 WellKnownTrait::Fn => LangItem::Fn,
609 WellKnownTrait::FnMut => LangItem::FnMut,
610 WellKnownTrait::FnOnce => LangItem::FnOnce,
611 WellKnownTrait::Generator => LangItem::Generator,
612 WellKnownTrait::Sized => LangItem::Sized,
613 WellKnownTrait::Tuple => LangItem::Tuple,
614 WellKnownTrait::Unpin => LangItem::Unpin,
615 WellKnownTrait::Unsize => LangItem::Unsize,
616 WellKnownTrait::Pointee => LangItem::PointeeTrait,
617 }
618 }
619
struct_datum_query( db: &dyn HirDatabase, krate: CrateId, struct_id: AdtId, ) -> Arc<StructDatum>620 pub(crate) fn struct_datum_query(
621 db: &dyn HirDatabase,
622 krate: CrateId,
623 struct_id: AdtId,
624 ) -> Arc<StructDatum> {
625 debug!("struct_datum {:?}", struct_id);
626 let chalk_ir::AdtId(adt_id) = struct_id;
627 let generic_params = generics(db.upcast(), adt_id.into());
628 let upstream = adt_id.module(db.upcast()).krate() != krate;
629 let where_clauses = {
630 let generic_params = generics(db.upcast(), adt_id.into());
631 let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
632 convert_where_clauses(db, adt_id.into(), &bound_vars)
633 };
634 let flags = rust_ir::AdtFlags {
635 upstream,
636 // FIXME set fundamental and phantom_data flags correctly
637 fundamental: false,
638 phantom_data: false,
639 };
640 // FIXME provide enum variants properly (for auto traits)
641 let variant = rust_ir::AdtVariantDatum {
642 fields: Vec::new(), // FIXME add fields (only relevant for auto traits),
643 };
644 let struct_datum_bound = rust_ir::AdtDatumBound { variants: vec![variant], where_clauses };
645 let struct_datum = StructDatum {
646 // FIXME set ADT kind
647 kind: rust_ir::AdtKind::Struct,
648 id: struct_id,
649 binders: make_binders(db, &generic_params, struct_datum_bound),
650 flags,
651 };
652 Arc::new(struct_datum)
653 }
654
impl_datum_query( db: &dyn HirDatabase, krate: CrateId, impl_id: ImplId, ) -> Arc<ImplDatum>655 pub(crate) fn impl_datum_query(
656 db: &dyn HirDatabase,
657 krate: CrateId,
658 impl_id: ImplId,
659 ) -> Arc<ImplDatum> {
660 let _p = profile::span("impl_datum");
661 debug!("impl_datum {:?}", impl_id);
662 let impl_: hir_def::ImplId = from_chalk(db, impl_id);
663 impl_def_datum(db, krate, impl_id, impl_)
664 }
665
impl_def_datum( db: &dyn HirDatabase, krate: CrateId, chalk_id: ImplId, impl_id: hir_def::ImplId, ) -> Arc<ImplDatum>666 fn impl_def_datum(
667 db: &dyn HirDatabase,
668 krate: CrateId,
669 chalk_id: ImplId,
670 impl_id: hir_def::ImplId,
671 ) -> Arc<ImplDatum> {
672 let trait_ref = db
673 .impl_trait(impl_id)
674 // ImplIds for impls where the trait ref can't be resolved should never reach Chalk
675 .expect("invalid impl passed to Chalk")
676 .into_value_and_skipped_binders()
677 .0;
678 let impl_data = db.impl_data(impl_id);
679
680 let generic_params = generics(db.upcast(), impl_id.into());
681 let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
682 let trait_ = trait_ref.hir_trait_id();
683 let impl_type = if impl_id.lookup(db.upcast()).container.krate() == krate {
684 rust_ir::ImplType::Local
685 } else {
686 rust_ir::ImplType::External
687 };
688 let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars);
689 let negative = impl_data.is_negative;
690 debug!(
691 "impl {:?}: {}{} where {:?}",
692 chalk_id,
693 if negative { "!" } else { "" },
694 trait_ref.display(db),
695 where_clauses
696 );
697
698 let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive };
699
700 let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses };
701 let trait_data = db.trait_data(trait_);
702 let associated_ty_value_ids = impl_data
703 .items
704 .iter()
705 .filter_map(|item| match item {
706 AssocItemId::TypeAliasId(type_alias) => Some(*type_alias),
707 _ => None,
708 })
709 .filter(|&type_alias| {
710 // don't include associated types that don't exist in the trait
711 let name = &db.type_alias_data(type_alias).name;
712 trait_data.associated_type_by_name(name).is_some()
713 })
714 .map(|type_alias| TypeAliasAsValue(type_alias).to_chalk(db))
715 .collect();
716 debug!("impl_datum: {:?}", impl_datum_bound);
717 let impl_datum = ImplDatum {
718 binders: make_binders(db, &generic_params, impl_datum_bound),
719 impl_type,
720 polarity,
721 associated_ty_value_ids,
722 };
723 Arc::new(impl_datum)
724 }
725
associated_ty_value_query( db: &dyn HirDatabase, krate: CrateId, id: AssociatedTyValueId, ) -> Arc<AssociatedTyValue>726 pub(crate) fn associated_ty_value_query(
727 db: &dyn HirDatabase,
728 krate: CrateId,
729 id: AssociatedTyValueId,
730 ) -> Arc<AssociatedTyValue> {
731 let type_alias: TypeAliasAsValue = from_chalk(db, id);
732 type_alias_associated_ty_value(db, krate, type_alias.0)
733 }
734
type_alias_associated_ty_value( db: &dyn HirDatabase, _krate: CrateId, type_alias: TypeAliasId, ) -> Arc<AssociatedTyValue>735 fn type_alias_associated_ty_value(
736 db: &dyn HirDatabase,
737 _krate: CrateId,
738 type_alias: TypeAliasId,
739 ) -> Arc<AssociatedTyValue> {
740 let type_alias_data = db.type_alias_data(type_alias);
741 let impl_id = match type_alias.lookup(db.upcast()).container {
742 ItemContainerId::ImplId(it) => it,
743 _ => panic!("assoc ty value should be in impl"),
744 };
745
746 let trait_ref = db
747 .impl_trait(impl_id)
748 .expect("assoc ty value should not exist")
749 .into_value_and_skipped_binders()
750 .0; // we don't return any assoc ty values if the impl'd trait can't be resolved
751
752 let assoc_ty = db
753 .trait_data(trait_ref.hir_trait_id())
754 .associated_type_by_name(&type_alias_data.name)
755 .expect("assoc ty value should not exist"); // validated when building the impl data as well
756 let (ty, binders) = db.ty(type_alias.into()).into_value_and_skipped_binders();
757 let value_bound = rust_ir::AssociatedTyValueBound { ty };
758 let value = rust_ir::AssociatedTyValue {
759 impl_id: impl_id.to_chalk(db),
760 associated_ty_id: to_assoc_type_id(assoc_ty),
761 value: chalk_ir::Binders::new(binders, value_bound),
762 };
763 Arc::new(value)
764 }
765
fn_def_datum_query( db: &dyn HirDatabase, _krate: CrateId, fn_def_id: FnDefId, ) -> Arc<FnDefDatum>766 pub(crate) fn fn_def_datum_query(
767 db: &dyn HirDatabase,
768 _krate: CrateId,
769 fn_def_id: FnDefId,
770 ) -> Arc<FnDefDatum> {
771 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
772 let generic_params = generics(db.upcast(), callable_def.into());
773 let (sig, binders) = db.callable_item_signature(callable_def).into_value_and_skipped_binders();
774 let bound_vars = generic_params.bound_vars_subst(db, DebruijnIndex::INNERMOST);
775 let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars);
776 let bound = rust_ir::FnDefDatumBound {
777 // Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway
778 inputs_and_output: chalk_ir::Binders::empty(
779 Interner,
780 rust_ir::FnDefInputsAndOutputDatum {
781 argument_types: sig.params().to_vec(),
782 return_type: sig.ret().clone(),
783 }
784 .shifted_in(Interner),
785 ),
786 where_clauses,
787 };
788 let datum = FnDefDatum {
789 id: fn_def_id,
790 sig: chalk_ir::FnSig { abi: (), safety: chalk_ir::Safety::Safe, variadic: sig.is_varargs },
791 binders: chalk_ir::Binders::new(binders, bound),
792 };
793 Arc::new(datum)
794 }
795
fn_def_variance_query(db: &dyn HirDatabase, fn_def_id: FnDefId) -> Variances796 pub(crate) fn fn_def_variance_query(db: &dyn HirDatabase, fn_def_id: FnDefId) -> Variances {
797 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
798 let generic_params = generics(db.upcast(), callable_def.into());
799 Variances::from_iter(
800 Interner,
801 std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
802 )
803 }
804
adt_variance_query( db: &dyn HirDatabase, chalk_ir::AdtId(adt_id): AdtId, ) -> Variances805 pub(crate) fn adt_variance_query(
806 db: &dyn HirDatabase,
807 chalk_ir::AdtId(adt_id): AdtId,
808 ) -> Variances {
809 let generic_params = generics(db.upcast(), adt_id.into());
810 Variances::from_iter(
811 Interner,
812 std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
813 )
814 }
815
816 /// Returns instantiated predicates.
convert_where_clauses( db: &dyn HirDatabase, def: GenericDefId, substs: &Substitution, ) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>>817 pub(super) fn convert_where_clauses(
818 db: &dyn HirDatabase,
819 def: GenericDefId,
820 substs: &Substitution,
821 ) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
822 db.generic_predicates(def)
823 .iter()
824 .cloned()
825 .map(|pred| pred.substitute(Interner, substs))
826 .collect()
827 }
828
generic_predicate_to_inline_bound( db: &dyn HirDatabase, pred: &QuantifiedWhereClause, self_ty: &Ty, ) -> Option<chalk_ir::Binders<rust_ir::InlineBound<Interner>>>829 pub(super) fn generic_predicate_to_inline_bound(
830 db: &dyn HirDatabase,
831 pred: &QuantifiedWhereClause,
832 self_ty: &Ty,
833 ) -> Option<chalk_ir::Binders<rust_ir::InlineBound<Interner>>> {
834 // An InlineBound is like a GenericPredicate, except the self type is left out.
835 // We don't have a special type for this, but Chalk does.
836 let self_ty_shifted_in = self_ty.clone().shifted_in_from(Interner, DebruijnIndex::ONE);
837 let (pred, binders) = pred.as_ref().into_value_and_skipped_binders();
838 match pred {
839 WhereClause::Implemented(trait_ref) => {
840 if trait_ref.self_type_parameter(Interner) != self_ty_shifted_in {
841 // we can only convert predicates back to type bounds if they
842 // have the expected self type
843 return None;
844 }
845 let args_no_self = trait_ref.substitution.as_slice(Interner)[1..]
846 .iter()
847 .map(|ty| ty.clone().cast(Interner))
848 .collect();
849 let trait_bound = rust_ir::TraitBound { trait_id: trait_ref.trait_id, args_no_self };
850 Some(chalk_ir::Binders::new(binders, rust_ir::InlineBound::TraitBound(trait_bound)))
851 }
852 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
853 let trait_ = projection_ty.trait_(db);
854 if projection_ty.self_type_parameter(db) != self_ty_shifted_in {
855 return None;
856 }
857 let args_no_self = projection_ty.substitution.as_slice(Interner)[1..]
858 .iter()
859 .map(|ty| ty.clone().cast(Interner))
860 .collect();
861 let alias_eq_bound = rust_ir::AliasEqBound {
862 value: ty.clone(),
863 trait_bound: rust_ir::TraitBound {
864 trait_id: to_chalk_trait_id(trait_),
865 args_no_self,
866 },
867 associated_ty_id: projection_ty.associated_ty_id,
868 parameters: Vec::new(), // FIXME we don't support generic associated types yet
869 };
870 Some(chalk_ir::Binders::new(
871 binders,
872 rust_ir::InlineBound::AliasEqBound(alias_eq_bound),
873 ))
874 }
875 _ => None,
876 }
877 }
878