1mod autoderef;
19mod callee;
20pub(crate) mod cast;
21pub(crate) mod closure;
22mod coerce;
23pub(crate) mod diagnostics;
24mod expr;
25mod fallback;
26mod mutability;
27mod op;
28mod opaques;
29mod pat;
30mod path;
31mod place_op;
32pub(crate) mod unify;
33
34use std::{
35 cell::{OnceCell, RefCell},
36 cmp,
37 convert::identity,
38 fmt,
39 hash::Hash,
40 ops::Deref,
41};
42
43use base_db::{Crate, FxIndexMap};
44use either::Either;
45use hir_def::{
46 AdtId, AssocItemId, AttrDefId, DefWithBodyId, ExpressionStoreOwnerId, FieldId, FunctionId,
47 GenericDefId, GenericParamId, HasModule, LocalFieldId, Lookup, TraitId, TupleFieldId, TupleId,
48 VariantId,
49 attrs::AttrFlags,
50 expr_store::{Body, ExpressionStore, HygieneId, body::Param, path::Path},
51 hir::{BindingId, Expr, ExprId, ExprOrPatId, ExprOrPatIdPacked, LabelId, PatId, UnaryOp},
52 lang_item::LangItems,
53 layout::Integer,
54 resolver::{HasResolver, ResolveValueResult, Resolver, TypeNs, ValueNs},
55 signatures::EnumSignature,
56 type_ref::{LifetimeRefId, TypeRefId},
57 unstable_features::UnstableFeatures,
58};
59use hir_expand::{mod_path::ModPath, name::Name};
60use indexmap::IndexSet;
61use la_arena::ArenaMap;
62use macros::{TypeFoldable, TypeVisitable};
63use rustc_abi::TargetDataLayout;
64use rustc_ast_ir::Mutability;
65use rustc_hash::{FxHashMap, FxHashSet};
66use rustc_type_ir::{
67 AliasTyKind, TypeFoldable, TypeVisitableExt,
68 inherent::{GenericArgs as _, IntoKind, Ty as _},
69};
70use salsa::SalsaValue;
71use smallvec::SmallVec;
72use span::Edition;
73use stdx::never;
74use thin_vec::ThinVec;
75
76use crate::{
77 ImplTraitId, IncorrectGenericsLenKind, InferBodyId, PathLoweringDiagnostic, Span,
78 TargetFeatures, ThinFxHashMap, ThinFxHashSet, ValueTyDefId,
79 closure_analysis::PlaceBase,
80 consteval::{create_anon_const, path_to_const},
81 db::{AnonConstId, GeneralConstId, HirDatabase, InternedOpaqueTyId},
82 generics::Generics,
83 infer::{
84 callee::DeferredCallResolution,
85 closure::analysis::{
86 BorrowKind,
87 expr_use_visitor::{FakeReadCause, Place},
88 },
89 coerce::{CoerceMany, DynamicCoerceMany},
90 diagnostics::{
91 Diagnostics, InferenceTyLoweringContext as TyLoweringContext,
92 InferenceTyLoweringVarsCtx,
93 },
94 expr::ExprIsRead,
95 pat::PatOrigin,
96 unify::resolve_completely::WriteBackCtxt,
97 },
98 lower::{
99 ImplTraitIdx, LifetimeElisionKind, LifetimeLoweringMode, LoweringMode,
100 diagnostics::TyLoweringDiagnostic,
101 },
102 method_resolution::CandidateId,
103 next_solver::{
104 AliasTy, Const, ConstKind, DbInterner, GenericArgs, Region, StoredFnSig, StoredGenericArg,
105 StoredGenericArgs, StoredTerm, StoredTy, StoredTys, Term, TermRefIdPacked, Ty, TyKind, Tys,
106 abi::Safety,
107 default_types,
108 infer::{InferCtxt, ObligationInspector, traits::ObligationCause},
109 },
110 solver_errors::SolverDiagnostic,
111 utils::TargetFeatureIsSafeInTarget,
112};
113
114pub use coerce::could_coerce;
115pub use unify::{could_unify, could_unify_deeply};
116
117use cast::{CastCheck, CastError};
118
119fn infer_query<'db>(db: &'db dyn HirDatabase, def: DefWithBodyId) -> InferenceResult<'db> {
121 infer_query_with_inspect(db, def, None, LoweringMode::Analysis)
122}
123
124pub fn infer_query_with_inspect<'db>(
125 db: &'db dyn HirDatabase,
126 def: DefWithBodyId,
127 inspect: Option<ObligationInspector<'db>>,
128 lowering_mode: LoweringMode,
129) -> InferenceResult<'db> {
130 let _p = tracing::info_span!("infer_query").entered();
131 let resolver = def.resolver(db);
132 let body = Body::of(db, def);
133 let mut ctx = InferenceContext::new(
134 db,
135 InferBodyId::DefWithBodyId(def),
136 ExpressionStoreOwnerId::Body(def),
137 def.generic_def(db),
138 &body.store,
139 resolver,
140 true,
141 lowering_mode,
142 );
143
144 if let Some(inspect) = inspect {
145 ctx.table.infer_ctxt.attach_obligation_inspector(inspect);
146 }
147
148 match def {
149 DefWithBodyId::FunctionId(f) => {
150 ctx.collect_fn(f, body.self_param.map(|param| param.formal), &body.params)
151 }
152 DefWithBodyId::ConstId(c) => ctx.collect_const_or_static(c.into()),
153 DefWithBodyId::StaticId(s) => ctx.collect_const_or_static(s.into()),
154 DefWithBodyId::VariantId(v) => {
155 ctx.return_ty = match EnumSignature::variant_body_type(db, v.lookup(db).parent) {
156 hir_def::layout::IntegerType::Pointer(signed) => match signed {
157 true => ctx.types.types.isize,
158 false => ctx.types.types.usize,
159 },
160 hir_def::layout::IntegerType::Fixed(size, signed) => match signed {
161 true => match size {
162 Integer::I8 => ctx.types.types.i8,
163 Integer::I16 => ctx.types.types.i16,
164 Integer::I32 => ctx.types.types.i32,
165 Integer::I64 => ctx.types.types.i64,
166 Integer::I128 => ctx.types.types.i128,
167 },
168 false => match size {
169 Integer::I8 => ctx.types.types.u8,
170 Integer::I16 => ctx.types.types.u16,
171 Integer::I32 => ctx.types.types.u32,
172 Integer::I64 => ctx.types.types.u64,
173 Integer::I128 => ctx.types.types.u128,
174 },
175 },
176 };
177 }
178 }
179
180 ctx.infer_body(body.root_expr());
181
182 ctx.infer_mut_body(body.root_expr());
183
184 infer_finalize(ctx)
185}
186
187fn infer_cycle_result<'db>(
188 _: &'db dyn HirDatabase,
189 _: salsa::Id,
190 _: DefWithBodyId,
191) -> InferenceResult<'db> {
192 InferenceResult { has_errors: true, ..InferenceResult::new() }
193}
194
195fn infer_anon_const_query<'db>(
197 db: &'db dyn HirDatabase,
198 def: AnonConstId<'db>,
199) -> InferenceResult<'db> {
200 let _p = tracing::info_span!("infer_anon_const_query").entered();
201 let loc = def.loc(db);
202 let store_owner = loc.owner;
203 let store = ExpressionStore::of(db, store_owner);
204
205 let resolver = store_owner.resolver(db);
206
207 let mut ctx = InferenceContext::new(
208 db,
209 InferBodyId::AnonConstId(def),
210 store_owner,
211 loc.owner.generic_def(db),
212 store,
213 resolver,
214 loc.allow_using_generic_params,
215 LoweringMode::Analysis,
216 );
217
218 ctx.infer_expr(
219 loc.expr,
220 &Expectation::has_type(loc.ty.get().instantiate_identity().skip_norm_wip()),
221 ExprIsRead::Yes,
222 );
223
224 infer_finalize(ctx)
225}
226
227fn infer_anon_const_cycle_result<'db>(
228 _: &'db dyn HirDatabase,
229 _: salsa::Id,
230 _: AnonConstId<'db>,
231) -> InferenceResult<'db> {
232 InferenceResult { has_errors: true, ..InferenceResult::new() }
233}
234
235fn infer_finalize<'db>(mut ctx: InferenceContext<'db>) -> InferenceResult<'db> {
236 ctx.handle_opaque_type_uses();
237
238 ctx.type_inference_fallback();
239
240 let cast_checks = std::mem::take(&mut ctx.deferred_cast_checks);
244 for mut cast in cast_checks.into_iter() {
245 if let Err(diag) = cast.check(&mut ctx) {
246 ctx.diagnostics.push(diag);
247 }
248 }
249
250 ctx.table.select_obligations_where_possible();
251
252 ctx.closure_analyze();
255 assert!(ctx.deferred_call_resolutions.is_empty());
256
257 ctx.table.select_obligations_where_possible();
258
259 ctx.handle_opaque_type_uses();
260
261 ctx.merge_anon_consts();
262
263 ctx.resolve_all()
264}
265
266#[derive(Clone, Copy, Debug, Eq, PartialEq)]
267pub enum ByRef {
268 Yes(Mutability),
269 No,
270}
271
272#[derive(Copy, Clone, Debug, Eq, PartialEq)]
278pub struct BindingMode(pub ByRef, pub Mutability);
279
280#[derive(Debug, PartialEq, Eq, Clone, TypeVisitable, TypeFoldable)]
281pub enum InferenceDiagnostic {
282 NoSuchField {
283 #[type_visitable(ignore)]
284 field: ExprOrPatIdPacked,
285 #[type_visitable(ignore)]
286 private: Option<LocalFieldId>,
287 #[type_visitable(ignore)]
288 variant: VariantId,
289 },
290 MismatchedArrayPatLen {
291 #[type_visitable(ignore)]
292 pat: PatId,
293 #[type_visitable(ignore)]
294 expected: u64,
295 #[type_visitable(ignore)]
296 found: u64,
297 #[type_visitable(ignore)]
298 has_rest: bool,
299 },
300 ArrayPatternWithoutFixedLength {
301 #[type_visitable(ignore)]
302 pat: PatId,
303 },
304 ExpectedArrayOrSlicePat {
305 #[type_visitable(ignore)]
306 pat: PatId,
307 found: StoredTy,
308 },
309 InvalidRangePatType {
310 #[type_visitable(ignore)]
311 pat: PatId,
312 },
313 DuplicateField {
314 #[type_visitable(ignore)]
315 field: ExprOrPatIdPacked,
316 #[type_visitable(ignore)]
317 variant: VariantId,
318 },
319 PrivateField {
320 #[type_visitable(ignore)]
321 expr: ExprId,
322 #[type_visitable(ignore)]
323 field: FieldId,
324 },
325 PrivateAssocItem {
326 #[type_visitable(ignore)]
327 id: ExprOrPatIdPacked,
328 #[type_visitable(ignore)]
329 item: AssocItemId,
330 },
331 UnresolvedField {
332 #[type_visitable(ignore)]
333 expr: ExprId,
334 receiver: StoredTy,
335 #[type_visitable(ignore)]
336 name: Name,
337 #[type_visitable(ignore)]
338 method_with_same_name_exists: bool,
339 },
340 UnresolvedMethodCall {
341 #[type_visitable(ignore)]
342 expr: ExprId,
343 receiver: StoredTy,
344 #[type_visitable(ignore)]
345 name: Name,
346 field_with_same_name: Option<StoredTy>,
348 #[type_visitable(ignore)]
349 assoc_func_with_same_name: Option<FunctionId>,
350 },
351 UnresolvedAssocItem {
352 #[type_visitable(ignore)]
353 id: ExprOrPatIdPacked,
354 },
355 UnresolvedIdent {
356 #[type_visitable(ignore)]
357 id: ExprOrPatIdPacked,
358 },
359 BreakOutsideOfLoop {
361 #[type_visitable(ignore)]
362 expr: ExprId,
363 #[type_visitable(ignore)]
364 is_break: bool,
365 #[type_visitable(ignore)]
366 bad_value_break: bool,
367 },
368 NonExhaustiveRecordExpr {
369 #[type_visitable(ignore)]
370 expr: ExprId,
371 },
372 NonExhaustiveRecordPat {
373 #[type_visitable(ignore)]
374 pat: PatId,
375 #[type_visitable(ignore)]
376 variant: VariantId,
377 },
378 UnionPatMustHaveExactlyOneField {
379 #[type_visitable(ignore)]
380 pat: PatId,
381 },
382 UnionPatHasRest {
383 #[type_visitable(ignore)]
384 pat: PatId,
385 },
386 FunctionalRecordUpdateOnNonStruct {
387 #[type_visitable(ignore)]
388 base_expr: ExprId,
389 },
390 MismatchedArgCount {
391 #[type_visitable(ignore)]
392 call_expr: ExprId,
393 #[type_visitable(ignore)]
394 expected: usize,
395 #[type_visitable(ignore)]
396 found: usize,
397 #[type_visitable(ignore)]
401 is_fn_trait_call: bool,
402 },
403 MismatchedTupleStructPatArgCount {
404 #[type_visitable(ignore)]
405 pat: PatId,
406 #[type_visitable(ignore)]
407 expected: usize,
408 #[type_visitable(ignore)]
409 found: usize,
410 },
411 ExpectedFunction {
412 #[type_visitable(ignore)]
413 call_expr: ExprId,
414 found: StoredTy,
415 },
416 CannotBeDereferenced {
417 #[type_visitable(ignore)]
418 expr: ExprId,
419 found: StoredTy,
420 },
421 UnaryOperatorCannotBeApplied {
422 #[type_visitable(ignore)]
423 expr: ExprId,
424 #[type_visitable(ignore)]
425 op: UnaryOp,
426 found: StoredTy,
427 },
428 MutRefInImmRefPat {
429 #[type_visitable(ignore)]
430 pat: PatId,
431 },
432 CannotImplicitlyDerefTraitObject {
433 #[type_visitable(ignore)]
434 pat: PatId,
435 found: StoredTy,
436 },
437 CannotIndexInto {
438 #[type_visitable(ignore)]
439 expr: ExprId,
440 found: StoredTy,
441 },
442 TypedHole {
443 #[type_visitable(ignore)]
444 expr: ExprId,
445 expected: StoredTy,
446 },
447 CastToUnsized {
448 #[type_visitable(ignore)]
449 expr: ExprId,
450 cast_ty: StoredTy,
451 },
452 InvalidCast {
453 #[type_visitable(ignore)]
454 expr: ExprId,
455 #[type_visitable(ignore)]
456 error: CastError,
457 expr_ty: StoredTy,
458 cast_ty: StoredTy,
459 },
460 TyDiagnostic {
461 #[type_visitable(ignore)]
462 diag: TyLoweringDiagnostic,
463 },
464 PathDiagnostic {
465 #[type_visitable(ignore)]
466 node: ExprOrPatIdPacked,
467 #[type_visitable(ignore)]
468 diag: PathLoweringDiagnostic,
469 },
470 MethodCallIncorrectGenericsLen {
471 #[type_visitable(ignore)]
472 expr: ExprId,
473 #[type_visitable(ignore)]
474 provided_count: u32,
475 #[type_visitable(ignore)]
476 expected_count: u32,
477 #[type_visitable(ignore)]
478 kind: IncorrectGenericsLenKind,
479 #[type_visitable(ignore)]
480 def: GenericDefId,
481 },
482 MethodCallIllegalSizedBound {
483 #[type_visitable(ignore)]
484 call_expr: ExprId,
485 },
486 MethodCallIncorrectGenericsOrder {
487 #[type_visitable(ignore)]
488 expr: ExprId,
489 #[type_visitable(ignore)]
490 param_id: GenericParamId,
491 #[type_visitable(ignore)]
492 arg_idx: u32,
493 #[type_visitable(ignore)]
495 has_self_arg: bool,
496 },
497 InvalidLhsOfAssignment {
498 #[type_visitable(ignore)]
499 lhs: ExprId,
500 },
501 TypeMustBeKnown {
502 #[type_visitable(ignore)]
503 at_point: Span,
504 top_term: Option<StoredGenericArg>,
505 },
506 UnionExprMustHaveExactlyOneField {
507 #[type_visitable(ignore)]
508 expr: ExprId,
509 },
510 TypeMismatch {
511 #[type_visitable(ignore)]
512 node: ExprOrPatIdPacked,
513 expected: StoredTy,
514 found: StoredTy,
515 },
516 SolverDiagnostic(SolverDiagnostic),
517 ExplicitDropMethodUse {
518 #[type_visitable(ignore)]
519 kind: ExplicitDropMethodUseKind,
520 },
521 MutableRefBinding {
522 #[type_visitable(ignore)]
523 pat: PatId,
524 },
525 YieldOutsideCoroutine {
526 #[type_visitable(ignore)]
527 expr: ExprId,
528 },
529 ReturnOutsideFunction {
530 #[type_visitable(ignore)]
531 expr: ExprId,
532 #[type_visitable(ignore)]
533 kind: ReturnKind,
534 },
535 RecordMissingFields {
536 #[type_visitable(ignore)]
537 record: ExprOrPatId,
538 #[type_visitable(ignore)]
539 variant: VariantId,
540 #[type_visitable(ignore)]
541 missed_fields: Vec<LocalFieldId>,
542 },
543 InvalidPatPathRes {
544 #[type_visitable(ignore)]
545 pat: PatId,
546 #[type_visitable(ignore)]
547 res: ValueNs,
548 },
549 MatchInheritedImmRefWithMutRefPat {
550 #[type_visitable(ignore)]
551 pat: PatId,
552 },
553}
554
555#[derive(Debug, PartialEq, Eq, Clone, Copy)]
556pub enum ReturnKind {
557 ReturnExpr,
558 BecomeExpr,
559}
560
561#[derive(Debug, PartialEq, Eq, Clone)]
562pub enum ExplicitDropMethodUseKind {
563 MethodCall(ExprId),
564 Path(ExprOrPatIdPacked),
565}
566
567#[derive(Clone, Debug, PartialEq, Eq, Hash)]
608pub struct Adjustment {
609 pub kind: Adjust,
610 pub target: StoredTy,
611}
612
613impl Adjustment {
614 pub fn borrow<'db>(
615 interner: DbInterner<'db>,
616 m: Mutability,
617 ty: Ty<'db>,
618 lt: Region<'db>,
619 ) -> Self {
620 let ty = Ty::new_ref(interner, lt, ty, m);
621 Adjustment {
622 kind: Adjust::Borrow(AutoBorrow::Ref(AutoBorrowMutability::new(m, AllowTwoPhase::No))),
623 target: ty.store(),
624 }
625 }
626}
627
628#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
642pub enum AllowTwoPhase {
643 Yes,
645 No,
646}
647
648#[derive(Clone, Debug, PartialEq, Eq, Hash)]
649pub enum Adjust {
650 NeverToAny,
652 Deref(Option<OverloadedDeref>),
654 Borrow(AutoBorrow),
656 Pointer(PointerCast),
657}
658
659#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
664pub struct OverloadedDeref(pub Mutability);
665
666#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
667pub enum AutoBorrowMutability {
668 Mut { allow_two_phase_borrow: AllowTwoPhase },
669 Not,
670}
671
672impl AutoBorrowMutability {
673 pub fn new(mutbl: Mutability, allow_two_phase_borrow: AllowTwoPhase) -> Self {
677 match mutbl {
678 Mutability::Not => Self::Not,
679 Mutability::Mut => Self::Mut { allow_two_phase_borrow },
680 }
681 }
682}
683
684impl From<AutoBorrowMutability> for Mutability {
685 fn from(m: AutoBorrowMutability) -> Self {
686 match m {
687 AutoBorrowMutability::Mut { .. } => Mutability::Mut,
688 AutoBorrowMutability::Not => Mutability::Not,
689 }
690 }
691}
692
693#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
694pub enum AutoBorrow {
695 Ref(AutoBorrowMutability),
697 RawPtr(Mutability),
699}
700
701#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
702pub enum PointerCast {
703 ReifyFnPointer,
705
706 UnsafeFnPointer,
708
709 ClosureFnPointer(Safety),
712
713 MutToConstPointer,
715
716 #[allow(dead_code)]
717 ArrayToPointer,
719
720 Unsize,
731}
732
733#[derive(Debug, Clone, PartialEq, Eq)]
736pub struct PatAdjustment {
737 pub kind: PatAdjust,
738 pub source: StoredTy,
741}
742
743#[derive(Clone, Copy, PartialEq, Eq, Debug)]
745pub enum PatAdjust {
746 BuiltinDeref,
749 OverloadedDeref,
752}
753
754#[derive(Clone, PartialEq, Eq, Debug, SalsaValue)]
760pub struct InferenceResult<'db> {
761 method_resolutions: ThinFxHashMap<ExprId, (FunctionId, StoredGenericArgs)>,
763 field_resolutions: ThinFxHashMap<ExprId, Either<FieldId, TupleFieldId>>,
765 variant_resolutions: ThinFxHashMap<ExprOrPatIdPacked, VariantId>,
767 assoc_resolutions: ThinFxHashMap<ExprOrPatIdPacked, (CandidateId, StoredGenericArgs)>,
769 tuple_field_access_types: ThinVec<StoredTys>,
773
774 pub type_of_expr: ArenaMap<ExprId, StoredTy>,
775 pub type_of_pat: ArenaMap<PatId, StoredTy>,
780 pub type_of_binding: ArenaMap<BindingId, StoredTy>,
781 pub term_of_term_placeholders: ThinFxHashMap<TermRefIdPacked, StoredTerm>,
782 pub type_of_opaque: ThinFxHashMap<InternedOpaqueTyId<'db>, StoredTy>,
783
784 pub has_errors: bool,
789 diagnostics: ThinVec<InferenceDiagnostic>,
791 nodes_with_type_mismatches: ThinFxHashSet<ExprOrPatIdPacked>,
793
794 pub expr_adjustments: FxHashMap<ExprId, Box<[Adjustment]>>,
795 pub pat_adjustments: ThinFxHashMap<PatId, Vec<PatAdjustment>>,
797 pub binding_modes: ArenaMap<PatId, BindingMode>,
811
812 skipped_ref_pats: ThinFxHashSet<PatId>,
815
816 pub coercion_casts: ThinFxHashSet<ExprId>,
817
818 pub closures_data: ThinFxHashMap<ExprId, ClosureData>,
819
820 defined_anon_consts: ThinVec<AnonConstId<'db>>,
821}
822
823#[derive(Clone, PartialEq, Eq, Debug)]
824pub struct ClosureData {
825 pub min_captures: RootVariableMinCaptureList,
828
829 pub fake_reads: Box<[(Place, FakeReadCause, SmallVec<[CaptureSourceStack; 2]>)]>,
852
853 pub liberated_sig: StoredFnSig,
888}
889
890pub(crate) type RootVariableMinCaptureList = FxIndexMap<BindingId, MinCaptureList>;
897
898pub(crate) type MinCaptureList = Vec<CapturedPlace>;
900
901#[derive(Eq, PartialEq, Clone, Debug, Hash)]
903pub struct CapturedPlace {
904 pub place: Place,
906
907 pub info: CaptureInfo,
909
910 pub mutability: Mutability,
912}
913
914impl CapturedPlace {
915 pub fn is_by_ref(&self) -> bool {
916 match self.info.capture_kind {
917 UpvarCapture::ByValue | UpvarCapture::ByUse => false,
918 UpvarCapture::ByRef(..) => true,
919 }
920 }
921
922 pub fn captured_local(&self) -> BindingId {
923 match self.place.base {
924 PlaceBase::Upvar { var_id: local, .. } | PlaceBase::Local(local) => local,
925 PlaceBase::Rvalue | PlaceBase::StaticItem => {
926 unreachable!("only locals can be captured")
927 }
928 }
929 }
930
931 pub fn captured_ty<'db>(&self, db: &'db dyn HirDatabase) -> Ty<'db> {
934 let place_ty = self.place.ty();
935 let make_ref = |mutbl| {
936 let interner = DbInterner::new_no_crate(db);
937 let region = Region::new_erased(interner);
938 Ty::new_ref(interner, region, place_ty, mutbl)
939 };
940 match self.info.capture_kind {
941 UpvarCapture::ByUse | UpvarCapture::ByValue => place_ty,
942 UpvarCapture::ByRef(kind) => make_ref(kind.to_mutbl_lossy()),
943 }
944 }
945}
946
947#[derive(Clone)]
948pub struct CaptureSourceStack(CaptureSourceStackRepr);
949
950#[derive(Clone)]
951enum CaptureSourceStackRepr {
952 One(ExprOrPatIdPacked),
953 Two([ExprOrPatIdPacked; 2]),
954 Many(ThinVec<ExprOrPatIdPacked>),
955}
956
957impl PartialEq for CaptureSourceStack {
958 fn eq(&self, other: &Self) -> bool {
959 **self == **other
960 }
961}
962
963impl Eq for CaptureSourceStack {}
964
965impl std::hash::Hash for CaptureSourceStack {
966 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
967 (**self).hash(state);
968 }
969}
970
971#[cfg(target_pointer_width = "64")]
972const _: () = assert!(size_of::<CaptureSourceStack>() == 16);
973
974impl Deref for CaptureSourceStack {
975 type Target = [ExprOrPatIdPacked];
976
977 #[inline]
978 fn deref(&self) -> &Self::Target {
979 match &self.0 {
980 CaptureSourceStackRepr::One(it) => std::slice::from_ref(it),
981 CaptureSourceStackRepr::Two(it) => it,
982 CaptureSourceStackRepr::Many(it) => it,
983 }
984 }
985}
986
987impl fmt::Debug for CaptureSourceStack {
988 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
989 f.debug_tuple("CaptureSourceStack").field(&&**self).finish()
990 }
991}
992
993impl CaptureSourceStack {
994 #[inline]
995 pub fn len(&self) -> usize {
996 match &self.0 {
997 CaptureSourceStackRepr::One(_) => 1,
998 CaptureSourceStackRepr::Two(_) => 2,
999 CaptureSourceStackRepr::Many(it) => it.len(),
1000 }
1001 }
1002
1003 #[inline]
1004 pub(crate) fn from_single(id: ExprOrPatIdPacked) -> Self {
1005 Self(CaptureSourceStackRepr::One(id))
1006 }
1007
1008 #[inline]
1009 pub fn final_source(&self) -> ExprOrPatIdPacked {
1010 *self.last().expect("should always have a final source")
1011 }
1012
1013 pub fn push(&mut self, new_id: ExprOrPatIdPacked) {
1014 match &mut self.0 {
1015 CaptureSourceStackRepr::One(old_id) => {
1016 self.0 = CaptureSourceStackRepr::Two([*old_id, new_id])
1017 }
1018 CaptureSourceStackRepr::Two([old_id1, old_id2]) => {
1019 self.0 = CaptureSourceStackRepr::Many(ThinVec::from([*old_id1, *old_id2, new_id]));
1020 }
1021 CaptureSourceStackRepr::Many(old_ids) => old_ids.push(new_id),
1022 }
1023 }
1024
1025 pub fn truncate(&mut self, new_len: usize) {
1026 debug_assert!(new_len > 0);
1027 match &mut self.0 {
1028 CaptureSourceStackRepr::One(_) => {}
1029 CaptureSourceStackRepr::Two([first, _]) => {
1030 if new_len == 1 {
1031 self.0 = CaptureSourceStackRepr::One(*first)
1032 }
1033 }
1034 CaptureSourceStackRepr::Many(ids) => ids.truncate(new_len),
1035 }
1036 }
1037
1038 pub fn shrink_to_fit(&mut self) {
1039 match &mut self.0 {
1040 CaptureSourceStackRepr::One(_) | CaptureSourceStackRepr::Two(_) => {}
1041 CaptureSourceStackRepr::Many(ids) => match **ids {
1042 [one] => self.0 = CaptureSourceStackRepr::One(one),
1043 [first, second] => self.0 = CaptureSourceStackRepr::Two([first, second]),
1044 _ => ids.shrink_to_fit(),
1045 },
1046 }
1047 }
1048}
1049
1050#[derive(Eq, PartialEq, Clone, Debug, Hash)]
1054pub struct CaptureInfo {
1055 pub sources: SmallVec<[CaptureSourceStack; 2]>,
1056
1057 pub capture_kind: UpvarCapture,
1059}
1060
1061#[derive(Eq, PartialEq, Clone, Debug, Copy, Hash)]
1064pub enum UpvarCapture {
1065 ByRef(BorrowKind),
1067
1068 ByUse,
1070
1071 ByValue,
1075}
1076
1077impl PartialOrd for UpvarCapture {
1079 #[inline]
1080 fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
1081 match (self, other) {
1082 (Self::ByValue, Self::ByValue) | (Self::ByUse, Self::ByUse) => {
1083 Some(cmp::Ordering::Equal)
1084 }
1085 (Self::ByValue | Self::ByUse, Self::ByRef(_)) => Some(cmp::Ordering::Greater),
1086 (Self::ByRef(_), Self::ByValue | Self::ByUse) => Some(cmp::Ordering::Less),
1087 (Self::ByRef(left), Self::ByRef(right)) => Some(left.cmp(right)),
1088 (Self::ByUse, Self::ByValue) | (Self::ByValue, Self::ByUse) => None,
1089 }
1090 }
1091}
1092
1093#[salsa::tracked]
1094impl<'db> InferenceResult<'db> {
1095 #[salsa::tracked(returns(ref), cycle_result = infer_cycle_result)]
1096 fn for_body(db: &dyn HirDatabase, def: DefWithBodyId) -> InferenceResult<'_> {
1097 infer_query(db, def)
1098 }
1099
1100 #[salsa::tracked(returns(ref), cycle_result = infer_anon_const_cycle_result)]
1106 fn for_anon_const(db: &'db dyn HirDatabase, def: AnonConstId<'db>) -> InferenceResult<'db> {
1107 infer_anon_const_query(db, def)
1108 }
1109}
1110
1111impl<'db> InferenceResult<'db> {
1112 #[inline]
1113 pub fn of(
1114 db: &'db dyn HirDatabase,
1115 def: impl Into<InferBodyId<'db>>,
1116 ) -> &'db InferenceResult<'db> {
1117 match def.into() {
1118 InferBodyId::DefWithBodyId(it) => InferenceResult::for_body(db, it),
1119 InferBodyId::AnonConstId(it) => InferenceResult::for_anon_const(db, it),
1120 }
1121 }
1122}
1123
1124impl<'db> InferenceResult<'db> {
1125 fn new() -> Self {
1126 Self {
1127 method_resolutions: Default::default(),
1128 field_resolutions: Default::default(),
1129 variant_resolutions: Default::default(),
1130 assoc_resolutions: Default::default(),
1131 tuple_field_access_types: Default::default(),
1132 diagnostics: Default::default(),
1133 nodes_with_type_mismatches: Default::default(),
1134 type_of_expr: Default::default(),
1135 type_of_pat: Default::default(),
1136 type_of_binding: Default::default(),
1137 term_of_term_placeholders: Default::default(),
1138 type_of_opaque: Default::default(),
1139 skipped_ref_pats: Default::default(),
1140 has_errors: Default::default(),
1141 pat_adjustments: Default::default(),
1142 binding_modes: Default::default(),
1143 expr_adjustments: Default::default(),
1144 coercion_casts: Default::default(),
1145 closures_data: Default::default(),
1146 defined_anon_consts: Default::default(),
1147 }
1148 }
1149
1150 pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, GenericArgs<'db>)> {
1151 self.method_resolutions.get(&expr).map(|(func, args)| (*func, args.as_ref()))
1152 }
1153 pub fn field_resolution(&self, expr: ExprId) -> Option<Either<FieldId, TupleFieldId>> {
1154 self.field_resolutions.get(&expr).copied()
1155 }
1156 pub fn variant_resolution_for_expr(&self, id: ExprId) -> Option<VariantId> {
1157 self.variant_resolutions.get(&id.into()).copied()
1158 }
1159 pub fn variant_resolution_for_pat(&self, id: PatId) -> Option<VariantId> {
1160 self.variant_resolutions.get(&id.into()).copied()
1161 }
1162 pub fn variant_resolution_for_expr_or_pat(&self, id: ExprOrPatId) -> Option<VariantId> {
1163 match id {
1164 ExprOrPatId::ExprId(id) => self.variant_resolution_for_expr(id),
1165 ExprOrPatId::PatId(id) => self.variant_resolution_for_pat(id),
1166 }
1167 }
1168 pub fn assoc_resolutions_for_expr<'a>(
1169 &self,
1170 id: ExprId,
1171 ) -> Option<(CandidateId, GenericArgs<'a>)> {
1172 self.assoc_resolutions.get(&id.into()).map(|(assoc, args)| (*assoc, args.as_ref()))
1173 }
1174 pub fn assoc_resolutions_for_pat<'a>(
1175 &self,
1176 id: PatId,
1177 ) -> Option<(CandidateId, GenericArgs<'a>)> {
1178 self.assoc_resolutions.get(&id.into()).map(|(assoc, args)| (*assoc, args.as_ref()))
1179 }
1180 pub fn assoc_resolutions_for_expr_or_pat<'a>(
1181 &self,
1182 id: ExprOrPatId,
1183 ) -> Option<(CandidateId, GenericArgs<'a>)> {
1184 match id {
1185 ExprOrPatId::ExprId(id) => self.assoc_resolutions_for_expr(id),
1186 ExprOrPatId::PatId(id) => self.assoc_resolutions_for_pat(id),
1187 }
1188 }
1189 pub fn expr_or_pat_has_type_mismatch(&self, node: ExprOrPatIdPacked) -> bool {
1190 self.nodes_with_type_mismatches.contains(&node)
1191 }
1192 pub fn expr_has_type_mismatch(&self, expr: ExprId) -> bool {
1193 self.expr_or_pat_has_type_mismatch(expr.into())
1194 }
1195 pub fn pat_has_type_mismatch(&self, pat: PatId) -> bool {
1196 self.expr_or_pat_has_type_mismatch(pat.into())
1197 }
1198 pub fn exprs_have_type_mismatches(&self) -> bool {
1199 self.nodes_with_type_mismatches.iter().any(|node| node.is_expr())
1200 }
1201 pub fn has_type_mismatches(&self) -> bool {
1202 !self.nodes_with_type_mismatches.is_empty()
1203 }
1204 pub fn term_of_term_placeholders<'a>(
1205 &self,
1206 ) -> impl Iterator<Item = (TermRefIdPacked, Term<'a>)> {
1207 self.term_of_term_placeholders.iter().map(|(&term_ref, term)| (term_ref, term.as_ref()))
1208 }
1209 pub fn term_of_term_placeholder<'a>(&self, term_ref: TermRefIdPacked) -> Option<Term<'a>> {
1210 self.term_of_term_placeholders.get(&term_ref).map(|term| term.as_ref())
1211 }
1212 pub fn type_of_expr_or_pat<'a>(&self, id: ExprOrPatId) -> Option<Ty<'a>> {
1213 match id {
1214 ExprOrPatId::ExprId(id) => self.type_of_expr.get(id).map(|it| it.as_ref()),
1215 ExprOrPatId::PatId(id) => self.type_of_pat.get(id).map(|it| it.as_ref()),
1216 }
1217 }
1218 pub fn type_of_expr_with_adjust<'a>(&self, id: ExprId) -> Option<Ty<'a>> {
1219 match self.expr_adjustments.get(&id).and_then(|adjustments| {
1220 adjustments.iter().rfind(|adj| {
1221 !matches!(
1223 adj,
1224 Adjustment {
1225 kind: Adjust::NeverToAny,
1226 target,
1227 } if target.as_ref().is_never()
1228 )
1229 })
1230 }) {
1231 Some(adjustment) => Some(adjustment.target.as_ref()),
1232 None => self.type_of_expr.get(id).map(|it| it.as_ref()),
1233 }
1234 }
1235 pub fn type_of_pat_with_adjust<'a>(&self, id: PatId) -> Ty<'a> {
1236 match self.pat_adjustments.get(&id).and_then(|adjustments| adjustments.last()) {
1237 Some(adjusted) => adjusted.source.as_ref(),
1238 None => self.pat_ty(id),
1239 }
1240 }
1241 pub fn is_erroneous(&self) -> bool {
1242 self.has_errors && self.type_of_expr.iter().count() == 0
1243 }
1244
1245 pub fn diagnostics(&self) -> &[InferenceDiagnostic] {
1246 &self.diagnostics
1247 }
1248
1249 pub fn tuple_field_access_type<'a>(&self, id: TupleId) -> Tys<'a> {
1250 self.tuple_field_access_types[id.0 as usize].as_ref()
1251 }
1252
1253 pub fn pat_adjustment(&self, id: PatId) -> Option<&[PatAdjustment]> {
1254 self.pat_adjustments.get(&id).map(|it| &**it)
1255 }
1256
1257 pub fn expr_adjustment(&self, id: ExprId) -> Option<&[Adjustment]> {
1258 self.expr_adjustments.get(&id).map(|it| &**it)
1259 }
1260
1261 pub fn binding_mode(&self, id: PatId) -> Option<BindingMode> {
1262 self.binding_modes.get(id).copied()
1263 }
1264
1265 pub fn expression_types<'a>(&self) -> impl Iterator<Item = (ExprId, Ty<'a>)> {
1267 self.type_of_expr.iter().map(|(k, v)| (k, v.as_ref()))
1268 }
1269
1270 pub fn pattern_types<'a>(&self) -> impl Iterator<Item = (PatId, Ty<'a>)> {
1272 self.type_of_pat.iter().map(|(k, v)| (k, v.as_ref()))
1273 }
1274
1275 pub fn binding_types<'a>(&self) -> impl Iterator<Item = (BindingId, Ty<'a>)> {
1277 self.type_of_binding.iter().map(|(k, v)| (k, v.as_ref()))
1278 }
1279
1280 pub fn return_position_impl_trait_types<'a>(
1282 &'a self,
1283 db: &'a dyn HirDatabase,
1284 ) -> impl Iterator<Item = (ImplTraitIdx, Ty<'a>)> {
1285 self.type_of_opaque.iter().filter_map(move |(&id, ty)| {
1286 let ImplTraitId::ReturnTypeImplTrait(_, rpit_idx) = id.loc(db) else {
1287 return None;
1288 };
1289 Some((rpit_idx, ty.as_ref()))
1290 })
1291 }
1292
1293 pub fn expr_ty<'a>(&self, id: ExprId) -> Ty<'a> {
1294 self.type_of_expr.get(id).map_or(default_types().types.error, |it| it.as_ref())
1295 }
1296
1297 pub fn pat_ty<'a>(&self, id: PatId) -> Ty<'a> {
1298 self.type_of_pat.get(id).map_or(default_types().types.error, |it| it.as_ref())
1299 }
1300
1301 pub fn expr_or_pat_ty<'a>(&self, id: ExprOrPatId) -> Ty<'a> {
1302 self.type_of_expr_or_pat(id).unwrap_or(default_types().types.error)
1303 }
1304
1305 pub fn binding_ty<'a>(&self, id: BindingId) -> Ty<'a> {
1306 self.type_of_binding.get(id).map_or(default_types().types.error, |it| it.as_ref())
1307 }
1308
1309 pub fn closure_captures_tys<'a>(&self, closure: ExprId) -> impl Iterator<Item = Ty<'a>> {
1311 self.closures_data[&closure]
1312 .min_captures
1313 .values()
1314 .flat_map(|captures| captures.iter().map(|capture| capture.place.ty()))
1315 }
1316
1317 pub fn closure_captures_captured_tys<'a>(
1319 &self,
1320 db: &'a dyn HirDatabase,
1321 closure: ExprId,
1322 ) -> impl Iterator<Item = Ty<'a>> {
1323 self.closures_data[&closure]
1324 .min_captures
1325 .values()
1326 .flat_map(|captures| captures.iter().map(|capture| capture.captured_ty(db)))
1327 }
1328
1329 pub fn is_skipped_ref_pat(&self, pat: PatId) -> bool {
1330 self.skipped_ref_pats.contains(&pat)
1331 }
1332}
1333
1334#[derive(Debug, Clone, Copy)]
1335enum DerefPatBorrowMode {
1336 Borrow(Mutability),
1337 Box,
1338}
1339
1340#[derive(Debug)]
1342pub(crate) struct InferenceContext<'db> {
1343 pub(crate) db: &'db dyn HirDatabase,
1344 pub(crate) owner: InferBodyId<'db>,
1345 pub(crate) store_owner: ExpressionStoreOwnerId,
1346 pub(crate) generic_def: GenericDefId,
1347 pub(crate) store: &'db ExpressionStore,
1348 pub(crate) lowering_mode: LoweringMode,
1349 pub(crate) resolver: Resolver<'db>,
1352 target_features: OnceCell<(TargetFeatures<'db>, TargetFeatureIsSafeInTarget)>,
1353 data_layout: OnceCell<&'db TargetDataLayout>,
1354 pub(crate) edition: Edition,
1355 allow_using_generic_params: bool,
1356 generics: OnceCell<Generics<'db>>,
1357 identity_args: OnceCell<GenericArgs<'db>>,
1358 pub(crate) table: unify::InferenceTable<'db>,
1359 pub(crate) lang_items: &'db LangItems,
1360 pub(crate) features: &'db UnstableFeatures,
1361 traits_in_scope: FxHashSet<TraitId>,
1363 pub(crate) result: InferenceResult<'db>,
1364 tuple_field_accesses_rev:
1365 IndexSet<Tys<'db>, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>,
1366 return_ty: Ty<'db>,
1372 return_coercion: Option<DynamicCoerceMany<'db>>,
1376 resume_yield_tys: Option<(Ty<'db>, Ty<'db>)>,
1378 diverges: Diverges,
1379 breakables: Vec<BreakableContext<'db>>,
1380 types: &'db crate::next_solver::DefaultAny<'db>,
1381
1382 deferred_cast_checks: Vec<CastCheck<'db>>,
1383
1384 deferred_call_resolutions: FxHashMap<ExprId, Vec<DeferredCallResolution<'db>>>,
1386
1387 diagnostics: Diagnostics,
1388 vars_emitted_type_must_be_known_for: FxHashSet<Term<'db>>,
1389
1390 defined_anon_consts: RefCell<ThinVec<AnonConstId<'db>>>,
1391}
1392
1393#[derive(Clone, Debug)]
1394struct BreakableContext<'db> {
1395 may_break: bool,
1397 coerce: Option<DynamicCoerceMany<'db>>,
1399 label: Option<LabelId>,
1401 kind: BreakableKind,
1402}
1403
1404#[derive(Clone, Debug)]
1405enum BreakableKind {
1406 Block,
1407 Loop,
1408 Border,
1411}
1412
1413fn find_breakable(ctxs: &[BreakableContext<'_>], label: Option<LabelId>) -> Option<usize> {
1414 let mut ctxs = ctxs
1415 .iter()
1416 .enumerate()
1417 .rev()
1418 .take_while(|(_, it)| matches!(it.kind, BreakableKind::Block | BreakableKind::Loop));
1419 let result = match label {
1420 Some(_) => ctxs.find(|(_, ctx)| ctx.label == label),
1421 None => ctxs.find(|(_, ctx)| matches!(ctx.kind, BreakableKind::Loop)),
1422 };
1423 result.map(|(idx, _)| idx)
1424}
1425
1426fn find_continuable(ctxs: &[BreakableContext<'_>], label: Option<LabelId>) -> Option<usize> {
1427 find_breakable(ctxs, label)
1428 .filter(|&idx| label.is_none() || matches!(ctxs[idx].kind, BreakableKind::Loop))
1429}
1430
1431impl<'db> InferenceContext<'db> {
1432 fn new(
1433 db: &'db dyn HirDatabase,
1434 owner: InferBodyId<'db>,
1435 store_owner: ExpressionStoreOwnerId,
1436 generic_def: GenericDefId,
1437 store: &'db ExpressionStore,
1438 resolver: Resolver<'db>,
1439 allow_using_generic_params: bool,
1440 lowering_mode: LoweringMode,
1441 ) -> Self {
1442 let trait_env = db.trait_environment(generic_def);
1443 let table = unify::InferenceTable::new(db, trait_env, resolver.krate(), owner);
1444 let types = crate::next_solver::default_types();
1445 InferenceContext {
1446 result: InferenceResult::new(),
1447 return_ty: types.types.error, types,
1449 target_features: OnceCell::new(),
1450 data_layout: OnceCell::new(),
1451 lang_items: table.interner().lang_items(),
1452 features: resolver.top_level_def_map().features(),
1453 edition: resolver.krate().data(db).edition,
1454 table,
1455 tuple_field_accesses_rev: Default::default(),
1456 resume_yield_tys: None,
1457 return_coercion: None,
1458 db,
1459 owner,
1460 store_owner,
1461 generic_def,
1462 allow_using_generic_params,
1463 generics: OnceCell::new(),
1464 identity_args: OnceCell::new(),
1465 store,
1466 traits_in_scope: resolver.traits_in_scope(db),
1467 resolver,
1468 diverges: Diverges::Maybe,
1469 breakables: Vec::new(),
1470 deferred_cast_checks: Vec::new(),
1471 diagnostics: Diagnostics::default(),
1472 vars_emitted_type_must_be_known_for: FxHashSet::default(),
1473 deferred_call_resolutions: FxHashMap::default(),
1474 defined_anon_consts: RefCell::new(ThinVec::new()),
1475 lowering_mode,
1476 }
1477 }
1478
1479 fn merge(&mut self, other: &InferenceResult<'db>) {
1480 let InferenceResult {
1481 method_resolutions,
1482 field_resolutions,
1483 variant_resolutions,
1484 assoc_resolutions,
1485 tuple_field_access_types: _,
1486 type_of_expr,
1487 type_of_pat,
1488 type_of_binding,
1489 term_of_term_placeholders: placeholders,
1490 type_of_opaque,
1491 has_errors: _,
1492 diagnostics: _,
1493 expr_adjustments,
1494 pat_adjustments,
1495 binding_modes,
1496 skipped_ref_pats,
1497 coercion_casts,
1498 closures_data,
1499 nodes_with_type_mismatches,
1500 defined_anon_consts: _,
1501 } = &mut self.result;
1502 merge_thin_hash_maps(method_resolutions, &other.method_resolutions);
1503 merge_thin_hash_maps(variant_resolutions, &other.variant_resolutions);
1504 merge_thin_hash_maps(assoc_resolutions, &other.assoc_resolutions);
1505 field_resolutions.extend(other.field_resolutions.iter().map(
1506 |(&field_expr, &field_resolution)| {
1507 let mut field_resolution = field_resolution;
1508 if let Either::Right(tuple_field) = &mut field_resolution {
1509 let tys = other.tuple_field_access_type(tuple_field.tuple);
1510 tuple_field.tuple =
1511 TupleId(self.tuple_field_accesses_rev.insert_full(tys).0 as u32);
1512 };
1513 (field_expr, field_resolution)
1514 },
1515 ));
1516 merge_arena_maps(type_of_expr, &other.type_of_expr);
1517 merge_arena_maps(type_of_pat, &other.type_of_pat);
1518 merge_arena_maps(type_of_binding, &other.type_of_binding);
1519 merge_thin_hash_maps(placeholders, &other.term_of_term_placeholders);
1520 merge_thin_hash_maps(type_of_opaque, &other.type_of_opaque);
1521 merge_hash_maps(expr_adjustments, &other.expr_adjustments);
1522 merge_thin_hash_maps(pat_adjustments, &other.pat_adjustments);
1523 merge_arena_maps(binding_modes, &other.binding_modes);
1524 merge_thin_hash_set(skipped_ref_pats, &other.skipped_ref_pats);
1525 merge_thin_hash_set(coercion_casts, &other.coercion_casts);
1526 merge_thin_hash_maps(closures_data, &other.closures_data);
1527 merge_thin_hash_set(nodes_with_type_mismatches, &other.nodes_with_type_mismatches);
1528 self.defined_anon_consts.borrow_mut().extend(other.defined_anon_consts.iter().copied());
1529 self.diagnostics.extend(&other.diagnostics);
1530
1531 fn merge_thin_hash_set<T: Hash + Eq + Clone>(
1532 dest: &mut ThinFxHashSet<T>,
1533 source: &ThinFxHashSet<T>,
1534 ) {
1535 dest.extend(source.iter().cloned());
1536 }
1537
1538 #[cfg_attr(debug_assertions, track_caller)]
1539 fn merge_hash_maps<K: Hash + Eq + Clone, V: Clone + PartialEq>(
1540 dest: &mut FxHashMap<K, V>,
1541 source: &FxHashMap<K, V>,
1542 ) {
1543 if cfg!(debug_assertions) {
1544 for (key, src) in source {
1545 assert!(dest.get(key).is_none_or(|dst| dst == src));
1546 }
1547 }
1548
1549 dest.extend(source.iter().map(|(k, v)| (k.clone(), v.clone())));
1550 }
1551
1552 #[cfg_attr(debug_assertions, track_caller)]
1553 fn merge_thin_hash_maps<K: Hash + Eq + Clone, V: Clone + PartialEq>(
1554 dest: &mut ThinFxHashMap<K, V>,
1555 source: &ThinFxHashMap<K, V>,
1556 ) {
1557 if cfg!(debug_assertions) {
1558 for (key, src) in source {
1559 assert!(dest.get(key).is_none_or(|dst| dst == src));
1560 }
1561 }
1562
1563 dest.extend(source.iter().map(|(k, v)| (k.clone(), v.clone())));
1564 }
1565
1566 #[cfg_attr(debug_assertions, track_caller)]
1567 fn merge_arena_maps<K, V: Clone + PartialEq>(
1568 dest: &mut ArenaMap<la_arena::Idx<K>, V>,
1569 source: &ArenaMap<la_arena::Idx<K>, V>,
1570 ) {
1571 if cfg!(debug_assertions) {
1572 for (key, src) in source.iter() {
1573 assert!(dest.get(key).is_none_or(|dst| dst == src));
1574 }
1575 }
1576
1577 dest.extend(source.iter().map(|(k, v)| (k, v.clone())));
1578 }
1579 }
1580
1581 #[inline]
1582 fn krate(&self) -> Crate {
1583 self.resolver.krate()
1584 }
1585
1586 fn target_features(&self) -> (&TargetFeatures<'db>, TargetFeatureIsSafeInTarget) {
1587 let (target_features, target_feature_is_safe) = self.target_features.get_or_init(|| {
1588 let target_features = match self.store_owner {
1589 ExpressionStoreOwnerId::Body(DefWithBodyId::FunctionId(id)) => {
1590 TargetFeatures::from_fn(self.db, id)
1591 }
1592 _ => TargetFeatures::default(),
1593 };
1594 let target_feature_is_safe = match &self.krate().workspace_data(self.db).target {
1595 Ok(target) => crate::utils::target_feature_is_safe_in_target(target),
1596 Err(_) => TargetFeatureIsSafeInTarget::No,
1597 };
1598 (target_features, target_feature_is_safe)
1599 });
1600 (target_features, *target_feature_is_safe)
1601 }
1602
1603 fn data_layout(&self) -> &'db TargetDataLayout {
1604 self.data_layout.get_or_init(|| self.db.target_data_layout_or_default(self.krate()))
1605 }
1606
1607 fn deref_pat_borrow_mode(&self, pointer_ty: Ty<'_>, inner: PatId) -> DerefPatBorrowMode {
1614 if pointer_ty.is_box() {
1615 DerefPatBorrowMode::Box
1616 } else {
1617 let mutability =
1618 if self.pat_has_ref_mut_binding(inner) { Mutability::Mut } else { Mutability::Not };
1619 DerefPatBorrowMode::Borrow(mutability)
1620 }
1621 }
1622
1623 #[inline]
1624 fn set_tainted_by_errors(&mut self) {
1625 self.result.has_errors = true;
1626 }
1627
1628 fn merge_anon_consts(&mut self) {
1631 let mut defined_anon_consts = std::mem::take(&mut *self.defined_anon_consts.borrow_mut());
1632 defined_anon_consts.retain(|&konst| {
1633 if konst.loc(self.db).owner != self.store_owner {
1634 return false;
1636 }
1637
1638 let const_infer = InferenceResult::of(self.db, konst);
1639 self.merge(const_infer);
1640 true
1641 });
1642 self.defined_anon_consts.borrow_mut().append(&mut defined_anon_consts);
1644 }
1645
1646 fn resolve_all(self) -> InferenceResult<'db> {
1647 let InferenceContext {
1648 table,
1649 mut result,
1650 tuple_field_accesses_rev,
1651 diagnostics,
1652 types,
1653 vars_emitted_type_must_be_known_for,
1654 ..
1655 } = self;
1656 let diagnostics = diagnostics.finish();
1657 let InferenceResult {
1660 method_resolutions,
1661 field_resolutions: _,
1662 variant_resolutions: _,
1663 assoc_resolutions,
1664 type_of_expr,
1665 type_of_pat,
1666 type_of_binding,
1667 term_of_term_placeholders,
1668 type_of_opaque,
1669 skipped_ref_pats,
1670 closures_data,
1671 has_errors,
1672 pat_adjustments,
1673 binding_modes: _,
1674 expr_adjustments,
1675 tuple_field_access_types,
1676 coercion_casts: _,
1677 diagnostics: result_diagnostics,
1678 nodes_with_type_mismatches,
1679 defined_anon_consts: result_defined_anon_consts,
1680 } = &mut result;
1681
1682 *result_defined_anon_consts = self.defined_anon_consts.into_inner();
1683 result_defined_anon_consts.shrink_to_fit();
1684
1685 let mut resolver =
1686 WriteBackCtxt::new(table, diagnostics, vars_emitted_type_must_be_known_for);
1687
1688 skipped_ref_pats.shrink_to_fit();
1689 for ty in type_of_expr.values_mut() {
1690 resolver.resolve_completely(ty);
1691 }
1692 type_of_expr.shrink_to_fit();
1693 for ty in type_of_pat.values_mut() {
1694 resolver.resolve_completely(ty);
1695 }
1696 type_of_pat.shrink_to_fit();
1697 for ty in type_of_binding.values_mut() {
1698 resolver.resolve_completely(ty);
1699 }
1700 type_of_binding.shrink_to_fit();
1701 for term in term_of_term_placeholders.values_mut() {
1702 resolver.resolve_completely(term);
1703 }
1704 term_of_term_placeholders.shrink_to_fit();
1705 type_of_opaque.shrink_to_fit();
1706
1707 if !nodes_with_type_mismatches.is_empty() {
1708 *has_errors = true;
1709 }
1710 nodes_with_type_mismatches.shrink_to_fit();
1711 for (_, subst) in method_resolutions.values_mut() {
1712 resolver.resolve_completely(subst);
1713 }
1714 method_resolutions.shrink_to_fit();
1715 for (_, subst) in assoc_resolutions.values_mut() {
1716 resolver.resolve_completely(subst);
1717 }
1718 assoc_resolutions.shrink_to_fit();
1719 for adjustment in expr_adjustments.values_mut().flatten() {
1720 resolver.resolve_completely(&mut adjustment.target);
1721 }
1722 expr_adjustments.shrink_to_fit();
1723 for adjustments in pat_adjustments.values_mut() {
1724 for adjustment in &mut *adjustments {
1725 resolver.resolve_completely(&mut adjustment.source);
1726 }
1727 adjustments.shrink_to_fit();
1728 }
1729 pat_adjustments.shrink_to_fit();
1730 for closure_data in closures_data.values_mut() {
1731 let ClosureData { min_captures, fake_reads, liberated_sig } = closure_data;
1732 let dummy_place = || Place {
1733 base_ty: types.types.error.store(),
1734 base: closure::analysis::expr_use_visitor::PlaceBase::Rvalue,
1735 projections: Vec::new(),
1736 };
1737
1738 for (place, _, sources) in fake_reads {
1739 resolver.resolve_completely_with_default(place, dummy_place());
1740 place.projections.shrink_to_fit();
1741 for source in &mut *sources {
1742 source.shrink_to_fit();
1743 }
1744 sources.shrink_to_fit();
1745 }
1746
1747 for min_capture in min_captures.values_mut() {
1748 for captured in &mut *min_capture {
1749 let CapturedPlace { place, info, mutability: _ } = captured;
1750 resolver.resolve_completely_with_default(place, dummy_place());
1751 let CaptureInfo { sources, capture_kind: _ } = info;
1752 for source in &mut *sources {
1753 source.shrink_to_fit();
1754 }
1755 sources.shrink_to_fit();
1756 }
1757 min_capture.shrink_to_fit();
1758 }
1759 min_captures.shrink_to_fit();
1760
1761 resolver.resolve_completely(liberated_sig);
1762 }
1763 closures_data.shrink_to_fit();
1764 *tuple_field_access_types = tuple_field_accesses_rev
1765 .into_iter()
1766 .map(|mut subst| {
1767 resolver.resolve_completely(&mut subst);
1768 subst.store()
1769 })
1770 .collect();
1771 tuple_field_access_types.shrink_to_fit();
1772
1773 let (diagnostics, resolver_has_errors) = resolver.resolve_diagnostics();
1774 *result_diagnostics = diagnostics;
1775 *has_errors |= resolver_has_errors;
1776
1777 result
1778 }
1779
1780 fn collect_const_or_static(&mut self, id: ValueTyDefId) {
1781 let return_ty = self.db.value_ty(id).unwrap().instantiate_identity().skip_norm_wip();
1782 self.return_ty = self.process_remote_user_written_ty(return_ty);
1783 }
1784
1785 fn collect_fn(
1786 &mut self,
1787 func: FunctionId,
1788 self_param: Option<BindingId>,
1789 params: &[Param<PatId>],
1790 ) {
1791 let sig = self.interner().liberate_late_bound_regions(
1792 func.into(),
1793 self.db.callable_item_signature(func.into()).instantiate_identity().skip_norm_wip(),
1794 );
1795
1796 let maybe_va_list =
1799 if sig.fn_sig_kind.c_variadic() { self.resolve_va_list() } else { None };
1800 let maybe_va_list = maybe_va_list.map(|va_list| {
1801 let region = self.table.next_region_var(
1802 params.last().expect("variadic function must have parameters").user_written.into(),
1803 );
1804 Ty::new_adt(self.interner(), va_list, GenericArgs::new_from_slice(&[region.into()]))
1805 });
1806
1807 let mut param_tys = sig.inputs().iter().copied();
1808
1809 if let Some(self_param) = self_param
1810 && let Some(ty) = param_tys.next()
1811 {
1812 let ty = self.process_remote_user_written_ty(ty);
1813 self.write_binding_ty(self_param, ty);
1814 }
1815
1816 let mut param_tys = param_tys.chain(maybe_va_list);
1817 for pat in params {
1818 let ty = param_tys.next().unwrap_or_else(|| self.table.next_ty_var(Span::Dummy));
1819 let ty = self.process_remote_user_written_ty(ty);
1820
1821 self.infer_top_pat(pat.formal, ty, PatOrigin::Param);
1822 }
1823
1824 self.return_ty = self.process_remote_user_written_ty(sig.output());
1825 self.return_coercion = Some(CoerceMany::new(self.return_ty));
1826 }
1827
1828 #[inline]
1829 pub(crate) fn interner(&self) -> DbInterner<'db> {
1830 self.table.interner()
1831 }
1832
1833 #[inline]
1834 pub(crate) fn infcx(&self) -> &InferCtxt<'db> {
1835 &self.table.infer_ctxt
1836 }
1837
1838 fn insert_type_vars_shallow(&mut self, ty: Ty<'db>) -> Ty<'db> {
1853 if ty.is_ty_error() {
1854 let var = self.table.next_ty_var(Span::Dummy);
1855
1856 self.vars_emitted_type_must_be_known_for.insert(var.into());
1858
1859 var
1860 } else {
1861 ty
1862 }
1863 }
1864
1865 fn infer_body(&mut self, body_expr: ExprId) {
1866 match self.return_coercion {
1867 Some(_) => self.infer_return(body_expr),
1868 None => {
1869 _ = self.infer_expr_coerce(
1870 body_expr,
1871 &Expectation::has_type(self.return_ty),
1872 ExprIsRead::Yes,
1873 )
1874 }
1875 }
1876 }
1877
1878 fn write_expr_ty(&mut self, expr: ExprId, ty: Ty<'db>) {
1879 self.result.type_of_expr.insert(expr, ty.store());
1880 }
1881
1882 pub(crate) fn write_expr_adj(&mut self, expr: ExprId, adjustments: Box<[Adjustment]>) {
1883 if adjustments.is_empty() {
1884 return;
1885 }
1886 match self.result.expr_adjustments.entry(expr) {
1887 std::collections::hash_map::Entry::Occupied(mut entry) => {
1888 match (&mut entry.get_mut()[..], &adjustments[..]) {
1889 (
1890 [Adjustment { kind: Adjust::NeverToAny, target }],
1891 [.., Adjustment { target: new_target, .. }],
1892 ) => {
1893 *target = new_target.clone();
1896 }
1897 _ => {
1898 *entry.get_mut() = adjustments;
1899 }
1900 }
1901 }
1902 std::collections::hash_map::Entry::Vacant(entry) => {
1903 entry.insert(adjustments);
1904 }
1905 }
1906 }
1907
1908 pub(crate) fn write_method_resolution(
1909 &mut self,
1910 expr: ExprId,
1911 func: FunctionId,
1912 subst: GenericArgs<'db>,
1913 ) {
1914 self.result.method_resolutions.insert(expr, (func, subst.store()));
1915 }
1916
1917 fn write_variant_resolution(&mut self, id: ExprOrPatIdPacked, variant: VariantId) {
1918 self.result.variant_resolutions.insert(id, variant);
1919 }
1920
1921 fn write_assoc_resolution(
1922 &mut self,
1923 id: ExprOrPatIdPacked,
1924 item: CandidateId,
1925 subs: GenericArgs<'db>,
1926 ) {
1927 self.result.assoc_resolutions.insert(id, (item, subs.store()));
1928 }
1929
1930 fn write_pat_ty(&mut self, pat: PatId, ty: Ty<'db>) {
1931 self.result.type_of_pat.insert(pat, ty.store());
1932 }
1933
1934 fn write_binding_ty(&mut self, id: BindingId, ty: Ty<'db>) {
1935 self.result.type_of_binding.insert(id, ty.store());
1936 }
1937
1938 pub(crate) fn push_diagnostic(&self, diagnostic: InferenceDiagnostic) {
1939 self.diagnostics.push(diagnostic);
1940 }
1941
1942 fn record_deferred_call_resolution(
1943 &mut self,
1944 closure_def_id: ExprId,
1945 r: DeferredCallResolution<'db>,
1946 ) {
1947 self.deferred_call_resolutions.entry(closure_def_id).or_default().push(r);
1948 }
1949
1950 fn remove_deferred_call_resolutions(
1951 &mut self,
1952 closure_def_id: ExprId,
1953 ) -> Vec<DeferredCallResolution<'db>> {
1954 self.deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default()
1955 }
1956
1957 fn with_ty_lowering<R>(&mut self, f: impl FnOnce(&mut TyLoweringContext<'db, '_>) -> R) -> R {
1958 let mut infer_vars = InferenceTyLoweringVarsCtx {
1959 table: &mut self.table,
1960 term_of_term_placeholders: &mut self.result.term_of_term_placeholders,
1961 };
1962 let mut ctx = TyLoweringContext::new(
1963 self.db,
1964 &self.resolver,
1965 self.store,
1966 &self.diagnostics,
1967 self.store_owner,
1968 self.generic_def,
1969 &self.generics,
1970 LifetimeElisionKind::Infer,
1971 self.allow_using_generic_params,
1972 &mut infer_vars,
1973 &self.defined_anon_consts,
1974 LifetimeLoweringMode::LateParam,
1975 );
1976 f(&mut ctx)
1977 }
1978
1979 pub(crate) fn make_ty(&mut self, type_ref: TypeRefId) -> Ty<'db> {
1980 let ty = self.with_ty_lowering(|ctx| ctx.lower_ty(type_ref));
1981 self.process_user_written_ty(ty)
1982 }
1983
1984 fn generics(&self) -> &Generics<'db> {
1985 self.generics.get_or_init(|| crate::generics::generics(self.db, self.generic_def))
1986 }
1987
1988 fn identity_args(&self) -> GenericArgs<'db> {
1989 *self.identity_args.get_or_init(|| {
1990 GenericArgs::identity_for_item(self.interner(), self.generic_def.into())
1991 })
1992 }
1993
1994 pub(crate) fn create_anon_const(&mut self, expr: ExprId, expected_ty: Ty<'db>) -> Const<'db> {
1995 never!(expected_ty.has_infer(), "cannot have infer vars in an anon const's ty");
1996 let konst = create_anon_const(
1997 self.interner(),
1998 self.store_owner,
1999 self.store,
2000 expr,
2001 &self.resolver,
2002 expected_ty,
2003 &|| self.generics(),
2004 Some(&mut |span| self.table.next_const_var(span)),
2005 self.lowering_mode,
2006 (!self.allow_using_generic_params).then_some(0),
2007 false,
2011 );
2012
2013 if let Ok(konst) = konst
2014 && let ConstKind::Unevaluated(konst) = konst.kind()
2015 && let GeneralConstId::AnonConstId(konst) = konst.def.0
2016 {
2017 self.defined_anon_consts.borrow_mut().push(konst);
2018 } else {
2019 self.write_expr_ty(expr, expected_ty);
2020 }
2021
2022 konst.unwrap_or_else(|_| self.table.next_const_var(Span::Dummy))
2024 }
2025
2026 pub(crate) fn make_path_as_const(&mut self, path: &Path) -> Const<'db> {
2027 let forbid_params_after = if self.allow_using_generic_params { None } else { Some(0) };
2028 path_to_const(self.db, &self.resolver, &|| self.generics(), forbid_params_after, path)
2030 .unwrap_or_else(|_| self.table.next_const_var(Span::Dummy))
2031 }
2032
2033 fn err_ty(&self) -> Ty<'db> {
2034 self.types.types.error
2035 }
2036
2037 pub(crate) fn make_lifetime(&mut self, lifetime_ref: LifetimeRefId) -> Region<'db> {
2038 let lt = self.with_ty_lowering(|ctx| ctx.lower_lifetime(lifetime_ref));
2039 self.insert_type_vars(lt)
2040 }
2041
2042 fn insert_type_vars<T>(&mut self, ty: T) -> T
2043 where
2044 T: TypeFoldable<DbInterner<'db>>,
2045 {
2046 self.table.insert_type_vars(ty)
2047 }
2048
2049 fn struct_tail_without_normalization(&mut self, ty: Ty<'db>) -> Ty<'db> {
2053 self.struct_tail_with_normalize(ty, identity)
2054 }
2055
2056 fn struct_tail_with_normalize(
2064 &mut self,
2065 mut ty: Ty<'db>,
2066 mut normalize: impl FnMut(Ty<'db>) -> Ty<'db>,
2067 ) -> Ty<'db> {
2068 let recursion_limit = 10;
2070 for iteration in 0.. {
2071 if iteration > recursion_limit {
2072 return self.err_ty();
2073 }
2074 match ty.kind() {
2075 TyKind::Adt(adt_def, substs) => match adt_def.def_id() {
2076 AdtId::StructId(struct_id) => {
2077 match self
2078 .db
2079 .field_types(struct_id.into())
2080 .values()
2081 .next_back()
2082 .map(|it| it.ty())
2083 {
2084 Some(field) => {
2085 ty = field.instantiate(self.interner(), substs).skip_norm_wip();
2086 }
2087 None => break,
2088 }
2089 }
2090 _ => break,
2091 },
2092 TyKind::Tuple(substs) => match substs.as_slice().split_last() {
2093 Some((last_ty, _)) => ty = *last_ty,
2094 None => break,
2095 },
2096 TyKind::Alias(..) => {
2097 let normalized = normalize(ty);
2098 if ty == normalized {
2099 return ty;
2100 } else {
2101 ty = normalized;
2102 }
2103 }
2104 _ => break,
2105 }
2106 }
2107 ty
2108 }
2109
2110 fn process_user_written_ty(&mut self, ty: Ty<'db>) -> Ty<'db> {
2112 self.table.process_user_written_ty(ty)
2113 }
2114
2115 fn process_remote_user_written_ty(&mut self, ty: Ty<'db>) -> Ty<'db> {
2118 self.table.process_remote_user_written_ty(ty)
2119 }
2120
2121 fn shallow_resolve(&self, ty: Ty<'db>) -> Ty<'db> {
2122 self.table.shallow_resolve(ty)
2123 }
2124
2125 pub(crate) fn resolve_vars_if_possible<T: TypeFoldable<DbInterner<'db>>>(&self, t: T) -> T {
2126 self.table.resolve_vars_if_possible(t)
2127 }
2128
2129 pub(crate) fn structurally_resolve_type(
2130 &mut self,
2131 node: ExprOrPatIdPacked,
2132 ty: Ty<'db>,
2133 ) -> Ty<'db> {
2134 let result = self.table.try_structurally_resolve_type(node.into(), ty);
2135 if result.is_ty_var() { self.type_must_be_known_at_this_point(node, ty) } else { result }
2136 }
2137
2138 pub(crate) fn innermost_tail_expr(&self, mut expr: ExprId) -> ExprId {
2139 while let Expr::Block { tail: Some(tail), label: None, .. } = self.store[expr] {
2140 expr = tail;
2141 }
2142 expr
2143 }
2144
2145 pub(crate) fn emit_type_mismatch(
2146 &mut self,
2147 node: ExprOrPatIdPacked,
2148 expected: Ty<'db>,
2149 found: Ty<'db>,
2150 ) {
2151 if self.result.nodes_with_type_mismatches.insert(node) {
2152 self.diagnostics.push(InferenceDiagnostic::TypeMismatch {
2153 node,
2154 expected: expected.store(),
2155 found: found.store(),
2156 });
2157 }
2158 }
2159
2160 fn demand_eqtype(
2161 &mut self,
2162 id: ExprOrPatIdPacked,
2163 expected: Ty<'db>,
2164 actual: Ty<'db>,
2165 ) -> Result<(), ()> {
2166 let result = self
2167 .table
2168 .at(&ObligationCause::new(id))
2169 .eq(expected, actual)
2170 .map(|infer_ok| self.table.register_infer_ok(infer_ok));
2171 if result.is_err() {
2172 self.emit_type_mismatch(id, expected, actual);
2173 }
2174 result.map_err(drop)
2175 }
2176
2177 fn demand_eqtype_fixme_no_diag(
2178 &mut self,
2179 expected: Ty<'db>,
2180 actual: Ty<'db>,
2181 ) -> Result<(), ()> {
2182 let result = self
2183 .table
2184 .at(&ObligationCause::dummy())
2185 .eq(expected, actual)
2186 .map(|infer_ok| self.table.register_infer_ok(infer_ok));
2187 result.map_err(drop)
2188 }
2189
2190 fn demand_suptype(
2191 &mut self,
2192 id: ExprOrPatIdPacked,
2193 expected: Ty<'db>,
2194 actual: Ty<'db>,
2195 ) -> Result<(), ()> {
2196 let result = self
2197 .table
2198 .at(&ObligationCause::new(id))
2199 .sup(expected, actual)
2200 .map(|infer_ok| self.table.register_infer_ok(infer_ok));
2201 if result.is_err() {
2202 self.emit_type_mismatch(id, expected, actual);
2203 }
2204 result.map_err(drop)
2205 }
2206
2207 fn demand_coerce(
2208 &mut self,
2209 expr: ExprId,
2210 checked_ty: Ty<'db>,
2211 expected: Ty<'db>,
2212 allow_two_phase: AllowTwoPhase,
2213 expr_is_read: ExprIsRead,
2214 ) -> Ty<'db> {
2215 let result = self.coerce(expr, checked_ty, expected, allow_two_phase, expr_is_read);
2216 if let Err(_err) = result {
2217 }
2219 result.unwrap_or(self.types.types.error)
2220 }
2221
2222 pub(crate) fn type_must_be_known_at_this_point(
2223 &mut self,
2224 node: ExprOrPatIdPacked,
2225 ty: Ty<'db>,
2226 ) -> Ty<'db> {
2227 if self.vars_emitted_type_must_be_known_for.insert(ty.into()) {
2228 self.push_diagnostic(InferenceDiagnostic::TypeMustBeKnown {
2229 at_point: node.into(),
2230 top_term: None,
2231 });
2232 }
2233 self.types.types.error
2234 }
2235
2236 pub(crate) fn require_type_is_sized(&mut self, ty: Ty<'db>, span: Span) {
2237 if !ty.references_non_lt_error()
2238 && let Some(sized_trait) = self.lang_items.Sized
2239 {
2240 self.table.register_bound(ty, sized_trait, ObligationCause::new(span));
2241 }
2242 }
2243
2244 fn expr_ty(&self, expr: ExprId) -> Ty<'db> {
2245 self.result.expr_ty(expr)
2246 }
2247
2248 fn expr_ty_after_adjustments(&self, e: ExprId) -> Ty<'db> {
2249 let mut ty = None;
2250 if let Some(it) = self.result.expr_adjustments.get(&e)
2251 && let Some(it) = it.last()
2252 {
2253 ty = Some(it.target.as_ref());
2254 }
2255 ty.unwrap_or_else(|| self.expr_ty(e))
2256 }
2257
2258 fn resolve_variant(
2259 &mut self,
2260 node: ExprOrPatIdPacked,
2261 path: &Path,
2262 value_ns: bool,
2263 ) -> (Ty<'db>, Option<VariantId>) {
2264 let interner = self.interner();
2265 let mut vars_ctx = InferenceTyLoweringVarsCtx {
2266 table: &mut self.table,
2267 term_of_term_placeholders: &mut self.result.term_of_term_placeholders,
2268 };
2269 let mut ctx = TyLoweringContext::new(
2270 self.db,
2271 &self.resolver,
2272 self.store,
2273 &self.diagnostics,
2274 self.store_owner,
2275 self.generic_def,
2276 &self.generics,
2277 LifetimeElisionKind::Infer,
2278 self.allow_using_generic_params,
2279 &mut vars_ctx,
2280 &self.defined_anon_consts,
2281 LifetimeLoweringMode::LateParam,
2282 );
2283
2284 if let Some(type_anchor) = path.type_anchor() {
2285 let mut segments = path.segments();
2286 if segments.is_empty() {
2287 return (self.types.types.error, None);
2288 }
2289 let (mut ty, type_ns) = ctx.lower_ty_ext(type_anchor);
2290 ty = ctx.expect_table().process_user_written_ty(ty);
2291
2292 if let Some(TypeNs::SelfType(impl_)) = type_ns
2293 && let Some(trait_ref) = self.db.impl_trait(impl_)
2294 && let trait_ref = trait_ref.instantiate_identity().skip_norm_wip()
2295 && let Some(assoc_type) = trait_ref
2296 .def_id
2297 .0
2298 .trait_items(self.db)
2299 .associated_type_by_name(segments.first().unwrap().name)
2300 {
2301 let args = ctx.expect_table().infer_ctxt.fill_rest_fresh_args(
2303 node.into(),
2304 assoc_type.into(),
2305 trait_ref.args,
2306 );
2307 let alias = Ty::new_alias(
2308 interner,
2309 AliasTy::new_from_args(
2310 interner,
2311 AliasTyKind::Projection { def_id: assoc_type.into() },
2312 args,
2313 ),
2314 );
2315 ty = ctx.expect_table().try_structurally_resolve_type(node.into(), alias);
2316 segments = segments.skip(1);
2317 }
2318
2319 let variant = match ty.as_adt() {
2320 Some((AdtId::StructId(id), _)) => id.into(),
2321 Some((AdtId::UnionId(id), _)) => id.into(),
2322 Some((AdtId::EnumId(id), _)) => {
2323 if let Some(segment) = segments.first()
2324 && let enum_data = id.enum_variants(self.db)
2325 && let Some(variant) = enum_data.variant(segment.name)
2326 {
2327 segments = segments.skip(1);
2329 variant.into()
2330 } else {
2331 return (self.types.types.error, None);
2332 }
2333 }
2334 None => return (self.types.types.error, None),
2335 };
2336
2337 if !segments.is_empty() {
2338 return (self.types.types.error, None);
2340 } else {
2341 return (ty, Some(variant));
2342 }
2343 }
2344
2345 let mut path_ctx = ctx.at_path(path, node);
2346 let (resolution, unresolved) = if value_ns {
2347 let Some(res) = path_ctx.resolve_path_in_value_ns(HygieneId::ROOT) else {
2348 return (self.types.types.error, None);
2349 };
2350 match res {
2351 ResolveValueResult::ValueNs(value) => match value {
2352 ValueNs::EnumVariantId(var) => {
2353 let args = path_ctx.substs_from_path(var.into(), true, false, node.into());
2354 drop(ctx);
2355 let ty = self
2356 .db
2357 .ty(var.lookup(self.db).parent.into())
2358 .instantiate(interner, args)
2359 .skip_norm_wip();
2360 let ty = self.insert_type_vars(ty);
2361 return (ty, Some(var.into()));
2362 }
2363 ValueNs::StructId(strukt) => {
2364 let args =
2365 path_ctx.substs_from_path(strukt.into(), true, false, node.into());
2366 drop(ctx);
2367 let ty =
2368 self.db.ty(strukt.into()).instantiate(interner, args).skip_norm_wip();
2369 let ty = self.insert_type_vars(ty);
2370 return (ty, Some(strukt.into()));
2371 }
2372 ValueNs::ImplSelf(impl_id) => (TypeNs::SelfType(impl_id), None),
2373 _ => {
2374 drop(ctx);
2375 return (self.types.types.error, None);
2376 }
2377 },
2378 ResolveValueResult::Partial(typens, unresolved) => (typens, Some(unresolved)),
2379 }
2380 } else {
2381 match path_ctx.resolve_path_in_type_ns() {
2382 Some((it, idx)) => (it, idx),
2383 None => return (self.types.types.error, None),
2384 }
2385 };
2386 return match resolution {
2387 TypeNs::AdtId(AdtId::StructId(strukt)) => {
2388 let args = path_ctx.substs_from_path(strukt.into(), true, false, node.into());
2389 drop(ctx);
2390 let ty = self.db.ty(strukt.into()).instantiate(interner, args).skip_norm_wip();
2391 let ty = self.insert_type_vars(ty);
2392 forbid_unresolved_segments(self, (ty, Some(strukt.into())), unresolved)
2393 }
2394 TypeNs::AdtId(AdtId::UnionId(u)) => {
2395 let args = path_ctx.substs_from_path(u.into(), true, false, node.into());
2396 drop(ctx);
2397 let ty = self.db.ty(u.into()).instantiate(interner, args).skip_norm_wip();
2398 let ty = self.insert_type_vars(ty);
2399 forbid_unresolved_segments(self, (ty, Some(u.into())), unresolved)
2400 }
2401 TypeNs::EnumVariantId(var) => {
2402 let args = path_ctx.substs_from_path(var.into(), true, false, node.into());
2403 drop(ctx);
2404 let ty = self
2405 .db
2406 .ty(var.lookup(self.db).parent.into())
2407 .instantiate(interner, args)
2408 .skip_norm_wip();
2409 let ty = self.insert_type_vars(ty);
2410 forbid_unresolved_segments(self, (ty, Some(var.into())), unresolved)
2411 }
2412 TypeNs::SelfType(impl_id) => {
2413 let mut ty = self.db.impl_self_ty(impl_id).instantiate_identity().skip_norm_wip();
2414
2415 let Some(remaining_idx) = unresolved else {
2416 drop(ctx);
2417 let Some(mod_path) = path.mod_path() else {
2418 never!("resolver should always resolve lang item paths");
2419 return (self.types.types.error, None);
2420 };
2421 return self.resolve_variant_on_alias(node, ty, None, mod_path);
2422 };
2423
2424 let mut remaining_segments = path.segments().skip(remaining_idx);
2425
2426 if remaining_segments.len() >= 2 {
2427 path_ctx.ignore_last_segment();
2428 }
2429
2430 let mut tried_resolving_once = false;
2433 while let Some(current_segment) = remaining_segments.first() {
2434 if let TyKind::Adt(adt_def, _) = ty.kind()
2437 && let AdtId::EnumId(id) = adt_def.def_id()
2438 {
2439 let enum_data = id.enum_variants(self.db);
2440 if let Some(variant) = enum_data.variant(current_segment.name) {
2441 return if remaining_segments.len() == 1 {
2442 (ty, Some(variant.into()))
2443 } else {
2444 (self.types.types.error, None)
2448 };
2449 }
2450 }
2451
2452 if tried_resolving_once {
2453 break;
2456 }
2457
2458 (ty, _) = path_ctx.lower_partly_resolved_path(resolution, true, node.into());
2462 tried_resolving_once = true;
2463
2464 ty = path_ctx.expect_table().process_user_written_ty(ty);
2465 if ty.is_ty_error() {
2466 return (self.types.types.error, None);
2467 }
2468
2469 remaining_segments = remaining_segments.skip(1);
2470 }
2471 drop(ctx);
2472
2473 let variant = ty.as_adt().and_then(|(id, _)| match id {
2474 AdtId::StructId(s) => Some(VariantId::StructId(s)),
2475 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
2476 AdtId::EnumId(_) => {
2477 None
2479 }
2480 });
2481 (ty, variant)
2482 }
2483 TypeNs::TraitId(_) => {
2484 let Some(remaining_idx) = unresolved else {
2485 return (self.types.types.error, None);
2486 };
2487
2488 let remaining_segments = path.segments().skip(remaining_idx);
2489
2490 if remaining_segments.len() >= 2 {
2491 path_ctx.ignore_last_segment();
2492 }
2493
2494 let (mut ty, _) =
2495 path_ctx.lower_partly_resolved_path(resolution, true, node.into());
2496 ty = ctx.expect_table().process_user_written_ty(ty);
2497
2498 if let Some(segment) = remaining_segments.get(1)
2499 && let Some((AdtId::EnumId(id), _)) = ty.as_adt()
2500 {
2501 let enum_data = id.enum_variants(self.db);
2502 if let Some(variant) = enum_data.variant(segment.name) {
2503 return if remaining_segments.len() == 2 {
2504 (ty, Some(variant.into()))
2505 } else {
2506 (self.types.types.error, None)
2510 };
2511 }
2512 }
2513
2514 let variant = ty.as_adt().and_then(|(id, _)| match id {
2515 AdtId::StructId(s) => Some(VariantId::StructId(s)),
2516 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
2517 AdtId::EnumId(_) => {
2518 None
2520 }
2521 });
2522 (ty, variant)
2523 }
2524 TypeNs::TypeAliasId(it) => {
2525 let Some(mod_path) = path.mod_path() else {
2526 never!("resolver should always resolve lang item paths");
2527 return (self.types.types.error, None);
2528 };
2529 let args =
2530 path_ctx.substs_from_path_segment(it.into(), true, None, false, node.into());
2531 let interner = path_ctx.interner();
2532 drop(ctx);
2533 let ty = self.db.ty(it.into()).instantiate(interner, args).skip_norm_wip();
2534 let ty = self.insert_type_vars(ty);
2535
2536 self.resolve_variant_on_alias(node, ty, unresolved, mod_path)
2537 }
2538 TypeNs::AdtSelfType(_) => {
2539 (self.types.types.error, None)
2541 }
2542 TypeNs::GenericParam(_) => {
2543 (self.types.types.error, None)
2545 }
2546 TypeNs::AdtId(AdtId::EnumId(_)) | TypeNs::BuiltinType(_) | TypeNs::ModuleId(_) => {
2547 (self.types.types.error, None)
2549 }
2550 };
2551
2552 fn forbid_unresolved_segments<'db>(
2553 ctx: &InferenceContext<'db>,
2554 result: (Ty<'db>, Option<VariantId>),
2555 unresolved: Option<usize>,
2556 ) -> (Ty<'db>, Option<VariantId>) {
2557 if unresolved.is_none() {
2558 result
2559 } else {
2560 (ctx.types.types.error, None)
2562 }
2563 }
2564 }
2565
2566 fn resolve_variant_on_alias(
2567 &mut self,
2568 node: ExprOrPatIdPacked,
2569 ty: Ty<'db>,
2570 unresolved: Option<usize>,
2571 path: &ModPath,
2572 ) -> (Ty<'db>, Option<VariantId>) {
2573 let remaining = unresolved.map(|it| path.segments()[it..].len()).filter(|it| it > &0);
2574 let ty = self.table.try_structurally_resolve_type(node.into(), ty);
2575 match remaining {
2576 None => {
2577 let variant = ty.as_adt().and_then(|(adt_id, _)| match adt_id {
2578 AdtId::StructId(s) => Some(VariantId::StructId(s)),
2579 AdtId::UnionId(u) => Some(VariantId::UnionId(u)),
2580 AdtId::EnumId(_) => {
2581 None
2583 }
2584 });
2585 (ty, variant)
2586 }
2587 Some(1) => {
2588 let segment = path.segments().last().unwrap();
2589 if let Some((AdtId::EnumId(enum_id), _)) = ty.as_adt() {
2591 let enum_data = enum_id.enum_variants(self.db);
2592 if let Some(variant) = enum_data.variant(segment) {
2593 return (ty, Some(variant.into()));
2594 }
2595 }
2596 (self.err_ty(), None)
2598 }
2599 Some(_) => {
2600 (self.err_ty(), None)
2602 }
2603 }
2604 }
2605
2606 fn resolve_va_list(&self) -> Option<AdtId> {
2607 let struct_ = self.lang_items.VaList?;
2608 Some(struct_.into())
2609 }
2610
2611 pub(crate) fn get_traits_in_scope(&self) -> Either<FxHashSet<TraitId>, &FxHashSet<TraitId>> {
2612 let mut b_traits = self.resolver.traits_in_scope_from_block_scopes().peekable();
2613 if b_traits.peek().is_some() {
2614 Either::Left(self.traits_in_scope.iter().copied().chain(b_traits).collect())
2615 } else {
2616 Either::Right(&self.traits_in_scope)
2617 }
2618 }
2619
2620 fn has_applicable_non_exhaustive(&self, def: AttrDefId) -> bool {
2621 AttrFlags::query(self.db, def).contains(AttrFlags::NON_EXHAUSTIVE)
2622 && def.krate(self.db) != self.krate()
2623 }
2624}
2625
2626#[derive(Clone, PartialEq, Eq, Debug)]
2629pub(crate) enum Expectation<'db> {
2630 None,
2631 HasType(Ty<'db>),
2632 Castable(Ty<'db>),
2633 RValueLikeUnsized(Ty<'db>),
2634}
2635
2636impl<'db> Expectation<'db> {
2637 fn has_type(ty: Ty<'db>) -> Self {
2640 if ty.is_ty_error() {
2641 Expectation::None
2643 } else {
2644 Expectation::HasType(ty)
2645 }
2646 }
2647
2648 fn rvalue_hint(ctx: &mut InferenceContext<'db>, ty: Ty<'db>) -> Self {
2669 match ctx.struct_tail_without_normalization(ty).kind() {
2670 TyKind::Slice(_) | TyKind::Str | TyKind::Dynamic(..) => {
2671 Expectation::RValueLikeUnsized(ty)
2672 }
2673 _ => Expectation::has_type(ty),
2674 }
2675 }
2676
2677 fn none() -> Self {
2679 Expectation::None
2680 }
2681
2682 fn resolve(&self, table: &unify::InferenceTable<'db>) -> Expectation<'db> {
2683 match self {
2684 Expectation::None => Expectation::None,
2685 Expectation::HasType(t) => Expectation::HasType(table.shallow_resolve(*t)),
2686 Expectation::Castable(t) => Expectation::Castable(table.shallow_resolve(*t)),
2687 Expectation::RValueLikeUnsized(t) => {
2688 Expectation::RValueLikeUnsized(table.shallow_resolve(*t))
2689 }
2690 }
2691 }
2692
2693 fn to_option(&self, table: &unify::InferenceTable<'db>) -> Option<Ty<'db>> {
2694 match self.resolve(table) {
2695 Expectation::None => None,
2696 Expectation::HasType(t)
2697 | Expectation::Castable(t)
2698 | Expectation::RValueLikeUnsized(t) => Some(t),
2699 }
2700 }
2701
2702 fn only_has_type(&self, table: &mut unify::InferenceTable<'db>) -> Option<Ty<'db>> {
2703 match self {
2704 Expectation::HasType(t) => Some(table.resolve_vars_if_possible(*t)),
2705 Expectation::Castable(_) | Expectation::RValueLikeUnsized(_) | Expectation::None => {
2706 None
2707 }
2708 }
2709 }
2710
2711 fn coercion_target_type(&self, table: &mut unify::InferenceTable<'db>, span: Span) -> Ty<'db> {
2712 self.only_has_type(table).unwrap_or_else(|| table.next_ty_var(span))
2713 }
2714
2715 fn adjust_for_branches(
2733 &self,
2734 table: &mut unify::InferenceTable<'db>,
2735 span: Span,
2736 ) -> Expectation<'db> {
2737 match *self {
2738 Expectation::HasType(ety) => {
2739 let ety = table.try_structurally_resolve_type(span, ety);
2740 if ety.is_ty_var() { Expectation::None } else { Expectation::HasType(ety) }
2741 }
2742 Expectation::RValueLikeUnsized(ety) => Expectation::RValueLikeUnsized(ety),
2743 _ => Expectation::None,
2744 }
2745 }
2746}
2747
2748#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
2749enum Diverges {
2750 Maybe,
2751 Always,
2752}
2753
2754impl Diverges {
2755 fn is_always(self) -> bool {
2756 self == Diverges::Always
2757 }
2758}
2759
2760impl std::ops::BitAnd for Diverges {
2761 type Output = Self;
2762 fn bitand(self, other: Self) -> Self {
2763 std::cmp::min(self, other)
2764 }
2765}
2766
2767impl std::ops::BitOr for Diverges {
2768 type Output = Self;
2769 fn bitor(self, other: Self) -> Self {
2770 std::cmp::max(self, other)
2771 }
2772}
2773
2774impl std::ops::BitAndAssign for Diverges {
2775 fn bitand_assign(&mut self, other: Self) {
2776 *self = *self & other;
2777 }
2778}
2779
2780impl std::ops::BitOrAssign for Diverges {
2781 fn bitor_assign(&mut self, other: Self) {
2782 *self = *self | other;
2783 }
2784}