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