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::{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), inner_ty).intern(&Interner)
165 TypeRef::Array(inner) => {
166 let inner_ty = self.lower_ty(inner);
167 TyKind::Array(inner_ty).intern(&Interner)
169 TypeRef::Slice(inner) => {
170 let inner_ty = self.lower_ty(inner);
171 TyKind::Slice(inner_ty).intern(&Interner)
173 TypeRef::Reference(inner, _, mutability) => {
174 let inner_ty = self.lower_ty(inner);
175 TyKind::Ref(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
177 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
178 TypeRef::Fn(params, is_varargs) => {
179 let substs = Substs(params.iter().map(|tr| self.lower_ty(tr)).collect());
180 TyKind::Function(FnPointer {
181 num_args: substs.len() - 1,
182 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
187 TypeRef::DynTrait(bounds) => {
189 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
190 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
191 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
193 TyKind::Dyn(predicates).intern(&Interner)
195 TypeRef::ImplTrait(bounds) => {
196 match self.impl_trait_mode {
197 ImplTraitLoweringMode::Opaque => {
198 let idx = self.impl_trait_counter.get();
199 self.impl_trait_counter.set(idx + 1);
201 assert!(idx as usize == self.opaque_type_data.borrow().len());
202 // this dance is to make sure the data is in the right
203 // place even if we encounter more opaque types while
204 // lowering the bounds
205 self.opaque_type_data
207 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
208 // We don't want to lower the bounds inside the binders
209 // we're currently in, because they don't end up inside
210 // those binders. E.g. when we have `impl Trait<impl
211 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
212 // to the self parameter from `impl Trait`, and the
213 // bounds aren't actually stored nested within each
214 // other, but separately. So if the `T` refers to a type
215 // parameter of the outer function, it's just one binder
216 // away instead of two.
217 let actual_opaque_type_data = self
218 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
219 ctx.lower_impl_trait(&bounds)
221 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
223 let func = match self.resolver.generic_def() {
224 Some(GenericDefId::FunctionId(f)) => f,
225 _ => panic!("opaque impl trait lowering in non-function"),
227 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
228 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
229 let generics = generics(self.db.upcast(), func.into());
230 let parameters = Substs::bound_vars(&generics, self.in_binders);
231 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
233 substitution: parameters,
237 ImplTraitLoweringMode::Param => {
238 let idx = self.impl_trait_counter.get();
239 // FIXME we're probably doing something wrong here
240 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
241 if let Some(def) = self.resolver.generic_def() {
242 let generics = generics(self.db.upcast(), def);
245 .filter(|(_, data)| {
246 data.provenance == TypeParamProvenance::ArgumentImplTrait
249 .map_or(TyKind::Unknown, |(id, _)| {
250 TyKind::Placeholder(to_placeholder_idx(self.db, id))
252 param.intern(&Interner)
254 TyKind::Unknown.intern(&Interner)
257 ImplTraitLoweringMode::Variable => {
258 let idx = self.impl_trait_counter.get();
259 // FIXME we're probably doing something wrong here
260 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
261 let (parent_params, self_params, list_params, _impl_trait_params) =
262 if let Some(def) = self.resolver.generic_def() {
263 let generics = generics(self.db.upcast(), def);
264 generics.provenance_split()
268 TyKind::BoundVar(BoundVar::new(
270 idx as usize + parent_params + self_params + list_params,
274 ImplTraitLoweringMode::Disallowed => {
275 // FIXME: report error
276 TyKind::Unknown.intern(&Interner)
280 TypeRef::Error => TyKind::Unknown.intern(&Interner),
285 /// This is only for `generic_predicates_for_param`, where we can't just
286 /// lower the self types of the predicates since that could lead to cycles.
287 /// So we just check here if the `type_ref` resolves to a generic param, and which.
288 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
289 let path = match type_ref {
290 TypeRef::Path(path) => path,
293 if path.type_anchor().is_some() {
296 if path.segments().len() > 1 {
300 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
301 Some((it, None)) => it,
304 if let TypeNs::GenericParam(param_id) = resolution {
311 pub(crate) fn lower_ty_relative_path(
314 // We need the original resolution to lower `Self::AssocTy` correctly
316 remaining_segments: PathSegments<'_>,
317 ) -> (Ty, Option<TypeNs>) {
318 if remaining_segments.len() == 1 {
319 // resolve unselected assoc types
320 let segment = remaining_segments.first().unwrap();
321 (self.select_associated_type(res, segment), None)
322 } else if remaining_segments.len() > 1 {
323 // FIXME report error (ambiguous associated type)
324 (TyKind::Unknown.intern(&Interner), None)
330 pub(crate) fn lower_partly_resolved_path(
333 resolved_segment: PathSegment<'_>,
334 remaining_segments: PathSegments<'_>,
336 ) -> (Ty, Option<TypeNs>) {
337 let ty = match resolution {
338 TypeNs::TraitId(trait_) => {
339 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
340 let self_ty = if remaining_segments.len() == 0 {
342 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
349 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
350 let ty = if remaining_segments.len() == 1 {
351 let segment = remaining_segments.first().unwrap();
352 let found = associated_type_by_name_including_super_traits(
358 Some((super_trait_ref, associated_ty)) => {
359 // FIXME handle type parameters on the segment
360 TyKind::Alias(AliasTy::Projection(ProjectionTy {
361 associated_ty_id: to_assoc_type_id(associated_ty),
362 substitution: super_trait_ref.substs,
367 // FIXME: report error (associated type not found)
368 TyKind::Unknown.intern(&Interner)
371 } else if remaining_segments.len() > 1 {
372 // FIXME report error (ambiguous associated type)
373 TyKind::Unknown.intern(&Interner)
375 TyKind::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)]))
380 TypeNs::GenericParam(param_id) => {
381 let generics = generics(
383 self.resolver.generic_def().expect("generics in scope"),
385 match self.type_param_mode {
386 TypeParamLoweringMode::Placeholder => {
387 TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
389 TypeParamLoweringMode::Variable => {
390 let idx = generics.param_idx(param_id).expect("matching generics");
391 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
396 TypeNs::SelfType(impl_id) => {
397 let generics = generics(self.db.upcast(), impl_id.into());
398 let substs = match self.type_param_mode {
399 TypeParamLoweringMode::Placeholder => {
400 Substs::type_params_for_generics(self.db, &generics)
402 TypeParamLoweringMode::Variable => {
403 Substs::bound_vars(&generics, self.in_binders)
406 self.db.impl_self_ty(impl_id).subst(&substs)
408 TypeNs::AdtSelfType(adt) => {
409 let generics = generics(self.db.upcast(), adt.into());
410 let substs = match self.type_param_mode {
411 TypeParamLoweringMode::Placeholder => {
412 Substs::type_params_for_generics(self.db, &generics)
414 TypeParamLoweringMode::Variable => {
415 Substs::bound_vars(&generics, self.in_binders)
418 self.db.ty(adt.into()).subst(&substs)
421 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
422 TypeNs::BuiltinType(it) => {
423 self.lower_path_inner(resolved_segment, it.into(), infer_args)
425 TypeNs::TypeAliasId(it) => {
426 self.lower_path_inner(resolved_segment, it.into(), infer_args)
428 // FIXME: report error
429 TypeNs::EnumVariantId(_) => return (TyKind::Unknown.intern(&Interner), None),
431 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
434 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
435 // Resolve the path (in type namespace)
436 if let Some(type_ref) = path.type_anchor() {
437 let (ty, res) = self.lower_ty_ext(&type_ref);
438 return self.lower_ty_relative_path(ty, res, path.segments());
440 let (resolution, remaining_index) =
441 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
443 None => return (TyKind::Unknown.intern(&Interner), None),
445 let (resolved_segment, remaining_segments) = match remaining_index {
447 path.segments().last().expect("resolved path has at least one element"),
450 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
452 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
455 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
456 if let Some(res) = res {
457 let ty = associated_type_shorthand_candidates(
460 move |name, t, associated_ty| {
461 if name == segment.name {
462 let substs = match self.type_param_mode {
463 TypeParamLoweringMode::Placeholder => {
464 // if we're lowering to placeholders, we have to put
466 let s = Substs::type_params(
468 self.resolver.generic_def().expect(
469 "there should be generics if there's a generic param",
472 t.substs.clone().subst_bound_vars(&s)
474 TypeParamLoweringMode::Variable => t.substs.clone(),
476 // We need to shift in the bound vars, since
477 // associated_type_shorthand_candidates does not do that
478 let substs = substs.shift_bound_vars(self.in_binders);
479 // FIXME handle type parameters on the segment
481 TyKind::Alias(AliasTy::Projection(ProjectionTy {
482 associated_ty_id: to_assoc_type_id(associated_ty),
483 substitution: substs,
493 ty.unwrap_or(TyKind::Unknown.intern(&Interner))
495 TyKind::Unknown.intern(&Interner)
501 segment: PathSegment<'_>,
505 let generic_def = match typeable {
506 TyDefId::BuiltinType(_) => None,
507 TyDefId::AdtId(it) => Some(it.into()),
508 TyDefId::TypeAliasId(it) => Some(it.into()),
510 let substs = self.substs_from_path_segment(segment, generic_def, infer_args);
511 self.db.ty(typeable).subst(&substs)
514 /// Collect generic arguments from a path into a `Substs`. See also
515 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
516 pub(super) fn substs_from_path(
519 // Note that we don't call `db.value_type(resolved)` here,
520 // `ValueTyDefId` is just a convenient way to pass generics and
521 // special-case enum variants
522 resolved: ValueTyDefId,
525 let last = path.segments().last().expect("path should have at least one segment");
526 let (segment, generic_def) = match resolved {
527 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
528 ValueTyDefId::StructId(it) => (last, Some(it.into())),
529 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
530 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
531 ValueTyDefId::StaticId(_) => (last, None),
532 ValueTyDefId::EnumVariantId(var) => {
533 // the generic args for an enum variant may be either specified
534 // on the segment referring to the enum, or on the segment
535 // referring to the variant. So `Option::<T>::None` and
536 // `Option::None::<T>` are both allowed (though the former is
537 // preferred). See also `def_ids_for_path_segments` in rustc.
538 let len = path.segments().len();
539 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
540 let segment = match penultimate {
541 Some(segment) if segment.args_and_bindings.is_some() => segment,
544 (segment, Some(var.parent.into()))
547 self.substs_from_path_segment(segment, generic_def, infer_args)
550 fn substs_from_path_segment(
552 segment: PathSegment<'_>,
553 def_generic: Option<GenericDefId>,
556 let mut substs = Vec::new();
557 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
559 let (parent_params, self_params, type_params, impl_trait_params) =
560 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
561 let total_len = parent_params + self_params + type_params + impl_trait_params;
563 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(parent_params));
565 let mut had_explicit_type_args = false;
567 if let Some(generic_args) = &segment.args_and_bindings {
568 if !generic_args.has_self_type {
569 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(self_params));
572 if generic_args.has_self_type { self_params + type_params } else { type_params };
573 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
574 // if args are provided, it should be all of them, but we can't rely on that
575 for arg in generic_args
578 .filter(|arg| matches!(arg, GenericArg::Type(_)))
583 GenericArg::Type(type_ref) => {
584 had_explicit_type_args = true;
585 let ty = self.lower_ty(type_ref);
588 GenericArg::Lifetime(_) => {}
593 // handle defaults. In expression or pattern path segments without
594 // explicitly specified type arguments, missing type arguments are inferred
595 // (i.e. defaults aren't used).
596 if !infer_args || had_explicit_type_args {
597 if let Some(def_generic) = def_generic {
598 let defaults = self.db.generic_defaults(def_generic);
599 assert_eq!(total_len, defaults.len());
601 for default_ty in defaults.iter().skip(substs.len()) {
602 // each default can depend on the previous parameters
603 let substs_so_far = Substs(substs.clone().into());
604 substs.push(default_ty.clone().subst(&substs_so_far));
609 // add placeholders for args that were not provided
610 // FIXME: emit diagnostics in contexts where this is not allowed
611 for _ in substs.len()..total_len {
612 substs.push(TyKind::Unknown.intern(&Interner));
614 assert_eq!(substs.len(), total_len);
616 Substs(substs.into())
619 fn lower_trait_ref_from_path(
622 explicit_self_ty: Option<Ty>,
623 ) -> Option<TraitRef> {
625 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
626 TypeNs::TraitId(tr) => tr,
629 let segment = path.segments().last().expect("path should have at least one segment");
630 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
633 pub(crate) fn lower_trait_ref_from_resolved_path(
636 segment: PathSegment<'_>,
637 explicit_self_ty: Option<Ty>,
639 let mut substs = self.trait_ref_substs_from_path(segment, resolved);
640 if let Some(self_ty) = explicit_self_ty {
641 make_mut_slice(&mut substs.0)[0] = self_ty;
643 TraitRef { trait_: resolved, substs }
649 explicit_self_ty: Option<Ty>,
650 ) -> Option<TraitRef> {
651 let path = match type_ref {
652 TypeRef::Path(path) => path,
655 self.lower_trait_ref_from_path(path, explicit_self_ty)
658 fn trait_ref_substs_from_path(&self, segment: PathSegment<'_>, resolved: TraitId) -> Substs {
659 self.substs_from_path_segment(segment, Some(resolved.into()), false)
662 pub(crate) fn lower_where_predicate(
664 where_predicate: &'a WherePredicate,
665 ) -> impl Iterator<Item = GenericPredicate> + 'a {
666 match where_predicate {
667 WherePredicate::ForLifetime { target, bound, .. }
668 | WherePredicate::TypeBound { target, bound } => {
669 let self_ty = match target {
670 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
671 WherePredicateTypeTarget::TypeParam(param_id) => {
672 let generic_def = self.resolver.generic_def().expect("generics in scope");
673 let generics = generics(self.db.upcast(), generic_def);
675 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
676 let placeholder = to_placeholder_idx(self.db, param_id);
677 match self.type_param_mode {
678 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
679 TypeParamLoweringMode::Variable => {
680 let idx = generics.param_idx(param_id).expect("matching generics");
681 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
687 self.lower_type_bound(bound, self_ty).collect::<Vec<_>>().into_iter()
689 WherePredicate::Lifetime { .. } => vec![].into_iter(),
693 pub(crate) fn lower_type_bound(
695 bound: &'a TypeBound,
697 ) -> impl Iterator<Item = GenericPredicate> + 'a {
698 let mut bindings = None;
699 let trait_ref = match bound {
700 TypeBound::Path(path) => {
701 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
703 bindings.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented),
706 TypeBound::Lifetime(_) => None,
707 TypeBound::Error => Some(GenericPredicate::Error),
709 trait_ref.into_iter().chain(
712 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
716 fn assoc_type_bindings_from_type_bound(
718 bound: &'a TypeBound,
720 ) -> impl Iterator<Item = GenericPredicate> + 'a {
721 let last_segment = match bound {
722 TypeBound::Path(path) => path.segments().last(),
723 TypeBound::Error | TypeBound::Lifetime(_) => None,
727 .flat_map(|segment| segment.args_and_bindings.into_iter())
728 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
729 .flat_map(move |binding| {
730 let found = associated_type_by_name_including_super_traits(
735 let (super_trait_ref, associated_ty) = match found {
736 None => return SmallVec::<[GenericPredicate; 1]>::new(),
739 let projection_ty = ProjectionTy {
740 associated_ty_id: to_assoc_type_id(associated_ty),
741 substitution: super_trait_ref.substs,
743 let mut preds = SmallVec::with_capacity(
744 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
746 if let Some(type_ref) = &binding.type_ref {
747 let ty = self.lower_ty(type_ref);
748 let projection_predicate =
749 ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
750 preds.push(GenericPredicate::Projection(projection_predicate));
752 for bound in &binding.bounds {
753 preds.extend(self.lower_type_bound(
755 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
762 fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
763 cov_mark::hit!(lower_rpit);
765 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
766 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
767 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
769 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
773 fn count_impl_traits(type_ref: &TypeRef) -> usize {
775 type_ref.walk(&mut |type_ref| {
776 if matches!(type_ref, TypeRef::ImplTrait(_)) {
783 /// Build the signature of a callable item (function, struct or enum variant).
784 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
786 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
787 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
788 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
792 pub fn associated_type_shorthand_candidates<R>(
793 db: &dyn HirDatabase,
795 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
797 let traits_from_env: Vec<_> = match res {
798 TypeNs::SelfType(impl_id) => match db.impl_trait(impl_id) {
800 Some(trait_ref) => vec![trait_ref.value],
802 TypeNs::GenericParam(param_id) => {
803 let predicates = db.generic_predicates_for_param(param_id);
804 let mut traits_: Vec<_> = predicates
806 .filter_map(|pred| match &pred.value {
807 GenericPredicate::Implemented(tr) => Some(tr.clone()),
811 // Handle `Self::Type` referring to own associated type in trait definitions
812 if let GenericDefId::TraitId(trait_id) = param_id.parent {
813 let generics = generics(db.upcast(), trait_id.into());
814 if generics.params.types[param_id.local_id].provenance
815 == TypeParamProvenance::TraitSelf
817 let trait_ref = TraitRef {
819 substs: Substs::bound_vars(&generics, DebruijnIndex::INNERMOST),
821 traits_.push(trait_ref);
829 for t in traits_from_env.into_iter().flat_map(move |t| all_super_trait_refs(db, t)) {
830 let data = db.trait_data(t.trait_);
832 for (name, assoc_id) in &data.items {
834 AssocItemId::TypeAliasId(alias) => {
835 if let Some(result) = cb(name, &t, *alias) {
839 AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => {}
847 /// Build the type of all specific fields of a struct or enum variant.
848 pub(crate) fn field_types_query(
849 db: &dyn HirDatabase,
850 variant_id: VariantId,
851 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
852 let var_data = variant_data(db.upcast(), variant_id);
853 let (resolver, def): (_, GenericDefId) = match variant_id {
854 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
855 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
856 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
858 let generics = generics(db.upcast(), def);
859 let mut res = ArenaMap::default();
861 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
862 for (field_id, field_data) in var_data.fields().iter() {
863 res.insert(field_id, Binders::new(generics.len(), ctx.lower_ty(&field_data.type_ref)))
868 /// This query exists only to be used when resolving short-hand associated types
871 /// See the analogous query in rustc and its comment:
872 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
873 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
874 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
875 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
876 pub(crate) fn generic_predicates_for_param_query(
877 db: &dyn HirDatabase,
878 param_id: TypeParamId,
879 ) -> Arc<[Binders<GenericPredicate>]> {
880 let resolver = param_id.parent.resolver(db.upcast());
882 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
883 let generics = generics(db.upcast(), param_id.parent);
885 .where_predicates_in_scope()
886 // we have to filter out all other predicates *first*, before attempting to lower them
887 .filter(|pred| match pred {
888 WherePredicate::ForLifetime { target, .. }
889 | WherePredicate::TypeBound { target, .. } => match target {
890 WherePredicateTypeTarget::TypeRef(type_ref) => {
891 ctx.lower_ty_only_param(type_ref) == Some(param_id)
893 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
895 WherePredicate::Lifetime { .. } => false,
897 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
901 pub(crate) fn generic_predicates_for_param_recover(
902 _db: &dyn HirDatabase,
904 _param_id: &TypeParamId,
905 ) -> Arc<[Binders<GenericPredicate>]> {
909 pub(crate) fn trait_environment_query(
910 db: &dyn HirDatabase,
912 ) -> Arc<TraitEnvironment> {
913 let resolver = def.resolver(db.upcast());
914 let ctx = TyLoweringContext::new(db, &resolver)
915 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
916 let mut traits_in_scope = Vec::new();
917 let mut clauses = Vec::new();
918 for pred in resolver.where_predicates_in_scope() {
919 for pred in ctx.lower_where_predicate(pred) {
923 if let GenericPredicate::Implemented(tr) = &pred {
924 traits_in_scope.push((tr.self_ty().clone(), tr.trait_));
926 let program_clause: chalk_ir::ProgramClause<Interner> =
927 pred.clone().to_chalk(db).cast(&Interner);
928 clauses.push(program_clause.into_from_env_clause(&Interner));
932 let container: Option<AssocContainerId> = match def {
933 // FIXME: is there a function for this?
934 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
935 GenericDefId::AdtId(_) => None,
936 GenericDefId::TraitId(_) => None,
937 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
938 GenericDefId::ImplId(_) => None,
939 GenericDefId::EnumVariantId(_) => None,
940 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
942 if let Some(AssocContainerId::TraitId(trait_id)) = container {
943 // add `Self: Trait<T1, T2, ...>` to the environment in trait
944 // function default implementations (and hypothetical code
945 // inside consts or type aliases)
946 cov_mark::hit!(trait_self_implements_self);
947 let substs = Substs::type_params(db, trait_id);
948 let trait_ref = TraitRef { trait_: trait_id, substs };
949 let pred = GenericPredicate::Implemented(trait_ref);
950 let program_clause: chalk_ir::ProgramClause<Interner> =
951 pred.clone().to_chalk(db).cast(&Interner);
952 clauses.push(program_clause.into_from_env_clause(&Interner));
955 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
957 Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
960 /// Resolve the where clause(s) of an item with generics.
961 pub(crate) fn generic_predicates_query(
962 db: &dyn HirDatabase,
964 ) -> Arc<[Binders<GenericPredicate>]> {
965 let resolver = def.resolver(db.upcast());
967 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
968 let generics = generics(db.upcast(), def);
970 .where_predicates_in_scope()
971 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
975 /// Resolve the default type params from generics
976 pub(crate) fn generic_defaults_query(
977 db: &dyn HirDatabase,
979 ) -> Arc<[Binders<Ty>]> {
980 let resolver = def.resolver(db.upcast());
982 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
983 let generic_params = generics(db.upcast(), def);
985 let defaults = generic_params
988 .map(|(idx, (_, p))| {
990 p.default.as_ref().map_or(TyKind::Unknown.intern(&Interner), |t| ctx.lower_ty(t));
992 // Each default can only refer to previous parameters.
994 &mut |ty, binders| match ty.interned_mut() {
995 TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
997 // type variable default referring to parameter coming
998 // after it. This is forbidden (FIXME: report
1000 *ty = TyKind::Unknown.intern(&Interner);
1005 DebruijnIndex::INNERMOST,
1008 Binders::new(idx, ty)
1015 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1016 let data = db.function_data(def);
1017 let resolver = def.resolver(db.upcast());
1018 let ctx_params = TyLoweringContext::new(db, &resolver)
1019 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1020 .with_type_param_mode(TypeParamLoweringMode::Variable);
1021 let params = data.params.iter().map(|tr| (&ctx_params).lower_ty(tr)).collect::<Vec<_>>();
1022 let ctx_ret = TyLoweringContext::new(db, &resolver)
1023 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1024 .with_type_param_mode(TypeParamLoweringMode::Variable);
1025 let ret = (&ctx_ret).lower_ty(&data.ret_type);
1026 let generics = generics(db.upcast(), def.into());
1027 let num_binders = generics.len();
1028 Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs))
1031 /// Build the declared type of a function. This should not need to look at the
1033 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1034 let generics = generics(db.upcast(), def.into());
1035 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1038 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1042 /// Build the declared type of a const.
1043 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1044 let data = db.const_data(def);
1045 let generics = generics(db.upcast(), def.into());
1046 let resolver = def.resolver(db.upcast());
1048 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1050 Binders::new(generics.len(), ctx.lower_ty(&data.type_ref))
1053 /// Build the declared type of a static.
1054 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1055 let data = db.static_data(def);
1056 let resolver = def.resolver(db.upcast());
1057 let ctx = TyLoweringContext::new(db, &resolver);
1059 Binders::new(0, ctx.lower_ty(&data.type_ref))
1062 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1063 let struct_data = db.struct_data(def);
1064 let fields = struct_data.variant_data.fields();
1065 let resolver = def.resolver(db.upcast());
1067 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1068 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1069 let ret = type_for_adt(db, def.into());
1070 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1073 /// Build the type of a tuple struct constructor.
1074 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1075 let struct_data = db.struct_data(def);
1076 if let StructKind::Unit = struct_data.variant_data.kind() {
1077 return type_for_adt(db, def.into());
1079 let generics = generics(db.upcast(), def.into());
1080 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1083 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1087 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1088 let enum_data = db.enum_data(def.parent);
1089 let var_data = &enum_data.variants[def.local_id];
1090 let fields = var_data.variant_data.fields();
1091 let resolver = def.parent.resolver(db.upcast());
1093 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1094 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1095 let ret = type_for_adt(db, def.parent.into());
1096 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1099 /// Build the type of a tuple enum variant constructor.
1100 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1101 let enum_data = db.enum_data(def.parent);
1102 let var_data = &enum_data.variants[def.local_id].variant_data;
1103 if let StructKind::Unit = var_data.kind() {
1104 return type_for_adt(db, def.parent.into());
1106 let generics = generics(db.upcast(), def.parent.into());
1107 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1110 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1114 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1115 let generics = generics(db.upcast(), adt.into());
1116 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1117 Binders::new(substs.len(), Ty::adt_ty(adt, substs))
1120 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1121 let generics = generics(db.upcast(), t.into());
1122 let resolver = t.resolver(db.upcast());
1124 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1125 if db.type_alias_data(t).is_extern {
1126 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1128 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1129 let type_ref = &db.type_alias_data(t).type_ref;
1130 let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error));
1131 Binders::new(substs.len(), inner)
1135 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1136 pub enum CallableDefId {
1137 FunctionId(FunctionId),
1139 EnumVariantId(EnumVariantId),
1141 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1143 impl CallableDefId {
1144 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1145 let db = db.upcast();
1147 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1148 CallableDefId::StructId(s) => s.lookup(db).container,
1149 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1155 impl From<CallableDefId> for GenericDefId {
1156 fn from(def: CallableDefId) -> GenericDefId {
1158 CallableDefId::FunctionId(f) => f.into(),
1159 CallableDefId::StructId(s) => s.into(),
1160 CallableDefId::EnumVariantId(e) => e.into(),
1165 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1167 BuiltinType(BuiltinType),
1169 TypeAliasId(TypeAliasId),
1171 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1173 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1174 pub enum ValueTyDefId {
1175 FunctionId(FunctionId),
1178 EnumVariantId(EnumVariantId),
1182 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1184 /// Build the declared type of an item. This depends on the namespace; e.g. for
1185 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1186 /// the constructor function `(usize) -> Foo` which lives in the values
1188 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1190 TyDefId::BuiltinType(it) => Binders::new(0, Ty::builtin(it)),
1191 TyDefId::AdtId(it) => type_for_adt(db, it),
1192 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1196 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1197 let num_binders = match *def {
1198 TyDefId::BuiltinType(_) => 0,
1199 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1200 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1202 Binders::new(num_binders, TyKind::Unknown.intern(&Interner))
1205 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1207 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1208 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1209 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1210 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1211 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1212 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1216 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1217 let impl_data = db.impl_data(impl_id);
1218 let resolver = impl_id.resolver(db.upcast());
1219 let generics = generics(db.upcast(), impl_id.into());
1221 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1222 Binders::new(generics.len(), ctx.lower_ty(&impl_data.target_type))
1225 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1226 let parent_data = db.generic_params(def.parent);
1227 let data = &parent_data.consts[def.local_id];
1228 let resolver = def.parent.resolver(db.upcast());
1229 let ctx = TyLoweringContext::new(db, &resolver);
1231 ctx.lower_ty(&data.ty)
1234 pub(crate) fn impl_self_ty_recover(
1235 db: &dyn HirDatabase,
1239 let generics = generics(db.upcast(), (*impl_id).into());
1240 Binders::new(generics.len(), TyKind::Unknown.intern(&Interner))
1243 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1244 let impl_data = db.impl_data(impl_id);
1245 let resolver = impl_id.resolver(db.upcast());
1247 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1248 let self_ty = db.impl_self_ty(impl_id);
1249 let target_trait = impl_data.target_trait.as_ref()?;
1250 Some(Binders::new(self_ty.num_binders, ctx.lower_trait_ref(target_trait, Some(self_ty.value))?))
1253 pub(crate) fn return_type_impl_traits(
1254 db: &dyn HirDatabase,
1255 def: hir_def::FunctionId,
1256 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1257 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1258 let data = db.function_data(def);
1259 let resolver = def.resolver(db.upcast());
1260 let ctx_ret = TyLoweringContext::new(db, &resolver)
1261 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1262 .with_type_param_mode(TypeParamLoweringMode::Variable);
1263 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1264 let generics = generics(db.upcast(), def.into());
1265 let num_binders = generics.len();
1266 let return_type_impl_traits =
1267 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1268 if return_type_impl_traits.impl_traits.is_empty() {
1271 Some(Arc::new(Binders::new(num_binders, return_type_impl_traits)))
1275 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1277 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1278 hir_def::type_ref::Mutability::Mut => Mutability::Mut,