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