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