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