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