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