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