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