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