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