1use std::cell::{OnceCell, RefCell};
6use std::ops::{Deref, DerefMut};
7
8use either::Either;
9use hir_def::expr_store::ExpressionStore;
10use hir_def::expr_store::path::Path;
11use hir_def::type_ref::ConstRef;
12use hir_def::{ExpressionStoreOwnerId, GenericDefId};
13use hir_def::{
14 hir::{ExprId, ExprOrPatIdPacked},
15 resolver::Resolver,
16};
17use la_arena::RawIdx;
18use thin_vec::ThinVec;
19
20use crate::next_solver::{StoredTerm, Term};
21use crate::{
22 InferenceDiagnostic, Span, ThinFxHashMap, TyLoweringDiagnostic,
23 db::{AnonConstId, HirDatabase},
24 generics::Generics,
25 infer::unify::InferenceTable,
26 lower::{
27 ForbidParamsAfterReason, LifetimeElisionKind, LifetimeLoweringMode, TyLoweringContext,
28 TyLoweringInferVarsCtx,
29 path::{PathDiagnosticCallback, PathLoweringContext},
30 },
31 next_solver::{Const, Region, TermRefIdPacked, Ty},
32};
33
34#[derive(Debug, Default, Clone)]
39pub(super) struct Diagnostics(RefCell<ThinVec<InferenceDiagnostic>>);
40
41impl Diagnostics {
42 pub(super) fn push(&self, diagnostic: InferenceDiagnostic) {
43 self.0.borrow_mut().push(diagnostic);
44 }
45
46 pub(super) fn extend(&self, diagnostic: &[InferenceDiagnostic]) {
47 self.0.borrow_mut().extend(diagnostic.iter().cloned());
48 }
49
50 fn push_ty_diagnostics(&self, diagnostics: ThinVec<TyLoweringDiagnostic>) {
51 self.0
52 .borrow_mut()
53 .extend(diagnostics.into_iter().map(|diag| InferenceDiagnostic::TyDiagnostic { diag }));
54 }
55
56 pub(super) fn finish(self) -> ThinVec<InferenceDiagnostic> {
57 self.0.into_inner()
58 }
59}
60
61pub(crate) struct PathDiagnosticCallbackData<'a> {
62 node: ExprOrPatIdPacked,
63 diagnostics: &'a Diagnostics,
64}
65
66pub(super) struct InferenceTyLoweringVarsCtx<'a, 'db> {
67 pub(super) table: &'a mut InferenceTable<'db>,
68 pub(super) term_of_term_placeholders: &'a mut ThinFxHashMap<TermRefIdPacked, StoredTerm>,
69}
70
71impl<'db> TyLoweringInferVarsCtx<'db> for InferenceTyLoweringVarsCtx<'_, 'db> {
72 fn next_ty_var(&mut self, span: Span) -> Ty<'db> {
73 let ty = self.table.infer_ctxt.next_ty_var(span);
74
75 if let Span::TypeRefId(type_ref) = span {
76 self.term_of_term_placeholders.insert(type_ref.into(), Term::from(ty).store());
77 }
78
79 ty
80 }
81 fn next_const_var(&mut self, span: Span) -> Const<'db> {
82 let const_ = self.table.infer_ctxt.next_const_var(span);
83
84 let term_ref = match span {
85 Span::ExprId(expr) => Some(ConstRef { expr }.into()),
86 Span::TypeRefId(type_ref) => Some(type_ref.into()),
87 _ => None,
88 };
89 if let Some(key) = term_ref {
90 self.term_of_term_placeholders.insert(key, Term::from(const_).store());
91 }
92
93 const_
94 }
95 fn next_region_var(&mut self, span: Span) -> Region<'db> {
96 self.table.infer_ctxt.next_region_var(span)
97 }
98
99 fn as_table(&mut self) -> Option<&mut InferenceTable<'db>> {
100 Some(self.table)
101 }
102}
103
104pub(super) struct InferenceTyLoweringContext<'db, 'a> {
105 ctx: TyLoweringContext<'db, 'a>,
106 diagnostics: &'a Diagnostics,
107 defined_anon_consts: &'a RefCell<ThinVec<AnonConstId<'db>>>,
108}
109
110impl<'db, 'a> InferenceTyLoweringContext<'db, 'a> {
111 #[inline]
112 pub(super) fn new(
113 db: &'db dyn HirDatabase,
114 resolver: &'a Resolver<'db>,
115 store: &'db ExpressionStore,
116 diagnostics: &'a Diagnostics,
117 def: ExpressionStoreOwnerId,
118 generic_def: GenericDefId,
119 generics: &'a OnceCell<Generics<'db>>,
120 lifetime_elision: LifetimeElisionKind<'db>,
121 allow_using_generic_params: bool,
122 infer_vars: &'a mut InferenceTyLoweringVarsCtx<'a, 'db>,
123 defined_anon_consts: &'a RefCell<ThinVec<AnonConstId<'db>>>,
124 lifetime_lowering_mode: LifetimeLoweringMode,
125 ) -> Self {
126 let mut ctx = TyLoweringContext::new(
127 db,
128 resolver,
129 store,
130 def,
131 generic_def,
132 generics,
133 lifetime_elision,
134 lifetime_lowering_mode,
135 )
136 .with_infer_vars_behavior(Some(infer_vars));
137 if !allow_using_generic_params {
138 ctx.forbid_params_after(0, ForbidParamsAfterReason::AnonConst);
139 }
140 Self { ctx, diagnostics, defined_anon_consts }
141 }
142
143 #[inline]
144 pub(super) fn at_path<'b>(
145 &'b mut self,
146 path: &'b Path,
147 node: ExprOrPatIdPacked,
148 ) -> PathLoweringContext<'b, 'a, 'db> {
149 let on_diagnostic = PathDiagnosticCallback {
150 data: Either::Right(PathDiagnosticCallbackData { diagnostics: self.diagnostics, node }),
151 callback: |data, _, diag| {
152 let data = data.as_ref().right().unwrap();
153 data.diagnostics
154 .push(InferenceDiagnostic::PathDiagnostic { node: data.node, diag });
155 },
156 };
157 PathLoweringContext::new(&mut self.ctx, on_diagnostic, path)
158 }
159
160 #[inline]
161 pub(super) fn at_path_forget_diagnostics<'b>(
162 &'b mut self,
163 path: &'b Path,
164 ) -> PathLoweringContext<'b, 'a, 'db> {
165 let on_diagnostic = PathDiagnosticCallback {
166 data: Either::Right(PathDiagnosticCallbackData {
167 diagnostics: self.diagnostics,
168 node: ExprOrPatIdPacked::from(ExprId::from_raw(RawIdx::from_u32(0))),
169 }),
170 callback: |_data, _, _diag| {},
171 };
172 PathLoweringContext::new(&mut self.ctx, on_diagnostic, path)
173 }
174
175 #[inline]
176 pub(super) fn forget_diagnostics(&mut self) {
177 self.ctx.diagnostics.clear();
178 }
179}
180
181impl<'db, 'a> Deref for InferenceTyLoweringContext<'db, 'a> {
182 type Target = TyLoweringContext<'db, 'a>;
183
184 #[inline]
185 fn deref(&self) -> &Self::Target {
186 &self.ctx
187 }
188}
189
190impl DerefMut for InferenceTyLoweringContext<'_, '_> {
191 #[inline]
192 fn deref_mut(&mut self) -> &mut Self::Target {
193 &mut self.ctx
194 }
195}
196
197impl Drop for InferenceTyLoweringContext<'_, '_> {
198 #[inline]
199 fn drop(&mut self) {
200 self.diagnostics.push_ty_diagnostics(std::mem::take(&mut self.ctx.diagnostics));
201 self.defined_anon_consts.borrow_mut().extend(self.ctx.defined_anon_consts.iter().copied());
202 }
203}