]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_traits/src/chalk/db.rs
Rollup merge of #93412 - fee1-dead:improve-rustdoc-const-bounds, r=GuillaumeGomez
[rust.git] / compiler / rustc_traits / src / chalk / db.rs
1 //! Provides the `RustIrDatabase` implementation for `chalk-solve`
2 //!
3 //! The purpose of the `chalk_solve::RustIrDatabase` is to get data about
4 //! specific types, such as bounds, where clauses, or fields. This file contains
5 //! the minimal logic to assemble the types for `chalk-solve` by calling out to
6 //! either the `TyCtxt` (for information about types) or
7 //! `crate::chalk::lowering` (to lower rustc types into Chalk types).
8
9 use rustc_middle::traits::ChalkRustInterner as RustInterner;
10 use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef};
11 use rustc_middle::ty::{self, AssocItemContainer, AssocKind, Ty, TyCtxt, TypeFoldable};
12
13 use rustc_ast::ast;
14 use rustc_attr as attr;
15
16 use rustc_hir::def_id::DefId;
17
18 use rustc_span::symbol::sym;
19
20 use std::fmt;
21 use std::sync::Arc;
22
23 use crate::chalk::lowering::LowerInto;
24
25 pub struct RustIrDatabase<'tcx> {
26     pub(crate) interner: RustInterner<'tcx>,
27 }
28
29 impl fmt::Debug for RustIrDatabase<'_> {
30     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31         write!(f, "RustIrDatabase")
32     }
33 }
34
35 impl<'tcx> RustIrDatabase<'tcx> {
36     fn where_clauses_for(
37         &self,
38         def_id: DefId,
39         bound_vars: SubstsRef<'tcx>,
40     ) -> Vec<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>> {
41         let predicates = self.interner.tcx.predicates_defined_on(def_id).predicates;
42         predicates
43             .iter()
44             .map(|(wc, _)| wc.subst(self.interner.tcx, bound_vars))
45             .filter_map(|wc| LowerInto::<
46                     Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>
47                     >::lower_into(wc, self.interner)).collect()
48     }
49
50     fn bounds_for<T>(&self, def_id: DefId, bound_vars: SubstsRef<'tcx>) -> Vec<T>
51     where
52         ty::Predicate<'tcx>: LowerInto<'tcx, std::option::Option<T>>,
53     {
54         self.interner
55             .tcx
56             .explicit_item_bounds(def_id)
57             .iter()
58             .map(|(bound, _)| bound.subst(self.interner.tcx, &bound_vars))
59             .filter_map(|bound| LowerInto::<Option<_>>::lower_into(bound, self.interner))
60             .collect()
61     }
62 }
63
64 impl<'tcx> chalk_solve::RustIrDatabase<RustInterner<'tcx>> for RustIrDatabase<'tcx> {
65     fn interner(&self) -> RustInterner<'tcx> {
66         self.interner
67     }
68
69     fn associated_ty_data(
70         &self,
71         assoc_type_id: chalk_ir::AssocTypeId<RustInterner<'tcx>>,
72     ) -> Arc<chalk_solve::rust_ir::AssociatedTyDatum<RustInterner<'tcx>>> {
73         let def_id = assoc_type_id.0;
74         let assoc_item = self.interner.tcx.associated_item(def_id);
75         let AssocItemContainer::TraitContainer(trait_def_id) = assoc_item.container else {
76             unimplemented!("Not possible??");
77         };
78         match assoc_item.kind {
79             AssocKind::Type => {}
80             _ => unimplemented!("Not possible??"),
81         }
82         let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
83         let binders = binders_for(self.interner, bound_vars);
84
85         let where_clauses = self.where_clauses_for(def_id, bound_vars);
86         let bounds = self.bounds_for(def_id, bound_vars);
87
88         Arc::new(chalk_solve::rust_ir::AssociatedTyDatum {
89             trait_id: chalk_ir::TraitId(trait_def_id),
90             id: assoc_type_id,
91             name: (),
92             binders: chalk_ir::Binders::new(
93                 binders,
94                 chalk_solve::rust_ir::AssociatedTyDatumBound { bounds, where_clauses },
95             ),
96         })
97     }
98
99     fn trait_datum(
100         &self,
101         trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
102     ) -> Arc<chalk_solve::rust_ir::TraitDatum<RustInterner<'tcx>>> {
103         let def_id = trait_id.0;
104         let trait_def = self.interner.tcx.trait_def(def_id);
105
106         let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
107         let binders = binders_for(self.interner, bound_vars);
108
109         let where_clauses = self.where_clauses_for(def_id, bound_vars);
110
111         let associated_ty_ids: Vec<_> = self
112             .interner
113             .tcx
114             .associated_items(def_id)
115             .in_definition_order()
116             .filter(|i| i.kind == AssocKind::Type)
117             .map(|i| chalk_ir::AssocTypeId(i.def_id))
118             .collect();
119
120         let lang_items = self.interner.tcx.lang_items();
121         let well_known = if lang_items.sized_trait() == Some(def_id) {
122             Some(chalk_solve::rust_ir::WellKnownTrait::Sized)
123         } else if lang_items.copy_trait() == Some(def_id) {
124             Some(chalk_solve::rust_ir::WellKnownTrait::Copy)
125         } else if lang_items.clone_trait() == Some(def_id) {
126             Some(chalk_solve::rust_ir::WellKnownTrait::Clone)
127         } else if lang_items.drop_trait() == Some(def_id) {
128             Some(chalk_solve::rust_ir::WellKnownTrait::Drop)
129         } else if lang_items.fn_trait() == Some(def_id) {
130             Some(chalk_solve::rust_ir::WellKnownTrait::Fn)
131         } else if lang_items.fn_once_trait() == Some(def_id) {
132             Some(chalk_solve::rust_ir::WellKnownTrait::FnOnce)
133         } else if lang_items.fn_mut_trait() == Some(def_id) {
134             Some(chalk_solve::rust_ir::WellKnownTrait::FnMut)
135         } else if lang_items.unsize_trait() == Some(def_id) {
136             Some(chalk_solve::rust_ir::WellKnownTrait::Unsize)
137         } else if lang_items.unpin_trait() == Some(def_id) {
138             Some(chalk_solve::rust_ir::WellKnownTrait::Unpin)
139         } else if lang_items.coerce_unsized_trait() == Some(def_id) {
140             Some(chalk_solve::rust_ir::WellKnownTrait::CoerceUnsized)
141         } else {
142             None
143         };
144         Arc::new(chalk_solve::rust_ir::TraitDatum {
145             id: trait_id,
146             binders: chalk_ir::Binders::new(
147                 binders,
148                 chalk_solve::rust_ir::TraitDatumBound { where_clauses },
149             ),
150             flags: chalk_solve::rust_ir::TraitFlags {
151                 auto: trait_def.has_auto_impl,
152                 marker: trait_def.is_marker,
153                 upstream: !def_id.is_local(),
154                 fundamental: self.interner.tcx.has_attr(def_id, sym::fundamental),
155                 non_enumerable: true,
156                 coinductive: false,
157             },
158             associated_ty_ids,
159             well_known,
160         })
161     }
162
163     fn adt_datum(
164         &self,
165         adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
166     ) -> Arc<chalk_solve::rust_ir::AdtDatum<RustInterner<'tcx>>> {
167         let adt_def = adt_id.0;
168
169         let bound_vars = bound_vars_for_item(self.interner.tcx, adt_def.did);
170         let binders = binders_for(self.interner, bound_vars);
171
172         let where_clauses = self.where_clauses_for(adt_def.did, bound_vars);
173
174         let variants: Vec<_> = adt_def
175             .variants
176             .iter()
177             .map(|variant| chalk_solve::rust_ir::AdtVariantDatum {
178                 fields: variant
179                     .fields
180                     .iter()
181                     .map(|field| field.ty(self.interner.tcx, bound_vars).lower_into(self.interner))
182                     .collect(),
183             })
184             .collect();
185         Arc::new(chalk_solve::rust_ir::AdtDatum {
186             id: adt_id,
187             binders: chalk_ir::Binders::new(
188                 binders,
189                 chalk_solve::rust_ir::AdtDatumBound { variants, where_clauses },
190             ),
191             flags: chalk_solve::rust_ir::AdtFlags {
192                 upstream: !adt_def.did.is_local(),
193                 fundamental: adt_def.is_fundamental(),
194                 phantom_data: adt_def.is_phantom_data(),
195             },
196             kind: match adt_def.adt_kind() {
197                 ty::AdtKind::Struct => chalk_solve::rust_ir::AdtKind::Struct,
198                 ty::AdtKind::Union => chalk_solve::rust_ir::AdtKind::Union,
199                 ty::AdtKind::Enum => chalk_solve::rust_ir::AdtKind::Enum,
200             },
201         })
202     }
203
204     fn adt_repr(
205         &self,
206         adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
207     ) -> Arc<chalk_solve::rust_ir::AdtRepr<RustInterner<'tcx>>> {
208         let adt_def = adt_id.0;
209         let int = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Int(i)).intern(self.interner);
210         let uint = |i| chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Uint(i)).intern(self.interner);
211         Arc::new(chalk_solve::rust_ir::AdtRepr {
212             c: adt_def.repr.c(),
213             packed: adt_def.repr.packed(),
214             int: adt_def.repr.int.map(|i| match i {
215                 attr::IntType::SignedInt(ty) => match ty {
216                     ast::IntTy::Isize => int(chalk_ir::IntTy::Isize),
217                     ast::IntTy::I8 => int(chalk_ir::IntTy::I8),
218                     ast::IntTy::I16 => int(chalk_ir::IntTy::I16),
219                     ast::IntTy::I32 => int(chalk_ir::IntTy::I32),
220                     ast::IntTy::I64 => int(chalk_ir::IntTy::I64),
221                     ast::IntTy::I128 => int(chalk_ir::IntTy::I128),
222                 },
223                 attr::IntType::UnsignedInt(ty) => match ty {
224                     ast::UintTy::Usize => uint(chalk_ir::UintTy::Usize),
225                     ast::UintTy::U8 => uint(chalk_ir::UintTy::U8),
226                     ast::UintTy::U16 => uint(chalk_ir::UintTy::U16),
227                     ast::UintTy::U32 => uint(chalk_ir::UintTy::U32),
228                     ast::UintTy::U64 => uint(chalk_ir::UintTy::U64),
229                     ast::UintTy::U128 => uint(chalk_ir::UintTy::U128),
230                 },
231             }),
232         })
233     }
234
235     fn fn_def_datum(
236         &self,
237         fn_def_id: chalk_ir::FnDefId<RustInterner<'tcx>>,
238     ) -> Arc<chalk_solve::rust_ir::FnDefDatum<RustInterner<'tcx>>> {
239         let def_id = fn_def_id.0;
240         let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
241         let binders = binders_for(self.interner, bound_vars);
242
243         let where_clauses = self.where_clauses_for(def_id, bound_vars);
244
245         let sig = self.interner.tcx.fn_sig(def_id);
246         let (inputs_and_output, iobinders, _) = crate::chalk::lowering::collect_bound_vars(
247             self.interner,
248             self.interner.tcx,
249             sig.inputs_and_output().subst(self.interner.tcx, bound_vars),
250         );
251
252         let argument_types = inputs_and_output[..inputs_and_output.len() - 1]
253             .iter()
254             .map(|t| t.subst(self.interner.tcx, &bound_vars).lower_into(self.interner))
255             .collect();
256
257         let return_type = inputs_and_output[inputs_and_output.len() - 1]
258             .subst(self.interner.tcx, &bound_vars)
259             .lower_into(self.interner);
260
261         let bound = chalk_solve::rust_ir::FnDefDatumBound {
262             inputs_and_output: chalk_ir::Binders::new(
263                 iobinders,
264                 chalk_solve::rust_ir::FnDefInputsAndOutputDatum { argument_types, return_type },
265             ),
266             where_clauses,
267         };
268         Arc::new(chalk_solve::rust_ir::FnDefDatum {
269             id: fn_def_id,
270             sig: sig.lower_into(self.interner),
271             binders: chalk_ir::Binders::new(binders, bound),
272         })
273     }
274
275     fn impl_datum(
276         &self,
277         impl_id: chalk_ir::ImplId<RustInterner<'tcx>>,
278     ) -> Arc<chalk_solve::rust_ir::ImplDatum<RustInterner<'tcx>>> {
279         let def_id = impl_id.0;
280         let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
281         let binders = binders_for(self.interner, bound_vars);
282
283         let trait_ref = self.interner.tcx.impl_trait_ref(def_id).expect("not an impl");
284         let trait_ref = trait_ref.subst(self.interner.tcx, bound_vars);
285
286         let where_clauses = self.where_clauses_for(def_id, bound_vars);
287
288         let value = chalk_solve::rust_ir::ImplDatumBound {
289             trait_ref: trait_ref.lower_into(self.interner),
290             where_clauses,
291         };
292
293         let associated_ty_value_ids: Vec<_> = self
294             .interner
295             .tcx
296             .associated_items(def_id)
297             .in_definition_order()
298             .filter(|i| i.kind == AssocKind::Type)
299             .map(|i| chalk_solve::rust_ir::AssociatedTyValueId(i.def_id))
300             .collect();
301
302         Arc::new(chalk_solve::rust_ir::ImplDatum {
303             polarity: self.interner.tcx.impl_polarity(def_id).lower_into(self.interner),
304             binders: chalk_ir::Binders::new(binders, value),
305             impl_type: chalk_solve::rust_ir::ImplType::Local,
306             associated_ty_value_ids,
307         })
308     }
309
310     fn impls_for_trait(
311         &self,
312         trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
313         parameters: &[chalk_ir::GenericArg<RustInterner<'tcx>>],
314         _binders: &chalk_ir::CanonicalVarKinds<RustInterner<'tcx>>,
315     ) -> Vec<chalk_ir::ImplId<RustInterner<'tcx>>> {
316         let def_id = trait_id.0;
317
318         // FIXME(chalk): use TraitDef::for_each_relevant_impl, but that will
319         // require us to be able to interconvert `Ty<'tcx>`, and we're
320         // not there yet.
321
322         let all_impls = self.interner.tcx.all_impls(def_id);
323         let matched_impls = all_impls.filter(|impl_def_id| {
324             use chalk_ir::could_match::CouldMatch;
325             let trait_ref = self.interner.tcx.impl_trait_ref(*impl_def_id).unwrap();
326             let bound_vars = bound_vars_for_item(self.interner.tcx, *impl_def_id);
327
328             let self_ty = trait_ref.self_ty();
329             let self_ty = self_ty.subst(self.interner.tcx, bound_vars);
330             let lowered_ty = self_ty.lower_into(self.interner);
331
332             parameters[0].assert_ty_ref(self.interner).could_match(
333                 self.interner,
334                 self.unification_database(),
335                 &lowered_ty,
336             )
337         });
338
339         let impls = matched_impls.map(chalk_ir::ImplId).collect();
340         impls
341     }
342
343     fn impl_provided_for(
344         &self,
345         auto_trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
346         chalk_ty: &chalk_ir::TyKind<RustInterner<'tcx>>,
347     ) -> bool {
348         use chalk_ir::Scalar::*;
349         use chalk_ir::TyKind::*;
350
351         let trait_def_id = auto_trait_id.0;
352         let all_impls = self.interner.tcx.all_impls(trait_def_id);
353         for impl_def_id in all_impls {
354             let trait_ref = self.interner.tcx.impl_trait_ref(impl_def_id).unwrap();
355             let self_ty = trait_ref.self_ty();
356             let provides = match (self_ty.kind(), chalk_ty) {
357                 (&ty::Adt(impl_adt_def, ..), Adt(id, ..)) => impl_adt_def.did == id.0.did,
358                 (_, AssociatedType(_ty_id, ..)) => {
359                     // FIXME(chalk): See https://github.com/rust-lang/rust/pull/77152#discussion_r494484774
360                     false
361                 }
362                 (ty::Bool, Scalar(Bool)) => true,
363                 (ty::Char, Scalar(Char)) => true,
364                 (ty::Int(ty1), Scalar(Int(ty2))) => matches!(
365                     (ty1, ty2),
366                     (ty::IntTy::Isize, chalk_ir::IntTy::Isize)
367                         | (ty::IntTy::I8, chalk_ir::IntTy::I8)
368                         | (ty::IntTy::I16, chalk_ir::IntTy::I16)
369                         | (ty::IntTy::I32, chalk_ir::IntTy::I32)
370                         | (ty::IntTy::I64, chalk_ir::IntTy::I64)
371                         | (ty::IntTy::I128, chalk_ir::IntTy::I128)
372                 ),
373                 (ty::Uint(ty1), Scalar(Uint(ty2))) => matches!(
374                     (ty1, ty2),
375                     (ty::UintTy::Usize, chalk_ir::UintTy::Usize)
376                         | (ty::UintTy::U8, chalk_ir::UintTy::U8)
377                         | (ty::UintTy::U16, chalk_ir::UintTy::U16)
378                         | (ty::UintTy::U32, chalk_ir::UintTy::U32)
379                         | (ty::UintTy::U64, chalk_ir::UintTy::U64)
380                         | (ty::UintTy::U128, chalk_ir::UintTy::U128)
381                 ),
382                 (ty::Float(ty1), Scalar(Float(ty2))) => matches!(
383                     (ty1, ty2),
384                     (ty::FloatTy::F32, chalk_ir::FloatTy::F32)
385                         | (ty::FloatTy::F64, chalk_ir::FloatTy::F64)
386                 ),
387                 (&ty::Tuple(substs), Tuple(len, _)) => substs.len() == *len,
388                 (&ty::Array(..), Array(..)) => true,
389                 (&ty::Slice(..), Slice(..)) => true,
390                 (&ty::RawPtr(type_and_mut), Raw(mutability, _)) => {
391                     match (type_and_mut.mutbl, mutability) {
392                         (ast::Mutability::Mut, chalk_ir::Mutability::Mut) => true,
393                         (ast::Mutability::Mut, chalk_ir::Mutability::Not) => false,
394                         (ast::Mutability::Not, chalk_ir::Mutability::Mut) => false,
395                         (ast::Mutability::Not, chalk_ir::Mutability::Not) => true,
396                     }
397                 }
398                 (&ty::Ref(.., mutability1), Ref(mutability2, ..)) => {
399                     match (mutability1, mutability2) {
400                         (ast::Mutability::Mut, chalk_ir::Mutability::Mut) => true,
401                         (ast::Mutability::Mut, chalk_ir::Mutability::Not) => false,
402                         (ast::Mutability::Not, chalk_ir::Mutability::Mut) => false,
403                         (ast::Mutability::Not, chalk_ir::Mutability::Not) => true,
404                     }
405                 }
406                 (&ty::Opaque(def_id, ..), OpaqueType(opaque_ty_id, ..)) => def_id == opaque_ty_id.0,
407                 (&ty::FnDef(def_id, ..), FnDef(fn_def_id, ..)) => def_id == fn_def_id.0,
408                 (&ty::Str, Str) => true,
409                 (&ty::Never, Never) => true,
410                 (&ty::Closure(def_id, ..), Closure(closure_id, _)) => def_id == closure_id.0,
411                 (&ty::Foreign(def_id), Foreign(foreign_def_id)) => def_id == foreign_def_id.0,
412                 (&ty::Error(..), Error) => false,
413                 _ => false,
414             };
415             if provides {
416                 return true;
417             }
418         }
419         false
420     }
421
422     fn associated_ty_value(
423         &self,
424         associated_ty_id: chalk_solve::rust_ir::AssociatedTyValueId<RustInterner<'tcx>>,
425     ) -> Arc<chalk_solve::rust_ir::AssociatedTyValue<RustInterner<'tcx>>> {
426         let def_id = associated_ty_id.0;
427         let assoc_item = self.interner.tcx.associated_item(def_id);
428         let impl_id = assoc_item.container.id();
429         match assoc_item.kind {
430             AssocKind::Type => {}
431             _ => unimplemented!("Not possible??"),
432         }
433
434         let trait_item_id = assoc_item.trait_item_def_id.expect("assoc_ty with no trait version");
435         let bound_vars = bound_vars_for_item(self.interner.tcx, def_id);
436         let binders = binders_for(self.interner, bound_vars);
437         let ty = self
438             .interner
439             .tcx
440             .type_of(def_id)
441             .subst(self.interner.tcx, bound_vars)
442             .lower_into(self.interner);
443
444         Arc::new(chalk_solve::rust_ir::AssociatedTyValue {
445             impl_id: chalk_ir::ImplId(impl_id),
446             associated_ty_id: chalk_ir::AssocTypeId(trait_item_id),
447             value: chalk_ir::Binders::new(
448                 binders,
449                 chalk_solve::rust_ir::AssociatedTyValueBound { ty },
450             ),
451         })
452     }
453
454     fn custom_clauses(&self) -> Vec<chalk_ir::ProgramClause<RustInterner<'tcx>>> {
455         vec![]
456     }
457
458     fn local_impls_to_coherence_check(
459         &self,
460         _trait_id: chalk_ir::TraitId<RustInterner<'tcx>>,
461     ) -> Vec<chalk_ir::ImplId<RustInterner<'tcx>>> {
462         unimplemented!()
463     }
464
465     fn opaque_ty_data(
466         &self,
467         opaque_ty_id: chalk_ir::OpaqueTyId<RustInterner<'tcx>>,
468     ) -> Arc<chalk_solve::rust_ir::OpaqueTyDatum<RustInterner<'tcx>>> {
469         let bound_vars = ty::fold::shift_vars(
470             self.interner.tcx,
471             bound_vars_for_item(self.interner.tcx, opaque_ty_id.0),
472             1,
473         );
474         let where_clauses = self.where_clauses_for(opaque_ty_id.0, bound_vars);
475
476         let identity_substs = InternalSubsts::identity_for_item(self.interner.tcx, opaque_ty_id.0);
477
478         let bounds =
479             self.interner
480                 .tcx
481                 .explicit_item_bounds(opaque_ty_id.0)
482                 .iter()
483                 .map(|(bound, _)| bound.subst(self.interner.tcx, &bound_vars))
484                 .map(|bound| {
485                     bound.fold_with(&mut ReplaceOpaqueTyFolder {
486                         tcx: self.interner.tcx,
487                         opaque_ty_id,
488                         identity_substs,
489                         binder_index: ty::INNERMOST,
490                     })
491                 })
492                 .filter_map(|bound| {
493                     LowerInto::<
494                     Option<chalk_ir::QuantifiedWhereClause<RustInterner<'tcx>>>
495                 >::lower_into(bound, self.interner)
496                 })
497                 .collect();
498
499         // Binder for the bound variable representing the concrete impl Trait type.
500         let existential_binder = chalk_ir::VariableKinds::from1(
501             self.interner,
502             chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General),
503         );
504
505         let value = chalk_solve::rust_ir::OpaqueTyDatumBound {
506             bounds: chalk_ir::Binders::new(existential_binder.clone(), bounds),
507             where_clauses: chalk_ir::Binders::new(existential_binder, where_clauses),
508         };
509
510         let binders = binders_for(self.interner, bound_vars);
511         Arc::new(chalk_solve::rust_ir::OpaqueTyDatum {
512             opaque_ty_id,
513             bound: chalk_ir::Binders::new(binders, value),
514         })
515     }
516
517     fn program_clauses_for_env(
518         &self,
519         environment: &chalk_ir::Environment<RustInterner<'tcx>>,
520     ) -> chalk_ir::ProgramClauses<RustInterner<'tcx>> {
521         chalk_solve::program_clauses_for_env(self, environment)
522     }
523
524     fn well_known_trait_id(
525         &self,
526         well_known_trait: chalk_solve::rust_ir::WellKnownTrait,
527     ) -> Option<chalk_ir::TraitId<RustInterner<'tcx>>> {
528         use chalk_solve::rust_ir::WellKnownTrait::*;
529         let lang_items = self.interner.tcx.lang_items();
530         let def_id = match well_known_trait {
531             Sized => lang_items.sized_trait(),
532             Copy => lang_items.copy_trait(),
533             Clone => lang_items.clone_trait(),
534             Drop => lang_items.drop_trait(),
535             Fn => lang_items.fn_trait(),
536             FnMut => lang_items.fn_mut_trait(),
537             FnOnce => lang_items.fn_once_trait(),
538             Generator => lang_items.gen_trait(),
539             Unsize => lang_items.unsize_trait(),
540             Unpin => lang_items.unpin_trait(),
541             CoerceUnsized => lang_items.coerce_unsized_trait(),
542             DiscriminantKind => lang_items.discriminant_kind_trait(),
543         };
544         def_id.map(chalk_ir::TraitId)
545     }
546
547     fn is_object_safe(&self, trait_id: chalk_ir::TraitId<RustInterner<'tcx>>) -> bool {
548         self.interner.tcx.is_object_safe(trait_id.0)
549     }
550
551     fn hidden_opaque_type(
552         &self,
553         _id: chalk_ir::OpaqueTyId<RustInterner<'tcx>>,
554     ) -> chalk_ir::Ty<RustInterner<'tcx>> {
555         // FIXME(chalk): actually get hidden ty
556         self.interner
557             .tcx
558             .mk_ty(ty::Tuple(self.interner.tcx.intern_type_list(&[])))
559             .lower_into(self.interner)
560     }
561
562     fn closure_kind(
563         &self,
564         _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
565         substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
566     ) -> chalk_solve::rust_ir::ClosureKind {
567         let kind = &substs.as_slice(self.interner)[substs.len(self.interner) - 3];
568         match kind.assert_ty_ref(self.interner).kind(self.interner) {
569             chalk_ir::TyKind::Scalar(chalk_ir::Scalar::Int(int_ty)) => match int_ty {
570                 chalk_ir::IntTy::I8 => chalk_solve::rust_ir::ClosureKind::Fn,
571                 chalk_ir::IntTy::I16 => chalk_solve::rust_ir::ClosureKind::FnMut,
572                 chalk_ir::IntTy::I32 => chalk_solve::rust_ir::ClosureKind::FnOnce,
573                 _ => bug!("bad closure kind"),
574             },
575             _ => bug!("bad closure kind"),
576         }
577     }
578
579     fn closure_inputs_and_output(
580         &self,
581         _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
582         substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
583     ) -> chalk_ir::Binders<chalk_solve::rust_ir::FnDefInputsAndOutputDatum<RustInterner<'tcx>>>
584     {
585         let sig = &substs.as_slice(self.interner)[substs.len(self.interner) - 2];
586         match sig.assert_ty_ref(self.interner).kind(self.interner) {
587             chalk_ir::TyKind::Function(f) => {
588                 let substitution = f.substitution.0.as_slice(self.interner);
589                 let return_type = substitution.last().unwrap().assert_ty_ref(self.interner).clone();
590                 // Closure arguments are tupled
591                 let argument_tuple = substitution[0].assert_ty_ref(self.interner);
592                 let argument_types = match argument_tuple.kind(self.interner) {
593                     chalk_ir::TyKind::Tuple(_len, substitution) => substitution
594                         .iter(self.interner)
595                         .map(|arg| arg.assert_ty_ref(self.interner))
596                         .cloned()
597                         .collect(),
598                     _ => bug!("Expecting closure FnSig args to be tupled."),
599                 };
600
601                 chalk_ir::Binders::new(
602                     chalk_ir::VariableKinds::from_iter(
603                         self.interner,
604                         (0..f.num_binders).map(|_| chalk_ir::VariableKind::Lifetime),
605                     ),
606                     chalk_solve::rust_ir::FnDefInputsAndOutputDatum { argument_types, return_type },
607                 )
608             }
609             _ => panic!("Invalid sig."),
610         }
611     }
612
613     fn closure_upvars(
614         &self,
615         _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
616         substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
617     ) -> chalk_ir::Binders<chalk_ir::Ty<RustInterner<'tcx>>> {
618         let inputs_and_output = self.closure_inputs_and_output(_closure_id, substs);
619         let tuple = substs.as_slice(self.interner).last().unwrap().assert_ty_ref(self.interner);
620         inputs_and_output.map_ref(|_| tuple.clone())
621     }
622
623     fn closure_fn_substitution(
624         &self,
625         _closure_id: chalk_ir::ClosureId<RustInterner<'tcx>>,
626         substs: &chalk_ir::Substitution<RustInterner<'tcx>>,
627     ) -> chalk_ir::Substitution<RustInterner<'tcx>> {
628         let substitution = &substs.as_slice(self.interner)[0..substs.len(self.interner) - 3];
629         chalk_ir::Substitution::from_iter(self.interner, substitution)
630     }
631
632     fn generator_datum(
633         &self,
634         _generator_id: chalk_ir::GeneratorId<RustInterner<'tcx>>,
635     ) -> Arc<chalk_solve::rust_ir::GeneratorDatum<RustInterner<'tcx>>> {
636         unimplemented!()
637     }
638
639     fn generator_witness_datum(
640         &self,
641         _generator_id: chalk_ir::GeneratorId<RustInterner<'tcx>>,
642     ) -> Arc<chalk_solve::rust_ir::GeneratorWitnessDatum<RustInterner<'tcx>>> {
643         unimplemented!()
644     }
645
646     fn unification_database(&self) -> &dyn chalk_ir::UnificationDatabase<RustInterner<'tcx>> {
647         self
648     }
649
650     fn discriminant_type(
651         &self,
652         _: chalk_ir::Ty<RustInterner<'tcx>>,
653     ) -> chalk_ir::Ty<RustInterner<'tcx>> {
654         unimplemented!()
655     }
656 }
657
658 impl<'tcx> chalk_ir::UnificationDatabase<RustInterner<'tcx>> for RustIrDatabase<'tcx> {
659     fn fn_def_variance(
660         &self,
661         def_id: chalk_ir::FnDefId<RustInterner<'tcx>>,
662     ) -> chalk_ir::Variances<RustInterner<'tcx>> {
663         let variances = self.interner.tcx.variances_of(def_id.0);
664         chalk_ir::Variances::from_iter(
665             self.interner,
666             variances.iter().map(|v| v.lower_into(self.interner)),
667         )
668     }
669
670     fn adt_variance(
671         &self,
672         adt_id: chalk_ir::AdtId<RustInterner<'tcx>>,
673     ) -> chalk_ir::Variances<RustInterner<'tcx>> {
674         let variances = self.interner.tcx.variances_of(adt_id.0.did);
675         chalk_ir::Variances::from_iter(
676             self.interner,
677             variances.iter().map(|v| v.lower_into(self.interner)),
678         )
679     }
680 }
681
682 /// Creates an `InternalSubsts` that maps each generic parameter to a higher-ranked
683 /// var bound at index `0`. For types, we use a `BoundVar` index equal to
684 /// the type parameter index. For regions, we use the `BoundRegionKind::BrNamed`
685 /// variant (which has a `DefId`).
686 fn bound_vars_for_item<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> {
687     InternalSubsts::for_item(tcx, def_id, |param, substs| match param.kind {
688         ty::GenericParamDefKind::Type { .. } => tcx
689             .mk_ty(ty::Bound(
690                 ty::INNERMOST,
691                 ty::BoundTy {
692                     var: ty::BoundVar::from(param.index),
693                     kind: ty::BoundTyKind::Param(param.name),
694                 },
695             ))
696             .into(),
697
698         ty::GenericParamDefKind::Lifetime => {
699             let br = ty::BoundRegion {
700                 var: ty::BoundVar::from_usize(substs.len()),
701                 kind: ty::BrAnon(substs.len() as u32),
702             };
703             tcx.mk_region(ty::ReLateBound(ty::INNERMOST, br)).into()
704         }
705
706         ty::GenericParamDefKind::Const { .. } => tcx
707             .mk_const(ty::ConstS {
708                 val: ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from(param.index)),
709                 ty: tcx.type_of(param.def_id),
710             })
711             .into(),
712     })
713 }
714
715 fn binders_for<'tcx>(
716     interner: RustInterner<'tcx>,
717     bound_vars: SubstsRef<'tcx>,
718 ) -> chalk_ir::VariableKinds<RustInterner<'tcx>> {
719     chalk_ir::VariableKinds::from_iter(
720         interner,
721         bound_vars.iter().map(|arg| match arg.unpack() {
722             ty::subst::GenericArgKind::Lifetime(_re) => chalk_ir::VariableKind::Lifetime,
723             ty::subst::GenericArgKind::Type(_ty) => {
724                 chalk_ir::VariableKind::Ty(chalk_ir::TyVariableKind::General)
725             }
726             ty::subst::GenericArgKind::Const(c) => {
727                 chalk_ir::VariableKind::Const(c.ty().lower_into(interner))
728             }
729         }),
730     )
731 }
732
733 struct ReplaceOpaqueTyFolder<'tcx> {
734     tcx: TyCtxt<'tcx>,
735     opaque_ty_id: chalk_ir::OpaqueTyId<RustInterner<'tcx>>,
736     identity_substs: SubstsRef<'tcx>,
737     binder_index: ty::DebruijnIndex,
738 }
739
740 impl<'tcx> ty::TypeFolder<'tcx> for ReplaceOpaqueTyFolder<'tcx> {
741     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
742         self.tcx
743     }
744
745     fn fold_binder<T: TypeFoldable<'tcx>>(
746         &mut self,
747         t: ty::Binder<'tcx, T>,
748     ) -> ty::Binder<'tcx, T> {
749         self.binder_index.shift_in(1);
750         let t = t.super_fold_with(self);
751         self.binder_index.shift_out(1);
752         t
753     }
754
755     fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
756         if let ty::Opaque(def_id, substs) = *ty.kind() {
757             if def_id == self.opaque_ty_id.0 && substs == self.identity_substs {
758                 return self.tcx.mk_ty(ty::Bound(
759                     self.binder_index,
760                     ty::BoundTy::from(ty::BoundVar::from_u32(0)),
761                 ));
762             }
763         }
764         ty
765     }
766 }