rustc_hir_typeck/
gather_locals.rs

1use rustc_hir as hir;
2use rustc_hir::intravisit::{self, Visitor};
3use rustc_hir::{HirId, PatKind};
4use rustc_infer::traits::ObligationCauseCode;
5use rustc_middle::ty::{self, Ty};
6use rustc_span::Span;
7use rustc_span::def_id::LocalDefId;
8use tracing::debug;
9
10use crate::FnCtxt;
11
12/// Provides context for checking patterns in declarations. More specifically this
13/// allows us to infer array types if the pattern is irrefutable and allows us to infer
14/// the size of the array. See issue #76342.
15#[derive(Debug, Copy, Clone)]
16pub(super) enum DeclOrigin<'a> {
17    // from an `if let` expression
18    LetExpr,
19    // from `let x = ..`
20    LocalDecl { els: Option<&'a hir::Block<'a>> },
21}
22
23impl<'a> DeclOrigin<'a> {
24    pub(super) fn try_get_else(&self) -> Option<&'a hir::Block<'a>> {
25        match self {
26            Self::LocalDecl { els } => *els,
27            Self::LetExpr => None,
28        }
29    }
30}
31
32/// A declaration is an abstraction of [hir::LetStmt] and [hir::LetExpr].
33///
34/// It must have a hir_id, as this is how we connect gather_locals to the check functions.
35pub(super) struct Declaration<'a> {
36    pub hir_id: HirId,
37    pub pat: &'a hir::Pat<'a>,
38    pub ty: Option<&'a hir::Ty<'a>>,
39    pub span: Span,
40    pub init: Option<&'a hir::Expr<'a>>,
41    pub origin: DeclOrigin<'a>,
42}
43
44impl<'a> From<&'a hir::LetStmt<'a>> for Declaration<'a> {
45    fn from(local: &'a hir::LetStmt<'a>) -> Self {
46        let hir::LetStmt { hir_id, super_: _, pat, ty, span, init, els, source: _ } = *local;
47        Declaration { hir_id, pat, ty, span, init, origin: DeclOrigin::LocalDecl { els } }
48    }
49}
50
51impl<'a> From<(&'a hir::LetExpr<'a>, HirId)> for Declaration<'a> {
52    fn from((let_expr, hir_id): (&'a hir::LetExpr<'a>, HirId)) -> Self {
53        let hir::LetExpr { pat, ty, span, init, recovered: _ } = *let_expr;
54        Declaration { hir_id, pat, ty, span, init: Some(init), origin: DeclOrigin::LetExpr }
55    }
56}
57
58/// The `GatherLocalsVisitor` is responsible for initializing local variable types
59/// in the [`ty::TypeckResults`] for all subpatterns in statements and expressions
60/// like `let`, `match`, and params of function bodies. It also adds `Sized` bounds
61/// for these types (with exceptions for unsized feature gates like `unsized_fn_params`).
62///
63/// Failure to visit locals will cause an ICE in writeback when the local's type is
64/// resolved. Visiting locals twice will ICE in the `GatherLocalsVisitor`, since it
65/// will overwrite the type previously stored in the local.
66pub(super) struct GatherLocalsVisitor<'a, 'tcx> {
67    fcx: &'a FnCtxt<'a, 'tcx>,
68    // parameters are special cases of patterns, but we want to handle them as
69    // *distinct* cases. so track when we are hitting a pattern *within* an fn
70    // parameter.
71    outermost_fn_param_pat: Option<(Span, HirId)>,
72}
73
74// N.B. additional `gather_*` functions should be careful to only walk the pattern
75// for new expressions, since visiting sub-expressions or nested bodies may initialize
76// locals which are not conceptually owned by the gathered statement or expression.
77impl<'a, 'tcx> GatherLocalsVisitor<'a, 'tcx> {
78    pub(crate) fn gather_from_local(fcx: &'a FnCtxt<'a, 'tcx>, local: &'tcx hir::LetStmt<'tcx>) {
79        let mut visitor = GatherLocalsVisitor { fcx, outermost_fn_param_pat: None };
80        visitor.declare(local.into());
81        visitor.visit_pat(local.pat);
82    }
83
84    pub(crate) fn gather_from_let_expr(
85        fcx: &'a FnCtxt<'a, 'tcx>,
86        let_expr: &'tcx hir::LetExpr<'tcx>,
87        expr_hir_id: hir::HirId,
88    ) {
89        let mut visitor = GatherLocalsVisitor { fcx, outermost_fn_param_pat: None };
90        visitor.declare((let_expr, expr_hir_id).into());
91        visitor.visit_pat(let_expr.pat);
92    }
93
94    pub(crate) fn gather_from_param(fcx: &'a FnCtxt<'a, 'tcx>, param: &'tcx hir::Param<'tcx>) {
95        let mut visitor = GatherLocalsVisitor {
96            fcx,
97            outermost_fn_param_pat: Some((param.ty_span, param.hir_id)),
98        };
99        visitor.visit_pat(param.pat);
100    }
101
102    pub(crate) fn gather_from_arm(fcx: &'a FnCtxt<'a, 'tcx>, local: &'tcx hir::Arm<'tcx>) {
103        let mut visitor = GatherLocalsVisitor { fcx, outermost_fn_param_pat: None };
104        visitor.visit_pat(local.pat);
105    }
106
107    fn assign(&mut self, span: Span, nid: HirId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
108        match ty_opt {
109            None => {
110                // Infer the variable's type.
111                let var_ty = self.fcx.next_ty_var(span);
112                assert_eq!(self.fcx.locals.borrow_mut().insert(nid, var_ty), None);
113                var_ty
114            }
115            Some(typ) => {
116                // Take type that the user specified.
117                assert_eq!(self.fcx.locals.borrow_mut().insert(nid, typ), None);
118                typ
119            }
120        }
121    }
122
123    /// Allocates a type for a declaration, which may have a type annotation. If it does have
124    /// a type annotation, then the [`Ty`] stored will be the resolved type. This may be found
125    /// again during type checking by querying [`FnCtxt::local_ty`] for the same hir_id.
126    fn declare(&mut self, decl: Declaration<'tcx>) {
127        let local_ty = match decl.ty {
128            Some(ref ty) => {
129                let o_ty = self.fcx.lower_ty(ty);
130
131                let c_ty = self.fcx.infcx.canonicalize_user_type_annotation(
132                    ty::UserType::new_with_bounds(
133                        ty::UserTypeKind::Ty(o_ty.raw),
134                        self.fcx.collect_impl_trait_clauses_from_hir_ty(ty),
135                    ),
136                );
137                debug!("visit_local: ty.hir_id={:?} o_ty={:?} c_ty={:?}", ty.hir_id, o_ty, c_ty);
138                self.fcx
139                    .typeck_results
140                    .borrow_mut()
141                    .user_provided_types_mut()
142                    .insert(ty.hir_id, c_ty);
143
144                Some(o_ty.normalized)
145            }
146            None => None,
147        };
148        self.assign(decl.span, decl.hir_id, local_ty);
149
150        debug!(
151            "local variable {:?} is assigned type {}",
152            decl.pat,
153            self.fcx.ty_to_string(*self.fcx.locals.borrow().get(&decl.hir_id).unwrap())
154        );
155    }
156}
157
158impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> {
159    // Add explicitly-declared locals.
160    fn visit_local(&mut self, local: &'tcx hir::LetStmt<'tcx>) {
161        self.declare(local.into());
162        intravisit::walk_local(self, local)
163    }
164
165    fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
166        if let hir::ExprKind::Let(let_expr) = expr.kind {
167            self.declare((let_expr, expr.hir_id).into());
168        }
169        intravisit::walk_expr(self, expr)
170    }
171
172    // Add pattern bindings.
173    fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
174        if let PatKind::Binding(_, _, ident, _) = p.kind {
175            let var_ty = self.assign(p.span, p.hir_id, None);
176
177            if let Some((ty_span, hir_id)) = self.outermost_fn_param_pat {
178                if !self.fcx.tcx.features().unsized_fn_params() {
179                    self.fcx.require_type_is_sized(
180                        var_ty,
181                        ty_span,
182                        // ty_span == ident.span iff this is a closure parameter with no type
183                        // ascription, or if it's an implicit `self` parameter
184                        ObligationCauseCode::SizedArgumentType(
185                            if ty_span == ident.span
186                                && self.fcx.tcx.is_closure_like(self.fcx.body_id.into())
187                            {
188                                None
189                            } else {
190                                Some(hir_id)
191                            },
192                        ),
193                    );
194                }
195            } else if !self.fcx.tcx.features().unsized_locals() {
196                self.fcx.require_type_is_sized(
197                    var_ty,
198                    p.span,
199                    ObligationCauseCode::VariableType(p.hir_id),
200                );
201            }
202
203            debug!(
204                "pattern binding {} is assigned to {} with type {:?}",
205                ident,
206                self.fcx.ty_to_string(*self.fcx.locals.borrow().get(&p.hir_id).unwrap()),
207                var_ty
208            );
209        }
210        let old_outermost_fn_param_pat = self.outermost_fn_param_pat.take();
211        intravisit::walk_pat(self, p);
212        self.outermost_fn_param_pat = old_outermost_fn_param_pat;
213    }
214
215    // Don't descend into the bodies of nested closures.
216    fn visit_fn(
217        &mut self,
218        _: intravisit::FnKind<'tcx>,
219        _: &'tcx hir::FnDecl<'tcx>,
220        _: hir::BodyId,
221        _: Span,
222        _: LocalDefId,
223    ) {
224    }
225}