aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_ty/src/lower.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir_ty/src/lower.rs')
-rw-r--r--crates/ra_hir_ty/src/lower.rs1239
1 files changed, 0 insertions, 1239 deletions
diff --git a/crates/ra_hir_ty/src/lower.rs b/crates/ra_hir_ty/src/lower.rs
deleted file mode 100644
index 1eacc6f95..000000000
--- a/crates/ra_hir_ty/src/lower.rs
+++ /dev/null
@@ -1,1239 +0,0 @@
1//! Methods for lowering the HIR to types. There are two main cases here:
2//!
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.
6//!
7//! This usually involves resolving names, collecting generic arguments etc.
8use std::{iter, sync::Arc};
9
10use hir_def::{
11 adt::StructKind,
12 builtin_type::BuiltinType,
13 generics::{TypeParamProvenance, WherePredicate, WherePredicateTarget},
14 path::{GenericArg, Path, PathSegment, PathSegments},
15 resolver::{HasResolver, Resolver, TypeNs},
16 type_ref::{TypeBound, TypeRef},
17 AdtId, AssocContainerId, AssocItemId, ConstId, EnumId, EnumVariantId, FunctionId, GenericDefId,
18 HasModule, ImplId, LocalFieldId, Lookup, StaticId, StructId, TraitId, TypeAliasId, TypeParamId,
19 UnionId, VariantId,
20};
21use hir_expand::name::Name;
22use ra_arena::map::ArenaMap;
23use ra_db::CrateId;
24use smallvec::SmallVec;
25use stdx::impl_from;
26use test_utils::mark;
27
28use crate::{
29 db::HirDatabase,
30 primitive::{FloatTy, IntTy},
31 utils::{
32 all_super_trait_refs, associated_type_by_name_including_super_traits, generics,
33 make_mut_slice, variant_data,
34 },
35 Binders, BoundVar, DebruijnIndex, FnSig, GenericPredicate, OpaqueTy, OpaqueTyId, PolyFnSig,
36 ProjectionPredicate, ProjectionTy, ReturnTypeImplTrait, ReturnTypeImplTraits, Substs,
37 TraitEnvironment, TraitRef, Ty, TypeCtor, TypeWalk,
38};
39
40#[derive(Debug)]
41pub struct TyLoweringContext<'a> {
42 pub db: &'a dyn HirDatabase,
43 pub resolver: &'a Resolver,
44 in_binders: DebruijnIndex,
45 /// Note: Conceptually, it's thinkable that we could be in a location where
46 /// some type params should be represented as placeholders, and others
47 /// should be converted to variables. I think in practice, this isn't
48 /// possible currently, so this should be fine for now.
49 pub type_param_mode: TypeParamLoweringMode,
50 pub impl_trait_mode: ImplTraitLoweringMode,
51 impl_trait_counter: std::cell::Cell<u16>,
52 /// When turning `impl Trait` into opaque types, we have to collect the
53 /// bounds at the same time to get the IDs correct (without becoming too
54 /// complicated). I don't like using interior mutability (as for the
55 /// counter), but I've tried and failed to make the lifetimes work for
56 /// passing around a `&mut TyLoweringContext`. The core problem is that
57 /// we're grouping the mutable data (the counter and this field) together
58 /// with the immutable context (the references to the DB and resolver).
59 /// Splitting this up would be a possible fix.
60 opaque_type_data: std::cell::RefCell<Vec<ReturnTypeImplTrait>>,
61}
62
63impl<'a> TyLoweringContext<'a> {
64 pub fn new(db: &'a dyn HirDatabase, resolver: &'a Resolver) -> Self {
65 let impl_trait_counter = std::cell::Cell::new(0);
66 let impl_trait_mode = ImplTraitLoweringMode::Disallowed;
67 let type_param_mode = TypeParamLoweringMode::Placeholder;
68 let in_binders = DebruijnIndex::INNERMOST;
69 let opaque_type_data = std::cell::RefCell::new(Vec::new());
70 Self {
71 db,
72 resolver,
73 in_binders,
74 impl_trait_mode,
75 impl_trait_counter,
76 type_param_mode,
77 opaque_type_data,
78 }
79 }
80
81 pub fn with_debruijn<T>(
82 &self,
83 debruijn: DebruijnIndex,
84 f: impl FnOnce(&TyLoweringContext) -> T,
85 ) -> T {
86 let opaque_ty_data_vec = self.opaque_type_data.replace(Vec::new());
87 let new_ctx = Self {
88 in_binders: debruijn,
89 impl_trait_counter: std::cell::Cell::new(self.impl_trait_counter.get()),
90 opaque_type_data: std::cell::RefCell::new(opaque_ty_data_vec),
91 ..*self
92 };
93 let result = f(&new_ctx);
94 self.impl_trait_counter.set(new_ctx.impl_trait_counter.get());
95 self.opaque_type_data.replace(new_ctx.opaque_type_data.into_inner());
96 result
97 }
98
99 pub fn with_shifted_in<T>(
100 &self,
101 debruijn: DebruijnIndex,
102 f: impl FnOnce(&TyLoweringContext) -> T,
103 ) -> T {
104 self.with_debruijn(self.in_binders.shifted_in_from(debruijn), f)
105 }
106
107 pub fn with_impl_trait_mode(self, impl_trait_mode: ImplTraitLoweringMode) -> Self {
108 Self { impl_trait_mode, ..self }
109 }
110
111 pub fn with_type_param_mode(self, type_param_mode: TypeParamLoweringMode) -> Self {
112 Self { type_param_mode, ..self }
113 }
114}
115
116#[derive(Copy, Clone, Debug, PartialEq, Eq)]
117pub enum ImplTraitLoweringMode {
118 /// `impl Trait` gets lowered into an opaque type that doesn't unify with
119 /// anything except itself. This is used in places where values flow 'out',
120 /// i.e. for arguments of the function we're currently checking, and return
121 /// types of functions we're calling.
122 Opaque,
123 /// `impl Trait` gets lowered into a type variable. Used for argument
124 /// position impl Trait when inside the respective function, since it allows
125 /// us to support that without Chalk.
126 Param,
127 /// `impl Trait` gets lowered into a variable that can unify with some
128 /// type. This is used in places where values flow 'in', i.e. for arguments
129 /// of functions we're calling, and the return type of the function we're
130 /// currently checking.
131 Variable,
132 /// `impl Trait` is disallowed and will be an error.
133 Disallowed,
134}
135
136#[derive(Copy, Clone, Debug, PartialEq, Eq)]
137pub enum TypeParamLoweringMode {
138 Placeholder,
139 Variable,
140}
141
142impl Ty {
143 pub fn from_hir(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Self {
144 Ty::from_hir_ext(ctx, type_ref).0
145 }
146 pub fn from_hir_ext(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> (Self, Option<TypeNs>) {
147 let mut res = None;
148 let ty = match type_ref {
149 TypeRef::Never => Ty::simple(TypeCtor::Never),
150 TypeRef::Tuple(inner) => {
151 let inner_tys: Arc<[Ty]> = inner.iter().map(|tr| Ty::from_hir(ctx, tr)).collect();
152 Ty::apply(
153 TypeCtor::Tuple { cardinality: inner_tys.len() as u16 },
154 Substs(inner_tys),
155 )
156 }
157 TypeRef::Path(path) => {
158 let (ty, res_) = Ty::from_hir_path(ctx, path);
159 res = res_;
160 ty
161 }
162 TypeRef::RawPtr(inner, mutability) => {
163 let inner_ty = Ty::from_hir(ctx, inner);
164 Ty::apply_one(TypeCtor::RawPtr(*mutability), inner_ty)
165 }
166 TypeRef::Array(inner) => {
167 let inner_ty = Ty::from_hir(ctx, inner);
168 Ty::apply_one(TypeCtor::Array, inner_ty)
169 }
170 TypeRef::Slice(inner) => {
171 let inner_ty = Ty::from_hir(ctx, inner);
172 Ty::apply_one(TypeCtor::Slice, inner_ty)
173 }
174 TypeRef::Reference(inner, mutability) => {
175 let inner_ty = Ty::from_hir(ctx, inner);
176 Ty::apply_one(TypeCtor::Ref(*mutability), inner_ty)
177 }
178 TypeRef::Placeholder => Ty::Unknown,
179 TypeRef::Fn(params, is_varargs) => {
180 let sig = Substs(params.iter().map(|tr| Ty::from_hir(ctx, tr)).collect());
181 Ty::apply(
182 TypeCtor::FnPtr { num_args: sig.len() as u16 - 1, is_varargs: *is_varargs },
183 sig,
184 )
185 }
186 TypeRef::DynTrait(bounds) => {
187 let self_ty = Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0));
188 let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| {
189 bounds
190 .iter()
191 .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
192 .collect()
193 });
194 Ty::Dyn(predicates)
195 }
196 TypeRef::ImplTrait(bounds) => {
197 match ctx.impl_trait_mode {
198 ImplTraitLoweringMode::Opaque => {
199 let idx = ctx.impl_trait_counter.get();
200 ctx.impl_trait_counter.set(idx + 1);
201
202 assert!(idx as usize == ctx.opaque_type_data.borrow().len());
203 // this dance is to make sure the data is in the right
204 // place even if we encounter more opaque types while
205 // lowering the bounds
206 ctx.opaque_type_data
207 .borrow_mut()
208 .push(ReturnTypeImplTrait { bounds: Binders::new(1, Vec::new()) });
209 // We don't want to lower the bounds inside the binders
210 // we're currently in, because they don't end up inside
211 // those binders. E.g. when we have `impl Trait<impl
212 // OtherTrait<T>>`, the `impl OtherTrait<T>` can't refer
213 // to the self parameter from `impl Trait`, and the
214 // bounds aren't actually stored nested within each
215 // other, but separately. So if the `T` refers to a type
216 // parameter of the outer function, it's just one binder
217 // away instead of two.
218 let actual_opaque_type_data = ctx
219 .with_debruijn(DebruijnIndex::INNERMOST, |ctx| {
220 ReturnTypeImplTrait::from_hir(ctx, &bounds)
221 });
222 ctx.opaque_type_data.borrow_mut()[idx as usize] = actual_opaque_type_data;
223
224 let func = match ctx.resolver.generic_def() {
225 Some(GenericDefId::FunctionId(f)) => f,
226 _ => panic!("opaque impl trait lowering in non-function"),
227 };
228 let impl_trait_id = OpaqueTyId::ReturnTypeImplTrait(func, idx);
229 let generics = generics(ctx.db.upcast(), func.into());
230 let parameters = Substs::bound_vars(&generics, ctx.in_binders);
231 Ty::Opaque(OpaqueTy { opaque_ty_id: impl_trait_id, parameters })
232 }
233 ImplTraitLoweringMode::Param => {
234 let idx = ctx.impl_trait_counter.get();
235 // FIXME we're probably doing something wrong here
236 ctx.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
237 if let Some(def) = ctx.resolver.generic_def() {
238 let generics = generics(ctx.db.upcast(), def);
239 let param = generics
240 .iter()
241 .filter(|(_, data)| {
242 data.provenance == TypeParamProvenance::ArgumentImplTrait
243 })
244 .nth(idx as usize)
245 .map_or(Ty::Unknown, |(id, _)| Ty::Placeholder(id));
246 param
247 } else {
248 Ty::Unknown
249 }
250 }
251 ImplTraitLoweringMode::Variable => {
252 let idx = ctx.impl_trait_counter.get();
253 // FIXME we're probably doing something wrong here
254 ctx.impl_trait_counter.set(idx + count_impl_traits(type_ref) as u16);
255 let (parent_params, self_params, list_params, _impl_trait_params) =
256 if let Some(def) = ctx.resolver.generic_def() {
257 let generics = generics(ctx.db.upcast(), def);
258 generics.provenance_split()
259 } else {
260 (0, 0, 0, 0)
261 };
262 Ty::Bound(BoundVar::new(
263 ctx.in_binders,
264 idx as usize + parent_params + self_params + list_params,
265 ))
266 }
267 ImplTraitLoweringMode::Disallowed => {
268 // FIXME: report error
269 Ty::Unknown
270 }
271 }
272 }
273 TypeRef::Error => Ty::Unknown,
274 };
275 (ty, res)
276 }
277
278 /// This is only for `generic_predicates_for_param`, where we can't just
279 /// lower the self types of the predicates since that could lead to cycles.
280 /// So we just check here if the `type_ref` resolves to a generic param, and which.
281 fn from_hir_only_param(ctx: &TyLoweringContext<'_>, type_ref: &TypeRef) -> Option<TypeParamId> {
282 let path = match type_ref {
283 TypeRef::Path(path) => path,
284 _ => return None,
285 };
286 if path.type_anchor().is_some() {
287 return None;
288 }
289 if path.segments().len() > 1 {
290 return None;
291 }
292 let resolution =
293 match ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) {
294 Some((it, None)) => it,
295 _ => return None,
296 };
297 if let TypeNs::GenericParam(param_id) = resolution {
298 Some(param_id)
299 } else {
300 None
301 }
302 }
303
304 pub(crate) fn from_type_relative_path(
305 ctx: &TyLoweringContext<'_>,
306 ty: Ty,
307 // We need the original resolution to lower `Self::AssocTy` correctly
308 res: Option<TypeNs>,
309 remaining_segments: PathSegments<'_>,
310 ) -> (Ty, Option<TypeNs>) {
311 if remaining_segments.len() == 1 {
312 // resolve unselected assoc types
313 let segment = remaining_segments.first().unwrap();
314 (Ty::select_associated_type(ctx, res, segment), None)
315 } else if remaining_segments.len() > 1 {
316 // FIXME report error (ambiguous associated type)
317 (Ty::Unknown, None)
318 } else {
319 (ty, res)
320 }
321 }
322
323 pub(crate) fn from_partly_resolved_hir_path(
324 ctx: &TyLoweringContext<'_>,
325 resolution: TypeNs,
326 resolved_segment: PathSegment<'_>,
327 remaining_segments: PathSegments<'_>,
328 infer_args: bool,
329 ) -> (Ty, Option<TypeNs>) {
330 let ty = match resolution {
331 TypeNs::TraitId(trait_) => {
332 // if this is a bare dyn Trait, we'll directly put the required ^0 for the self type in there
333 let self_ty = if remaining_segments.len() == 0 {
334 Some(Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0)))
335 } else {
336 None
337 };
338 let trait_ref =
339 TraitRef::from_resolved_path(ctx, trait_, resolved_segment, self_ty);
340 let ty = if remaining_segments.len() == 1 {
341 let segment = remaining_segments.first().unwrap();
342 let found = associated_type_by_name_including_super_traits(
343 ctx.db,
344 trait_ref,
345 &segment.name,
346 );
347 match found {
348 Some((super_trait_ref, associated_ty)) => {
349 // FIXME handle type parameters on the segment
350 Ty::Projection(ProjectionTy {
351 associated_ty,
352 parameters: super_trait_ref.substs,
353 })
354 }
355 None => {
356 // FIXME: report error (associated type not found)
357 Ty::Unknown
358 }
359 }
360 } else if remaining_segments.len() > 1 {
361 // FIXME report error (ambiguous associated type)
362 Ty::Unknown
363 } else {
364 Ty::Dyn(Arc::new([GenericPredicate::Implemented(trait_ref)]))
365 };
366 return (ty, None);
367 }
368 TypeNs::GenericParam(param_id) => {
369 let generics = generics(
370 ctx.db.upcast(),
371 ctx.resolver.generic_def().expect("generics in scope"),
372 );
373 match ctx.type_param_mode {
374 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id),
375 TypeParamLoweringMode::Variable => {
376 let idx = generics.param_idx(param_id).expect("matching generics");
377 Ty::Bound(BoundVar::new(ctx.in_binders, idx))
378 }
379 }
380 }
381 TypeNs::SelfType(impl_id) => {
382 let generics = generics(ctx.db.upcast(), impl_id.into());
383 let substs = match ctx.type_param_mode {
384 TypeParamLoweringMode::Placeholder => {
385 Substs::type_params_for_generics(&generics)
386 }
387 TypeParamLoweringMode::Variable => {
388 Substs::bound_vars(&generics, ctx.in_binders)
389 }
390 };
391 ctx.db.impl_self_ty(impl_id).subst(&substs)
392 }
393 TypeNs::AdtSelfType(adt) => {
394 let generics = generics(ctx.db.upcast(), adt.into());
395 let substs = match ctx.type_param_mode {
396 TypeParamLoweringMode::Placeholder => {
397 Substs::type_params_for_generics(&generics)
398 }
399 TypeParamLoweringMode::Variable => {
400 Substs::bound_vars(&generics, ctx.in_binders)
401 }
402 };
403 ctx.db.ty(adt.into()).subst(&substs)
404 }
405
406 TypeNs::AdtId(it) => {
407 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
408 }
409 TypeNs::BuiltinType(it) => {
410 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
411 }
412 TypeNs::TypeAliasId(it) => {
413 Ty::from_hir_path_inner(ctx, resolved_segment, it.into(), infer_args)
414 }
415 // FIXME: report error
416 TypeNs::EnumVariantId(_) => return (Ty::Unknown, None),
417 };
418
419 Ty::from_type_relative_path(ctx, ty, Some(resolution), remaining_segments)
420 }
421
422 pub(crate) fn from_hir_path(ctx: &TyLoweringContext<'_>, path: &Path) -> (Ty, Option<TypeNs>) {
423 // Resolve the path (in type namespace)
424 if let Some(type_ref) = path.type_anchor() {
425 let (ty, res) = Ty::from_hir_ext(ctx, &type_ref);
426 return Ty::from_type_relative_path(ctx, ty, res, path.segments());
427 }
428 let (resolution, remaining_index) =
429 match ctx.resolver.resolve_path_in_type_ns(ctx.db.upcast(), path.mod_path()) {
430 Some(it) => it,
431 None => return (Ty::Unknown, None),
432 };
433 let (resolved_segment, remaining_segments) = match remaining_index {
434 None => (
435 path.segments().last().expect("resolved path has at least one element"),
436 PathSegments::EMPTY,
437 ),
438 Some(i) => (path.segments().get(i - 1).unwrap(), path.segments().skip(i)),
439 };
440 Ty::from_partly_resolved_hir_path(
441 ctx,
442 resolution,
443 resolved_segment,
444 remaining_segments,
445 false,
446 )
447 }
448
449 fn select_associated_type(
450 ctx: &TyLoweringContext<'_>,
451 res: Option<TypeNs>,
452 segment: PathSegment<'_>,
453 ) -> Ty {
454 if let Some(res) = res {
455 let ty =
456 associated_type_shorthand_candidates(ctx.db, res, move |name, t, associated_ty| {
457 if name == segment.name {
458 let substs = match ctx.type_param_mode {
459 TypeParamLoweringMode::Placeholder => {
460 // if we're lowering to placeholders, we have to put
461 // them in now
462 let s = Substs::type_params(
463 ctx.db,
464 ctx.resolver.generic_def().expect(
465 "there should be generics if there's a generic param",
466 ),
467 );
468 t.substs.clone().subst_bound_vars(&s)
469 }
470 TypeParamLoweringMode::Variable => t.substs.clone(),
471 };
472 // We need to shift in the bound vars, since
473 // associated_type_shorthand_candidates does not do that
474 let substs = substs.shift_bound_vars(ctx.in_binders);
475 // FIXME handle type parameters on the segment
476 return Some(Ty::Projection(ProjectionTy {
477 associated_ty,
478 parameters: substs,
479 }));
480 }
481
482 None
483 });
484
485 ty.unwrap_or(Ty::Unknown)
486 } else {
487 Ty::Unknown
488 }
489 }
490
491 fn from_hir_path_inner(
492 ctx: &TyLoweringContext<'_>,
493 segment: PathSegment<'_>,
494 typable: TyDefId,
495 infer_args: bool,
496 ) -> Ty {
497 let generic_def = match typable {
498 TyDefId::BuiltinType(_) => None,
499 TyDefId::AdtId(it) => Some(it.into()),
500 TyDefId::TypeAliasId(it) => Some(it.into()),
501 };
502 let substs = substs_from_path_segment(ctx, segment, generic_def, infer_args);
503 ctx.db.ty(typable).subst(&substs)
504 }
505
506 /// Collect generic arguments from a path into a `Substs`. See also
507 /// `create_substs_for_ast_path` and `def_to_ty` in rustc.
508 pub(super) fn substs_from_path(
509 ctx: &TyLoweringContext<'_>,
510 path: &Path,
511 // Note that we don't call `db.value_type(resolved)` here,
512 // `ValueTyDefId` is just a convenient way to pass generics and
513 // special-case enum variants
514 resolved: ValueTyDefId,
515 infer_args: bool,
516 ) -> Substs {
517 let last = path.segments().last().expect("path should have at least one segment");
518 let (segment, generic_def) = match resolved {
519 ValueTyDefId::FunctionId(it) => (last, Some(it.into())),
520 ValueTyDefId::StructId(it) => (last, Some(it.into())),
521 ValueTyDefId::ConstId(it) => (last, Some(it.into())),
522 ValueTyDefId::StaticId(_) => (last, None),
523 ValueTyDefId::EnumVariantId(var) => {
524 // the generic args for an enum variant may be either specified
525 // on the segment referring to the enum, or on the segment
526 // referring to the variant. So `Option::<T>::None` and
527 // `Option::None::<T>` are both allowed (though the former is
528 // preferred). See also `def_ids_for_path_segments` in rustc.
529 let len = path.segments().len();
530 let penultimate = if len >= 2 { path.segments().get(len - 2) } else { None };
531 let segment = match penultimate {
532 Some(segment) if segment.args_and_bindings.is_some() => segment,
533 _ => last,
534 };
535 (segment, Some(var.parent.into()))
536 }
537 };
538 substs_from_path_segment(ctx, segment, generic_def, infer_args)
539 }
540}
541
542fn substs_from_path_segment(
543 ctx: &TyLoweringContext<'_>,
544 segment: PathSegment<'_>,
545 def_generic: Option<GenericDefId>,
546 infer_args: bool,
547) -> Substs {
548 let mut substs = Vec::new();
549 let def_generics = def_generic.map(|def| generics(ctx.db.upcast(), def));
550
551 let (parent_params, self_params, type_params, impl_trait_params) =
552 def_generics.map_or((0, 0, 0, 0), |g| g.provenance_split());
553 let total_len = parent_params + self_params + type_params + impl_trait_params;
554
555 substs.extend(iter::repeat(Ty::Unknown).take(parent_params));
556
557 let mut had_explicit_args = false;
558
559 if let Some(generic_args) = &segment.args_and_bindings {
560 if !generic_args.has_self_type {
561 substs.extend(iter::repeat(Ty::Unknown).take(self_params));
562 }
563 let expected_num =
564 if generic_args.has_self_type { self_params + type_params } else { type_params };
565 let skip = if generic_args.has_self_type && self_params == 0 { 1 } else { 0 };
566 // if args are provided, it should be all of them, but we can't rely on that
567 for arg in generic_args.args.iter().skip(skip).take(expected_num) {
568 match arg {
569 GenericArg::Type(type_ref) => {
570 had_explicit_args = true;
571 let ty = Ty::from_hir(ctx, type_ref);
572 substs.push(ty);
573 }
574 }
575 }
576 }
577
578 // handle defaults. In expression or pattern path segments without
579 // explicitly specified type arguments, missing type arguments are inferred
580 // (i.e. defaults aren't used).
581 if !infer_args || had_explicit_args {
582 if let Some(def_generic) = def_generic {
583 let defaults = ctx.db.generic_defaults(def_generic);
584 assert_eq!(total_len, defaults.len());
585
586 for default_ty in defaults.iter().skip(substs.len()) {
587 // each default can depend on the previous parameters
588 let substs_so_far = Substs(substs.clone().into());
589 substs.push(default_ty.clone().subst(&substs_so_far));
590 }
591 }
592 }
593
594 // add placeholders for args that were not provided
595 // FIXME: emit diagnostics in contexts where this is not allowed
596 for _ in substs.len()..total_len {
597 substs.push(Ty::Unknown);
598 }
599 assert_eq!(substs.len(), total_len);
600
601 Substs(substs.into())
602}
603
604impl TraitRef {
605 fn from_path(
606 ctx: &TyLoweringContext<'_>,
607 path: &Path,
608 explicit_self_ty: Option<Ty>,
609 ) -> Option<Self> {
610 let resolved =
611 match ctx.resolver.resolve_path_in_type_ns_fully(ctx.db.upcast(), path.mod_path())? {
612 TypeNs::TraitId(tr) => tr,
613 _ => return None,
614 };
615 let segment = path.segments().last().expect("path should have at least one segment");
616 Some(TraitRef::from_resolved_path(ctx, resolved, segment, explicit_self_ty))
617 }
618
619 pub(crate) fn from_resolved_path(
620 ctx: &TyLoweringContext<'_>,
621 resolved: TraitId,
622 segment: PathSegment<'_>,
623 explicit_self_ty: Option<Ty>,
624 ) -> Self {
625 let mut substs = TraitRef::substs_from_path(ctx, segment, resolved);
626 if let Some(self_ty) = explicit_self_ty {
627 make_mut_slice(&mut substs.0)[0] = self_ty;
628 }
629 TraitRef { trait_: resolved, substs }
630 }
631
632 fn from_hir(
633 ctx: &TyLoweringContext<'_>,
634 type_ref: &TypeRef,
635 explicit_self_ty: Option<Ty>,
636 ) -> Option<Self> {
637 let path = match type_ref {
638 TypeRef::Path(path) => path,
639 _ => return None,
640 };
641 TraitRef::from_path(ctx, path, explicit_self_ty)
642 }
643
644 fn substs_from_path(
645 ctx: &TyLoweringContext<'_>,
646 segment: PathSegment<'_>,
647 resolved: TraitId,
648 ) -> Substs {
649 substs_from_path_segment(ctx, segment, Some(resolved.into()), false)
650 }
651
652 pub(crate) fn from_type_bound(
653 ctx: &TyLoweringContext<'_>,
654 bound: &TypeBound,
655 self_ty: Ty,
656 ) -> Option<TraitRef> {
657 match bound {
658 TypeBound::Path(path) => TraitRef::from_path(ctx, path, Some(self_ty)),
659 TypeBound::Error => None,
660 }
661 }
662}
663
664impl GenericPredicate {
665 pub(crate) fn from_where_predicate<'a>(
666 ctx: &'a TyLoweringContext<'a>,
667 where_predicate: &'a WherePredicate,
668 ) -> impl Iterator<Item = GenericPredicate> + 'a {
669 let self_ty = match &where_predicate.target {
670 WherePredicateTarget::TypeRef(type_ref) => Ty::from_hir(ctx, type_ref),
671 WherePredicateTarget::TypeParam(param_id) => {
672 let generic_def = ctx.resolver.generic_def().expect("generics in scope");
673 let generics = generics(ctx.db.upcast(), generic_def);
674 let param_id = hir_def::TypeParamId { parent: generic_def, local_id: *param_id };
675 match ctx.type_param_mode {
676 TypeParamLoweringMode::Placeholder => Ty::Placeholder(param_id),
677 TypeParamLoweringMode::Variable => {
678 let idx = generics.param_idx(param_id).expect("matching generics");
679 Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, idx))
680 }
681 }
682 }
683 };
684 GenericPredicate::from_type_bound(ctx, &where_predicate.bound, self_ty)
685 }
686
687 pub(crate) fn from_type_bound<'a>(
688 ctx: &'a TyLoweringContext<'a>,
689 bound: &'a TypeBound,
690 self_ty: Ty,
691 ) -> impl Iterator<Item = GenericPredicate> + 'a {
692 let trait_ref = TraitRef::from_type_bound(ctx, bound, self_ty);
693 iter::once(trait_ref.clone().map_or(GenericPredicate::Error, GenericPredicate::Implemented))
694 .chain(
695 trait_ref
696 .into_iter()
697 .flat_map(move |tr| assoc_type_bindings_from_type_bound(ctx, bound, tr)),
698 )
699 }
700}
701
702fn assoc_type_bindings_from_type_bound<'a>(
703 ctx: &'a TyLoweringContext<'a>,
704 bound: &'a TypeBound,
705 trait_ref: TraitRef,
706) -> impl Iterator<Item = GenericPredicate> + 'a {
707 let last_segment = match bound {
708 TypeBound::Path(path) => path.segments().last(),
709 TypeBound::Error => None,
710 };
711 last_segment
712 .into_iter()
713 .flat_map(|segment| segment.args_and_bindings.into_iter())
714 .flat_map(|args_and_bindings| args_and_bindings.bindings.iter())
715 .flat_map(move |binding| {
716 let found = associated_type_by_name_including_super_traits(
717 ctx.db,
718 trait_ref.clone(),
719 &binding.name,
720 );
721 let (super_trait_ref, associated_ty) = match found {
722 None => return SmallVec::<[GenericPredicate; 1]>::new(),
723 Some(t) => t,
724 };
725 let projection_ty = ProjectionTy { associated_ty, parameters: super_trait_ref.substs };
726 let mut preds = SmallVec::with_capacity(
727 binding.type_ref.as_ref().map_or(0, |_| 1) + binding.bounds.len(),
728 );
729 if let Some(type_ref) = &binding.type_ref {
730 let ty = Ty::from_hir(ctx, type_ref);
731 let projection_predicate =
732 ProjectionPredicate { projection_ty: projection_ty.clone(), ty };
733 preds.push(GenericPredicate::Projection(projection_predicate));
734 }
735 for bound in &binding.bounds {
736 preds.extend(GenericPredicate::from_type_bound(
737 ctx,
738 bound,
739 Ty::Projection(projection_ty.clone()),
740 ));
741 }
742 preds
743 })
744}
745
746impl ReturnTypeImplTrait {
747 fn from_hir(ctx: &TyLoweringContext, bounds: &[TypeBound]) -> Self {
748 mark::hit!(lower_rpit);
749 let self_ty = Ty::Bound(BoundVar::new(DebruijnIndex::INNERMOST, 0));
750 let predicates = ctx.with_shifted_in(DebruijnIndex::ONE, |ctx| {
751 bounds
752 .iter()
753 .flat_map(|b| GenericPredicate::from_type_bound(ctx, b, self_ty.clone()))
754 .collect()
755 });
756 ReturnTypeImplTrait { bounds: Binders::new(1, predicates) }
757 }
758}
759
760fn count_impl_traits(type_ref: &TypeRef) -> usize {
761 let mut count = 0;
762 type_ref.walk(&mut |type_ref| {
763 if matches!(type_ref, TypeRef::ImplTrait(_)) {
764 count += 1;
765 }
766 });
767 count
768}
769
770/// Build the signature of a callable item (function, struct or enum variant).
771pub fn callable_item_sig(db: &dyn HirDatabase, def: CallableDefId) -> PolyFnSig {
772 match def {
773 CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f),
774 CallableDefId::StructId(s) => fn_sig_for_struct_constructor(db, s),
775 CallableDefId::EnumVariantId(e) => fn_sig_for_enum_variant_constructor(db, e),
776 }
777}
778
779pub fn associated_type_shorthand_candidates<R>(
780 db: &dyn HirDatabase,
781 res: TypeNs,
782 mut cb: impl FnMut(&Name, &TraitRef, TypeAliasId) -> Option<R>,
783) -> Option<R> {
784 let traits_from_env: Vec<_> = match res {
785 TypeNs::SelfType(impl_id) => match db.impl_trait(impl_id) {
786 None => vec![],
787 Some(trait_ref) => vec![trait_ref.value],
788 },
789 TypeNs::GenericParam(param_id) => {
790 let predicates = db.generic_predicates_for_param(param_id);
791 let mut traits_: Vec<_> = predicates
792 .iter()
793 .filter_map(|pred| match &pred.value {
794 GenericPredicate::Implemented(tr) => Some(tr.clone()),
795 _ => None,
796 })
797 .collect();
798 // Handle `Self::Type` referring to own associated type in trait definitions
799 if let GenericDefId::TraitId(trait_id) = param_id.parent {
800 let generics = generics(db.upcast(), trait_id.into());
801 if generics.params.types[param_id.local_id].provenance
802 == TypeParamProvenance::TraitSelf
803 {
804 let trait_ref = TraitRef {
805 trait_: trait_id,
806 substs: Substs::bound_vars(&generics, DebruijnIndex::INNERMOST),
807 };
808 traits_.push(trait_ref);
809 }
810 }
811 traits_
812 }
813 _ => vec![],
814 };
815
816 for t in traits_from_env.into_iter().flat_map(move |t| all_super_trait_refs(db, t)) {
817 let data = db.trait_data(t.trait_);
818
819 for (name, assoc_id) in &data.items {
820 match assoc_id {
821 AssocItemId::TypeAliasId(alias) => {
822 if let Some(result) = cb(name, &t, *alias) {
823 return Some(result);
824 }
825 }
826 AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => {}
827 }
828 }
829 }
830
831 None
832}
833
834/// Build the type of all specific fields of a struct or enum variant.
835pub(crate) fn field_types_query(
836 db: &dyn HirDatabase,
837 variant_id: VariantId,
838) -> Arc<ArenaMap<LocalFieldId, Binders<Ty>>> {
839 let var_data = variant_data(db.upcast(), variant_id);
840 let (resolver, def): (_, GenericDefId) = match variant_id {
841 VariantId::StructId(it) => (it.resolver(db.upcast()), it.into()),
842 VariantId::UnionId(it) => (it.resolver(db.upcast()), it.into()),
843 VariantId::EnumVariantId(it) => (it.parent.resolver(db.upcast()), it.parent.into()),
844 };
845 let generics = generics(db.upcast(), def);
846 let mut res = ArenaMap::default();
847 let ctx =
848 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
849 for (field_id, field_data) in var_data.fields().iter() {
850 res.insert(field_id, Binders::new(generics.len(), Ty::from_hir(&ctx, &field_data.type_ref)))
851 }
852 Arc::new(res)
853}
854
855/// This query exists only to be used when resolving short-hand associated types
856/// like `T::Item`.
857///
858/// See the analogous query in rustc and its comment:
859/// https://github.com/rust-lang/rust/blob/9150f844e2624eb013ec78ca08c1d416e6644026/src/librustc_typeck/astconv.rs#L46
860/// This is a query mostly to handle cycles somewhat gracefully; e.g. the
861/// following bounds are disallowed: `T: Foo<U::Item>, U: Foo<T::Item>`, but
862/// these are fine: `T: Foo<U::Item>, U: Foo<()>`.
863pub(crate) fn generic_predicates_for_param_query(
864 db: &dyn HirDatabase,
865 param_id: TypeParamId,
866) -> Arc<[Binders<GenericPredicate>]> {
867 let resolver = param_id.parent.resolver(db.upcast());
868 let ctx =
869 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
870 let generics = generics(db.upcast(), param_id.parent);
871 resolver
872 .where_predicates_in_scope()
873 // we have to filter out all other predicates *first*, before attempting to lower them
874 .filter(|pred| match &pred.target {
875 WherePredicateTarget::TypeRef(type_ref) => {
876 Ty::from_hir_only_param(&ctx, type_ref) == Some(param_id)
877 }
878 WherePredicateTarget::TypeParam(local_id) => *local_id == param_id.local_id,
879 })
880 .flat_map(|pred| {
881 GenericPredicate::from_where_predicate(&ctx, pred)
882 .map(|p| Binders::new(generics.len(), p))
883 })
884 .collect()
885}
886
887pub(crate) fn generic_predicates_for_param_recover(
888 _db: &dyn HirDatabase,
889 _cycle: &[String],
890 _param_id: &TypeParamId,
891) -> Arc<[Binders<GenericPredicate>]> {
892 Arc::new([])
893}
894
895impl TraitEnvironment {
896 pub fn lower(db: &dyn HirDatabase, resolver: &Resolver) -> Arc<TraitEnvironment> {
897 let ctx = TyLoweringContext::new(db, &resolver)
898 .with_type_param_mode(TypeParamLoweringMode::Placeholder);
899 let mut predicates = resolver
900 .where_predicates_in_scope()
901 .flat_map(|pred| GenericPredicate::from_where_predicate(&ctx, pred))
902 .collect::<Vec<_>>();
903
904 if let Some(def) = resolver.generic_def() {
905 let container: Option<AssocContainerId> = match def {
906 // FIXME: is there a function for this?
907 GenericDefId::FunctionId(f) => Some(f.lookup(db.upcast()).container),
908 GenericDefId::AdtId(_) => None,
909 GenericDefId::TraitId(_) => None,
910 GenericDefId::TypeAliasId(t) => Some(t.lookup(db.upcast()).container),
911 GenericDefId::ImplId(_) => None,
912 GenericDefId::EnumVariantId(_) => None,
913 GenericDefId::ConstId(c) => Some(c.lookup(db.upcast()).container),
914 };
915 if let Some(AssocContainerId::TraitId(trait_id)) = container {
916 // add `Self: Trait<T1, T2, ...>` to the environment in trait
917 // function default implementations (and hypothetical code
918 // inside consts or type aliases)
919 test_utils::mark::hit!(trait_self_implements_self);
920 let substs = Substs::type_params(db, trait_id);
921 let trait_ref = TraitRef { trait_: trait_id, substs };
922 let pred = GenericPredicate::Implemented(trait_ref);
923
924 predicates.push(pred);
925 }
926 }
927
928 Arc::new(TraitEnvironment { predicates })
929 }
930}
931
932/// Resolve the where clause(s) of an item with generics.
933pub(crate) fn generic_predicates_query(
934 db: &dyn HirDatabase,
935 def: GenericDefId,
936) -> Arc<[Binders<GenericPredicate>]> {
937 let resolver = def.resolver(db.upcast());
938 let ctx =
939 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
940 let generics = generics(db.upcast(), def);
941 resolver
942 .where_predicates_in_scope()
943 .flat_map(|pred| {
944 GenericPredicate::from_where_predicate(&ctx, pred)
945 .map(|p| Binders::new(generics.len(), p))
946 })
947 .collect()
948}
949
950/// Resolve the default type params from generics
951pub(crate) fn generic_defaults_query(
952 db: &dyn HirDatabase,
953 def: GenericDefId,
954) -> Arc<[Binders<Ty>]> {
955 let resolver = def.resolver(db.upcast());
956 let ctx =
957 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
958 let generic_params = generics(db.upcast(), def);
959
960 let defaults = generic_params
961 .iter()
962 .enumerate()
963 .map(|(idx, (_, p))| {
964 let mut ty = p.default.as_ref().map_or(Ty::Unknown, |t| Ty::from_hir(&ctx, t));
965
966 // Each default can only refer to previous parameters.
967 ty.walk_mut_binders(
968 &mut |ty, binders| match ty {
969 Ty::Bound(BoundVar { debruijn, index }) if *debruijn == binders => {
970 if *index >= idx {
971 // type variable default referring to parameter coming
972 // after it. This is forbidden (FIXME: report
973 // diagnostic)
974 *ty = Ty::Unknown;
975 }
976 }
977 _ => {}
978 },
979 DebruijnIndex::INNERMOST,
980 );
981
982 Binders::new(idx, ty)
983 })
984 .collect();
985
986 defaults
987}
988
989fn fn_sig_for_fn(db: &dyn HirDatabase, def: FunctionId) -> PolyFnSig {
990 let data = db.function_data(def);
991 let resolver = def.resolver(db.upcast());
992 let ctx_params = TyLoweringContext::new(db, &resolver)
993 .with_impl_trait_mode(ImplTraitLoweringMode::Variable)
994 .with_type_param_mode(TypeParamLoweringMode::Variable);
995 let params = data.params.iter().map(|tr| Ty::from_hir(&ctx_params, tr)).collect::<Vec<_>>();
996 let ctx_ret = TyLoweringContext::new(db, &resolver)
997 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
998 .with_type_param_mode(TypeParamLoweringMode::Variable);
999 let ret = Ty::from_hir(&ctx_ret, &data.ret_type);
1000 let generics = generics(db.upcast(), def.into());
1001 let num_binders = generics.len();
1002 Binders::new(num_binders, FnSig::from_params_and_return(params, ret, data.is_varargs))
1003}
1004
1005/// Build the declared type of a function. This should not need to look at the
1006/// function body.
1007fn type_for_fn(db: &dyn HirDatabase, def: FunctionId) -> Binders<Ty> {
1008 let generics = generics(db.upcast(), def.into());
1009 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1010 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
1011}
1012
1013/// Build the declared type of a const.
1014fn type_for_const(db: &dyn HirDatabase, def: ConstId) -> Binders<Ty> {
1015 let data = db.const_data(def);
1016 let generics = generics(db.upcast(), def.into());
1017 let resolver = def.resolver(db.upcast());
1018 let ctx =
1019 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1020
1021 Binders::new(generics.len(), Ty::from_hir(&ctx, &data.type_ref))
1022}
1023
1024/// Build the declared type of a static.
1025fn type_for_static(db: &dyn HirDatabase, def: StaticId) -> Binders<Ty> {
1026 let data = db.static_data(def);
1027 let resolver = def.resolver(db.upcast());
1028 let ctx = TyLoweringContext::new(db, &resolver);
1029
1030 Binders::new(0, Ty::from_hir(&ctx, &data.type_ref))
1031}
1032
1033/// Build the declared type of a static.
1034fn type_for_builtin(def: BuiltinType) -> Ty {
1035 Ty::simple(match def {
1036 BuiltinType::Char => TypeCtor::Char,
1037 BuiltinType::Bool => TypeCtor::Bool,
1038 BuiltinType::Str => TypeCtor::Str,
1039 BuiltinType::Int(t) => TypeCtor::Int(IntTy::from(t).into()),
1040 BuiltinType::Float(t) => TypeCtor::Float(FloatTy::from(t).into()),
1041 })
1042}
1043
1044fn fn_sig_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> PolyFnSig {
1045 let struct_data = db.struct_data(def);
1046 let fields = struct_data.variant_data.fields();
1047 let resolver = def.resolver(db.upcast());
1048 let ctx =
1049 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1050 let params =
1051 fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
1052 let ret = type_for_adt(db, def.into());
1053 Binders::new(ret.num_binders, FnSig::from_params_and_return(params, ret.value, false))
1054}
1055
1056/// Build the type of a tuple struct constructor.
1057fn type_for_struct_constructor(db: &dyn HirDatabase, def: StructId) -> Binders<Ty> {
1058 let struct_data = db.struct_data(def);
1059 if let StructKind::Unit = struct_data.variant_data.kind() {
1060 return type_for_adt(db, def.into());
1061 }
1062 let generics = generics(db.upcast(), def.into());
1063 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1064 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
1065}
1066
1067fn fn_sig_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> PolyFnSig {
1068 let enum_data = db.enum_data(def.parent);
1069 let var_data = &enum_data.variants[def.local_id];
1070 let fields = var_data.variant_data.fields();
1071 let resolver = def.parent.resolver(db.upcast());
1072 let ctx =
1073 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1074 let params =
1075 fields.iter().map(|(_, field)| Ty::from_hir(&ctx, &field.type_ref)).collect::<Vec<_>>();
1076 let ret = type_for_adt(db, def.parent.into());
1077 Binders::new(ret.num_binders, FnSig::from_params_and_return(params, ret.value, false))
1078}
1079
1080/// Build the type of a tuple enum variant constructor.
1081fn type_for_enum_variant_constructor(db: &dyn HirDatabase, def: EnumVariantId) -> Binders<Ty> {
1082 let enum_data = db.enum_data(def.parent);
1083 let var_data = &enum_data.variants[def.local_id].variant_data;
1084 if let StructKind::Unit = var_data.kind() {
1085 return type_for_adt(db, def.parent.into());
1086 }
1087 let generics = generics(db.upcast(), def.parent.into());
1088 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1089 Binders::new(substs.len(), Ty::apply(TypeCtor::FnDef(def.into()), substs))
1090}
1091
1092fn type_for_adt(db: &dyn HirDatabase, adt: AdtId) -> Binders<Ty> {
1093 let generics = generics(db.upcast(), adt.into());
1094 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1095 Binders::new(substs.len(), Ty::apply(TypeCtor::Adt(adt), substs))
1096}
1097
1098fn type_for_type_alias(db: &dyn HirDatabase, t: TypeAliasId) -> Binders<Ty> {
1099 let generics = generics(db.upcast(), t.into());
1100 let resolver = t.resolver(db.upcast());
1101 let ctx =
1102 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1103 let type_ref = &db.type_alias_data(t).type_ref;
1104 let substs = Substs::bound_vars(&generics, DebruijnIndex::INNERMOST);
1105 let inner = Ty::from_hir(&ctx, type_ref.as_ref().unwrap_or(&TypeRef::Error));
1106 Binders::new(substs.len(), inner)
1107}
1108
1109#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1110pub enum CallableDefId {
1111 FunctionId(FunctionId),
1112 StructId(StructId),
1113 EnumVariantId(EnumVariantId),
1114}
1115impl_from!(FunctionId, StructId, EnumVariantId for CallableDefId);
1116
1117impl CallableDefId {
1118 pub fn krate(self, db: &dyn HirDatabase) -> CrateId {
1119 let db = db.upcast();
1120 match self {
1121 CallableDefId::FunctionId(f) => f.lookup(db).module(db),
1122 CallableDefId::StructId(s) => s.lookup(db).container.module(db),
1123 CallableDefId::EnumVariantId(e) => e.parent.lookup(db).container.module(db),
1124 }
1125 .krate
1126 }
1127}
1128
1129impl From<CallableDefId> for GenericDefId {
1130 fn from(def: CallableDefId) -> GenericDefId {
1131 match def {
1132 CallableDefId::FunctionId(f) => f.into(),
1133 CallableDefId::StructId(s) => s.into(),
1134 CallableDefId::EnumVariantId(e) => e.into(),
1135 }
1136 }
1137}
1138
1139#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1140pub enum TyDefId {
1141 BuiltinType(BuiltinType),
1142 AdtId(AdtId),
1143 TypeAliasId(TypeAliasId),
1144}
1145impl_from!(BuiltinType, AdtId(StructId, EnumId, UnionId), TypeAliasId for TyDefId);
1146
1147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1148pub enum ValueTyDefId {
1149 FunctionId(FunctionId),
1150 StructId(StructId),
1151 EnumVariantId(EnumVariantId),
1152 ConstId(ConstId),
1153 StaticId(StaticId),
1154}
1155impl_from!(FunctionId, StructId, EnumVariantId, ConstId, StaticId for ValueTyDefId);
1156
1157/// Build the declared type of an item. This depends on the namespace; e.g. for
1158/// `struct Foo(usize)`, we have two types: The type of the struct itself, and
1159/// the constructor function `(usize) -> Foo` which lives in the values
1160/// namespace.
1161pub(crate) fn ty_query(db: &dyn HirDatabase, def: TyDefId) -> Binders<Ty> {
1162 match def {
1163 TyDefId::BuiltinType(it) => Binders::new(0, type_for_builtin(it)),
1164 TyDefId::AdtId(it) => type_for_adt(db, it),
1165 TyDefId::TypeAliasId(it) => type_for_type_alias(db, it),
1166 }
1167}
1168
1169pub(crate) fn ty_recover(db: &dyn HirDatabase, _cycle: &[String], def: &TyDefId) -> Binders<Ty> {
1170 let num_binders = match *def {
1171 TyDefId::BuiltinType(_) => 0,
1172 TyDefId::AdtId(it) => generics(db.upcast(), it.into()).len(),
1173 TyDefId::TypeAliasId(it) => generics(db.upcast(), it.into()).len(),
1174 };
1175 Binders::new(num_binders, Ty::Unknown)
1176}
1177
1178pub(crate) fn value_ty_query(db: &dyn HirDatabase, def: ValueTyDefId) -> Binders<Ty> {
1179 match def {
1180 ValueTyDefId::FunctionId(it) => type_for_fn(db, it),
1181 ValueTyDefId::StructId(it) => type_for_struct_constructor(db, it),
1182 ValueTyDefId::EnumVariantId(it) => type_for_enum_variant_constructor(db, it),
1183 ValueTyDefId::ConstId(it) => type_for_const(db, it),
1184 ValueTyDefId::StaticId(it) => type_for_static(db, it),
1185 }
1186}
1187
1188pub(crate) fn impl_self_ty_query(db: &dyn HirDatabase, impl_id: ImplId) -> Binders<Ty> {
1189 let impl_data = db.impl_data(impl_id);
1190 let resolver = impl_id.resolver(db.upcast());
1191 let generics = generics(db.upcast(), impl_id.into());
1192 let ctx =
1193 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1194 Binders::new(generics.len(), Ty::from_hir(&ctx, &impl_data.target_type))
1195}
1196
1197pub(crate) fn impl_self_ty_recover(
1198 db: &dyn HirDatabase,
1199 _cycle: &[String],
1200 impl_id: &ImplId,
1201) -> Binders<Ty> {
1202 let generics = generics(db.upcast(), (*impl_id).into());
1203 Binders::new(generics.len(), Ty::Unknown)
1204}
1205
1206pub(crate) fn impl_trait_query(db: &dyn HirDatabase, impl_id: ImplId) -> Option<Binders<TraitRef>> {
1207 let impl_data = db.impl_data(impl_id);
1208 let resolver = impl_id.resolver(db.upcast());
1209 let ctx =
1210 TyLoweringContext::new(db, &resolver).with_type_param_mode(TypeParamLoweringMode::Variable);
1211 let self_ty = db.impl_self_ty(impl_id);
1212 let target_trait = impl_data.target_trait.as_ref()?;
1213 Some(Binders::new(
1214 self_ty.num_binders,
1215 TraitRef::from_hir(&ctx, target_trait, Some(self_ty.value))?,
1216 ))
1217}
1218
1219pub(crate) fn return_type_impl_traits(
1220 db: &dyn HirDatabase,
1221 def: hir_def::FunctionId,
1222) -> Option<Arc<Binders<ReturnTypeImplTraits>>> {
1223 // FIXME unify with fn_sig_for_fn instead of doing lowering twice, maybe
1224 let data = db.function_data(def);
1225 let resolver = def.resolver(db.upcast());
1226 let ctx_ret = TyLoweringContext::new(db, &resolver)
1227 .with_impl_trait_mode(ImplTraitLoweringMode::Opaque)
1228 .with_type_param_mode(TypeParamLoweringMode::Variable);
1229 let _ret = Ty::from_hir(&ctx_ret, &data.ret_type);
1230 let generics = generics(db.upcast(), def.into());
1231 let num_binders = generics.len();
1232 let return_type_impl_traits =
1233 ReturnTypeImplTraits { impl_traits: ctx_ret.opaque_type_data.into_inner() };
1234 if return_type_impl_traits.impl_traits.is_empty() {
1235 None
1236 } else {
1237 Some(Arc::new(Binders::new(num_binders, return_type_impl_traits)))
1238 }
1239}