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