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