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