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