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::{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
30/// The `FnCtxt` stores type-checking context needed to type-check bodies of
31/// functions, closures, and `const`s, including performing type inference
32/// with [`InferCtxt`].
33///
34/// This is in contrast to `rustc_hir_analysis::collect::ItemCtxt`, which is
35/// used to type-check item *signatures* and thus does not perform type
36/// inference.
37///
38/// See `ItemCtxt`'s docs for more.
39///
40/// [`InferCtxt`]: infer::InferCtxt
41pub(crate) struct FnCtxt<'a, 'tcx> {
42    pub(super) body_id: LocalDefId,
43
44    /// The parameter environment used for proving trait obligations
45    /// in this function. This can change when we descend into
46    /// closures (as they bring new things into scope), hence it is
47    /// not part of `Inherited` (as of the time of this writing,
48    /// closures do not yet change the environment, but they will
49    /// eventually).
50    pub(super) param_env: ty::ParamEnv<'tcx>,
51
52    /// If `Some`, this stores coercion information for returned
53    /// expressions. If `None`, this is in a context where return is
54    /// inappropriate, such as a const expression.
55    ///
56    /// This is a `RefCell<DynamicCoerceMany>`, which means that we
57    /// can track all the return expressions and then use them to
58    /// compute a useful coercion from the set, similar to a match
59    /// expression or other branching context. You can use methods
60    /// like `expected_ty` to access the declared return type (if
61    /// any).
62    pub(super) ret_coercion: Option<RefCell<DynamicCoerceMany<'tcx>>>,
63
64    /// First span of a return site that we find. Used in error messages.
65    pub(super) ret_coercion_span: Cell<Option<Span>>,
66
67    pub(super) coroutine_types: Option<CoroutineTypes<'tcx>>,
68
69    /// Whether the last checked node generates a divergence (e.g.,
70    /// `return` will set this to `Always`). In general, when entering
71    /// an expression or other node in the tree, the initial value
72    /// indicates whether prior parts of the containing expression may
73    /// have diverged. It is then typically set to `Maybe` (and the
74    /// old value remembered) for processing the subparts of the
75    /// current expression. As each subpart is processed, they may set
76    /// the flag to `Always`, etc. Finally, at the end, we take the
77    /// result and "union" it with the original value, so that when we
78    /// return the flag indicates if any subpart of the parent
79    /// expression (up to and including this part) has diverged. So,
80    /// if you read it after evaluating a subexpression `X`, the value
81    /// you get indicates whether any subexpression that was
82    /// evaluating up to and including `X` diverged.
83    ///
84    /// We currently use this flag only for diagnostic purposes:
85    ///
86    /// - To warn about unreachable code: if, after processing a
87    ///   sub-expression but before we have applied the effects of the
88    ///   current node, we see that the flag is set to `Always`, we
89    ///   can issue a warning. This corresponds to something like
90    ///   `foo(return)`; we warn on the `foo()` expression. (We then
91    ///   update the flag to `WarnedAlways` to suppress duplicate
92    ///   reports.) Similarly, if we traverse to a fresh statement (or
93    ///   tail expression) from an `Always` setting, we will issue a
94    ///   warning. This corresponds to something like `{return;
95    ///   foo();}` or `{return; 22}`, where we would warn on the
96    ///   `foo()` or `22`.
97    ///
98    /// An expression represents dead code if, after checking it,
99    /// the diverges flag is set to something other than `Maybe`.
100    pub(super) diverges: Cell<Diverges>,
101
102    /// If one of the function arguments is a never pattern, this counts as diverging code. This
103    /// affect typechecking of the function body.
104    pub(super) function_diverges_because_of_empty_arguments: Cell<Diverges>,
105
106    /// Whether the currently checked node is the whole body of the function.
107    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    /// Clauses that we lowered as part of the `impl_trait_in_bindings` feature.
119    ///
120    /// These are stored here so we may collect them when canonicalizing user
121    /// type ascriptions later.
122    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    /// Creates an `TypeErrCtxt` with a reference to the in-progress
175    /// `TypeckResults` which is used for diagnostics.
176    /// Use [`InferCtxtErrorExt::err_ctxt`] to start one without a `TypeckResults`.
177    ///
178    /// [`InferCtxtErrorExt::err_ctxt`]: rustc_trait_selection::error_reporting::InferCtxtErrorExt::err_ctxt
179    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        // FIXME ideally this shouldn't use unwrap
256        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        // HACK(eddyb) should get the original `Span`.
297        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            // FIXME(mgca): this should be assoc const if that is the `kind`
322            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            // FIXME(#104767): Should we handle bound regions here?
340            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        // FIXME: normalization and escaping regions
355        let ty = if !ty.has_escaping_bound_vars() {
356            // NOTE: These obligations are 100% redundant and are implied by
357            // WF obligations that are registered elsewhere, but they have a
358            // better cause code assigned to them in `add_required_obligations_for_hir`.
359            // This means that they should shadow obligations with worse spans.
360            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/// The `ty` representation of a user-provided type. Depending on the use-site
395/// we want to either use the unnormalized or the normalized form of this type.
396///
397/// This is a bridge between the interface of HIR ty lowering, which outputs a raw
398/// `Ty`, and the API in this module, which expect `Ty` to be fully normalized.
399#[derive(Clone, Copy, Debug)]
400pub(crate) struct LoweredTy<'tcx> {
401    /// The unnormalized type provided by the user.
402    pub raw: Ty<'tcx>,
403
404    /// The normalized form of `raw`, stored here for efficiency.
405    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        // FIXME(-Znext-solver): We're still figuring out how to best handle
411        // normalization and this doesn't feel too great. We should look at this
412        // code again before stabilizing it.
413        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
430/// Returns the default fallback which is used when there is no explicit override via `#![never_type_options(...)]`.
431fn default_fallback(tcx: TyCtxt<'_>) -> DivergingFallbackBehavior {
432    // Edition 2024: fallback to `!`
433    if tcx.sess.edition().at_least_rust_2024() {
434        return DivergingFallbackBehavior::ToNever;
435    }
436
437    // `feature(never_type_fallback)`: fallback to `!` or `()` trying to not break stuff
438    if tcx.features().never_type_fallback() {
439        return DivergingFallbackBehavior::ContextDependent;
440    }
441
442    // Otherwise: fallback to `()`
443    DivergingFallbackBehavior::ToUnit
444}
445
446fn parse_never_type_options_attr(
447    tcx: TyCtxt<'_>,
448) -> (Option<DivergingFallbackBehavior>, Option<DivergingBlockBehavior>) {
449    // Error handling is dubious here (unwraps), but that's probably fine for an internal attribute.
450    // Just don't write incorrect attributes <3
451
452    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}