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
11pub(crate) use inspect_obligations::UseSubtyping;
12use rustc_data_structures::thin_vec::{ThinVec, thin_vec};
13use rustc_errors::DiagCtxtHandle;
14use rustc_hir::def_id::{DefId, LocalDefId};
15use rustc_hir::{self as hir, HirId, ItemLocalMap};
16use rustc_hir_analysis::hir_ty_lowering::{
17    HirTyLowerer, InherentAssocCandidate, RegionInferReason,
18};
19use rustc_infer::infer::{self, RegionVariableOrigin};
20use rustc_infer::traits::{DynCompatibilityViolation, Obligation, TraitErrors};
21use rustc_middle::ty::{
22    self, CallerBoundsIterator, CantBeErased, Const, Flags, Ty, TyCtxt, TypeVisitableExt,
23    TypingMode, Unnormalized,
24};
25use rustc_session::Session;
26use rustc_span::def_id::LocalModId;
27use rustc_span::{self, DUMMY_SP, ErrorGuaranteed, Ident, Span};
28use rustc_trait_selection::error_reporting::TypeErrCtxt;
29use rustc_trait_selection::traits::{
30    self, FulfillmentError, ObligationCause, ObligationCauseCode, ObligationCtxt,
31};
32
33use crate::coercion::CoerceMany;
34use crate::{CoroutineTypes, Diverges, EnclosingBreakables, TypeckRootCtxt};
35
36/// The `FnCtxt` stores type-checking context needed to type-check bodies of
37/// functions, closures, and `const`s, including performing type inference
38/// with [`InferCtxt`].
39///
40/// This is in contrast to `rustc_hir_analysis::collect::ItemCtxt`, which is
41/// used to type-check item *signatures* and thus does not perform type
42/// inference.
43///
44/// See `ItemCtxt`'s docs for more.
45///
46/// [`InferCtxt`]: infer::InferCtxt
47pub(crate) struct FnCtxt<'a, 'tcx> {
48    pub(super) body_def_id: LocalDefId,
49
50    /// The parameter environment used for proving trait obligations
51    /// in this function. This can change when we descend into
52    /// closures (as they bring new things into scope), hence it is
53    /// not part of `Inherited` (as of the time of this writing,
54    /// closures do not yet change the environment, but they will
55    /// eventually).
56    pub(super) param_env: ty::ParamEnv<'tcx>,
57
58    /// If `Some`, this stores coercion information for returned
59    /// expressions. If `None`, this is in a context where return is
60    /// inappropriate, such as a const expression.
61    ///
62    /// This is a `RefCell<CoerceMany>`, which means that we
63    /// can track all the return expressions and then use them to
64    /// compute a useful coercion from the set, similar to a match
65    /// expression or other branching context. You can use methods
66    /// like `expected_ty` to access the declared return type (if
67    /// any).
68    pub(super) ret_coercion: Option<RefCell<CoerceMany<'tcx>>>,
69
70    /// First span of a return site that we find. Used in error messages.
71    pub(super) ret_coercion_span: Cell<Option<Span>>,
72
73    pub(super) coroutine_types: Option<CoroutineTypes<'tcx>>,
74
75    /// Whether the last checked node generates a divergence (e.g.,
76    /// `return` will set this to `Always`). In general, when entering
77    /// an expression or other node in the tree, the initial value
78    /// indicates whether prior parts of the containing expression may
79    /// have diverged. It is then typically set to `Maybe` (and the
80    /// old value remembered) for processing the subparts of the
81    /// current expression. As each subpart is processed, they may set
82    /// the flag to `Always`, etc. Finally, at the end, we take the
83    /// result and "union" it with the original value, so that when we
84    /// return the flag indicates if any subpart of the parent
85    /// expression (up to and including this part) has diverged. So,
86    /// if you read it after evaluating a subexpression `X`, the value
87    /// you get indicates whether any subexpression that was
88    /// evaluating up to and including `X` diverged.
89    ///
90    /// We currently use this flag for the following purposes:
91    ///
92    /// - To warn about unreachable code: if, after processing a
93    ///   sub-expression but before we have applied the effects of the
94    ///   current node, we see that the flag is set to `Always`, we
95    ///   can issue a warning. This corresponds to something like
96    ///   `foo(return)`; we warn on the `foo()` expression. (We then
97    ///   update the flag to `WarnedAlways` to suppress duplicate
98    ///   reports.) Similarly, if we traverse to a fresh statement (or
99    ///   tail expression) from an `Always` setting, we will issue a
100    ///   warning. This corresponds to something like `{return;
101    ///   foo();}` or `{return; 22}`, where we would warn on the
102    ///   `foo()` or `22`.
103    /// - To assign the `!` type to block expressions with diverging
104    ///   statements.
105    ///
106    /// An expression represents dead code if, after checking it,
107    /// the diverges flag is set to something other than `Maybe`.
108    pub(super) diverges: Cell<Diverges>,
109
110    /// If one of the function arguments is a never pattern, this counts as diverging code.
111    /// This affect typechecking of the function body.
112    pub(super) function_diverges_because_of_empty_arguments: Cell<Diverges>,
113
114    /// Whether the currently checked node is the whole body of the function.
115    pub(super) is_whole_body: Cell<bool>,
116
117    pub(super) enclosing_breakables: RefCell<EnclosingBreakables<'tcx>>,
118
119    pub(super) root_ctxt: &'a TypeckRootCtxt<'tcx>,
120
121    /// True if a divirging inference variable has been set to `()`/`!` because
122    /// of never type fallback. This is only used for diagnostics.
123    pub(super) diverging_fallback_has_occurred: Cell<bool>,
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_def_id: LocalDefId,
141    ) -> FnCtxt<'a, 'tcx> {
142        FnCtxt {
143            body_def_id,
144            param_env,
145            ret_coercion: None,
146            ret_coercion_span: Cell::new(None),
147            coroutine_types: None,
148            diverges: Cell::new(Diverges::Maybe),
149            function_diverges_because_of_empty_arguments: Cell::new(Diverges::Maybe),
150            is_whole_body: Cell::new(false),
151            enclosing_breakables: RefCell::new(EnclosingBreakables {
152                stack: Vec::new(),
153                by_id: Default::default(),
154            }),
155            root_ctxt,
156            diverging_fallback_has_occurred: Cell::new(false),
157            trait_ascriptions: Default::default(),
158            has_rustc_attrs: root_ctxt.tcx.features().rustc_attrs(),
159        }
160    }
161
162    pub(crate) fn typing_mode(&self) -> TypingMode<'tcx, CantBeErased> {
163        // `FnCtxt` is never constructed in the trait solver, so we can safely use
164        // `assert_not_erased`.
165        self.infcx.typing_mode_raw().assert_not_erased()
166    }
167
168    pub(crate) fn dcx(&self) -> DiagCtxtHandle<'a> {
169        self.root_ctxt.infcx.dcx()
170    }
171
172    pub(crate) fn cause(
173        &self,
174        span: Span,
175        code: ObligationCauseCode<'tcx>,
176    ) -> ObligationCause<'tcx> {
177        ObligationCause::new(span, self.body_def_id, code)
178    }
179
180    pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx> {
181        self.cause(span, ObligationCauseCode::Misc)
182    }
183
184    pub(crate) fn sess(&self) -> &Session {
185        self.tcx.sess
186    }
187
188    /// Creates an `TypeErrCtxt` with a reference to the in-progress
189    /// `TypeckResults` which is used for diagnostics.
190    /// Use [`InferCtxtErrorExt::err_ctxt`] to start one without a `TypeckResults`.
191    ///
192    /// [`InferCtxtErrorExt::err_ctxt`]: rustc_trait_selection::error_reporting::InferCtxtErrorExt::err_ctxt
193    pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx> {
194        TypeErrCtxt {
195            infcx: &self.infcx,
196            param_env: Some(self.param_env),
197            typeck_results: Some(self.typeck_results.borrow()),
198            diverging_fallback_has_occurred: self.diverging_fallback_has_occurred.get(),
199            autoderef_steps: Box::new(|ty| {
200                let mut autoderef = self.autoderef(DUMMY_SP, ty).silence_errors();
201                let mut steps = ::alloc::vec::Vec::new()vec![];
202                while let Some((ty, _)) = autoderef.next() {
203                    steps.push((ty, autoderef.current_obligations()));
204                }
205                steps
206            }),
207            infer_closure_kind: Box::new(|closure_def_id| {
208                self.infer_closure_kind_for_diagnostic(closure_def_id)
209            }),
210        }
211    }
212}
213
214impl<'a, 'tcx> Deref for FnCtxt<'a, 'tcx> {
215    type Target = TypeckRootCtxt<'tcx>;
216    fn deref(&self) -> &Self::Target {
217        self.root_ctxt
218    }
219}
220
221impl<'tcx> rustc_hir_pretty::PpAnn for FnCtxt<'_, 'tcx> {
222    fn nested(&self, state: &mut rustc_hir_pretty::State<'_>, nested: rustc_hir_pretty::Nested) {
223        rustc_hir_pretty::PpAnn::nested(
224            &(&self.tcx as &dyn rustc_hir::intravisit::HirTyCtxt<'_>),
225            state,
226            nested,
227        )
228    }
229}
230
231impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> {
232    fn tcx(&self) -> TyCtxt<'tcx> {
233        self.tcx
234    }
235
236    fn dcx(&self) -> DiagCtxtHandle<'_> {
237        self.root_ctxt.dcx()
238    }
239
240    fn item_def_id(&self) -> LocalDefId {
241        self.body_def_id
242    }
243
244    fn mod_id(&self) -> LocalModId {
245        self.mod_id
246    }
247
248    fn re_infer(&self, span: Span, reason: RegionInferReason<'_>) -> ty::Region<'tcx> {
249        let v = match reason {
250            RegionInferReason::Param(def) => {
251                RegionVariableOrigin::RegionParameterDefinition(span, def.name)
252            }
253            _ => RegionVariableOrigin::Misc(span),
254        };
255        self.next_region_var(v)
256    }
257
258    fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx> {
259        match param {
260            Some(param) => self.var_for_def(span, param).as_type().unwrap(),
261            None => self.next_ty_var(span),
262        }
263    }
264
265    fn ct_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Const<'tcx> {
266        // FIXME ideally this shouldn't use unwrap
267        match param {
268            Some(param) => self.var_for_def(span, param).as_const().unwrap(),
269            None => self.next_const_var(span),
270        }
271    }
272
273    fn register_trait_ascription_bounds(
274        &self,
275        bounds: Vec<(ty::Clause<'tcx>, Span)>,
276        hir_id: HirId,
277        _span: Span,
278    ) {
279        for (clause, span) in bounds {
280            if clause.has_escaping_bound_vars() {
281                self.dcx().span_delayed_bug(span, "clause should have no escaping bound vars");
282                continue;
283            }
284
285            self.trait_ascriptions.borrow_mut().entry(hir_id.local_id).or_default().push(clause);
286
287            let clause = self.normalize(span, Unnormalized::new_wip(clause));
288            self.register_predicate(Obligation::new(
289                self.tcx,
290                self.misc(span),
291                self.param_env,
292                clause,
293            ));
294        }
295    }
296
297    fn probe_ty_param_bounds(
298        &self,
299        _: Span,
300        def_id: LocalDefId,
301        _: Ident,
302    ) -> ty::EarlyBinder<'tcx, &'tcx [(ty::Clause<'tcx>, Span)]> {
303        let tcx = self.tcx;
304        let item_def_id = tcx.hir_ty_param_owner(def_id);
305        let generics = tcx.generics_of(item_def_id);
306        let index = generics.param_def_id_to_index[&def_id.to_def_id()];
307        // HACK(eddyb) should get the original `Span`.
308        let span = tcx.def_span(def_id);
309
310        ty::EarlyBinder::bind_iter(
311            tcx.arena.alloc_from_iter(
312                self.param_env
313                    .caller_bounds()
314                    .trait_clauses(tcx)
315                    .validate_self_ty(|actual_self_ty| actual_self_ty.is_param(index))
316                    .interned()
317                    .iter()
318                    .map(|trait_clause| {
319                        (ty::set_aliases_to_non_rigid(tcx, trait_clause).skip_norm_wip(), span)
320                    }),
321            ),
322        )
323    }
324
325    fn select_inherent_assoc_candidates(
326        &self,
327        span: Span,
328        self_ty: Ty<'tcx>,
329        candidates: Vec<InherentAssocCandidate>,
330    ) -> (Vec<InherentAssocCandidate>, ThinVec<FulfillmentError<'tcx>>) {
331        let tcx = self.tcx();
332        let infcx = &self.infcx;
333        let mut fulfillment_errors = ::thin_vec::ThinVec::new()thin_vec![];
334
335        let mut filter_iat_candidate = |self_ty, impl_| {
336            let ocx = ObligationCtxt::new_with_diagnostics(self);
337            let self_ty = ocx.normalize(
338                &ObligationCause::dummy(),
339                self.param_env,
340                Unnormalized::new_wip(self_ty),
341            );
342
343            let impl_args = infcx.fresh_args_for_item(span, impl_);
344            let impl_ty = tcx.type_of(impl_).instantiate(tcx, impl_args);
345            let impl_ty = ocx.normalize(&ObligationCause::dummy(), self.param_env, impl_ty);
346
347            // Check that the self types can be related.
348            if ocx.eq(&ObligationCause::dummy(), self.param_env, impl_ty, self_ty).is_err() {
349                return false;
350            }
351
352            // Check whether the impl imposes obligations we have to worry about.
353            let impl_bounds = tcx.clauses_of(impl_).instantiate(tcx, impl_args);
354            let impl_obligations = traits::predicates_for_generics(
355                |_, _| ObligationCause::dummy(),
356                |clause| ocx.normalize(&ObligationCause::dummy(), self.param_env, clause),
357                self.param_env,
358                impl_bounds,
359            );
360            ocx.register_obligations(impl_obligations);
361
362            let errors = ocx.try_evaluate_obligations();
363            if let TraitErrors::HasErrors(mut errors) = errors {
364                fulfillment_errors.append(&mut errors);
365                return false;
366            }
367
368            true
369        };
370
371        let mut universes = if self_ty.has_escaping_bound_vars() {
372            ::alloc::vec::from_elem_global(None,
    self_ty.outer_exclusive_binder().as_usize())vec![None; self_ty.outer_exclusive_binder().as_usize()]
373        } else {
374            ::alloc::vec::Vec::new()vec![]
375        };
376
377        let candidates =
378            traits::with_replaced_escaping_bound_vars(infcx, &mut universes, self_ty, |self_ty| {
379                candidates
380                    .into_iter()
381                    .filter(|&InherentAssocCandidate { impl_, .. }| {
382                        infcx.probe(|_| filter_iat_candidate(self_ty, impl_))
383                    })
384                    .collect()
385            });
386
387        (candidates, fulfillment_errors)
388    }
389
390    fn lower_assoc_item_path(
391        &self,
392        span: Span,
393        item_def_id: DefId,
394        item_segment: &rustc_hir::PathSegment<'_>,
395        poly_trait_ref: ty::PolyTraitRef<'tcx>,
396    ) -> Result<(DefId, ty::GenericArgs<'tcx>), ErrorGuaranteed> {
397        let trait_ref = self.instantiate_binder_with_fresh_vars(
398            span,
399            // FIXME(mgca): `item_def_id` can be an AssocConst; rename this variant.
400            infer::BoundRegionConversionTime::AssocTypeProjection(item_def_id),
401            poly_trait_ref,
402        );
403
404        let item_args = self.lowerer().lower_generic_args_of_assoc_item(
405            span,
406            item_def_id,
407            item_segment,
408            trait_ref.args,
409        );
410
411        Ok((item_def_id, item_args))
412    }
413
414    fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>> {
415        match ty.kind() {
416            ty::Adt(adt_def, _) => Some(*adt_def),
417            // FIXME(#104767): Should we handle bound regions here?
418            ty::Alias(
419                _,
420                ty::AliasTy {
421                    kind: ty::Projection { .. } | ty::Inherent { .. } | ty::Free { .. },
422                    ..
423                },
424            ) if !ty.has_escaping_bound_vars() => {
425                self.normalize(span, Unnormalized::new_wip(ty)).ty_adt_def()
426            }
427            _ => None,
428        }
429    }
430
431    fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span) {
432        // FIXME: normalization and escaping regions
433        let ty = if !ty.has_escaping_bound_vars() {
434            // NOTE: These obligations are 100% redundant and are implied by
435            // WF obligations that are registered elsewhere, but they have a
436            // better cause code assigned to them in `add_required_obligations_for_hir`.
437            // This means that they should shadow obligations with worse spans.
438            if let ty::Alias(
439                _,
440                ty::AliasTy { kind: ty::Projection { def_id } | ty::Free { def_id }, args, .. },
441            ) = ty.kind()
442            {
443                self.add_required_obligations_for_hir(span, *def_id, *args, hir_id);
444            }
445
446            self.normalize(span, Unnormalized::new_wip(ty))
447        } else {
448            ty
449        };
450        self.write_ty(hir_id, ty)
451    }
452
453    fn infcx(&self) -> Option<&infer::InferCtxt<'tcx>> {
454        Some(&self.infcx)
455    }
456
457    fn lower_fn_sig(
458        &self,
459        decl: &rustc_hir::FnDecl<'_>,
460        _generics: Option<&rustc_hir::Generics<'_>>,
461        _hir_id: rustc_hir::HirId,
462        _hir_ty: Option<&hir::Ty<'_>>,
463    ) -> (Vec<Ty<'tcx>>, Ty<'tcx>) {
464        let input_tys = decl.inputs.iter().map(|a| self.lowerer().lower_ty(a)).collect();
465
466        let output_ty = match decl.output {
467            hir::FnRetTy::Return(output) => self.lowerer().lower_ty(output),
468            hir::FnRetTy::DefaultReturn(..) => self.tcx().types.unit,
469        };
470        (input_tys, output_ty)
471    }
472
473    fn dyn_compatibility_violations(&self, trait_def_id: DefId) -> Vec<DynCompatibilityViolation> {
474        self.tcx.dyn_compatibility_violations(trait_def_id).to_vec()
475    }
476}
477
478/// The `ty` representation of a user-provided type. Depending on the use-site
479/// we want to either use the unnormalized or the normalized form of this type.
480///
481/// This is a bridge between the interface of HIR ty lowering, which outputs a raw
482/// `Ty`, and the API in this module, which expect `Ty` to be fully normalized.
483#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl<'tcx>
    ::core::clone::TrivialClone for LoweredTy<'tcx> {
}
#[automatically_derived]impl<'tcx> ::core::clone::Clone for LoweredTy<'tcx> {
    #[inline]
    fn clone(&self) -> Self {
        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 normalized", &self.raw, &&self.normalized)
    }
}Debug)]
484pub(crate) struct LoweredTy<'tcx> {
485    /// The unnormalized type provided by the user.
486    pub raw: Ty<'tcx>,
487
488    /// The normalized form of `raw`, stored here for efficiency.
489    pub normalized: Ty<'tcx>,
490}
491
492impl<'tcx> LoweredTy<'tcx> {
493    fn from_raw(fcx: &FnCtxt<'_, 'tcx>, span: Span, raw: Ty<'tcx>) -> LoweredTy<'tcx> {
494        let normalized = fcx.normalize(span, Unnormalized::new_wip(raw));
495        LoweredTy { raw, normalized }
496    }
497}