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
11use rustc_errors::DiagCtxtHandle;
12use rustc_hir::attrs::{DivergingBlockBehavior, DivergingFallbackBehavior};
13use rustc_hir::def_id::{DefId, LocalDefId};
14use rustc_hir::{self as hir, HirId, ItemLocalMap, find_attr};
15use rustc_hir_analysis::hir_ty_lowering::{
16 HirTyLowerer, InherentAssocCandidate, RegionInferReason,
17};
18use rustc_infer::infer::{self, RegionVariableOrigin};
19use rustc_infer::traits::{DynCompatibilityViolation, Obligation};
20use rustc_middle::ty::{
21 self, CantBeErased, Const, Flags, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized,
22};
23use rustc_session::Session;
24use rustc_span::{self, DUMMY_SP, ErrorGuaranteed, Ident, Span};
25use rustc_trait_selection::error_reporting::TypeErrCtxt;
26use rustc_trait_selection::traits::{
27 self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
28};
29
30use crate::coercion::CoerceMany;
31use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
32
33pub(crate) struct FnCtxt<'a, 'tcx> {
45 pub(super) body_id: LocalDefId,
46
47 pub(super) param_env: ty::ParamEnv<'tcx>,
54
55 pub(super) ret_coercion: Option<RefCell<CoerceMany<'tcx>>>,
66
67 pub(super) ret_coercion_span: Cell<Option<Span>>,
69
70 pub(super) coroutine_types: Option<CoroutineTypes<'tcx>>,
71
72 pub(super) diverges: Cell<Diverges>,
106
107 pub(super) function_diverges_because_of_empty_arguments: Cell<Diverges>,
110
111 pub(super) is_whole_body: Cell<bool>,
113
114 pub(super) enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>,
115
116 pub(super) root_ctxt: &'a TypeckRootCtxt<'tcx>,
117
118 pub(super) diverging_fallback_has_occurred: Cell<bool>,
121
122 pub(super) diverging_fallback_behavior: DivergingFallbackBehavior,
123 pub(super) diverging_block_behavior: DivergingBlockBehavior,
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_id: LocalDefId,
141 ) -> FnCtxt<'a, 'tcx> {
142 let (diverging_fallback_behavior, diverging_block_behavior) =
143 never_type_behavior(root_ctxt.tcx);
144 FnCtxt {
145 body_id,
146 param_env,
147 ret_coercion: None,
148 ret_coercion_span: Cell::new(None),
149 coroutine_types: None,
150 diverges: Cell::new(Diverges::Maybe),
151 function_diverges_because_of_empty_arguments: Cell::new(Diverges::Maybe),
152 is_whole_body: Cell::new(false),
153 enclosing_breakables: RefCell::new(EnclosingBreakables {
154 stack: Vec::new(),
155 by_id: Default::default(),
156 }),
157 root_ctxt,
158 diverging_fallback_has_occurred: Cell::new(false),
159 diverging_fallback_behavior,
160 diverging_block_behavior,
161 trait_ascriptions: Default::default(),
162 has_rustc_attrs: root_ctxt.tcx.features().rustc_attrs(),
163 }
164 }
165
166 pub(crate) fn typing_mode(&self) -> TypingMode<'tcx, CantBeErased> {
167 self.infcx.typing_mode_raw().assert_not_erased()
170 }
171
172 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'a> {
173 self.root_ctxt.infcx.dcx()
174 }
175
176 pub(crate) fn cause(
177 &self,
178 span: Span,
179 code: ObligationCauseCode<'tcx>,
180 ) -> ObligationCause<'tcx> {
181 ObligationCause::new(span, self.body_id, code)
182 }
183
184 pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> {
185 self.cause(span, ObligationCauseCode::Misc)
186 }
187
188 pub(crate) fn sess(&self) -> &Session {
189 self.tcx.sess
190 }
191
192 pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> {
198 TypeErrCtxt {
199 infcx: &self.infcx,
200 param_env: Some(self.param_env),
201 typeck_results: Some(self.typeck_results.borrow()),
202 diverging_fallback_has_occurred: self.diverging_fallback_has_occurred.get(),
203 autoderef_steps: Box::new(|ty| {
204 let mut autoderef = self.autoderef(DUMMY_SP, ty).silence_errors();
205 let mut steps = ::alloc::vec::Vec::new()vec![];
206 while let Some((ty, _)) = autoderef.next() {
207 steps.push((ty, autoderef.current_obligations()));
208 }
209 steps
210 }),
211 }
212 }
213}
214
215impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
216 type Target = TypeckRootCtxt<'tcx>;
217 fn deref(&self) -> &Self::Target {
218 self.root_ctxt
219 }
220}
221
222impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> {
223 fn tcx(&self) -> TyCtxt<'tcx> {
224 self.tcx
225 }
226
227 fn dcx(&self) -> DiagCtxtHandle<'_> {
228 self.root_ctxt.dcx()
229 }
230
231 fn item_def_id(&self) -> LocalDefId {
232 self.body_id
233 }
234
235 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
236 let v = match reason {
237 RegionInferReason::Param(def) => {
238 RegionVariableOrigin::RegionParameterDefinition(span, def.name)
239 }
240 _ => RegionVariableOrigin::Misc(span),
241 };
242 self.next_region_var(v)
243 }
244
245 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
246 match param {
247 Some(param) => self.var_for_def(span, param).as_type().unwrap(),
248 None => self.next_ty_var(span),
249 }
250 }
251
252 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
253 match param {
255 Some(param) => self.var_for_def(span, param).as_const().unwrap(),
256 None => self.next_const_var(span),
257 }
258 }
259
260 fn register_trait_ascription_bounds(
261 &self,
262 bounds: Vec<(ty::Clause<'tcx>, Span)>,
263 hir_id: HirId,
264 _span: Span,
265 ) {
266 for (clause, span) in bounds {
267 if clause.has_escaping_bound_vars() {
268 self.dcx().span_delayed_bug(span, "clause should have no escaping bound vars");
269 continue;
270 }
271
272 self.trait_ascriptions.borrow_mut().entry(hir_id.local_id).or_default().push(clause);
273
274 let clause = self.normalize(span, Unnormalized::new_wip(clause));
275 self.register_predicate(Obligation::new(
276 self.tcx,
277 self.misc(span),
278 self.param_env,
279 clause,
280 ));
281 }
282 }
283
284 fn probe_ty_param_bounds(
285 &self,
286 _: Span,
287 def_id: LocalDefId,
288 _: Ident,
289 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
290 let tcx = self.tcx;
291 let item_def_id = tcx.hir_ty_param_owner(def_id);
292 let generics = tcx.generics_of(item_def_id);
293 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
294 let span = tcx.def_span(def_id);
296
297 ty::EarlyBinder::bind(tcx.arena.alloc_from_iter(
298 self.param_env.caller_bounds().iter().filter_map(|predicate| {
299 match predicate.kind().skip_binder() {
300 ty::ClauseKind::Trait(data) if data.self_ty().is_param(index) => {
301 Some((predicate, span))
302 }
303 _ => None,
304 }
305 }),
306 ))
307 }
308
309 fn select_inherent_assoc_candidates(
310 &self,
311 span: Span,
312 self_ty: Ty<'tcx>,
313 candidates: Vec<InherentAssocCandidate>,
314 ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>) {
315 let tcx = self.tcx();
316 let infcx = &self.infcx;
317 let mut fulfillment_errors = ::alloc::vec::Vec::new()vec![];
318
319 let mut filter_iat_candidate = |self_ty, impl_| {
320 let ocx = ObligationCtxt::new_with_diagnostics(self);
321 let self_ty = ocx.normalize(
322 &ObligationCause::dummy(),
323 self.param_env,
324 Unnormalized::new_wip(self_ty),
325 );
326
327 let impl_args = infcx.fresh_args_for_item(span, impl_);
328 let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
329 let impl_ty = ocx.normalize(&ObligationCause::dummy(), self.param_env, impl_ty);
330
331 if ocx.eq(&ObligationCause::dummy(), self.param_env, impl_ty, self_ty).is_err() {
333 return false;
334 }
335
336 let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args);
338 let impl_obligations = traits::predicates_for_generics(
339 |_, _| ObligationCause::dummy(),
340 |pred| ocx.normalize(&ObligationCause::dummy(), self.param_env, pred),
341 self.param_env,
342 impl_bounds,
343 );
344 ocx.register_obligations(impl_obligations);
345
346 let mut errors = ocx.try_evaluate_obligations();
347 if !errors.is_empty() {
348 fulfillment_errors.append(&mut errors);
349 return false;
350 }
351
352 true
353 };
354
355 let mut universes = if self_ty.has_escaping_bound_vars() {
356 ::alloc::vec::from_elem(None, self_ty.outer_exclusive_binder().as_usize())vec![None; self_ty.outer_exclusive_binder().as_usize()]
357 } else {
358 ::alloc::vec::Vec::new()vec![]
359 };
360
361 let candidates =
362 traits::with_replaced_escaping_bound_vars(infcx, &mut universes, self_ty, |self_ty| {
363 candidates
364 .into_iter()
365 .filter(|&InherentAssocCandidate { impl_, .. }| {
366 infcx.probe(|_| filter_iat_candidate(self_ty, impl_))
367 })
368 .collect()
369 });
370
371 (candidates, fulfillment_errors)
372 }
373
374 fn lower_assoc_item_path(
375 &self,
376 span: Span,
377 item_def_id: DefId,
378 item_segment: &rustc_hir::PathSegment<'tcx>,
379 poly_trait_ref: ty::PolyTraitRef<'tcx>,
380 ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
381 let trait_ref = self.instantiate_binder_with_fresh_vars(
382 span,
383 infer::BoundRegionConversionTime::AssocTypeProjection(item_def_id),
385 poly_trait_ref,
386 );
387
388 let item_args = self.lowerer().lower_generic_args_of_assoc_item(
389 span,
390 item_def_id,
391 item_segment,
392 trait_ref.args,
393 );
394
395 Ok((item_def_id, item_args))
396 }
397
398 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
399 match ty.kind() {
400 ty::Adt(adt_def, _) => Some(*adt_def),
401 ty::Alias(ty::AliasTy {
403 kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },
404 ..
405 }) if !ty.has_escaping_bound_vars() => {
406 self.normalize(span, Unnormalized::new_wip(ty)).ty_adt_def()
407 }
408 _ => None,
409 }
410 }
411
412 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span) {
413 let ty = if !ty.has_escaping_bound_vars() {
415 if let ty::Alias(ty::AliasTy {
420 kind: ty::Projection { def_id } | ty::Free { def_id },
421 args,
422 ..
423 }) = ty.kind()
424 {
425 self.add_required_obligations_for_hir(span, *def_id, args, hir_id);
426 }
427
428 self.normalize(span, Unnormalized::new_wip(ty))
429 } else {
430 ty
431 };
432 self.write_ty(hir_id, ty)
433 }
434
435 fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> {
436 Some(&self.infcx)
437 }
438
439 fn lower_fn_sig(
440 &self,
441 decl: &rustc_hir::FnDecl<'tcx>,
442 _generics: Option<&rustc_hir::Generics<'_>>,
443 _hir_id: rustc_hir::HirId,
444 _hir_ty: Option<&hir::Ty<'_>>,
445 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
446 let input_tys = decl.inputs.iter().map(|a| self.lowerer().lower_ty(a)).collect();
447
448 let output_ty = match decl.output {
449 hir::FnRetTy::Return(output) => self.lowerer().lower_ty(output),
450 hir::FnRetTy::DefaultReturn(..) => self.tcx().types.unit,
451 };
452 (input_tys, output_ty)
453 }
454
455 fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
456 self.tcx.dyn_compatibility_violations(trait_def_id).to_vec()
457 }
458}
459
460#[derive(#[automatically_derived]
impl<'tcx> ::core::clone::Clone for LoweredTy<'tcx> {
#[inline]
fn clone(&self) -> LoweredTy<'tcx> {
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", &self.raw, "normalized", &&self.normalized)
}
}Debug)]
466pub(crate) struct LoweredTy<'tcx> {
467 pub raw: Ty<'tcx>,
469
470 pub normalized: Ty<'tcx>,
472}
473
474impl<'tcx> LoweredTy<'tcx> {
475 fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> {
476 let normalized = fcx.normalize(span, Unnormalized::new_wip(raw));
477 LoweredTy { raw, normalized }
478 }
479}
480
481fn never_type_behavior(tcx: TyCtxt<'_>) -> (DivergingFallbackBehavior, DivergingBlockBehavior) {
482 let (fallback, block) = parse_never_type_options_attr(tcx);
483 let fallback = fallback.unwrap_or_else(|| default_fallback(tcx));
484 let block = block.unwrap_or_default();
485
486 (fallback, block)
487}
488
489fn default_fallback(tcx: TyCtxt<'_>) -> DivergingFallbackBehavior {
491 if tcx.sess.edition().at_least_rust_2024() {
493 return DivergingFallbackBehavior::ToNever;
494 }
495
496 DivergingFallbackBehavior::ToUnit
498}
499
500fn parse_never_type_options_attr(
501 tcx: TyCtxt<'_>,
502) -> (Option<DivergingFallbackBehavior>, Option<DivergingBlockBehavior>) {
503 {
'done:
{
for i in tcx.hir_krate_attrs() {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcNeverTypeOptions {
fallback, diverging_block_default }) => {
break 'done Some((*fallback, *diverging_block_default));
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(tcx, crate, RustcNeverTypeOptions {fallback, diverging_block_default} => (*fallback, *diverging_block_default)).unwrap_or_default()
507}