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