]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lower.rs
infer: remove `record_field_resolutions` field
[rust.git] / crates / hir_ty / src / lower.rs
1 //! Methods for lowering the HIR to types. There are two main cases here:
2 //!
3 //!  - Lowering a type reference like `&usize` or `Option<foo::bar::Baz>` to a
4 //!    type: The entry point for this is `Ty::from_hir`.
5 //!  - Building the type for an item: This happens through the `type_for_def` query.
6 //!
7 //! This usually involves resolving names, collecting generic arguments etc.
8 use std::{iter, sync::Arc};
9
10 use base_db::CrateId;
11 use chalk_ir::{cast::Cast, Mutability, Safety};
12 use hir_def::{
13     adt::StructKind,
14     builtin_type::BuiltinType,
15     generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget},
16     path::{GenericArg, Path, PathSegment, PathSegments},
17     resolver::{HasResolver, Resolver, TypeNs},
18     type_ref::{TraitRef as HirTraitRef, TypeBound, TypeRef},
19     AdtId, AssocContainerId, AssocItemId, ConstId, ConstParamId, EnumId, EnumVariantId, FunctionId,
20     GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId,
21     TypeAliasId, TypeParamId, UnionId, VariantId,
22 };
23 use hir_expand::name::Name;
24 use la_arena::ArenaMap;
25 use smallvec::SmallVec;
26 use stdx::impl_from;
27
28 use crate::{
29     db::HirDatabase,
30     dummy_usize_const, static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx,
31     traits::chalk::{Interner, ToChalk},
32     utils::{
33         all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics,
34     },
35     AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig,
36     FnSubst, ImplTraitId, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause,
37     QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution,
38     TraitEnvironment, TraitRef, Ty, TyBuilder, TyKind, TypeWalk, WhereClause,
39 };
40
41 #[derive(Debug)]
42 pub struct TyLoweringContext<'a> {
43     pub db: &'a dyn HirDatabase,
44     pub resolver: &'a Resolver,
45     in_binders: DebruijnIndex,
46     /// Note: Conceptually, it's thinkable that we could be in a location where
47     /// some type params should be represented as placeholders, and others
48     /// should be converted to variables. I think in practice, this isn't
49     /// possible currently, so this should be fine for now.
50     pub type_param_mode: TypeParamLoweringMode,
51     pub impl_trait_mode: ImplTraitLoweringMode,
52     impl_trait_counter: std::cell::Cell<u16>,
53     /// When turning `impl Trait` into opaque types, we have to collect the
54     /// bounds at the same time to get the IDs correct (without becoming too
55     /// complicated). I don't like using interior mutability (as for the
56     /// counter), but I've tried and failed to make the lifetimes work for
57     /// passing around a `&mut TyLoweringContext`. The core problem is that
58     /// we're grouping the mutable data (the counter and this field) together
59     /// with the immutable context (the references to the DB and resolver).
60     /// Splitting this up would be a possible fix.
61     opaque_type_data: std::cell::RefCell<Vec<ReturnTypeImplTrait>>,
62 }
63
64 impl<'a> TyLoweringContext<'a> {
65     pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
66         let impl_trait_counter = std::cell::Cell::new(0);
67         let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
68         let type_param_mode = TypeParamLoweringMode::Placeholder;
69         let in_binders = DebruijnIndex::INNERMOST;
70         let opaque_type_data = std::cell::RefCell::new(Vec::new());
71         Self {
72             db,
73             resolver,
74             in_binders,
75             impl_trait_mode,
76             impl_trait_counter,
77             type_param_mode,
78             opaque_type_data,
79         }
80     }
81
82     pub fn with_debruijn<T>(
83         &self,
84         debruijn: DebruijnIndex,
85         f: impl FnOnce(&TyLoweringContext) -> T,
86     ) -> T {
87         let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new());
88         let new_ctx = Self {
89             in_binders: debruijn,
90             impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()),
91             opaque_type_data: std::cell::RefCell::new(opaque_ty_data_vec),
92             ..*self
93         };
94         let result = f(&new_ctx);
95         self.impl_trait_counter.set(new_ctx.impl_trait_counter.get());
96         self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner());
97         result
98     }
99
100     pub fn with_shifted_in<T>(
101         &self,
102         debruijn: DebruijnIndex,
103         f: impl FnOnce(&TyLoweringContext) -> T,
104     ) -> T {
105         self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
106     }
107
108     pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
109         Self { impl_trait_mode, ..self }
110     }
111
112     pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
113         Self { type_param_mode, ..self }
114     }
115 }
116
117 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
118 pub enum ImplTraitLoweringMode {
119     /// `impl Trait` gets lowered into an opaque type that doesn't unify with
120     /// anything except itself. This is used in places where values flow 'out',
121     /// i.e. for arguments of the function we're currently checking, and return
122     /// types of functions we're calling.
123     Opaque,
124     /// `impl Trait` gets lowered into a type variable. Used for argument
125     /// position impl Trait when inside the respective function, since it allows
126     /// us to support that without Chalk.
127     Param,
128     /// `impl Trait` gets lowered into a variable that can unify with some
129     /// type. This is used in places where values flow 'in', i.e. for arguments
130     /// of functions we're calling, and the return type of the function we're
131     /// currently checking.
132     Variable,
133     /// `impl Trait` is disallowed and will be an error.
134     Disallowed,
135 }
136
137 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
138 pub enum TypeParamLoweringMode {
139     Placeholder,
140     Variable,
141 }
142
143 impl<'a> TyLoweringContext<'a> {
144     pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
145         self.lower_ty_ext(type_ref).0
146     }
147
148     pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
149         let mut res = None;
150         let ty = match type_ref {
151             TypeRef::Never => TyKind::Never.intern(&Interner),
152             TypeRef::Tuple(inner) => {
153                 let inner_tys = inner.iter().map(|tr| self.lower_ty(tr));
154                 TyKind::Tuple(inner_tys.len(), Substitution::from_iter(&Interner, inner_tys))
155                     .intern(&Interner)
156             }
157             TypeRef::Path(path) => {
158                 let (ty, res_) = self.lower_path(path);
159                 res = res_;
160                 ty
161             }
162             TypeRef::RawPtr(inner, mutability) => {
163                 let inner_ty = self.lower_ty(inner);
164                 TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
165             }
166             TypeRef::Array(inner) => {
167                 let inner_ty = self.lower_ty(inner);
168                 TyKind::Array(inner_ty, dummy_usize_const()).intern(&Interner)
169             }
170             TypeRef::Slice(inner) => {
171                 let inner_ty = self.lower_ty(inner);
172                 TyKind::Slice(inner_ty).intern(&Interner)
173             }
174             TypeRef::Reference(inner, _, mutability) => {
175                 let inner_ty = self.lower_ty(inner);
176                 let lifetime = static_lifetime();
177                 TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty)
178                     .intern(&Interner)
179             }
180             TypeRef::Placeholder => TyKind::Error.intern(&Interner),
181             TypeRef::Fn(params, is_varargs) => {
182                 let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
183                     Substitution::from_iter(&Interner, params.iter().map(|tr| ctx.lower_ty(tr)))
184                 });
185                 TyKind::Function(FnPointer {
186                     num_binders: 0, // FIXME lower `for<'a> fn()` correctly
187                     sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
188                     substitution: FnSubst(substs),
189                 })
190                 .intern(&Interner)
191             }
192             TypeRef::DynTrait(bounds) => {
193                 let self_ty =
194                     TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
195                 let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
196                     QuantifiedWhereClauses::from_iter(
197                         &Interner,
198                         bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)),
199                     )
200                 });
201                 let bounds = crate::make_only_type_binders(1, bounds);
202                 TyKind::Dyn(DynTy { bounds, lifetime: static_lifetime() }).intern(&Interner)
203             }
204             TypeRef::ImplTrait(bounds) => {
205                 match self.impl_trait_mode {
206                     ImplTraitLoweringMode::Opaque => {
207                         let idx = self.impl_trait_counter.get();
208                         self.impl_trait_counter.set(idx + 1);
209
210                         assert!(idx as usize == self.opaque_type_data.borrow().len());
211                         // this dance is to make sure the data is in the right
212                         // place even if we encounter more opaque types while
213                         // lowering the bounds
214                         self.opaque_type_data.borrow_mut().push(ReturnTypeImplTrait {
215                             bounds: crate::make_only_type_binders(1, Vec::new()),
216                         });
217                         // We don't want to lower the bounds inside the binders
218                         // we're currently in, because they don't end up inside
219                         // those binders. E.g. when we have `impl Trait<impl
220                         // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
221                         // to the self parameter from `impl Trait`, and the
222                         // bounds aren't actually stored nested within each
223                         // other, but separately. So if the `T` refers to a type
224                         // parameter of the outer function, it's just one binder
225                         // away instead of two.
226                         let actual_opaque_type_data = self
227                             .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
228                                 ctx.lower_impl_trait(&bounds)
229                             });
230                         self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
231
232                         let func = match self.resolver.generic_def() {
233                             Some(GenericDefId::FunctionId(f)) => f,
234                             _ => panic!("opaque impl trait lowering in non-function"),
235                         };
236                         let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
237                         let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
238                         let generics = generics(self.db.upcast(), func.into());
239                         let parameters = generics.bound_vars_subst(self.in_binders);
240                         TyKind::Alias(AliasTy::Opaque(OpaqueTy {
241                             opaque_ty_id,
242                             substitution: parameters,
243                         }))
244                         .intern(&Interner)
245                     }
246                     ImplTraitLoweringMode::Param => {
247                         let idx = self.impl_trait_counter.get();
248                         // FIXME we're probably doing something wrong here
249                         self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
250                         if let Some(def) = self.resolver.generic_def() {
251                             let generics = generics(self.db.upcast(), def);
252                             let param = generics
253                                 .iter()
254                                 .filter(|(_, data)| {
255                                     data.provenance == TypeParamProvenance::ArgumentImplTrait
256                                 })
257                                 .nth(idx as usize)
258                                 .map_or(TyKind::Error, |(id, _)| {
259                                     TyKind::Placeholder(to_placeholder_idx(self.db, id))
260                                 });
261                             param.intern(&Interner)
262                         } else {
263                             TyKind::Error.intern(&Interner)
264                         }
265                     }
266                     ImplTraitLoweringMode::Variable => {
267                         let idx = self.impl_trait_counter.get();
268                         // FIXME we're probably doing something wrong here
269                         self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
270                         let (parent_params, self_params, list_params, _impl_trait_params) =
271                             if let Some(def) = self.resolver.generic_def() {
272                                 let generics = generics(self.db.upcast(), def);
273                                 generics.provenance_split()
274                             } else {
275                                 (0, 0, 0, 0)
276                             };
277                         TyKind::BoundVar(BoundVar::new(
278                             self.in_binders,
279                             idx as usize + parent_params + self_params + list_params,
280                         ))
281                         .intern(&Interner)
282                     }
283                     ImplTraitLoweringMode::Disallowed => {
284                         // FIXME: report error
285                         TyKind::Error.intern(&Interner)
286                     }
287                 }
288             }
289             TypeRef::Error => TyKind::Error.intern(&Interner),
290         };
291         (ty, res)
292     }
293
294     /// This is only for `generic_predicates_for_param`, where we can't just
295     /// lower the self types of the predicates since that could lead to cycles.
296     /// So we just check here if the `type_ref` resolves to a generic param, and which.
297     fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
298         let path = match type_ref {
299             TypeRef::Path(path) => path,
300             _ => return None,
301         };
302         if path.type_anchor().is_some() {
303             return None;
304         }
305         if path.segments().len() > 1 {
306             return None;
307         }
308         let resolution =
309             match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
310                 Some((it, None)) => it,
311                 _ => return None,
312             };
313         if let TypeNs::GenericParam(param_id) = resolution {
314             Some(param_id)
315         } else {
316             None
317         }
318     }
319
320     pub(crate) fn lower_ty_relative_path(
321         &self,
322         ty: Ty,
323         // We need the original resolution to lower `Self::AssocTy` correctly
324         res: Option<TypeNs>,
325         remaining_segments: PathSegments<'_>,
326     ) -> (Ty, Option<TypeNs>) {
327         if remaining_segments.len() == 1 {
328             // resolve unselected assoc types
329             let segment = remaining_segments.first().unwrap();
330             (self.select_associated_type(res, segment), None)
331         } else if remaining_segments.len() > 1 {
332             // FIXME report error (ambiguous associated type)
333             (TyKind::Error.intern(&Interner), None)
334         } else {
335             (ty, res)
336         }
337     }
338
339     pub(crate) fn lower_partly_resolved_path(
340         &self,
341         resolution: TypeNs,
342         resolved_segment: PathSegment<'_>,
343         remaining_segments: PathSegments<'_>,
344         infer_args: bool,
345     ) -> (Ty, Option<TypeNs>) {
346         let ty = match resolution {
347             TypeNs::TraitId(trait_) => {
348                 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
349                 let self_ty = if remaining_segments.len() == 0 {
350                     Some(
351                         TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
352                             .intern(&Interner),
353                     )
354                 } else {
355                     None
356                 };
357                 let trait_ref =
358                     self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
359                 let ty = if remaining_segments.len() == 1 {
360                     let segment = remaining_segments.first().unwrap();
361                     let found = associated_type_by_name_including_super_traits(
362                         self.db,
363                         trait_ref,
364                         &segment.name,
365                     );
366                     match found {
367                         Some((super_trait_ref, associated_ty)) => {
368                             // FIXME handle type parameters on the segment
369                             TyKind::Alias(AliasTy::Projection(ProjectionTy {
370                                 associated_ty_id: to_assoc_type_id(associated_ty),
371                                 substitution: super_trait_ref.substitution,
372                             }))
373                             .intern(&Interner)
374                         }
375                         None => {
376                             // FIXME: report error (associated type not found)
377                             TyKind::Error.intern(&Interner)
378                         }
379                     }
380                 } else if remaining_segments.len() > 1 {
381                     // FIXME report error (ambiguous associated type)
382                     TyKind::Error.intern(&Interner)
383                 } else {
384                     let dyn_ty = DynTy {
385                         bounds: crate::make_only_type_binders(
386                             1,
387                             QuantifiedWhereClauses::from_iter(
388                                 &Interner,
389                                 Some(crate::wrap_empty_binders(WhereClause::Implemented(
390                                     trait_ref,
391                                 ))),
392                             ),
393                         ),
394                         lifetime: static_lifetime(),
395                     };
396                     TyKind::Dyn(dyn_ty).intern(&Interner)
397                 };
398                 return (ty, None);
399             }
400             TypeNs::GenericParam(param_id) => {
401                 let generics = generics(
402                     self.db.upcast(),
403                     self.resolver.generic_def().expect("generics in scope"),
404                 );
405                 match self.type_param_mode {
406                     TypeParamLoweringMode::Placeholder => {
407                         TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
408                     }
409                     TypeParamLoweringMode::Variable => {
410                         let idx = generics.param_idx(param_id).expect("matching generics");
411                         TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
412                     }
413                 }
414                 .intern(&Interner)
415             }
416             TypeNs::SelfType(impl_id) => {
417                 let generics = generics(self.db.upcast(), impl_id.into());
418                 let substs = match self.type_param_mode {
419                     TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
420                     TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
421                 };
422                 self.db.impl_self_ty(impl_id).substitute(&Interner, &substs)
423             }
424             TypeNs::AdtSelfType(adt) => {
425                 let generics = generics(self.db.upcast(), adt.into());
426                 let substs = match self.type_param_mode {
427                     TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
428                     TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
429                 };
430                 self.db.ty(adt.into()).substitute(&Interner, &substs)
431             }
432
433             TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
434             TypeNs::BuiltinType(it) => {
435                 self.lower_path_inner(resolved_segment, it.into(), infer_args)
436             }
437             TypeNs::TypeAliasId(it) => {
438                 self.lower_path_inner(resolved_segment, it.into(), infer_args)
439             }
440             // FIXME: report error
441             TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(&Interner), None),
442         };
443         self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
444     }
445
446     pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
447         // Resolve the path (in type namespace)
448         if let Some(type_ref) = path.type_anchor() {
449             let (ty, res) = self.lower_ty_ext(&type_ref);
450             return self.lower_ty_relative_path(ty, res, path.segments());
451         }
452         let (resolution, remaining_index) =
453             match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
454                 Some(it) => it,
455                 None => return (TyKind::Error.intern(&Interner), None),
456             };
457         let (resolved_segment, remaining_segments) = match remaining_index {
458             None => (
459                 path.segments().last().expect("resolved path has at least one element"),
460                 PathSegments::EMPTY,
461             ),
462             Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
463         };
464         self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
465     }
466
467     fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
468         if let Some(res) = res {
469             let ty = associated_type_shorthand_candidates(
470                 self.db,
471                 res,
472                 move |name, t, associated_ty| {
473                     if name == segment.name {
474                         let substs = match self.type_param_mode {
475                             TypeParamLoweringMode::Placeholder => {
476                                 // if we're lowering to placeholders, we have to put
477                                 // them in now
478                                 let generics = generics(
479                                     self.db.upcast(),
480                                     self.resolver.generic_def().expect(
481                                         "there should be generics if there's a generic param",
482                                     ),
483                                 );
484                                 let s = generics.type_params_subst(self.db);
485                                 s.apply(t.substitution.clone(), &Interner)
486                             }
487                             TypeParamLoweringMode::Variable => t.substitution.clone(),
488                         };
489                         // We need to shift in the bound vars, since
490                         // associated_type_shorthand_candidates does not do that
491                         let substs = substs.shifted_in_from(self.in_binders);
492                         // FIXME handle type parameters on the segment
493                         return Some(
494                             TyKind::Alias(AliasTy::Projection(ProjectionTy {
495                                 associated_ty_id: to_assoc_type_id(associated_ty),
496                                 substitution: substs,
497                             }))
498                             .intern(&Interner),
499                         );
500                     }
501
502                     None
503                 },
504             );
505
506             ty.unwrap_or(TyKind::Error.intern(&Interner))
507         } else {
508             TyKind::Error.intern(&Interner)
509         }
510     }
511
512     fn lower_path_inner(
513         &self,
514         segment: PathSegment<'_>,
515         typeable: TyDefId,
516         infer_args: bool,
517     ) -> Ty {
518         let generic_def = match typeable {
519             TyDefId::BuiltinType(_) => None,
520             TyDefId::AdtId(it) => Some(it.into()),
521             TyDefId::TypeAliasId(it) => Some(it.into()),
522         };
523         let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None);
524         self.db.ty(typeable).substitute(&Interner, &substs)
525     }
526
527     /// Collect generic arguments from a path into a `Substs`. See also
528     /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
529     pub(super) fn substs_from_path(
530         &self,
531         path: &Path,
532         // Note that we don't call `db.value_type(resolved)` here,
533         // `ValueTyDefId` is just a convenient way to pass generics and
534         // special-case enum variants
535         resolved: ValueTyDefId,
536         infer_args: bool,
537     ) -> Substitution {
538         let last = path.segments().last().expect("path should have at least one segment");
539         let (segment, generic_def) = match resolved {
540             ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
541             ValueTyDefId::StructId(it) => (last, Some(it.into())),
542             ValueTyDefId::UnionId(it) => (last, Some(it.into())),
543             ValueTyDefId::ConstId(it) => (last, Some(it.into())),
544             ValueTyDefId::StaticId(_) => (last, None),
545             ValueTyDefId::EnumVariantId(var) => {
546                 // the generic args for an enum variant may be either specified
547                 // on the segment referring to the enum, or on the segment
548                 // referring to the variant. So `Option::<T>::None` and
549                 // `Option::None::<T>` are both allowed (though the former is
550                 // preferred). See also `def_ids_for_path_segments` in rustc.
551                 let len = path.segments().len();
552                 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
553                 let segment = match penultimate {
554                     Some(segment) if segment.args_and_bindings.is_some() => segment,
555                     _ => last,
556                 };
557                 (segment, Some(var.parent.into()))
558             }
559         };
560         self.substs_from_path_segment(segment, generic_def, infer_args, None)
561     }
562
563     fn substs_from_path_segment(
564         &self,
565         segment: PathSegment<'_>,
566         def_generic: Option<GenericDefId>,
567         infer_args: bool,
568         explicit_self_ty: Option<Ty>,
569     ) -> Substitution {
570         let mut substs = Vec::new();
571         let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
572
573         let (parent_params, self_params, type_params, impl_trait_params) =
574             def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
575         let total_len = parent_params + self_params + type_params + impl_trait_params;
576
577         substs.extend(iter::repeat(TyKind::Error.intern(&Interner)).take(parent_params));
578
579         let fill_self_params = || {
580             substs.extend(
581                 explicit_self_ty
582                     .into_iter()
583                     .chain(iter::repeat(TyKind::Error.intern(&Interner)))
584                     .take(self_params),
585             )
586         };
587         let mut had_explicit_type_args = false;
588
589         if let Some(generic_args) = &segment.args_and_bindings {
590             if !generic_args.has_self_type {
591                 fill_self_params();
592             }
593             let expected_num =
594                 if generic_args.has_self_type { self_params + type_params } else { type_params };
595             let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
596             // if args are provided, it should be all of them, but we can't rely on that
597             for arg in generic_args
598                 .args
599                 .iter()
600                 .filter(|arg| matches!(arg, GenericArg::Type(_)))
601                 .skip(skip)
602                 .take(expected_num)
603             {
604                 match arg {
605                     GenericArg::Type(type_ref) => {
606                         had_explicit_type_args = true;
607                         let ty = self.lower_ty(type_ref);
608                         substs.push(ty);
609                     }
610                     GenericArg::Lifetime(_) => {}
611                 }
612             }
613         } else {
614             fill_self_params();
615         }
616
617         // handle defaults. In expression or pattern path segments without
618         // explicitly specified type arguments, missing type arguments are inferred
619         // (i.e. defaults aren't used).
620         if !infer_args || had_explicit_type_args {
621             if let Some(def_generic) = def_generic {
622                 let defaults = self.db.generic_defaults(def_generic);
623                 assert_eq!(total_len, defaults.len());
624
625                 for default_ty in defaults.iter().skip(substs.len()) {
626                     // each default can depend on the previous parameters
627                     let substs_so_far = Substitution::from_iter(&Interner, substs.clone());
628                     substs.push(default_ty.clone().substitute(&Interner, &substs_so_far));
629                 }
630             }
631         }
632
633         // add placeholders for args that were not provided
634         // FIXME: emit diagnostics in contexts where this is not allowed
635         for _ in substs.len()..total_len {
636             substs.push(TyKind::Error.intern(&Interner));
637         }
638         assert_eq!(substs.len(), total_len);
639
640         Substitution::from_iter(&Interner, substs)
641     }
642
643     fn lower_trait_ref_from_path(
644         &self,
645         path: &Path,
646         explicit_self_ty: Option<Ty>,
647     ) -> Option<TraitRef> {
648         let resolved =
649             match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
650                 TypeNs::TraitId(tr) => tr,
651                 _ => return None,
652             };
653         let segment = path.segments().last().expect("path should have at least one segment");
654         Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
655     }
656
657     pub(crate) fn lower_trait_ref_from_resolved_path(
658         &self,
659         resolved: TraitId,
660         segment: PathSegment<'_>,
661         explicit_self_ty: Option<Ty>,
662     ) -> TraitRef {
663         let substs = self.trait_ref_substs_from_path(segment, resolved, explicit_self_ty);
664         TraitRef { trait_id: to_chalk_trait_id(resolved), substitution: substs }
665     }
666
667     fn lower_trait_ref(
668         &self,
669         trait_ref: &HirTraitRef,
670         explicit_self_ty: Option<Ty>,
671     ) -> Option<TraitRef> {
672         self.lower_trait_ref_from_path(&trait_ref.path, explicit_self_ty)
673     }
674
675     fn trait_ref_substs_from_path(
676         &self,
677         segment: PathSegment<'_>,
678         resolved: TraitId,
679         explicit_self_ty: Option<Ty>,
680     ) -> Substitution {
681         self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty)
682     }
683
684     pub(crate) fn lower_where_predicate(
685         &'a self,
686         where_predicate: &'a WherePredicate,
687         ignore_bindings: bool,
688     ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
689         match where_predicate {
690             WherePredicate::ForLifetime { target, bound, .. }
691             | WherePredicate::TypeBound { target, bound } => {
692                 let self_ty = match target {
693                     WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
694                     WherePredicateTypeTarget::TypeParam(param_id) => {
695                         let generic_def = self.resolver.generic_def().expect("generics in scope");
696                         let generics = generics(self.db.upcast(), generic_def);
697                         let param_id =
698                             hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
699                         let placeholder = to_placeholder_idx(self.db, param_id);
700                         match self.type_param_mode {
701                             TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
702                             TypeParamLoweringMode::Variable => {
703                                 let idx = generics.param_idx(param_id).expect("matching generics");
704                                 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
705                             }
706                         }
707                         .intern(&Interner)
708                     }
709                 };
710                 self.lower_type_bound(bound, self_ty, ignore_bindings)
711                     .collect::<Vec<_>>()
712                     .into_iter()
713             }
714             WherePredicate::Lifetime { .. } => vec![].into_iter(),
715         }
716     }
717
718     pub(crate) fn lower_type_bound(
719         &'a self,
720         bound: &'a TypeBound,
721         self_ty: Ty,
722         ignore_bindings: bool,
723     ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
724         let mut bindings = None;
725         let trait_ref = match bound {
726             TypeBound::Path(path) => {
727                 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
728                 bindings.clone().map(WhereClause::Implemented).map(|b| crate::wrap_empty_binders(b))
729             }
730             TypeBound::Lifetime(_) => None,
731             TypeBound::Error => None,
732         };
733         trait_ref.into_iter().chain(
734             bindings
735                 .into_iter()
736                 .filter(move |_| !ignore_bindings)
737                 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
738         )
739     }
740
741     fn assoc_type_bindings_from_type_bound(
742         &'a self,
743         bound: &'a TypeBound,
744         trait_ref: TraitRef,
745     ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
746         let last_segment = match bound {
747             TypeBound::Path(path) => path.segments().last(),
748             TypeBound::Error | TypeBound::Lifetime(_) => None,
749         };
750         last_segment
751             .into_iter()
752             .flat_map(|segment| segment.args_and_bindings.into_iter())
753             .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
754             .flat_map(move |binding| {
755                 let found = associated_type_by_name_including_super_traits(
756                     self.db,
757                     trait_ref.clone(),
758                     &binding.name,
759                 );
760                 let (super_trait_ref, associated_ty) = match found {
761                     None => return SmallVec::<[QuantifiedWhereClause; 1]>::new(),
762                     Some(t) => t,
763                 };
764                 let projection_ty = ProjectionTy {
765                     associated_ty_id: to_assoc_type_id(associated_ty),
766                     substitution: super_trait_ref.substitution,
767                 };
768                 let mut preds = SmallVec::with_capacity(
769                     binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
770                 );
771                 if let Some(type_ref) = &binding.type_ref {
772                     let ty = self.lower_ty(type_ref);
773                     let alias_eq =
774                         AliasEq { alias: AliasTy::Projection(projection_ty.clone()), ty };
775                     preds.push(crate::wrap_empty_binders(WhereClause::AliasEq(alias_eq)));
776                 }
777                 for bound in &binding.bounds {
778                     preds.extend(self.lower_type_bound(
779                         bound,
780                         TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
781                         false,
782                     ));
783                 }
784                 preds
785             })
786     }
787
788     fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
789         cov_mark::hit!(lower_rpit);
790         let self_ty =
791             TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
792         let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
793             bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)).collect()
794         });
795         ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, predicates) }
796     }
797 }
798
799 fn count_impl_traits(type_ref: &TypeRef) -> usize {
800     let mut count = 0;
801     type_ref.walk(&mut |type_ref| {
802         if matches!(type_ref, TypeRef::ImplTrait(_)) {
803             count += 1;
804         }
805     });
806     count
807 }
808
809 /// Build the signature of a callable item (function, struct or enum variant).
810 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
811     match def {
812         CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
813         CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
814         CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
815     }
816 }
817
818 pub fn associated_type_shorthand_candidates<R>(
819     db: &dyn HirDatabase,
820     res: TypeNs,
821     mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
822 ) -> Option<R> {
823     let mut search = |t| {
824         for t in all_super_trait_refs(db, t) {
825             let data = db.trait_data(t.hir_trait_id());
826
827             for (name, assoc_id) in &data.items {
828                 if let AssocItemId::TypeAliasId(alias) = assoc_id {
829                     if let Some(result) = cb(name, &t, *alias) {
830                         return Some(result);
831                     }
832                 }
833             }
834         }
835         None
836     };
837
838     match res {
839         TypeNs::SelfType(impl_id) => search(
840             // we're _in_ the impl -- the binders get added back later. Correct,
841             // but it would be nice to make this more explicit
842             db.impl_trait(impl_id)?.into_value_and_skipped_binders().0,
843         ),
844         TypeNs::GenericParam(param_id) => {
845             let predicates = db.generic_predicates_for_param(param_id);
846             let res = predicates.iter().find_map(|pred| match pred.skip_binders().skip_binders() {
847                 // FIXME: how to correctly handle higher-ranked bounds here?
848                 WhereClause::Implemented(tr) => search(
849                     tr.clone()
850                         .shifted_out_to(DebruijnIndex::ONE)
851                         .expect("FIXME unexpected higher-ranked trait bound"),
852                 ),
853                 _ => None,
854             });
855             if let res @ Some(_) = res {
856                 return res;
857             }
858             // Handle `Self::Type` referring to own associated type in trait definitions
859             if let GenericDefId::TraitId(trait_id) = param_id.parent {
860                 let generics = generics(db.upcast(), trait_id.into());
861                 if generics.params.types[param_id.local_id].provenance
862                     == TypeParamProvenance::TraitSelf
863                 {
864                     let trait_ref = TyBuilder::trait_ref(db, trait_id)
865                         .fill_with_bound_vars(DebruijnIndex::INNERMOST, 0)
866                         .build();
867                     return search(trait_ref);
868                 }
869             }
870             None
871         }
872         _ => None,
873     }
874 }
875
876 /// Build the type of all specific fields of a struct or enum variant.
877 pub(crate) fn field_types_query(
878     db: &dyn HirDatabase,
879     variant_id: VariantId,
880 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
881     let var_data = variant_id.variant_data(db.upcast());
882     let (resolver, def): (_, GenericDefId) = match variant_id {
883         VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
884         VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
885         VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
886     };
887     let generics = generics(db.upcast(), def);
888     let mut res = ArenaMap::default();
889     let ctx =
890         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
891     for (field_id, field_data) in var_data.fields().iter() {
892         res.insert(field_id, make_binders(&generics, ctx.lower_ty(&field_data.type_ref)))
893     }
894     Arc::new(res)
895 }
896
897 /// This query exists only to be used when resolving short-hand associated types
898 /// like `T::Item`.
899 ///
900 /// See the analogous query in rustc and its comment:
901 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
902 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
903 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
904 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
905 pub(crate) fn generic_predicates_for_param_query(
906     db: &dyn HirDatabase,
907     param_id: TypeParamId,
908 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
909     let resolver = param_id.parent.resolver(db.upcast());
910     let ctx =
911         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
912     let generics = generics(db.upcast(), param_id.parent);
913     resolver
914         .where_predicates_in_scope()
915         // we have to filter out all other predicates *first*, before attempting to lower them
916         .filter(|pred| match pred {
917             WherePredicate::ForLifetime { target, .. }
918             | WherePredicate::TypeBound { target, .. } => match target {
919                 WherePredicateTypeTarget::TypeRef(type_ref) => {
920                     ctx.lower_ty_only_param(type_ref) == Some(param_id)
921                 }
922                 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
923             },
924             WherePredicate::Lifetime { .. } => false,
925         })
926         .flat_map(|pred| ctx.lower_where_predicate(pred, true).map(|p| make_binders(&generics, p)))
927         .collect()
928 }
929
930 pub(crate) fn generic_predicates_for_param_recover(
931     _db: &dyn HirDatabase,
932     _cycle: &[String],
933     _param_id: &TypeParamId,
934 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
935     Arc::new([])
936 }
937
938 pub(crate) fn trait_environment_query(
939     db: &dyn HirDatabase,
940     def: GenericDefId,
941 ) -> Arc<TraitEnvironment> {
942     let resolver = def.resolver(db.upcast());
943     let ctx = TyLoweringContext::new(db, &resolver)
944         .with_type_param_mode(TypeParamLoweringMode::Placeholder);
945     let mut traits_in_scope = Vec::new();
946     let mut clauses = Vec::new();
947     for pred in resolver.where_predicates_in_scope() {
948         for pred in ctx.lower_where_predicate(pred, false) {
949             if let WhereClause::Implemented(tr) = &pred.skip_binders() {
950                 traits_in_scope
951                     .push((tr.self_type_parameter(&Interner).clone(), tr.hir_trait_id()));
952             }
953             let program_clause: chalk_ir::ProgramClause<Interner> =
954                 pred.clone().to_chalk(db).cast(&Interner);
955             clauses.push(program_clause.into_from_env_clause(&Interner));
956         }
957     }
958
959     let container: Option<AssocContainerId> = match def {
960         // FIXME: is there a function for this?
961         GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
962         GenericDefId::AdtId(_) => None,
963         GenericDefId::TraitId(_) => None,
964         GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
965         GenericDefId::ImplId(_) => None,
966         GenericDefId::EnumVariantId(_) => None,
967         GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
968     };
969     if let Some(AssocContainerId::TraitId(trait_id)) = container {
970         // add `Self: Trait<T1, T2, ...>` to the environment in trait
971         // function default implementations (and hypothetical code
972         // inside consts or type aliases)
973         cov_mark::hit!(trait_self_implements_self);
974         let substs = TyBuilder::type_params_subst(db, trait_id);
975         let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs };
976         let pred = WhereClause::Implemented(trait_ref);
977         let program_clause: chalk_ir::ProgramClause<Interner> = pred.to_chalk(db).cast(&Interner);
978         clauses.push(program_clause.into_from_env_clause(&Interner));
979     }
980
981     let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
982
983     Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
984 }
985
986 /// Resolve the where clause(s) of an item with generics.
987 pub(crate) fn generic_predicates_query(
988     db: &dyn HirDatabase,
989     def: GenericDefId,
990 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
991     let resolver = def.resolver(db.upcast());
992     let ctx =
993         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
994     let generics = generics(db.upcast(), def);
995     resolver
996         .where_predicates_in_scope()
997         .flat_map(|pred| ctx.lower_where_predicate(pred, false).map(|p| make_binders(&generics, p)))
998         .collect()
999 }
1000
1001 /// Resolve the default type params from generics
1002 pub(crate) fn generic_defaults_query(
1003     db: &dyn HirDatabase,
1004     def: GenericDefId,
1005 ) -> Arc<[Binders<Ty>]> {
1006     let resolver = def.resolver(db.upcast());
1007     let ctx =
1008         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1009     let generic_params = generics(db.upcast(), def);
1010
1011     let defaults = generic_params
1012         .iter()
1013         .enumerate()
1014         .map(|(idx, (_, p))| {
1015             let mut ty =
1016                 p.default.as_ref().map_or(TyKind::Error.intern(&Interner), |t| ctx.lower_ty(t));
1017
1018             // Each default can only refer to previous parameters.
1019             ty = ty.fold_binders(
1020                 &mut |ty, binders| match ty.kind(&Interner) {
1021                     TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
1022                         if *index >= idx {
1023                             // type variable default referring to parameter coming
1024                             // after it. This is forbidden (FIXME: report
1025                             // diagnostic)
1026                             TyKind::Error.intern(&Interner)
1027                         } else {
1028                             ty
1029                         }
1030                     }
1031                     _ => ty,
1032                 },
1033                 DebruijnIndex::INNERMOST,
1034             );
1035
1036             crate::make_only_type_binders(idx, ty)
1037         })
1038         .collect();
1039
1040     defaults
1041 }
1042
1043 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1044     let data = db.function_data(def);
1045     let resolver = def.resolver(db.upcast());
1046     let ctx_params = TyLoweringContext::new(db, &resolver)
1047         .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1048         .with_type_param_mode(TypeParamLoweringMode::Variable);
1049     let params = data.params.iter().map(|tr| ctx_params.lower_ty(tr)).collect::<Vec<_>>();
1050     let ctx_ret = TyLoweringContext::new(db, &resolver)
1051         .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1052         .with_type_param_mode(TypeParamLoweringMode::Variable);
1053     let ret = ctx_ret.lower_ty(&data.ret_type);
1054     let generics = generics(db.upcast(), def.into());
1055     make_binders(&generics, CallableSig::from_params_and_return(params, ret, data.is_varargs()))
1056 }
1057
1058 /// Build the declared type of a function. This should not need to look at the
1059 /// function body.
1060 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1061     let generics = generics(db.upcast(), def.into());
1062     let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1063     make_binders(
1064         &generics,
1065         TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1066     )
1067 }
1068
1069 /// Build the declared type of a const.
1070 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1071     let data = db.const_data(def);
1072     let generics = generics(db.upcast(), def.into());
1073     let resolver = def.resolver(db.upcast());
1074     let ctx =
1075         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1076
1077     make_binders(&generics, ctx.lower_ty(&data.type_ref))
1078 }
1079
1080 /// Build the declared type of a static.
1081 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1082     let data = db.static_data(def);
1083     let resolver = def.resolver(db.upcast());
1084     let ctx = TyLoweringContext::new(db, &resolver);
1085
1086     Binders::empty(&Interner, ctx.lower_ty(&data.type_ref))
1087 }
1088
1089 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1090     let struct_data = db.struct_data(def);
1091     let fields = struct_data.variant_data.fields();
1092     let resolver = def.resolver(db.upcast());
1093     let ctx =
1094         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1095     let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1096     let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders();
1097     Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1098 }
1099
1100 /// Build the type of a tuple struct constructor.
1101 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1102     let struct_data = db.struct_data(def);
1103     if let StructKind::Unit = struct_data.variant_data.kind() {
1104         return type_for_adt(db, def.into());
1105     }
1106     let generics = generics(db.upcast(), def.into());
1107     let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1108     make_binders(
1109         &generics,
1110         TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1111     )
1112 }
1113
1114 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1115     let enum_data = db.enum_data(def.parent);
1116     let var_data = &enum_data.variants[def.local_id];
1117     let fields = var_data.variant_data.fields();
1118     let resolver = def.parent.resolver(db.upcast());
1119     let ctx =
1120         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1121     let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1122     let (ret, binders) = type_for_adt(db, def.parent.into()).into_value_and_skipped_binders();
1123     Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1124 }
1125
1126 /// Build the type of a tuple enum variant constructor.
1127 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1128     let enum_data = db.enum_data(def.parent);
1129     let var_data = &enum_data.variants[def.local_id].variant_data;
1130     if let StructKind::Unit = var_data.kind() {
1131         return type_for_adt(db, def.parent.into());
1132     }
1133     let generics = generics(db.upcast(), def.parent.into());
1134     let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1135     make_binders(
1136         &generics,
1137         TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1138     )
1139 }
1140
1141 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1142     let generics = generics(db.upcast(), adt.into());
1143     let b = TyBuilder::adt(db, adt);
1144     let ty = b.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0).build();
1145     make_binders(&generics, ty)
1146 }
1147
1148 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1149     let generics = generics(db.upcast(), t.into());
1150     let resolver = t.resolver(db.upcast());
1151     let ctx =
1152         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1153     if db.type_alias_data(t).is_extern {
1154         Binders::empty(&Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(&Interner))
1155     } else {
1156         let type_ref = &db.type_alias_data(t).type_ref;
1157         let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error));
1158         make_binders(&generics, inner)
1159     }
1160 }
1161
1162 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1163 pub enum CallableDefId {
1164     FunctionId(FunctionId),
1165     StructId(StructId),
1166     EnumVariantId(EnumVariantId),
1167 }
1168 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1169
1170 impl CallableDefId {
1171     pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1172         let db = db.upcast();
1173         match self {
1174             CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1175             CallableDefId::StructId(s) => s.lookup(db).container,
1176             CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1177         }
1178         .krate()
1179     }
1180 }
1181
1182 impl From<CallableDefId> for GenericDefId {
1183     fn from(def: CallableDefId) -> GenericDefId {
1184         match def {
1185             CallableDefId::FunctionId(f) => f.into(),
1186             CallableDefId::StructId(s) => s.into(),
1187             CallableDefId::EnumVariantId(e) => e.into(),
1188         }
1189     }
1190 }
1191
1192 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1193 pub enum TyDefId {
1194     BuiltinType(BuiltinType),
1195     AdtId(AdtId),
1196     TypeAliasId(TypeAliasId),
1197 }
1198 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1199
1200 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1201 pub enum ValueTyDefId {
1202     FunctionId(FunctionId),
1203     StructId(StructId),
1204     UnionId(UnionId),
1205     EnumVariantId(EnumVariantId),
1206     ConstId(ConstId),
1207     StaticId(StaticId),
1208 }
1209 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1210
1211 /// Build the declared type of an item. This depends on the namespace; e.g. for
1212 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1213 /// the constructor function `(usize) -> Foo` which lives in the values
1214 /// namespace.
1215 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1216     match def {
1217         TyDefId::BuiltinType(it) => Binders::empty(&Interner, TyBuilder::builtin(it)),
1218         TyDefId::AdtId(it) => type_for_adt(db, it),
1219         TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1220     }
1221 }
1222
1223 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1224     let generics = match *def {
1225         TyDefId::BuiltinType(_) => {
1226             return Binders::empty(&Interner, TyKind::Error.intern(&Interner))
1227         }
1228         TyDefId::AdtId(it) => generics(db.upcast(), it.into()),
1229         TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()),
1230     };
1231     make_binders(&generics, TyKind::Error.intern(&Interner))
1232 }
1233
1234 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1235     match def {
1236         ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1237         ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1238         ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1239         ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1240         ValueTyDefId::ConstId(it) => type_for_const(db, it),
1241         ValueTyDefId::StaticId(it) => type_for_static(db, it),
1242     }
1243 }
1244
1245 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1246     let impl_data = db.impl_data(impl_id);
1247     let resolver = impl_id.resolver(db.upcast());
1248     let generics = generics(db.upcast(), impl_id.into());
1249     let ctx =
1250         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1251     make_binders(&generics, ctx.lower_ty(&impl_data.self_ty))
1252 }
1253
1254 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1255     let parent_data = db.generic_params(def.parent);
1256     let data = &parent_data.consts[def.local_id];
1257     let resolver = def.parent.resolver(db.upcast());
1258     let ctx = TyLoweringContext::new(db, &resolver);
1259
1260     ctx.lower_ty(&data.ty)
1261 }
1262
1263 pub(crate) fn impl_self_ty_recover(
1264     db: &dyn HirDatabase,
1265     _cycle: &[String],
1266     impl_id: &ImplId,
1267 ) -> Binders<Ty> {
1268     let generics = generics(db.upcast(), (*impl_id).into());
1269     make_binders(&generics, TyKind::Error.intern(&Interner))
1270 }
1271
1272 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1273     let impl_data = db.impl_data(impl_id);
1274     let resolver = impl_id.resolver(db.upcast());
1275     let ctx =
1276         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1277     let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders();
1278     let target_trait = impl_data.target_trait.as_ref()?;
1279     Some(Binders::new(binders, ctx.lower_trait_ref(target_trait, Some(self_ty))?))
1280 }
1281
1282 pub(crate) fn return_type_impl_traits(
1283     db: &dyn HirDatabase,
1284     def: hir_def::FunctionId,
1285 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1286     // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1287     let data = db.function_data(def);
1288     let resolver = def.resolver(db.upcast());
1289     let ctx_ret = TyLoweringContext::new(db, &resolver)
1290         .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1291         .with_type_param_mode(TypeParamLoweringMode::Variable);
1292     let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1293     let generics = generics(db.upcast(), def.into());
1294     let return_type_impl_traits =
1295         ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1296     if return_type_impl_traits.impl_traits.is_empty() {
1297         None
1298     } else {
1299         Some(Arc::new(make_binders(&generics, return_type_impl_traits)))
1300     }
1301 }
1302
1303 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1304     match m {
1305         hir_def::type_ref::Mutability::Shared => Mutability::Not,
1306         hir_def::type_ref::Mutability::Mut => Mutability::Mut,
1307     }
1308 }
1309
1310 fn make_binders<T>(generics: &Generics, value: T) -> Binders<T> {
1311     crate::make_only_type_binders(generics.len(), value)
1312 }