1 //! Methods for lowering the HIR to types. There are two main cases here:
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.
7 //! This usually involves resolving names, collecting generic arguments etc.
8 use std::{iter, sync::Arc};
11 use chalk_ir::{cast::Cast, Mutability, Safety};
14 builtin_type::BuiltinType,
15 generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget},
16 path::{GenericArg, Path, PathSegment, PathSegments},
17 resolver::{HasResolver, Resolver, TypeNs},
18 type_ref::{TraitRef as HirTraitRef, TypeBound, TypeRef},
19 AdtId, AssocContainerId, AssocItemId, ConstId, ConstParamId, EnumId, EnumVariantId, FunctionId,
20 GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId,
21 TypeAliasId, TypeParamId, UnionId, VariantId,
23 use hir_expand::name::Name;
24 use la_arena::ArenaMap;
25 use smallvec::SmallVec;
30 to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx,
31 traits::chalk::{Interner, ToChalk},
33 all_super_trait_refs, associated_type_by_name_including_super_traits, generics,
34 variant_data, Generics,
36 AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig,
37 ImplTraitId, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause, QuantifiedWhereClauses,
38 ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution, TraitEnvironment, TraitRef, Ty,
39 TyBuilder, TyKind, TypeWalk, WhereClause,
43 pub struct TyLoweringContext<'a> {
44 pub db: &'a dyn HirDatabase,
45 pub resolver: &'a Resolver,
46 in_binders: DebruijnIndex,
47 /// Note: Conceptually, it's thinkable that we could be in a location where
48 /// some type params should be represented as placeholders, and others
49 /// should be converted to variables. I think in practice, this isn't
50 /// possible currently, so this should be fine for now.
51 pub type_param_mode: TypeParamLoweringMode,
52 pub impl_trait_mode: ImplTraitLoweringMode,
53 impl_trait_counter: std::cell::Cell<u16>,
54 /// When turning `impl Trait` into opaque types, we have to collect the
55 /// bounds at the same time to get the IDs correct (without becoming too
56 /// complicated). I don't like using interior mutability (as for the
57 /// counter), but I've tried and failed to make the lifetimes work for
58 /// passing around a `&mut TyLoweringContext`. The core problem is that
59 /// we're grouping the mutable data (the counter and this field) together
60 /// with the immutable context (the references to the DB and resolver).
61 /// Splitting this up would be a possible fix.
62 opaque_type_data: std::cell::RefCell<Vec<ReturnTypeImplTrait>>,
65 impl<'a> TyLoweringContext<'a> {
66 pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
67 let impl_trait_counter = std::cell::Cell::new(0);
68 let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
69 let type_param_mode = TypeParamLoweringMode::Placeholder;
70 let in_binders = DebruijnIndex::INNERMOST;
71 let opaque_type_data = std::cell::RefCell::new(Vec::new());
83 pub fn with_debruijn<T>(
85 debruijn: DebruijnIndex,
86 f: impl FnOnce(&TyLoweringContext) -> T,
88 let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new());
91 impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()),
92 opaque_type_data: std::cell::RefCell::new(opaque_ty_data_vec),
95 let result = f(&new_ctx);
96 self.impl_trait_counter.set(new_ctx.impl_trait_counter.get());
97 self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner());
101 pub fn with_shifted_in<T>(
103 debruijn: DebruijnIndex,
104 f: impl FnOnce(&TyLoweringContext) -> T,
106 self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
109 pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
110 Self { impl_trait_mode, ..self }
113 pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
114 Self { type_param_mode, ..self }
118 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
119 pub enum ImplTraitLoweringMode {
120 /// `impl Trait` gets lowered into an opaque type that doesn't unify with
121 /// anything except itself. This is used in places where values flow 'out',
122 /// i.e. for arguments of the function we're currently checking, and return
123 /// types of functions we're calling.
125 /// `impl Trait` gets lowered into a type variable. Used for argument
126 /// position impl Trait when inside the respective function, since it allows
127 /// us to support that without Chalk.
129 /// `impl Trait` gets lowered into a variable that can unify with some
130 /// type. This is used in places where values flow 'in', i.e. for arguments
131 /// of functions we're calling, and the return type of the function we're
132 /// currently checking.
134 /// `impl Trait` is disallowed and will be an error.
138 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
139 pub enum TypeParamLoweringMode {
144 impl<'a> TyLoweringContext<'a> {
145 pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
146 self.lower_ty_ext(type_ref).0
149 pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
151 let ty = match type_ref {
152 TypeRef::Never => TyKind::Never.intern(&Interner),
153 TypeRef::Tuple(inner) => {
154 let inner_tys = inner.iter().map(|tr| self.lower_ty(tr));
155 TyKind::Tuple(inner_tys.len(), Substitution::from_iter(&Interner, inner_tys))
158 TypeRef::Path(path) => {
159 let (ty, res_) = self.lower_path(path);
163 TypeRef::RawPtr(inner, mutability) => {
164 let inner_ty = self.lower_ty(inner);
165 TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
167 TypeRef::Array(inner) => {
168 let inner_ty = self.lower_ty(inner);
169 TyKind::Array(inner_ty).intern(&Interner)
171 TypeRef::Slice(inner) => {
172 let inner_ty = self.lower_ty(inner);
173 TyKind::Slice(inner_ty).intern(&Interner)
175 TypeRef::Reference(inner, _, mutability) => {
176 let inner_ty = self.lower_ty(inner);
177 TyKind::Ref(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
179 TypeRef::Placeholder => TyKind::Error.intern(&Interner),
180 TypeRef::Fn(params, is_varargs) => {
182 Substitution::from_iter(&Interner, params.iter().map(|tr| self.lower_ty(tr)));
183 TyKind::Function(FnPointer {
184 num_args: substs.len(&Interner) - 1,
185 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
190 TypeRef::DynTrait(bounds) => {
192 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
193 let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
194 QuantifiedWhereClauses::from_iter(
196 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)),
199 let bounds = crate::make_only_type_binders(1, bounds);
200 TyKind::Dyn(DynTy { bounds }).intern(&Interner)
202 TypeRef::ImplTrait(bounds) => {
203 match self.impl_trait_mode {
204 ImplTraitLoweringMode::Opaque => {
205 let idx = self.impl_trait_counter.get();
206 self.impl_trait_counter.set(idx + 1);
208 assert!(idx as usize == self.opaque_type_data.borrow().len());
209 // this dance is to make sure the data is in the right
210 // place even if we encounter more opaque types while
211 // lowering the bounds
212 self.opaque_type_data.borrow_mut().push(ReturnTypeImplTrait {
213 bounds: crate::make_only_type_binders(1, Vec::new()),
215 // We don't want to lower the bounds inside the binders
216 // we're currently in, because they don't end up inside
217 // those binders. E.g. when we have `impl Trait<impl
218 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
219 // to the self parameter from `impl Trait`, and the
220 // bounds aren't actually stored nested within each
221 // other, but separately. So if the `T` refers to a type
222 // parameter of the outer function, it's just one binder
223 // away instead of two.
224 let actual_opaque_type_data = self
225 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
226 ctx.lower_impl_trait(&bounds)
228 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
230 let func = match self.resolver.generic_def() {
231 Some(GenericDefId::FunctionId(f)) => f,
232 _ => panic!("opaque impl trait lowering in non-function"),
234 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
235 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
236 let generics = generics(self.db.upcast(), func.into());
237 let parameters = generics.bound_vars_subst(self.in_binders);
238 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
240 substitution: parameters,
244 ImplTraitLoweringMode::Param => {
245 let idx = self.impl_trait_counter.get();
246 // FIXME we're probably doing something wrong here
247 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
248 if let Some(def) = self.resolver.generic_def() {
249 let generics = generics(self.db.upcast(), def);
252 .filter(|(_, data)| {
253 data.provenance == TypeParamProvenance::ArgumentImplTrait
256 .map_or(TyKind::Error, |(id, _)| {
257 TyKind::Placeholder(to_placeholder_idx(self.db, id))
259 param.intern(&Interner)
261 TyKind::Error.intern(&Interner)
264 ImplTraitLoweringMode::Variable => {
265 let idx = self.impl_trait_counter.get();
266 // FIXME we're probably doing something wrong here
267 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
268 let (parent_params, self_params, list_params, _impl_trait_params) =
269 if let Some(def) = self.resolver.generic_def() {
270 let generics = generics(self.db.upcast(), def);
271 generics.provenance_split()
275 TyKind::BoundVar(BoundVar::new(
277 idx as usize + parent_params + self_params + list_params,
281 ImplTraitLoweringMode::Disallowed => {
282 // FIXME: report error
283 TyKind::Error.intern(&Interner)
287 TypeRef::Error => TyKind::Error.intern(&Interner),
292 /// This is only for `generic_predicates_for_param`, where we can't just
293 /// lower the self types of the predicates since that could lead to cycles.
294 /// So we just check here if the `type_ref` resolves to a generic param, and which.
295 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
296 let path = match type_ref {
297 TypeRef::Path(path) => path,
300 if path.type_anchor().is_some() {
303 if path.segments().len() > 1 {
307 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
308 Some((it, None)) => it,
311 if let TypeNs::GenericParam(param_id) = resolution {
318 pub(crate) fn lower_ty_relative_path(
321 // We need the original resolution to lower `Self::AssocTy` correctly
323 remaining_segments: PathSegments<'_>,
324 ) -> (Ty, Option<TypeNs>) {
325 if remaining_segments.len() == 1 {
326 // resolve unselected assoc types
327 let segment = remaining_segments.first().unwrap();
328 (self.select_associated_type(res, segment), None)
329 } else if remaining_segments.len() > 1 {
330 // FIXME report error (ambiguous associated type)
331 (TyKind::Error.intern(&Interner), None)
337 pub(crate) fn lower_partly_resolved_path(
340 resolved_segment: PathSegment<'_>,
341 remaining_segments: PathSegments<'_>,
343 ) -> (Ty, Option<TypeNs>) {
344 let ty = match resolution {
345 TypeNs::TraitId(trait_) => {
346 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
347 let self_ty = if remaining_segments.len() == 0 {
349 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
356 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
357 let ty = if remaining_segments.len() == 1 {
358 let segment = remaining_segments.first().unwrap();
359 let found = associated_type_by_name_including_super_traits(
365 Some((super_trait_ref, associated_ty)) => {
366 // FIXME handle type parameters on the segment
367 TyKind::Alias(AliasTy::Projection(ProjectionTy {
368 associated_ty_id: to_assoc_type_id(associated_ty),
369 substitution: super_trait_ref.substitution,
374 // FIXME: report error (associated type not found)
375 TyKind::Error.intern(&Interner)
378 } else if remaining_segments.len() > 1 {
379 // FIXME report error (ambiguous associated type)
380 TyKind::Error.intern(&Interner)
383 bounds: crate::make_only_type_binders(
385 QuantifiedWhereClauses::from_iter(
387 Some(Binders::wrap_empty(WhereClause::Implemented(trait_ref))),
391 TyKind::Dyn(dyn_ty).intern(&Interner)
395 TypeNs::GenericParam(param_id) => {
396 let generics = generics(
398 self.resolver.generic_def().expect("generics in scope"),
400 match self.type_param_mode {
401 TypeParamLoweringMode::Placeholder => {
402 TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
404 TypeParamLoweringMode::Variable => {
405 let idx = generics.param_idx(param_id).expect("matching generics");
406 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
411 TypeNs::SelfType(impl_id) => {
412 let generics = generics(self.db.upcast(), impl_id.into());
413 let substs = match self.type_param_mode {
414 TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
415 TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
417 self.db.impl_self_ty(impl_id).subst(&substs)
419 TypeNs::AdtSelfType(adt) => {
420 let generics = generics(self.db.upcast(), adt.into());
421 let substs = match self.type_param_mode {
422 TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
423 TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
425 self.db.ty(adt.into()).subst(&substs)
428 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
429 TypeNs::BuiltinType(it) => {
430 self.lower_path_inner(resolved_segment, it.into(), infer_args)
432 TypeNs::TypeAliasId(it) => {
433 self.lower_path_inner(resolved_segment, it.into(), infer_args)
435 // FIXME: report error
436 TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(&Interner), None),
438 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
441 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
442 // Resolve the path (in type namespace)
443 if let Some(type_ref) = path.type_anchor() {
444 let (ty, res) = self.lower_ty_ext(&type_ref);
445 return self.lower_ty_relative_path(ty, res, path.segments());
447 let (resolution, remaining_index) =
448 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
450 None => return (TyKind::Error.intern(&Interner), None),
452 let (resolved_segment, remaining_segments) = match remaining_index {
454 path.segments().last().expect("resolved path has at least one element"),
457 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
459 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
462 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
463 if let Some(res) = res {
464 let ty = associated_type_shorthand_candidates(
467 move |name, t, associated_ty| {
468 if name == segment.name {
469 let substs = match self.type_param_mode {
470 TypeParamLoweringMode::Placeholder => {
471 // if we're lowering to placeholders, we have to put
473 let generics = generics(
475 self.resolver.generic_def().expect(
476 "there should be generics if there's a generic param",
479 let s = generics.type_params_subst(self.db);
480 t.substitution.clone().subst_bound_vars(&s)
482 TypeParamLoweringMode::Variable => t.substitution.clone(),
484 // We need to shift in the bound vars, since
485 // associated_type_shorthand_candidates does not do that
486 let substs = substs.shift_bound_vars(self.in_binders);
487 // FIXME handle type parameters on the segment
489 TyKind::Alias(AliasTy::Projection(ProjectionTy {
490 associated_ty_id: to_assoc_type_id(associated_ty),
491 substitution: substs,
501 ty.unwrap_or(TyKind::Error.intern(&Interner))
503 TyKind::Error.intern(&Interner)
509 segment: PathSegment<'_>,
513 let generic_def = match typeable {
514 TyDefId::BuiltinType(_) => None,
515 TyDefId::AdtId(it) => Some(it.into()),
516 TyDefId::TypeAliasId(it) => Some(it.into()),
518 let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None);
519 self.db.ty(typeable).subst(&substs)
522 /// Collect generic arguments from a path into a `Substs`. See also
523 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
524 pub(super) fn substs_from_path(
527 // Note that we don't call `db.value_type(resolved)` here,
528 // `ValueTyDefId` is just a convenient way to pass generics and
529 // special-case enum variants
530 resolved: ValueTyDefId,
533 let last = path.segments().last().expect("path should have at least one segment");
534 let (segment, generic_def) = match resolved {
535 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
536 ValueTyDefId::StructId(it) => (last, Some(it.into())),
537 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
538 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
539 ValueTyDefId::StaticId(_) => (last, None),
540 ValueTyDefId::EnumVariantId(var) => {
541 // the generic args for an enum variant may be either specified
542 // on the segment referring to the enum, or on the segment
543 // referring to the variant. So `Option::<T>::None` and
544 // `Option::None::<T>` are both allowed (though the former is
545 // preferred). See also `def_ids_for_path_segments` in rustc.
546 let len = path.segments().len();
547 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
548 let segment = match penultimate {
549 Some(segment) if segment.args_and_bindings.is_some() => segment,
552 (segment, Some(var.parent.into()))
555 self.substs_from_path_segment(segment, generic_def, infer_args, None)
558 fn substs_from_path_segment(
560 segment: PathSegment<'_>,
561 def_generic: Option<GenericDefId>,
563 explicit_self_ty: Option<Ty>,
565 let mut substs = Vec::new();
566 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
568 let (parent_params, self_params, type_params, impl_trait_params) =
569 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
570 let total_len = parent_params + self_params + type_params + impl_trait_params;
572 substs.extend(iter::repeat(TyKind::Error.intern(&Interner)).take(parent_params));
574 let fill_self_params = || {
578 .chain(iter::repeat(TyKind::Error.intern(&Interner)))
582 let mut had_explicit_type_args = false;
584 if let Some(generic_args) = &segment.args_and_bindings {
585 if !generic_args.has_self_type {
589 if generic_args.has_self_type { self_params + type_params } else { type_params };
590 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
591 // if args are provided, it should be all of them, but we can't rely on that
592 for arg in generic_args
595 .filter(|arg| matches!(arg, GenericArg::Type(_)))
600 GenericArg::Type(type_ref) => {
601 had_explicit_type_args = true;
602 let ty = self.lower_ty(type_ref);
605 GenericArg::Lifetime(_) => {}
612 // handle defaults. In expression or pattern path segments without
613 // explicitly specified type arguments, missing type arguments are inferred
614 // (i.e. defaults aren't used).
615 if !infer_args || had_explicit_type_args {
616 if let Some(def_generic) = def_generic {
617 let defaults = self.db.generic_defaults(def_generic);
618 assert_eq!(total_len, defaults.len());
620 for default_ty in defaults.iter().skip(substs.len()) {
621 // each default can depend on the previous parameters
622 let substs_so_far = Substitution::from_iter(&Interner, substs.clone());
623 substs.push(default_ty.clone().subst(&substs_so_far));
628 // add placeholders for args that were not provided
629 // FIXME: emit diagnostics in contexts where this is not allowed
630 for _ in substs.len()..total_len {
631 substs.push(TyKind::Error.intern(&Interner));
633 assert_eq!(substs.len(), total_len);
635 Substitution::from_iter(&Interner, substs)
638 fn lower_trait_ref_from_path(
641 explicit_self_ty: Option<Ty>,
642 ) -> Option<TraitRef> {
644 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
645 TypeNs::TraitId(tr) => tr,
648 let segment = path.segments().last().expect("path should have at least one segment");
649 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
652 pub(crate) fn lower_trait_ref_from_resolved_path(
655 segment: PathSegment<'_>,
656 explicit_self_ty: Option<Ty>,
658 let substs = self.trait_ref_substs_from_path(segment, resolved, explicit_self_ty);
659 TraitRef { trait_id: to_chalk_trait_id(resolved), substitution: substs }
664 trait_ref: &HirTraitRef,
665 explicit_self_ty: Option<Ty>,
666 ) -> Option<TraitRef> {
667 self.lower_trait_ref_from_path(&trait_ref.path, explicit_self_ty)
670 fn trait_ref_substs_from_path(
672 segment: PathSegment<'_>,
674 explicit_self_ty: Option<Ty>,
676 self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty)
679 pub(crate) fn lower_where_predicate(
681 where_predicate: &'a WherePredicate,
682 ignore_bindings: bool,
683 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
684 match where_predicate {
685 WherePredicate::ForLifetime { target, bound, .. }
686 | WherePredicate::TypeBound { target, bound } => {
687 let self_ty = match target {
688 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
689 WherePredicateTypeTarget::TypeParam(param_id) => {
690 let generic_def = self.resolver.generic_def().expect("generics in scope");
691 let generics = generics(self.db.upcast(), generic_def);
693 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
694 let placeholder = to_placeholder_idx(self.db, param_id);
695 match self.type_param_mode {
696 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
697 TypeParamLoweringMode::Variable => {
698 let idx = generics.param_idx(param_id).expect("matching generics");
699 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
705 self.lower_type_bound(bound, self_ty, ignore_bindings)
709 WherePredicate::Lifetime { .. } => vec![].into_iter(),
713 pub(crate) fn lower_type_bound(
715 bound: &'a TypeBound,
717 ignore_bindings: bool,
718 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
719 let mut bindings = None;
720 let trait_ref = match bound {
721 TypeBound::Path(path) => {
722 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
723 bindings.clone().map(WhereClause::Implemented).map(|b| Binders::wrap_empty(b))
725 TypeBound::Lifetime(_) => None,
726 TypeBound::Error => None,
728 trait_ref.into_iter().chain(
731 .filter(move |_| !ignore_bindings)
732 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
736 fn assoc_type_bindings_from_type_bound(
738 bound: &'a TypeBound,
740 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
741 let last_segment = match bound {
742 TypeBound::Path(path) => path.segments().last(),
743 TypeBound::Error | TypeBound::Lifetime(_) => None,
747 .flat_map(|segment| segment.args_and_bindings.into_iter())
748 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
749 .flat_map(move |binding| {
750 let found = associated_type_by_name_including_super_traits(
755 let (super_trait_ref, associated_ty) = match found {
756 None => return SmallVec::<[QuantifiedWhereClause; 1]>::new(),
759 let projection_ty = ProjectionTy {
760 associated_ty_id: to_assoc_type_id(associated_ty),
761 substitution: super_trait_ref.substitution,
763 let mut preds = SmallVec::with_capacity(
764 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
766 if let Some(type_ref) = &binding.type_ref {
767 let ty = self.lower_ty(type_ref);
769 AliasEq { alias: AliasTy::Projection(projection_ty.clone()), ty };
770 preds.push(Binders::wrap_empty(WhereClause::AliasEq(alias_eq)));
772 for bound in &binding.bounds {
773 preds.extend(self.lower_type_bound(
775 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
783 fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
784 cov_mark::hit!(lower_rpit);
786 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
787 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
788 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)).collect()
790 ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, predicates) }
794 fn count_impl_traits(type_ref: &TypeRef) -> usize {
796 type_ref.walk(&mut |type_ref| {
797 if matches!(type_ref, TypeRef::ImplTrait(_)) {
804 /// Build the signature of a callable item (function, struct or enum variant).
805 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
807 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
808 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
809 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
813 pub fn associated_type_shorthand_candidates<R>(
814 db: &dyn HirDatabase,
816 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
818 let mut search = |t| {
819 for t in all_super_trait_refs(db, t) {
820 let data = db.trait_data(t.hir_trait_id());
822 for (name, assoc_id) in &data.items {
823 if let AssocItemId::TypeAliasId(alias) = assoc_id {
824 if let Some(result) = cb(name, &t, *alias) {
834 // FIXME: how to correctly handle higher-ranked bounds here?
835 TypeNs::SelfType(impl_id) => search(
836 db.impl_trait(impl_id)?
837 .into_value_and_skipped_binders()
839 .shift_bound_vars_out(DebruijnIndex::ONE),
841 TypeNs::GenericParam(param_id) => {
842 let predicates = db.generic_predicates_for_param(param_id);
843 let res = predicates.iter().find_map(|pred| match pred.skip_binders().skip_binders() {
844 // FIXME: how to correctly handle higher-ranked bounds here?
845 WhereClause::Implemented(tr) => {
846 search(tr.clone().shift_bound_vars_out(DebruijnIndex::ONE))
850 if let res @ Some(_) = res {
853 // Handle `Self::Type` referring to own associated type in trait definitions
854 if let GenericDefId::TraitId(trait_id) = param_id.parent {
855 let generics = generics(db.upcast(), trait_id.into());
856 if generics.params.types[param_id.local_id].provenance
857 == TypeParamProvenance::TraitSelf
859 let trait_ref = TyBuilder::trait_ref(db, trait_id)
860 .fill_with_bound_vars(DebruijnIndex::INNERMOST, 0)
862 return search(trait_ref);
871 /// Build the type of all specific fields of a struct or enum variant.
872 pub(crate) fn field_types_query(
873 db: &dyn HirDatabase,
874 variant_id: VariantId,
875 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
876 let var_data = variant_data(db.upcast(), variant_id);
877 let (resolver, def): (_, GenericDefId) = match variant_id {
878 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
879 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
880 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
882 let generics = generics(db.upcast(), def);
883 let mut res = ArenaMap::default();
885 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
886 for (field_id, field_data) in var_data.fields().iter() {
887 res.insert(field_id, make_binders(&generics, ctx.lower_ty(&field_data.type_ref)))
892 /// This query exists only to be used when resolving short-hand associated types
895 /// See the analogous query in rustc and its comment:
896 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
897 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
898 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
899 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
900 pub(crate) fn generic_predicates_for_param_query(
901 db: &dyn HirDatabase,
902 param_id: TypeParamId,
903 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
904 let resolver = param_id.parent.resolver(db.upcast());
906 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
907 let generics = generics(db.upcast(), param_id.parent);
909 .where_predicates_in_scope()
910 // we have to filter out all other predicates *first*, before attempting to lower them
911 .filter(|pred| match pred {
912 WherePredicate::ForLifetime { target, .. }
913 | WherePredicate::TypeBound { target, .. } => match target {
914 WherePredicateTypeTarget::TypeRef(type_ref) => {
915 ctx.lower_ty_only_param(type_ref) == Some(param_id)
917 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
919 WherePredicate::Lifetime { .. } => false,
921 .flat_map(|pred| ctx.lower_where_predicate(pred, true).map(|p| make_binders(&generics, p)))
925 pub(crate) fn generic_predicates_for_param_recover(
926 _db: &dyn HirDatabase,
928 _param_id: &TypeParamId,
929 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
933 pub(crate) fn trait_environment_query(
934 db: &dyn HirDatabase,
936 ) -> Arc<TraitEnvironment> {
937 let resolver = def.resolver(db.upcast());
938 let ctx = TyLoweringContext::new(db, &resolver)
939 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
940 let mut traits_in_scope = Vec::new();
941 let mut clauses = Vec::new();
942 for pred in resolver.where_predicates_in_scope() {
943 for pred in ctx.lower_where_predicate(pred, false) {
944 if let WhereClause::Implemented(tr) = &pred.skip_binders() {
946 .push((tr.self_type_parameter(&Interner).clone(), tr.hir_trait_id()));
948 let program_clause: chalk_ir::ProgramClause<Interner> =
949 pred.clone().to_chalk(db).cast(&Interner);
950 clauses.push(program_clause.into_from_env_clause(&Interner));
954 let container: Option<AssocContainerId> = match def {
955 // FIXME: is there a function for this?
956 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
957 GenericDefId::AdtId(_) => None,
958 GenericDefId::TraitId(_) => None,
959 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
960 GenericDefId::ImplId(_) => None,
961 GenericDefId::EnumVariantId(_) => None,
962 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
964 if let Some(AssocContainerId::TraitId(trait_id)) = container {
965 // add `Self: Trait<T1, T2, ...>` to the environment in trait
966 // function default implementations (and hypothetical code
967 // inside consts or type aliases)
968 cov_mark::hit!(trait_self_implements_self);
969 let substs = TyBuilder::type_params_subst(db, trait_id);
970 let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs };
971 let pred = WhereClause::Implemented(trait_ref);
972 let program_clause: chalk_ir::ProgramClause<Interner> = pred.to_chalk(db).cast(&Interner);
973 clauses.push(program_clause.into_from_env_clause(&Interner));
976 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
978 Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
981 /// Resolve the where clause(s) of an item with generics.
982 pub(crate) fn generic_predicates_query(
983 db: &dyn HirDatabase,
985 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
986 let resolver = def.resolver(db.upcast());
988 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
989 let generics = generics(db.upcast(), def);
991 .where_predicates_in_scope()
992 .flat_map(|pred| ctx.lower_where_predicate(pred, false).map(|p| make_binders(&generics, p)))
996 /// Resolve the default type params from generics
997 pub(crate) fn generic_defaults_query(
998 db: &dyn HirDatabase,
1000 ) -> Arc<[Binders<Ty>]> {
1001 let resolver = def.resolver(db.upcast());
1003 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1004 let generic_params = generics(db.upcast(), def);
1006 let defaults = generic_params
1009 .map(|(idx, (_, p))| {
1011 p.default.as_ref().map_or(TyKind::Error.intern(&Interner), |t| ctx.lower_ty(t));
1013 // Each default can only refer to previous parameters.
1014 ty.walk_mut_binders(
1015 &mut |ty, binders| match ty.interned_mut() {
1016 TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
1018 // type variable default referring to parameter coming
1019 // after it. This is forbidden (FIXME: report
1021 *ty = TyKind::Error.intern(&Interner);
1026 DebruijnIndex::INNERMOST,
1029 crate::make_only_type_binders(idx, ty)
1036 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1037 let data = db.function_data(def);
1038 let resolver = def.resolver(db.upcast());
1039 let ctx_params = TyLoweringContext::new(db, &resolver)
1040 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1041 .with_type_param_mode(TypeParamLoweringMode::Variable);
1042 let params = data.params.iter().map(|tr| ctx_params.lower_ty(tr)).collect::<Vec<_>>();
1043 let ctx_ret = TyLoweringContext::new(db, &resolver)
1044 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1045 .with_type_param_mode(TypeParamLoweringMode::Variable);
1046 let ret = ctx_ret.lower_ty(&data.ret_type);
1047 let generics = generics(db.upcast(), def.into());
1048 make_binders(&generics, CallableSig::from_params_and_return(params, ret, data.is_varargs()))
1051 /// Build the declared type of a function. This should not need to look at the
1053 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1054 let generics = generics(db.upcast(), def.into());
1055 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1058 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1062 /// Build the declared type of a const.
1063 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1064 let data = db.const_data(def);
1065 let generics = generics(db.upcast(), def.into());
1066 let resolver = def.resolver(db.upcast());
1068 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1070 make_binders(&generics, ctx.lower_ty(&data.type_ref))
1073 /// Build the declared type of a static.
1074 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1075 let data = db.static_data(def);
1076 let resolver = def.resolver(db.upcast());
1077 let ctx = TyLoweringContext::new(db, &resolver);
1079 Binders::empty(&Interner, ctx.lower_ty(&data.type_ref))
1082 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1083 let struct_data = db.struct_data(def);
1084 let fields = struct_data.variant_data.fields();
1085 let resolver = def.resolver(db.upcast());
1087 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1088 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1089 let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders();
1090 Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1093 /// Build the type of a tuple struct constructor.
1094 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1095 let struct_data = db.struct_data(def);
1096 if let StructKind::Unit = struct_data.variant_data.kind() {
1097 return type_for_adt(db, def.into());
1099 let generics = generics(db.upcast(), def.into());
1100 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1103 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1107 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1108 let enum_data = db.enum_data(def.parent);
1109 let var_data = &enum_data.variants[def.local_id];
1110 let fields = var_data.variant_data.fields();
1111 let resolver = def.parent.resolver(db.upcast());
1113 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1114 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1115 let (ret, binders) = type_for_adt(db, def.parent.into()).into_value_and_skipped_binders();
1116 Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1119 /// Build the type of a tuple enum variant constructor.
1120 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1121 let enum_data = db.enum_data(def.parent);
1122 let var_data = &enum_data.variants[def.local_id].variant_data;
1123 if let StructKind::Unit = var_data.kind() {
1124 return type_for_adt(db, def.parent.into());
1126 let generics = generics(db.upcast(), def.parent.into());
1127 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1130 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1134 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1135 let generics = generics(db.upcast(), adt.into());
1136 let b = TyBuilder::adt(db, adt);
1137 let ty = b.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0).build();
1138 make_binders(&generics, ty)
1141 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1142 let generics = generics(db.upcast(), t.into());
1143 let resolver = t.resolver(db.upcast());
1145 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1146 if db.type_alias_data(t).is_extern {
1147 Binders::empty(&Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(&Interner))
1149 let type_ref = &db.type_alias_data(t).type_ref;
1150 let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error));
1151 make_binders(&generics, inner)
1155 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1156 pub enum CallableDefId {
1157 FunctionId(FunctionId),
1159 EnumVariantId(EnumVariantId),
1161 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1163 impl CallableDefId {
1164 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1165 let db = db.upcast();
1167 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1168 CallableDefId::StructId(s) => s.lookup(db).container,
1169 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1175 impl From<CallableDefId> for GenericDefId {
1176 fn from(def: CallableDefId) -> GenericDefId {
1178 CallableDefId::FunctionId(f) => f.into(),
1179 CallableDefId::StructId(s) => s.into(),
1180 CallableDefId::EnumVariantId(e) => e.into(),
1185 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1187 BuiltinType(BuiltinType),
1189 TypeAliasId(TypeAliasId),
1191 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1193 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1194 pub enum ValueTyDefId {
1195 FunctionId(FunctionId),
1198 EnumVariantId(EnumVariantId),
1202 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1204 /// Build the declared type of an item. This depends on the namespace; e.g. for
1205 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1206 /// the constructor function `(usize) -> Foo` which lives in the values
1208 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1210 TyDefId::BuiltinType(it) => Binders::empty(&Interner, TyBuilder::builtin(it)),
1211 TyDefId::AdtId(it) => type_for_adt(db, it),
1212 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1216 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1217 let generics = match *def {
1218 TyDefId::BuiltinType(_) => {
1219 return Binders::empty(&Interner, TyKind::Error.intern(&Interner))
1221 TyDefId::AdtId(it) => generics(db.upcast(), it.into()),
1222 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()),
1224 make_binders(&generics, TyKind::Error.intern(&Interner))
1227 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1229 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1230 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1231 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1232 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1233 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1234 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1238 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1239 let impl_data = db.impl_data(impl_id);
1240 let resolver = impl_id.resolver(db.upcast());
1241 let generics = generics(db.upcast(), impl_id.into());
1243 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1244 make_binders(&generics, ctx.lower_ty(&impl_data.self_ty))
1247 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1248 let parent_data = db.generic_params(def.parent);
1249 let data = &parent_data.consts[def.local_id];
1250 let resolver = def.parent.resolver(db.upcast());
1251 let ctx = TyLoweringContext::new(db, &resolver);
1253 ctx.lower_ty(&data.ty)
1256 pub(crate) fn impl_self_ty_recover(
1257 db: &dyn HirDatabase,
1261 let generics = generics(db.upcast(), (*impl_id).into());
1262 make_binders(&generics, TyKind::Error.intern(&Interner))
1265 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1266 let impl_data = db.impl_data(impl_id);
1267 let resolver = impl_id.resolver(db.upcast());
1269 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1270 let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders();
1271 let target_trait = impl_data.target_trait.as_ref()?;
1272 Some(Binders::new(binders, ctx.lower_trait_ref(target_trait, Some(self_ty))?))
1275 pub(crate) fn return_type_impl_traits(
1276 db: &dyn HirDatabase,
1277 def: hir_def::FunctionId,
1278 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1279 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1280 let data = db.function_data(def);
1281 let resolver = def.resolver(db.upcast());
1282 let ctx_ret = TyLoweringContext::new(db, &resolver)
1283 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1284 .with_type_param_mode(TypeParamLoweringMode::Variable);
1285 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1286 let generics = generics(db.upcast(), def.into());
1287 let return_type_impl_traits =
1288 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1289 if return_type_impl_traits.impl_traits.is_empty() {
1292 Some(Arc::new(make_binders(&generics, return_type_impl_traits)))
1296 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1298 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1299 hir_def::type_ref::Mutability::Mut => Mutability::Mut,
1303 fn make_binders<T>(generics: &Generics, value: T) -> Binders<T> {
1304 crate::make_only_type_binders(generics.len(), value)