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