rustc_hir_typeck/fn_ctxt/
mod.rs1mod _impl;
2mod adjust_fulfillment_errors;
3mod arg_matrix;
4mod checks;
5mod inspect_obligations;
6mod suggestions;
7
8use std::cell::{Cell, RefCell};
9use std::ops::Deref;
10
11pub(crate) use inspect_obligations::UseSubtyping;
12use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
13use rustc_errors::DiagCtxtHandle;
14use rustc_hir::def_id::{DefId, LocalDefId};
15use rustc_hir::{self as hir, HirId, ItemLocalMap};
16use rustc_hir_analysis::hir_ty_lowering::{
17 HirTyLowerer, InherentAssocCandidate, RegionInferReason,
18};
19use rustc_infer::infer::{self, RegionVariableOrigin};
20use rustc_infer::traits::{DynCompatibilityViolation, Obligation, TraitErrors};
21use rustc_middle::ty::{
22 self, CallerBoundsIterator, CantBeErased, Const, Flags, Ty, TyCtxt, TypeVisitableExt,
23 TypingMode, Unnormalized,
24};
25use rustc_session::Session;
26use rustc_span::def_id::LocalModId;
27use rustc_span::{self, DUMMY_SP, ErrorGuaranteed, Ident, Span};
28use rustc_trait_selection::error_reporting::TypeErrCtxt;
29use rustc_trait_selection::traits::{
30 self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
31};
32
33use crate::coercion::CoerceMany;
34use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
35
36pub(crate) struct FnCtxt<'a, 'tcx> {
48 pub(super) body_def_id: LocalDefId,
49
50 pub(super) param_env: ty::ParamEnv<'tcx>,
57
58 pub(super) ret_coercion: Option<RefCell<CoerceMany<'tcx>>>,
69
70 pub(super) ret_coercion_span: Cell<Option<Span>>,
72
73 pub(super) coroutine_types: Option<CoroutineTypes<'tcx>>,
74
75 pub(super) diverges: Cell<Diverges>,
109
110 pub(super) function_diverges_because_of_empty_arguments: Cell<Diverges>,
113
114 pub(super) is_whole_body: Cell<bool>,
116
117 pub(super) enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>,
118
119 pub(super) root_ctxt: &'a TypeckRootCtxt<'tcx>,
120
121 pub(super) diverging_fallback_has_occurred: Cell<bool>,
124
125 pub(super) trait_ascriptions: RefCell<ItemLocalMap<Vec<ty::Clause<'tcx>>>>,
130
131 pub(super) has_rustc_attrs: bool,
134}
135
136impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
137 pub(crate) fn new(
138 root_ctxt: &'a TypeckRootCtxt<'tcx>,
139 param_env: ty::ParamEnv<'tcx>,
140 body_def_id: LocalDefId,
141 ) -> FnCtxt<'a, 'tcx> {
142 FnCtxt {
143 body_def_id,
144 param_env,
145 ret_coercion: None,
146 ret_coercion_span: Cell::new(None),
147 coroutine_types: None,
148 diverges: Cell::new(Diverges::Maybe),
149 function_diverges_because_of_empty_arguments: Cell::new(Diverges::Maybe),
150 is_whole_body: Cell::new(false),
151 enclosing_breakables: RefCell::new(EnclosingBreakables {
152 stack: Vec::new(),
153 by_id: Default::default(),
154 }),
155 root_ctxt,
156 diverging_fallback_has_occurred: Cell::new(false),
157 trait_ascriptions: Default::default(),
158 has_rustc_attrs: root_ctxt.tcx.features().rustc_attrs(),
159 }
160 }
161
162 pub(crate) fn typing_mode(&self) -> TypingMode<'tcx, CantBeErased> {
163 self.infcx.typing_mode_raw().assert_not_erased()
166 }
167
168 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'a> {
169 self.root_ctxt.infcx.dcx()
170 }
171
172 pub(crate) fn cause(
173 &self,
174 span: Span,
175 code: ObligationCauseCode<'tcx>,
176 ) -> ObligationCause<'tcx> {
177 ObligationCause::new(span, self.body_def_id, code)
178 }
179
180 pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> {
181 self.cause(span, ObligationCauseCode::Misc)
182 }
183
184 pub(crate) fn sess(&self) -> &Session {
185 self.tcx.sess
186 }
187
188 pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> {
194 TypeErrCtxt {
195 infcx: &self.infcx,
196 param_env: Some(self.param_env),
197 typeck_results: Some(self.typeck_results.borrow()),
198 diverging_fallback_has_occurred: self.diverging_fallback_has_occurred.get(),
199 autoderef_steps: Box::new(|ty| {
200 let mut autoderef = self.autoderef(DUMMY_SP, ty).silence_errors();
201 let mut steps = ::alloc::vec::Vec::new()vec![];
202 while let Some((ty, _)) = autoderef.next() {
203 steps.push((ty, autoderef.current_obligations()));
204 }
205 steps
206 }),
207 infer_closure_kind: Box::new(|closure_def_id| {
208 self.infer_closure_kind_for_diagnostic(closure_def_id)
209 }),
210 }
211 }
212}
213
214impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
215 type Target = TypeckRootCtxt<'tcx>;
216 fn deref(&self) -> &Self::Target {
217 self.root_ctxt
218 }
219}
220
221impl<'tcx> rustc_hir_pretty::PpAnn for FnCtxt<'_, 'tcx> {
222 fn nested(&self, state: &mut rustc_hir_pretty::State<'_>, nested: rustc_hir_pretty::Nested) {
223 rustc_hir_pretty::PpAnn::nested(
224 &(&self.tcx as &dyn rustc_hir::intravisit::HirTyCtxt<'_>),
225 state,
226 nested,
227 )
228 }
229}
230
231impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> {
232 fn tcx(&self) -> TyCtxt<'tcx> {
233 self.tcx
234 }
235
236 fn dcx(&self) -> DiagCtxtHandle<'_> {
237 self.root_ctxt.dcx()
238 }
239
240 fn item_def_id(&self) -> LocalDefId {
241 self.body_def_id
242 }
243
244 fn mod_id(&self) -> LocalModId {
245 self.mod_id
246 }
247
248 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
249 let v = match reason {
250 RegionInferReason::Param(def) => {
251 RegionVariableOrigin::RegionParameterDefinition(span, def.name)
252 }
253 _ => RegionVariableOrigin::Misc(span),
254 };
255 self.next_region_var(v)
256 }
257
258 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
259 match param {
260 Some(param) => self.var_for_def(span, param).as_type().unwrap(),
261 None => self.next_ty_var(span),
262 }
263 }
264
265 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
266 match param {
268 Some(param) => self.var_for_def(span, param).as_const().unwrap(),
269 None => self.next_const_var(span),
270 }
271 }
272
273 fn register_trait_ascription_bounds(
274 &self,
275 bounds: Vec<(ty::Clause<'tcx>, Span)>,
276 hir_id: HirId,
277 _span: Span,
278 ) {
279 for (clause, span) in bounds {
280 if clause.has_escaping_bound_vars() {
281 self.dcx().span_delayed_bug(span, "clause should have no escaping bound vars");
282 continue;
283 }
284
285 self.trait_ascriptions.borrow_mut().entry(hir_id.local_id).or_default().push(clause);
286
287 let clause = self.normalize(span, Unnormalized::new_wip(clause));
288 self.register_predicate(Obligation::new(
289 self.tcx,
290 self.misc(span),
291 self.param_env,
292 clause,
293 ));
294 }
295 }
296
297 fn probe_ty_param_bounds(
298 &self,
299 _: Span,
300 def_id: LocalDefId,
301 _: Ident,
302 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
303 let tcx = self.tcx;
304 let item_def_id = tcx.hir_ty_param_owner(def_id);
305 let generics = tcx.generics_of(item_def_id);
306 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
307 let span = tcx.def_span(def_id);
309
310 ty::EarlyBinder::bind_iter(
311 tcx.arena.alloc_from_iter(
312 self.param_env
313 .caller_bounds()
314 .trait_clauses(tcx)
315 .validate_self_ty(|actual_self_ty| actual_self_ty.is_param(index))
316 .interned()
317 .iter()
318 .map(|trait_clause| {
319 (ty::set_aliases_to_non_rigid(tcx, trait_clause).skip_norm_wip(), span)
320 }),
321 ),
322 )
323 }
324
325 fn select_inherent_assoc_candidates(
326 &self,
327 span: Span,
328 self_ty: Ty<'tcx>,
329 candidates: Vec<InherentAssocCandidate>,
330 ) -> (Vec<InherentAssocCandidate>, ThinVec<FulfillmentError<'tcx>>) {
331 let tcx = self.tcx();
332 let infcx = &self.infcx;
333 let mut fulfillment_errors = ::thin_vec::ThinVec::new()thin_vec![];
334
335 let mut filter_iat_candidate = |self_ty, impl_| {
336 let ocx = ObligationCtxt::new_with_diagnostics(self);
337 let self_ty = ocx.normalize(
338 &ObligationCause::dummy(),
339 self.param_env,
340 Unnormalized::new_wip(self_ty),
341 );
342
343 let impl_args = infcx.fresh_args_for_item(span, impl_);
344 let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
345 let impl_ty = ocx.normalize(&ObligationCause::dummy(), self.param_env, impl_ty);
346
347 if ocx.eq(&ObligationCause::dummy(), self.param_env, impl_ty, self_ty).is_err() {
349 return false;
350 }
351
352 let impl_bounds = tcx.clauses_of(impl_).instantiate(tcx, impl_args);
354 let impl_obligations = traits::predicates_for_generics(
355 |_, _| ObligationCause::dummy(),
356 |clause| ocx.normalize(&ObligationCause::dummy(), self.param_env, clause),
357 self.param_env,
358 impl_bounds,
359 );
360 ocx.register_obligations(impl_obligations);
361
362 let errors = ocx.try_evaluate_obligations();
363 if let TraitErrors::HasErrors(mut errors) = errors {
364 fulfillment_errors.append(&mut errors);
365 return false;
366 }
367
368 true
369 };
370
371 let mut universes = if self_ty.has_escaping_bound_vars() {
372 ::alloc::vec::from_elem_global(None,
self_ty.outer_exclusive_binder().as_usize())vec![None; self_ty.outer_exclusive_binder().as_usize()]
373 } else {
374 ::alloc::vec::Vec::new()vec![]
375 };
376
377 let candidates =
378 traits::with_replaced_escaping_bound_vars(infcx, &mut universes, self_ty, |self_ty| {
379 candidates
380 .into_iter()
381 .filter(|&InherentAssocCandidate { impl_, .. }| {
382 infcx.probe(|_| filter_iat_candidate(self_ty, impl_))
383 })
384 .collect()
385 });
386
387 (candidates, fulfillment_errors)
388 }
389
390 fn lower_assoc_item_path(
391 &self,
392 span: Span,
393 item_def_id: DefId,
394 item_segment: &rustc_hir::PathSegment<'_>,
395 poly_trait_ref: ty::PolyTraitRef<'tcx>,
396 ) -> Result<(DefId, ty::GenericArgs<'tcx>), ErrorGuaranteed> {
397 let trait_ref = self.instantiate_binder_with_fresh_vars(
398 span,
399 infer::BoundRegionConversionTime::AssocTypeProjection(item_def_id),
401 poly_trait_ref,
402 );
403
404 let item_args = self.lowerer().lower_generic_args_of_assoc_item(
405 span,
406 item_def_id,
407 item_segment,
408 trait_ref.args,
409 );
410
411 Ok((item_def_id, item_args))
412 }
413
414 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
415 match ty.kind() {
416 ty::Adt(adt_def, _) => Some(*adt_def),
417 ty::Alias(
419 _,
420 ty::AliasTy {
421 kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },
422 ..
423 },
424 ) if !ty.has_escaping_bound_vars() => {
425 self.normalize(span, Unnormalized::new_wip(ty)).ty_adt_def()
426 }
427 _ => None,
428 }
429 }
430
431 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span) {
432 let ty = if !ty.has_escaping_bound_vars() {
434 if let ty::Alias(
439 _,
440 ty::AliasTy { kind: ty::Projection { def_id } | ty::Free { def_id }, args, .. },
441 ) = ty.kind()
442 {
443 self.add_required_obligations_for_hir(span, *def_id, *args, hir_id);
444 }
445
446 self.normalize(span, Unnormalized::new_wip(ty))
447 } else {
448 ty
449 };
450 self.write_ty(hir_id, ty)
451 }
452
453 fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> {
454 Some(&self.infcx)
455 }
456
457 fn lower_fn_sig(
458 &self,
459 decl: &rustc_hir::FnDecl<'_>,
460 _generics: Option<&rustc_hir::Generics<'_>>,
461 _hir_id: rustc_hir::HirId,
462 _hir_ty: Option<&hir::Ty<'_>>,
463 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
464 let input_tys = decl.inputs.iter().map(|a| self.lowerer().lower_ty(a)).collect();
465
466 let output_ty = match decl.output {
467 hir::FnRetTy::Return(output) => self.lowerer().lower_ty(output),
468 hir::FnRetTy::DefaultReturn(..) => self.tcx().types.unit,
469 };
470 (input_tys, output_ty)
471 }
472
473 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
474 self.tcx.dyn_compatibility_violations(trait_def_id).to_vec()
475 }
476}
477
478#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
::core::clone::TrivialClone for LoweredTy<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for LoweredTy<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone, #[automatically_derived]impl<'tcx> ::core::marker::Copy for LoweredTy<'tcx> {
}Copy, #[automatically_derived]impl<'tcx> ::core::fmt::Debug for LoweredTy<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"LoweredTy raw normalized", &self.raw, &&self.normalized)
}
}Debug)]
484pub(crate) struct LoweredTy<'tcx> {
485 pub raw: Ty<'tcx>,
487
488 pub normalized: Ty<'tcx>,
490}
491
492impl<'tcx> LoweredTy<'tcx> {
493 fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> {
494 let normalized = fcx.normalize(span, Unnormalized::new_wip(raw));
495 LoweredTy { raw, normalized }
496 }
497}