]> git.lizzy.rs Git - rust.git/blob - crates/hir_ty/src/lower.rs
Fix chalk_ir assertion
[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::{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     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,
35     },
36     AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig,
37     ImplTraitId, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause, QuantifiedWhereClauses,
38     ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution, TraitEnvironment, TraitRef, Ty,
39     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     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                 TyKind::Ref(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
178             }
179             TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
180             TypeRef::Fn(params, is_varargs) => {
181                 let substs = Substitution(params.iter().map(|tr| self.lower_ty(tr)).collect());
182                 TyKind::Function(FnPointer {
183                     num_args: substs.len() - 1,
184                     sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
185                     substs,
186                 })
187                 .intern(&Interner)
188             }
189             TypeRef::DynTrait(bounds) => {
190                 let self_ty =
191                     TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
192                 let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
193                     QuantifiedWhereClauses::from_iter(
194                         &Interner,
195                         bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)),
196                     )
197                 });
198                 let bounds = Binders::new(1, bounds);
199                 TyKind::Dyn(DynTy { bounds }).intern(&Interner)
200             }
201             TypeRef::ImplTrait(bounds) => {
202                 match self.impl_trait_mode {
203                     ImplTraitLoweringMode::Opaque => {
204                         let idx = self.impl_trait_counter.get();
205                         self.impl_trait_counter.set(idx + 1);
206
207                         assert!(idx as usize == self.opaque_type_data.borrow().len());
208                         // this dance is to make sure the data is in the right
209                         // place even if we encounter more opaque types while
210                         // lowering the bounds
211                         self.opaque_type_data
212                             .borrow_mut()
213                             .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
214                         // We don't want to lower the bounds inside the binders
215                         // we're currently in, because they don't end up inside
216                         // those binders. E.g. when we have `impl Trait<impl
217                         // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
218                         // to the self parameter from `impl Trait`, and the
219                         // bounds aren't actually stored nested within each
220                         // other, but separately. So if the `T` refers to a type
221                         // parameter of the outer function, it's just one binder
222                         // away instead of two.
223                         let actual_opaque_type_data = self
224                             .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
225                                 ctx.lower_impl_trait(&bounds)
226                             });
227                         self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
228
229                         let func = match self.resolver.generic_def() {
230                             Some(GenericDefId::FunctionId(f)) => f,
231                             _ => panic!("opaque impl trait lowering in non-function"),
232                         };
233                         let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
234                         let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
235                         let generics = generics(self.db.upcast(), func.into());
236                         let parameters = Substitution::bound_vars(&generics, self.in_binders);
237                         TyKind::Alias(AliasTy::Opaque(OpaqueTy {
238                             opaque_ty_id,
239                             substitution: parameters,
240                         }))
241                         .intern(&Interner)
242                     }
243                     ImplTraitLoweringMode::Param => {
244                         let idx = self.impl_trait_counter.get();
245                         // FIXME we're probably doing something wrong here
246                         self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
247                         if let Some(def) = self.resolver.generic_def() {
248                             let generics = generics(self.db.upcast(), def);
249                             let param = generics
250                                 .iter()
251                                 .filter(|(_, data)| {
252                                     data.provenance == TypeParamProvenance::ArgumentImplTrait
253                                 })
254                                 .nth(idx as usize)
255                                 .map_or(TyKind::Unknown, |(id, _)| {
256                                     TyKind::Placeholder(to_placeholder_idx(self.db, id))
257                                 });
258                             param.intern(&Interner)
259                         } else {
260                             TyKind::Unknown.intern(&Interner)
261                         }
262                     }
263                     ImplTraitLoweringMode::Variable => {
264                         let idx = self.impl_trait_counter.get();
265                         // FIXME we're probably doing something wrong here
266                         self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
267                         let (parent_params, self_params, list_params, _impl_trait_params) =
268                             if let Some(def) = self.resolver.generic_def() {
269                                 let generics = generics(self.db.upcast(), def);
270                                 generics.provenance_split()
271                             } else {
272                                 (0, 0, 0, 0)
273                             };
274                         TyKind::BoundVar(BoundVar::new(
275                             self.in_binders,
276                             idx as usize + parent_params + self_params + list_params,
277                         ))
278                         .intern(&Interner)
279                     }
280                     ImplTraitLoweringMode::Disallowed => {
281                         // FIXME: report error
282                         TyKind::Unknown.intern(&Interner)
283                     }
284                 }
285             }
286             TypeRef::Error => TyKind::Unknown.intern(&Interner),
287         };
288         (ty, res)
289     }
290
291     /// This is only for `generic_predicates_for_param`, where we can't just
292     /// lower the self types of the predicates since that could lead to cycles.
293     /// So we just check here if the `type_ref` resolves to a generic param, and which.
294     fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
295         let path = match type_ref {
296             TypeRef::Path(path) => path,
297             _ => return None,
298         };
299         if path.type_anchor().is_some() {
300             return None;
301         }
302         if path.segments().len() > 1 {
303             return None;
304         }
305         let resolution =
306             match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
307                 Some((it, None)) => it,
308                 _ => return None,
309             };
310         if let TypeNs::GenericParam(param_id) = resolution {
311             Some(param_id)
312         } else {
313             None
314         }
315     }
316
317     pub(crate) fn lower_ty_relative_path(
318         &self,
319         ty: Ty,
320         // We need the original resolution to lower `Self::AssocTy` correctly
321         res: Option<TypeNs>,
322         remaining_segments: PathSegments<'_>,
323     ) -> (Ty, Option<TypeNs>) {
324         if remaining_segments.len() == 1 {
325             // resolve unselected assoc types
326             let segment = remaining_segments.first().unwrap();
327             (self.select_associated_type(res, segment), None)
328         } else if remaining_segments.len() > 1 {
329             // FIXME report error (ambiguous associated type)
330             (TyKind::Unknown.intern(&Interner), None)
331         } else {
332             (ty, res)
333         }
334     }
335
336     pub(crate) fn lower_partly_resolved_path(
337         &self,
338         resolution: TypeNs,
339         resolved_segment: PathSegment<'_>,
340         remaining_segments: PathSegments<'_>,
341         infer_args: bool,
342     ) -> (Ty, Option<TypeNs>) {
343         let ty = match resolution {
344             TypeNs::TraitId(trait_) => {
345                 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
346                 let self_ty = if remaining_segments.len() == 0 {
347                     Some(
348                         TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
349                             .intern(&Interner),
350                     )
351                 } else {
352                     None
353                 };
354                 let trait_ref =
355                     self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
356                 let ty = if remaining_segments.len() == 1 {
357                     let segment = remaining_segments.first().unwrap();
358                     let found = associated_type_by_name_including_super_traits(
359                         self.db,
360                         trait_ref,
361                         &segment.name,
362                     );
363                     match found {
364                         Some((super_trait_ref, associated_ty)) => {
365                             // FIXME handle type parameters on the segment
366                             TyKind::Alias(AliasTy::Projection(ProjectionTy {
367                                 associated_ty_id: to_assoc_type_id(associated_ty),
368                                 substitution: super_trait_ref.substitution,
369                             }))
370                             .intern(&Interner)
371                         }
372                         None => {
373                             // FIXME: report error (associated type not found)
374                             TyKind::Unknown.intern(&Interner)
375                         }
376                     }
377                 } else if remaining_segments.len() > 1 {
378                     // FIXME report error (ambiguous associated type)
379                     TyKind::Unknown.intern(&Interner)
380                 } else {
381                     let dyn_ty = DynTy {
382                         bounds: Binders::new(
383                             1,
384                             QuantifiedWhereClauses::from_iter(
385                                 &Interner,
386                                 Some(Binders::wrap_empty(WhereClause::Implemented(trait_ref))),
387                             ),
388                         ),
389                     };
390                     TyKind::Dyn(dyn_ty).intern(&Interner)
391                 };
392                 return (ty, None);
393             }
394             TypeNs::GenericParam(param_id) => {
395                 let generics = generics(
396                     self.db.upcast(),
397                     self.resolver.generic_def().expect("generics in scope"),
398                 );
399                 match self.type_param_mode {
400                     TypeParamLoweringMode::Placeholder => {
401                         TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
402                     }
403                     TypeParamLoweringMode::Variable => {
404                         let idx = generics.param_idx(param_id).expect("matching generics");
405                         TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
406                     }
407                 }
408                 .intern(&Interner)
409             }
410             TypeNs::SelfType(impl_id) => {
411                 let generics = generics(self.db.upcast(), impl_id.into());
412                 let substs = match self.type_param_mode {
413                     TypeParamLoweringMode::Placeholder => {
414                         Substitution::type_params_for_generics(self.db, &generics)
415                     }
416                     TypeParamLoweringMode::Variable => {
417                         Substitution::bound_vars(&generics, self.in_binders)
418                     }
419                 };
420                 self.db.impl_self_ty(impl_id).subst(&substs)
421             }
422             TypeNs::AdtSelfType(adt) => {
423                 let generics = generics(self.db.upcast(), adt.into());
424                 let substs = match self.type_param_mode {
425                     TypeParamLoweringMode::Placeholder => {
426                         Substitution::type_params_for_generics(self.db, &generics)
427                     }
428                     TypeParamLoweringMode::Variable => {
429                         Substitution::bound_vars(&generics, self.in_binders)
430                     }
431                 };
432                 self.db.ty(adt.into()).subst(&substs)
433             }
434
435             TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
436             TypeNs::BuiltinType(it) => {
437                 self.lower_path_inner(resolved_segment, it.into(), infer_args)
438             }
439             TypeNs::TypeAliasId(it) => {
440                 self.lower_path_inner(resolved_segment, it.into(), infer_args)
441             }
442             // FIXME: report error
443             TypeNs::EnumVariantId(_) => return (TyKind::Unknown.intern(&Interner), None),
444         };
445         self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
446     }
447
448     pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
449         // Resolve the path (in type namespace)
450         if let Some(type_ref) = path.type_anchor() {
451             let (ty, res) = self.lower_ty_ext(&type_ref);
452             return self.lower_ty_relative_path(ty, res, path.segments());
453         }
454         let (resolution, remaining_index) =
455             match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
456                 Some(it) => it,
457                 None => return (TyKind::Unknown.intern(&Interner), None),
458             };
459         let (resolved_segment, remaining_segments) = match remaining_index {
460             None => (
461                 path.segments().last().expect("resolved path has at least one element"),
462                 PathSegments::EMPTY,
463             ),
464             Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
465         };
466         self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
467     }
468
469     fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
470         if let Some(res) = res {
471             let ty = associated_type_shorthand_candidates(
472                 self.db,
473                 res,
474                 move |name, t, associated_ty| {
475                     if name == segment.name {
476                         let substs = match self.type_param_mode {
477                             TypeParamLoweringMode::Placeholder => {
478                                 // if we're lowering to placeholders, we have to put
479                                 // them in now
480                                 let s = Substitution::type_params(
481                                     self.db,
482                                     self.resolver.generic_def().expect(
483                                         "there should be generics if there's a generic param",
484                                     ),
485                                 );
486                                 t.substitution.clone().subst_bound_vars(&s)
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.shift_bound_vars(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::Unknown.intern(&Interner))
508         } else {
509             TyKind::Unknown.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).subst(&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::Unknown.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::Unknown.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(substs.clone().into());
629                     substs.push(default_ty.clone().subst(&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::Unknown.intern(&Interner));
638         }
639         assert_eq!(substs.len(), total_len);
640
641         Substitution(substs.into())
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         type_ref: &TypeRef,
671         explicit_self_ty: Option<Ty>,
672     ) -> Option<TraitRef> {
673         let path = match type_ref {
674             TypeRef::Path(path) => path,
675             _ => return None,
676         };
677         self.lower_trait_ref_from_path(path, explicit_self_ty)
678     }
679
680     fn trait_ref_substs_from_path(
681         &self,
682         segment: PathSegment<'_>,
683         resolved: TraitId,
684         explicit_self_ty: Option<Ty>,
685     ) -> Substitution {
686         self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty)
687     }
688
689     pub(crate) fn lower_where_predicate(
690         &'a self,
691         where_predicate: &'a WherePredicate,
692         ignore_bindings: bool,
693     ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
694         match where_predicate {
695             WherePredicate::ForLifetime { target, bound, .. }
696             | WherePredicate::TypeBound { target, bound } => {
697                 let self_ty = match target {
698                     WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
699                     WherePredicateTypeTarget::TypeParam(param_id) => {
700                         let generic_def = self.resolver.generic_def().expect("generics in scope");
701                         let generics = generics(self.db.upcast(), generic_def);
702                         let param_id =
703                             hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
704                         let placeholder = to_placeholder_idx(self.db, param_id);
705                         match self.type_param_mode {
706                             TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
707                             TypeParamLoweringMode::Variable => {
708                                 let idx = generics.param_idx(param_id).expect("matching generics");
709                                 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
710                             }
711                         }
712                         .intern(&Interner)
713                     }
714                 };
715                 self.lower_type_bound(bound, self_ty, ignore_bindings)
716                     .collect::<Vec<_>>()
717                     .into_iter()
718             }
719             WherePredicate::Lifetime { .. } => vec![].into_iter(),
720         }
721     }
722
723     pub(crate) fn lower_type_bound(
724         &'a self,
725         bound: &'a TypeBound,
726         self_ty: Ty,
727         ignore_bindings: bool,
728     ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
729         let mut bindings = None;
730         let trait_ref = match bound {
731             TypeBound::Path(path) => {
732                 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
733                 bindings.clone().map(WhereClause::Implemented).map(|b| Binders::wrap_empty(b))
734             }
735             TypeBound::Lifetime(_) => None,
736             TypeBound::Error => None,
737         };
738         trait_ref.into_iter().chain(
739             bindings
740                 .into_iter()
741                 .filter(move |_| !ignore_bindings)
742                 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
743         )
744     }
745
746     fn assoc_type_bindings_from_type_bound(
747         &'a self,
748         bound: &'a TypeBound,
749         trait_ref: TraitRef,
750     ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
751         let last_segment = match bound {
752             TypeBound::Path(path) => path.segments().last(),
753             TypeBound::Error | TypeBound::Lifetime(_) => None,
754         };
755         last_segment
756             .into_iter()
757             .flat_map(|segment| segment.args_and_bindings.into_iter())
758             .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
759             .flat_map(move |binding| {
760                 let found = associated_type_by_name_including_super_traits(
761                     self.db,
762                     trait_ref.clone(),
763                     &binding.name,
764                 );
765                 let (super_trait_ref, associated_ty) = match found {
766                     None => return SmallVec::<[QuantifiedWhereClause; 1]>::new(),
767                     Some(t) => t,
768                 };
769                 let projection_ty = ProjectionTy {
770                     associated_ty_id: to_assoc_type_id(associated_ty),
771                     substitution: super_trait_ref.substitution,
772                 };
773                 let mut preds = SmallVec::with_capacity(
774                     binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
775                 );
776                 if let Some(type_ref) = &binding.type_ref {
777                     let ty = self.lower_ty(type_ref);
778                     let alias_eq =
779                         AliasEq { alias: AliasTy::Projection(projection_ty.clone()), ty };
780                     preds.push(Binders::wrap_empty(WhereClause::AliasEq(alias_eq)));
781                 }
782                 for bound in &binding.bounds {
783                     preds.extend(self.lower_type_bound(
784                         bound,
785                         TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
786                         false,
787                     ));
788                 }
789                 preds
790             })
791     }
792
793     fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
794         cov_mark::hit!(lower_rpit);
795         let self_ty =
796             TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
797         let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
798             bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)).collect()
799         });
800         ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
801     }
802 }
803
804 fn count_impl_traits(type_ref: &TypeRef) -> usize {
805     let mut count = 0;
806     type_ref.walk(&mut |type_ref| {
807         if matches!(type_ref, TypeRef::ImplTrait(_)) {
808             count += 1;
809         }
810     });
811     count
812 }
813
814 /// Build the signature of a callable item (function, struct or enum variant).
815 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
816     match def {
817         CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
818         CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
819         CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
820     }
821 }
822
823 pub fn associated_type_shorthand_candidates<R>(
824     db: &dyn HirDatabase,
825     res: TypeNs,
826     mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
827 ) -> Option<R> {
828     let traits_from_env: Vec<_> = match res {
829         TypeNs::SelfType(impl_id) => match db.impl_trait(impl_id) {
830             None => vec![],
831             // FIXME: how to correctly handle higher-ranked bounds here?
832             Some(trait_ref) => vec![trait_ref.value.shift_bound_vars_out(DebruijnIndex::ONE)],
833         },
834         TypeNs::GenericParam(param_id) => {
835             let predicates = db.generic_predicates_for_param(param_id);
836             let mut traits_: Vec<_> = predicates
837                 .iter()
838                 .filter_map(|pred| match &pred.value.value {
839                     // FIXME: how to correctly handle higher-ranked bounds here?
840                     WhereClause::Implemented(tr) => {
841                         Some(tr.clone().shift_bound_vars_out(DebruijnIndex::ONE))
842                     }
843                     _ => None,
844                 })
845                 .collect();
846             // Handle `Self::Type` referring to own associated type in trait definitions
847             if let GenericDefId::TraitId(trait_id) = param_id.parent {
848                 let generics = generics(db.upcast(), trait_id.into());
849                 if generics.params.types[param_id.local_id].provenance
850                     == TypeParamProvenance::TraitSelf
851                 {
852                     let trait_ref = TraitRef {
853                         trait_id: to_chalk_trait_id(trait_id),
854                         substitution: Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST),
855                     };
856                     traits_.push(trait_ref);
857                 }
858             }
859             traits_
860         }
861         _ => vec![],
862     };
863
864     for t in traits_from_env.into_iter().flat_map(move |t| all_super_trait_refs(db, t)) {
865         let data = db.trait_data(t.hir_trait_id());
866
867         for (name, assoc_id) in &data.items {
868             match assoc_id {
869                 AssocItemId::TypeAliasId(alias) => {
870                     if let Some(result) = cb(name, &t, *alias) {
871                         return Some(result);
872                     }
873                 }
874                 AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => {}
875             }
876         }
877     }
878
879     None
880 }
881
882 /// Build the type of all specific fields of a struct or enum variant.
883 pub(crate) fn field_types_query(
884     db: &dyn HirDatabase,
885     variant_id: VariantId,
886 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
887     let var_data = variant_data(db.upcast(), variant_id);
888     let (resolver, def): (_, GenericDefId) = match variant_id {
889         VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
890         VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
891         VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
892     };
893     let generics = generics(db.upcast(), def);
894     let mut res = ArenaMap::default();
895     let ctx =
896         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
897     for (field_id, field_data) in var_data.fields().iter() {
898         res.insert(field_id, Binders::new(generics.len(), ctx.lower_ty(&field_data.type_ref)))
899     }
900     Arc::new(res)
901 }
902
903 /// This query exists only to be used when resolving short-hand associated types
904 /// like `T::Item`.
905 ///
906 /// See the analogous query in rustc and its comment:
907 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
908 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
909 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
910 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
911 pub(crate) fn generic_predicates_for_param_query(
912     db: &dyn HirDatabase,
913     param_id: TypeParamId,
914 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
915     let resolver = param_id.parent.resolver(db.upcast());
916     let ctx =
917         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
918     let generics = generics(db.upcast(), param_id.parent);
919     resolver
920         .where_predicates_in_scope()
921         // we have to filter out all other predicates *first*, before attempting to lower them
922         .filter(|pred| match pred {
923             WherePredicate::ForLifetime { target, .. }
924             | WherePredicate::TypeBound { target, .. } => match target {
925                 WherePredicateTypeTarget::TypeRef(type_ref) => {
926                     ctx.lower_ty_only_param(type_ref) == Some(param_id)
927                 }
928                 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
929             },
930             WherePredicate::Lifetime { .. } => false,
931         })
932         .flat_map(|pred| {
933             ctx.lower_where_predicate(pred, true).map(|p| Binders::new(generics.len(), p))
934         })
935         .collect()
936 }
937
938 pub(crate) fn generic_predicates_for_param_recover(
939     _db: &dyn HirDatabase,
940     _cycle: &[String],
941     _param_id: &TypeParamId,
942 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
943     Arc::new([])
944 }
945
946 pub(crate) fn trait_environment_query(
947     db: &dyn HirDatabase,
948     def: GenericDefId,
949 ) -> Arc<TraitEnvironment> {
950     let resolver = def.resolver(db.upcast());
951     let ctx = TyLoweringContext::new(db, &resolver)
952         .with_type_param_mode(TypeParamLoweringMode::Placeholder);
953     let mut traits_in_scope = Vec::new();
954     let mut clauses = Vec::new();
955     for pred in resolver.where_predicates_in_scope() {
956         for pred in ctx.lower_where_predicate(pred, false) {
957             if let WhereClause::Implemented(tr) = &pred.skip_binders() {
958                 traits_in_scope.push((tr.self_type_parameter().clone(), tr.hir_trait_id()));
959             }
960             let program_clause: chalk_ir::ProgramClause<Interner> =
961                 pred.clone().to_chalk(db).cast(&Interner);
962             clauses.push(program_clause.into_from_env_clause(&Interner));
963         }
964     }
965
966     let container: Option<AssocContainerId> = match def {
967         // FIXME: is there a function for this?
968         GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
969         GenericDefId::AdtId(_) => None,
970         GenericDefId::TraitId(_) => None,
971         GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
972         GenericDefId::ImplId(_) => None,
973         GenericDefId::EnumVariantId(_) => None,
974         GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
975     };
976     if let Some(AssocContainerId::TraitId(trait_id)) = container {
977         // add `Self: Trait<T1, T2, ...>` to the environment in trait
978         // function default implementations (and hypothetical code
979         // inside consts or type aliases)
980         cov_mark::hit!(trait_self_implements_self);
981         let substs = Substitution::type_params(db, trait_id);
982         let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs };
983         let pred = WhereClause::Implemented(trait_ref);
984         let program_clause: chalk_ir::ProgramClause<Interner> = pred.to_chalk(db).cast(&Interner);
985         clauses.push(program_clause.into_from_env_clause(&Interner));
986     }
987
988     let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
989
990     Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
991 }
992
993 /// Resolve the where clause(s) of an item with generics.
994 pub(crate) fn generic_predicates_query(
995     db: &dyn HirDatabase,
996     def: GenericDefId,
997 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
998     let resolver = def.resolver(db.upcast());
999     let ctx =
1000         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1001     let generics = generics(db.upcast(), def);
1002     resolver
1003         .where_predicates_in_scope()
1004         .flat_map(|pred| {
1005             ctx.lower_where_predicate(pred, false).map(|p| Binders::new(generics.len(), p))
1006         })
1007         .collect()
1008 }
1009
1010 /// Resolve the default type params from generics
1011 pub(crate) fn generic_defaults_query(
1012     db: &dyn HirDatabase,
1013     def: GenericDefId,
1014 ) -> Arc<[Binders<Ty>]> {
1015     let resolver = def.resolver(db.upcast());
1016     let ctx =
1017         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1018     let generic_params = generics(db.upcast(), def);
1019
1020     let defaults = generic_params
1021         .iter()
1022         .enumerate()
1023         .map(|(idx, (_, p))| {
1024             let mut ty =
1025                 p.default.as_ref().map_or(TyKind::Unknown.intern(&Interner), |t| ctx.lower_ty(t));
1026
1027             // Each default can only refer to previous parameters.
1028             ty.walk_mut_binders(
1029                 &mut |ty, binders| match ty.interned_mut() {
1030                     TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
1031                         if *index >= idx {
1032                             // type variable default referring to parameter coming
1033                             // after it. This is forbidden (FIXME: report
1034                             // diagnostic)
1035                             *ty = TyKind::Unknown.intern(&Interner);
1036                         }
1037                     }
1038                     _ => {}
1039                 },
1040                 DebruijnIndex::INNERMOST,
1041             );
1042
1043             Binders::new(idx, ty)
1044         })
1045         .collect();
1046
1047     defaults
1048 }
1049
1050 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1051     let data = db.function_data(def);
1052     let resolver = def.resolver(db.upcast());
1053     let ctx_params = TyLoweringContext::new(db, &resolver)
1054         .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1055         .with_type_param_mode(TypeParamLoweringMode::Variable);
1056     let params = data.params.iter().map(|tr| (&ctx_params).lower_ty(tr)).collect::<Vec<_>>();
1057     let ctx_ret = TyLoweringContext::new(db, &resolver)
1058         .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1059         .with_type_param_mode(TypeParamLoweringMode::Variable);
1060     let ret = (&ctx_ret).lower_ty(&data.ret_type);
1061     let generics = generics(db.upcast(), def.into());
1062     let num_binders = generics.len();
1063     Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs))
1064 }
1065
1066 /// Build the declared type of a function. This should not need to look at the
1067 /// function body.
1068 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1069     let generics = generics(db.upcast(), def.into());
1070     let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1071     Binders::new(
1072         substs.len(),
1073         TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1074     )
1075 }
1076
1077 /// Build the declared type of a const.
1078 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1079     let data = db.const_data(def);
1080     let generics = generics(db.upcast(), def.into());
1081     let resolver = def.resolver(db.upcast());
1082     let ctx =
1083         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1084
1085     Binders::new(generics.len(), ctx.lower_ty(&data.type_ref))
1086 }
1087
1088 /// Build the declared type of a static.
1089 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1090     let data = db.static_data(def);
1091     let resolver = def.resolver(db.upcast());
1092     let ctx = TyLoweringContext::new(db, &resolver);
1093
1094     Binders::new(0, ctx.lower_ty(&data.type_ref))
1095 }
1096
1097 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1098     let struct_data = db.struct_data(def);
1099     let fields = struct_data.variant_data.fields();
1100     let resolver = def.resolver(db.upcast());
1101     let ctx =
1102         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1103     let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1104     let ret = type_for_adt(db, def.into());
1105     Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1106 }
1107
1108 /// Build the type of a tuple struct constructor.
1109 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1110     let struct_data = db.struct_data(def);
1111     if let StructKind::Unit = struct_data.variant_data.kind() {
1112         return type_for_adt(db, def.into());
1113     }
1114     let generics = generics(db.upcast(), def.into());
1115     let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1116     Binders::new(
1117         substs.len(),
1118         TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1119     )
1120 }
1121
1122 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1123     let enum_data = db.enum_data(def.parent);
1124     let var_data = &enum_data.variants[def.local_id];
1125     let fields = var_data.variant_data.fields();
1126     let resolver = def.parent.resolver(db.upcast());
1127     let ctx =
1128         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1129     let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1130     let ret = type_for_adt(db, def.parent.into());
1131     Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1132 }
1133
1134 /// Build the type of a tuple enum variant constructor.
1135 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1136     let enum_data = db.enum_data(def.parent);
1137     let var_data = &enum_data.variants[def.local_id].variant_data;
1138     if let StructKind::Unit = var_data.kind() {
1139         return type_for_adt(db, def.parent.into());
1140     }
1141     let generics = generics(db.upcast(), def.parent.into());
1142     let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1143     Binders::new(
1144         substs.len(),
1145         TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1146     )
1147 }
1148
1149 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1150     let generics = generics(db.upcast(), adt.into());
1151     let substs = Substitution::bound_vars(&generics, DebruijnIndex::INNERMOST);
1152     Binders::new(substs.len(), Ty::adt_ty(adt, substs))
1153 }
1154
1155 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1156     let generics = generics(db.upcast(), t.into());
1157     let resolver = t.resolver(db.upcast());
1158     let ctx =
1159         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1160     if db.type_alias_data(t).is_extern {
1161         Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1162     } else {
1163         let type_ref = &db.type_alias_data(t).type_ref;
1164         let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error));
1165         Binders::new(generics.len(), inner)
1166     }
1167 }
1168
1169 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1170 pub enum CallableDefId {
1171     FunctionId(FunctionId),
1172     StructId(StructId),
1173     EnumVariantId(EnumVariantId),
1174 }
1175 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1176
1177 impl CallableDefId {
1178     pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1179         let db = db.upcast();
1180         match self {
1181             CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1182             CallableDefId::StructId(s) => s.lookup(db).container,
1183             CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1184         }
1185         .krate()
1186     }
1187 }
1188
1189 impl From<CallableDefId> for GenericDefId {
1190     fn from(def: CallableDefId) -> GenericDefId {
1191         match def {
1192             CallableDefId::FunctionId(f) => f.into(),
1193             CallableDefId::StructId(s) => s.into(),
1194             CallableDefId::EnumVariantId(e) => e.into(),
1195         }
1196     }
1197 }
1198
1199 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1200 pub enum TyDefId {
1201     BuiltinType(BuiltinType),
1202     AdtId(AdtId),
1203     TypeAliasId(TypeAliasId),
1204 }
1205 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1206
1207 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1208 pub enum ValueTyDefId {
1209     FunctionId(FunctionId),
1210     StructId(StructId),
1211     UnionId(UnionId),
1212     EnumVariantId(EnumVariantId),
1213     ConstId(ConstId),
1214     StaticId(StaticId),
1215 }
1216 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1217
1218 /// Build the declared type of an item. This depends on the namespace; e.g. for
1219 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1220 /// the constructor function `(usize) -> Foo` which lives in the values
1221 /// namespace.
1222 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1223     match def {
1224         TyDefId::BuiltinType(it) => Binders::new(0, Ty::builtin(it)),
1225         TyDefId::AdtId(it) => type_for_adt(db, it),
1226         TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1227     }
1228 }
1229
1230 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1231     let num_binders = match *def {
1232         TyDefId::BuiltinType(_) => 0,
1233         TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1234         TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1235     };
1236     Binders::new(num_binders, TyKind::Unknown.intern(&Interner))
1237 }
1238
1239 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1240     match def {
1241         ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1242         ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1243         ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1244         ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1245         ValueTyDefId::ConstId(it) => type_for_const(db, it),
1246         ValueTyDefId::StaticId(it) => type_for_static(db, it),
1247     }
1248 }
1249
1250 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1251     let impl_data = db.impl_data(impl_id);
1252     let resolver = impl_id.resolver(db.upcast());
1253     let generics = generics(db.upcast(), impl_id.into());
1254     let ctx =
1255         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1256     Binders::new(generics.len(), ctx.lower_ty(&impl_data.target_type))
1257 }
1258
1259 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1260     let parent_data = db.generic_params(def.parent);
1261     let data = &parent_data.consts[def.local_id];
1262     let resolver = def.parent.resolver(db.upcast());
1263     let ctx = TyLoweringContext::new(db, &resolver);
1264
1265     ctx.lower_ty(&data.ty)
1266 }
1267
1268 pub(crate) fn impl_self_ty_recover(
1269     db: &dyn HirDatabase,
1270     _cycle: &[String],
1271     impl_id: &ImplId,
1272 ) -> Binders<Ty> {
1273     let generics = generics(db.upcast(), (*impl_id).into());
1274     Binders::new(generics.len(), TyKind::Unknown.intern(&Interner))
1275 }
1276
1277 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1278     let impl_data = db.impl_data(impl_id);
1279     let resolver = impl_id.resolver(db.upcast());
1280     let ctx =
1281         TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1282     let self_ty = db.impl_self_ty(impl_id);
1283     let target_trait = impl_data.target_trait.as_ref()?;
1284     Some(Binders::new(self_ty.num_binders, ctx.lower_trait_ref(target_trait, Some(self_ty.value))?))
1285 }
1286
1287 pub(crate) fn return_type_impl_traits(
1288     db: &dyn HirDatabase,
1289     def: hir_def::FunctionId,
1290 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1291     // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1292     let data = db.function_data(def);
1293     let resolver = def.resolver(db.upcast());
1294     let ctx_ret = TyLoweringContext::new(db, &resolver)
1295         .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1296         .with_type_param_mode(TypeParamLoweringMode::Variable);
1297     let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1298     let generics = generics(db.upcast(), def.into());
1299     let num_binders = generics.len();
1300     let return_type_impl_traits =
1301         ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1302     if return_type_impl_traits.impl_traits.is_empty() {
1303         None
1304     } else {
1305         Some(Arc::new(Binders::new(num_binders, return_type_impl_traits)))
1306     }
1307 }
1308
1309 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1310     match m {
1311         hir_def::type_ref::Mutability::Shared => Mutability::Not,
1312         hir_def::type_ref::Mutability::Mut => Mutability::Mut,
1313     }
1314 }