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 hir::def_id::CRATE_DEF_ID;
12use rustc_errors::DiagCtxtHandle;
13use rustc_hir::def_id::{DefId, LocalDefId};
14use rustc_hir::{self as hir, HirId, ItemLocalMap};
15use rustc_hir_analysis::hir_ty_lowering::{HirTyLowerer, RegionInferReason};
16use rustc_infer::infer;
17use rustc_infer::traits::Obligation;
18use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeVisitableExt};
19use rustc_session::Session;
20use rustc_span::{self, DUMMY_SP, ErrorGuaranteed, Ident, Span, sym};
21use rustc_trait_selection::error_reporting::TypeErrCtxt;
22use rustc_trait_selection::error_reporting::infer::sub_relations::SubRelations;
23use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode, ObligationCtxt};
24
25use crate::coercion::DynamicCoerceMany;
26use crate::fallback::DivergingFallbackBehavior;
27use crate::fn_ctxt::checks::DivergingBlockBehavior;
28use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
29
30pub(crate) struct FnCtxt<'a, 'tcx> {
42 pub(super) body_id: LocalDefId,
43
44 pub(super) param_env: ty::ParamEnv<'tcx>,
51
52 pub(super) ret_coercion: Option<RefCell<DynamicCoerceMany<'tcx>>>,
63
64 pub(super) ret_coercion_span: Cell<Option<Span>>,
66
67 pub(super) coroutine_types: Option<CoroutineTypes<'tcx>>,
68
69 pub(super) diverges: Cell<Diverges>,
101
102 pub(super) function_diverges_because_of_empty_arguments: Cell<Diverges>,
105
106 pub(super) is_whole_body: Cell<bool>,
108
109 pub(super) enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>,
110
111 pub(super) root_ctxt: &'a TypeckRootCtxt<'tcx>,
112
113 pub(super) fallback_has_occurred: Cell<bool>,
114
115 pub(super) diverging_fallback_behavior: DivergingFallbackBehavior,
116 pub(super) diverging_block_behavior: DivergingBlockBehavior,
117
118 pub(super) trait_ascriptions: RefCell<ItemLocalMap<Vec<ty::Clause<'tcx>>>>,
123}
124
125impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
126 pub(crate) fn new(
127 root_ctxt: &'a TypeckRootCtxt<'tcx>,
128 param_env: ty::ParamEnv<'tcx>,
129 body_id: LocalDefId,
130 ) -> FnCtxt<'a, 'tcx> {
131 let (diverging_fallback_behavior, diverging_block_behavior) =
132 never_type_behavior(root_ctxt.tcx);
133 FnCtxt {
134 body_id,
135 param_env,
136 ret_coercion: None,
137 ret_coercion_span: Cell::new(None),
138 coroutine_types: None,
139 diverges: Cell::new(Diverges::Maybe),
140 function_diverges_because_of_empty_arguments: Cell::new(Diverges::Maybe),
141 is_whole_body: Cell::new(false),
142 enclosing_breakables: RefCell::new(EnclosingBreakables {
143 stack: Vec::new(),
144 by_id: Default::default(),
145 }),
146 root_ctxt,
147 fallback_has_occurred: Cell::new(false),
148 diverging_fallback_behavior,
149 diverging_block_behavior,
150 trait_ascriptions: Default::default(),
151 }
152 }
153
154 pub(crate) fn dcx(&self) -> DiagCtxtHandle<'a> {
155 self.root_ctxt.infcx.dcx()
156 }
157
158 pub(crate) fn cause(
159 &self,
160 span: Span,
161 code: ObligationCauseCode<'tcx>,
162 ) -> ObligationCause<'tcx> {
163 ObligationCause::new(span, self.body_id, code)
164 }
165
166 pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> {
167 self.cause(span, ObligationCauseCode::Misc)
168 }
169
170 pub(crate) fn sess(&self) -> &Session {
171 self.tcx.sess
172 }
173
174 pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> {
180 let mut sub_relations = SubRelations::default();
181 sub_relations.add_constraints(
182 self,
183 self.fulfillment_cx.borrow_mut().pending_obligations().iter().map(|o| o.predicate),
184 );
185 TypeErrCtxt {
186 infcx: &self.infcx,
187 sub_relations: RefCell::new(sub_relations),
188 typeck_results: Some(self.typeck_results.borrow()),
189 fallback_has_occurred: self.fallback_has_occurred.get(),
190 normalize_fn_sig: Box::new(|fn_sig| {
191 if fn_sig.has_escaping_bound_vars() {
192 return fn_sig;
193 }
194 self.probe(|_| {
195 let ocx = ObligationCtxt::new(self);
196 let normalized_fn_sig =
197 ocx.normalize(&ObligationCause::dummy(), self.param_env, fn_sig);
198 if ocx.select_all_or_error().is_empty() {
199 let normalized_fn_sig = self.resolve_vars_if_possible(normalized_fn_sig);
200 if !normalized_fn_sig.has_infer() {
201 return normalized_fn_sig;
202 }
203 }
204 fn_sig
205 })
206 }),
207 autoderef_steps: Box::new(|ty| {
208 let mut autoderef = self.autoderef(DUMMY_SP, ty).silence_errors();
209 let mut steps = vec![];
210 while let Some((ty, _)) = autoderef.next() {
211 steps.push((ty, autoderef.current_obligations()));
212 }
213 steps
214 }),
215 }
216 }
217}
218
219impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
220 type Target = TypeckRootCtxt<'tcx>;
221 fn deref(&self) -> &Self::Target {
222 self.root_ctxt
223 }
224}
225
226impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> {
227 fn tcx(&self) -> TyCtxt<'tcx> {
228 self.tcx
229 }
230
231 fn dcx(&self) -> DiagCtxtHandle<'_> {
232 self.root_ctxt.dcx()
233 }
234
235 fn item_def_id(&self) -> LocalDefId {
236 self.body_id
237 }
238
239 fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
240 let v = match reason {
241 RegionInferReason::Param(def) => infer::RegionParameterDefinition(span, def.name),
242 _ => infer::MiscVariable(span),
243 };
244 self.next_region_var(v)
245 }
246
247 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
248 match param {
249 Some(param) => self.var_for_def(span, param).as_type().unwrap(),
250 None => self.next_ty_var(span),
251 }
252 }
253
254 fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
255 match param {
257 Some(param) => self.var_for_def(span, param).as_const().unwrap(),
258 None => self.next_const_var(span),
259 }
260 }
261
262 fn register_trait_ascription_bounds(
263 &self,
264 bounds: Vec<(ty::Clause<'tcx>, Span)>,
265 hir_id: HirId,
266 _span: Span,
267 ) {
268 for (clause, span) in bounds {
269 if clause.has_escaping_bound_vars() {
270 self.dcx().span_delayed_bug(span, "clause should have no escaping bound vars");
271 continue;
272 }
273
274 self.trait_ascriptions.borrow_mut().entry(hir_id.local_id).or_default().push(clause);
275
276 let clause = self.normalize(span, clause);
277 self.register_predicate(Obligation::new(
278 self.tcx,
279 self.misc(span),
280 self.param_env,
281 clause,
282 ));
283 }
284 }
285
286 fn probe_ty_param_bounds(
287 &self,
288 _: Span,
289 def_id: LocalDefId,
290 _: Ident,
291 ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
292 let tcx = self.tcx;
293 let item_def_id = tcx.hir_ty_param_owner(def_id);
294 let generics = tcx.generics_of(item_def_id);
295 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
296 let span = tcx.def_span(def_id);
298
299 ty::EarlyBinder::bind(tcx.arena.alloc_from_iter(
300 self.param_env.caller_bounds().iter().filter_map(|predicate| {
301 match predicate.kind().skip_binder() {
302 ty::ClauseKind::Trait(data) if data.self_ty().is_param(index) => {
303 Some((predicate, span))
304 }
305 _ => None,
306 }
307 }),
308 ))
309 }
310
311 fn lower_assoc_shared(
312 &self,
313 span: Span,
314 item_def_id: DefId,
315 item_segment: &rustc_hir::PathSegment<'tcx>,
316 poly_trait_ref: ty::PolyTraitRef<'tcx>,
317 _assoc_tag: ty::AssocTag,
318 ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
319 let trait_ref = self.instantiate_binder_with_fresh_vars(
320 span,
321 infer::BoundRegionConversionTime::AssocTypeProjection(item_def_id),
323 poly_trait_ref,
324 );
325
326 let item_args = self.lowerer().lower_generic_args_of_assoc_item(
327 span,
328 item_def_id,
329 item_segment,
330 trait_ref.args,
331 );
332
333 Ok((item_def_id, item_args))
334 }
335
336 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
337 match ty.kind() {
338 ty::Adt(adt_def, _) => Some(*adt_def),
339 ty::Alias(ty::Projection | ty::Inherent | ty::Free, _)
341 if !ty.has_escaping_bound_vars() =>
342 {
343 if self.next_trait_solver() {
344 self.try_structurally_resolve_type(span, ty).ty_adt_def()
345 } else {
346 self.normalize(span, ty).ty_adt_def()
347 }
348 }
349 _ => None,
350 }
351 }
352
353 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span) {
354 let ty = if !ty.has_escaping_bound_vars() {
356 if let ty::Alias(ty::Projection | ty::Free, ty::AliasTy { args, def_id, .. }) =
361 ty.kind()
362 {
363 self.add_required_obligations_for_hir(span, *def_id, args, hir_id);
364 }
365
366 self.normalize(span, ty)
367 } else {
368 ty
369 };
370 self.write_ty(hir_id, ty)
371 }
372
373 fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> {
374 Some(&self.infcx)
375 }
376
377 fn lower_fn_sig(
378 &self,
379 decl: &rustc_hir::FnDecl<'tcx>,
380 _generics: Option<&rustc_hir::Generics<'_>>,
381 _hir_id: rustc_hir::HirId,
382 _hir_ty: Option<&hir::Ty<'_>>,
383 ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
384 let input_tys = decl.inputs.iter().map(|a| self.lowerer().lower_arg_ty(a, None)).collect();
385
386 let output_ty = match decl.output {
387 hir::FnRetTy::Return(output) => self.lowerer().lower_ty(output),
388 hir::FnRetTy::DefaultReturn(..) => self.tcx().types.unit,
389 };
390 (input_tys, output_ty)
391 }
392}
393
394#[derive(Clone, Copy, Debug)]
400pub(crate) struct LoweredTy<'tcx> {
401 pub raw: Ty<'tcx>,
403
404 pub normalized: Ty<'tcx>,
406}
407
408impl<'tcx> LoweredTy<'tcx> {
409 fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> {
410 let normalized = if fcx.next_trait_solver() {
414 fcx.try_structurally_resolve_type(span, raw)
415 } else {
416 fcx.normalize(span, raw)
417 };
418 LoweredTy { raw, normalized }
419 }
420}
421
422fn never_type_behavior(tcx: TyCtxt<'_>) -> (DivergingFallbackBehavior, DivergingBlockBehavior) {
423 let (fallback, block) = parse_never_type_options_attr(tcx);
424 let fallback = fallback.unwrap_or_else(|| default_fallback(tcx));
425 let block = block.unwrap_or_default();
426
427 (fallback, block)
428}
429
430fn default_fallback(tcx: TyCtxt<'_>) -> DivergingFallbackBehavior {
432 if tcx.sess.edition().at_least_rust_2024() {
434 return DivergingFallbackBehavior::ToNever;
435 }
436
437 if tcx.features().never_type_fallback() {
439 return DivergingFallbackBehavior::ContextDependent;
440 }
441
442 DivergingFallbackBehavior::ToUnit
444}
445
446fn parse_never_type_options_attr(
447 tcx: TyCtxt<'_>,
448) -> (Option<DivergingFallbackBehavior>, Option<DivergingBlockBehavior>) {
449 let mut fallback = None;
453 let mut block = None;
454
455 let items = tcx
456 .get_attr(CRATE_DEF_ID, sym::rustc_never_type_options)
457 .map(|attr| attr.meta_item_list().unwrap())
458 .unwrap_or_default();
459
460 for item in items {
461 if item.has_name(sym::fallback) && fallback.is_none() {
462 let mode = item.value_str().unwrap();
463 match mode {
464 sym::unit => fallback = Some(DivergingFallbackBehavior::ToUnit),
465 sym::niko => fallback = Some(DivergingFallbackBehavior::ContextDependent),
466 sym::never => fallback = Some(DivergingFallbackBehavior::ToNever),
467 sym::no => fallback = Some(DivergingFallbackBehavior::NoFallback),
468 _ => {
469 tcx.dcx().span_err(item.span(), format!("unknown never type fallback mode: `{mode}` (supported: `unit`, `niko`, `never` and `no`)"));
470 }
471 };
472 continue;
473 }
474
475 if item.has_name(sym::diverging_block_default) && block.is_none() {
476 let default = item.value_str().unwrap();
477 match default {
478 sym::unit => block = Some(DivergingBlockBehavior::Unit),
479 sym::never => block = Some(DivergingBlockBehavior::Never),
480 _ => {
481 tcx.dcx().span_err(item.span(), format!("unknown diverging block default: `{default}` (supported: `unit` and `never`)"));
482 }
483 };
484 continue;
485 }
486
487 tcx.dcx().span_err(
488 item.span(),
489 format!(
490 "unknown or duplicate never type option: `{}` (supported: `fallback`, `diverging_block_default`)",
491 item.name().unwrap()
492 ),
493 );
494 }
495
496 (fallback, block)
497}