Skip to main content

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 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
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 typing_mode(&self) -> TypingMode<'tcx, CantBeErased> {
167        // `FnCtxt` is never constructed in the trait solver, so we can safely use
168        // `assert_not_erased`.
169        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    /// Creates an `TypeErrCtxt` with a reference to the in-progress
193    /// `TypeckResults` which is used for diagnostics.
194    /// Use [`InferCtxtErrorExt::err_ctxt`] to start one without a `TypeckResults`.
195    ///
196    /// [`InferCtxtErrorExt::err_ctxt`]: rustc_trait_selection::error_reporting::InferCtxtErrorExt::err_ctxt
197    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        // FIXME ideally this shouldn't use unwrap
254        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        // HACK(eddyb) should get the original `Span`.
295        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            // Check that the self types can be related.
332            if ocx.eq(&ObligationCause::dummy(), self.param_env, impl_ty, self_ty).is_err() {
333                return false;
334            }
335
336            // Check whether the impl imposes obligations we have to worry about.
337            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            // FIXME(mgca): `item_def_id` can be an AssocConst; rename this variant.
384            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            // FIXME(#104767): Should we handle bound regions here?
402            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        // FIXME: normalization and escaping regions
414        let ty = if !ty.has_escaping_bound_vars() {
415            // NOTE: These obligations are 100% redundant and are implied by
416            // WF obligations that are registered elsewhere, but they have a
417            // better cause code assigned to them in `add_required_obligations_for_hir`.
418            // This means that they should shadow obligations with worse spans.
419            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/// The `ty` representation of a user-provided type. Depending on the use-site
461/// we want to either use the unnormalized or the normalized form of this type.
462///
463/// This is a bridge between the interface of HIR ty lowering, which outputs a raw
464/// `Ty`, and the API in this module, which expect `Ty` to be fully normalized.
465#[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    /// The unnormalized type provided by the user.
468    pub raw: Ty<'tcx>,
469
470    /// The normalized form of `raw`, stored here for efficiency.
471    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
489/// Returns the default fallback which is used when there is no explicit override via `#![never_type_options(...)]`.
490fn default_fallback(tcx: TyCtxt<'_>) -> DivergingFallbackBehavior {
491    // Edition 2024: fallback to `!`
492    if tcx.sess.edition().at_least_rust_2024() {
493        return DivergingFallbackBehavior::ToNever;
494    }
495
496    // Otherwise: fallback to `()`
497    DivergingFallbackBehavior::ToUnit
498}
499
500fn parse_never_type_options_attr(
501    tcx: TyCtxt<'_>,
502) -> (Option<DivergingFallbackBehavior>, Option<DivergingBlockBehavior>) {
503    // Error handling is dubious here (unwraps), but that's probably fine for an internal attribute.
504    // Just don't write incorrect attributes <3
505
506    {
    '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}