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::cell::{Cell, RefCell};
9 use std::{iter, sync::Arc};
12 use chalk_ir::{cast::Cast, fold::Shift, interner::HasInterner, Mutability, Safety};
13 use hir_def::intern::Interned;
16 body::{Expander, LowerCtx},
17 builtin_type::BuiltinType,
18 generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget},
19 path::{GenericArg, Path, PathSegment, PathSegments},
20 resolver::{HasResolver, Resolver, TypeNs},
21 type_ref::{TraitRef as HirTraitRef, TypeBound, TypeRef},
22 AdtId, AssocContainerId, AssocItemId, ConstId, ConstParamId, EnumId, EnumVariantId, FunctionId,
23 GenericDefId, HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId,
24 TypeAliasId, TypeParamId, UnionId, VariantId,
26 use hir_expand::{name::Name, ExpandResult};
27 use la_arena::ArenaMap;
28 use smallvec::SmallVec;
36 static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx,
38 all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics,
40 AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig,
41 FnSubst, ImplTraitId, Interner, OpaqueTy, PolyFnSig, ProjectionTy, QuantifiedWhereClause,
42 QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution,
43 TraitEnvironment, TraitRef, TraitRefExt, Ty, TyBuilder, TyKind, WhereClause,
47 pub struct TyLoweringContext<'a> {
48 pub db: &'a dyn HirDatabase,
49 pub resolver: &'a Resolver,
50 in_binders: DebruijnIndex,
51 /// Note: Conceptually, it's thinkable that we could be in a location where
52 /// some type params should be represented as placeholders, and others
53 /// should be converted to variables. I think in practice, this isn't
54 /// possible currently, so this should be fine for now.
55 pub type_param_mode: TypeParamLoweringMode,
56 pub impl_trait_mode: ImplTraitLoweringMode,
57 impl_trait_counter: Cell<u16>,
58 /// When turning `impl Trait` into opaque types, we have to collect the
59 /// bounds at the same time to get the IDs correct (without becoming too
60 /// complicated). I don't like using interior mutability (as for the
61 /// counter), but I've tried and failed to make the lifetimes work for
62 /// passing around a `&mut TyLoweringContext`. The core problem is that
63 /// we're grouping the mutable data (the counter and this field) together
64 /// with the immutable context (the references to the DB and resolver).
65 /// Splitting this up would be a possible fix.
66 opaque_type_data: RefCell<Vec<ReturnTypeImplTrait>>,
67 expander: RefCell<Option<Expander>>,
70 impl<'a> TyLoweringContext<'a> {
71 pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
72 let impl_trait_counter = Cell::new(0);
73 let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
74 let type_param_mode = TypeParamLoweringMode::Placeholder;
75 let in_binders = DebruijnIndex::INNERMOST;
76 let opaque_type_data = RefCell::new(Vec::new());
85 expander: RefCell::new(None),
89 pub fn with_debruijn<T>(
91 debruijn: DebruijnIndex,
92 f: impl FnOnce(&TyLoweringContext) -> T,
94 let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new());
95 let expander = self.expander.replace(None);
98 impl_trait_counter: Cell::new(self.impl_trait_counter.get()),
99 opaque_type_data: RefCell::new(opaque_ty_data_vec),
100 expander: RefCell::new(expander),
103 let result = f(&new_ctx);
104 self.impl_trait_counter.set(new_ctx.impl_trait_counter.get());
105 self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner());
106 self.expander.replace(new_ctx.expander.into_inner());
110 pub fn with_shifted_in<T>(
112 debruijn: DebruijnIndex,
113 f: impl FnOnce(&TyLoweringContext) -> T,
115 self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
118 pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
119 Self { impl_trait_mode, ..self }
122 pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
123 Self { type_param_mode, ..self }
127 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
128 pub enum ImplTraitLoweringMode {
129 /// `impl Trait` gets lowered into an opaque type that doesn't unify with
130 /// anything except itself. This is used in places where values flow 'out',
131 /// i.e. for arguments of the function we're currently checking, and return
132 /// types of functions we're calling.
134 /// `impl Trait` gets lowered into a type variable. Used for argument
135 /// position impl Trait when inside the respective function, since it allows
136 /// us to support that without Chalk.
138 /// `impl Trait` gets lowered into a variable that can unify with some
139 /// type. This is used in places where values flow 'in', i.e. for arguments
140 /// of functions we're calling, and the return type of the function we're
141 /// currently checking.
143 /// `impl Trait` is disallowed and will be an error.
147 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
148 pub enum TypeParamLoweringMode {
153 impl<'a> TyLoweringContext<'a> {
154 pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
155 self.lower_ty_ext(type_ref).0
158 pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
160 let ty = match type_ref {
161 TypeRef::Never => TyKind::Never.intern(&Interner),
162 TypeRef::Tuple(inner) => {
163 let inner_tys = inner.iter().map(|tr| self.lower_ty(tr));
164 TyKind::Tuple(inner_tys.len(), Substitution::from_iter(&Interner, inner_tys))
167 TypeRef::Path(path) => {
168 let (ty, res_) = self.lower_path(path);
172 TypeRef::RawPtr(inner, mutability) => {
173 let inner_ty = self.lower_ty(inner);
174 TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(&Interner)
176 TypeRef::Array(inner, len) => {
177 let inner_ty = self.lower_ty(inner);
179 let const_len = consteval::usize_const(len.as_usize());
181 TyKind::Array(inner_ty, const_len).intern(&Interner)
183 TypeRef::Slice(inner) => {
184 let inner_ty = self.lower_ty(inner);
185 TyKind::Slice(inner_ty).intern(&Interner)
187 TypeRef::Reference(inner, _, mutability) => {
188 let inner_ty = self.lower_ty(inner);
189 let lifetime = static_lifetime();
190 TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty)
193 TypeRef::Placeholder => TyKind::Error.intern(&Interner),
194 TypeRef::Fn(params, is_varargs) => {
195 let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
196 Substitution::from_iter(&Interner, params.iter().map(|tr| ctx.lower_ty(tr)))
198 TyKind::Function(FnPointer {
199 num_binders: 0, // FIXME lower `for<'a> fn()` correctly
200 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
201 substitution: FnSubst(substs),
205 TypeRef::DynTrait(bounds) => {
207 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
208 let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
209 QuantifiedWhereClauses::from_iter(
211 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)),
214 let bounds = crate::make_only_type_binders(1, bounds);
215 TyKind::Dyn(DynTy { bounds, lifetime: static_lifetime() }).intern(&Interner)
217 TypeRef::ImplTrait(bounds) => {
218 match self.impl_trait_mode {
219 ImplTraitLoweringMode::Opaque => {
220 let idx = self.impl_trait_counter.get();
221 self.impl_trait_counter.set(idx + 1);
223 assert!(idx as usize == self.opaque_type_data.borrow().len());
224 // this dance is to make sure the data is in the right
225 // place even if we encounter more opaque types while
226 // lowering the bounds
227 self.opaque_type_data.borrow_mut().push(ReturnTypeImplTrait {
228 bounds: crate::make_only_type_binders(1, Vec::new()),
230 // We don't want to lower the bounds inside the binders
231 // we're currently in, because they don't end up inside
232 // those binders. E.g. when we have `impl Trait<impl
233 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
234 // to the self parameter from `impl Trait`, and the
235 // bounds aren't actually stored nested within each
236 // other, but separately. So if the `T` refers to a type
237 // parameter of the outer function, it's just one binder
238 // away instead of two.
239 let actual_opaque_type_data = self
240 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
241 ctx.lower_impl_trait(&bounds)
243 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
245 let func = match self.resolver.generic_def() {
246 Some(GenericDefId::FunctionId(f)) => f,
247 _ => panic!("opaque impl trait lowering in non-function"),
249 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
250 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
251 let generics = generics(self.db.upcast(), func.into());
252 let parameters = generics.bound_vars_subst(self.in_binders);
253 TyKind::Alias(AliasTy::Opaque(OpaqueTy {
255 substitution: parameters,
259 ImplTraitLoweringMode::Param => {
260 let idx = self.impl_trait_counter.get();
261 // FIXME we're probably doing something wrong here
262 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
263 if let Some(def) = self.resolver.generic_def() {
264 let generics = generics(self.db.upcast(), def);
267 .filter(|(_, data)| {
268 data.provenance == TypeParamProvenance::ArgumentImplTrait
271 .map_or(TyKind::Error, |(id, _)| {
272 TyKind::Placeholder(to_placeholder_idx(self.db, id))
274 param.intern(&Interner)
276 TyKind::Error.intern(&Interner)
279 ImplTraitLoweringMode::Variable => {
280 let idx = self.impl_trait_counter.get();
281 // FIXME we're probably doing something wrong here
282 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
283 let (parent_params, self_params, list_params, _impl_trait_params) =
284 if let Some(def) = self.resolver.generic_def() {
285 let generics = generics(self.db.upcast(), def);
286 generics.provenance_split()
290 TyKind::BoundVar(BoundVar::new(
292 idx as usize + parent_params + self_params + list_params,
296 ImplTraitLoweringMode::Disallowed => {
297 // FIXME: report error
298 TyKind::Error.intern(&Interner)
302 TypeRef::Macro(macro_call) => {
303 let (expander, recursion_start) = {
304 let mut expander = self.expander.borrow_mut();
305 if expander.is_some() {
306 (Some(expander), false)
308 if let Some(module_id) = self.resolver.module() {
309 *expander = Some(Expander::new(
314 (Some(expander), true)
320 let ty = if let Some(mut expander) = expander {
321 let expander_mut = expander.as_mut().unwrap();
322 let macro_call = macro_call.to_node(self.db.upcast());
323 match expander_mut.enter_expand::<ast::Type>(self.db.upcast(), macro_call) {
324 Ok(ExpandResult { value: Some((mark, expanded)), .. }) => {
326 LowerCtx::new(self.db.upcast(), expander_mut.current_file_id());
327 let type_ref = TypeRef::from_ast(&ctx, expanded);
330 let ty = self.lower_ty(&type_ref);
336 .exit(self.db.upcast(), mark);
345 *self.expander.borrow_mut() = None;
347 ty.unwrap_or_else(|| TyKind::Error.intern(&Interner))
349 TypeRef::Error => TyKind::Error.intern(&Interner),
354 /// This is only for `generic_predicates_for_param`, where we can't just
355 /// lower the self types of the predicates since that could lead to cycles.
356 /// So we just check here if the `type_ref` resolves to a generic param, and which.
357 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeParamId> {
358 let path = match type_ref {
359 TypeRef::Path(path) => path,
362 if path.type_anchor().is_some() {
365 if path.segments().len() > 1 {
369 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
370 Some((it, None)) => it,
373 if let TypeNs::GenericParam(param_id) = resolution {
380 pub(crate) fn lower_ty_relative_path(
383 // We need the original resolution to lower `Self::AssocTy` correctly
385 remaining_segments: PathSegments<'_>,
386 ) -> (Ty, Option<TypeNs>) {
387 if remaining_segments.len() == 1 {
388 // resolve unselected assoc types
389 let segment = remaining_segments.first().unwrap();
390 (self.select_associated_type(res, segment), None)
391 } else if remaining_segments.len() > 1 {
392 // FIXME report error (ambiguous associated type)
393 (TyKind::Error.intern(&Interner), None)
399 pub(crate) fn lower_partly_resolved_path(
402 resolved_segment: PathSegment<'_>,
403 remaining_segments: PathSegments<'_>,
405 ) -> (Ty, Option<TypeNs>) {
406 let ty = match resolution {
407 TypeNs::TraitId(trait_) => {
408 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
409 let self_ty = if remaining_segments.len() == 0 {
411 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
418 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, self_ty);
419 let ty = if remaining_segments.len() == 1 {
420 let segment = remaining_segments.first().unwrap();
423 .trait_data(trait_ref.hir_trait_id())
424 .associated_type_by_name(&segment.name);
426 Some(associated_ty) => {
427 // FIXME handle type parameters on the segment
428 TyKind::Alias(AliasTy::Projection(ProjectionTy {
429 associated_ty_id: to_assoc_type_id(associated_ty),
430 substitution: trait_ref.substitution,
435 // FIXME: report error (associated type not found)
436 TyKind::Error.intern(&Interner)
439 } else if remaining_segments.len() > 1 {
440 // FIXME report error (ambiguous associated type)
441 TyKind::Error.intern(&Interner)
444 bounds: crate::make_only_type_binders(
446 QuantifiedWhereClauses::from_iter(
448 Some(crate::wrap_empty_binders(WhereClause::Implemented(
453 lifetime: static_lifetime(),
455 TyKind::Dyn(dyn_ty).intern(&Interner)
459 TypeNs::GenericParam(param_id) => {
460 let generics = generics(
462 self.resolver.generic_def().expect("generics in scope"),
464 match self.type_param_mode {
465 TypeParamLoweringMode::Placeholder => {
466 TyKind::Placeholder(to_placeholder_idx(self.db, param_id))
468 TypeParamLoweringMode::Variable => {
469 let idx = generics.param_idx(param_id).expect("matching generics");
470 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
475 TypeNs::SelfType(impl_id) => {
476 let generics = generics(self.db.upcast(), impl_id.into());
477 let substs = match self.type_param_mode {
478 TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
479 TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
481 self.db.impl_self_ty(impl_id).substitute(&Interner, &substs)
483 TypeNs::AdtSelfType(adt) => {
484 let generics = generics(self.db.upcast(), adt.into());
485 let substs = match self.type_param_mode {
486 TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
487 TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
489 self.db.ty(adt.into()).substitute(&Interner, &substs)
492 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
493 TypeNs::BuiltinType(it) => {
494 self.lower_path_inner(resolved_segment, it.into(), infer_args)
496 TypeNs::TypeAliasId(it) => {
497 self.lower_path_inner(resolved_segment, it.into(), infer_args)
499 // FIXME: report error
500 TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(&Interner), None),
502 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
505 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
506 // Resolve the path (in type namespace)
507 if let Some(type_ref) = path.type_anchor() {
508 let (ty, res) = self.lower_ty_ext(&type_ref);
509 return self.lower_ty_relative_path(ty, res, path.segments());
511 let (resolution, remaining_index) =
512 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
514 None => return (TyKind::Error.intern(&Interner), None),
516 let (resolved_segment, remaining_segments) = match remaining_index {
518 path.segments().last().expect("resolved path has at least one element"),
521 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
523 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
526 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
527 if let Some(res) = res {
528 let ty = associated_type_shorthand_candidates(
531 move |name, t, associated_ty| {
532 if name == segment.name {
533 let substs = match self.type_param_mode {
534 TypeParamLoweringMode::Placeholder => {
535 // if we're lowering to placeholders, we have to put
537 let generics = generics(
539 self.resolver.generic_def().expect(
540 "there should be generics if there's a generic param",
543 let s = generics.type_params_subst(self.db);
544 s.apply(t.substitution.clone(), &Interner)
546 TypeParamLoweringMode::Variable => t.substitution.clone(),
548 // We need to shift in the bound vars, since
549 // associated_type_shorthand_candidates does not do that
550 let substs = substs.shifted_in_from(&Interner, self.in_binders);
551 // FIXME handle type parameters on the segment
553 TyKind::Alias(AliasTy::Projection(ProjectionTy {
554 associated_ty_id: to_assoc_type_id(associated_ty),
555 substitution: substs,
565 ty.unwrap_or(TyKind::Error.intern(&Interner))
567 TyKind::Error.intern(&Interner)
573 segment: PathSegment<'_>,
577 let generic_def = match typeable {
578 TyDefId::BuiltinType(_) => None,
579 TyDefId::AdtId(it) => Some(it.into()),
580 TyDefId::TypeAliasId(it) => Some(it.into()),
582 let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None);
583 self.db.ty(typeable).substitute(&Interner, &substs)
586 /// Collect generic arguments from a path into a `Substs`. See also
587 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
588 pub(super) fn substs_from_path(
591 // Note that we don't call `db.value_type(resolved)` here,
592 // `ValueTyDefId` is just a convenient way to pass generics and
593 // special-case enum variants
594 resolved: ValueTyDefId,
597 let last = path.segments().last().expect("path should have at least one segment");
598 let (segment, generic_def) = match resolved {
599 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
600 ValueTyDefId::StructId(it) => (last, Some(it.into())),
601 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
602 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
603 ValueTyDefId::StaticId(_) => (last, None),
604 ValueTyDefId::EnumVariantId(var) => {
605 // the generic args for an enum variant may be either specified
606 // on the segment referring to the enum, or on the segment
607 // referring to the variant. So `Option::<T>::None` and
608 // `Option::None::<T>` are both allowed (though the former is
609 // preferred). See also `def_ids_for_path_segments` in rustc.
610 let len = path.segments().len();
611 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
612 let segment = match penultimate {
613 Some(segment) if segment.args_and_bindings.is_some() => segment,
616 (segment, Some(var.parent.into()))
619 self.substs_from_path_segment(segment, generic_def, infer_args, None)
622 fn substs_from_path_segment(
624 segment: PathSegment<'_>,
625 def_generic: Option<GenericDefId>,
627 explicit_self_ty: Option<Ty>,
629 let mut substs = Vec::new();
630 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
632 let (parent_params, self_params, type_params, impl_trait_params) =
633 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
634 let total_len = parent_params + self_params + type_params + impl_trait_params;
636 substs.extend(iter::repeat(TyKind::Error.intern(&Interner)).take(parent_params));
638 let fill_self_params = || {
642 .chain(iter::repeat(TyKind::Error.intern(&Interner)))
646 let mut had_explicit_type_args = false;
648 if let Some(generic_args) = &segment.args_and_bindings {
649 if !generic_args.has_self_type {
653 if generic_args.has_self_type { self_params + type_params } else { type_params };
654 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
655 // if args are provided, it should be all of them, but we can't rely on that
656 for arg in generic_args
659 .filter(|arg| matches!(arg, GenericArg::Type(_)))
664 GenericArg::Type(type_ref) => {
665 had_explicit_type_args = true;
666 let ty = self.lower_ty(type_ref);
669 GenericArg::Lifetime(_) => {}
676 // handle defaults. In expression or pattern path segments without
677 // explicitly specified type arguments, missing type arguments are inferred
678 // (i.e. defaults aren't used).
679 if !infer_args || had_explicit_type_args {
680 if let Some(def_generic) = def_generic {
681 let defaults = self.db.generic_defaults(def_generic);
682 assert_eq!(total_len, defaults.len());
684 for default_ty in defaults.iter().skip(substs.len()) {
685 // each default can depend on the previous parameters
686 let substs_so_far = Substitution::from_iter(&Interner, substs.clone());
687 substs.push(default_ty.clone().substitute(&Interner, &substs_so_far));
692 // add placeholders for args that were not provided
693 // FIXME: emit diagnostics in contexts where this is not allowed
694 for _ in substs.len()..total_len {
695 substs.push(TyKind::Error.intern(&Interner));
697 assert_eq!(substs.len(), total_len);
699 Substitution::from_iter(&Interner, substs)
702 fn lower_trait_ref_from_path(
705 explicit_self_ty: Option<Ty>,
706 ) -> Option<TraitRef> {
708 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
709 TypeNs::TraitId(tr) => tr,
712 let segment = path.segments().last().expect("path should have at least one segment");
713 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
716 pub(crate) fn lower_trait_ref_from_resolved_path(
719 segment: PathSegment<'_>,
720 explicit_self_ty: Option<Ty>,
722 let substs = self.trait_ref_substs_from_path(segment, resolved, explicit_self_ty);
723 TraitRef { trait_id: to_chalk_trait_id(resolved), substitution: substs }
728 trait_ref: &HirTraitRef,
729 explicit_self_ty: Option<Ty>,
730 ) -> Option<TraitRef> {
731 self.lower_trait_ref_from_path(&trait_ref.path, explicit_self_ty)
734 fn trait_ref_substs_from_path(
736 segment: PathSegment<'_>,
738 explicit_self_ty: Option<Ty>,
740 self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty)
743 pub(crate) fn lower_where_predicate(
745 where_predicate: &'a WherePredicate,
746 ignore_bindings: bool,
747 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
748 match where_predicate {
749 WherePredicate::ForLifetime { target, bound, .. }
750 | WherePredicate::TypeBound { target, bound } => {
751 let self_ty = match target {
752 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
753 WherePredicateTypeTarget::TypeParam(param_id) => {
754 let generic_def = self.resolver.generic_def().expect("generics in scope");
755 let generics = generics(self.db.upcast(), generic_def);
757 hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
758 let placeholder = to_placeholder_idx(self.db, param_id);
759 match self.type_param_mode {
760 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
761 TypeParamLoweringMode::Variable => {
762 let idx = generics.param_idx(param_id).expect("matching generics");
763 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
769 self.lower_type_bound(bound, self_ty, ignore_bindings)
773 WherePredicate::Lifetime { .. } => vec![].into_iter(),
777 pub(crate) fn lower_type_bound(
779 bound: &'a TypeBound,
781 ignore_bindings: bool,
782 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
783 let mut bindings = None;
784 let trait_ref = match bound {
785 TypeBound::Path(path) => {
786 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
787 bindings.clone().map(WhereClause::Implemented).map(|b| crate::wrap_empty_binders(b))
789 TypeBound::Lifetime(_) => None,
790 TypeBound::Error => None,
792 trait_ref.into_iter().chain(
795 .filter(move |_| !ignore_bindings)
796 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
800 fn assoc_type_bindings_from_type_bound(
802 bound: &'a TypeBound,
804 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
805 let last_segment = match bound {
806 TypeBound::Path(path) => path.segments().last(),
807 TypeBound::Error | TypeBound::Lifetime(_) => None,
811 .flat_map(|segment| segment.args_and_bindings.into_iter())
812 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
813 .flat_map(move |binding| {
814 let found = associated_type_by_name_including_super_traits(
819 let (super_trait_ref, associated_ty) = match found {
820 None => return SmallVec::<[QuantifiedWhereClause; 1]>::new(),
823 let projection_ty = ProjectionTy {
824 associated_ty_id: to_assoc_type_id(associated_ty),
825 substitution: super_trait_ref.substitution,
827 let mut preds = SmallVec::with_capacity(
828 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
830 if let Some(type_ref) = &binding.type_ref {
831 let ty = self.lower_ty(type_ref);
833 AliasEq { alias: AliasTy::Projection(projection_ty.clone()), ty };
834 preds.push(crate::wrap_empty_binders(WhereClause::AliasEq(alias_eq)));
836 for bound in &binding.bounds {
837 preds.extend(self.lower_type_bound(
839 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(&Interner),
847 fn lower_impl_trait(&self, bounds: &[Interned<TypeBound>]) -> ReturnTypeImplTrait {
848 cov_mark::hit!(lower_rpit);
850 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(&Interner);
851 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
852 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)).collect()
854 ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, predicates) }
858 fn count_impl_traits(type_ref: &TypeRef) -> usize {
860 type_ref.walk(&mut |type_ref| {
861 if matches!(type_ref, TypeRef::ImplTrait(_)) {
868 /// Build the signature of a callable item (function, struct or enum variant).
869 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
871 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
872 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
873 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
877 pub fn associated_type_shorthand_candidates<R>(
878 db: &dyn HirDatabase,
880 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
882 let mut search = |t| {
883 for t in all_super_trait_refs(db, t) {
884 let data = db.trait_data(t.hir_trait_id());
886 for (name, assoc_id) in &data.items {
887 if let AssocItemId::TypeAliasId(alias) = assoc_id {
888 if let Some(result) = cb(name, &t, *alias) {
898 TypeNs::SelfType(impl_id) => search(
899 // we're _in_ the impl -- the binders get added back later. Correct,
900 // but it would be nice to make this more explicit
901 db.impl_trait(impl_id)?.into_value_and_skipped_binders().0,
903 TypeNs::GenericParam(param_id) => {
904 let predicates = db.generic_predicates_for_param(param_id);
905 let res = predicates.iter().find_map(|pred| match pred.skip_binders().skip_binders() {
906 // FIXME: how to correctly handle higher-ranked bounds here?
907 WhereClause::Implemented(tr) => search(
909 .shifted_out_to(&Interner, DebruijnIndex::ONE)
910 .expect("FIXME unexpected higher-ranked trait bound"),
914 if let res @ Some(_) = res {
917 // Handle `Self::Type` referring to own associated type in trait definitions
918 if let GenericDefId::TraitId(trait_id) = param_id.parent {
919 let generics = generics(db.upcast(), trait_id.into());
920 if generics.params.types[param_id.local_id].provenance
921 == TypeParamProvenance::TraitSelf
923 let trait_ref = TyBuilder::trait_ref(db, trait_id)
924 .fill_with_bound_vars(DebruijnIndex::INNERMOST, 0)
926 return search(trait_ref);
935 /// Build the type of all specific fields of a struct or enum variant.
936 pub(crate) fn field_types_query(
937 db: &dyn HirDatabase,
938 variant_id: VariantId,
939 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
940 let var_data = variant_id.variant_data(db.upcast());
941 let (resolver, def): (_, GenericDefId) = match variant_id {
942 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
943 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
944 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
946 let generics = generics(db.upcast(), def);
947 let mut res = ArenaMap::default();
949 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
950 for (field_id, field_data) in var_data.fields().iter() {
951 res.insert(field_id, make_binders(&generics, ctx.lower_ty(&field_data.type_ref)))
956 /// This query exists only to be used when resolving short-hand associated types
959 /// See the analogous query in rustc and its comment:
960 /// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
961 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
962 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
963 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
964 pub(crate) fn generic_predicates_for_param_query(
965 db: &dyn HirDatabase,
966 param_id: TypeParamId,
967 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
968 let resolver = param_id.parent.resolver(db.upcast());
970 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
971 let generics = generics(db.upcast(), param_id.parent);
973 .where_predicates_in_scope()
974 // we have to filter out all other predicates *first*, before attempting to lower them
975 .filter(|pred| match pred {
976 WherePredicate::ForLifetime { target, .. }
977 | WherePredicate::TypeBound { target, .. } => match target {
978 WherePredicateTypeTarget::TypeRef(type_ref) => {
979 ctx.lower_ty_only_param(type_ref) == Some(param_id)
981 WherePredicateTypeTarget::TypeParam(local_id) => *local_id == param_id.local_id,
983 WherePredicate::Lifetime { .. } => false,
985 .flat_map(|pred| ctx.lower_where_predicate(pred, true).map(|p| make_binders(&generics, p)))
989 pub(crate) fn generic_predicates_for_param_recover(
990 _db: &dyn HirDatabase,
992 _param_id: &TypeParamId,
993 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
997 pub(crate) fn trait_environment_query(
998 db: &dyn HirDatabase,
1000 ) -> Arc<TraitEnvironment> {
1001 let resolver = def.resolver(db.upcast());
1002 let ctx = TyLoweringContext::new(db, &resolver)
1003 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
1004 let mut traits_in_scope = Vec::new();
1005 let mut clauses = Vec::new();
1006 for pred in resolver.where_predicates_in_scope() {
1007 for pred in ctx.lower_where_predicate(pred, false) {
1008 if let WhereClause::Implemented(tr) = &pred.skip_binders() {
1010 .push((tr.self_type_parameter(&Interner).clone(), tr.hir_trait_id()));
1012 let program_clause: chalk_ir::ProgramClause<Interner> = pred.clone().cast(&Interner);
1013 clauses.push(program_clause.into_from_env_clause(&Interner));
1017 let container: Option<AssocContainerId> = match def {
1018 // FIXME: is there a function for this?
1019 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
1020 GenericDefId::AdtId(_) => None,
1021 GenericDefId::TraitId(_) => None,
1022 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
1023 GenericDefId::ImplId(_) => None,
1024 GenericDefId::EnumVariantId(_) => None,
1025 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
1027 if let Some(AssocContainerId::TraitId(trait_id)) = container {
1028 // add `Self: Trait<T1, T2, ...>` to the environment in trait
1029 // function default implementations (and speculative code
1030 // inside consts or type aliases)
1031 cov_mark::hit!(trait_self_implements_self);
1032 let substs = TyBuilder::type_params_subst(db, trait_id);
1033 let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs };
1034 let pred = WhereClause::Implemented(trait_ref);
1035 let program_clause: chalk_ir::ProgramClause<Interner> = pred.cast(&Interner);
1036 clauses.push(program_clause.into_from_env_clause(&Interner));
1039 let krate = def.module(db.upcast()).krate();
1041 let env = chalk_ir::Environment::new(&Interner).add_clauses(&Interner, clauses);
1043 Arc::new(TraitEnvironment { krate, traits_from_clauses: traits_in_scope, env })
1046 /// Resolve the where clause(s) of an item with generics.
1047 pub(crate) fn generic_predicates_query(
1048 db: &dyn HirDatabase,
1050 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
1051 let resolver = def.resolver(db.upcast());
1053 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1054 let generics = generics(db.upcast(), def);
1056 .where_predicates_in_scope()
1057 .flat_map(|pred| ctx.lower_where_predicate(pred, false).map(|p| make_binders(&generics, p)))
1061 /// Resolve the default type params from generics
1062 pub(crate) fn generic_defaults_query(
1063 db: &dyn HirDatabase,
1065 ) -> Arc<[Binders<Ty>]> {
1066 let resolver = def.resolver(db.upcast());
1068 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1069 let generic_params = generics(db.upcast(), def);
1071 let defaults = generic_params
1074 .map(|(idx, (_, p))| {
1076 p.default.as_ref().map_or(TyKind::Error.intern(&Interner), |t| ctx.lower_ty(t));
1078 // Each default can only refer to previous parameters.
1079 ty = crate::fold_free_vars(ty, |bound, binders| {
1080 if bound.index >= idx && bound.debruijn == DebruijnIndex::INNERMOST {
1081 // type variable default referring to parameter coming
1082 // after it. This is forbidden (FIXME: report
1084 TyKind::Error.intern(&Interner)
1086 bound.shifted_in_from(binders).to_ty(&Interner)
1090 crate::make_only_type_binders(idx, ty)
1097 pub(crate) fn generic_defaults_recover(
1098 db: &dyn HirDatabase,
1101 ) -> Arc<[Binders<Ty>]> {
1102 let generic_params = generics(db.upcast(), *def);
1104 // we still need one default per parameter
1105 let defaults = generic_params
1109 let ty = TyKind::Error.intern(&Interner);
1111 crate::make_only_type_binders(idx, ty)
1118 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1119 let data = db.function_data(def);
1120 let resolver = def.resolver(db.upcast());
1121 let ctx_params = TyLoweringContext::new(db, &resolver)
1122 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1123 .with_type_param_mode(TypeParamLoweringMode::Variable);
1124 let params = data.params.iter().map(|tr| ctx_params.lower_ty(tr)).collect::<Vec<_>>();
1125 let ctx_ret = TyLoweringContext::new(db, &resolver)
1126 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1127 .with_type_param_mode(TypeParamLoweringMode::Variable);
1128 let ret = ctx_ret.lower_ty(&data.ret_type);
1129 let generics = generics(db.upcast(), def.into());
1130 make_binders(&generics, CallableSig::from_params_and_return(params, ret, data.is_varargs()))
1133 /// Build the declared type of a function. This should not need to look at the
1135 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1136 let generics = generics(db.upcast(), def.into());
1137 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1140 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(&Interner),
1144 /// Build the declared type of a const.
1145 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1146 let data = db.const_data(def);
1147 let generics = generics(db.upcast(), def.into());
1148 let resolver = def.resolver(db.upcast());
1150 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1152 make_binders(&generics, ctx.lower_ty(&data.type_ref))
1155 /// Build the declared type of a static.
1156 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1157 let data = db.static_data(def);
1158 let resolver = def.resolver(db.upcast());
1159 let ctx = TyLoweringContext::new(db, &resolver);
1161 Binders::empty(&Interner, ctx.lower_ty(&data.type_ref))
1164 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1165 let struct_data = db.struct_data(def);
1166 let fields = struct_data.variant_data.fields();
1167 let resolver = def.resolver(db.upcast());
1169 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1170 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1171 let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders();
1172 Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1175 /// Build the type of a tuple struct constructor.
1176 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1177 let struct_data = db.struct_data(def);
1178 if let StructKind::Unit = struct_data.variant_data.kind() {
1179 return type_for_adt(db, def.into());
1181 let generics = generics(db.upcast(), def.into());
1182 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1185 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(&Interner),
1189 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1190 let enum_data = db.enum_data(def.parent);
1191 let var_data = &enum_data.variants[def.local_id];
1192 let fields = var_data.variant_data.fields();
1193 let resolver = def.parent.resolver(db.upcast());
1195 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1196 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1197 let (ret, binders) = type_for_adt(db, def.parent.into()).into_value_and_skipped_binders();
1198 Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1201 /// Build the type of a tuple enum variant constructor.
1202 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1203 let enum_data = db.enum_data(def.parent);
1204 let var_data = &enum_data.variants[def.local_id].variant_data;
1205 if let StructKind::Unit = var_data.kind() {
1206 return type_for_adt(db, def.parent.into());
1208 let generics = generics(db.upcast(), def.parent.into());
1209 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1212 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(&Interner),
1216 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1217 let generics = generics(db.upcast(), adt.into());
1218 let b = TyBuilder::adt(db, adt);
1219 let ty = b.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0).build();
1220 make_binders(&generics, ty)
1223 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1224 let generics = generics(db.upcast(), t.into());
1225 let resolver = t.resolver(db.upcast());
1227 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1228 if db.type_alias_data(t).is_extern {
1229 Binders::empty(&Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(&Interner))
1231 let type_ref = &db.type_alias_data(t).type_ref;
1232 let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error));
1233 make_binders(&generics, inner)
1237 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1238 pub enum CallableDefId {
1239 FunctionId(FunctionId),
1241 EnumVariantId(EnumVariantId),
1243 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1245 impl CallableDefId {
1246 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1247 let db = db.upcast();
1249 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1250 CallableDefId::StructId(s) => s.lookup(db).container,
1251 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1257 impl From<CallableDefId> for GenericDefId {
1258 fn from(def: CallableDefId) -> GenericDefId {
1260 CallableDefId::FunctionId(f) => f.into(),
1261 CallableDefId::StructId(s) => s.into(),
1262 CallableDefId::EnumVariantId(e) => e.into(),
1267 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1269 BuiltinType(BuiltinType),
1271 TypeAliasId(TypeAliasId),
1273 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1275 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1276 pub enum ValueTyDefId {
1277 FunctionId(FunctionId),
1280 EnumVariantId(EnumVariantId),
1284 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1286 /// Build the declared type of an item. This depends on the namespace; e.g. for
1287 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1288 /// the constructor function `(usize) -> Foo` which lives in the values
1290 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1292 TyDefId::BuiltinType(it) => Binders::empty(&Interner, TyBuilder::builtin(it)),
1293 TyDefId::AdtId(it) => type_for_adt(db, it),
1294 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1298 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1299 let generics = match *def {
1300 TyDefId::BuiltinType(_) => {
1301 return Binders::empty(&Interner, TyKind::Error.intern(&Interner))
1303 TyDefId::AdtId(it) => generics(db.upcast(), it.into()),
1304 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()),
1306 make_binders(&generics, TyKind::Error.intern(&Interner))
1309 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1311 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1312 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1313 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1314 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1315 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1316 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1320 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1321 let impl_data = db.impl_data(impl_id);
1322 let resolver = impl_id.resolver(db.upcast());
1323 let generics = generics(db.upcast(), impl_id.into());
1325 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1326 make_binders(&generics, ctx.lower_ty(&impl_data.self_ty))
1329 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1330 let parent_data = db.generic_params(def.parent);
1331 let data = &parent_data.consts[def.local_id];
1332 let resolver = def.parent.resolver(db.upcast());
1333 let ctx = TyLoweringContext::new(db, &resolver);
1335 ctx.lower_ty(&data.ty)
1338 pub(crate) fn impl_self_ty_recover(
1339 db: &dyn HirDatabase,
1343 let generics = generics(db.upcast(), (*impl_id).into());
1344 make_binders(&generics, TyKind::Error.intern(&Interner))
1347 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1348 let impl_data = db.impl_data(impl_id);
1349 let resolver = impl_id.resolver(db.upcast());
1351 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1352 let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders();
1353 let target_trait = impl_data.target_trait.as_ref()?;
1354 Some(Binders::new(binders, ctx.lower_trait_ref(target_trait, Some(self_ty))?))
1357 pub(crate) fn return_type_impl_traits(
1358 db: &dyn HirDatabase,
1359 def: hir_def::FunctionId,
1360 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1361 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1362 let data = db.function_data(def);
1363 let resolver = def.resolver(db.upcast());
1364 let ctx_ret = TyLoweringContext::new(db, &resolver)
1365 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1366 .with_type_param_mode(TypeParamLoweringMode::Variable);
1367 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1368 let generics = generics(db.upcast(), def.into());
1369 let return_type_impl_traits =
1370 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1371 if return_type_impl_traits.impl_traits.is_empty() {
1374 Some(Arc::new(make_binders(&generics, return_type_impl_traits)))
1378 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1380 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1381 hir_def::type_ref::Mutability::Mut => Mutability::Mut,
1385 fn make_binders<T: HasInterner<Interner = Interner>>(generics: &Generics, value: T) -> Binders<T> {
1386 crate::make_only_type_binders(generics.len(), value)