rustc_hir_typeck/fn_ctxt/
mod.rs

1mod _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::{
16    HirTyLowerer, InherentAssocCandidate, RegionInferReason,
17};
18use rustc_infer::infer::{self, RegionVariableOrigin};
19use rustc_infer::traits::{DynCompatibilityViolation, Obligation};
20use rustc_middle::ty::{self, Const, Ty, TyCtxt, TypeVisitableExt};
21use rustc_session::Session;
22use rustc_span::{self, DUMMY_SP, ErrorGuaranteed, Ident, Span, sym};
23use rustc_trait_selection::error_reporting::TypeErrCtxt;
24use rustc_trait_selection::traits::{
25    self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
26};
27
28use crate::coercion::CoerceMany;
29use crate::fallback::DivergingFallbackBehavior;
30use crate::fn_ctxt::checks::DivergingBlockBehavior;
31use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
32
33/// The `FnCtxt` stores type-checking context needed to type-check bodies of
34/// functions, closures, and `const`s, including performing type inference
35/// with [`InferCtxt`].
36///
37/// This is in contrast to `rustc_hir_analysis::collect::ItemCtxt`, which is
38/// used to type-check item *signatures* and thus does not perform type
39/// inference.
40///
41/// See `ItemCtxt`'s docs for more.
42///
43/// [`InferCtxt`]: infer::InferCtxt
44pub(crate) struct FnCtxt<'a, 'tcx> {
45    pub(super) body_id: LocalDefId,
46
47    /// The parameter environment used for proving trait obligations
48    /// in this function. This can change when we descend into
49    /// closures (as they bring new things into scope), hence it is
50    /// not part of `Inherited` (as of the time of this writing,
51    /// closures do not yet change the environment, but they will
52    /// eventually).
53    pub(super) param_env: ty::ParamEnv<'tcx>,
54
55    /// If `Some`, this stores coercion information for returned
56    /// expressions. If `None`, this is in a context where return is
57    /// inappropriate, such as a const expression.
58    ///
59    /// This is a `RefCell<CoerceMany>`, which means that we
60    /// can track all the return expressions and then use them to
61    /// compute a useful coercion from the set, similar to a match
62    /// expression or other branching context. You can use methods
63    /// like `expected_ty` to access the declared return type (if
64    /// any).
65    pub(super) ret_coercion: Option<RefCell<CoerceMany<'tcx>>>,
66
67    /// First span of a return site that we find. Used in error messages.
68    pub(super) ret_coercion_span: Cell<Option<Span>>,
69
70    pub(super) coroutine_types: Option<CoroutineTypes<'tcx>>,
71
72    /// Whether the last checked node generates a divergence (e.g.,
73    /// `return` will set this to `Always`). In general, when entering
74    /// an expression or other node in the tree, the initial value
75    /// indicates whether prior parts of the containing expression may
76    /// have diverged. It is then typically set to `Maybe` (and the
77    /// old value remembered) for processing the subparts of the
78    /// current expression. As each subpart is processed, they may set
79    /// the flag to `Always`, etc. Finally, at the end, we take the
80    /// result and "union" it with the original value, so that when we
81    /// return the flag indicates if any subpart of the parent
82    /// expression (up to and including this part) has diverged. So,
83    /// if you read it after evaluating a subexpression `X`, the value
84    /// you get indicates whether any subexpression that was
85    /// evaluating up to and including `X` diverged.
86    ///
87    /// We currently use this flag for the following purposes:
88    ///
89    /// - To warn about unreachable code: if, after processing a
90    ///   sub-expression but before we have applied the effects of the
91    ///   current node, we see that the flag is set to `Always`, we
92    ///   can issue a warning. This corresponds to something like
93    ///   `foo(return)`; we warn on the `foo()` expression. (We then
94    ///   update the flag to `WarnedAlways` to suppress duplicate
95    ///   reports.) Similarly, if we traverse to a fresh statement (or
96    ///   tail expression) from an `Always` setting, we will issue a
97    ///   warning. This corresponds to something like `{return;
98    ///   foo();}` or `{return; 22}`, where we would warn on the
99    ///   `foo()` or `22`.
100    /// - To assign the `!` type to block expressions with diverging
101    ///   statements.
102    ///
103    /// An expression represents dead code if, after checking it,
104    /// the diverges flag is set to something other than `Maybe`.
105    pub(super) diverges: Cell<Diverges>,
106
107    /// If one of the function arguments is a never pattern, this counts as diverging code.
108    /// This affect typechecking of the function body.
109    pub(super) function_diverges_because_of_empty_arguments: Cell<Diverges>,
110
111    /// Whether the currently checked node is the whole body of the function.
112    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    /// True if a divirging inference variable has been set to `()`/`!` because
119    /// of never type fallback. This is only used for diagnostics.
120    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    /// Clauses that we lowered as part of the `impl_trait_in_bindings` feature.
126    ///
127    /// These are stored here so we may collect them when canonicalizing user
128    /// type ascriptions later.
129    pub(super) trait_ascriptions: RefCell<ItemLocalMap<Vec<ty::Clause<'tcx>>>>,
130
131    /// Whether the current crate enables the `rustc_attrs` feature.
132    /// This allows to skip processing attributes in many places.
133    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 dcx(&self) -> DiagCtxtHandle<'a> {
167        self.root_ctxt.infcx.dcx()
168    }
169
170    pub(crate) fn cause(
171        &self,
172        span: Span,
173        code: ObligationCauseCode<'tcx>,
174    ) -> ObligationCause<'tcx> {
175        ObligationCause::new(span, self.body_id, code)
176    }
177
178    pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> {
179        self.cause(span, ObligationCauseCode::Misc)
180    }
181
182    pub(crate) fn sess(&self) -> &Session {
183        self.tcx.sess
184    }
185
186    /// Creates an `TypeErrCtxt` with a reference to the in-progress
187    /// `TypeckResults` which is used for diagnostics.
188    /// Use [`InferCtxtErrorExt::err_ctxt`] to start one without a `TypeckResults`.
189    ///
190    /// [`InferCtxtErrorExt::err_ctxt`]: rustc_trait_selection::error_reporting::InferCtxtErrorExt::err_ctxt
191    pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> {
192        TypeErrCtxt {
193            infcx: &self.infcx,
194            typeck_results: Some(self.typeck_results.borrow()),
195            diverging_fallback_has_occurred: self.diverging_fallback_has_occurred.get(),
196            normalize_fn_sig: Box::new(|fn_sig| {
197                if fn_sig.has_escaping_bound_vars() {
198                    return fn_sig;
199                }
200                self.probe(|_| {
201                    let ocx = ObligationCtxt::new(self);
202                    let normalized_fn_sig =
203                        ocx.normalize(&ObligationCause::dummy(), self.param_env, fn_sig);
204                    if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
205                        let normalized_fn_sig = self.resolve_vars_if_possible(normalized_fn_sig);
206                        if !normalized_fn_sig.has_infer() {
207                            return normalized_fn_sig;
208                        }
209                    }
210                    fn_sig
211                })
212            }),
213            autoderef_steps: Box::new(|ty| {
214                let mut autoderef = self.autoderef(DUMMY_SP, ty).silence_errors();
215                let mut steps = vec![];
216                while let Some((ty, _)) = autoderef.next() {
217                    steps.push((ty, autoderef.current_obligations()));
218                }
219                steps
220            }),
221        }
222    }
223}
224
225impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
226    type Target = TypeckRootCtxt<'tcx>;
227    fn deref(&self) -> &Self::Target {
228        self.root_ctxt
229    }
230}
231
232impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> {
233    fn tcx(&self) -> TyCtxt<'tcx> {
234        self.tcx
235    }
236
237    fn dcx(&self) -> DiagCtxtHandle<'_> {
238        self.root_ctxt.dcx()
239    }
240
241    fn item_def_id(&self) -> LocalDefId {
242        self.body_id
243    }
244
245    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
246        let v = match reason {
247            RegionInferReason::Param(def) => {
248                RegionVariableOrigin::RegionParameterDefinition(span, def.name)
249            }
250            _ => RegionVariableOrigin::Misc(span),
251        };
252        self.next_region_var(v)
253    }
254
255    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
256        match param {
257            Some(param) => self.var_for_def(span, param).as_type().unwrap(),
258            None => self.next_ty_var(span),
259        }
260    }
261
262    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
263        // FIXME ideally this shouldn't use unwrap
264        match param {
265            Some(param) => self.var_for_def(span, param).as_const().unwrap(),
266            None => self.next_const_var(span),
267        }
268    }
269
270    fn register_trait_ascription_bounds(
271        &self,
272        bounds: Vec<(ty::Clause<'tcx>, Span)>,
273        hir_id: HirId,
274        _span: Span,
275    ) {
276        for (clause, span) in bounds {
277            if clause.has_escaping_bound_vars() {
278                self.dcx().span_delayed_bug(span, "clause should have no escaping bound vars");
279                continue;
280            }
281
282            self.trait_ascriptions.borrow_mut().entry(hir_id.local_id).or_default().push(clause);
283
284            let clause = self.normalize(span, clause);
285            self.register_predicate(Obligation::new(
286                self.tcx,
287                self.misc(span),
288                self.param_env,
289                clause,
290            ));
291        }
292    }
293
294    fn probe_ty_param_bounds(
295        &self,
296        _: Span,
297        def_id: LocalDefId,
298        _: Ident,
299    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
300        let tcx = self.tcx;
301        let item_def_id = tcx.hir_ty_param_owner(def_id);
302        let generics = tcx.generics_of(item_def_id);
303        let index = generics.param_def_id_to_index[&def_id.to_def_id()];
304        // HACK(eddyb) should get the original `Span`.
305        let span = tcx.def_span(def_id);
306
307        ty::EarlyBinder::bind(tcx.arena.alloc_from_iter(
308            self.param_env.caller_bounds().iter().filter_map(|predicate| {
309                match predicate.kind().skip_binder() {
310                    ty::ClauseKind::Trait(data) if data.self_ty().is_param(index) => {
311                        Some((predicate, span))
312                    }
313                    _ => None,
314                }
315            }),
316        ))
317    }
318
319    fn select_inherent_assoc_candidates(
320        &self,
321        span: Span,
322        self_ty: Ty<'tcx>,
323        candidates: Vec<InherentAssocCandidate>,
324    ) -> (Vec<InherentAssocCandidate>, Vec<FulfillmentError<'tcx>>) {
325        let tcx = self.tcx();
326        let infcx = &self.infcx;
327        let mut fulfillment_errors = vec![];
328
329        let mut filter_iat_candidate = |self_ty, impl_| {
330            let ocx = ObligationCtxt::new_with_diagnostics(self);
331            let self_ty = ocx.normalize(&ObligationCause::dummy(), self.param_env, self_ty);
332
333            let impl_args = infcx.fresh_args_for_item(span, impl_);
334            let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
335            let impl_ty = ocx.normalize(&ObligationCause::dummy(), self.param_env, impl_ty);
336
337            // Check that the self types can be related.
338            if ocx.eq(&ObligationCause::dummy(), self.param_env, impl_ty, self_ty).is_err() {
339                return false;
340            }
341
342            // Check whether the impl imposes obligations we have to worry about.
343            let impl_bounds = tcx.predicates_of(impl_).instantiate(tcx, impl_args);
344            let impl_bounds = ocx.normalize(&ObligationCause::dummy(), self.param_env, impl_bounds);
345            let impl_obligations = traits::predicates_for_generics(
346                |_, _| ObligationCause::dummy(),
347                self.param_env,
348                impl_bounds,
349            );
350            ocx.register_obligations(impl_obligations);
351
352            let mut errors = ocx.try_evaluate_obligations();
353            if !errors.is_empty() {
354                fulfillment_errors.append(&mut errors);
355                return false;
356            }
357
358            true
359        };
360
361        let mut universes = if self_ty.has_escaping_bound_vars() {
362            vec![None; self_ty.outer_exclusive_binder().as_usize()]
363        } else {
364            vec![]
365        };
366
367        let candidates =
368            traits::with_replaced_escaping_bound_vars(infcx, &mut universes, self_ty, |self_ty| {
369                candidates
370                    .into_iter()
371                    .filter(|&InherentAssocCandidate { impl_, .. }| {
372                        infcx.probe(|_| filter_iat_candidate(self_ty, impl_))
373                    })
374                    .collect()
375            });
376
377        (candidates, fulfillment_errors)
378    }
379
380    fn lower_assoc_item_path(
381        &self,
382        span: Span,
383        item_def_id: DefId,
384        item_segment: &rustc_hir::PathSegment<'tcx>,
385        poly_trait_ref: ty::PolyTraitRef<'tcx>,
386    ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> {
387        let trait_ref = self.instantiate_binder_with_fresh_vars(
388            span,
389            // FIXME(mgca): `item_def_id` can be an AssocConst; rename this variant.
390            infer::BoundRegionConversionTime::AssocTypeProjection(item_def_id),
391            poly_trait_ref,
392        );
393
394        let item_args = self.lowerer().lower_generic_args_of_assoc_item(
395            span,
396            item_def_id,
397            item_segment,
398            trait_ref.args,
399        );
400
401        Ok((item_def_id, item_args))
402    }
403
404    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
405        match ty.kind() {
406            ty::Adt(adt_def, _) => Some(*adt_def),
407            // FIXME(#104767): Should we handle bound regions here?
408            ty::Alias(ty::Projection | ty::Inherent | ty::Free, _)
409                if !ty.has_escaping_bound_vars() =>
410            {
411                if self.next_trait_solver() {
412                    self.try_structurally_resolve_type(span, ty).ty_adt_def()
413                } else {
414                    self.normalize(span, ty).ty_adt_def()
415                }
416            }
417            _ => None,
418        }
419    }
420
421    fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span) {
422        // FIXME: normalization and escaping regions
423        let ty = if !ty.has_escaping_bound_vars() {
424            // NOTE: These obligations are 100% redundant and are implied by
425            // WF obligations that are registered elsewhere, but they have a
426            // better cause code assigned to them in `add_required_obligations_for_hir`.
427            // This means that they should shadow obligations with worse spans.
428            if let ty::Alias(ty::Projection | ty::Free, ty::AliasTy { args, def_id, .. }) =
429                ty.kind()
430            {
431                self.add_required_obligations_for_hir(span, *def_id, args, hir_id);
432            }
433
434            self.normalize(span, ty)
435        } else {
436            ty
437        };
438        self.write_ty(hir_id, ty)
439    }
440
441    fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> {
442        Some(&self.infcx)
443    }
444
445    fn lower_fn_sig(
446        &self,
447        decl: &rustc_hir::FnDecl<'tcx>,
448        _generics: Option<&rustc_hir::Generics<'_>>,
449        _hir_id: rustc_hir::HirId,
450        _hir_ty: Option<&hir::Ty<'_>>,
451    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
452        let input_tys = decl.inputs.iter().map(|a| self.lowerer().lower_ty(a)).collect();
453
454        let output_ty = match decl.output {
455            hir::FnRetTy::Return(output) => self.lowerer().lower_ty(output),
456            hir::FnRetTy::DefaultReturn(..) => self.tcx().types.unit,
457        };
458        (input_tys, output_ty)
459    }
460
461    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
462        self.tcx.dyn_compatibility_violations(trait_def_id).to_vec()
463    }
464}
465
466/// The `ty` representation of a user-provided type. Depending on the use-site
467/// we want to either use the unnormalized or the normalized form of this type.
468///
469/// This is a bridge between the interface of HIR ty lowering, which outputs a raw
470/// `Ty`, and the API in this module, which expect `Ty` to be fully normalized.
471#[derive(Clone, Copy, Debug)]
472pub(crate) struct LoweredTy<'tcx> {
473    /// The unnormalized type provided by the user.
474    pub raw: Ty<'tcx>,
475
476    /// The normalized form of `raw`, stored here for efficiency.
477    pub normalized: Ty<'tcx>,
478}
479
480impl<'tcx> LoweredTy<'tcx> {
481    fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> {
482        // FIXME(-Znext-solver=no): This is easier than requiring all uses of `LoweredTy`
483        // to call `try_structurally_resolve_type` instead. This seems like a lot of
484        // effort, especially as we're still supporting the old solver. We may revisit
485        // this in the future.
486        let normalized = if fcx.next_trait_solver() {
487            fcx.try_structurally_resolve_type(span, raw)
488        } else {
489            fcx.normalize(span, raw)
490        };
491        LoweredTy { raw, normalized }
492    }
493}
494
495fn never_type_behavior(tcx: TyCtxt<'_>) -> (DivergingFallbackBehavior, DivergingBlockBehavior) {
496    let (fallback, block) = parse_never_type_options_attr(tcx);
497    let fallback = fallback.unwrap_or_else(|| default_fallback(tcx));
498    let block = block.unwrap_or_default();
499
500    (fallback, block)
501}
502
503/// Returns the default fallback which is used when there is no explicit override via `#![never_type_options(...)]`.
504fn default_fallback(tcx: TyCtxt<'_>) -> DivergingFallbackBehavior {
505    // Edition 2024: fallback to `!`
506    if tcx.sess.edition().at_least_rust_2024() {
507        return DivergingFallbackBehavior::ToNever;
508    }
509
510    // Otherwise: fallback to `()`
511    DivergingFallbackBehavior::ToUnit
512}
513
514fn parse_never_type_options_attr(
515    tcx: TyCtxt<'_>,
516) -> (Option<DivergingFallbackBehavior>, Option<DivergingBlockBehavior>) {
517    // Error handling is dubious here (unwraps), but that's probably fine for an internal attribute.
518    // Just don't write incorrect attributes <3
519
520    let mut fallback = None;
521    let mut block = None;
522
523    let items = if tcx.features().rustc_attrs() {
524        tcx.get_attr(CRATE_DEF_ID, sym::rustc_never_type_options)
525            .map(|attr| attr.meta_item_list().unwrap())
526    } else {
527        None
528    };
529    let items = items.unwrap_or_default();
530
531    for item in items {
532        if item.has_name(sym::fallback) && fallback.is_none() {
533            let mode = item.value_str().unwrap();
534            match mode {
535                sym::unit => fallback = Some(DivergingFallbackBehavior::ToUnit),
536                sym::never => fallback = Some(DivergingFallbackBehavior::ToNever),
537                sym::no => fallback = Some(DivergingFallbackBehavior::NoFallback),
538                _ => {
539                    tcx.dcx().span_err(item.span(), format!("unknown never type fallback mode: `{mode}` (supported: `unit`, `niko`, `never` and `no`)"));
540                }
541            };
542            continue;
543        }
544
545        if item.has_name(sym::diverging_block_default) && block.is_none() {
546            let default = item.value_str().unwrap();
547            match default {
548                sym::unit => block = Some(DivergingBlockBehavior::Unit),
549                sym::never => block = Some(DivergingBlockBehavior::Never),
550                _ => {
551                    tcx.dcx().span_err(item.span(), format!("unknown diverging block default: `{default}` (supported: `unit` and `never`)"));
552                }
553            };
554            continue;
555        }
556
557        tcx.dcx().span_err(
558            item.span(),
559            format!(
560                "unknown or duplicate never type option: `{}` (supported: `fallback`, `diverging_block_default`)",
561                item.name().unwrap()
562            ),
563        );
564    }
565
566    (fallback, block)
567}