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