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