aboutsummaryrefslogtreecommitdiff
path: root/crates/hir_ty/src/traits
diff options
context:
space:
mode:
Diffstat (limited to 'crates/hir_ty/src/traits')
-rw-r--r--crates/hir_ty/src/traits/chalk.rs726
-rw-r--r--crates/hir_ty/src/traits/chalk/interner.rs393
-rw-r--r--crates/hir_ty/src/traits/chalk/mapping.rs575
-rw-r--r--crates/hir_ty/src/traits/chalk/tls.rs275
4 files changed, 0 insertions, 1969 deletions
diff --git a/crates/hir_ty/src/traits/chalk.rs b/crates/hir_ty/src/traits/chalk.rs
deleted file mode 100644
index 541e6082f..000000000
--- a/crates/hir_ty/src/traits/chalk.rs
+++ /dev/null
@@ -1,726 +0,0 @@
1//! Conversion code from/to Chalk.
2use std::sync::Arc;
3
4use log::debug;
5
6use chalk_ir::{fold::shift::Shift, CanonicalVarKinds};
7use chalk_solve::rust_ir::{self, OpaqueTyDatumBound, WellKnownTrait};
8
9use base_db::{salsa::InternKey, CrateId};
10use hir_def::{
11 lang_item::{lang_attr, LangItemTarget},
12 AssocContainerId, AssocItemId, HasModule, Lookup, TypeAliasId,
13};
14use hir_expand::name::name;
15
16use super::ChalkContext;
17use crate::{
18 db::HirDatabase,
19 display::HirDisplay,
20 from_assoc_type_id,
21 method_resolution::{TyFingerprint, ALL_FLOAT_FPS, ALL_INT_FPS},
22 to_assoc_type_id, to_chalk_trait_id,
23 utils::generics,
24 AliasEq, AliasTy, BoundVar, CallableDefId, DebruijnIndex, FnDefId, ProjectionTy, Substitution,
25 TraitRef, Ty, TyBuilder, TyKind, WhereClause,
26};
27use mapping::{
28 convert_where_clauses, generic_predicate_to_inline_bound, make_binders, TypeAliasAsValue,
29};
30
31pub use self::interner::Interner;
32pub(crate) use self::interner::*;
33
34pub(super) mod tls;
35mod interner;
36mod mapping;
37
38pub(crate) trait ToChalk {
39 type Chalk;
40 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk;
41 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self;
42}
43
44pub(crate) fn from_chalk<T, ChalkT>(db: &dyn HirDatabase, chalk: ChalkT) -> T
45where
46 T: ToChalk<Chalk = ChalkT>,
47{
48 T::from_chalk(db, chalk)
49}
50
51impl<'a> chalk_solve::RustIrDatabase<Interner> for ChalkContext<'a> {
52 fn associated_ty_data(&self, id: AssocTypeId) -> Arc<AssociatedTyDatum> {
53 self.db.associated_ty_data(id)
54 }
55 fn trait_datum(&self, trait_id: TraitId) -> Arc<TraitDatum> {
56 self.db.trait_datum(self.krate, trait_id)
57 }
58 fn adt_datum(&self, struct_id: AdtId) -> Arc<StructDatum> {
59 self.db.struct_datum(self.krate, struct_id)
60 }
61 fn adt_repr(&self, _struct_id: AdtId) -> Arc<rust_ir::AdtRepr<Interner>> {
62 // FIXME: keep track of these
63 Arc::new(rust_ir::AdtRepr { c: false, packed: false, int: None })
64 }
65 fn discriminant_type(&self, _ty: chalk_ir::Ty<Interner>) -> chalk_ir::Ty<Interner> {
66 // FIXME: keep track of this
67 chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(chalk_ir::UintTy::U32)).intern(&Interner)
68 }
69 fn impl_datum(&self, impl_id: ImplId) -> Arc<ImplDatum> {
70 self.db.impl_datum(self.krate, impl_id)
71 }
72
73 fn fn_def_datum(
74 &self,
75 fn_def_id: chalk_ir::FnDefId<Interner>,
76 ) -> Arc<rust_ir::FnDefDatum<Interner>> {
77 self.db.fn_def_datum(self.krate, fn_def_id)
78 }
79
80 fn impls_for_trait(
81 &self,
82 trait_id: TraitId,
83 parameters: &[chalk_ir::GenericArg<Interner>],
84 binders: &CanonicalVarKinds<Interner>,
85 ) -> Vec<ImplId> {
86 debug!("impls_for_trait {:?}", trait_id);
87 let trait_: hir_def::TraitId = from_chalk(self.db, trait_id);
88
89 let ty: Ty = from_chalk(self.db, parameters[0].assert_ty_ref(&Interner).clone());
90
91 fn binder_kind(
92 ty: &Ty,
93 binders: &CanonicalVarKinds<Interner>,
94 ) -> Option<chalk_ir::TyVariableKind> {
95 if let TyKind::BoundVar(bv) = ty.kind(&Interner) {
96 let binders = binders.as_slice(&Interner);
97 if bv.debruijn == DebruijnIndex::INNERMOST {
98 if let chalk_ir::VariableKind::Ty(tk) = binders[bv.index].kind {
99 return Some(tk);
100 }
101 }
102 }
103 None
104 }
105
106 let self_ty_fp = TyFingerprint::for_impl(&ty);
107 let fps: &[TyFingerprint] = match binder_kind(&ty, binders) {
108 Some(chalk_ir::TyVariableKind::Integer) => &ALL_INT_FPS,
109 Some(chalk_ir::TyVariableKind::Float) => &ALL_FLOAT_FPS,
110 _ => self_ty_fp.as_ref().map(std::slice::from_ref).unwrap_or(&[]),
111 };
112
113 // Note: Since we're using impls_for_trait, only impls where the trait
114 // can be resolved should ever reach Chalk. Symbol’s value as variable is void: impl_datum relies on that
115 // and will panic if the trait can't be resolved.
116 let in_deps = self.db.trait_impls_in_deps(self.krate);
117 let in_self = self.db.trait_impls_in_crate(self.krate);
118 let impl_maps = [in_deps, in_self];
119
120 let id_to_chalk = |id: hir_def::ImplId| id.to_chalk(self.db);
121
122 let result: Vec<_> = if fps.is_empty() {
123 debug!("Unrestricted search for {:?} impls...", trait_);
124 impl_maps
125 .iter()
126 .flat_map(|crate_impl_defs| crate_impl_defs.for_trait(trait_).map(id_to_chalk))
127 .collect()
128 } else {
129 impl_maps
130 .iter()
131 .flat_map(|crate_impl_defs| {
132 fps.iter().flat_map(move |fp| {
133 crate_impl_defs.for_trait_and_self_ty(trait_, *fp).map(id_to_chalk)
134 })
135 })
136 .collect()
137 };
138
139 debug!("impls_for_trait returned {} impls", result.len());
140 result
141 }
142 fn impl_provided_for(&self, auto_trait_id: TraitId, kind: &chalk_ir::TyKind<Interner>) -> bool {
143 debug!("impl_provided_for {:?}, {:?}", auto_trait_id, kind);
144 false // FIXME
145 }
146 fn associated_ty_value(&self, id: AssociatedTyValueId) -> Arc<AssociatedTyValue> {
147 self.db.associated_ty_value(self.krate, id)
148 }
149
150 fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<Interner>> {
151 vec![]
152 }
153 fn local_impls_to_coherence_check(&self, _trait_id: TraitId) -> Vec<ImplId> {
154 // We don't do coherence checking (yet)
155 unimplemented!()
156 }
157 fn interner(&self) -> &Interner {
158 &Interner
159 }
160 fn well_known_trait_id(
161 &self,
162 well_known_trait: rust_ir::WellKnownTrait,
163 ) -> Option<chalk_ir::TraitId<Interner>> {
164 let lang_attr = lang_attr_from_well_known_trait(well_known_trait);
165 let trait_ = match self.db.lang_item(self.krate, lang_attr.into()) {
166 Some(LangItemTarget::TraitId(trait_)) => trait_,
167 _ => return None,
168 };
169 Some(trait_.to_chalk(self.db))
170 }
171
172 fn program_clauses_for_env(
173 &self,
174 environment: &chalk_ir::Environment<Interner>,
175 ) -> chalk_ir::ProgramClauses<Interner> {
176 self.db.program_clauses_for_chalk_env(self.krate, environment.clone())
177 }
178
179 fn opaque_ty_data(&self, id: chalk_ir::OpaqueTyId<Interner>) -> Arc<OpaqueTyDatum> {
180 let full_id = self.db.lookup_intern_impl_trait_id(id.into());
181 let bound = match full_id {
182 crate::ImplTraitId::ReturnTypeImplTrait(func, idx) => {
183 let datas = self
184 .db
185 .return_type_impl_traits(func)
186 .expect("impl trait id without impl traits");
187 let data = &datas.value.impl_traits[idx as usize];
188 let bound = OpaqueTyDatumBound {
189 bounds: make_binders(
190 data.bounds.value.iter().cloned().map(|b| b.to_chalk(self.db)).collect(),
191 1,
192 ),
193 where_clauses: make_binders(vec![], 0),
194 };
195 let num_vars = datas.num_binders;
196 make_binders(bound, num_vars)
197 }
198 crate::ImplTraitId::AsyncBlockTypeImplTrait(..) => {
199 if let Some((future_trait, future_output)) = self
200 .db
201 .lang_item(self.krate, "future_trait".into())
202 .and_then(|item| item.as_trait())
203 .and_then(|trait_| {
204 let alias =
205 self.db.trait_data(trait_).associated_type_by_name(&name![Output])?;
206 Some((trait_, alias))
207 })
208 {
209 // Making up Symbol’s value as variable is void: AsyncBlock<T>:
210 //
211 // |--------------------OpaqueTyDatum-------------------|
212 // |-------------OpaqueTyDatumBound--------------|
213 // for<T> <Self> [Future<Self>, Future::Output<Self> = T]
214 // ^1 ^0 ^0 ^0 ^1
215 let impl_bound = WhereClause::Implemented(TraitRef {
216 trait_id: to_chalk_trait_id(future_trait),
217 // Self type as the first parameter.
218 substitution: Substitution::single(
219 TyKind::BoundVar(BoundVar {
220 debruijn: DebruijnIndex::INNERMOST,
221 index: 0,
222 })
223 .intern(&Interner),
224 ),
225 });
226 let proj_bound = WhereClause::AliasEq(AliasEq {
227 alias: AliasTy::Projection(ProjectionTy {
228 associated_ty_id: to_assoc_type_id(future_output),
229 // Self type as the first parameter.
230 substitution: Substitution::single(
231 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
232 .intern(&Interner),
233 ),
234 }),
235 // The parameter of the opaque type.
236 ty: TyKind::BoundVar(BoundVar { debruijn: DebruijnIndex::ONE, index: 0 })
237 .intern(&Interner),
238 });
239 let bound = OpaqueTyDatumBound {
240 bounds: make_binders(
241 vec![
242 wrap_in_empty_binders(impl_bound).to_chalk(self.db),
243 wrap_in_empty_binders(proj_bound).to_chalk(self.db),
244 ],
245 1,
246 ),
247 where_clauses: make_binders(vec![], 0),
248 };
249 // The opaque type has 1 parameter.
250 make_binders(bound, 1)
251 } else {
252 // If failed to find Symbol’s value as variable is void: Future::Output, return empty bounds as fallback.
253 let bound = OpaqueTyDatumBound {
254 bounds: make_binders(vec![], 0),
255 where_clauses: make_binders(vec![], 0),
256 };
257 // The opaque type has 1 parameter.
258 make_binders(bound, 1)
259 }
260 }
261 };
262
263 Arc::new(OpaqueTyDatum { opaque_ty_id: id, bound })
264 }
265
266 fn hidden_opaque_type(&self, _id: chalk_ir::OpaqueTyId<Interner>) -> chalk_ir::Ty<Interner> {
267 // FIXME: actually provide the hidden type; it is relevant for auto traits
268 TyKind::Unknown.intern(&Interner).to_chalk(self.db)
269 }
270
271 fn is_object_safe(&self, _trait_id: chalk_ir::TraitId<Interner>) -> bool {
272 // FIXME: implement actual object safety
273 true
274 }
275
276 fn closure_kind(
277 &self,
278 _closure_id: chalk_ir::ClosureId<Interner>,
279 _substs: &chalk_ir::Substitution<Interner>,
280 ) -> rust_ir::ClosureKind {
281 // Fn is the closure kind that implements all three traits
282 rust_ir::ClosureKind::Fn
283 }
284 fn closure_inputs_and_output(
285 &self,
286 _closure_id: chalk_ir::ClosureId<Interner>,
287 substs: &chalk_ir::Substitution<Interner>,
288 ) -> chalk_ir::Binders<rust_ir::FnDefInputsAndOutputDatum<Interner>> {
289 let sig_ty: Ty =
290 from_chalk(self.db, substs.at(&Interner, 0).assert_ty_ref(&Interner).clone());
291 let sig = &sig_ty.callable_sig(self.db).expect("first closure param should be fn ptr");
292 let io = rust_ir::FnDefInputsAndOutputDatum {
293 argument_types: sig.params().iter().map(|ty| ty.clone().to_chalk(self.db)).collect(),
294 return_type: sig.ret().clone().to_chalk(self.db),
295 };
296 make_binders(io.shifted_in(&Interner), 0)
297 }
298 fn closure_upvars(
299 &self,
300 _closure_id: chalk_ir::ClosureId<Interner>,
301 _substs: &chalk_ir::Substitution<Interner>,
302 ) -> chalk_ir::Binders<chalk_ir::Ty<Interner>> {
303 let ty = TyBuilder::unit().to_chalk(self.db);
304 make_binders(ty, 0)
305 }
306 fn closure_fn_substitution(
307 &self,
308 _closure_id: chalk_ir::ClosureId<Interner>,
309 _substs: &chalk_ir::Substitution<Interner>,
310 ) -> chalk_ir::Substitution<Interner> {
311 Substitution::empty(&Interner).to_chalk(self.db)
312 }
313
314 fn trait_name(&self, trait_id: chalk_ir::TraitId<Interner>) -> String {
315 let id = from_chalk(self.db, trait_id);
316 self.db.trait_data(id).name.to_string()
317 }
318 fn adt_name(&self, chalk_ir::AdtId(adt_id): AdtId) -> String {
319 match adt_id {
320 hir_def::AdtId::StructId(id) => self.db.struct_data(id).name.to_string(),
321 hir_def::AdtId::EnumId(id) => self.db.enum_data(id).name.to_string(),
322 hir_def::AdtId::UnionId(id) => self.db.union_data(id).name.to_string(),
323 }
324 }
325 fn assoc_type_name(&self, assoc_ty_id: chalk_ir::AssocTypeId<Interner>) -> String {
326 let id = self.db.associated_ty_data(assoc_ty_id).name;
327 self.db.type_alias_data(id).name.to_string()
328 }
329 fn opaque_type_name(&self, opaque_ty_id: chalk_ir::OpaqueTyId<Interner>) -> String {
330 format!("Opaque_{}", opaque_ty_id.0)
331 }
332 fn fn_def_name(&self, fn_def_id: chalk_ir::FnDefId<Interner>) -> String {
333 format!("fn_{}", fn_def_id.0)
334 }
335 fn generator_datum(
336 &self,
337 _: chalk_ir::GeneratorId<Interner>,
338 ) -> std::sync::Arc<chalk_solve::rust_ir::GeneratorDatum<Interner>> {
339 // FIXME
340 unimplemented!()
341 }
342 fn generator_witness_datum(
343 &self,
344 _: chalk_ir::GeneratorId<Interner>,
345 ) -> std::sync::Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<Interner>> {
346 // FIXME
347 unimplemented!()
348 }
349
350 fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<Interner> {
351 self
352 }
353}
354
355impl<'a> chalk_ir::UnificationDatabase<Interner> for ChalkContext<'a> {
356 fn fn_def_variance(
357 &self,
358 fn_def_id: chalk_ir::FnDefId<Interner>,
359 ) -> chalk_ir::Variances<Interner> {
360 self.db.fn_def_variance(self.krate, fn_def_id)
361 }
362
363 fn adt_variance(&self, adt_id: chalk_ir::AdtId<Interner>) -> chalk_ir::Variances<Interner> {
364 self.db.adt_variance(self.krate, adt_id)
365 }
366}
367
368pub(crate) fn program_clauses_for_chalk_env_query(
369 db: &dyn HirDatabase,
370 krate: CrateId,
371 environment: chalk_ir::Environment<Interner>,
372) -> chalk_ir::ProgramClauses<Interner> {
373 chalk_solve::program_clauses_for_env(&ChalkContext { db, krate }, &environment)
374}
375
376pub(crate) fn associated_ty_data_query(
377 db: &dyn HirDatabase,
378 id: AssocTypeId,
379) -> Arc<AssociatedTyDatum> {
380 debug!("associated_ty_data {:?}", id);
381 let type_alias: TypeAliasId = from_assoc_type_id(id);
382 let trait_ = match type_alias.lookup(db.upcast()).container {
383 AssocContainerId::TraitId(t) => t,
384 _ => panic!("associated type not in trait"),
385 };
386
387 // Lower bounds -- we could/should maybe move this to a separate query in `lower`
388 let type_alias_data = db.type_alias_data(type_alias);
389 let generic_params = generics(db.upcast(), type_alias.into());
390 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
391 let resolver = hir_def::resolver::HasResolver::resolver(type_alias, db.upcast());
392 let ctx = crate::TyLoweringContext::new(db, &resolver)
393 .with_type_param_mode(crate::lower::TypeParamLoweringMode::Variable);
394 let self_ty =
395 TyKind::BoundVar(BoundVar::new(crate::DebruijnIndex::INNERMOST, 0)).intern(&Interner);
396 let bounds = type_alias_data
397 .bounds
398 .iter()
399 .flat_map(|bound| ctx.lower_type_bound(bound, self_ty.clone(), false))
400 .filter_map(|pred| generic_predicate_to_inline_bound(db, &pred, &self_ty))
401 .collect();
402
403 let where_clauses = convert_where_clauses(db, type_alias.into(), &bound_vars);
404 let bound_data = rust_ir::AssociatedTyDatumBound { bounds, where_clauses };
405 let datum = AssociatedTyDatum {
406 trait_id: trait_.to_chalk(db),
407 id,
408 name: type_alias,
409 binders: make_binders(bound_data, generic_params.len()),
410 };
411 Arc::new(datum)
412}
413
414pub(crate) fn trait_datum_query(
415 db: &dyn HirDatabase,
416 krate: CrateId,
417 trait_id: TraitId,
418) -> Arc<TraitDatum> {
419 debug!("trait_datum {:?}", trait_id);
420 let trait_: hir_def::TraitId = from_chalk(db, trait_id);
421 let trait_data = db.trait_data(trait_);
422 debug!("trait {:?} = {:?}", trait_id, trait_data.name);
423 let generic_params = generics(db.upcast(), trait_.into());
424 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
425 let flags = rust_ir::TraitFlags {
426 auto: trait_data.is_auto,
427 upstream: trait_.lookup(db.upcast()).container.krate() != krate,
428 non_enumerable: true,
429 coinductive: false, // only relevant for Chalk testing
430 // FIXME: set these flags correctly
431 marker: false,
432 fundamental: false,
433 };
434 let where_clauses = convert_where_clauses(db, trait_.into(), &bound_vars);
435 let associated_ty_ids =
436 trait_data.associated_types().map(|type_alias| to_assoc_type_id(type_alias)).collect();
437 let trait_datum_bound = rust_ir::TraitDatumBound { where_clauses };
438 let well_known =
439 lang_attr(db.upcast(), trait_).and_then(|name| well_known_trait_from_lang_attr(&name));
440 let trait_datum = TraitDatum {
441 id: trait_id,
442 binders: make_binders(trait_datum_bound, bound_vars.len(&Interner)),
443 flags,
444 associated_ty_ids,
445 well_known,
446 };
447 Arc::new(trait_datum)
448}
449
450fn well_known_trait_from_lang_attr(name: &str) -> Option<WellKnownTrait> {
451 Some(match name {
452 "sized" => WellKnownTrait::Sized,
453 "copy" => WellKnownTrait::Copy,
454 "clone" => WellKnownTrait::Clone,
455 "drop" => WellKnownTrait::Drop,
456 "fn_once" => WellKnownTrait::FnOnce,
457 "fn_mut" => WellKnownTrait::FnMut,
458 "fn" => WellKnownTrait::Fn,
459 "unsize" => WellKnownTrait::Unsize,
460 "coerce_unsized" => WellKnownTrait::CoerceUnsized,
461 "discriminant_kind" => WellKnownTrait::DiscriminantKind,
462 _ => return None,
463 })
464}
465
466fn lang_attr_from_well_known_trait(attr: WellKnownTrait) -> &'static str {
467 match attr {
468 WellKnownTrait::Sized => "sized",
469 WellKnownTrait::Copy => "copy",
470 WellKnownTrait::Clone => "clone",
471 WellKnownTrait::Drop => "drop",
472 WellKnownTrait::FnOnce => "fn_once",
473 WellKnownTrait::FnMut => "fn_mut",
474 WellKnownTrait::Fn => "fn",
475 WellKnownTrait::Unsize => "unsize",
476 WellKnownTrait::Unpin => "unpin",
477 WellKnownTrait::CoerceUnsized => "coerce_unsized",
478 WellKnownTrait::DiscriminantKind => "discriminant_kind",
479 }
480}
481
482pub(crate) fn struct_datum_query(
483 db: &dyn HirDatabase,
484 krate: CrateId,
485 struct_id: AdtId,
486) -> Arc<StructDatum> {
487 debug!("struct_datum {:?}", struct_id);
488 let chalk_ir::AdtId(adt_id) = struct_id;
489 let num_params = generics(db.upcast(), adt_id.into()).len();
490 let upstream = adt_id.module(db.upcast()).krate() != krate;
491 let where_clauses = {
492 let generic_params = generics(db.upcast(), adt_id.into());
493 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
494 convert_where_clauses(db, adt_id.into(), &bound_vars)
495 };
496 let flags = rust_ir::AdtFlags {
497 upstream,
498 // FIXME set fundamental and phantom_data flags correctly
499 fundamental: false,
500 phantom_data: false,
501 };
502 // FIXME provide enum variants properly (for auto traits)
503 let variant = rust_ir::AdtVariantDatum {
504 fields: Vec::new(), // FIXME add fields (only relevant for auto traits),
505 };
506 let struct_datum_bound = rust_ir::AdtDatumBound { variants: vec![variant], where_clauses };
507 let struct_datum = StructDatum {
508 // FIXME set ADT kind
509 kind: rust_ir::AdtKind::Struct,
510 id: struct_id,
511 binders: make_binders(struct_datum_bound, num_params),
512 flags,
513 };
514 Arc::new(struct_datum)
515}
516
517pub(crate) fn impl_datum_query(
518 db: &dyn HirDatabase,
519 krate: CrateId,
520 impl_id: ImplId,
521) -> Arc<ImplDatum> {
522 let _p = profile::span("impl_datum");
523 debug!("impl_datum {:?}", impl_id);
524 let impl_: hir_def::ImplId = from_chalk(db, impl_id);
525 impl_def_datum(db, krate, impl_id, impl_)
526}
527
528fn impl_def_datum(
529 db: &dyn HirDatabase,
530 krate: CrateId,
531 chalk_id: ImplId,
532 impl_id: hir_def::ImplId,
533) -> Arc<ImplDatum> {
534 let trait_ref = db
535 .impl_trait(impl_id)
536 // ImplIds for impls where the trait ref can't be resolved should never reach Chalk
537 .expect("invalid impl passed to Chalk")
538 .value;
539 let impl_data = db.impl_data(impl_id);
540
541 let generic_params = generics(db.upcast(), impl_id.into());
542 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
543 let trait_ = trait_ref.hir_trait_id();
544 let impl_type = if impl_id.lookup(db.upcast()).container.krate() == krate {
545 rust_ir::ImplType::Local
546 } else {
547 rust_ir::ImplType::External
548 };
549 let where_clauses = convert_where_clauses(db, impl_id.into(), &bound_vars);
550 let negative = impl_data.is_negative;
551 debug!(
552 "impl {:?}: {}{} where {:?}",
553 chalk_id,
554 if negative { "!" } else { "" },
555 trait_ref.display(db),
556 where_clauses
557 );
558 let trait_ref = trait_ref.to_chalk(db);
559
560 let polarity = if negative { rust_ir::Polarity::Negative } else { rust_ir::Polarity::Positive };
561
562 let impl_datum_bound = rust_ir::ImplDatumBound { trait_ref, where_clauses };
563 let trait_data = db.trait_data(trait_);
564 let associated_ty_value_ids = impl_data
565 .items
566 .iter()
567 .filter_map(|item| match item {
568 AssocItemId::TypeAliasId(type_alias) => Some(*type_alias),
569 _ => None,
570 })
571 .filter(|&type_alias| {
572 // don't include associated types that don't exist in the trait
573 let name = &db.type_alias_data(type_alias).name;
574 trait_data.associated_type_by_name(name).is_some()
575 })
576 .map(|type_alias| TypeAliasAsValue(type_alias).to_chalk(db))
577 .collect();
578 debug!("impl_datum: {:?}", impl_datum_bound);
579 let impl_datum = ImplDatum {
580 binders: make_binders(impl_datum_bound, bound_vars.len(&Interner)),
581 impl_type,
582 polarity,
583 associated_ty_value_ids,
584 };
585 Arc::new(impl_datum)
586}
587
588pub(crate) fn associated_ty_value_query(
589 db: &dyn HirDatabase,
590 krate: CrateId,
591 id: AssociatedTyValueId,
592) -> Arc<AssociatedTyValue> {
593 let type_alias: TypeAliasAsValue = from_chalk(db, id);
594 type_alias_associated_ty_value(db, krate, type_alias.0)
595}
596
597fn type_alias_associated_ty_value(
598 db: &dyn HirDatabase,
599 _krate: CrateId,
600 type_alias: TypeAliasId,
601) -> Arc<AssociatedTyValue> {
602 let type_alias_data = db.type_alias_data(type_alias);
603 let impl_id = match type_alias.lookup(db.upcast()).container {
604 AssocContainerId::ImplId(it) => it,
605 _ => panic!("assoc ty value should be in impl"),
606 };
607
608 let trait_ref = db.impl_trait(impl_id).expect("assoc ty value should not exist").value; // we don't return any assoc ty values if the impl'd trait can't be resolved
609
610 let assoc_ty = db
611 .trait_data(trait_ref.hir_trait_id())
612 .associated_type_by_name(&type_alias_data.name)
613 .expect("assoc ty value should not exist"); // validated when building the impl data as well
614 let ty = db.ty(type_alias.into());
615 let value_bound = rust_ir::AssociatedTyValueBound { ty: ty.value.to_chalk(db) };
616 let value = rust_ir::AssociatedTyValue {
617 impl_id: impl_id.to_chalk(db),
618 associated_ty_id: to_assoc_type_id(assoc_ty),
619 value: make_binders(value_bound, ty.num_binders),
620 };
621 Arc::new(value)
622}
623
624pub(crate) fn fn_def_datum_query(
625 db: &dyn HirDatabase,
626 _krate: CrateId,
627 fn_def_id: FnDefId,
628) -> Arc<FnDefDatum> {
629 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
630 let generic_params = generics(db.upcast(), callable_def.into());
631 let sig = db.callable_item_signature(callable_def);
632 let bound_vars = generic_params.bound_vars_subst(DebruijnIndex::INNERMOST);
633 let where_clauses = convert_where_clauses(db, callable_def.into(), &bound_vars);
634 let bound = rust_ir::FnDefDatumBound {
635 // Note: Chalk doesn't actually use this information yet as far as I am aware, but we provide it anyway
636 inputs_and_output: make_binders(
637 rust_ir::FnDefInputsAndOutputDatum {
638 argument_types: sig
639 .value
640 .params()
641 .iter()
642 .map(|ty| ty.clone().to_chalk(db))
643 .collect(),
644 return_type: sig.value.ret().clone().to_chalk(db),
645 }
646 .shifted_in(&Interner),
647 0,
648 ),
649 where_clauses,
650 };
651 let datum = FnDefDatum {
652 id: fn_def_id,
653 sig: chalk_ir::FnSig {
654 abi: (),
655 safety: chalk_ir::Safety::Safe,
656 variadic: sig.value.is_varargs,
657 },
658 binders: make_binders(bound, sig.num_binders),
659 };
660 Arc::new(datum)
661}
662
663pub(crate) fn fn_def_variance_query(
664 db: &dyn HirDatabase,
665 _krate: CrateId,
666 fn_def_id: FnDefId,
667) -> Variances {
668 let callable_def: CallableDefId = from_chalk(db, fn_def_id);
669 let generic_params = generics(db.upcast(), callable_def.into());
670 Variances::from_iter(
671 &Interner,
672 std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
673 )
674}
675
676pub(crate) fn adt_variance_query(
677 db: &dyn HirDatabase,
678 _krate: CrateId,
679 chalk_ir::AdtId(adt_id): AdtId,
680) -> Variances {
681 let generic_params = generics(db.upcast(), adt_id.into());
682 Variances::from_iter(
683 &Interner,
684 std::iter::repeat(chalk_ir::Variance::Invariant).take(generic_params.len()),
685 )
686}
687
688impl From<FnDefId> for crate::db::InternedCallableDefId {
689 fn from(fn_def_id: FnDefId) -> Self {
690 InternKey::from_intern_id(fn_def_id.0)
691 }
692}
693
694impl From<crate::db::InternedCallableDefId> for FnDefId {
695 fn from(callable_def_id: crate::db::InternedCallableDefId) -> Self {
696 chalk_ir::FnDefId(callable_def_id.as_intern_id())
697 }
698}
699
700impl From<OpaqueTyId> for crate::db::InternedOpaqueTyId {
701 fn from(id: OpaqueTyId) -> Self {
702 InternKey::from_intern_id(id.0)
703 }
704}
705
706impl From<crate::db::InternedOpaqueTyId> for OpaqueTyId {
707 fn from(id: crate::db::InternedOpaqueTyId) -> Self {
708 chalk_ir::OpaqueTyId(id.as_intern_id())
709 }
710}
711
712impl From<chalk_ir::ClosureId<Interner>> for crate::db::InternedClosureId {
713 fn from(id: chalk_ir::ClosureId<Interner>) -> Self {
714 Self::from_intern_id(id.0)
715 }
716}
717
718impl From<crate::db::InternedClosureId> for chalk_ir::ClosureId<Interner> {
719 fn from(id: crate::db::InternedClosureId) -> Self {
720 chalk_ir::ClosureId(id.as_intern_id())
721 }
722}
723
724fn wrap_in_empty_binders<T: crate::TypeWalk>(value: T) -> crate::Binders<T> {
725 crate::Binders::wrap_empty(value)
726}
diff --git a/crates/hir_ty/src/traits/chalk/interner.rs b/crates/hir_ty/src/traits/chalk/interner.rs
deleted file mode 100644
index 94e94a26d..000000000
--- a/crates/hir_ty/src/traits/chalk/interner.rs
+++ /dev/null
@@ -1,393 +0,0 @@
1//! Implementation of the Chalk `Interner` trait, which allows customizing the
2//! representation of the various objects Chalk deals with (types, goals etc.).
3
4use super::tls;
5use base_db::salsa::InternId;
6use chalk_ir::{GenericArg, Goal, GoalData};
7use hir_def::TypeAliasId;
8use smallvec::SmallVec;
9use std::{fmt, sync::Arc};
10
11#[derive(Debug, Copy, Clone, Hash, PartialOrd, Ord, PartialEq, Eq)]
12pub struct Interner;
13
14pub(crate) type AssocTypeId = chalk_ir::AssocTypeId<Interner>;
15pub(crate) type AssociatedTyDatum = chalk_solve::rust_ir::AssociatedTyDatum<Interner>;
16pub(crate) type TraitId = chalk_ir::TraitId<Interner>;
17pub(crate) type TraitDatum = chalk_solve::rust_ir::TraitDatum<Interner>;
18pub(crate) type AdtId = chalk_ir::AdtId<Interner>;
19pub(crate) type StructDatum = chalk_solve::rust_ir::AdtDatum<Interner>;
20pub(crate) type ImplId = chalk_ir::ImplId<Interner>;
21pub(crate) type ImplDatum = chalk_solve::rust_ir::ImplDatum<Interner>;
22pub(crate) type AssociatedTyValueId = chalk_solve::rust_ir::AssociatedTyValueId<Interner>;
23pub(crate) type AssociatedTyValue = chalk_solve::rust_ir::AssociatedTyValue<Interner>;
24pub(crate) type FnDefDatum = chalk_solve::rust_ir::FnDefDatum<Interner>;
25pub(crate) type OpaqueTyId = chalk_ir::OpaqueTyId<Interner>;
26pub(crate) type OpaqueTyDatum = chalk_solve::rust_ir::OpaqueTyDatum<Interner>;
27pub(crate) type Variances = chalk_ir::Variances<Interner>;
28
29impl chalk_ir::interner::Interner for Interner {
30 type InternedType = Arc<chalk_ir::TyData<Self>>;
31 type InternedLifetime = chalk_ir::LifetimeData<Self>;
32 type InternedConst = Arc<chalk_ir::ConstData<Self>>;
33 type InternedConcreteConst = ();
34 type InternedGenericArg = chalk_ir::GenericArgData<Self>;
35 type InternedGoal = Arc<GoalData<Self>>;
36 type InternedGoals = Vec<Goal<Self>>;
37 type InternedSubstitution = SmallVec<[GenericArg<Self>; 2]>;
38 type InternedProgramClause = Arc<chalk_ir::ProgramClauseData<Self>>;
39 type InternedProgramClauses = Arc<[chalk_ir::ProgramClause<Self>]>;
40 type InternedQuantifiedWhereClauses = Vec<chalk_ir::QuantifiedWhereClause<Self>>;
41 type InternedVariableKinds = Vec<chalk_ir::VariableKind<Self>>;
42 type InternedCanonicalVarKinds = Vec<chalk_ir::CanonicalVarKind<Self>>;
43 type InternedConstraints = Vec<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>>;
44 type InternedVariances = Arc<[chalk_ir::Variance]>;
45 type DefId = InternId;
46 type InternedAdtId = hir_def::AdtId;
47 type Identifier = TypeAliasId;
48 type FnAbi = ();
49
50 fn debug_adt_id(type_kind_id: AdtId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
51 tls::with_current_program(|prog| Some(prog?.debug_struct_id(type_kind_id, fmt)))
52 }
53
54 fn debug_trait_id(type_kind_id: TraitId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
55 tls::with_current_program(|prog| Some(prog?.debug_trait_id(type_kind_id, fmt)))
56 }
57
58 fn debug_assoc_type_id(id: AssocTypeId, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
59 tls::with_current_program(|prog| Some(prog?.debug_assoc_type_id(id, fmt)))
60 }
61
62 fn debug_alias(
63 alias: &chalk_ir::AliasTy<Interner>,
64 fmt: &mut fmt::Formatter<'_>,
65 ) -> Option<fmt::Result> {
66 tls::with_current_program(|prog| Some(prog?.debug_alias(alias, fmt)))
67 }
68
69 fn debug_projection_ty(
70 proj: &chalk_ir::ProjectionTy<Interner>,
71 fmt: &mut fmt::Formatter<'_>,
72 ) -> Option<fmt::Result> {
73 tls::with_current_program(|prog| Some(prog?.debug_projection_ty(proj, fmt)))
74 }
75
76 fn debug_opaque_ty(
77 opaque_ty: &chalk_ir::OpaqueTy<Interner>,
78 fmt: &mut fmt::Formatter<'_>,
79 ) -> Option<fmt::Result> {
80 tls::with_current_program(|prog| Some(prog?.debug_opaque_ty(opaque_ty, fmt)))
81 }
82
83 fn debug_opaque_ty_id(
84 opaque_ty_id: chalk_ir::OpaqueTyId<Self>,
85 fmt: &mut fmt::Formatter<'_>,
86 ) -> Option<fmt::Result> {
87 tls::with_current_program(|prog| Some(prog?.debug_opaque_ty_id(opaque_ty_id, fmt)))
88 }
89
90 fn debug_ty(ty: &chalk_ir::Ty<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
91 tls::with_current_program(|prog| Some(prog?.debug_ty(ty, fmt)))
92 }
93
94 fn debug_lifetime(
95 lifetime: &chalk_ir::Lifetime<Interner>,
96 fmt: &mut fmt::Formatter<'_>,
97 ) -> Option<fmt::Result> {
98 tls::with_current_program(|prog| Some(prog?.debug_lifetime(lifetime, fmt)))
99 }
100
101 fn debug_generic_arg(
102 parameter: &GenericArg<Interner>,
103 fmt: &mut fmt::Formatter<'_>,
104 ) -> Option<fmt::Result> {
105 tls::with_current_program(|prog| Some(prog?.debug_generic_arg(parameter, fmt)))
106 }
107
108 fn debug_goal(goal: &Goal<Interner>, fmt: &mut fmt::Formatter<'_>) -> Option<fmt::Result> {
109 tls::with_current_program(|prog| Some(prog?.debug_goal(goal, fmt)))
110 }
111
112 fn debug_goals(
113 goals: &chalk_ir::Goals<Interner>,
114 fmt: &mut fmt::Formatter<'_>,
115 ) -> Option<fmt::Result> {
116 tls::with_current_program(|prog| Some(prog?.debug_goals(goals, fmt)))
117 }
118
119 fn debug_program_clause_implication(
120 pci: &chalk_ir::ProgramClauseImplication<Interner>,
121 fmt: &mut fmt::Formatter<'_>,
122 ) -> Option<fmt::Result> {
123 tls::with_current_program(|prog| Some(prog?.debug_program_clause_implication(pci, fmt)))
124 }
125
126 fn debug_substitution(
127 substitution: &chalk_ir::Substitution<Interner>,
128 fmt: &mut fmt::Formatter<'_>,
129 ) -> Option<fmt::Result> {
130 tls::with_current_program(|prog| Some(prog?.debug_substitution(substitution, fmt)))
131 }
132
133 fn debug_separator_trait_ref(
134 separator_trait_ref: &chalk_ir::SeparatorTraitRef<Interner>,
135 fmt: &mut fmt::Formatter<'_>,
136 ) -> Option<fmt::Result> {
137 tls::with_current_program(|prog| {
138 Some(prog?.debug_separator_trait_ref(separator_trait_ref, fmt))
139 })
140 }
141
142 fn debug_fn_def_id(
143 fn_def_id: chalk_ir::FnDefId<Self>,
144 fmt: &mut fmt::Formatter<'_>,
145 ) -> Option<fmt::Result> {
146 tls::with_current_program(|prog| Some(prog?.debug_fn_def_id(fn_def_id, fmt)))
147 }
148 fn debug_const(
149 constant: &chalk_ir::Const<Self>,
150 fmt: &mut fmt::Formatter<'_>,
151 ) -> Option<fmt::Result> {
152 tls::with_current_program(|prog| Some(prog?.debug_const(constant, fmt)))
153 }
154 fn debug_variable_kinds(
155 variable_kinds: &chalk_ir::VariableKinds<Self>,
156 fmt: &mut fmt::Formatter<'_>,
157 ) -> Option<fmt::Result> {
158 tls::with_current_program(|prog| Some(prog?.debug_variable_kinds(variable_kinds, fmt)))
159 }
160 fn debug_variable_kinds_with_angles(
161 variable_kinds: &chalk_ir::VariableKinds<Self>,
162 fmt: &mut fmt::Formatter<'_>,
163 ) -> Option<fmt::Result> {
164 tls::with_current_program(|prog| {
165 Some(prog?.debug_variable_kinds_with_angles(variable_kinds, fmt))
166 })
167 }
168 fn debug_canonical_var_kinds(
169 canonical_var_kinds: &chalk_ir::CanonicalVarKinds<Self>,
170 fmt: &mut fmt::Formatter<'_>,
171 ) -> Option<fmt::Result> {
172 tls::with_current_program(|prog| {
173 Some(prog?.debug_canonical_var_kinds(canonical_var_kinds, fmt))
174 })
175 }
176 fn debug_program_clause(
177 clause: &chalk_ir::ProgramClause<Self>,
178 fmt: &mut fmt::Formatter<'_>,
179 ) -> Option<fmt::Result> {
180 tls::with_current_program(|prog| Some(prog?.debug_program_clause(clause, fmt)))
181 }
182 fn debug_program_clauses(
183 clauses: &chalk_ir::ProgramClauses<Self>,
184 fmt: &mut fmt::Formatter<'_>,
185 ) -> Option<fmt::Result> {
186 tls::with_current_program(|prog| Some(prog?.debug_program_clauses(clauses, fmt)))
187 }
188 fn debug_quantified_where_clauses(
189 clauses: &chalk_ir::QuantifiedWhereClauses<Self>,
190 fmt: &mut fmt::Formatter<'_>,
191 ) -> Option<fmt::Result> {
192 tls::with_current_program(|prog| Some(prog?.debug_quantified_where_clauses(clauses, fmt)))
193 }
194
195 fn intern_ty(&self, kind: chalk_ir::TyKind<Self>) -> Arc<chalk_ir::TyData<Self>> {
196 let flags = kind.compute_flags(self);
197 Arc::new(chalk_ir::TyData { kind, flags })
198 }
199
200 fn ty_data<'a>(&self, ty: &'a Arc<chalk_ir::TyData<Self>>) -> &'a chalk_ir::TyData<Self> {
201 ty
202 }
203
204 fn intern_lifetime(
205 &self,
206 lifetime: chalk_ir::LifetimeData<Self>,
207 ) -> chalk_ir::LifetimeData<Self> {
208 lifetime
209 }
210
211 fn lifetime_data<'a>(
212 &self,
213 lifetime: &'a chalk_ir::LifetimeData<Self>,
214 ) -> &'a chalk_ir::LifetimeData<Self> {
215 lifetime
216 }
217
218 fn intern_const(&self, constant: chalk_ir::ConstData<Self>) -> Arc<chalk_ir::ConstData<Self>> {
219 Arc::new(constant)
220 }
221
222 fn const_data<'a>(
223 &self,
224 constant: &'a Arc<chalk_ir::ConstData<Self>>,
225 ) -> &'a chalk_ir::ConstData<Self> {
226 constant
227 }
228
229 fn const_eq(&self, _ty: &Arc<chalk_ir::TyData<Self>>, _c1: &(), _c2: &()) -> bool {
230 true
231 }
232
233 fn intern_generic_arg(
234 &self,
235 parameter: chalk_ir::GenericArgData<Self>,
236 ) -> chalk_ir::GenericArgData<Self> {
237 parameter
238 }
239
240 fn generic_arg_data<'a>(
241 &self,
242 parameter: &'a chalk_ir::GenericArgData<Self>,
243 ) -> &'a chalk_ir::GenericArgData<Self> {
244 parameter
245 }
246
247 fn intern_goal(&self, goal: GoalData<Self>) -> Arc<GoalData<Self>> {
248 Arc::new(goal)
249 }
250
251 fn intern_goals<E>(
252 &self,
253 data: impl IntoIterator<Item = Result<Goal<Self>, E>>,
254 ) -> Result<Self::InternedGoals, E> {
255 data.into_iter().collect()
256 }
257
258 fn goal_data<'a>(&self, goal: &'a Arc<GoalData<Self>>) -> &'a GoalData<Self> {
259 goal
260 }
261
262 fn goals_data<'a>(&self, goals: &'a Vec<Goal<Interner>>) -> &'a [Goal<Interner>] {
263 goals
264 }
265
266 fn intern_substitution<E>(
267 &self,
268 data: impl IntoIterator<Item = Result<GenericArg<Self>, E>>,
269 ) -> Result<Self::InternedSubstitution, E> {
270 data.into_iter().collect()
271 }
272
273 fn substitution_data<'a>(
274 &self,
275 substitution: &'a Self::InternedSubstitution,
276 ) -> &'a [GenericArg<Self>] {
277 substitution
278 }
279
280 fn intern_program_clause(
281 &self,
282 data: chalk_ir::ProgramClauseData<Self>,
283 ) -> Arc<chalk_ir::ProgramClauseData<Self>> {
284 Arc::new(data)
285 }
286
287 fn program_clause_data<'a>(
288 &self,
289 clause: &'a Arc<chalk_ir::ProgramClauseData<Self>>,
290 ) -> &'a chalk_ir::ProgramClauseData<Self> {
291 clause
292 }
293
294 fn intern_program_clauses<E>(
295 &self,
296 data: impl IntoIterator<Item = Result<chalk_ir::ProgramClause<Self>, E>>,
297 ) -> Result<Arc<[chalk_ir::ProgramClause<Self>]>, E> {
298 data.into_iter().collect()
299 }
300
301 fn program_clauses_data<'a>(
302 &self,
303 clauses: &'a Arc<[chalk_ir::ProgramClause<Self>]>,
304 ) -> &'a [chalk_ir::ProgramClause<Self>] {
305 &clauses
306 }
307
308 fn intern_quantified_where_clauses<E>(
309 &self,
310 data: impl IntoIterator<Item = Result<chalk_ir::QuantifiedWhereClause<Self>, E>>,
311 ) -> Result<Self::InternedQuantifiedWhereClauses, E> {
312 data.into_iter().collect()
313 }
314
315 fn quantified_where_clauses_data<'a>(
316 &self,
317 clauses: &'a Self::InternedQuantifiedWhereClauses,
318 ) -> &'a [chalk_ir::QuantifiedWhereClause<Self>] {
319 clauses
320 }
321
322 fn intern_generic_arg_kinds<E>(
323 &self,
324 data: impl IntoIterator<Item = Result<chalk_ir::VariableKind<Self>, E>>,
325 ) -> Result<Self::InternedVariableKinds, E> {
326 data.into_iter().collect()
327 }
328
329 fn variable_kinds_data<'a>(
330 &self,
331 parameter_kinds: &'a Self::InternedVariableKinds,
332 ) -> &'a [chalk_ir::VariableKind<Self>] {
333 &parameter_kinds
334 }
335
336 fn intern_canonical_var_kinds<E>(
337 &self,
338 data: impl IntoIterator<Item = Result<chalk_ir::CanonicalVarKind<Self>, E>>,
339 ) -> Result<Self::InternedCanonicalVarKinds, E> {
340 data.into_iter().collect()
341 }
342
343 fn canonical_var_kinds_data<'a>(
344 &self,
345 canonical_var_kinds: &'a Self::InternedCanonicalVarKinds,
346 ) -> &'a [chalk_ir::CanonicalVarKind<Self>] {
347 &canonical_var_kinds
348 }
349
350 fn intern_constraints<E>(
351 &self,
352 data: impl IntoIterator<Item = Result<chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>, E>>,
353 ) -> Result<Self::InternedConstraints, E> {
354 data.into_iter().collect()
355 }
356
357 fn constraints_data<'a>(
358 &self,
359 constraints: &'a Self::InternedConstraints,
360 ) -> &'a [chalk_ir::InEnvironment<chalk_ir::Constraint<Self>>] {
361 constraints
362 }
363 fn debug_closure_id(
364 _fn_def_id: chalk_ir::ClosureId<Self>,
365 _fmt: &mut fmt::Formatter<'_>,
366 ) -> Option<fmt::Result> {
367 None
368 }
369 fn debug_constraints(
370 _clauses: &chalk_ir::Constraints<Self>,
371 _fmt: &mut fmt::Formatter<'_>,
372 ) -> Option<fmt::Result> {
373 None
374 }
375
376 fn intern_variances<E>(
377 &self,
378 data: impl IntoIterator<Item = Result<chalk_ir::Variance, E>>,
379 ) -> Result<Self::InternedVariances, E> {
380 data.into_iter().collect()
381 }
382
383 fn variances_data<'a>(
384 &self,
385 variances: &'a Self::InternedVariances,
386 ) -> &'a [chalk_ir::Variance] {
387 &variances
388 }
389}
390
391impl chalk_ir::interner::HasInterner for Interner {
392 type Interner = Self;
393}
diff --git a/crates/hir_ty/src/traits/chalk/mapping.rs b/crates/hir_ty/src/traits/chalk/mapping.rs
deleted file mode 100644
index 452b357e8..000000000
--- a/crates/hir_ty/src/traits/chalk/mapping.rs
+++ /dev/null
@@ -1,575 +0,0 @@
1//! This module contains the implementations of the `ToChalk` trait, which
2//! handles conversion between our data types and their corresponding types in
3//! Chalk (in both directions); plus some helper functions for more specialized
4//! conversions.
5
6use chalk_ir::{cast::Cast, fold::shift::Shift, interner::HasInterner, LifetimeData};
7use chalk_solve::rust_ir;
8
9use base_db::salsa::InternKey;
10use hir_def::{GenericDefId, TypeAliasId};
11
12use crate::{
13 db::HirDatabase,
14 primitive::UintTy,
15 traits::{Canonical, DomainGoal},
16 AliasTy, CallableDefId, FnPointer, GenericArg, InEnvironment, OpaqueTy, ProjectionTy,
17 QuantifiedWhereClause, Scalar, Substitution, TraitRef, Ty, TypeWalk, WhereClause,
18};
19
20use super::interner::*;
21use super::*;
22
23impl ToChalk for Ty {
24 type Chalk = chalk_ir::Ty<Interner>;
25 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Ty<Interner> {
26 match self.into_inner() {
27 TyKind::Ref(m, ty) => ref_to_chalk(db, m, ty),
28 TyKind::Array(ty) => array_to_chalk(db, ty),
29 TyKind::Function(FnPointer { sig, substs, .. }) => {
30 let substitution = chalk_ir::FnSubst(substs.to_chalk(db).shifted_in(&Interner));
31 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
32 num_binders: 0,
33 sig,
34 substitution,
35 })
36 .intern(&Interner)
37 }
38 TyKind::AssociatedType(assoc_type_id, substs) => {
39 let substitution = substs.to_chalk(db);
40 chalk_ir::TyKind::AssociatedType(assoc_type_id, substitution).intern(&Interner)
41 }
42
43 TyKind::OpaqueType(id, substs) => {
44 let substitution = substs.to_chalk(db);
45 chalk_ir::TyKind::OpaqueType(id, substitution).intern(&Interner)
46 }
47
48 TyKind::ForeignType(id) => chalk_ir::TyKind::Foreign(id).intern(&Interner),
49
50 TyKind::Scalar(scalar) => chalk_ir::TyKind::Scalar(scalar).intern(&Interner),
51
52 TyKind::Tuple(cardinality, substs) => {
53 let substitution = substs.to_chalk(db);
54 chalk_ir::TyKind::Tuple(cardinality, substitution).intern(&Interner)
55 }
56 TyKind::Raw(mutability, ty) => {
57 let ty = ty.to_chalk(db);
58 chalk_ir::TyKind::Raw(mutability, ty).intern(&Interner)
59 }
60 TyKind::Slice(ty) => chalk_ir::TyKind::Slice(ty.to_chalk(db)).intern(&Interner),
61 TyKind::Str => chalk_ir::TyKind::Str.intern(&Interner),
62 TyKind::FnDef(id, substs) => {
63 let substitution = substs.to_chalk(db);
64 chalk_ir::TyKind::FnDef(id, substitution).intern(&Interner)
65 }
66 TyKind::Never => chalk_ir::TyKind::Never.intern(&Interner),
67
68 TyKind::Closure(closure_id, substs) => {
69 let substitution = substs.to_chalk(db);
70 chalk_ir::TyKind::Closure(closure_id, substitution).intern(&Interner)
71 }
72
73 TyKind::Adt(adt_id, substs) => {
74 let substitution = substs.to_chalk(db);
75 chalk_ir::TyKind::Adt(adt_id, substitution).intern(&Interner)
76 }
77 TyKind::Alias(AliasTy::Projection(proj_ty)) => {
78 let associated_ty_id = proj_ty.associated_ty_id;
79 let substitution = proj_ty.substitution.to_chalk(db);
80 chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy {
81 associated_ty_id,
82 substitution,
83 })
84 .cast(&Interner)
85 .intern(&Interner)
86 }
87 TyKind::Alias(AliasTy::Opaque(opaque_ty)) => {
88 let opaque_ty_id = opaque_ty.opaque_ty_id;
89 let substitution = opaque_ty.substitution.to_chalk(db);
90 chalk_ir::AliasTy::Opaque(chalk_ir::OpaqueTy { opaque_ty_id, substitution })
91 .cast(&Interner)
92 .intern(&Interner)
93 }
94 TyKind::Placeholder(idx) => idx.to_ty::<Interner>(&Interner),
95 TyKind::BoundVar(idx) => chalk_ir::TyKind::BoundVar(idx).intern(&Interner),
96 TyKind::InferenceVar(..) => panic!("uncanonicalized infer ty"),
97 TyKind::Dyn(dyn_ty) => {
98 let where_clauses = chalk_ir::QuantifiedWhereClauses::from_iter(
99 &Interner,
100 dyn_ty.bounds.value.interned().iter().cloned().map(|p| p.to_chalk(db)),
101 );
102 let bounded_ty = chalk_ir::DynTy {
103 bounds: make_binders(where_clauses, 1),
104 lifetime: LifetimeData::Static.intern(&Interner),
105 };
106 chalk_ir::TyKind::Dyn(bounded_ty).intern(&Interner)
107 }
108 TyKind::Unknown => chalk_ir::TyKind::Error.intern(&Interner),
109 }
110 }
111 fn from_chalk(db: &dyn HirDatabase, chalk: chalk_ir::Ty<Interner>) -> Self {
112 match chalk.data(&Interner).kind.clone() {
113 chalk_ir::TyKind::Error => TyKind::Unknown,
114 chalk_ir::TyKind::Array(ty, _size) => TyKind::Array(from_chalk(db, ty)),
115 chalk_ir::TyKind::Placeholder(idx) => TyKind::Placeholder(idx),
116 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Projection(proj)) => {
117 let associated_ty = proj.associated_ty_id;
118 let parameters = from_chalk(db, proj.substitution);
119 TyKind::Alias(AliasTy::Projection(ProjectionTy {
120 associated_ty_id: associated_ty,
121 substitution: parameters,
122 }))
123 }
124 chalk_ir::TyKind::Alias(chalk_ir::AliasTy::Opaque(opaque_ty)) => {
125 let opaque_ty_id = opaque_ty.opaque_ty_id;
126 let parameters = from_chalk(db, opaque_ty.substitution);
127 TyKind::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id, substitution: parameters }))
128 }
129 chalk_ir::TyKind::Function(chalk_ir::FnPointer {
130 num_binders,
131 sig,
132 substitution,
133 ..
134 }) => {
135 assert_eq!(num_binders, 0);
136 let substs: Substitution = from_chalk(
137 db,
138 substitution.0.shifted_out(&Interner).expect("fn ptr should have no binders"),
139 );
140 TyKind::Function(FnPointer { num_args: (substs.len(&Interner) - 1), sig, substs })
141 }
142 chalk_ir::TyKind::BoundVar(idx) => TyKind::BoundVar(idx),
143 chalk_ir::TyKind::InferenceVar(_iv, _kind) => TyKind::Unknown,
144 chalk_ir::TyKind::Dyn(where_clauses) => {
145 assert_eq!(where_clauses.bounds.binders.len(&Interner), 1);
146 let bounds = where_clauses
147 .bounds
148 .skip_binders()
149 .iter(&Interner)
150 .map(|c| from_chalk(db, c.clone()));
151 TyKind::Dyn(crate::DynTy {
152 bounds: crate::Binders::new(
153 1,
154 crate::QuantifiedWhereClauses::from_iter(&Interner, bounds),
155 ),
156 })
157 }
158
159 chalk_ir::TyKind::Adt(adt_id, subst) => TyKind::Adt(adt_id, from_chalk(db, subst)),
160 chalk_ir::TyKind::AssociatedType(type_id, subst) => {
161 TyKind::AssociatedType(type_id, from_chalk(db, subst))
162 }
163
164 chalk_ir::TyKind::OpaqueType(opaque_type_id, subst) => {
165 TyKind::OpaqueType(opaque_type_id, from_chalk(db, subst))
166 }
167
168 chalk_ir::TyKind::Scalar(scalar) => TyKind::Scalar(scalar),
169 chalk_ir::TyKind::Tuple(cardinality, subst) => {
170 TyKind::Tuple(cardinality, from_chalk(db, subst))
171 }
172 chalk_ir::TyKind::Raw(mutability, ty) => TyKind::Raw(mutability, from_chalk(db, ty)),
173 chalk_ir::TyKind::Slice(ty) => TyKind::Slice(from_chalk(db, ty)),
174 chalk_ir::TyKind::Ref(mutability, _lifetime, ty) => {
175 TyKind::Ref(mutability, from_chalk(db, ty))
176 }
177 chalk_ir::TyKind::Str => TyKind::Str,
178 chalk_ir::TyKind::Never => TyKind::Never,
179
180 chalk_ir::TyKind::FnDef(fn_def_id, subst) => {
181 TyKind::FnDef(fn_def_id, from_chalk(db, subst))
182 }
183
184 chalk_ir::TyKind::Closure(id, subst) => TyKind::Closure(id, from_chalk(db, subst)),
185
186 chalk_ir::TyKind::Foreign(foreign_def_id) => TyKind::ForeignType(foreign_def_id),
187 chalk_ir::TyKind::Generator(_, _) => unimplemented!(), // FIXME
188 chalk_ir::TyKind::GeneratorWitness(_, _) => unimplemented!(), // FIXME
189 }
190 .intern(&Interner)
191 }
192}
193
194/// We currently don't model lifetimes, but Chalk does. So, we have to insert a
195/// fake lifetime here, because Chalks built-in logic may expect it to be there.
196fn ref_to_chalk(
197 db: &dyn HirDatabase,
198 mutability: chalk_ir::Mutability,
199 ty: Ty,
200) -> chalk_ir::Ty<Interner> {
201 let arg = ty.to_chalk(db);
202 let lifetime = LifetimeData::Static.intern(&Interner);
203 chalk_ir::TyKind::Ref(mutability, lifetime, arg).intern(&Interner)
204}
205
206/// We currently don't model constants, but Chalk does. So, we have to insert a
207/// fake constant here, because Chalks built-in logic may expect it to be there.
208fn array_to_chalk(db: &dyn HirDatabase, ty: Ty) -> chalk_ir::Ty<Interner> {
209 let arg = ty.to_chalk(db);
210 let usize_ty = chalk_ir::TyKind::Scalar(Scalar::Uint(UintTy::Usize)).intern(&Interner);
211 let const_ = chalk_ir::ConstData {
212 ty: usize_ty,
213 value: chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: () }),
214 }
215 .intern(&Interner);
216 chalk_ir::TyKind::Array(arg, const_).intern(&Interner)
217}
218
219impl ToChalk for GenericArg {
220 type Chalk = chalk_ir::GenericArg<Interner>;
221
222 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk {
223 match self.interned {
224 crate::GenericArgData::Ty(ty) => ty.to_chalk(db).cast(&Interner),
225 }
226 }
227
228 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self {
229 match chalk.interned() {
230 chalk_ir::GenericArgData::Ty(ty) => Ty::from_chalk(db, ty.clone()).cast(&Interner),
231 chalk_ir::GenericArgData::Lifetime(_) => unimplemented!(),
232 chalk_ir::GenericArgData::Const(_) => unimplemented!(),
233 }
234 }
235}
236
237impl ToChalk for Substitution {
238 type Chalk = chalk_ir::Substitution<Interner>;
239
240 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Substitution<Interner> {
241 chalk_ir::Substitution::from_iter(
242 &Interner,
243 self.iter(&Interner).map(|ty| ty.clone().to_chalk(db)),
244 )
245 }
246
247 fn from_chalk(
248 db: &dyn HirDatabase,
249 parameters: chalk_ir::Substitution<Interner>,
250 ) -> Substitution {
251 let tys = parameters.iter(&Interner).map(|p| from_chalk(db, p.clone())).collect();
252 Substitution(tys)
253 }
254}
255
256impl ToChalk for TraitRef {
257 type Chalk = chalk_ir::TraitRef<Interner>;
258
259 fn to_chalk(self: TraitRef, db: &dyn HirDatabase) -> chalk_ir::TraitRef<Interner> {
260 let trait_id = self.trait_id;
261 let substitution = self.substitution.to_chalk(db);
262 chalk_ir::TraitRef { trait_id, substitution }
263 }
264
265 fn from_chalk(db: &dyn HirDatabase, trait_ref: chalk_ir::TraitRef<Interner>) -> Self {
266 let trait_id = trait_ref.trait_id;
267 let substs = from_chalk(db, trait_ref.substitution);
268 TraitRef { trait_id, substitution: substs }
269 }
270}
271
272impl ToChalk for hir_def::TraitId {
273 type Chalk = TraitId;
274
275 fn to_chalk(self, _db: &dyn HirDatabase) -> TraitId {
276 chalk_ir::TraitId(self.as_intern_id())
277 }
278
279 fn from_chalk(_db: &dyn HirDatabase, trait_id: TraitId) -> hir_def::TraitId {
280 InternKey::from_intern_id(trait_id.0)
281 }
282}
283
284impl ToChalk for hir_def::ImplId {
285 type Chalk = ImplId;
286
287 fn to_chalk(self, _db: &dyn HirDatabase) -> ImplId {
288 chalk_ir::ImplId(self.as_intern_id())
289 }
290
291 fn from_chalk(_db: &dyn HirDatabase, impl_id: ImplId) -> hir_def::ImplId {
292 InternKey::from_intern_id(impl_id.0)
293 }
294}
295
296impl ToChalk for CallableDefId {
297 type Chalk = FnDefId;
298
299 fn to_chalk(self, db: &dyn HirDatabase) -> FnDefId {
300 db.intern_callable_def(self).into()
301 }
302
303 fn from_chalk(db: &dyn HirDatabase, fn_def_id: FnDefId) -> CallableDefId {
304 db.lookup_intern_callable_def(fn_def_id.into())
305 }
306}
307
308pub(crate) struct TypeAliasAsValue(pub(crate) TypeAliasId);
309
310impl ToChalk for TypeAliasAsValue {
311 type Chalk = AssociatedTyValueId;
312
313 fn to_chalk(self, _db: &dyn HirDatabase) -> AssociatedTyValueId {
314 rust_ir::AssociatedTyValueId(self.0.as_intern_id())
315 }
316
317 fn from_chalk(
318 _db: &dyn HirDatabase,
319 assoc_ty_value_id: AssociatedTyValueId,
320 ) -> TypeAliasAsValue {
321 TypeAliasAsValue(TypeAliasId::from_intern_id(assoc_ty_value_id.0))
322 }
323}
324
325impl ToChalk for WhereClause {
326 type Chalk = chalk_ir::WhereClause<Interner>;
327
328 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::WhereClause<Interner> {
329 match self {
330 WhereClause::Implemented(trait_ref) => {
331 chalk_ir::WhereClause::Implemented(trait_ref.to_chalk(db))
332 }
333 WhereClause::AliasEq(alias_eq) => chalk_ir::WhereClause::AliasEq(alias_eq.to_chalk(db)),
334 }
335 }
336
337 fn from_chalk(
338 db: &dyn HirDatabase,
339 where_clause: chalk_ir::WhereClause<Interner>,
340 ) -> WhereClause {
341 match where_clause {
342 chalk_ir::WhereClause::Implemented(tr) => WhereClause::Implemented(from_chalk(db, tr)),
343 chalk_ir::WhereClause::AliasEq(alias_eq) => {
344 WhereClause::AliasEq(from_chalk(db, alias_eq))
345 }
346
347 chalk_ir::WhereClause::LifetimeOutlives(_) => {
348 // we shouldn't get these from Chalk
349 panic!("encountered LifetimeOutlives from Chalk")
350 }
351
352 chalk_ir::WhereClause::TypeOutlives(_) => {
353 // we shouldn't get these from Chalk
354 panic!("encountered TypeOutlives from Chalk")
355 }
356 }
357 }
358}
359
360impl ToChalk for ProjectionTy {
361 type Chalk = chalk_ir::ProjectionTy<Interner>;
362
363 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::ProjectionTy<Interner> {
364 chalk_ir::ProjectionTy {
365 associated_ty_id: self.associated_ty_id,
366 substitution: self.substitution.to_chalk(db),
367 }
368 }
369
370 fn from_chalk(
371 db: &dyn HirDatabase,
372 projection_ty: chalk_ir::ProjectionTy<Interner>,
373 ) -> ProjectionTy {
374 ProjectionTy {
375 associated_ty_id: projection_ty.associated_ty_id,
376 substitution: from_chalk(db, projection_ty.substitution),
377 }
378 }
379}
380impl ToChalk for OpaqueTy {
381 type Chalk = chalk_ir::OpaqueTy<Interner>;
382
383 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk {
384 chalk_ir::OpaqueTy {
385 opaque_ty_id: self.opaque_ty_id,
386 substitution: self.substitution.to_chalk(db),
387 }
388 }
389
390 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self {
391 OpaqueTy {
392 opaque_ty_id: chalk.opaque_ty_id,
393 substitution: from_chalk(db, chalk.substitution),
394 }
395 }
396}
397
398impl ToChalk for AliasTy {
399 type Chalk = chalk_ir::AliasTy<Interner>;
400
401 fn to_chalk(self, db: &dyn HirDatabase) -> Self::Chalk {
402 match self {
403 AliasTy::Projection(projection_ty) => {
404 chalk_ir::AliasTy::Projection(projection_ty.to_chalk(db))
405 }
406 AliasTy::Opaque(opaque_ty) => chalk_ir::AliasTy::Opaque(opaque_ty.to_chalk(db)),
407 }
408 }
409
410 fn from_chalk(db: &dyn HirDatabase, chalk: Self::Chalk) -> Self {
411 match chalk {
412 chalk_ir::AliasTy::Projection(projection_ty) => {
413 AliasTy::Projection(from_chalk(db, projection_ty))
414 }
415 chalk_ir::AliasTy::Opaque(opaque_ty) => AliasTy::Opaque(from_chalk(db, opaque_ty)),
416 }
417 }
418}
419
420impl ToChalk for AliasEq {
421 type Chalk = chalk_ir::AliasEq<Interner>;
422
423 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::AliasEq<Interner> {
424 chalk_ir::AliasEq { alias: self.alias.to_chalk(db), ty: self.ty.to_chalk(db) }
425 }
426
427 fn from_chalk(db: &dyn HirDatabase, alias_eq: chalk_ir::AliasEq<Interner>) -> Self {
428 AliasEq { alias: from_chalk(db, alias_eq.alias), ty: from_chalk(db, alias_eq.ty) }
429 }
430}
431
432impl ToChalk for DomainGoal {
433 type Chalk = chalk_ir::DomainGoal<Interner>;
434
435 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::DomainGoal<Interner> {
436 match self {
437 DomainGoal::Holds(WhereClause::Implemented(tr)) => tr.to_chalk(db).cast(&Interner),
438 DomainGoal::Holds(WhereClause::AliasEq(alias_eq)) => {
439 alias_eq.to_chalk(db).cast(&Interner)
440 }
441 }
442 }
443
444 fn from_chalk(_db: &dyn HirDatabase, _goal: chalk_ir::DomainGoal<Interner>) -> Self {
445 unimplemented!()
446 }
447}
448
449impl<T> ToChalk for Canonical<T>
450where
451 T: ToChalk,
452 T::Chalk: HasInterner<Interner = Interner>,
453{
454 type Chalk = chalk_ir::Canonical<T::Chalk>;
455
456 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Canonical<T::Chalk> {
457 let value = self.value.to_chalk(db);
458 chalk_ir::Canonical { value, binders: self.binders }
459 }
460
461 fn from_chalk(db: &dyn HirDatabase, canonical: chalk_ir::Canonical<T::Chalk>) -> Canonical<T> {
462 Canonical { binders: canonical.binders, value: from_chalk(db, canonical.value) }
463 }
464}
465
466impl<T: ToChalk> ToChalk for InEnvironment<T>
467where
468 T::Chalk: chalk_ir::interner::HasInterner<Interner = Interner>,
469{
470 type Chalk = chalk_ir::InEnvironment<T::Chalk>;
471
472 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::InEnvironment<T::Chalk> {
473 chalk_ir::InEnvironment { environment: self.environment, goal: self.goal.to_chalk(db) }
474 }
475
476 fn from_chalk(
477 _db: &dyn HirDatabase,
478 _in_env: chalk_ir::InEnvironment<T::Chalk>,
479 ) -> InEnvironment<T> {
480 unimplemented!()
481 }
482}
483
484impl<T: ToChalk> ToChalk for crate::Binders<T>
485where
486 T::Chalk: chalk_ir::interner::HasInterner<Interner = Interner>,
487{
488 type Chalk = chalk_ir::Binders<T::Chalk>;
489
490 fn to_chalk(self, db: &dyn HirDatabase) -> chalk_ir::Binders<T::Chalk> {
491 chalk_ir::Binders::new(
492 chalk_ir::VariableKinds::from_iter(
493 &Interner,
494 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
495 .take(self.num_binders),
496 ),
497 self.value.to_chalk(db),
498 )
499 }
500
501 fn from_chalk(db: &dyn HirDatabase, binders: chalk_ir::Binders<T::Chalk>) -> crate::Binders<T> {
502 let (v, b) = binders.into_value_and_skipped_binders();
503 crate::Binders::new(b.len(&Interner), from_chalk(db, v))
504 }
505}
506
507pub(super) fn make_binders<T>(value: T, num_vars: usize) -> chalk_ir::Binders<T>
508where
509 T: HasInterner<Interner = Interner>,
510{
511 chalk_ir::Binders::new(
512 chalk_ir::VariableKinds::from_iter(
513 &Interner,
514 std::iter::repeat(chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General))
515 .take(num_vars),
516 ),
517 value,
518 )
519}
520
521pub(super) fn convert_where_clauses(
522 db: &dyn HirDatabase,
523 def: GenericDefId,
524 substs: &Substitution,
525) -> Vec<chalk_ir::QuantifiedWhereClause<Interner>> {
526 let generic_predicates = db.generic_predicates(def);
527 let mut result = Vec::with_capacity(generic_predicates.len());
528 for pred in generic_predicates.iter() {
529 result.push(pred.clone().subst(substs).to_chalk(db));
530 }
531 result
532}
533
534pub(super) fn generic_predicate_to_inline_bound(
535 db: &dyn HirDatabase,
536 pred: &QuantifiedWhereClause,
537 self_ty: &Ty,
538) -> Option<chalk_ir::Binders<rust_ir::InlineBound<Interner>>> {
539 // An InlineBound is like a GenericPredicate, except the self type is left out.
540 // We don't have a special type for this, but Chalk does.
541 let self_ty_shifted_in = self_ty.clone().shift_bound_vars(DebruijnIndex::ONE);
542 match &pred.value {
543 WhereClause::Implemented(trait_ref) => {
544 if trait_ref.self_type_parameter() != &self_ty_shifted_in {
545 // we can only convert predicates back to type bounds if they
546 // have the expected self type
547 return None;
548 }
549 let args_no_self = trait_ref.substitution.interned(&Interner)[1..]
550 .iter()
551 .map(|ty| ty.clone().to_chalk(db).cast(&Interner))
552 .collect();
553 let trait_bound = rust_ir::TraitBound { trait_id: trait_ref.trait_id, args_no_self };
554 Some(make_binders(rust_ir::InlineBound::TraitBound(trait_bound), pred.num_binders))
555 }
556 WhereClause::AliasEq(AliasEq { alias: AliasTy::Projection(projection_ty), ty }) => {
557 if projection_ty.self_type_parameter() != &self_ty_shifted_in {
558 return None;
559 }
560 let trait_ = projection_ty.trait_(db);
561 let args_no_self = projection_ty.substitution.interned(&Interner)[1..]
562 .iter()
563 .map(|ty| ty.clone().to_chalk(db).cast(&Interner))
564 .collect();
565 let alias_eq_bound = rust_ir::AliasEqBound {
566 value: ty.clone().to_chalk(db),
567 trait_bound: rust_ir::TraitBound { trait_id: trait_.to_chalk(db), args_no_self },
568 associated_ty_id: projection_ty.associated_ty_id,
569 parameters: Vec::new(), // FIXME we don't support generic associated types yet
570 };
571 Some(make_binders(rust_ir::InlineBound::AliasEqBound(alias_eq_bound), pred.num_binders))
572 }
573 _ => None,
574 }
575}
diff --git a/crates/hir_ty/src/traits/chalk/tls.rs b/crates/hir_ty/src/traits/chalk/tls.rs
deleted file mode 100644
index 8892a63a9..000000000
--- a/crates/hir_ty/src/traits/chalk/tls.rs
+++ /dev/null
@@ -1,275 +0,0 @@
1//! Implementation of Chalk debug helper functions using TLS.
2use std::fmt;
3
4use chalk_ir::{AliasTy, GenericArg, Goal, Goals, Lifetime, ProgramClauseImplication};
5use itertools::Itertools;
6
7use super::{from_chalk, Interner};
8use crate::{db::HirDatabase, from_assoc_type_id, CallableDefId};
9use hir_def::{AdtId, AssocContainerId, Lookup, TypeAliasId};
10
11pub(crate) use unsafe_tls::{set_current_program, with_current_program};
12
13pub(crate) struct DebugContext<'a>(&'a dyn HirDatabase);
14
15impl DebugContext<'_> {
16 pub(crate) fn debug_struct_id(
17 &self,
18 id: super::AdtId,
19 f: &mut fmt::Formatter<'_>,
20 ) -> Result<(), fmt::Error> {
21 let name = match id.0 {
22 AdtId::StructId(it) => self.0.struct_data(it).name.clone(),
23 AdtId::UnionId(it) => self.0.union_data(it).name.clone(),
24 AdtId::EnumId(it) => self.0.enum_data(it).name.clone(),
25 };
26 write!(f, "{}", name)
27 }
28
29 pub(crate) fn debug_trait_id(
30 &self,
31 id: super::TraitId,
32 fmt: &mut fmt::Formatter<'_>,
33 ) -> Result<(), fmt::Error> {
34 let trait_: hir_def::TraitId = from_chalk(self.0, id);
35 let trait_data = self.0.trait_data(trait_);
36 write!(fmt, "{}", trait_data.name)
37 }
38
39 pub(crate) fn debug_assoc_type_id(
40 &self,
41 id: super::AssocTypeId,
42 fmt: &mut fmt::Formatter<'_>,
43 ) -> Result<(), fmt::Error> {
44 let type_alias: TypeAliasId = from_assoc_type_id(id);
45 let type_alias_data = self.0.type_alias_data(type_alias);
46 let trait_ = match type_alias.lookup(self.0.upcast()).container {
47 AssocContainerId::TraitId(t) => t,
48 _ => panic!("associated type not in trait"),
49 };
50 let trait_data = self.0.trait_data(trait_);
51 write!(fmt, "{}::{}", trait_data.name, type_alias_data.name)
52 }
53
54 pub(crate) fn debug_opaque_ty_id(
55 &self,
56 opaque_ty_id: chalk_ir::OpaqueTyId<Interner>,
57 fmt: &mut fmt::Formatter<'_>,
58 ) -> Result<(), fmt::Error> {
59 fmt.debug_struct("OpaqueTyId").field("index", &opaque_ty_id.0).finish()
60 }
61
62 pub(crate) fn debug_alias(
63 &self,
64 alias_ty: &AliasTy<Interner>,
65 fmt: &mut fmt::Formatter<'_>,
66 ) -> Result<(), fmt::Error> {
67 match alias_ty {
68 AliasTy::Projection(projection_ty) => self.debug_projection_ty(projection_ty, fmt),
69 AliasTy::Opaque(opaque_ty) => self.debug_opaque_ty(opaque_ty, fmt),
70 }
71 }
72
73 pub(crate) fn debug_projection_ty(
74 &self,
75 projection_ty: &chalk_ir::ProjectionTy<Interner>,
76 fmt: &mut fmt::Formatter<'_>,
77 ) -> Result<(), fmt::Error> {
78 let type_alias = from_assoc_type_id(projection_ty.associated_ty_id);
79 let type_alias_data = self.0.type_alias_data(type_alias);
80 let trait_ = match type_alias.lookup(self.0.upcast()).container {
81 AssocContainerId::TraitId(t) => t,
82 _ => panic!("associated type not in trait"),
83 };
84 let trait_data = self.0.trait_data(trait_);
85 let params = projection_ty.substitution.as_slice(&Interner);
86 write!(fmt, "<{:?} as {}", &params[0], trait_data.name,)?;
87 if params.len() > 1 {
88 write!(
89 fmt,
90 "<{}>",
91 &params[1..].iter().format_with(", ", |x, f| f(&format_args!("{:?}", x))),
92 )?;
93 }
94 write!(fmt, ">::{}", type_alias_data.name)
95 }
96
97 pub(crate) fn debug_opaque_ty(
98 &self,
99 opaque_ty: &chalk_ir::OpaqueTy<Interner>,
100 fmt: &mut fmt::Formatter<'_>,
101 ) -> Result<(), fmt::Error> {
102 write!(fmt, "{:?}", opaque_ty.opaque_ty_id)
103 }
104
105 pub(crate) fn debug_ty(
106 &self,
107 ty: &chalk_ir::Ty<Interner>,
108 fmt: &mut fmt::Formatter<'_>,
109 ) -> Result<(), fmt::Error> {
110 write!(fmt, "{:?}", ty.data(&Interner))
111 }
112
113 pub(crate) fn debug_lifetime(
114 &self,
115 lifetime: &Lifetime<Interner>,
116 fmt: &mut fmt::Formatter<'_>,
117 ) -> Result<(), fmt::Error> {
118 write!(fmt, "{:?}", lifetime.data(&Interner))
119 }
120
121 pub(crate) fn debug_generic_arg(
122 &self,
123 parameter: &GenericArg<Interner>,
124 fmt: &mut fmt::Formatter<'_>,
125 ) -> Result<(), fmt::Error> {
126 write!(fmt, "{:?}", parameter.data(&Interner).inner_debug())
127 }
128
129 pub(crate) fn debug_goal(
130 &self,
131 goal: &Goal<Interner>,
132 fmt: &mut fmt::Formatter<'_>,
133 ) -> Result<(), fmt::Error> {
134 let goal_data = goal.data(&Interner);
135 write!(fmt, "{:?}", goal_data)
136 }
137
138 pub(crate) fn debug_goals(
139 &self,
140 goals: &Goals<Interner>,
141 fmt: &mut fmt::Formatter<'_>,
142 ) -> Result<(), fmt::Error> {
143 write!(fmt, "{:?}", goals.debug(&Interner))
144 }
145
146 pub(crate) fn debug_program_clause_implication(
147 &self,
148 pci: &ProgramClauseImplication<Interner>,
149 fmt: &mut fmt::Formatter<'_>,
150 ) -> Result<(), fmt::Error> {
151 write!(fmt, "{:?}", pci.debug(&Interner))
152 }
153
154 pub(crate) fn debug_substitution(
155 &self,
156 substitution: &chalk_ir::Substitution<Interner>,
157 fmt: &mut fmt::Formatter<'_>,
158 ) -> Result<(), fmt::Error> {
159 write!(fmt, "{:?}", substitution.debug(&Interner))
160 }
161
162 pub(crate) fn debug_separator_trait_ref(
163 &self,
164 separator_trait_ref: &chalk_ir::SeparatorTraitRef<Interner>,
165 fmt: &mut fmt::Formatter<'_>,
166 ) -> Result<(), fmt::Error> {
167 write!(fmt, "{:?}", separator_trait_ref.debug(&Interner))
168 }
169
170 pub(crate) fn debug_fn_def_id(
171 &self,
172 fn_def_id: chalk_ir::FnDefId<Interner>,
173 fmt: &mut fmt::Formatter<'_>,
174 ) -> Result<(), fmt::Error> {
175 let def: CallableDefId = from_chalk(self.0, fn_def_id);
176 let name = match def {
177 CallableDefId::FunctionId(ff) => self.0.function_data(ff).name.clone(),
178 CallableDefId::StructId(s) => self.0.struct_data(s).name.clone(),
179 CallableDefId::EnumVariantId(e) => {
180 let enum_data = self.0.enum_data(e.parent);
181 enum_data.variants[e.local_id].name.clone()
182 }
183 };
184 match def {
185 CallableDefId::FunctionId(_) => write!(fmt, "{{fn {}}}", name),
186 CallableDefId::StructId(_) | CallableDefId::EnumVariantId(_) => {
187 write!(fmt, "{{ctor {}}}", name)
188 }
189 }
190 }
191
192 pub(crate) fn debug_const(
193 &self,
194 _constant: &chalk_ir::Const<Interner>,
195 fmt: &mut fmt::Formatter<'_>,
196 ) -> fmt::Result {
197 write!(fmt, "const")
198 }
199
200 pub(crate) fn debug_variable_kinds(
201 &self,
202 variable_kinds: &chalk_ir::VariableKinds<Interner>,
203 fmt: &mut fmt::Formatter<'_>,
204 ) -> fmt::Result {
205 write!(fmt, "{:?}", variable_kinds.as_slice(&Interner))
206 }
207 pub(crate) fn debug_variable_kinds_with_angles(
208 &self,
209 variable_kinds: &chalk_ir::VariableKinds<Interner>,
210 fmt: &mut fmt::Formatter<'_>,
211 ) -> fmt::Result {
212 write!(fmt, "{:?}", variable_kinds.inner_debug(&Interner))
213 }
214 pub(crate) fn debug_canonical_var_kinds(
215 &self,
216 canonical_var_kinds: &chalk_ir::CanonicalVarKinds<Interner>,
217 fmt: &mut fmt::Formatter<'_>,
218 ) -> fmt::Result {
219 write!(fmt, "{:?}", canonical_var_kinds.as_slice(&Interner))
220 }
221 pub(crate) fn debug_program_clause(
222 &self,
223 clause: &chalk_ir::ProgramClause<Interner>,
224 fmt: &mut fmt::Formatter<'_>,
225 ) -> fmt::Result {
226 write!(fmt, "{:?}", clause.data(&Interner))
227 }
228 pub(crate) fn debug_program_clauses(
229 &self,
230 clauses: &chalk_ir::ProgramClauses<Interner>,
231 fmt: &mut fmt::Formatter<'_>,
232 ) -> fmt::Result {
233 write!(fmt, "{:?}", clauses.as_slice(&Interner))
234 }
235 pub(crate) fn debug_quantified_where_clauses(
236 &self,
237 clauses: &chalk_ir::QuantifiedWhereClauses<Interner>,
238 fmt: &mut fmt::Formatter<'_>,
239 ) -> fmt::Result {
240 write!(fmt, "{:?}", clauses.as_slice(&Interner))
241 }
242}
243
244mod unsafe_tls {
245 use super::DebugContext;
246 use crate::db::HirDatabase;
247 use scoped_tls::scoped_thread_local;
248
249 scoped_thread_local!(static PROGRAM: DebugContext);
250
251 pub(crate) fn with_current_program<R>(
252 op: impl for<'a> FnOnce(Option<&'a DebugContext<'a>>) -> R,
253 ) -> R {
254 if PROGRAM.is_set() {
255 PROGRAM.with(|prog| op(Some(prog)))
256 } else {
257 op(None)
258 }
259 }
260
261 pub(crate) fn set_current_program<OP, R>(p: &dyn HirDatabase, op: OP) -> R
262 where
263 OP: FnOnce() -> R,
264 {
265 let ctx = DebugContext(p);
266 // we're transmuting the lifetime in the DebugContext to static. This is
267 // fine because we only keep the reference for the lifetime of this
268 // function, *and* the only way to access the context is through
269 // `with_current_program`, which hides the lifetime through the `for`
270 // type.
271 let static_p: &DebugContext<'static> =
272 unsafe { std::mem::transmute::<&DebugContext, &DebugContext<'static>>(&ctx) };
273 PROGRAM.set(static_p, || op())
274 }
275}