]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/expr_use_visitor.rs
Rollup merge of #73443 - pietroalbini:gha-auto-fallible, r=Mark-Simulacrum
[rust.git] / src / librustc_typeck / expr_use_visitor.rs
1 //! A different sort of visitor for walking fn bodies. Unlike the
2 //! normal visitor, which just walks the entire body in one shot, the
3 //! `ExprUseVisitor` determines how expressions are being used.
4
5 pub use self::ConsumeMode::*;
6
7 // Export these here so that Clippy can use them.
8 pub use mc::{PlaceBase, PlaceWithHirId, Projection};
9
10 use rustc_hir as hir;
11 use rustc_hir::def::Res;
12 use rustc_hir::def_id::LocalDefId;
13 use rustc_hir::PatKind;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::ty::{self, adjustment, TyCtxt};
16
17 use crate::mem_categorization as mc;
18 use rustc_span::Span;
19
20 ///////////////////////////////////////////////////////////////////////////
21 // The Delegate trait
22
23 /// This trait defines the callbacks you can expect to receive when
24 /// employing the ExprUseVisitor.
25 pub trait Delegate<'tcx> {
26     // The value found at `place` is either copied or moved, depending
27     // on mode.
28     fn consume(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, mode: ConsumeMode);
29
30     // The value found at `place` is being borrowed with kind `bk`.
31     fn borrow(&mut self, place_with_id: &mc::PlaceWithHirId<'tcx>, bk: ty::BorrowKind);
32
33     // The path at `place_with_id` is being assigned to.
34     fn mutate(&mut self, assignee_place: &mc::PlaceWithHirId<'tcx>);
35 }
36
37 #[derive(Copy, Clone, PartialEq, Debug)]
38 pub enum ConsumeMode {
39     Copy, // reference to x where x has a type that copies
40     Move, // reference to x where x has a type that moves
41 }
42
43 #[derive(Copy, Clone, PartialEq, Debug)]
44 pub enum MutateMode {
45     Init,
46     JustWrite,    // x = y
47     WriteAndRead, // x += y
48 }
49
50 ///////////////////////////////////////////////////////////////////////////
51 // The ExprUseVisitor type
52 //
53 // This is the code that actually walks the tree.
54 pub struct ExprUseVisitor<'a, 'tcx> {
55     mc: mc::MemCategorizationContext<'a, 'tcx>,
56     delegate: &'a mut dyn Delegate<'tcx>,
57 }
58
59 // If the MC results in an error, it's because the type check
60 // failed (or will fail, when the error is uncovered and reported
61 // during writeback). In this case, we just ignore this part of the
62 // code.
63 //
64 // Note that this macro appears similar to try!(), but, unlike try!(),
65 // it does not propagate the error.
66 macro_rules! return_if_err {
67     ($inp: expr) => {
68         match $inp {
69             Ok(v) => v,
70             Err(()) => {
71                 debug!("mc reported err");
72                 return;
73             }
74         }
75     };
76 }
77
78 impl<'a, 'tcx> ExprUseVisitor<'a, 'tcx> {
79     /// Creates the ExprUseVisitor, configuring it with the various options provided:
80     ///
81     /// - `delegate` -- who receives the callbacks
82     /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`)
83     /// - `tables` --- typeck results for the code being analyzed
84     pub fn new(
85         delegate: &'a mut (dyn Delegate<'tcx> + 'a),
86         infcx: &'a InferCtxt<'a, 'tcx>,
87         body_owner: LocalDefId,
88         param_env: ty::ParamEnv<'tcx>,
89         tables: &'a ty::TypeckTables<'tcx>,
90     ) -> Self {
91         ExprUseVisitor {
92             mc: mc::MemCategorizationContext::new(infcx, param_env, body_owner, tables),
93             delegate,
94         }
95     }
96
97     pub fn consume_body(&mut self, body: &hir::Body<'_>) {
98         debug!("consume_body(body={:?})", body);
99
100         for param in body.params {
101             let param_ty = return_if_err!(self.mc.pat_ty_adjusted(&param.pat));
102             debug!("consume_body: param_ty = {:?}", param_ty);
103
104             let param_place = self.mc.cat_rvalue(param.hir_id, param.pat.span, param_ty);
105
106             self.walk_irrefutable_pat(&param_place, &param.pat);
107         }
108
109         self.consume_expr(&body.value);
110     }
111
112     fn tcx(&self) -> TyCtxt<'tcx> {
113         self.mc.tcx()
114     }
115
116     fn delegate_consume(&mut self, place_with_id: &PlaceWithHirId<'tcx>) {
117         debug!("delegate_consume(place_with_id={:?})", place_with_id);
118
119         let mode = copy_or_move(&self.mc, place_with_id);
120         self.delegate.consume(place_with_id, mode);
121     }
122
123     fn consume_exprs(&mut self, exprs: &[hir::Expr<'_>]) {
124         for expr in exprs {
125             self.consume_expr(&expr);
126         }
127     }
128
129     pub fn consume_expr(&mut self, expr: &hir::Expr<'_>) {
130         debug!("consume_expr(expr={:?})", expr);
131
132         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
133         self.delegate_consume(&place_with_id);
134         self.walk_expr(expr);
135     }
136
137     fn mutate_expr(&mut self, expr: &hir::Expr<'_>) {
138         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
139         self.delegate.mutate(&place_with_id);
140         self.walk_expr(expr);
141     }
142
143     fn borrow_expr(&mut self, expr: &hir::Expr<'_>, bk: ty::BorrowKind) {
144         debug!("borrow_expr(expr={:?}, bk={:?})", expr, bk);
145
146         let place_with_id = return_if_err!(self.mc.cat_expr(expr));
147         self.delegate.borrow(&place_with_id, bk);
148
149         self.walk_expr(expr)
150     }
151
152     fn select_from_expr(&mut self, expr: &hir::Expr<'_>) {
153         self.walk_expr(expr)
154     }
155
156     pub fn walk_expr(&mut self, expr: &hir::Expr<'_>) {
157         debug!("walk_expr(expr={:?})", expr);
158
159         self.walk_adjustment(expr);
160
161         match expr.kind {
162             hir::ExprKind::Path(_) => {}
163
164             hir::ExprKind::Type(ref subexpr, _) => self.walk_expr(subexpr),
165
166             hir::ExprKind::Unary(hir::UnOp::UnDeref, ref base) => {
167                 // *base
168                 self.select_from_expr(base);
169             }
170
171             hir::ExprKind::Field(ref base, _) => {
172                 // base.f
173                 self.select_from_expr(base);
174             }
175
176             hir::ExprKind::Index(ref lhs, ref rhs) => {
177                 // lhs[rhs]
178                 self.select_from_expr(lhs);
179                 self.consume_expr(rhs);
180             }
181
182             hir::ExprKind::Call(ref callee, ref args) => {
183                 // callee(args)
184                 self.consume_expr(callee);
185                 self.consume_exprs(args);
186             }
187
188             hir::ExprKind::MethodCall(.., ref args, _) => {
189                 // callee.m(args)
190                 self.consume_exprs(args);
191             }
192
193             hir::ExprKind::Struct(_, ref fields, ref opt_with) => {
194                 self.walk_struct_expr(fields, opt_with);
195             }
196
197             hir::ExprKind::Tup(ref exprs) => {
198                 self.consume_exprs(exprs);
199             }
200
201             hir::ExprKind::Match(ref discr, arms, _) => {
202                 let discr_place = return_if_err!(self.mc.cat_expr(&discr));
203                 self.borrow_expr(&discr, ty::ImmBorrow);
204
205                 // treatment of the discriminant is handled while walking the arms.
206                 for arm in arms {
207                     self.walk_arm(&discr_place, arm);
208                 }
209             }
210
211             hir::ExprKind::Array(ref exprs) => {
212                 self.consume_exprs(exprs);
213             }
214
215             hir::ExprKind::AddrOf(_, m, ref base) => {
216                 // &base
217                 // make sure that the thing we are pointing out stays valid
218                 // for the lifetime `scope_r` of the resulting ptr:
219                 let bk = ty::BorrowKind::from_mutbl(m);
220                 self.borrow_expr(&base, bk);
221             }
222
223             hir::ExprKind::InlineAsm(ref asm) => {
224                 for op in asm.operands {
225                     match op {
226                         hir::InlineAsmOperand::In { expr, .. }
227                         | hir::InlineAsmOperand::Const { expr, .. }
228                         | hir::InlineAsmOperand::Sym { expr, .. } => self.consume_expr(expr),
229                         hir::InlineAsmOperand::Out { expr, .. } => {
230                             if let Some(expr) = expr {
231                                 self.mutate_expr(expr);
232                             }
233                         }
234                         hir::InlineAsmOperand::InOut { expr, .. } => {
235                             self.mutate_expr(expr);
236                         }
237                         hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
238                             self.consume_expr(in_expr);
239                             if let Some(out_expr) = out_expr {
240                                 self.mutate_expr(out_expr);
241                             }
242                         }
243                     }
244                 }
245             }
246
247             hir::ExprKind::LlvmInlineAsm(ref ia) => {
248                 for (o, output) in ia.inner.outputs.iter().zip(ia.outputs_exprs) {
249                     if o.is_indirect {
250                         self.consume_expr(output);
251                     } else {
252                         self.mutate_expr(output);
253                     }
254                 }
255                 self.consume_exprs(&ia.inputs_exprs);
256             }
257
258             hir::ExprKind::Continue(..) | hir::ExprKind::Lit(..) | hir::ExprKind::Err => {}
259
260             hir::ExprKind::Loop(ref blk, _, _) => {
261                 self.walk_block(blk);
262             }
263
264             hir::ExprKind::Unary(_, ref lhs) => {
265                 self.consume_expr(lhs);
266             }
267
268             hir::ExprKind::Binary(_, ref lhs, ref rhs) => {
269                 self.consume_expr(lhs);
270                 self.consume_expr(rhs);
271             }
272
273             hir::ExprKind::Block(ref blk, _) => {
274                 self.walk_block(blk);
275             }
276
277             hir::ExprKind::Break(_, ref opt_expr) | hir::ExprKind::Ret(ref opt_expr) => {
278                 if let Some(ref expr) = *opt_expr {
279                     self.consume_expr(expr);
280                 }
281             }
282
283             hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
284                 self.mutate_expr(lhs);
285                 self.consume_expr(rhs);
286             }
287
288             hir::ExprKind::Cast(ref base, _) => {
289                 self.consume_expr(base);
290             }
291
292             hir::ExprKind::DropTemps(ref expr) => {
293                 self.consume_expr(expr);
294             }
295
296             hir::ExprKind::AssignOp(_, ref lhs, ref rhs) => {
297                 if self.mc.tables.is_method_call(expr) {
298                     self.consume_expr(lhs);
299                 } else {
300                     self.mutate_expr(lhs);
301                 }
302                 self.consume_expr(rhs);
303             }
304
305             hir::ExprKind::Repeat(ref base, _) => {
306                 self.consume_expr(base);
307             }
308
309             hir::ExprKind::Closure(_, _, _, fn_decl_span, _) => {
310                 self.walk_captures(expr, fn_decl_span);
311             }
312
313             hir::ExprKind::Box(ref base) => {
314                 self.consume_expr(base);
315             }
316
317             hir::ExprKind::Yield(ref value, _) => {
318                 self.consume_expr(value);
319             }
320         }
321     }
322
323     fn walk_stmt(&mut self, stmt: &hir::Stmt<'_>) {
324         match stmt.kind {
325             hir::StmtKind::Local(ref local) => {
326                 self.walk_local(&local);
327             }
328
329             hir::StmtKind::Item(_) => {
330                 // We don't visit nested items in this visitor,
331                 // only the fn body we were given.
332             }
333
334             hir::StmtKind::Expr(ref expr) | hir::StmtKind::Semi(ref expr) => {
335                 self.consume_expr(&expr);
336             }
337         }
338     }
339
340     fn walk_local(&mut self, local: &hir::Local<'_>) {
341         if let Some(ref expr) = local.init {
342             // Variable declarations with
343             // initializers are considered
344             // "assigns", which is handled by
345             // `walk_pat`:
346             self.walk_expr(&expr);
347             let init_place = return_if_err!(self.mc.cat_expr(&expr));
348             self.walk_irrefutable_pat(&init_place, &local.pat);
349         }
350     }
351
352     /// Indicates that the value of `blk` will be consumed, meaning either copied or moved
353     /// depending on its type.
354     fn walk_block(&mut self, blk: &hir::Block<'_>) {
355         debug!("walk_block(blk.hir_id={})", blk.hir_id);
356
357         for stmt in blk.stmts {
358             self.walk_stmt(stmt);
359         }
360
361         if let Some(ref tail_expr) = blk.expr {
362             self.consume_expr(&tail_expr);
363         }
364     }
365
366     fn walk_struct_expr(
367         &mut self,
368         fields: &[hir::Field<'_>],
369         opt_with: &Option<&'hir hir::Expr<'_>>,
370     ) {
371         // Consume the expressions supplying values for each field.
372         for field in fields {
373             self.consume_expr(&field.expr);
374         }
375
376         let with_expr = match *opt_with {
377             Some(ref w) => &**w,
378             None => {
379                 return;
380             }
381         };
382
383         let with_place = return_if_err!(self.mc.cat_expr(&with_expr));
384
385         // Select just those fields of the `with`
386         // expression that will actually be used
387         match with_place.place.ty.kind {
388             ty::Adt(adt, substs) if adt.is_struct() => {
389                 // Consume those fields of the with expression that are needed.
390                 for (f_index, with_field) in adt.non_enum_variant().fields.iter().enumerate() {
391                     let is_mentioned = fields
392                         .iter()
393                         .any(|f| self.tcx().field_index(f.hir_id, self.mc.tables) == f_index);
394                     if !is_mentioned {
395                         let field_place = self.mc.cat_projection(
396                             &*with_expr,
397                             with_place.clone(),
398                             with_field.ty(self.tcx(), substs),
399                         );
400                         self.delegate_consume(&field_place);
401                     }
402                 }
403             }
404             _ => {
405                 // the base expression should always evaluate to a
406                 // struct; however, when EUV is run during typeck, it
407                 // may not. This will generate an error earlier in typeck,
408                 // so we can just ignore it.
409                 if !self.tcx().sess.has_errors() {
410                     span_bug!(with_expr.span, "with expression doesn't evaluate to a struct");
411                 }
412             }
413         }
414
415         // walk the with expression so that complex expressions
416         // are properly handled.
417         self.walk_expr(with_expr);
418     }
419
420     // Invoke the appropriate delegate calls for anything that gets
421     // consumed or borrowed as part of the automatic adjustment
422     // process.
423     fn walk_adjustment(&mut self, expr: &hir::Expr<'_>) {
424         let adjustments = self.mc.tables.expr_adjustments(expr);
425         let mut place_with_id = return_if_err!(self.mc.cat_expr_unadjusted(expr));
426         for adjustment in adjustments {
427             debug!("walk_adjustment expr={:?} adj={:?}", expr, adjustment);
428             match adjustment.kind {
429                 adjustment::Adjust::NeverToAny | adjustment::Adjust::Pointer(_) => {
430                     // Creating a closure/fn-pointer or unsizing consumes
431                     // the input and stores it into the resulting rvalue.
432                     self.delegate_consume(&place_with_id);
433                 }
434
435                 adjustment::Adjust::Deref(None) => {}
436
437                 // Autoderefs for overloaded Deref calls in fact reference
438                 // their receiver. That is, if we have `(*x)` where `x`
439                 // is of type `Rc<T>`, then this in fact is equivalent to
440                 // `x.deref()`. Since `deref()` is declared with `&self`,
441                 // this is an autoref of `x`.
442                 adjustment::Adjust::Deref(Some(ref deref)) => {
443                     let bk = ty::BorrowKind::from_mutbl(deref.mutbl);
444                     self.delegate.borrow(&place_with_id, bk);
445                 }
446
447                 adjustment::Adjust::Borrow(ref autoref) => {
448                     self.walk_autoref(expr, &place_with_id, autoref);
449                 }
450             }
451             place_with_id =
452                 return_if_err!(self.mc.cat_expr_adjusted(expr, place_with_id, &adjustment));
453         }
454     }
455
456     /// Walks the autoref `autoref` applied to the autoderef'd
457     /// `expr`. `base_place` is the mem-categorized form of `expr`
458     /// after all relevant autoderefs have occurred.
459     fn walk_autoref(
460         &mut self,
461         expr: &hir::Expr<'_>,
462         base_place: &mc::PlaceWithHirId<'tcx>,
463         autoref: &adjustment::AutoBorrow<'tcx>,
464     ) {
465         debug!(
466             "walk_autoref(expr.hir_id={} base_place={:?} autoref={:?})",
467             expr.hir_id, base_place, autoref
468         );
469
470         match *autoref {
471             adjustment::AutoBorrow::Ref(_, m) => {
472                 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m.into()));
473             }
474
475             adjustment::AutoBorrow::RawPtr(m) => {
476                 debug!("walk_autoref: expr.hir_id={} base_place={:?}", expr.hir_id, base_place);
477
478                 self.delegate.borrow(base_place, ty::BorrowKind::from_mutbl(m));
479             }
480         }
481     }
482
483     fn walk_arm(&mut self, discr_place: &PlaceWithHirId<'tcx>, arm: &hir::Arm<'_>) {
484         self.walk_pat(discr_place, &arm.pat);
485
486         if let Some(hir::Guard::If(ref e)) = arm.guard {
487             self.consume_expr(e)
488         }
489
490         self.consume_expr(&arm.body);
491     }
492
493     /// Walks a pat that occurs in isolation (i.e., top-level of fn argument or
494     /// let binding, and *not* a match arm or nested pat.)
495     fn walk_irrefutable_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
496         self.walk_pat(discr_place, pat);
497     }
498
499     /// The core driver for walking a pattern
500     fn walk_pat(&mut self, discr_place: &PlaceWithHirId<'tcx>, pat: &hir::Pat<'_>) {
501         debug!("walk_pat(discr_place={:?}, pat={:?})", discr_place, pat);
502
503         let tcx = self.tcx();
504         let ExprUseVisitor { ref mc, ref mut delegate } = *self;
505         return_if_err!(mc.cat_pattern(discr_place.clone(), pat, |place, pat| {
506             if let PatKind::Binding(_, canonical_id, ..) = pat.kind {
507                 debug!("walk_pat: binding place={:?} pat={:?}", place, pat,);
508                 if let Some(bm) = mc.tables.extract_binding_mode(tcx.sess, pat.hir_id, pat.span) {
509                     debug!("walk_pat: pat.hir_id={:?} bm={:?}", pat.hir_id, bm);
510
511                     // pat_ty: the type of the binding being produced.
512                     let pat_ty = return_if_err!(mc.node_ty(pat.hir_id));
513                     debug!("walk_pat: pat_ty={:?}", pat_ty);
514
515                     // Each match binding is effectively an assignment to the
516                     // binding being produced.
517                     let def = Res::Local(canonical_id);
518                     if let Ok(ref binding_place) = mc.cat_res(pat.hir_id, pat.span, pat_ty, def) {
519                         delegate.mutate(binding_place);
520                     }
521
522                     // It is also a borrow or copy/move of the value being matched.
523                     match bm {
524                         ty::BindByReference(m) => {
525                             let bk = ty::BorrowKind::from_mutbl(m);
526                             delegate.borrow(place, bk);
527                         }
528                         ty::BindByValue(..) => {
529                             let mode = copy_or_move(mc, place);
530                             debug!("walk_pat binding consuming pat");
531                             delegate.consume(place, mode);
532                         }
533                     }
534                 }
535             }
536         }));
537     }
538
539     fn walk_captures(&mut self, closure_expr: &hir::Expr<'_>, fn_decl_span: Span) {
540         debug!("walk_captures({:?})", closure_expr);
541
542         let closure_def_id = self.tcx().hir().local_def_id(closure_expr.hir_id);
543         if let Some(upvars) = self.tcx().upvars_mentioned(closure_def_id) {
544             for &var_id in upvars.keys() {
545                 let upvar_id = ty::UpvarId {
546                     var_path: ty::UpvarPath { hir_id: var_id },
547                     closure_expr_id: closure_def_id,
548                 };
549                 let upvar_capture = self.mc.tables.upvar_capture(upvar_id);
550                 let captured_place = return_if_err!(self.cat_captured_var(
551                     closure_expr.hir_id,
552                     fn_decl_span,
553                     var_id,
554                 ));
555                 match upvar_capture {
556                     ty::UpvarCapture::ByValue => {
557                         let mode = copy_or_move(&self.mc, &captured_place);
558                         self.delegate.consume(&captured_place, mode);
559                     }
560                     ty::UpvarCapture::ByRef(upvar_borrow) => {
561                         self.delegate.borrow(&captured_place, upvar_borrow.kind);
562                     }
563                 }
564             }
565         }
566     }
567
568     fn cat_captured_var(
569         &mut self,
570         closure_hir_id: hir::HirId,
571         closure_span: Span,
572         var_id: hir::HirId,
573     ) -> mc::McResult<mc::PlaceWithHirId<'tcx>> {
574         // Create the place for the variable being borrowed, from the
575         // perspective of the creator (parent) of the closure.
576         let var_ty = self.mc.node_ty(var_id)?;
577         self.mc.cat_res(closure_hir_id, closure_span, var_ty, Res::Local(var_id))
578     }
579 }
580
581 fn copy_or_move<'a, 'tcx>(
582     mc: &mc::MemCategorizationContext<'a, 'tcx>,
583     place_with_id: &PlaceWithHirId<'tcx>,
584 ) -> ConsumeMode {
585     if !mc.type_is_copy_modulo_regions(
586         place_with_id.place.ty,
587         mc.tcx().hir().span(place_with_id.hir_id),
588     ) {
589         Move
590     } else {
591         Copy
592     }
593 }