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