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;
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 OpaqueTy, OpaqueTyId, 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 {
144 pub fn from_hir(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Self {
145 Ty::from_hir_ext(ctx, type_ref).0
147 pub fn from_hir_ext(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> (Self, Option<TypeNs>) {
149 let ty = match type_ref {
150 TypeRef::Never => TyKind::Never.intern(&Interner),
151 TypeRef::Tuple(inner) => {
152 let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| Ty::from_hir(ctx, tr)).collect();
153 TyKind::Tuple(inner_tys.len(), Substs(inner_tys)).intern(&Interner)
155 TypeRef::Path(path) => {
156 let (ty, res_) = Ty::from_hir_path(ctx, path);
160 TypeRef::RawPtr(inner, mutability) => {
161 let inner_ty = Ty::from_hir(ctx, inner);
162 TyKind::Raw(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty))
165 TypeRef::Array(inner) => {
166 let inner_ty = Ty::from_hir(ctx, inner);
167 TyKind::Array(Substs::single(inner_ty)).intern(&Interner)
169 TypeRef::Slice(inner) => {
170 let inner_ty = Ty::from_hir(ctx, inner);
171 TyKind::Slice(Substs::single(inner_ty)).intern(&Interner)
173 TypeRef::Reference(inner, _, mutability) => {
174 let inner_ty = Ty::from_hir(ctx, inner);
175 TyKind::Ref(lower_to_chalk_mutability(*mutability), Substs::single(inner_ty))
178 TypeRef::Placeholder => TyKind::Unknown.intern(&Interner),
179 TypeRef::Fn(params, is_varargs) => {
180 let substs = Substs(params.iter().map(|tr| Ty::from_hir(ctx, tr)).collect());
181 TyKind::Function(FnPointer {
182 num_args: substs.len() - 1,
183 sig: FnSig { variadic: *is_varargs },
188 TypeRef::DynTrait(bounds) => {
190 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
191 let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| {
194 .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
197 TyKind::Dyn(predicates).intern(&Interner)
199 TypeRef::ImplTrait(bounds) => {
200 match ctx.impl_trait_mode {
201 ImplTraitLoweringMode::Opaque => {
202 let idx = ctx.impl_trait_counter.get();
203 ctx.impl_trait_counter.set(idx + 1);
205 assert!(idx as usize == ctx.opaque_type_data.borrow().len());
206 // this dance is to make sure the data is in the right
207 // place even if we encounter more opaque types while
208 // lowering the bounds
211 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
212 // We don't want to lower the bounds inside the binders
213 // we're currently in, because they don't end up inside
214 // those binders. E.g. when we have `impl Trait<impl
215 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
216 // to the self parameter from `impl Trait`, and the
217 // bounds aren't actually stored nested within each
218 // other, but separately. So if the `T` refers to a type
219 // parameter of the outer function, it's just one binder
220 // away instead of two.
221 let actual_opaque_type_data = ctx
222 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
223 ReturnTypeImplTrait::from_hir(ctx, &bounds)
225 ctx.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
227 let func = match ctx.resolver.generic_def() {
228 Some(GenericDefId::FunctionId(f)) => f,
229 _ => panic!("opaque impl trait lowering in non-function"),
231 let impl_trait_id = OpaqueTyId::ReturnTypeImplTrait(func, idx);
232 let generics = generics(ctx.db.upcast(), func.into());
233 let parameters = Substs::bound_vars(&generics, ctx.in_binders);
234 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
235 opaque_ty_id: impl_trait_id,
240 ImplTraitLoweringMode::Param => {
241 let idx = ctx.impl_trait_counter.get();
242 // FIXME we're probably doing something wrong here
243 ctx.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
244 if let Some(def) = ctx.resolver.generic_def() {
245 let generics = generics(ctx.db.upcast(), def);
248 .filter(|(_, data)| {
249 data.provenance == TypeParamProvenance::ArgumentImplTrait
252 .map_or(TyKind::Unknown, |(id, _)| TyKind::Placeholder(id));
253 param.intern(&Interner)
255 TyKind::Unknown.intern(&Interner)
258 ImplTraitLoweringMode::Variable => {
259 let idx = ctx.impl_trait_counter.get();
260 // FIXME we're probably doing something wrong here
261 ctx.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) = ctx.resolver.generic_def() {
264 let generics = generics(ctx.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 from_hir_only_param(ctx: &TyLoweringContext<'_>, 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 ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) {
302 Some((it, None)) => it,
305 if let TypeNs::GenericParam(param_id) = resolution {
312 pub(crate) fn from_type_relative_path(
313 ctx: &TyLoweringContext<'_>,
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 (Ty::select_associated_type(ctx, 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 from_partly_resolved_hir_path(
332 ctx: &TyLoweringContext<'_>,
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 TraitRef::from_resolved_path(ctx, 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: to_assoc_type_id(associated_ty),
363 parameters: 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 ctx.resolver.generic_def().expect("generics in scope"),
386 match ctx.type_param_mode {
387 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(param_id),
388 TypeParamLoweringMode::Variable => {
389 let idx = generics.param_idx(param_id).expect("matching generics");
390 TyKind::BoundVar(BoundVar::new(ctx.in_binders, idx))
395 TypeNs::SelfType(impl_id) => {
396 let generics = generics(ctx.db.upcast(), impl_id.into());
397 let substs = match ctx.type_param_mode {
398 TypeParamLoweringMode::Placeholder => {
399 Substs::type_params_for_generics(&generics)
401 TypeParamLoweringMode::Variable => {
402 Substs::bound_vars(&generics, ctx.in_binders)
405 ctx.db.impl_self_ty(impl_id).subst(&substs)
407 TypeNs::AdtSelfType(adt) => {
408 let generics = generics(ctx.db.upcast(), adt.into());
409 let substs = match ctx.type_param_mode {
410 TypeParamLoweringMode::Placeholder => {
411 Substs::type_params_for_generics(&generics)
413 TypeParamLoweringMode::Variable => {
414 Substs::bound_vars(&generics, ctx.in_binders)
417 ctx.db.ty(adt.into()).subst(&substs)
420 TypeNs::AdtId(it) => {
421 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
423 TypeNs::BuiltinType(it) => {
424 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
426 TypeNs::TypeAliasId(it) => {
427 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
429 // FIXME: report error
430 TypeNs::EnumVariantId(_) => return (TyKind::Unknown.intern(&Interner), None),
432 Ty::from_type_relative_path(ctx, ty, Some(resolution), remaining_segments)
435 pub(crate) fn from_hir_path(ctx: &TyLoweringContext<'_>, 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) = Ty::from_hir_ext(ctx, &type_ref);
439 return Ty::from_type_relative_path(ctx, ty, res, path.segments());
441 let (resolution, remaining_index) =
442 match ctx.resolver.resolve_path_in_type_ns(ctx.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 Ty::from_partly_resolved_hir_path(
462 fn select_associated_type(
463 ctx: &TyLoweringContext<'_>,
465 segment: PathSegment<'_>,
467 if let Some(res) = res {
469 associated_type_shorthand_candidates(ctx.db, res, move |name, t, associated_ty| {
470 if name == segment.name {
471 let substs = match ctx.type_param_mode {
472 TypeParamLoweringMode::Placeholder => {
473 // if we're lowering to placeholders, we have to put
475 let s = Substs::type_params(
477 ctx.resolver.generic_def().expect(
478 "there should be generics if there's a generic param",
481 t.substs.clone().subst_bound_vars(&s)
483 TypeParamLoweringMode::Variable => t.substs.clone(),
485 // We need to shift in the bound vars, since
486 // associated_type_shorthand_candidates does not do that
487 let substs = substs.shift_bound_vars(ctx.in_binders);
488 // FIXME handle type parameters on the segment
490 TyKind::Alias(AliasTy::Projection(ProjectionTy {
491 associated_ty: to_assoc_type_id(associated_ty),
501 ty.unwrap_or(TyKind::Unknown.intern(&Interner))
503 TyKind::Unknown.intern(&Interner)
507 fn from_hir_path_inner(
508 ctx: &TyLoweringContext<'_>,
509 segment: PathSegment<'_>,
513 let generic_def = match typeable {
514 TyDefId::BuiltinType(_) => None,
515 TyDefId::AdtId(it) => Some(it.into()),
516 TyDefId::TypeAliasId(it) => Some(it.into()),
518 let substs = substs_from_path_segment(ctx, segment, generic_def, infer_args);
519 ctx.db.ty(typeable).subst(&substs)
522 /// Collect generic arguments from a path into a `Substs`. See also
523 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
524 pub(super) fn substs_from_path(
525 ctx: &TyLoweringContext<'_>,
527 // Note that we don't call `db.value_type(resolved)` here,
528 // `ValueTyDefId` is just a convenient way to pass generics and
529 // special-case enum variants
530 resolved: ValueTyDefId,
533 let last = path.segments().last().expect("path should have at least one segment");
534 let (segment, generic_def) = match resolved {
535 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
536 ValueTyDefId::StructId(it) => (last, Some(it.into())),
537 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
538 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
539 ValueTyDefId::StaticId(_) => (last, None),
540 ValueTyDefId::EnumVariantId(var) => {
541 // the generic args for an enum variant may be either specified
542 // on the segment referring to the enum, or on the segment
543 // referring to the variant. So `Option::<T>::None` and
544 // `Option::None::<T>` are both allowed (though the former is
545 // preferred). See also `def_ids_for_path_segments` in rustc.
546 let len = path.segments().len();
547 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
548 let segment = match penultimate {
549 Some(segment) if segment.args_and_bindings.is_some() => segment,
552 (segment, Some(var.parent.into()))
555 substs_from_path_segment(ctx, segment, generic_def, infer_args)
559 fn substs_from_path_segment(
560 ctx: &TyLoweringContext<'_>,
561 segment: PathSegment<'_>,
562 def_generic: Option<GenericDefId>,
565 let mut substs = Vec::new();
566 let def_generics = def_generic.map(|def| generics(ctx.db.upcast(), def));
568 let (parent_params, self_params, type_params, impl_trait_params) =
569 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
570 let total_len = parent_params + self_params + type_params + impl_trait_params;
572 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(parent_params));
574 let mut had_explicit_type_args = false;
576 if let Some(generic_args) = &segment.args_and_bindings {
577 if !generic_args.has_self_type {
578 substs.extend(iter::repeat(TyKind::Unknown.intern(&Interner)).take(self_params));
581 if generic_args.has_self_type { self_params + type_params } else { type_params };
582 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
583 // if args are provided, it should be all of them, but we can't rely on that
584 for arg in generic_args
587 .filter(|arg| matches!(arg, GenericArg::Type(_)))
592 GenericArg::Type(type_ref) => {
593 had_explicit_type_args = true;
594 let ty = Ty::from_hir(ctx, type_ref);
597 GenericArg::Lifetime(_) => {}
602 // handle defaults. In expression or pattern path segments without
603 // explicitly specified type arguments, missing type arguments are inferred
604 // (i.e. defaults aren't used).
605 if !infer_args || had_explicit_type_args {
606 if let Some(def_generic) = def_generic {
607 let defaults = ctx.db.generic_defaults(def_generic);
608 assert_eq!(total_len, defaults.len());
610 for default_ty in defaults.iter().skip(substs.len()) {
611 // each default can depend on the previous parameters
612 let substs_so_far = Substs(substs.clone().into());
613 substs.push(default_ty.clone().subst(&substs_so_far));
618 // add placeholders for args that were not provided
619 // FIXME: emit diagnostics in contexts where this is not allowed
620 for _ in substs.len()..total_len {
621 substs.push(TyKind::Unknown.intern(&Interner));
623 assert_eq!(substs.len(), total_len);
625 Substs(substs.into())
630 ctx: &TyLoweringContext<'_>,
632 explicit_self_ty: Option<Ty>,
635 match ctx.resolver.resolve_path_in_type_ns_fully(ctx.db.upcast(), path.mod_path())? {
636 TypeNs::TraitId(tr) => tr,
639 let segment = path.segments().last().expect("path should have at least one segment");
640 Some(TraitRef::from_resolved_path(ctx, resolved, segment, explicit_self_ty))
643 pub(crate) fn from_resolved_path(
644 ctx: &TyLoweringContext<'_>,
646 segment: PathSegment<'_>,
647 explicit_self_ty: Option<Ty>,
649 let mut substs = TraitRef::substs_from_path(ctx, segment, resolved);
650 if let Some(self_ty) = explicit_self_ty {
651 make_mut_slice(&mut substs.0)[0] = self_ty;
653 TraitRef { trait_: resolved, substs }
657 ctx: &TyLoweringContext<'_>,
659 explicit_self_ty: Option<Ty>,
661 let path = match type_ref {
662 TypeRef::Path(path) => path,
665 TraitRef::from_path(ctx, path, explicit_self_ty)
669 ctx: &TyLoweringContext<'_>,
670 segment: PathSegment<'_>,
673 substs_from_path_segment(ctx, segment, Some(resolved.into()), false)
677 impl GenericPredicate {
678 pub(crate) fn from_where_predicate<'a>(
679 ctx: &'a TyLoweringContext<'a>,
680 where_predicate: &'a WherePredicate,
681 ) -> impl Iterator<Item = GenericPredicate> + 'a {
682 match where_predicate {
683 WherePredicate::ForLifetime { target, bound, .. }
684 | WherePredicate::TypeBound { target, bound } => {
685 let self_ty = match target {
686 WherePredicateTypeTarget::TypeRef(type_ref) => Ty::from_hir(ctx, type_ref),
687 WherePredicateTypeTarget::TypeParam(param_id) => {
688 let generic_def = ctx.resolver.generic_def().expect("generics in scope");
689 let generics = generics(ctx.db.upcast(), generic_def);
691 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
692 match ctx.type_param_mode {
693 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(param_id),
694 TypeParamLoweringMode::Variable => {
695 let idx = generics.param_idx(param_id).expect("matching generics");
696 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
702 GenericPredicate::from_type_bound(ctx, bound, self_ty)
706 WherePredicate::Lifetime { .. } => vec![].into_iter(),
710 pub(crate) fn from_type_bound<'a>(
711 ctx: &'a TyLoweringContext<'a>,
712 bound: &'a TypeBound,
714 ) -> impl Iterator<Item = GenericPredicate> + 'a {
715 let mut bindings = None;
716 let trait_ref = match bound {
717 TypeBound::Path(path) => {
718 bindings = TraitRef::from_path(ctx, path, Some(self_ty));
720 bindings.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented),
723 TypeBound::Lifetime(_) => None,
724 TypeBound::Error => Some(GenericPredicate::Error),
726 trait_ref.into_iter().chain(
729 .flat_map(move |tr| assoc_type_bindings_from_type_bound(ctx, bound, tr)),
734 fn assoc_type_bindings_from_type_bound<'a>(
735 ctx: &'a TyLoweringContext<'a>,
736 bound: &'a TypeBound,
738 ) -> impl Iterator<Item = GenericPredicate> + 'a {
739 let last_segment = match bound {
740 TypeBound::Path(path) => path.segments().last(),
741 TypeBound::Error | TypeBound::Lifetime(_) => None,
745 .flat_map(|segment| segment.args_and_bindings.into_iter())
746 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
747 .flat_map(move |binding| {
748 let found = associated_type_by_name_including_super_traits(
753 let (super_trait_ref, associated_ty) = match found {
754 None => return SmallVec::<[GenericPredicate; 1]>::new(),
757 let projection_ty = ProjectionTy {
758 associated_ty: to_assoc_type_id(associated_ty),
759 parameters: super_trait_ref.substs,
761 let mut preds = SmallVec::with_capacity(
762 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
764 if let Some(type_ref) = &binding.type_ref {
765 let ty = Ty::from_hir(ctx, type_ref);
766 let projection_predicate =
767 ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
768 preds.push(GenericPredicate::Projection(projection_predicate));
770 for bound in &binding.bounds {
771 preds.extend(GenericPredicate::from_type_bound(
774 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
781 impl ReturnTypeImplTrait {
782 fn from_hir(ctx: &TyLoweringContext, bounds: &[TypeBound]) -> Self {
783 cov_mark::hit!(lower_rpit);
785 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
786 let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| {
789 .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
792 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
796 fn count_impl_traits(type_ref: &TypeRef) -> usize {
798 type_ref.walk(&mut |type_ref| {
799 if matches!(type_ref, TypeRef::ImplTrait(_)) {
806 /// Build the signature of a callable item (function, struct or enum variant).
807 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
809 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
810 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
811 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
815 pub fn associated_type_shorthand_candidates<R>(
816 db: &dyn HirDatabase,
818 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
820 let traits_from_env: Vec<_> = match res {
821 TypeNs::SelfType(impl_id) => match db.impl_trait(impl_id) {
823 Some(trait_ref) => vec![trait_ref.value],
825 TypeNs::GenericParam(param_id) => {
826 let predicates = db.generic_predicates_for_param(param_id);
827 let mut traits_: Vec<_> = predicates
829 .filter_map(|pred| match &pred.value {
830 GenericPredicate::Implemented(tr) => Some(tr.clone()),
834 // Handle `Self::Type` referring to own associated type in trait definitions
835 if let GenericDefId::TraitId(trait_id) = param_id.parent {
836 let generics = generics(db.upcast(), trait_id.into());
837 if generics.params.types[param_id.local_id].provenance
838 == TypeParamProvenance::TraitSelf
840 let trait_ref = TraitRef {
842 substs: Substs::bound_vars(&generics, DebruijnIndex::INNERMOST),
844 traits_.push(trait_ref);
852 for t in traits_from_env.into_iter().flat_map(move |t| all_super_trait_refs(db, t)) {
853 let data = db.trait_data(t.trait_);
855 for (name, assoc_id) in &data.items {
857 AssocItemId::TypeAliasId(alias) => {
858 if let Some(result) = cb(name, &t, *alias) {
862 AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => {}
870 /// Build the type of all specific fields of a struct or enum variant.
871 pub(crate) fn field_types_query(
872 db: &dyn HirDatabase,
873 variant_id: VariantId,
874 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
875 let var_data = variant_data(db.upcast(), variant_id);
876 let (resolver, def): (_, GenericDefId) = match variant_id {
877 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
878 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
879 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
881 let generics = generics(db.upcast(), def);
882 let mut res = ArenaMap::default();
884 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
885 for (field_id, field_data) in var_data.fields().iter() {
886 res.insert(field_id, Binders::new(generics.len(), Ty::from_hir(&ctx, &field_data.type_ref)))
891 /// This query exists only to be used when resolving short-hand associated types
894 /// See the analogous query in rustc and its comment:
895 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
896 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
897 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
898 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
899 pub(crate) fn generic_predicates_for_param_query(
900 db: &dyn HirDatabase,
901 param_id: TypeParamId,
902 ) -> Arc<[Binders<GenericPredicate>]> {
903 let resolver = param_id.parent.resolver(db.upcast());
905 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
906 let generics = generics(db.upcast(), param_id.parent);
908 .where_predicates_in_scope()
909 // we have to filter out all other predicates *first*, before attempting to lower them
910 .filter(|pred| match pred {
911 WherePredicate::ForLifetime { target, .. }
912 | WherePredicate::TypeBound { target, .. } => match target {
913 WherePredicateTypeTarget::TypeRef(type_ref) => {
914 Ty::from_hir_only_param(&ctx, type_ref) == Some(param_id)
916 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
918 WherePredicate::Lifetime { .. } => false,
921 GenericPredicate::from_where_predicate(&ctx, pred)
922 .map(|p| Binders::new(generics.len(), p))
927 pub(crate) fn generic_predicates_for_param_recover(
928 _db: &dyn HirDatabase,
930 _param_id: &TypeParamId,
931 ) -> Arc<[Binders<GenericPredicate>]> {
935 impl TraitEnvironment {
936 pub fn lower(db: &dyn HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> {
937 let ctx = TyLoweringContext::new(db, &resolver)
938 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
939 let mut traits_in_scope = Vec::new();
940 let mut clauses = Vec::new();
941 for pred in resolver.where_predicates_in_scope() {
942 for pred in GenericPredicate::from_where_predicate(&ctx, pred) {
946 if let GenericPredicate::Implemented(tr) = &pred {
947 traits_in_scope.push((tr.self_ty().clone(), tr.trait_));
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));
955 if let Some(def) = resolver.generic_def() {
956 let container: Option<AssocContainerId> = match def {
957 // FIXME: is there a function for this?
958 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
959 GenericDefId::AdtId(_) => None,
960 GenericDefId::TraitId(_) => None,
961 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
962 GenericDefId::ImplId(_) => None,
963 GenericDefId::EnumVariantId(_) => None,
964 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
966 if let Some(AssocContainerId::TraitId(trait_id)) = container {
967 // add `Self: Trait<T1, T2, ...>` to the environment in trait
968 // function default implementations (and hypothetical code
969 // inside consts or type aliases)
970 cov_mark::hit!(trait_self_implements_self);
971 let substs = Substs::type_params(db, trait_id);
972 let trait_ref = TraitRef { trait_: trait_id, substs };
973 let pred = GenericPredicate::Implemented(trait_ref);
974 let program_clause: chalk_ir::ProgramClause<Interner> =
975 pred.clone().to_chalk(db).cast(&Interner);
976 clauses.push(program_clause.into_from_env_clause(&Interner));
980 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
982 Arc::new(TraitEnvironment { traits_from_clauses: traits_in_scope, env })
986 /// Resolve the where clause(s) of an item with generics.
987 pub(crate) fn generic_predicates_query(
988 db: &dyn HirDatabase,
990 ) -> Arc<[Binders<GenericPredicate>]> {
991 let resolver = def.resolver(db.upcast());
993 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
994 let generics = generics(db.upcast(), def);
996 .where_predicates_in_scope()
998 GenericPredicate::from_where_predicate(&ctx, pred)
999 .map(|p| Binders::new(generics.len(), p))
1004 /// Resolve the default type params from generics
1005 pub(crate) fn generic_defaults_query(
1006 db: &dyn HirDatabase,
1008 ) -> Arc<[Binders<Ty>]> {
1009 let resolver = def.resolver(db.upcast());
1011 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1012 let generic_params = generics(db.upcast(), def);
1014 let defaults = generic_params
1017 .map(|(idx, (_, p))| {
1021 .map_or(TyKind::Unknown.intern(&Interner), |t| Ty::from_hir(&ctx, t));
1023 // Each default can only refer to previous parameters.
1024 ty.walk_mut_binders(
1025 &mut |ty, binders| match &mut ty.0 {
1026 TyKind::BoundVar(BoundVar { debruijn, index }) if *debruijn == binders => {
1028 // type variable default referring to parameter coming
1029 // after it. This is forbidden (FIXME: report
1031 *ty = TyKind::Unknown.intern(&Interner);
1036 DebruijnIndex::INNERMOST,
1039 Binders::new(idx, ty)
1046 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1047 let data = db.function_data(def);
1048 let resolver = def.resolver(db.upcast());
1049 let ctx_params = TyLoweringContext::new(db, &resolver)
1050 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1051 .with_type_param_mode(TypeParamLoweringMode::Variable);
1052 let params = data.params.iter().map(|tr| Ty::from_hir(&ctx_params, tr)).collect::<Vec<_>>();
1053 let ctx_ret = TyLoweringContext::new(db, &resolver)
1054 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1055 .with_type_param_mode(TypeParamLoweringMode::Variable);
1056 let ret = Ty::from_hir(&ctx_ret, &data.ret_type);
1057 let generics = generics(db.upcast(), def.into());
1058 let num_binders = generics.len();
1059 Binders::new(num_binders, CallableSig::from_params_and_return(params, ret, data.is_varargs))
1062 /// Build the declared type of a function. This should not need to look at the
1064 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1065 let generics = generics(db.upcast(), def.into());
1066 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1069 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1073 /// Build the declared type of a const.
1074 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1075 let data = db.const_data(def);
1076 let generics = generics(db.upcast(), def.into());
1077 let resolver = def.resolver(db.upcast());
1079 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1081 Binders::new(generics.len(), Ty::from_hir(&ctx, &data.type_ref))
1084 /// Build the declared type of a static.
1085 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1086 let data = db.static_data(def);
1087 let resolver = def.resolver(db.upcast());
1088 let ctx = TyLoweringContext::new(db, &resolver);
1090 Binders::new(0, Ty::from_hir(&ctx, &data.type_ref))
1093 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1094 let struct_data = db.struct_data(def);
1095 let fields = struct_data.variant_data.fields();
1096 let resolver = def.resolver(db.upcast());
1098 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1100 fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
1101 let ret = type_for_adt(db, def.into());
1102 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1105 /// Build the type of a tuple struct constructor.
1106 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1107 let struct_data = db.struct_data(def);
1108 if let StructKind::Unit = struct_data.variant_data.kind() {
1109 return type_for_adt(db, def.into());
1111 let generics = generics(db.upcast(), def.into());
1112 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1115 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1119 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1120 let enum_data = db.enum_data(def.parent);
1121 let var_data = &enum_data.variants[def.local_id];
1122 let fields = var_data.variant_data.fields();
1123 let resolver = def.parent.resolver(db.upcast());
1125 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1127 fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
1128 let ret = type_for_adt(db, def.parent.into());
1129 Binders::new(ret.num_binders, CallableSig::from_params_and_return(params, ret.value, false))
1132 /// Build the type of a tuple enum variant constructor.
1133 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1134 let enum_data = db.enum_data(def.parent);
1135 let var_data = &enum_data.variants[def.local_id].variant_data;
1136 if let StructKind::Unit = var_data.kind() {
1137 return type_for_adt(db, def.parent.into());
1139 let generics = generics(db.upcast(), def.parent.into());
1140 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1143 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1147 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1148 let generics = generics(db.upcast(), adt.into());
1149 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1150 Binders::new(substs.len(), Ty::adt_ty(adt, substs))
1153 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1154 let generics = generics(db.upcast(), t.into());
1155 let resolver = t.resolver(db.upcast());
1157 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1158 if db.type_alias_data(t).is_extern {
1159 Binders::new(0, TyKind::ForeignType(crate::to_foreign_def_id(t)).intern(&Interner))
1161 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1162 let type_ref = &db.type_alias_data(t).type_ref;
1163 let inner = Ty::from_hir(&ctx, type_ref.as_ref().unwrap_or(&TypeRef::Error));
1164 Binders::new(substs.len(), inner)
1168 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1169 pub enum CallableDefId {
1170 FunctionId(FunctionId),
1172 EnumVariantId(EnumVariantId),
1174 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1176 impl CallableDefId {
1177 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1178 let db = db.upcast();
1180 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1181 CallableDefId::StructId(s) => s.lookup(db).container,
1182 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1188 impl From<CallableDefId> for GenericDefId {
1189 fn from(def: CallableDefId) -> GenericDefId {
1191 CallableDefId::FunctionId(f) => f.into(),
1192 CallableDefId::StructId(s) => s.into(),
1193 CallableDefId::EnumVariantId(e) => e.into(),
1198 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1200 BuiltinType(BuiltinType),
1202 TypeAliasId(TypeAliasId),
1204 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1206 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1207 pub enum ValueTyDefId {
1208 FunctionId(FunctionId),
1211 EnumVariantId(EnumVariantId),
1215 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1217 /// Build the declared type of an item. This depends on the namespace; e.g. for
1218 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1219 /// the constructor function `(usize) -> Foo` which lives in the values
1221 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1223 TyDefId::BuiltinType(it) => Binders::new(0, Ty::builtin(it)),
1224 TyDefId::AdtId(it) => type_for_adt(db, it),
1225 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1229 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1230 let num_binders = match *def {
1231 TyDefId::BuiltinType(_) => 0,
1232 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1233 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1235 Binders::new(num_binders, TyKind::Unknown.intern(&Interner))
1238 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1240 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1241 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1242 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1243 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1244 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1245 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1249 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1250 let impl_data = db.impl_data(impl_id);
1251 let resolver = impl_id.resolver(db.upcast());
1252 let generics = generics(db.upcast(), impl_id.into());
1254 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1255 Binders::new(generics.len(), Ty::from_hir(&ctx, &impl_data.target_type))
1258 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1259 let parent_data = db.generic_params(def.parent);
1260 let data = &parent_data.consts[def.local_id];
1261 let resolver = def.parent.resolver(db.upcast());
1262 let ctx = TyLoweringContext::new(db, &resolver);
1264 Ty::from_hir(&ctx, &data.ty)
1267 pub(crate) fn impl_self_ty_recover(
1268 db: &dyn HirDatabase,
1272 let generics = generics(db.upcast(), (*impl_id).into());
1273 Binders::new(generics.len(), TyKind::Unknown.intern(&Interner))
1276 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1277 let impl_data = db.impl_data(impl_id);
1278 let resolver = impl_id.resolver(db.upcast());
1280 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1281 let self_ty = db.impl_self_ty(impl_id);
1282 let target_trait = impl_data.target_trait.as_ref()?;
1284 self_ty.num_binders,
1285 TraitRef::from_hir(&ctx, target_trait, Some(self_ty.value))?,
1289 pub(crate) fn return_type_impl_traits(
1290 db: &dyn HirDatabase,
1291 def: hir_def::FunctionId,
1292 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1293 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1294 let data = db.function_data(def);
1295 let resolver = def.resolver(db.upcast());
1296 let ctx_ret = TyLoweringContext::new(db, &resolver)
1297 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1298 .with_type_param_mode(TypeParamLoweringMode::Variable);
1299 let _ret = Ty::from_hir(&ctx_ret, &data.ret_type);
1300 let generics = generics(db.upcast(), def.into());
1301 let num_binders = generics.len();
1302 let return_type_impl_traits =
1303 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1304 if return_type_impl_traits.impl_traits.is_empty() {
1307 Some(Arc::new(Binders::new(num_binders, return_type_impl_traits)))
1311 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1313 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1314 hir_def::type_ref::Mutability::Mut => Mutability::Mut,