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};
14 builtin_type::BuiltinType,
15 generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget},
16 path::{GenericArg, Path, PathSegment, PathSegments},
17 resolver::{HasResolver, Resolver, TypeNs},
18 type_ref::{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_placeholder_idx,
31 traits::chalk::{Interner, ToChalk},
33 all_super_trait_refs, associated_type_by_name_including_super_traits, generics,
34 make_mut_slice, variant_data,
36 AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, FnPointer, FnSig, GenericPredicate,
37 ImplTraitId, OpaqueTy, PolyFnSig, ProjectionPredicate, ProjectionTy, ReturnTypeImplTrait,
38 ReturnTypeImplTraits, Substs, TraitEnvironment, TraitRef, Ty, TyKind, TypeWalk,
42 pub struct TyLoweringContext<'a> {
43 pub db: &'a dyn HirDatabase,
44 pub resolver: &'a Resolver,
45 in_binders: DebruijnIndex,
46 /// Note: Conceptually, it's thinkable that we could be in a location where
47 /// some type params should be represented as placeholders, and others
48 /// should be converted to variables. I think in practice, this isn't
49 /// possible currently, so this should be fine for now.
50 pub type_param_mode: TypeParamLoweringMode,
51 pub impl_trait_mode: ImplTraitLoweringMode,
52 impl_trait_counter: std::cell::Cell<u16>,
53 /// When turning `impl Trait` into opaque types, we have to collect the
54 /// bounds at the same time to get the IDs correct (without becoming too
55 /// complicated). I don't like using interior mutability (as for the
56 /// counter), but I've tried and failed to make the lifetimes work for
57 /// passing around a `&mut TyLoweringContext`. The core problem is that
58 /// we're grouping the mutable data (the counter and this field) together
59 /// with the immutable context (the references to the DB and resolver).
60 /// Splitting this up would be a possible fix.
61 opaque_type_data: std::cell::RefCell<Vec<ReturnTypeImplTrait>>,
64 impl<'a> TyLoweringContext<'a> {
65 pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
66 let impl_trait_counter = std::cell::Cell::new(0);
67 let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
68 let type_param_mode = TypeParamLoweringMode::Placeholder;
69 let in_binders = DebruijnIndex::INNERMOST;
70 let opaque_type_data = std::cell::RefCell::new(Vec::new());
82 pub fn with_debruijn<T>(
84 debruijn: DebruijnIndex,
85 f: impl FnOnce(&TyLoweringContext) -> T,
87 let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new());
90 impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()),
91 opaque_type_data: std::cell::RefCell::new(opaque_ty_data_vec),
94 let result = f(&new_ctx);
95 self.impl_trait_counter.set(new_ctx.impl_trait_counter.get());
96 self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner());
100 pub fn with_shifted_in<T>(
102 debruijn: DebruijnIndex,
103 f: impl FnOnce(&TyLoweringContext) -> T,
105 self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
108 pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
109 Self { impl_trait_mode, ..self }
112 pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
113 Self { type_param_mode, ..self }
117 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
118 pub enum ImplTraitLoweringMode {
119 /// `impl Trait` gets lowered into an opaque type that doesn't unify with
120 /// anything except itself. This is used in places where values flow 'out',
121 /// i.e. for arguments of the function we're currently checking, and return
122 /// types of functions we're calling.
124 /// `impl Trait` gets lowered into a type variable. Used for argument
125 /// position impl Trait when inside the respective function, since it allows
126 /// us to support that without Chalk.
128 /// `impl Trait` gets lowered into a variable that can unify with some
129 /// type. This is used in places where values flow 'in', i.e. for arguments
130 /// of functions we're calling, and the return type of the function we're
131 /// currently checking.
133 /// `impl Trait` is disallowed and will be an error.
137 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
138 pub enum TypeParamLoweringMode {
143 impl<'a> TyLoweringContext<'a> {
144 pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
145 self.lower_ty_ext(type_ref).0
148 fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
150 let ty = match type_ref {
151 TypeRef::Never => TyKind::Never.intern(&Interner),
152 TypeRef::Tuple(inner) => {
153 let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| self.lower_ty(tr)).collect();
154 TyKind::Tuple(inner_tys.len(), Substs(inner_tys)).intern(&Interner)
156 TypeRef::Path(path) => {
157 let (ty, res_) = self.lower_path(path);
161 TypeRef::RawPtr(inner, mutability) => {
162 let inner_ty = self.lower_ty(inner);
163 TyKind::Raw(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty))
166 TypeRef::Array(inner) => {
167 let inner_ty = self.lower_ty(inner);
168 TyKind::Array(Substs::single(inner_ty)).intern(&Interner)
170 TypeRef::Slice(inner) => {
171 let inner_ty = self.lower_ty(inner);
172 TyKind::Slice(Substs::single(inner_ty)).intern(&Interner)
174 TypeRef::Reference(inner, _, mutability) => {
175 let inner_ty = self.lower_ty(inner);
176 TyKind::Ref(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty))
179 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
180 TypeRef::Fn(params, is_varargs) => {
181 let substs = Substs(params.iter().map(|tr| self.lower_ty(tr)).collect());
182 TyKind::Function(FnPointer {
183 num_args: substs.len() - 1,
184 sig: FnSig { variadic: *is_varargs },
189 TypeRef::DynTrait(bounds) => {
191 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
192 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
193 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
195 TyKind::Dyn(predicates).intern(&Interner)
197 TypeRef::ImplTrait(bounds) => {
198 match self.impl_trait_mode {
199 ImplTraitLoweringMode::Opaque => {
200 let idx = self.impl_trait_counter.get();
201 self.impl_trait_counter.set(idx + 1);
203 assert!(idx as usize == self.opaque_type_data.borrow().len());
204 // this dance is to make sure the data is in the right
205 // place even if we encounter more opaque types while
206 // lowering the bounds
207 self.opaque_type_data
209 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
210 // We don't want to lower the bounds inside the binders
211 // we're currently in, because they don't end up inside
212 // those binders. E.g. when we have `impl Trait<impl
213 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
214 // to the self parameter from `impl Trait`, and the
215 // bounds aren't actually stored nested within each
216 // other, but separately. So if the `T` refers to a type
217 // parameter of the outer function, it's just one binder
218 // away instead of two.
219 let actual_opaque_type_data = self
220 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
221 ctx.lower_impl_trait(&bounds)
223 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
225 let func = match self.resolver.generic_def() {
226 Some(GenericDefId::FunctionId(f)) => f,
227 _ => panic!("opaque impl trait lowering in non-function"),
229 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
230 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
231 let generics = generics(self.db.upcast(), func.into());
232 let parameters = Substs::bound_vars(&generics, self.in_binders);
233 TyKind::Alias(AliasTy::Opaque(OpaqueTy { opaque_ty_id, parameters }))
236 ImplTraitLoweringMode::Param => {
237 let idx = self.impl_trait_counter.get();
238 // FIXME we're probably doing something wrong here
239 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
240 if let Some(def) = self.resolver.generic_def() {
241 let generics = generics(self.db.upcast(), def);
244 .filter(|(_, data)| {
245 data.provenance == TypeParamProvenance::ArgumentImplTrait
248 .map_or(TyKind::Unknown, |(id, _)| {
249 TyKind::Placeholder(to_placeholder_idx(self.db, id))
251 param.intern(&Interner)
253 TyKind::Unknown.intern(&Interner)
256 ImplTraitLoweringMode::Variable => {
257 let idx = self.impl_trait_counter.get();
258 // FIXME we're probably doing something wrong here
259 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
260 let (parent_params, self_params, list_params, _impl_trait_params) =
261 if let Some(def) = self.resolver.generic_def() {
262 let generics = generics(self.db.upcast(), def);
263 generics.provenance_split()
267 TyKind::BoundVar(BoundVar::new(
269 idx as usize + parent_params + self_params + list_params,
273 ImplTraitLoweringMode::Disallowed => {
274 // FIXME: report error
275 TyKind::Unknown.intern(&Interner)
279 TypeRef::Error => TyKind::Unknown.intern(&Interner),
284 /// This is only for `generic_predicates_for_param`, where we can't just
285 /// lower the self types of the predicates since that could lead to cycles.
286 /// So we just check here if the `type_ref` resolves to a generic param, and which.
287 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
288 let path = match type_ref {
289 TypeRef::Path(path) => path,
292 if path.type_anchor().is_some() {
295 if path.segments().len() > 1 {
299 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
300 Some((it, None)) => it,
303 if let TypeNs::GenericParam(param_id) = resolution {
310 pub(crate) fn lower_ty_relative_path(
313 // We need the original resolution to lower `Self::AssocTy` correctly
315 remaining_segments: PathSegments<'_>,
316 ) -> (Ty, Option<TypeNs>) {
317 if remaining_segments.len() == 1 {
318 // resolve unselected assoc types
319 let segment = remaining_segments.first().unwrap();
320 (self.select_associated_type(res, segment), None)
321 } else if remaining_segments.len() > 1 {
322 // FIXME report error (ambiguous associated type)
323 (TyKind::Unknown.intern(&Interner), None)
329 pub(crate) fn lower_partly_resolved_path(
332 resolved_segment: PathSegment<'_>,
333 remaining_segments: PathSegments<'_>,
335 ) -> (Ty, Option<TypeNs>) {
336 let ty = match resolution {
337 TypeNs::TraitId(trait_) => {
338 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
339 let self_ty = if remaining_segments.len() == 0 {
341 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
348 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
349 let ty = if remaining_segments.len() == 1 {
350 let segment = remaining_segments.first().unwrap();
351 let found = associated_type_by_name_including_super_traits(
357 Some((super_trait_ref, associated_ty)) => {
358 // FIXME handle type parameters on the segment
359 TyKind::Alias(AliasTy::Projection(ProjectionTy {
360 associated_ty_id: to_assoc_type_id(associated_ty),
361 substitution: super_trait_ref.substs,
366 // FIXME: report error (associated type not found)
367 TyKind::Unknown.intern(&Interner)
370 } else if remaining_segments.len() > 1 {
371 // FIXME report error (ambiguous associated type)
372 TyKind::Unknown.intern(&Interner)
374 TyKind::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)]))
379 TypeNs::GenericParam(param_id) => {
380 let generics = generics(
382 self.resolver.generic_def().expect("generics in scope"),
384 match self.type_param_mode {
385 TypeParamLoweringMode::Placeholder => {
386 TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
388 TypeParamLoweringMode::Variable => {
389 let idx = generics.param_idx(param_id).expect("matching generics");
390 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
395 TypeNs::SelfType(impl_id) => {
396 let generics = generics(self.db.upcast(), impl_id.into());
397 let substs = match self.type_param_mode {
398 TypeParamLoweringMode::Placeholder => {
399 Substs::type_params_for_generics(self.db, &generics)
401 TypeParamLoweringMode::Variable => {
402 Substs::bound_vars(&generics, self.in_binders)
405 self.db.impl_self_ty(impl_id).subst(&substs)
407 TypeNs::AdtSelfType(adt) => {
408 let generics = generics(self.db.upcast(), adt.into());
409 let substs = match self.type_param_mode {
410 TypeParamLoweringMode::Placeholder => {
411 Substs::type_params_for_generics(self.db, &generics)
413 TypeParamLoweringMode::Variable => {
414 Substs::bound_vars(&generics, self.in_binders)
417 self.db.ty(adt.into()).subst(&substs)
420 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
421 TypeNs::BuiltinType(it) => {
422 self.lower_path_inner(resolved_segment, it.into(), infer_args)
424 TypeNs::TypeAliasId(it) => {
425 self.lower_path_inner(resolved_segment, it.into(), infer_args)
427 // FIXME: report error
428 TypeNs::EnumVariantId(_) => return (TyKind::Unknown.intern(&Interner), None),
430 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
433 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
434 // Resolve the path (in type namespace)
435 if let Some(type_ref) = path.type_anchor() {
436 let (ty, res) = self.lower_ty_ext(&type_ref);
437 return self.lower_ty_relative_path(ty, res, path.segments());
439 let (resolution, remaining_index) =
440 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
442 None => return (TyKind::Unknown.intern(&Interner), None),
444 let (resolved_segment, remaining_segments) = match remaining_index {
446 path.segments().last().expect("resolved path has at least one element"),
449 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
451 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
454 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
455 if let Some(res) = res {
456 let ty = associated_type_shorthand_candidates(
459 move |name, t, associated_ty| {
460 if name == segment.name {
461 let substs = match self.type_param_mode {
462 TypeParamLoweringMode::Placeholder => {
463 // if we're lowering to placeholders, we have to put
465 let s = Substs::type_params(
467 self.resolver.generic_def().expect(
468 "there should be generics if there's a generic param",
471 t.substs.clone().subst_bound_vars(&s)
473 TypeParamLoweringMode::Variable => t.substs.clone(),
475 // We need to shift in the bound vars, since
476 // associated_type_shorthand_candidates does not do that
477 let substs = substs.shift_bound_vars(self.in_binders);
478 // FIXME handle type parameters on the segment
480 TyKind::Alias(AliasTy::Projection(ProjectionTy {
481 associated_ty_id: to_assoc_type_id(associated_ty),
482 substitution: substs,
492 ty.unwrap_or(TyKind::Unknown.intern(&Interner))
494 TyKind::Unknown.intern(&Interner)
500 segment: PathSegment<'_>,
504 let generic_def = match typeable {
505 TyDefId::BuiltinType(_) => None,
506 TyDefId::AdtId(it) => Some(it.into()),
507 TyDefId::TypeAliasId(it) => Some(it.into()),
509 let substs = self.substs_from_path_segment(segment, generic_def, infer_args);
510 self.db.ty(typeable).subst(&substs)
513 /// Collect generic arguments from a path into a `Substs`. See also
514 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
515 pub(super) fn substs_from_path(
518 // Note that we don't call `db.value_type(resolved)` here,
519 // `ValueTyDefId` is just a convenient way to pass generics and
520 // special-case enum variants
521 resolved: ValueTyDefId,
524 let last = path.segments().last().expect("path should have at least one segment");
525 let (segment, generic_def) = match resolved {
526 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
527 ValueTyDefId::StructId(it) => (last, Some(it.into())),
528 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
529 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
530 ValueTyDefId::StaticId(_) => (last, None),
531 ValueTyDefId::EnumVariantId(var) => {
532 // the generic args for an enum variant may be either specified
533 // on the segment referring to the enum, or on the segment
534 // referring to the variant. So `Option::<T>::None` and
535 // `Option::None::<T>` are both allowed (though the former is
536 // preferred). See also `def_ids_for_path_segments` in rustc.
537 let len = path.segments().len();
538 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
539 let segment = match penultimate {
540 Some(segment) if segment.args_and_bindings.is_some() => segment,
543 (segment, Some(var.parent.into()))
546 self.substs_from_path_segment(segment, generic_def, infer_args)
549 fn substs_from_path_segment(
551 segment: PathSegment<'_>,
552 def_generic: Option<GenericDefId>,
555 let mut substs = Vec::new();
556 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
558 let (parent_params, self_params, type_params, impl_trait_params) =
559 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
560 let total_len = parent_params + self_params + type_params + impl_trait_params;
562 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(parent_params));
564 let mut had_explicit_type_args = false;
566 if let Some(generic_args) = &segment.args_and_bindings {
567 if !generic_args.has_self_type {
568 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(self_params));
571 if generic_args.has_self_type { self_params + type_params } else { type_params };
572 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
573 // if args are provided, it should be all of them, but we can't rely on that
574 for arg in generic_args
577 .filter(|arg| matches!(arg, GenericArg::Type(_)))
582 GenericArg::Type(type_ref) => {
583 had_explicit_type_args = true;
584 let ty = self.lower_ty(type_ref);
587 GenericArg::Lifetime(_) => {}
592 // handle defaults. In expression or pattern path segments without
593 // explicitly specified type arguments, missing type arguments are inferred
594 // (i.e. defaults aren't used).
595 if !infer_args || had_explicit_type_args {
596 if let Some(def_generic) = def_generic {
597 let defaults = self.db.generic_defaults(def_generic);
598 assert_eq!(total_len, defaults.len());
600 for default_ty in defaults.iter().skip(substs.len()) {
601 // each default can depend on the previous parameters
602 let substs_so_far = Substs(substs.clone().into());
603 substs.push(default_ty.clone().subst(&substs_so_far));
608 // add placeholders for args that were not provided
609 // FIXME: emit diagnostics in contexts where this is not allowed
610 for _ in substs.len()..total_len {
611 substs.push(TyKind::Unknown.intern(&Interner));
613 assert_eq!(substs.len(), total_len);
615 Substs(substs.into())
618 fn lower_trait_ref_from_path(
621 explicit_self_ty: Option<Ty>,
622 ) -> Option<TraitRef> {
624 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
625 TypeNs::TraitId(tr) => tr,
628 let segment = path.segments().last().expect("path should have at least one segment");
629 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
632 pub(crate) fn lower_trait_ref_from_resolved_path(
635 segment: PathSegment<'_>,
636 explicit_self_ty: Option<Ty>,
638 let mut substs = self.trait_ref_substs_from_path(segment, resolved);
639 if let Some(self_ty) = explicit_self_ty {
640 make_mut_slice(&mut substs.0)[0] = self_ty;
642 TraitRef { trait_: resolved, substs }
648 explicit_self_ty: Option<Ty>,
649 ) -> Option<TraitRef> {
650 let path = match type_ref {
651 TypeRef::Path(path) => path,
654 self.lower_trait_ref_from_path(path, explicit_self_ty)
657 fn trait_ref_substs_from_path(&self, segment: PathSegment<'_>, resolved: TraitId) -> Substs {
658 self.substs_from_path_segment(segment, Some(resolved.into()), false)
661 pub(crate) fn lower_where_predicate(
663 where_predicate: &'a WherePredicate,
664 ) -> impl Iterator<Item = GenericPredicate> + 'a {
665 match where_predicate {
666 WherePredicate::ForLifetime { target, bound, .. }
667 | WherePredicate::TypeBound { target, bound } => {
668 let self_ty = match target {
669 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
670 WherePredicateTypeTarget::TypeParam(param_id) => {
671 let generic_def = self.resolver.generic_def().expect("generics in scope");
672 let generics = generics(self.db.upcast(), generic_def);
674 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
675 let placeholder = to_placeholder_idx(self.db, param_id);
676 match self.type_param_mode {
677 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
678 TypeParamLoweringMode::Variable => {
679 let idx = generics.param_idx(param_id).expect("matching generics");
680 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
686 self.lower_type_bound(bound, self_ty).collect::<Vec<_>>().into_iter()
688 WherePredicate::Lifetime { .. } => vec![].into_iter(),
692 pub(crate) fn lower_type_bound(
694 bound: &'a TypeBound,
696 ) -> impl Iterator<Item = GenericPredicate> + 'a {
697 let mut bindings = None;
698 let trait_ref = match bound {
699 TypeBound::Path(path) => {
700 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
702 bindings.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented),
705 TypeBound::Lifetime(_) => None,
706 TypeBound::Error => Some(GenericPredicate::Error),
708 trait_ref.into_iter().chain(
711 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
715 fn assoc_type_bindings_from_type_bound(
717 bound: &'a TypeBound,
719 ) -> impl Iterator<Item = GenericPredicate> + 'a {
720 let last_segment = match bound {
721 TypeBound::Path(path) => path.segments().last(),
722 TypeBound::Error | TypeBound::Lifetime(_) => None,
726 .flat_map(|segment| segment.args_and_bindings.into_iter())
727 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
728 .flat_map(move |binding| {
729 let found = associated_type_by_name_including_super_traits(
734 let (super_trait_ref, associated_ty) = match found {
735 None => return SmallVec::<[GenericPredicate; 1]>::new(),
738 let projection_ty = ProjectionTy {
739 associated_ty_id: to_assoc_type_id(associated_ty),
740 substitution: super_trait_ref.substs,
742 let mut preds = SmallVec::with_capacity(
743 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
745 if let Some(type_ref) = &binding.type_ref {
746 let ty = self.lower_ty(type_ref);
747 let projection_predicate =
748 ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
749 preds.push(GenericPredicate::Projection(projection_predicate));
751 for bound in &binding.bounds {
752 preds.extend(self.lower_type_bound(
754 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
761 fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
762 cov_mark::hit!(lower_rpit);
764 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
765 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
766 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
768 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
772 fn count_impl_traits(type_ref: &TypeRef) -> usize {
774 type_ref.walk(&mut |type_ref| {
775 if matches!(type_ref, TypeRef::ImplTrait(_)) {
782 /// Build the signature of a callable item (function, struct or enum variant).
783 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
785 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
786 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
787 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
791 pub fn associated_type_shorthand_candidates<R>(
792 db: &dyn HirDatabase,
794 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
796 let traits_from_env: Vec<_> = match res {
797 TypeNs::SelfType(impl_id) => match db.impl_trait(impl_id) {
799 Some(trait_ref) => vec![trait_ref.value],
801 TypeNs::GenericParam(param_id) => {
802 let predicates = db.generic_predicates_for_param(param_id);
803 let mut traits_: Vec<_> = predicates
805 .filter_map(|pred| match &pred.value {
806 GenericPredicate::Implemented(tr) => Some(tr.clone()),
810 // Handle `Self::Type` referring to own associated type in trait definitions
811 if let GenericDefId::TraitId(trait_id) = param_id.parent {
812 let generics = generics(db.upcast(), trait_id.into());
813 if generics.params.types[param_id.local_id].provenance
814 == TypeParamProvenance::TraitSelf
816 let trait_ref = TraitRef {
818 substs: Substs::bound_vars(&generics, DebruijnIndex::INNERMOST),
820 traits_.push(trait_ref);
828 for t in traits_from_env.into_iter().flat_map(move |t| all_super_trait_refs(db, t)) {
829 let data = db.trait_data(t.trait_);
831 for (name, assoc_id) in &data.items {
833 AssocItemId::TypeAliasId(alias) => {
834 if let Some(result) = cb(name, &t, *alias) {
838 AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => {}
846 /// Build the type of all specific fields of a struct or enum variant.
847 pub(crate) fn field_types_query(
848 db: &dyn HirDatabase,
849 variant_id: VariantId,
850 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
851 let var_data = variant_data(db.upcast(), variant_id);
852 let (resolver, def): (_, GenericDefId) = match variant_id {
853 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
854 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
855 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
857 let generics = generics(db.upcast(), def);
858 let mut res = ArenaMap::default();
860 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
861 for (field_id, field_data) in var_data.fields().iter() {
862 res.insert(field_id, Binders::new(generics.len(), ctx.lower_ty(&field_data.type_ref)))
867 /// This query exists only to be used when resolving short-hand associated types
870 /// See the analogous query in rustc and its comment:
871 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
872 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
873 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
874 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
875 pub(crate) fn generic_predicates_for_param_query(
876 db: &dyn HirDatabase,
877 param_id: TypeParamId,
878 ) -> Arc<[Binders<GenericPredicate>]> {
879 let resolver = param_id.parent.resolver(db.upcast());
881 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
882 let generics = generics(db.upcast(), param_id.parent);
884 .where_predicates_in_scope()
885 // we have to filter out all other predicates *first*, before attempting to lower them
886 .filter(|pred| match pred {
887 WherePredicate::ForLifetime { target, .. }
888 | WherePredicate::TypeBound { target, .. } => match target {
889 WherePredicateTypeTarget::TypeRef(type_ref) => {
890 ctx.lower_ty_only_param(type_ref) == Some(param_id)
892 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
894 WherePredicate::Lifetime { .. } => false,
896 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
900 pub(crate) fn generic_predicates_for_param_recover(
901 _db: &dyn HirDatabase,
903 _param_id: &TypeParamId,
904 ) -> Arc<[Binders<GenericPredicate>]> {
908 pub(crate) fn trait_environment_query(
909 db: &dyn HirDatabase,
911 ) -> Arc<TraitEnvironment> {
912 let resolver = def.resolver(db.upcast());
913 let ctx = TyLoweringContext::new(db, &resolver)
914 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
915 let mut traits_in_scope = Vec::new();
916 let mut clauses = Vec::new();
917 for pred in resolver.where_predicates_in_scope() {
918 for pred in ctx.lower_where_predicate(pred) {
922 if let GenericPredicate::Implemented(tr) = &pred {
923 traits_in_scope.push((tr.self_ty().clone(), tr.trait_));
925 let program_clause: chalk_ir::ProgramClause<Interner> =
926 pred.clone().to_chalk(db).cast(&Interner);
927 clauses.push(program_clause.into_from_env_clause(&Interner));
931 let container: Option<AssocContainerId> = match def {
932 // FIXME: is there a function for this?
933 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
934 GenericDefId::AdtId(_) => None,
935 GenericDefId::TraitId(_) => None,
936 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
937 GenericDefId::ImplId(_) => None,
938 GenericDefId::EnumVariantId(_) => None,
939 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
941 if let Some(AssocContainerId::TraitId(trait_id)) = container {
942 // add `Self: Trait<T1, T2, ...>` to the environment in trait
943 // function default implementations (and hypothetical code
944 // inside consts or type aliases)
945 cov_mark::hit!(trait_self_implements_self);
946 let substs = Substs::type_params(db, trait_id);
947 let trait_ref = TraitRef { trait_: trait_id, substs };
948 let pred = GenericPredicate::Implemented(trait_ref);
949 let program_clause: chalk_ir::ProgramClause<Interner> =
950 pred.clone().to_chalk(db).cast(&Interner);
951 clauses.push(program_clause.into_from_env_clause(&Interner));
954 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
956 Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
959 /// Resolve the where clause(s) of an item with generics.
960 pub(crate) fn generic_predicates_query(
961 db: &dyn HirDatabase,
963 ) -> Arc<[Binders<GenericPredicate>]> {
964 let resolver = def.resolver(db.upcast());
966 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
967 let generics = generics(db.upcast(), def);
969 .where_predicates_in_scope()
970 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
974 /// Resolve the default type params from generics
975 pub(crate) fn generic_defaults_query(
976 db: &dyn HirDatabase,
978 ) -> Arc<[Binders<Ty>]> {
979 let resolver = def.resolver(db.upcast());
981 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
982 let generic_params = generics(db.upcast(), def);
984 let defaults = generic_params
987 .map(|(idx, (_, p))| {
989 p.default.as_ref().map_or(TyKind::Unknown.intern(&Interner), |t| ctx.lower_ty(t));
991 // Each default can only refer to previous parameters.
993 &mut |ty, binders| match &mut ty.0 {
994 TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
996 // type variable default referring to parameter coming
997 // after it. This is forbidden (FIXME: report
999 *ty = TyKind::Unknown.intern(&Interner);
1004 DebruijnIndex::INNERMOST,
1007 Binders::new(idx, ty)
1014 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1015 let data = db.function_data(def);
1016 let resolver = def.resolver(db.upcast());
1017 let ctx_params = TyLoweringContext::new(db, &resolver)
1018 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1019 .with_type_param_mode(TypeParamLoweringMode::Variable);
1020 let params = data.params.iter().map(|tr| (&ctx_params).lower_ty(tr)).collect::<Vec<_>>();
1021 let ctx_ret = TyLoweringContext::new(db, &resolver)
1022 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1023 .with_type_param_mode(TypeParamLoweringMode::Variable);
1024 let ret = (&ctx_ret).lower_ty(&data.ret_type);
1025 let generics = generics(db.upcast(), def.into());
1026 let num_binders = generics.len();
1027 Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs))
1030 /// Build the declared type of a function. This should not need to look at the
1032 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1033 let generics = generics(db.upcast(), def.into());
1034 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1037 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1041 /// Build the declared type of a const.
1042 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1043 let data = db.const_data(def);
1044 let generics = generics(db.upcast(), def.into());
1045 let resolver = def.resolver(db.upcast());
1047 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1049 Binders::new(generics.len(), ctx.lower_ty(&data.type_ref))
1052 /// Build the declared type of a static.
1053 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1054 let data = db.static_data(def);
1055 let resolver = def.resolver(db.upcast());
1056 let ctx = TyLoweringContext::new(db, &resolver);
1058 Binders::new(0, ctx.lower_ty(&data.type_ref))
1061 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1062 let struct_data = db.struct_data(def);
1063 let fields = struct_data.variant_data.fields();
1064 let resolver = def.resolver(db.upcast());
1066 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1067 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1068 let ret = type_for_adt(db, def.into());
1069 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1072 /// Build the type of a tuple struct constructor.
1073 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1074 let struct_data = db.struct_data(def);
1075 if let StructKind::Unit = struct_data.variant_data.kind() {
1076 return type_for_adt(db, def.into());
1078 let generics = generics(db.upcast(), def.into());
1079 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1082 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1086 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1087 let enum_data = db.enum_data(def.parent);
1088 let var_data = &enum_data.variants[def.local_id];
1089 let fields = var_data.variant_data.fields();
1090 let resolver = def.parent.resolver(db.upcast());
1092 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1093 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1094 let ret = type_for_adt(db, def.parent.into());
1095 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1098 /// Build the type of a tuple enum variant constructor.
1099 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1100 let enum_data = db.enum_data(def.parent);
1101 let var_data = &enum_data.variants[def.local_id].variant_data;
1102 if let StructKind::Unit = var_data.kind() {
1103 return type_for_adt(db, def.parent.into());
1105 let generics = generics(db.upcast(), def.parent.into());
1106 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1109 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1113 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1114 let generics = generics(db.upcast(), adt.into());
1115 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1116 Binders::new(substs.len(), Ty::adt_ty(adt, substs))
1119 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1120 let generics = generics(db.upcast(), t.into());
1121 let resolver = t.resolver(db.upcast());
1123 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1124 if db.type_alias_data(t).is_extern {
1125 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1127 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1128 let type_ref = &db.type_alias_data(t).type_ref;
1129 let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error));
1130 Binders::new(substs.len(), inner)
1134 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1135 pub enum CallableDefId {
1136 FunctionId(FunctionId),
1138 EnumVariantId(EnumVariantId),
1140 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1142 impl CallableDefId {
1143 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1144 let db = db.upcast();
1146 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1147 CallableDefId::StructId(s) => s.lookup(db).container,
1148 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1154 impl From<CallableDefId> for GenericDefId {
1155 fn from(def: CallableDefId) -> GenericDefId {
1157 CallableDefId::FunctionId(f) => f.into(),
1158 CallableDefId::StructId(s) => s.into(),
1159 CallableDefId::EnumVariantId(e) => e.into(),
1164 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1166 BuiltinType(BuiltinType),
1168 TypeAliasId(TypeAliasId),
1170 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1172 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1173 pub enum ValueTyDefId {
1174 FunctionId(FunctionId),
1177 EnumVariantId(EnumVariantId),
1181 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1183 /// Build the declared type of an item. This depends on the namespace; e.g. for
1184 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1185 /// the constructor function `(usize) -> Foo` which lives in the values
1187 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1189 TyDefId::BuiltinType(it) => Binders::new(0, Ty::builtin(it)),
1190 TyDefId::AdtId(it) => type_for_adt(db, it),
1191 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1195 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1196 let num_binders = match *def {
1197 TyDefId::BuiltinType(_) => 0,
1198 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1199 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1201 Binders::new(num_binders, TyKind::Unknown.intern(&Interner))
1204 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1206 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1207 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1208 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1209 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1210 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1211 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1215 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1216 let impl_data = db.impl_data(impl_id);
1217 let resolver = impl_id.resolver(db.upcast());
1218 let generics = generics(db.upcast(), impl_id.into());
1220 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1221 Binders::new(generics.len(), ctx.lower_ty(&impl_data.target_type))
1224 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1225 let parent_data = db.generic_params(def.parent);
1226 let data = &parent_data.consts[def.local_id];
1227 let resolver = def.parent.resolver(db.upcast());
1228 let ctx = TyLoweringContext::new(db, &resolver);
1230 ctx.lower_ty(&data.ty)
1233 pub(crate) fn impl_self_ty_recover(
1234 db: &dyn HirDatabase,
1238 let generics = generics(db.upcast(), (*impl_id).into());
1239 Binders::new(generics.len(), TyKind::Unknown.intern(&Interner))
1242 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1243 let impl_data = db.impl_data(impl_id);
1244 let resolver = impl_id.resolver(db.upcast());
1246 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1247 let self_ty = db.impl_self_ty(impl_id);
1248 let target_trait = impl_data.target_trait.as_ref()?;
1249 Some(Binders::new(self_ty.num_binders, ctx.lower_trait_ref(target_trait, Some(self_ty.value))?))
1252 pub(crate) fn return_type_impl_traits(
1253 db: &dyn HirDatabase,
1254 def: hir_def::FunctionId,
1255 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1256 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1257 let data = db.function_data(def);
1258 let resolver = def.resolver(db.upcast());
1259 let ctx_ret = TyLoweringContext::new(db, &resolver)
1260 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1261 .with_type_param_mode(TypeParamLoweringMode::Variable);
1262 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1263 let generics = generics(db.upcast(), def.into());
1264 let num_binders = generics.len();
1265 let return_type_impl_traits =
1266 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1267 if return_type_impl_traits.impl_traits.is_empty() {
1270 Some(Arc::new(Binders::new(num_binders, return_type_impl_traits)))
1274 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1276 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1277 hir_def::type_ref::Mutability::Mut => Mutability::Mut,