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