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,
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 = inner.iter().map(|tr| self.lower_ty(tr));
154 TyKind::Tuple(inner_tys.len(), Substs::from_iter(&Interner, inner_tys))
157 TypeRef::Path(path) => {
158 let (ty, res_) = self.lower_path(path);
162 TypeRef::RawPtr(inner, mutability) => {
163 let inner_ty = self.lower_ty(inner);
164 TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
166 TypeRef::Array(inner) => {
167 let inner_ty = self.lower_ty(inner);
168 TyKind::Array(inner_ty).intern(&Interner)
170 TypeRef::Slice(inner) => {
171 let inner_ty = self.lower_ty(inner);
172 TyKind::Slice(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), inner_ty).intern(&Interner)
178 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
179 TypeRef::Fn(params, is_varargs) => {
180 let substs = Substs(params.iter().map(|tr| self.lower_ty(tr)).collect());
181 TyKind::Function(FnPointer {
182 num_args: substs.len() - 1,
183 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
188 TypeRef::DynTrait(bounds) => {
190 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
191 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
192 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
194 TyKind::Dyn(predicates).intern(&Interner)
196 TypeRef::ImplTrait(bounds) => {
197 match self.impl_trait_mode {
198 ImplTraitLoweringMode::Opaque => {
199 let idx = self.impl_trait_counter.get();
200 self.impl_trait_counter.set(idx + 1);
202 assert!(idx as usize == self.opaque_type_data.borrow().len());
203 // this dance is to make sure the data is in the right
204 // place even if we encounter more opaque types while
205 // lowering the bounds
206 self.opaque_type_data
208 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
209 // We don't want to lower the bounds inside the binders
210 // we're currently in, because they don't end up inside
211 // those binders. E.g. when we have `impl Trait<impl
212 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
213 // to the self parameter from `impl Trait`, and the
214 // bounds aren't actually stored nested within each
215 // other, but separately. So if the `T` refers to a type
216 // parameter of the outer function, it's just one binder
217 // away instead of two.
218 let actual_opaque_type_data = self
219 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
220 ctx.lower_impl_trait(&bounds)
222 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
224 let func = match self.resolver.generic_def() {
225 Some(GenericDefId::FunctionId(f)) => f,
226 _ => panic!("opaque impl trait lowering in non-function"),
228 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
229 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
230 let generics = generics(self.db.upcast(), func.into());
231 let parameters = Substs::bound_vars(&generics, self.in_binders);
232 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
234 substitution: parameters,
238 ImplTraitLoweringMode::Param => {
239 let idx = self.impl_trait_counter.get();
240 // FIXME we're probably doing something wrong here
241 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
242 if let Some(def) = self.resolver.generic_def() {
243 let generics = generics(self.db.upcast(), def);
246 .filter(|(_, data)| {
247 data.provenance == TypeParamProvenance::ArgumentImplTrait
250 .map_or(TyKind::Unknown, |(id, _)| {
251 TyKind::Placeholder(to_placeholder_idx(self.db, id))
253 param.intern(&Interner)
255 TyKind::Unknown.intern(&Interner)
258 ImplTraitLoweringMode::Variable => {
259 let idx = self.impl_trait_counter.get();
260 // FIXME we're probably doing something wrong here
261 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
262 let (parent_params, self_params, list_params, _impl_trait_params) =
263 if let Some(def) = self.resolver.generic_def() {
264 let generics = generics(self.db.upcast(), def);
265 generics.provenance_split()
269 TyKind::BoundVar(BoundVar::new(
271 idx as usize + parent_params + self_params + list_params,
275 ImplTraitLoweringMode::Disallowed => {
276 // FIXME: report error
277 TyKind::Unknown.intern(&Interner)
281 TypeRef::Error => TyKind::Unknown.intern(&Interner),
286 /// This is only for `generic_predicates_for_param`, where we can't just
287 /// lower the self types of the predicates since that could lead to cycles.
288 /// So we just check here if the `type_ref` resolves to a generic param, and which.
289 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
290 let path = match type_ref {
291 TypeRef::Path(path) => path,
294 if path.type_anchor().is_some() {
297 if path.segments().len() > 1 {
301 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
302 Some((it, None)) => it,
305 if let TypeNs::GenericParam(param_id) = resolution {
312 pub(crate) fn lower_ty_relative_path(
315 // We need the original resolution to lower `Self::AssocTy` correctly
317 remaining_segments: PathSegments<'_>,
318 ) -> (Ty, Option<TypeNs>) {
319 if remaining_segments.len() == 1 {
320 // resolve unselected assoc types
321 let segment = remaining_segments.first().unwrap();
322 (self.select_associated_type(res, segment), None)
323 } else if remaining_segments.len() > 1 {
324 // FIXME report error (ambiguous associated type)
325 (TyKind::Unknown.intern(&Interner), None)
331 pub(crate) fn lower_partly_resolved_path(
334 resolved_segment: PathSegment<'_>,
335 remaining_segments: PathSegments<'_>,
337 ) -> (Ty, Option<TypeNs>) {
338 let ty = match resolution {
339 TypeNs::TraitId(trait_) => {
340 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
341 let self_ty = if remaining_segments.len() == 0 {
343 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
350 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
351 let ty = if remaining_segments.len() == 1 {
352 let segment = remaining_segments.first().unwrap();
353 let found = associated_type_by_name_including_super_traits(
359 Some((super_trait_ref, associated_ty)) => {
360 // FIXME handle type parameters on the segment
361 TyKind::Alias(AliasTy::Projection(ProjectionTy {
362 associated_ty_id: to_assoc_type_id(associated_ty),
363 substitution: super_trait_ref.substs,
368 // FIXME: report error (associated type not found)
369 TyKind::Unknown.intern(&Interner)
372 } else if remaining_segments.len() > 1 {
373 // FIXME report error (ambiguous associated type)
374 TyKind::Unknown.intern(&Interner)
376 TyKind::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)]))
381 TypeNs::GenericParam(param_id) => {
382 let generics = generics(
384 self.resolver.generic_def().expect("generics in scope"),
386 match self.type_param_mode {
387 TypeParamLoweringMode::Placeholder => {
388 TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
390 TypeParamLoweringMode::Variable => {
391 let idx = generics.param_idx(param_id).expect("matching generics");
392 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
397 TypeNs::SelfType(impl_id) => {
398 let generics = generics(self.db.upcast(), impl_id.into());
399 let substs = match self.type_param_mode {
400 TypeParamLoweringMode::Placeholder => {
401 Substs::type_params_for_generics(self.db, &generics)
403 TypeParamLoweringMode::Variable => {
404 Substs::bound_vars(&generics, self.in_binders)
407 self.db.impl_self_ty(impl_id).subst(&substs)
409 TypeNs::AdtSelfType(adt) => {
410 let generics = generics(self.db.upcast(), adt.into());
411 let substs = match self.type_param_mode {
412 TypeParamLoweringMode::Placeholder => {
413 Substs::type_params_for_generics(self.db, &generics)
415 TypeParamLoweringMode::Variable => {
416 Substs::bound_vars(&generics, self.in_binders)
419 self.db.ty(adt.into()).subst(&substs)
422 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
423 TypeNs::BuiltinType(it) => {
424 self.lower_path_inner(resolved_segment, it.into(), infer_args)
426 TypeNs::TypeAliasId(it) => {
427 self.lower_path_inner(resolved_segment, it.into(), infer_args)
429 // FIXME: report error
430 TypeNs::EnumVariantId(_) => return (TyKind::Unknown.intern(&Interner), None),
432 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
435 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
436 // Resolve the path (in type namespace)
437 if let Some(type_ref) = path.type_anchor() {
438 let (ty, res) = self.lower_ty_ext(&type_ref);
439 return self.lower_ty_relative_path(ty, res, path.segments());
441 let (resolution, remaining_index) =
442 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
444 None => return (TyKind::Unknown.intern(&Interner), None),
446 let (resolved_segment, remaining_segments) = match remaining_index {
448 path.segments().last().expect("resolved path has at least one element"),
451 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
453 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
456 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
457 if let Some(res) = res {
458 let ty = associated_type_shorthand_candidates(
461 move |name, t, associated_ty| {
462 if name == segment.name {
463 let substs = match self.type_param_mode {
464 TypeParamLoweringMode::Placeholder => {
465 // if we're lowering to placeholders, we have to put
467 let s = Substs::type_params(
469 self.resolver.generic_def().expect(
470 "there should be generics if there's a generic param",
473 t.substs.clone().subst_bound_vars(&s)
475 TypeParamLoweringMode::Variable => t.substs.clone(),
477 // We need to shift in the bound vars, since
478 // associated_type_shorthand_candidates does not do that
479 let substs = substs.shift_bound_vars(self.in_binders);
480 // FIXME handle type parameters on the segment
482 TyKind::Alias(AliasTy::Projection(ProjectionTy {
483 associated_ty_id: to_assoc_type_id(associated_ty),
484 substitution: substs,
494 ty.unwrap_or(TyKind::Unknown.intern(&Interner))
496 TyKind::Unknown.intern(&Interner)
502 segment: PathSegment<'_>,
506 let generic_def = match typeable {
507 TyDefId::BuiltinType(_) => None,
508 TyDefId::AdtId(it) => Some(it.into()),
509 TyDefId::TypeAliasId(it) => Some(it.into()),
511 let substs = self.substs_from_path_segment(segment, generic_def, infer_args);
512 self.db.ty(typeable).subst(&substs)
515 /// Collect generic arguments from a path into a `Substs`. See also
516 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
517 pub(super) fn substs_from_path(
520 // Note that we don't call `db.value_type(resolved)` here,
521 // `ValueTyDefId` is just a convenient way to pass generics and
522 // special-case enum variants
523 resolved: ValueTyDefId,
526 let last = path.segments().last().expect("path should have at least one segment");
527 let (segment, generic_def) = match resolved {
528 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
529 ValueTyDefId::StructId(it) => (last, Some(it.into())),
530 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
531 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
532 ValueTyDefId::StaticId(_) => (last, None),
533 ValueTyDefId::EnumVariantId(var) => {
534 // the generic args for an enum variant may be either specified
535 // on the segment referring to the enum, or on the segment
536 // referring to the variant. So `Option::<T>::None` and
537 // `Option::None::<T>` are both allowed (though the former is
538 // preferred). See also `def_ids_for_path_segments` in rustc.
539 let len = path.segments().len();
540 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
541 let segment = match penultimate {
542 Some(segment) if segment.args_and_bindings.is_some() => segment,
545 (segment, Some(var.parent.into()))
548 self.substs_from_path_segment(segment, generic_def, infer_args)
551 fn substs_from_path_segment(
553 segment: PathSegment<'_>,
554 def_generic: Option<GenericDefId>,
557 let mut substs = Vec::new();
558 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
560 let (parent_params, self_params, type_params, impl_trait_params) =
561 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
562 let total_len = parent_params + self_params + type_params + impl_trait_params;
564 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(parent_params));
566 let mut had_explicit_type_args = false;
568 if let Some(generic_args) = &segment.args_and_bindings {
569 if !generic_args.has_self_type {
570 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(self_params));
573 if generic_args.has_self_type { self_params + type_params } else { type_params };
574 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
575 // if args are provided, it should be all of them, but we can't rely on that
576 for arg in generic_args
579 .filter(|arg| matches!(arg, GenericArg::Type(_)))
584 GenericArg::Type(type_ref) => {
585 had_explicit_type_args = true;
586 let ty = self.lower_ty(type_ref);
589 GenericArg::Lifetime(_) => {}
594 // handle defaults. In expression or pattern path segments without
595 // explicitly specified type arguments, missing type arguments are inferred
596 // (i.e. defaults aren't used).
597 if !infer_args || had_explicit_type_args {
598 if let Some(def_generic) = def_generic {
599 let defaults = self.db.generic_defaults(def_generic);
600 assert_eq!(total_len, defaults.len());
602 for default_ty in defaults.iter().skip(substs.len()) {
603 // each default can depend on the previous parameters
604 let substs_so_far = Substs(substs.clone().into());
605 substs.push(default_ty.clone().subst(&substs_so_far));
610 // add placeholders for args that were not provided
611 // FIXME: emit diagnostics in contexts where this is not allowed
612 for _ in substs.len()..total_len {
613 substs.push(TyKind::Unknown.intern(&Interner));
615 assert_eq!(substs.len(), total_len);
617 Substs(substs.into())
620 fn lower_trait_ref_from_path(
623 explicit_self_ty: Option<Ty>,
624 ) -> Option<TraitRef> {
626 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
627 TypeNs::TraitId(tr) => tr,
630 let segment = path.segments().last().expect("path should have at least one segment");
631 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
634 pub(crate) fn lower_trait_ref_from_resolved_path(
637 segment: PathSegment<'_>,
638 explicit_self_ty: Option<Ty>,
640 let mut substs = self.trait_ref_substs_from_path(segment, resolved);
641 if let Some(self_ty) = explicit_self_ty {
642 substs.0[0] = self_ty;
644 TraitRef { trait_: resolved, substs }
650 explicit_self_ty: Option<Ty>,
651 ) -> Option<TraitRef> {
652 let path = match type_ref {
653 TypeRef::Path(path) => path,
656 self.lower_trait_ref_from_path(path, explicit_self_ty)
659 fn trait_ref_substs_from_path(&self, segment: PathSegment<'_>, resolved: TraitId) -> Substs {
660 self.substs_from_path_segment(segment, Some(resolved.into()), false)
663 pub(crate) fn lower_where_predicate(
665 where_predicate: &'a WherePredicate,
666 ) -> impl Iterator<Item = GenericPredicate> + 'a {
667 match where_predicate {
668 WherePredicate::ForLifetime { target, bound, .. }
669 | WherePredicate::TypeBound { target, bound } => {
670 let self_ty = match target {
671 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
672 WherePredicateTypeTarget::TypeParam(param_id) => {
673 let generic_def = self.resolver.generic_def().expect("generics in scope");
674 let generics = generics(self.db.upcast(), generic_def);
676 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
677 let placeholder = to_placeholder_idx(self.db, param_id);
678 match self.type_param_mode {
679 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
680 TypeParamLoweringMode::Variable => {
681 let idx = generics.param_idx(param_id).expect("matching generics");
682 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
688 self.lower_type_bound(bound, self_ty).collect::<Vec<_>>().into_iter()
690 WherePredicate::Lifetime { .. } => vec![].into_iter(),
694 pub(crate) fn lower_type_bound(
696 bound: &'a TypeBound,
698 ) -> impl Iterator<Item = GenericPredicate> + 'a {
699 let mut bindings = None;
700 let trait_ref = match bound {
701 TypeBound::Path(path) => {
702 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
704 bindings.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented),
707 TypeBound::Lifetime(_) => None,
708 TypeBound::Error => Some(GenericPredicate::Error),
710 trait_ref.into_iter().chain(
713 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
717 fn assoc_type_bindings_from_type_bound(
719 bound: &'a TypeBound,
721 ) -> impl Iterator<Item = GenericPredicate> + 'a {
722 let last_segment = match bound {
723 TypeBound::Path(path) => path.segments().last(),
724 TypeBound::Error | TypeBound::Lifetime(_) => None,
728 .flat_map(|segment| segment.args_and_bindings.into_iter())
729 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
730 .flat_map(move |binding| {
731 let found = associated_type_by_name_including_super_traits(
736 let (super_trait_ref, associated_ty) = match found {
737 None => return SmallVec::<[GenericPredicate; 1]>::new(),
740 let projection_ty = ProjectionTy {
741 associated_ty_id: to_assoc_type_id(associated_ty),
742 substitution: super_trait_ref.substs,
744 let mut preds = SmallVec::with_capacity(
745 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
747 if let Some(type_ref) = &binding.type_ref {
748 let ty = self.lower_ty(type_ref);
749 let projection_predicate =
750 ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
751 preds.push(GenericPredicate::Projection(projection_predicate));
753 for bound in &binding.bounds {
754 preds.extend(self.lower_type_bound(
756 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
763 fn lower_impl_trait(&self, bounds: &[TypeBound]) -> ReturnTypeImplTrait {
764 cov_mark::hit!(lower_rpit);
766 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
767 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
768 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone())).collect()
770 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
774 fn count_impl_traits(type_ref: &TypeRef) -> usize {
776 type_ref.walk(&mut |type_ref| {
777 if matches!(type_ref, TypeRef::ImplTrait(_)) {
784 /// Build the signature of a callable item (function, struct or enum variant).
785 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
787 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
788 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
789 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
793 pub fn associated_type_shorthand_candidates<R>(
794 db: &dyn HirDatabase,
796 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
798 let traits_from_env: Vec<_> = match res {
799 TypeNs::SelfType(impl_id) => match db.impl_trait(impl_id) {
801 Some(trait_ref) => vec![trait_ref.value],
803 TypeNs::GenericParam(param_id) => {
804 let predicates = db.generic_predicates_for_param(param_id);
805 let mut traits_: Vec<_> = predicates
807 .filter_map(|pred| match &pred.value {
808 GenericPredicate::Implemented(tr) => Some(tr.clone()),
812 // Handle `Self::Type` referring to own associated type in trait definitions
813 if let GenericDefId::TraitId(trait_id) = param_id.parent {
814 let generics = generics(db.upcast(), trait_id.into());
815 if generics.params.types[param_id.local_id].provenance
816 == TypeParamProvenance::TraitSelf
818 let trait_ref = TraitRef {
820 substs: Substs::bound_vars(&generics, DebruijnIndex::INNERMOST),
822 traits_.push(trait_ref);
830 for t in traits_from_env.into_iter().flat_map(move |t| all_super_trait_refs(db, t)) {
831 let data = db.trait_data(t.trait_);
833 for (name, assoc_id) in &data.items {
835 AssocItemId::TypeAliasId(alias) => {
836 if let Some(result) = cb(name, &t, *alias) {
840 AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => {}
848 /// Build the type of all specific fields of a struct or enum variant.
849 pub(crate) fn field_types_query(
850 db: &dyn HirDatabase,
851 variant_id: VariantId,
852 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
853 let var_data = variant_data(db.upcast(), variant_id);
854 let (resolver, def): (_, GenericDefId) = match variant_id {
855 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
856 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
857 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
859 let generics = generics(db.upcast(), def);
860 let mut res = ArenaMap::default();
862 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
863 for (field_id, field_data) in var_data.fields().iter() {
864 res.insert(field_id, Binders::new(generics.len(), ctx.lower_ty(&field_data.type_ref)))
869 /// This query exists only to be used when resolving short-hand associated types
872 /// See the analogous query in rustc and its comment:
873 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
874 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
875 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
876 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
877 pub(crate) fn generic_predicates_for_param_query(
878 db: &dyn HirDatabase,
879 param_id: TypeParamId,
880 ) -> Arc<[Binders<GenericPredicate>]> {
881 let resolver = param_id.parent.resolver(db.upcast());
883 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
884 let generics = generics(db.upcast(), param_id.parent);
886 .where_predicates_in_scope()
887 // we have to filter out all other predicates *first*, before attempting to lower them
888 .filter(|pred| match pred {
889 WherePredicate::ForLifetime { target, .. }
890 | WherePredicate::TypeBound { target, .. } => match target {
891 WherePredicateTypeTarget::TypeRef(type_ref) => {
892 ctx.lower_ty_only_param(type_ref) == Some(param_id)
894 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
896 WherePredicate::Lifetime { .. } => false,
898 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
902 pub(crate) fn generic_predicates_for_param_recover(
903 _db: &dyn HirDatabase,
905 _param_id: &TypeParamId,
906 ) -> Arc<[Binders<GenericPredicate>]> {
910 pub(crate) fn trait_environment_query(
911 db: &dyn HirDatabase,
913 ) -> Arc<TraitEnvironment> {
914 let resolver = def.resolver(db.upcast());
915 let ctx = TyLoweringContext::new(db, &resolver)
916 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
917 let mut traits_in_scope = Vec::new();
918 let mut clauses = Vec::new();
919 for pred in resolver.where_predicates_in_scope() {
920 for pred in ctx.lower_where_predicate(pred) {
924 if let GenericPredicate::Implemented(tr) = &pred {
925 traits_in_scope.push((tr.self_ty().clone(), tr.trait_));
927 let program_clause: chalk_ir::ProgramClause<Interner> =
928 pred.clone().to_chalk(db).cast(&Interner);
929 clauses.push(program_clause.into_from_env_clause(&Interner));
933 let container: Option<AssocContainerId> = match def {
934 // FIXME: is there a function for this?
935 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
936 GenericDefId::AdtId(_) => None,
937 GenericDefId::TraitId(_) => None,
938 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
939 GenericDefId::ImplId(_) => None,
940 GenericDefId::EnumVariantId(_) => None,
941 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
943 if let Some(AssocContainerId::TraitId(trait_id)) = container {
944 // add `Self: Trait<T1, T2, ...>` to the environment in trait
945 // function default implementations (and hypothetical code
946 // inside consts or type aliases)
947 cov_mark::hit!(trait_self_implements_self);
948 let substs = Substs::type_params(db, trait_id);
949 let trait_ref = TraitRef { trait_: trait_id, substs };
950 let pred = GenericPredicate::Implemented(trait_ref);
951 let program_clause: chalk_ir::ProgramClause<Interner> =
952 pred.clone().to_chalk(db).cast(&Interner);
953 clauses.push(program_clause.into_from_env_clause(&Interner));
956 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
958 Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
961 /// Resolve the where clause(s) of an item with generics.
962 pub(crate) fn generic_predicates_query(
963 db: &dyn HirDatabase,
965 ) -> Arc<[Binders<GenericPredicate>]> {
966 let resolver = def.resolver(db.upcast());
968 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
969 let generics = generics(db.upcast(), def);
971 .where_predicates_in_scope()
972 .flat_map(|pred| ctx.lower_where_predicate(pred).map(|p| Binders::new(generics.len(), p)))
976 /// Resolve the default type params from generics
977 pub(crate) fn generic_defaults_query(
978 db: &dyn HirDatabase,
980 ) -> Arc<[Binders<Ty>]> {
981 let resolver = def.resolver(db.upcast());
983 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
984 let generic_params = generics(db.upcast(), def);
986 let defaults = generic_params
989 .map(|(idx, (_, p))| {
991 p.default.as_ref().map_or(TyKind::Unknown.intern(&Interner), |t| ctx.lower_ty(t));
993 // Each default can only refer to previous parameters.
995 &mut |ty, binders| match ty.interned_mut() {
996 TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
998 // type variable default referring to parameter coming
999 // after it. This is forbidden (FIXME: report
1001 *ty = TyKind::Unknown.intern(&Interner);
1006 DebruijnIndex::INNERMOST,
1009 Binders::new(idx, ty)
1016 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1017 let data = db.function_data(def);
1018 let resolver = def.resolver(db.upcast());
1019 let ctx_params = TyLoweringContext::new(db, &resolver)
1020 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1021 .with_type_param_mode(TypeParamLoweringMode::Variable);
1022 let params = data.params.iter().map(|tr| (&ctx_params).lower_ty(tr)).collect::<Vec<_>>();
1023 let ctx_ret = TyLoweringContext::new(db, &resolver)
1024 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1025 .with_type_param_mode(TypeParamLoweringMode::Variable);
1026 let ret = (&ctx_ret).lower_ty(&data.ret_type);
1027 let generics = generics(db.upcast(), def.into());
1028 let num_binders = generics.len();
1029 Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs))
1032 /// Build the declared type of a function. This should not need to look at the
1034 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1035 let generics = generics(db.upcast(), def.into());
1036 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1039 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1043 /// Build the declared type of a const.
1044 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1045 let data = db.const_data(def);
1046 let generics = generics(db.upcast(), def.into());
1047 let resolver = def.resolver(db.upcast());
1049 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1051 Binders::new(generics.len(), ctx.lower_ty(&data.type_ref))
1054 /// Build the declared type of a static.
1055 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1056 let data = db.static_data(def);
1057 let resolver = def.resolver(db.upcast());
1058 let ctx = TyLoweringContext::new(db, &resolver);
1060 Binders::new(0, ctx.lower_ty(&data.type_ref))
1063 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1064 let struct_data = db.struct_data(def);
1065 let fields = struct_data.variant_data.fields();
1066 let resolver = def.resolver(db.upcast());
1068 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1069 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1070 let ret = type_for_adt(db, def.into());
1071 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1074 /// Build the type of a tuple struct constructor.
1075 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1076 let struct_data = db.struct_data(def);
1077 if let StructKind::Unit = struct_data.variant_data.kind() {
1078 return type_for_adt(db, def.into());
1080 let generics = generics(db.upcast(), def.into());
1081 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1084 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1088 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1089 let enum_data = db.enum_data(def.parent);
1090 let var_data = &enum_data.variants[def.local_id];
1091 let fields = var_data.variant_data.fields();
1092 let resolver = def.parent.resolver(db.upcast());
1094 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1095 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1096 let ret = type_for_adt(db, def.parent.into());
1097 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1100 /// Build the type of a tuple enum variant constructor.
1101 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1102 let enum_data = db.enum_data(def.parent);
1103 let var_data = &enum_data.variants[def.local_id].variant_data;
1104 if let StructKind::Unit = var_data.kind() {
1105 return type_for_adt(db, def.parent.into());
1107 let generics = generics(db.upcast(), def.parent.into());
1108 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1111 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1115 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1116 let generics = generics(db.upcast(), adt.into());
1117 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1118 Binders::new(substs.len(), Ty::adt_ty(adt, substs))
1121 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1122 let generics = generics(db.upcast(), t.into());
1123 let resolver = t.resolver(db.upcast());
1125 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1126 if db.type_alias_data(t).is_extern {
1127 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1129 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1130 let type_ref = &db.type_alias_data(t).type_ref;
1131 let inner = ctx.lower_ty(type_ref.as_ref().unwrap_or(&TypeRef::Error));
1132 Binders::new(substs.len(), inner)
1136 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1137 pub enum CallableDefId {
1138 FunctionId(FunctionId),
1140 EnumVariantId(EnumVariantId),
1142 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1144 impl CallableDefId {
1145 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1146 let db = db.upcast();
1148 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1149 CallableDefId::StructId(s) => s.lookup(db).container,
1150 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1156 impl From<CallableDefId> for GenericDefId {
1157 fn from(def: CallableDefId) -> GenericDefId {
1159 CallableDefId::FunctionId(f) => f.into(),
1160 CallableDefId::StructId(s) => s.into(),
1161 CallableDefId::EnumVariantId(e) => e.into(),
1166 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1168 BuiltinType(BuiltinType),
1170 TypeAliasId(TypeAliasId),
1172 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1174 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1175 pub enum ValueTyDefId {
1176 FunctionId(FunctionId),
1179 EnumVariantId(EnumVariantId),
1183 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1185 /// Build the declared type of an item. This depends on the namespace; e.g. for
1186 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1187 /// the constructor function `(usize) -> Foo` which lives in the values
1189 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1191 TyDefId::BuiltinType(it) => Binders::new(0, Ty::builtin(it)),
1192 TyDefId::AdtId(it) => type_for_adt(db, it),
1193 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1197 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1198 let num_binders = match *def {
1199 TyDefId::BuiltinType(_) => 0,
1200 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1201 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1203 Binders::new(num_binders, TyKind::Unknown.intern(&Interner))
1206 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1208 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1209 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1210 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1211 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1212 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1213 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1217 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1218 let impl_data = db.impl_data(impl_id);
1219 let resolver = impl_id.resolver(db.upcast());
1220 let generics = generics(db.upcast(), impl_id.into());
1222 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1223 Binders::new(generics.len(), ctx.lower_ty(&impl_data.target_type))
1226 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1227 let parent_data = db.generic_params(def.parent);
1228 let data = &parent_data.consts[def.local_id];
1229 let resolver = def.parent.resolver(db.upcast());
1230 let ctx = TyLoweringContext::new(db, &resolver);
1232 ctx.lower_ty(&data.ty)
1235 pub(crate) fn impl_self_ty_recover(
1236 db: &dyn HirDatabase,
1240 let generics = generics(db.upcast(), (*impl_id).into());
1241 Binders::new(generics.len(), TyKind::Unknown.intern(&Interner))
1244 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1245 let impl_data = db.impl_data(impl_id);
1246 let resolver = impl_id.resolver(db.upcast());
1248 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1249 let self_ty = db.impl_self_ty(impl_id);
1250 let target_trait = impl_data.target_trait.as_ref()?;
1251 Some(Binders::new(self_ty.num_binders, ctx.lower_trait_ref(target_trait, Some(self_ty.value))?))
1254 pub(crate) fn return_type_impl_traits(
1255 db: &dyn HirDatabase,
1256 def: hir_def::FunctionId,
1257 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1258 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1259 let data = db.function_data(def);
1260 let resolver = def.resolver(db.upcast());
1261 let ctx_ret = TyLoweringContext::new(db, &resolver)
1262 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1263 .with_type_param_mode(TypeParamLoweringMode::Variable);
1264 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1265 let generics = generics(db.upcast(), def.into());
1266 let num_binders = generics.len();
1267 let return_type_impl_traits =
1268 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1269 if return_type_impl_traits.impl_traits.is_empty() {
1272 Some(Arc::new(Binders::new(num_binders, return_type_impl_traits)))
1276 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1278 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1279 hir_def::type_ref::Mutability::Mut => Mutability::Mut,