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::generics::TypeOrConstParamData;
14 use hir_def::intern::Interned;
17 body::{Expander, LowerCtx},
18 builtin_type::BuiltinType,
19 generics::{TypeParamProvenance, WherePredicate, WherePredicateTypeTarget},
20 path::{GenericArg, Path, PathSegment, PathSegments},
21 resolver::{HasResolver, Resolver, TypeNs},
22 type_ref::{TraitBoundModifier, TraitRef as HirTraitRef, TypeBound, TypeRef},
23 AdtId, AssocItemId, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId, HasModule,
24 ImplId, ItemContainerId, LocalFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId,
27 use hir_def::{ConstParamId, TypeOrConstParamId};
28 use hir_expand::{name::Name, ExpandResult};
29 use la_arena::ArenaMap;
30 use rustc_hash::FxHashSet;
31 use smallvec::SmallVec;
32 use stdx::{impl_from, never};
33 use syntax::{ast, SmolStr};
35 use crate::all_super_traits;
40 static_lifetime, to_assoc_type_id, to_chalk_trait_id, to_placeholder_idx,
42 all_super_trait_refs, associated_type_by_name_including_super_traits, generics, Generics,
44 AliasEq, AliasTy, Binders, BoundVar, CallableSig, DebruijnIndex, DynTy, FnPointer, FnSig,
45 FnSubst, ImplTraitId, Interner, PolyFnSig, ProjectionTy, QuantifiedWhereClause,
46 QuantifiedWhereClauses, ReturnTypeImplTrait, ReturnTypeImplTraits, Substitution,
47 TraitEnvironment, TraitRef, TraitRefExt, Ty, TyBuilder, TyKind, WhereClause,
51 pub struct TyLoweringContext<'a> {
52 pub db: &'a dyn HirDatabase,
53 pub resolver: &'a Resolver,
54 in_binders: DebruijnIndex,
55 /// Note: Conceptually, it's thinkable that we could be in a location where
56 /// some type params should be represented as placeholders, and others
57 /// should be converted to variables. I think in practice, this isn't
58 /// possible currently, so this should be fine for now.
59 pub type_param_mode: TypeParamLoweringMode,
60 pub impl_trait_mode: ImplTraitLoweringMode,
61 impl_trait_counter: Cell<u16>,
62 /// When turning `impl Trait` into opaque types, we have to collect the
63 /// bounds at the same time to get the IDs correct (without becoming too
64 /// complicated). I don't like using interior mutability (as for the
65 /// counter), but I've tried and failed to make the lifetimes work for
66 /// passing around a `&mut TyLoweringContext`. The core problem is that
67 /// we're grouping the mutable data (the counter and this field) together
68 /// with the immutable context (the references to the DB and resolver).
69 /// Splitting this up would be a possible fix.
70 opaque_type_data: RefCell<Vec<ReturnTypeImplTrait>>,
71 expander: RefCell<Option<Expander>>,
72 /// Tracks types with explicit `?Sized` bounds.
73 pub(crate) unsized_types: RefCell<FxHashSet<Ty>>,
76 impl<'a> TyLoweringContext<'a> {
77 pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
78 let impl_trait_counter = Cell::new(0);
79 let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
80 let type_param_mode = TypeParamLoweringMode::Placeholder;
81 let in_binders = DebruijnIndex::INNERMOST;
82 let opaque_type_data = RefCell::new(Vec::new());
91 expander: RefCell::new(None),
92 unsized_types: RefCell::default(),
96 pub fn with_debruijn<T>(
98 debruijn: DebruijnIndex,
99 f: impl FnOnce(&TyLoweringContext) -> T,
101 let opaque_ty_data_vec = self.opaque_type_data.take();
102 let expander = self.expander.take();
103 let unsized_types = self.unsized_types.take();
105 in_binders: debruijn,
106 impl_trait_counter: Cell::new(self.impl_trait_counter.get()),
107 opaque_type_data: RefCell::new(opaque_ty_data_vec),
108 expander: RefCell::new(expander),
109 unsized_types: RefCell::new(unsized_types),
112 let result = f(&new_ctx);
113 self.impl_trait_counter.set(new_ctx.impl_trait_counter.get());
114 self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner());
115 self.expander.replace(new_ctx.expander.into_inner());
116 self.unsized_types.replace(new_ctx.unsized_types.into_inner());
120 pub fn with_shifted_in<T>(
122 debruijn: DebruijnIndex,
123 f: impl FnOnce(&TyLoweringContext) -> T,
125 self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
128 pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
129 Self { impl_trait_mode, ..self }
132 pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
133 Self { type_param_mode, ..self }
137 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
138 pub enum ImplTraitLoweringMode {
139 /// `impl Trait` gets lowered into an opaque type that doesn't unify with
140 /// anything except itself. This is used in places where values flow 'out',
141 /// i.e. for arguments of the function we're currently checking, and return
142 /// types of functions we're calling.
144 /// `impl Trait` gets lowered into a type variable. Used for argument
145 /// position impl Trait when inside the respective function, since it allows
146 /// us to support that without Chalk.
148 /// `impl Trait` gets lowered into a variable that can unify with some
149 /// type. This is used in places where values flow 'in', i.e. for arguments
150 /// of functions we're calling, and the return type of the function we're
151 /// currently checking.
153 /// `impl Trait` is disallowed and will be an error.
157 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
158 pub enum TypeParamLoweringMode {
163 impl<'a> TyLoweringContext<'a> {
164 pub fn lower_ty(&self, type_ref: &TypeRef) -> Ty {
165 self.lower_ty_ext(type_ref).0
168 pub fn lower_ty_ext(&self, type_ref: &TypeRef) -> (Ty, Option<TypeNs>) {
170 let ty = match type_ref {
171 TypeRef::Never => TyKind::Never.intern(Interner),
172 TypeRef::Tuple(inner) => {
173 let inner_tys = inner.iter().map(|tr| self.lower_ty(tr));
174 TyKind::Tuple(inner_tys.len(), Substitution::from_iter(Interner, inner_tys))
177 TypeRef::Path(path) => {
178 let (ty, res_) = self.lower_path(path);
182 TypeRef::RawPtr(inner, mutability) => {
183 let inner_ty = self.lower_ty(inner);
184 TyKind::Raw(lower_to_chalk_mutability(*mutability), inner_ty).intern(Interner)
186 TypeRef::Array(inner, len) => {
187 let inner_ty = self.lower_ty(inner);
189 let const_len = consteval::usize_const(len.as_usize());
191 TyKind::Array(inner_ty, const_len).intern(Interner)
193 TypeRef::Slice(inner) => {
194 let inner_ty = self.lower_ty(inner);
195 TyKind::Slice(inner_ty).intern(Interner)
197 TypeRef::Reference(inner, _, mutability) => {
198 let inner_ty = self.lower_ty(inner);
199 let lifetime = static_lifetime();
200 TyKind::Ref(lower_to_chalk_mutability(*mutability), lifetime, inner_ty)
203 TypeRef::Placeholder => TyKind::Error.intern(Interner),
204 TypeRef::Fn(params, is_varargs) => {
205 let substs = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
206 Substitution::from_iter(Interner, params.iter().map(|(_, tr)| ctx.lower_ty(tr)))
208 TyKind::Function(FnPointer {
209 num_binders: 0, // FIXME lower `for<'a> fn()` correctly
210 sig: FnSig { abi: (), safety: Safety::Safe, variadic: *is_varargs },
211 substitution: FnSubst(substs),
215 TypeRef::DynTrait(bounds) => {
217 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(Interner);
218 let bounds = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
219 QuantifiedWhereClauses::from_iter(
221 bounds.iter().flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false)),
224 let bounds = crate::make_only_type_binders(1, bounds);
225 TyKind::Dyn(DynTy { bounds, lifetime: static_lifetime() }).intern(Interner)
227 TypeRef::ImplTrait(bounds) => {
228 match self.impl_trait_mode {
229 ImplTraitLoweringMode::Opaque => {
230 let idx = self.impl_trait_counter.get();
231 self.impl_trait_counter.set(idx + 1);
232 let func = match self.resolver.generic_def() {
233 Some(GenericDefId::FunctionId(f)) => f,
234 _ => panic!("opaque impl trait lowering in non-function"),
237 assert!(idx as usize == self.opaque_type_data.borrow().len());
238 // this dance is to make sure the data is in the right
239 // place even if we encounter more opaque types while
240 // lowering the bounds
241 self.opaque_type_data.borrow_mut().push(ReturnTypeImplTrait {
242 bounds: crate::make_only_type_binders(1, Vec::new()),
244 // We don't want to lower the bounds inside the binders
245 // we're currently in, because they don't end up inside
246 // those binders. E.g. when we have `impl Trait<impl
247 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
248 // to the self parameter from `impl Trait`, and the
249 // bounds aren't actually stored nested within each
250 // other, but separately. So if the `T` refers to a type
251 // parameter of the outer function, it's just one binder
252 // away instead of two.
253 let actual_opaque_type_data = self
254 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
255 ctx.lower_impl_trait(bounds, func)
257 self.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
259 let impl_trait_id = ImplTraitId::ReturnTypeImplTrait(func, idx);
260 let opaque_ty_id = self.db.intern_impl_trait_id(impl_trait_id).into();
261 let generics = generics(self.db.upcast(), func.into());
262 let parameters = generics.bound_vars_subst(self.in_binders);
263 TyKind::OpaqueType(opaque_ty_id, parameters).intern(Interner)
265 ImplTraitLoweringMode::Param => {
266 let idx = self.impl_trait_counter.get();
267 // FIXME we're probably doing something wrong here
268 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
269 if let Some(def) = self.resolver.generic_def() {
270 let generics = generics(self.db.upcast(), def);
273 .filter(|(_, data)| {
274 data.provenance == TypeParamProvenance::ArgumentImplTrait
277 .map_or(TyKind::Error, |(id, _)| {
278 TyKind::Placeholder(to_placeholder_idx(self.db, id))
280 param.intern(Interner)
282 TyKind::Error.intern(Interner)
285 ImplTraitLoweringMode::Variable => {
286 let idx = self.impl_trait_counter.get();
287 // FIXME we're probably doing something wrong here
288 self.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
295 ) = if let Some(def) = self.resolver.generic_def() {
296 let generics = generics(self.db.upcast(), def);
297 generics.provenance_split()
301 TyKind::BoundVar(BoundVar::new(
303 idx as usize + parent_params + self_params + list_params + const_params,
307 ImplTraitLoweringMode::Disallowed => {
308 // FIXME: report error
309 TyKind::Error.intern(Interner)
313 TypeRef::Macro(macro_call) => {
314 let (expander, recursion_start) = {
315 let mut expander = self.expander.borrow_mut();
316 if expander.is_some() {
317 (Some(expander), false)
318 } else if let Some(module_id) = self.resolver.module() {
320 Some(Expander::new(self.db.upcast(), macro_call.file_id, module_id));
321 (Some(expander), true)
326 let ty = if let Some(mut expander) = expander {
327 let expander_mut = expander.as_mut().unwrap();
328 let macro_call = macro_call.to_node(self.db.upcast());
329 match expander_mut.enter_expand::<ast::Type>(self.db.upcast(), macro_call) {
330 Ok(ExpandResult { value: Some((mark, expanded)), .. }) => {
332 LowerCtx::new(self.db.upcast(), expander_mut.current_file_id());
333 let type_ref = TypeRef::from_ast(&ctx, expanded);
336 let ty = self.lower_ty(&type_ref);
342 .exit(self.db.upcast(), mark);
351 *self.expander.borrow_mut() = None;
353 ty.unwrap_or_else(|| TyKind::Error.intern(Interner))
355 TypeRef::Error => TyKind::Error.intern(Interner),
360 /// This is only for `generic_predicates_for_param`, where we can't just
361 /// lower the self types of the predicates since that could lead to cycles.
362 /// So we just check here if the `type_ref` resolves to a generic param, and which.
363 fn lower_ty_only_param(&self, type_ref: &TypeRef) -> Option<TypeOrConstParamId> {
364 let path = match type_ref {
365 TypeRef::Path(path) => path,
368 if path.type_anchor().is_some() {
371 if path.segments().len() > 1 {
375 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
376 Some((it, None)) => it,
380 TypeNs::GenericParam(param_id) => Some(param_id.into()),
385 pub(crate) fn lower_ty_relative_path(
388 // We need the original resolution to lower `Self::AssocTy` correctly
390 remaining_segments: PathSegments<'_>,
391 ) -> (Ty, Option<TypeNs>) {
392 match remaining_segments.len() {
395 // resolve unselected assoc types
396 let segment = remaining_segments.first().unwrap();
397 (self.select_associated_type(res, segment), None)
400 // FIXME report error (ambiguous associated type)
401 (TyKind::Error.intern(Interner), None)
406 pub(crate) fn lower_partly_resolved_path(
409 resolved_segment: PathSegment<'_>,
410 remaining_segments: PathSegments<'_>,
412 ) -> (Ty, Option<TypeNs>) {
413 let ty = match resolution {
414 TypeNs::TraitId(trait_) => {
415 let ty = match remaining_segments.len() {
418 self.lower_trait_ref_from_resolved_path(trait_, resolved_segment, None);
419 let segment = remaining_segments.first().unwrap();
422 .trait_data(trait_ref.hir_trait_id())
423 .associated_type_by_name(segment.name);
425 Some(associated_ty) => {
426 // FIXME handle type parameters on the segment
427 TyKind::Alias(AliasTy::Projection(ProjectionTy {
428 associated_ty_id: to_assoc_type_id(associated_ty),
429 substitution: trait_ref.substitution,
434 // FIXME: report error (associated type not found)
435 TyKind::Error.intern(Interner)
441 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0))
444 let trait_ref = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
445 ctx.lower_trait_ref_from_resolved_path(
452 bounds: crate::make_only_type_binders(
454 QuantifiedWhereClauses::from_iter(
456 Some(crate::wrap_empty_binders(WhereClause::Implemented(
461 lifetime: static_lifetime(),
463 TyKind::Dyn(dyn_ty).intern(Interner)
466 // FIXME report error (ambiguous associated type)
467 TyKind::Error.intern(Interner)
472 TypeNs::GenericParam(param_id) => {
473 let generics = generics(
475 self.resolver.generic_def().expect("generics in scope"),
477 match self.type_param_mode {
478 TypeParamLoweringMode::Placeholder => {
479 TyKind::Placeholder(to_placeholder_idx(self.db, param_id.into()))
481 TypeParamLoweringMode::Variable => {
482 let idx = generics.param_idx(param_id.into()).expect("matching generics");
483 TyKind::BoundVar(BoundVar::new(self.in_binders, idx))
488 TypeNs::SelfType(impl_id) => {
489 let generics = generics(self.db.upcast(), impl_id.into());
490 let substs = match self.type_param_mode {
491 TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
492 TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
494 self.db.impl_self_ty(impl_id).substitute(Interner, &substs)
496 TypeNs::AdtSelfType(adt) => {
497 let generics = generics(self.db.upcast(), adt.into());
498 let substs = match self.type_param_mode {
499 TypeParamLoweringMode::Placeholder => generics.type_params_subst(self.db),
500 TypeParamLoweringMode::Variable => generics.bound_vars_subst(self.in_binders),
502 self.db.ty(adt.into()).substitute(Interner, &substs)
505 TypeNs::AdtId(it) => self.lower_path_inner(resolved_segment, it.into(), infer_args),
506 TypeNs::BuiltinType(it) => {
507 self.lower_path_inner(resolved_segment, it.into(), infer_args)
509 TypeNs::TypeAliasId(it) => {
510 self.lower_path_inner(resolved_segment, it.into(), infer_args)
512 // FIXME: report error
513 TypeNs::EnumVariantId(_) => return (TyKind::Error.intern(Interner), None),
515 self.lower_ty_relative_path(ty, Some(resolution), remaining_segments)
518 pub(crate) fn lower_path(&self, path: &Path) -> (Ty, Option<TypeNs>) {
519 // Resolve the path (in type namespace)
520 if let Some(type_ref) = path.type_anchor() {
521 let (ty, res) = self.lower_ty_ext(type_ref);
522 return self.lower_ty_relative_path(ty, res, path.segments());
524 let (resolution, remaining_index) =
525 match self.resolver.resolve_path_in_type_ns(self.db.upcast(), path.mod_path()) {
527 None => return (TyKind::Error.intern(Interner), None),
529 let (resolved_segment, remaining_segments) = match remaining_index {
531 path.segments().last().expect("resolved path has at least one element"),
534 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
536 self.lower_partly_resolved_path(resolution, resolved_segment, remaining_segments, false)
539 fn select_associated_type(&self, res: Option<TypeNs>, segment: PathSegment<'_>) -> Ty {
540 let (def, res) = match (self.resolver.generic_def(), res) {
541 (Some(def), Some(res)) => (def, res),
542 _ => return TyKind::Error.intern(Interner),
544 let ty = named_associated_type_shorthand_candidates(
548 Some(segment.name.clone()),
549 move |name, t, associated_ty| {
550 if name == segment.name {
551 let substs = match self.type_param_mode {
552 TypeParamLoweringMode::Placeholder => {
553 // if we're lowering to placeholders, we have to put
555 let generics = generics(
559 .expect("there should be generics if there's a generic param"),
561 let s = generics.type_params_subst(self.db);
562 s.apply(t.substitution.clone(), Interner)
564 TypeParamLoweringMode::Variable => t.substitution.clone(),
566 // We need to shift in the bound vars, since
567 // associated_type_shorthand_candidates does not do that
568 let substs = substs.shifted_in_from(Interner, self.in_binders);
569 // FIXME handle type parameters on the segment
571 TyKind::Alias(AliasTy::Projection(ProjectionTy {
572 associated_ty_id: to_assoc_type_id(associated_ty),
573 substitution: substs,
583 ty.unwrap_or_else(|| TyKind::Error.intern(Interner))
588 segment: PathSegment<'_>,
592 let generic_def = match typeable {
593 TyDefId::BuiltinType(_) => None,
594 TyDefId::AdtId(it) => Some(it.into()),
595 TyDefId::TypeAliasId(it) => Some(it.into()),
597 let substs = self.substs_from_path_segment(segment, generic_def, infer_args, None);
598 self.db.ty(typeable).substitute(Interner, &substs)
601 /// Collect generic arguments from a path into a `Substs`. See also
602 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
603 pub(super) fn substs_from_path(
606 // Note that we don't call `db.value_type(resolved)` here,
607 // `ValueTyDefId` is just a convenient way to pass generics and
608 // special-case enum variants
609 resolved: ValueTyDefId,
612 let last = path.segments().last().expect("path should have at least one segment");
613 let (segment, generic_def) = match resolved {
614 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
615 ValueTyDefId::StructId(it) => (last, Some(it.into())),
616 ValueTyDefId::UnionId(it) => (last, Some(it.into())),
617 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
618 ValueTyDefId::StaticId(_) => (last, None),
619 ValueTyDefId::EnumVariantId(var) => {
620 // the generic args for an enum variant may be either specified
621 // on the segment referring to the enum, or on the segment
622 // referring to the variant. So `Option::<T>::None` and
623 // `Option::None::<T>` are both allowed (though the former is
624 // preferred). See also `def_ids_for_path_segments` in rustc.
625 let len = path.segments().len();
626 let penultimate = len.checked_sub(2).and_then(|idx| path.segments().get(idx));
627 let segment = match penultimate {
628 Some(segment) if segment.args_and_bindings.is_some() => segment,
631 (segment, Some(var.parent.into()))
634 self.substs_from_path_segment(segment, generic_def, infer_args, None)
637 fn substs_from_path_segment(
639 segment: PathSegment<'_>,
640 def_generic: Option<GenericDefId>,
642 explicit_self_ty: Option<Ty>,
644 let mut substs = Vec::new();
645 let def_generics = def_generic.map(|def| generics(self.db.upcast(), def));
647 let (parent_params, self_params, type_params, const_params, impl_trait_params) =
648 def_generics.map_or((0, 0, 0, 0, 0), |g| g.provenance_split());
650 parent_params + self_params + type_params + const_params + impl_trait_params;
652 substs.extend(iter::repeat(TyKind::Error.intern(Interner)).take(parent_params));
654 let fill_self_params = || {
658 .chain(iter::repeat(TyKind::Error.intern(Interner)))
662 let mut had_explicit_type_args = false;
664 if let Some(generic_args) = &segment.args_and_bindings {
665 if !generic_args.has_self_type {
669 if generic_args.has_self_type { self_params + type_params } else { type_params };
670 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
671 // if args are provided, it should be all of them, but we can't rely on that
672 for arg in generic_args
675 .filter(|arg| matches!(arg, GenericArg::Type(_)))
680 GenericArg::Type(type_ref) => {
681 had_explicit_type_args = true;
682 let ty = self.lower_ty(type_ref);
685 GenericArg::Lifetime(_) => {}
692 // handle defaults. In expression or pattern path segments without
693 // explicitly specified type arguments, missing type arguments are inferred
694 // (i.e. defaults aren't used).
695 if !infer_args || had_explicit_type_args {
696 if let Some(def_generic) = def_generic {
697 let defaults = self.db.generic_defaults(def_generic);
698 assert_eq!(total_len, defaults.len());
700 for default_ty in defaults.iter().skip(substs.len()) {
701 // each default can depend on the previous parameters
702 let substs_so_far = Substitution::from_iter(Interner, substs.clone());
703 substs.push(default_ty.clone().substitute(Interner, &substs_so_far));
708 // add placeholders for args that were not provided
709 // FIXME: emit diagnostics in contexts where this is not allowed
710 for _ in substs.len()..total_len {
711 substs.push(TyKind::Error.intern(Interner));
713 assert_eq!(substs.len(), total_len);
715 Substitution::from_iter(Interner, substs)
718 fn lower_trait_ref_from_path(
721 explicit_self_ty: Option<Ty>,
722 ) -> Option<TraitRef> {
724 match self.resolver.resolve_path_in_type_ns_fully(self.db.upcast(), path.mod_path())? {
725 TypeNs::TraitId(tr) => tr,
728 let segment = path.segments().last().expect("path should have at least one segment");
729 Some(self.lower_trait_ref_from_resolved_path(resolved, segment, explicit_self_ty))
732 pub(crate) fn lower_trait_ref_from_resolved_path(
735 segment: PathSegment<'_>,
736 explicit_self_ty: Option<Ty>,
738 let substs = self.trait_ref_substs_from_path(segment, resolved, explicit_self_ty);
739 TraitRef { trait_id: to_chalk_trait_id(resolved), substitution: substs }
744 trait_ref: &HirTraitRef,
745 explicit_self_ty: Option<Ty>,
746 ) -> Option<TraitRef> {
747 self.lower_trait_ref_from_path(&trait_ref.path, explicit_self_ty)
750 fn trait_ref_substs_from_path(
752 segment: PathSegment<'_>,
754 explicit_self_ty: Option<Ty>,
756 self.substs_from_path_segment(segment, Some(resolved.into()), false, explicit_self_ty)
759 pub(crate) fn lower_where_predicate(
761 where_predicate: &'a WherePredicate,
762 ignore_bindings: bool,
763 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
764 match where_predicate {
765 WherePredicate::ForLifetime { target, bound, .. }
766 | WherePredicate::TypeBound { target, bound } => {
767 let self_ty = match target {
768 WherePredicateTypeTarget::TypeRef(type_ref) => self.lower_ty(type_ref),
769 WherePredicateTypeTarget::TypeOrConstParam(param_id) => {
770 let generic_def = self.resolver.generic_def().expect("generics in scope");
771 let generics = generics(self.db.upcast(), generic_def);
772 let param_id = hir_def::TypeOrConstParamId {
776 let placeholder = to_placeholder_idx(self.db, param_id);
777 match self.type_param_mode {
778 TypeParamLoweringMode::Placeholder => TyKind::Placeholder(placeholder),
779 TypeParamLoweringMode::Variable => {
780 let idx = generics.param_idx(param_id).expect("matching generics");
781 TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, idx))
787 self.lower_type_bound(bound, self_ty, ignore_bindings)
791 WherePredicate::Lifetime { .. } => vec![].into_iter(),
795 pub(crate) fn lower_type_bound(
797 bound: &'a TypeBound,
799 ignore_bindings: bool,
800 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
801 let mut bindings = None;
802 let trait_ref = match bound {
803 TypeBound::Path(path, TraitBoundModifier::None) => {
804 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
805 bindings.clone().map(WhereClause::Implemented).map(crate::wrap_empty_binders)
807 TypeBound::Path(path, TraitBoundModifier::Maybe) => {
808 let sized_trait = self
811 .and_then(|krate| self.db.lang_item(krate, SmolStr::new_inline("sized")))
812 .and_then(|lang_item| lang_item.as_trait());
813 // Don't lower associated type bindings as the only possible relaxed trait bound
814 // `?Sized` has no of them.
815 // If we got another trait here ignore the bound completely.
817 .lower_trait_ref_from_path(path, Some(self_ty.clone()))
818 .map(|trait_ref| trait_ref.hir_trait_id());
819 if trait_id == sized_trait {
820 self.unsized_types.borrow_mut().insert(self_ty);
824 TypeBound::ForLifetime(_, path) => {
825 // FIXME Don't silently drop the hrtb lifetimes here
826 bindings = self.lower_trait_ref_from_path(path, Some(self_ty));
827 bindings.clone().map(WhereClause::Implemented).map(crate::wrap_empty_binders)
829 TypeBound::Lifetime(_) => None,
830 TypeBound::Error => None,
832 trait_ref.into_iter().chain(
835 .filter(move |_| !ignore_bindings)
836 .flat_map(move |tr| self.assoc_type_bindings_from_type_bound(bound, tr)),
840 fn assoc_type_bindings_from_type_bound(
842 bound: &'a TypeBound,
844 ) -> impl Iterator<Item = QuantifiedWhereClause> + 'a {
845 let last_segment = match bound {
846 TypeBound::Path(path, TraitBoundModifier::None) | TypeBound::ForLifetime(_, path) => {
847 path.segments().last()
849 TypeBound::Path(_, TraitBoundModifier::Maybe)
851 | TypeBound::Lifetime(_) => None,
855 .filter_map(|segment| segment.args_and_bindings)
856 .flat_map(|args_and_bindings| &args_and_bindings.bindings)
857 .flat_map(move |binding| {
858 let found = associated_type_by_name_including_super_traits(
863 let (super_trait_ref, associated_ty) = match found {
864 None => return SmallVec::new(),
867 let projection_ty = ProjectionTy {
868 associated_ty_id: to_assoc_type_id(associated_ty),
869 substitution: super_trait_ref.substitution,
871 let mut preds: SmallVec<[_; 1]> = SmallVec::with_capacity(
872 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
874 if let Some(type_ref) = &binding.type_ref {
875 let ty = self.lower_ty(type_ref);
877 AliasEq { alias: AliasTy::Projection(projection_ty.clone()), ty };
878 preds.push(crate::wrap_empty_binders(WhereClause::AliasEq(alias_eq)));
880 for bound in &binding.bounds {
881 preds.extend(self.lower_type_bound(
883 TyKind::Alias(AliasTy::Projection(projection_ty.clone())).intern(Interner),
893 bounds: &[Interned<TypeBound>],
895 ) -> ReturnTypeImplTrait {
896 cov_mark::hit!(lower_rpit);
897 let self_ty = TyKind::BoundVar(BoundVar::new(DebruijnIndex::INNERMOST, 0)).intern(Interner);
898 let predicates = self.with_shifted_in(DebruijnIndex::ONE, |ctx| {
899 let mut predicates: Vec<_> = bounds
901 .flat_map(|b| ctx.lower_type_bound(b, self_ty.clone(), false))
904 if !ctx.unsized_types.borrow().contains(&self_ty) {
905 let krate = func.lookup(ctx.db.upcast()).module(ctx.db.upcast()).krate();
906 let sized_trait = ctx
908 .lang_item(krate, SmolStr::new_inline("sized"))
909 .and_then(|lang_item| lang_item.as_trait().map(to_chalk_trait_id));
910 let sized_clause = sized_trait.map(|trait_id| {
911 let clause = WhereClause::Implemented(TraitRef {
913 substitution: Substitution::from1(Interner, self_ty.clone()),
915 crate::wrap_empty_binders(clause)
917 predicates.extend(sized_clause.into_iter());
918 predicates.shrink_to_fit();
923 ReturnTypeImplTrait { bounds: crate::make_only_type_binders(1, predicates) }
927 fn count_impl_traits(type_ref: &TypeRef) -> usize {
929 type_ref.walk(&mut |type_ref| {
930 if matches!(type_ref, TypeRef::ImplTrait(_)) {
937 /// Build the signature of a callable item (function, struct or enum variant).
938 pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
940 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
941 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
942 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
946 pub fn associated_type_shorthand_candidates<R>(
947 db: &dyn HirDatabase,
950 cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
952 named_associated_type_shorthand_candidates(db, def, res, None, cb)
955 fn named_associated_type_shorthand_candidates<R>(
956 db: &dyn HirDatabase,
957 // If the type parameter is defined in an impl and we're in a method, there
958 // might be additional where clauses to consider
961 assoc_name: Option<Name>,
962 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
964 let mut search = |t| {
965 for t in all_super_trait_refs(db, t) {
966 let data = db.trait_data(t.hir_trait_id());
968 for (name, assoc_id) in &data.items {
969 if let AssocItemId::TypeAliasId(alias) = assoc_id {
970 if let Some(result) = cb(name, &t, *alias) {
980 TypeNs::SelfType(impl_id) => search(
981 // we're _in_ the impl -- the binders get added back later. Correct,
982 // but it would be nice to make this more explicit
983 db.impl_trait(impl_id)?.into_value_and_skipped_binders().0,
985 TypeNs::GenericParam(param_id) => {
986 let predicates = db.generic_predicates_for_param(def, param_id.into(), assoc_name);
987 let res = predicates.iter().find_map(|pred| match pred.skip_binders().skip_binders() {
988 // FIXME: how to correctly handle higher-ranked bounds here?
989 WhereClause::Implemented(tr) => search(
991 .shifted_out_to(Interner, DebruijnIndex::ONE)
992 .expect("FIXME unexpected higher-ranked trait bound"),
996 if let res @ Some(_) = res {
999 // Handle `Self::Type` referring to own associated type in trait definitions
1000 if let GenericDefId::TraitId(trait_id) = param_id.parent() {
1001 let generics = generics(db.upcast(), trait_id.into());
1002 if generics.params.tocs[param_id.local_id()].is_trait_self() {
1003 let trait_ref = TyBuilder::trait_ref(db, trait_id)
1004 .fill_with_bound_vars(DebruijnIndex::INNERMOST, 0)
1006 return search(trait_ref);
1015 /// Build the type of all specific fields of a struct or enum variant.
1016 pub(crate) fn field_types_query(
1017 db: &dyn HirDatabase,
1018 variant_id: VariantId,
1019 ) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
1020 let var_data = variant_id.variant_data(db.upcast());
1021 let (resolver, def): (_, GenericDefId) = match variant_id {
1022 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
1023 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
1024 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
1026 let generics = generics(db.upcast(), def);
1027 let mut res = ArenaMap::default();
1029 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1030 for (field_id, field_data) in var_data.fields().iter() {
1031 res.insert(field_id, make_binders(&generics, ctx.lower_ty(&field_data.type_ref)))
1036 /// This query exists only to be used when resolving short-hand associated types
1039 /// See the analogous query in rustc and its comment:
1040 /// <https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46>
1041 /// This is a query mostly to handle cycles somewhat gracefully; e.g. the
1042 /// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
1043 /// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
1044 pub(crate) fn generic_predicates_for_param_query(
1045 db: &dyn HirDatabase,
1047 param_id: TypeOrConstParamId,
1048 assoc_name: Option<Name>,
1049 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
1050 let resolver = def.resolver(db.upcast());
1052 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1053 let generics = generics(db.upcast(), def);
1054 let mut predicates: Vec<_> = resolver
1055 .where_predicates_in_scope()
1056 // we have to filter out all other predicates *first*, before attempting to lower them
1057 .filter(|pred| match pred {
1058 WherePredicate::ForLifetime { target, bound, .. }
1059 | WherePredicate::TypeBound { target, bound, .. } => {
1061 WherePredicateTypeTarget::TypeRef(type_ref) => {
1062 if ctx.lower_ty_only_param(type_ref) != Some(param_id.into()) {
1066 WherePredicateTypeTarget::TypeOrConstParam(local_id) => {
1067 if *local_id != param_id.local_id {
1074 TypeBound::ForLifetime(_, path) | TypeBound::Path(path, _) => {
1075 // Only lower the bound if the trait could possibly define the associated
1076 // type we're looking for.
1078 let assoc_name = match &assoc_name {
1080 None => return true,
1082 let tr = match resolver
1083 .resolve_path_in_type_ns_fully(db.upcast(), path.mod_path())
1085 Some(TypeNs::TraitId(tr)) => tr,
1089 all_super_traits(db.upcast(), tr).iter().any(|tr| {
1090 db.trait_data(*tr).items.iter().any(|(name, item)| {
1091 matches!(item, AssocItemId::TypeAliasId(_)) && name == assoc_name
1095 TypeBound::Lifetime(_) | TypeBound::Error => false,
1098 WherePredicate::Lifetime { .. } => false,
1100 .flat_map(|pred| ctx.lower_where_predicate(pred, true).map(|p| make_binders(&generics, p)))
1103 let subst = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1104 let explicitly_unsized_tys = ctx.unsized_types.into_inner();
1105 let implicitly_sized_predicates =
1106 implicitly_sized_clauses(db, param_id.parent, &explicitly_unsized_tys, &subst, &resolver)
1107 .map(|p| make_binders(&generics, crate::wrap_empty_binders(p)));
1108 predicates.extend(implicitly_sized_predicates);
1112 pub(crate) fn generic_predicates_for_param_recover(
1113 _db: &dyn HirDatabase,
1115 _def: &GenericDefId,
1116 _param_id: &TypeOrConstParamId,
1117 _assoc_name: &Option<Name>,
1118 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
1122 pub(crate) fn trait_environment_query(
1123 db: &dyn HirDatabase,
1125 ) -> Arc<TraitEnvironment> {
1126 let resolver = def.resolver(db.upcast());
1127 let ctx = TyLoweringContext::new(db, &resolver)
1128 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
1129 let mut traits_in_scope = Vec::new();
1130 let mut clauses = Vec::new();
1131 for pred in resolver.where_predicates_in_scope() {
1132 for pred in ctx.lower_where_predicate(pred, false) {
1133 if let WhereClause::Implemented(tr) = &pred.skip_binders() {
1134 traits_in_scope.push((tr.self_type_parameter(Interner).clone(), tr.hir_trait_id()));
1136 let program_clause: chalk_ir::ProgramClause<Interner> = pred.cast(Interner);
1137 clauses.push(program_clause.into_from_env_clause(Interner));
1141 let container: Option<ItemContainerId> = match def {
1142 // FIXME: is there a function for this?
1143 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
1144 GenericDefId::AdtId(_) => None,
1145 GenericDefId::TraitId(_) => None,
1146 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
1147 GenericDefId::ImplId(_) => None,
1148 GenericDefId::EnumVariantId(_) => None,
1149 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
1151 if let Some(ItemContainerId::TraitId(trait_id)) = container {
1152 // add `Self: Trait<T1, T2, ...>` to the environment in trait
1153 // function default implementations (and speculative code
1154 // inside consts or type aliases)
1155 cov_mark::hit!(trait_self_implements_self);
1156 let substs = TyBuilder::type_params_subst(db, trait_id);
1157 let trait_ref = TraitRef { trait_id: to_chalk_trait_id(trait_id), substitution: substs };
1158 let pred = WhereClause::Implemented(trait_ref);
1159 let program_clause: chalk_ir::ProgramClause<Interner> = pred.cast(Interner);
1160 clauses.push(program_clause.into_from_env_clause(Interner));
1163 let subst = generics(db.upcast(), def).type_params_subst(db);
1164 let explicitly_unsized_tys = ctx.unsized_types.into_inner();
1165 let implicitly_sized_clauses =
1166 implicitly_sized_clauses(db, def, &explicitly_unsized_tys, &subst, &resolver).map(|pred| {
1167 let program_clause: chalk_ir::ProgramClause<Interner> = pred.cast(Interner);
1168 program_clause.into_from_env_clause(Interner)
1170 clauses.extend(implicitly_sized_clauses);
1172 let krate = def.module(db.upcast()).krate();
1174 let env = chalk_ir::Environment::new(Interner).add_clauses(Interner, clauses);
1176 Arc::new(TraitEnvironment { krate, traits_from_clauses: traits_in_scope, env })
1179 /// Resolve the where clause(s) of an item with generics.
1180 pub(crate) fn generic_predicates_query(
1181 db: &dyn HirDatabase,
1183 ) -> Arc<[Binders<QuantifiedWhereClause>]> {
1184 let resolver = def.resolver(db.upcast());
1186 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1187 let generics = generics(db.upcast(), def);
1189 let mut predicates = resolver
1190 .where_predicates_in_scope()
1191 .flat_map(|pred| ctx.lower_where_predicate(pred, false).map(|p| make_binders(&generics, p)))
1192 .collect::<Vec<_>>();
1194 let subst = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1195 let explicitly_unsized_tys = ctx.unsized_types.into_inner();
1196 let implicitly_sized_predicates =
1197 implicitly_sized_clauses(db, def, &explicitly_unsized_tys, &subst, &resolver)
1198 .map(|p| make_binders(&generics, crate::wrap_empty_binders(p)));
1199 predicates.extend(implicitly_sized_predicates);
1203 /// Generate implicit `: Sized` predicates for all generics that has no `?Sized` bound.
1204 /// Exception is Self of a trait def.
1205 fn implicitly_sized_clauses<'a>(
1206 db: &dyn HirDatabase,
1208 explicitly_unsized_tys: &'a FxHashSet<Ty>,
1209 substitution: &'a Substitution,
1210 resolver: &Resolver,
1211 ) -> impl Iterator<Item = WhereClause> + 'a {
1212 let is_trait_def = matches!(def, GenericDefId::TraitId(..));
1213 let generic_args = &substitution.as_slice(Interner)[is_trait_def as usize..];
1214 let sized_trait = resolver
1216 .and_then(|krate| db.lang_item(krate, SmolStr::new_inline("sized")))
1217 .and_then(|lang_item| lang_item.as_trait().map(to_chalk_trait_id));
1219 sized_trait.into_iter().flat_map(move |sized_trait| {
1220 let implicitly_sized_tys = generic_args
1222 .filter_map(|generic_arg| generic_arg.ty(Interner))
1223 .filter(move |&self_ty| !explicitly_unsized_tys.contains(self_ty));
1224 implicitly_sized_tys.map(move |self_ty| {
1225 WhereClause::Implemented(TraitRef {
1226 trait_id: sized_trait,
1227 substitution: Substitution::from1(Interner, self_ty.clone()),
1233 /// Resolve the default type params from generics
1234 pub(crate) fn generic_defaults_query(
1235 db: &dyn HirDatabase,
1237 ) -> Arc<[Binders<Ty>]> {
1238 let resolver = def.resolver(db.upcast());
1240 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1241 let generic_params = generics(db.upcast(), def);
1243 let defaults = generic_params
1246 .map(|(idx, (_, p))| {
1248 TypeOrConstParamData::TypeParamData(p) => p,
1249 TypeOrConstParamData::ConstParamData(_) => {
1250 // FIXME: here we should add const generic parameters
1251 let ty = TyKind::Error.intern(Interner);
1252 return crate::make_only_type_binders(idx, ty);
1256 p.default.as_ref().map_or(TyKind::Error.intern(Interner), |t| ctx.lower_ty(t));
1258 // Each default can only refer to previous parameters.
1259 ty = crate::fold_free_vars(ty, |bound, binders| {
1260 if bound.index >= idx && bound.debruijn == DebruijnIndex::INNERMOST {
1261 // type variable default referring to parameter coming
1262 // after it. This is forbidden (FIXME: report
1264 TyKind::Error.intern(Interner)
1266 bound.shifted_in_from(binders).to_ty(Interner)
1270 crate::make_only_type_binders(idx, ty)
1277 pub(crate) fn generic_defaults_recover(
1278 db: &dyn HirDatabase,
1281 ) -> Arc<[Binders<Ty>]> {
1282 let generic_params = generics(db.upcast(), *def);
1284 // we still need one default per parameter
1285 let defaults = generic_params
1289 let ty = TyKind::Error.intern(Interner);
1291 crate::make_only_type_binders(idx, ty)
1298 fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
1299 let data = db.function_data(def);
1300 let resolver = def.resolver(db.upcast());
1301 let ctx_params = TyLoweringContext::new(db, &resolver)
1302 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
1303 .with_type_param_mode(TypeParamLoweringMode::Variable);
1304 let params = data.params.iter().map(|(_, tr)| ctx_params.lower_ty(tr)).collect::<Vec<_>>();
1305 let ctx_ret = TyLoweringContext::new(db, &resolver)
1306 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1307 .with_type_param_mode(TypeParamLoweringMode::Variable);
1308 let ret = ctx_ret.lower_ty(&data.ret_type);
1309 let generics = generics(db.upcast(), def.into());
1310 let mut sig = CallableSig::from_params_and_return(params, ret, data.is_varargs());
1311 if !data.legacy_const_generics_indices.is_empty() {
1312 sig.set_legacy_const_generics_indices(&data.legacy_const_generics_indices);
1314 make_binders(&generics, sig)
1317 /// Build the declared type of a function. This should not need to look at the
1319 fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1320 let generics = generics(db.upcast(), def.into());
1321 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1324 TyKind::FnDef(CallableDefId::FunctionId(def).to_chalk(db), substs).intern(Interner),
1328 /// Build the declared type of a const.
1329 fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1330 let data = db.const_data(def);
1331 let generics = generics(db.upcast(), def.into());
1332 let resolver = def.resolver(db.upcast());
1334 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1336 make_binders(&generics, ctx.lower_ty(&data.type_ref))
1339 /// Build the declared type of a static.
1340 fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1341 let data = db.static_data(def);
1342 let resolver = def.resolver(db.upcast());
1343 let ctx = TyLoweringContext::new(db, &resolver);
1345 Binders::empty(Interner, ctx.lower_ty(&data.type_ref))
1348 fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1349 let struct_data = db.struct_data(def);
1350 let fields = struct_data.variant_data.fields();
1351 let resolver = def.resolver(db.upcast());
1353 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1354 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1355 let (ret, binders) = type_for_adt(db, def.into()).into_value_and_skipped_binders();
1356 Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1359 /// Build the type of a tuple struct constructor.
1360 fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1361 let struct_data = db.struct_data(def);
1362 if let StructKind::Unit = struct_data.variant_data.kind() {
1363 return type_for_adt(db, def.into());
1365 let generics = generics(db.upcast(), def.into());
1366 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1369 TyKind::FnDef(CallableDefId::StructId(def).to_chalk(db), substs).intern(Interner),
1373 fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1374 let enum_data = db.enum_data(def.parent);
1375 let var_data = &enum_data.variants[def.local_id];
1376 let fields = var_data.variant_data.fields();
1377 let resolver = def.parent.resolver(db.upcast());
1379 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1380 let params = fields.iter().map(|(_, field)| ctx.lower_ty(&field.type_ref)).collect::<Vec<_>>();
1381 let (ret, binders) = type_for_adt(db, def.parent.into()).into_value_and_skipped_binders();
1382 Binders::new(binders, CallableSig::from_params_and_return(params, ret, false))
1385 /// Build the type of a tuple enum variant constructor.
1386 fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1387 let enum_data = db.enum_data(def.parent);
1388 let var_data = &enum_data.variants[def.local_id].variant_data;
1389 if let StructKind::Unit = var_data.kind() {
1390 return type_for_adt(db, def.parent.into());
1392 let generics = generics(db.upcast(), def.parent.into());
1393 let substs = generics.bound_vars_subst(DebruijnIndex::INNERMOST);
1396 TyKind::FnDef(CallableDefId::EnumVariantId(def).to_chalk(db), substs).intern(Interner),
1400 fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1401 let generics = generics(db.upcast(), adt.into());
1402 let b = TyBuilder::adt(db, adt);
1403 let ty = b.fill_with_bound_vars(DebruijnIndex::INNERMOST, 0).build();
1404 make_binders(&generics, ty)
1407 fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1408 let generics = generics(db.upcast(), t.into());
1409 let resolver = t.resolver(db.upcast());
1411 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1412 if db.type_alias_data(t).is_extern {
1413 Binders::empty(Interner, TyKind::Foreign(crate::to_foreign_def_id(t)).intern(Interner))
1415 let type_ref = &db.type_alias_data(t).type_ref;
1416 let inner = ctx.lower_ty(type_ref.as_deref().unwrap_or(&TypeRef::Error));
1417 make_binders(&generics, inner)
1421 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1422 pub enum CallableDefId {
1423 FunctionId(FunctionId),
1425 EnumVariantId(EnumVariantId),
1427 impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1429 impl CallableDefId {
1430 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1431 let db = db.upcast();
1433 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1434 CallableDefId::StructId(s) => s.lookup(db).container,
1435 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container,
1441 impl From<CallableDefId> for GenericDefId {
1442 fn from(def: CallableDefId) -> GenericDefId {
1444 CallableDefId::FunctionId(f) => f.into(),
1445 CallableDefId::StructId(s) => s.into(),
1446 CallableDefId::EnumVariantId(e) => e.into(),
1451 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1453 BuiltinType(BuiltinType),
1455 TypeAliasId(TypeAliasId),
1457 impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1459 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1460 pub enum ValueTyDefId {
1461 FunctionId(FunctionId),
1464 EnumVariantId(EnumVariantId),
1468 impl_from!(FunctionId, StructId, UnionId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1470 /// Build the declared type of an item. This depends on the namespace; e.g. for
1471 /// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1472 /// the constructor function `(usize) -> Foo` which lives in the values
1474 pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1476 TyDefId::BuiltinType(it) => Binders::empty(Interner, TyBuilder::builtin(it)),
1477 TyDefId::AdtId(it) => type_for_adt(db, it),
1478 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1482 pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1483 let generics = match *def {
1484 TyDefId::BuiltinType(_) => return Binders::empty(Interner, TyKind::Error.intern(Interner)),
1485 TyDefId::AdtId(it) => generics(db.upcast(), it.into()),
1486 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()),
1488 make_binders(&generics, TyKind::Error.intern(Interner))
1491 pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1493 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1494 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1495 ValueTyDefId::UnionId(it) => type_for_adt(db, it.into()),
1496 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1497 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1498 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1502 pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1503 let impl_loc = impl_id.lookup(db.upcast());
1504 let impl_data = db.impl_data(impl_id);
1505 let resolver = impl_id.resolver(db.upcast());
1506 let _cx = stdx::panic_context::enter(format!(
1507 "impl_self_ty_query({:?} -> {:?} -> {:?})",
1508 impl_id, impl_loc, impl_data
1510 let generics = generics(db.upcast(), impl_id.into());
1512 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1513 make_binders(&generics, ctx.lower_ty(&impl_data.self_ty))
1516 // returns None if def is a type arg
1517 pub(crate) fn const_param_ty_query(db: &dyn HirDatabase, def: ConstParamId) -> Ty {
1518 let parent_data = db.generic_params(def.parent());
1519 let data = &parent_data.tocs[def.local_id()];
1520 let resolver = def.parent().resolver(db.upcast());
1521 let ctx = TyLoweringContext::new(db, &resolver);
1523 TypeOrConstParamData::TypeParamData(_) => {
1525 Ty::new(Interner, TyKind::Error)
1527 TypeOrConstParamData::ConstParamData(d) => ctx.lower_ty(&d.ty),
1531 pub(crate) fn impl_self_ty_recover(
1532 db: &dyn HirDatabase,
1536 let generics = generics(db.upcast(), (*impl_id).into());
1537 make_binders(&generics, TyKind::Error.intern(Interner))
1540 pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1541 let impl_loc = impl_id.lookup(db.upcast());
1542 let impl_data = db.impl_data(impl_id);
1543 let resolver = impl_id.resolver(db.upcast());
1544 let _cx = stdx::panic_context::enter(format!(
1545 "impl_trait_query({:?} -> {:?} -> {:?})",
1546 impl_id, impl_loc, impl_data
1549 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1550 let (self_ty, binders) = db.impl_self_ty(impl_id).into_value_and_skipped_binders();
1551 let target_trait = impl_data.target_trait.as_ref()?;
1552 Some(Binders::new(binders, ctx.lower_trait_ref(target_trait, Some(self_ty))?))
1555 pub(crate) fn return_type_impl_traits(
1556 db: &dyn HirDatabase,
1557 def: hir_def::FunctionId,
1558 ) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1559 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1560 let data = db.function_data(def);
1561 let resolver = def.resolver(db.upcast());
1562 let ctx_ret = TyLoweringContext::new(db, &resolver)
1563 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1564 .with_type_param_mode(TypeParamLoweringMode::Variable);
1565 let _ret = (&ctx_ret).lower_ty(&data.ret_type);
1566 let generics = generics(db.upcast(), def.into());
1567 let return_type_impl_traits =
1568 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1569 if return_type_impl_traits.impl_traits.is_empty() {
1572 Some(Arc::new(make_binders(&generics, return_type_impl_traits)))
1576 pub(crate) fn lower_to_chalk_mutability(m: hir_def::type_ref::Mutability) -> Mutability {
1578 hir_def::type_ref::Mutability::Shared => Mutability::Not,
1579 hir_def::type_ref::Mutability::Mut => Mutability::Mut,
1583 fn make_binders<T: HasInterner<Interner = Interner>>(generics: &Generics, value: T) -> Binders<T> {
1584 crate::make_only_type_binders(generics.len(), value)