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