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