]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/regionck.rs
ca6828cfdf68de599fee44ff104038bbb081a59c
[rust.git] / compiler / rustc_typeck / src / check / regionck.rs
1 //! The region check is a final pass that runs over the AST after we have
2 //! inferred the type constraints but before we have actually finalized
3 //! the types. Its purpose is to embed a variety of region constraints.
4 //! Inserting these constraints as a separate pass is good because (1) it
5 //! localizes the code that has to do with region inference and (2) often
6 //! we cannot know what constraints are needed until the basic types have
7 //! been inferred.
8 //!
9 //! ### Interaction with the borrow checker
10 //!
11 //! In general, the job of the borrowck module (which runs later) is to
12 //! check that all soundness criteria are met, given a particular set of
13 //! regions. The job of *this* module is to anticipate the needs of the
14 //! borrow checker and infer regions that will satisfy its requirements.
15 //! It is generally true that the inference doesn't need to be sound,
16 //! meaning that if there is a bug and we inferred bad regions, the borrow
17 //! checker should catch it. This is not entirely true though; for
18 //! example, the borrow checker doesn't check subtyping, and it doesn't
19 //! check that region pointers are always live when they are used. It
20 //! might be worthwhile to fix this so that borrowck serves as a kind of
21 //! verification step -- that would add confidence in the overall
22 //! correctness of the compiler, at the cost of duplicating some type
23 //! checks and effort.
24 //!
25 //! ### Inferring the duration of borrows, automatic and otherwise
26 //!
27 //! Whenever we introduce a borrowed pointer, for example as the result of
28 //! a borrow expression `let x = &data`, the lifetime of the pointer `x`
29 //! is always specified as a region inference variable. `regionck` has the
30 //! job of adding constraints such that this inference variable is as
31 //! narrow as possible while still accommodating all uses (that is, every
32 //! dereference of the resulting pointer must be within the lifetime).
33 //!
34 //! #### Reborrows
35 //!
36 //! Generally speaking, `regionck` does NOT try to ensure that the data
37 //! `data` will outlive the pointer `x`. That is the job of borrowck. The
38 //! one exception is when "re-borrowing" the contents of another borrowed
39 //! pointer. For example, imagine you have a borrowed pointer `b` with
40 //! lifetime `L1` and you have an expression `&*b`. The result of this
41 //! expression will be another borrowed pointer with lifetime `L2` (which is
42 //! an inference variable). The borrow checker is going to enforce the
43 //! constraint that `L2 < L1`, because otherwise you are re-borrowing data
44 //! for a lifetime larger than the original loan. However, without the
45 //! routines in this module, the region inferencer would not know of this
46 //! dependency and thus it might infer the lifetime of `L2` to be greater
47 //! than `L1` (issue #3148).
48 //!
49 //! There are a number of troublesome scenarios in the tests
50 //! `region-dependent-*.rs`, but here is one example:
51 //!
52 //!     struct Foo { i: i32 }
53 //!     struct Bar { foo: Foo  }
54 //!     fn get_i<'a>(x: &'a Bar) -> &'a i32 {
55 //!        let foo = &x.foo; // Lifetime L1
56 //!        &foo.i            // Lifetime L2
57 //!     }
58 //!
59 //! Note that this comes up either with `&` expressions, `ref`
60 //! bindings, and `autorefs`, which are the three ways to introduce
61 //! a borrow.
62 //!
63 //! The key point here is that when you are borrowing a value that
64 //! is "guaranteed" by a borrowed pointer, you must link the
65 //! lifetime of that borrowed pointer (`L1`, here) to the lifetime of
66 //! the borrow itself (`L2`). What do I mean by "guaranteed" by a
67 //! borrowed pointer? I mean any data that is reached by first
68 //! dereferencing a borrowed pointer and then either traversing
69 //! interior offsets or boxes. We say that the guarantor
70 //! of such data is the region of the borrowed pointer that was
71 //! traversed. This is essentially the same as the ownership
72 //! relation, except that a borrowed pointer never owns its
73 //! contents.
74
75 use crate::check::dropck;
76 use crate::check::FnCtxt;
77 use crate::mem_categorization as mc;
78 use crate::middle::region;
79 use rustc_hir as hir;
80 use rustc_hir::def_id::LocalDefId;
81 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
82 use rustc_hir::PatKind;
83 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
84 use rustc_infer::infer::{self, RegionObligation, RegionckMode};
85 use rustc_middle::hir::place::{PlaceBase, PlaceWithHirId};
86 use rustc_middle::ty::adjustment;
87 use rustc_middle::ty::{self, Ty};
88 use rustc_span::Span;
89 use rustc_trait_selection::infer::OutlivesEnvironmentExt;
90 use rustc_trait_selection::opaque_types::InferCtxtExt;
91 use std::ops::Deref;
92
93 // a variation on try that just returns unit
94 macro_rules! ignore_err {
95     ($e:expr) => {
96         match $e {
97             Ok(e) => e,
98             Err(_) => {
99                 debug!("ignoring mem-categorization error!");
100                 return ();
101             }
102         }
103     };
104 }
105
106 ///////////////////////////////////////////////////////////////////////////
107 // PUBLIC ENTRY POINTS
108
109 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
110     pub fn regionck_expr(&self, body: &'tcx hir::Body<'tcx>) {
111         let subject = self.tcx.hir().body_owner_def_id(body.id());
112         let id = body.value.hir_id;
113         let mut rcx = RegionCtxt::new(self, id, Subject(subject), self.param_env);
114
115         // There are no add'l implied bounds when checking a
116         // standalone expr (e.g., the `E` in a type like `[u32; E]`).
117         rcx.outlives_environment.save_implied_bounds(id);
118
119         if !self.errors_reported_since_creation() {
120             // regionck assumes typeck succeeded
121             rcx.visit_body(body);
122             rcx.visit_region_obligations(id);
123         }
124         rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
125     }
126
127     /// Region checking during the WF phase for items. `wf_tys` are the
128     /// types from which we should derive implied bounds, if any.
129     pub fn regionck_item(&self, item_id: hir::HirId, span: Span, wf_tys: &[Ty<'tcx>]) {
130         debug!("regionck_item(item.id={:?}, wf_tys={:?})", item_id, wf_tys);
131         let subject = self.tcx.hir().local_def_id(item_id);
132         let mut rcx = RegionCtxt::new(self, item_id, Subject(subject), self.param_env);
133         rcx.outlives_environment.add_implied_bounds(self, wf_tys, item_id, span);
134         rcx.outlives_environment.save_implied_bounds(item_id);
135         rcx.visit_region_obligations(item_id);
136         rcx.resolve_regions_and_report_errors(RegionckMode::default());
137     }
138
139     /// Region check a function body. Not invoked on closures, but
140     /// only on the "root" fn item (in which closures may be
141     /// embedded). Walks the function body and adds various add'l
142     /// constraints that are needed for region inference. This is
143     /// separated both to isolate "pure" region constraints from the
144     /// rest of type check and because sometimes we need type
145     /// inference to have completed before we can determine which
146     /// constraints to add.
147     pub fn regionck_fn(&self, fn_id: hir::HirId, body: &'tcx hir::Body<'tcx>) {
148         debug!("regionck_fn(id={})", fn_id);
149         let subject = self.tcx.hir().body_owner_def_id(body.id());
150         let hir_id = body.value.hir_id;
151         let mut rcx = RegionCtxt::new(self, hir_id, Subject(subject), self.param_env);
152
153         if !self.errors_reported_since_creation() {
154             // regionck assumes typeck succeeded
155             rcx.visit_fn_body(fn_id, body, self.tcx.hir().span(fn_id));
156         }
157
158         rcx.resolve_regions_and_report_errors(RegionckMode::for_item_body(self.tcx));
159     }
160 }
161
162 ///////////////////////////////////////////////////////////////////////////
163 // INTERNALS
164
165 pub struct RegionCtxt<'a, 'tcx> {
166     pub fcx: &'a FnCtxt<'a, 'tcx>,
167
168     pub region_scope_tree: &'tcx region::ScopeTree,
169
170     outlives_environment: OutlivesEnvironment<'tcx>,
171
172     // id of innermost fn body id
173     body_id: hir::HirId,
174     body_owner: LocalDefId,
175
176     // id of AST node being analyzed (the subject of the analysis).
177     subject_def_id: LocalDefId,
178 }
179
180 impl<'a, 'tcx> Deref for RegionCtxt<'a, 'tcx> {
181     type Target = FnCtxt<'a, 'tcx>;
182     fn deref(&self) -> &Self::Target {
183         &self.fcx
184     }
185 }
186
187 pub struct Subject(LocalDefId);
188
189 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
190     pub fn new(
191         fcx: &'a FnCtxt<'a, 'tcx>,
192         initial_body_id: hir::HirId,
193         Subject(subject): Subject,
194         param_env: ty::ParamEnv<'tcx>,
195     ) -> RegionCtxt<'a, 'tcx> {
196         let region_scope_tree = fcx.tcx.region_scope_tree(subject);
197         let outlives_environment = OutlivesEnvironment::new(param_env);
198         RegionCtxt {
199             fcx,
200             region_scope_tree,
201             body_id: initial_body_id,
202             body_owner: subject,
203             subject_def_id: subject,
204             outlives_environment,
205         }
206     }
207
208     /// Try to resolve the type for the given node, returning `t_err` if an error results. Note that
209     /// we never care about the details of the error, the same error will be detected and reported
210     /// in the writeback phase.
211     ///
212     /// Note one important point: we do not attempt to resolve *region variables* here. This is
213     /// because regionck is essentially adding constraints to those region variables and so may yet
214     /// influence how they are resolved.
215     ///
216     /// Consider this silly example:
217     ///
218     /// ```
219     /// fn borrow(x: &i32) -> &i32 {x}
220     /// fn foo(x: @i32) -> i32 {  // block: B
221     ///     let b = borrow(x);    // region: <R0>
222     ///     *b
223     /// }
224     /// ```
225     ///
226     /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
227     /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
228     /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
229     /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
230     /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
231     pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
232         self.resolve_vars_if_possible(unresolved_ty)
233     }
234
235     /// Try to resolve the type for the given node.
236     fn resolve_node_type(&self, id: hir::HirId) -> Ty<'tcx> {
237         let t = self.node_ty(id);
238         self.resolve_type(t)
239     }
240
241     /// This is the "main" function when region-checking a function item or a
242     /// closure within a function item. It begins by updating various fields
243     /// (e.g., `outlives_environment`) to be appropriate to the function and
244     /// then adds constraints derived from the function body.
245     ///
246     /// Note that it does **not** restore the state of the fields that
247     /// it updates! This is intentional, since -- for the main
248     /// function -- we wish to be able to read the final
249     /// `outlives_environment` and other fields from the caller. For
250     /// closures, however, we save and restore any "scoped state"
251     /// before we invoke this function. (See `visit_fn` in the
252     /// `intravisit::Visitor` impl below.)
253     fn visit_fn_body(
254         &mut self,
255         id: hir::HirId, // the id of the fn itself
256         body: &'tcx hir::Body<'tcx>,
257         span: Span,
258     ) {
259         // When we enter a function, we can derive
260         debug!("visit_fn_body(id={:?})", id);
261
262         let body_id = body.id();
263         self.body_id = body_id.hir_id;
264         self.body_owner = self.tcx.hir().body_owner_def_id(body_id);
265
266         let fn_sig = {
267             match self.typeck_results.borrow().liberated_fn_sigs().get(id) {
268                 Some(f) => *f,
269                 None => {
270                     bug!("No fn-sig entry for id={:?}", id);
271                 }
272             }
273         };
274
275         // Collect the types from which we create inferred bounds.
276         // For the return type, if diverging, substitute `bool` just
277         // because it will have no effect.
278         //
279         // FIXME(#27579) return types should not be implied bounds
280         let fn_sig_tys: Vec<_> =
281             fn_sig.inputs().iter().cloned().chain(Some(fn_sig.output())).collect();
282
283         self.outlives_environment.add_implied_bounds(
284             self.fcx,
285             &fn_sig_tys[..],
286             body_id.hir_id,
287             span,
288         );
289         self.outlives_environment.save_implied_bounds(body_id.hir_id);
290         self.link_fn_params(&body.params);
291         self.visit_body(body);
292         self.visit_region_obligations(body_id.hir_id);
293
294         self.constrain_opaque_types(self.outlives_environment.free_region_map());
295     }
296
297     fn visit_region_obligations(&mut self, hir_id: hir::HirId) {
298         debug!("visit_region_obligations: hir_id={:?}", hir_id);
299
300         // region checking can introduce new pending obligations
301         // which, when processed, might generate new region
302         // obligations. So make sure we process those.
303         self.select_all_obligations_or_error();
304     }
305
306     fn resolve_regions_and_report_errors(&self, mode: RegionckMode) {
307         self.infcx.process_registered_region_obligations(
308             self.outlives_environment.region_bound_pairs_map(),
309             Some(self.tcx.lifetimes.re_root_empty),
310             self.param_env,
311         );
312
313         self.fcx.resolve_regions_and_report_errors(
314             self.subject_def_id.to_def_id(),
315             &self.outlives_environment,
316             mode,
317         );
318     }
319
320     fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat<'_>) {
321         debug!("regionck::visit_pat(pat={:?})", pat);
322         pat.each_binding(|_, hir_id, span, _| {
323             let typ = self.resolve_node_type(hir_id);
324             let body_id = self.body_id;
325             dropck::check_drop_obligations(self, typ, span, body_id);
326         })
327     }
328 }
329
330 impl<'a, 'tcx> Visitor<'tcx> for RegionCtxt<'a, 'tcx> {
331     // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
332     // However, right now we run into an issue whereby some free
333     // regions are not properly related if they appear within the
334     // types of arguments that must be inferred. This could be
335     // addressed by deferring the construction of the region
336     // hierarchy, and in particular the relationships between free
337     // regions, until regionck, as described in #3238.
338
339     type Map = intravisit::ErasedMap<'tcx>;
340
341     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
342         NestedVisitorMap::None
343     }
344
345     fn visit_fn(
346         &mut self,
347         fk: intravisit::FnKind<'tcx>,
348         _: &'tcx hir::FnDecl<'tcx>,
349         body_id: hir::BodyId,
350         span: Span,
351         hir_id: hir::HirId,
352     ) {
353         assert!(
354             matches!(fk, intravisit::FnKind::Closure),
355             "visit_fn invoked for something other than a closure"
356         );
357
358         // Save state of current function before invoking
359         // `visit_fn_body`.  We will restore afterwards.
360         let old_body_id = self.body_id;
361         let old_body_owner = self.body_owner;
362         let env_snapshot = self.outlives_environment.push_snapshot_pre_closure();
363
364         let body = self.tcx.hir().body(body_id);
365         self.visit_fn_body(hir_id, body, span);
366
367         // Restore state from previous function.
368         self.outlives_environment.pop_snapshot_post_closure(env_snapshot);
369         self.body_id = old_body_id;
370         self.body_owner = old_body_owner;
371     }
372
373     //visit_pat: visit_pat, // (..) see above
374
375     fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) {
376         // see above
377         self.constrain_bindings_in_pat(&arm.pat);
378         intravisit::walk_arm(self, arm);
379     }
380
381     fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
382         // see above
383         self.constrain_bindings_in_pat(&l.pat);
384         self.link_local(l);
385         intravisit::walk_local(self, l);
386     }
387
388     fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) {
389         // Check any autoderefs or autorefs that appear.
390         let cmt_result = self.constrain_adjustments(expr);
391
392         // If necessary, constrain destructors in this expression. This will be
393         // the adjusted form if there is an adjustment.
394         match cmt_result {
395             Ok(head_cmt) => {
396                 self.check_safety_of_rvalue_destructor_if_necessary(&head_cmt, expr.span);
397             }
398             Err(..) => {
399                 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
400             }
401         }
402
403         match expr.kind {
404             hir::ExprKind::AddrOf(hir::BorrowKind::Ref, m, ref base) => {
405                 self.link_addr_of(expr, m, &base);
406
407                 intravisit::walk_expr(self, expr);
408             }
409
410             hir::ExprKind::Match(ref discr, ref arms, _) => {
411                 self.link_match(&discr, &arms[..]);
412
413                 intravisit::walk_expr(self, expr);
414             }
415
416             _ => intravisit::walk_expr(self, expr),
417         }
418     }
419 }
420
421 impl<'a, 'tcx> RegionCtxt<'a, 'tcx> {
422     /// Creates a temporary `MemCategorizationContext` and pass it to the closure.
423     fn with_mc<F, R>(&self, f: F) -> R
424     where
425         F: for<'b> FnOnce(mc::MemCategorizationContext<'b, 'tcx>) -> R,
426     {
427         f(mc::MemCategorizationContext::new(
428             &self.infcx,
429             self.outlives_environment.param_env,
430             self.body_owner,
431             &self.typeck_results.borrow(),
432         ))
433     }
434
435     /// Invoked on any adjustments that occur. Checks that if this is a region pointer being
436     /// dereferenced, the lifetime of the pointer includes the deref expr.
437     fn constrain_adjustments(
438         &mut self,
439         expr: &hir::Expr<'_>,
440     ) -> mc::McResult<PlaceWithHirId<'tcx>> {
441         debug!("constrain_adjustments(expr={:?})", expr);
442
443         let mut place = self.with_mc(|mc| mc.cat_expr_unadjusted(expr))?;
444
445         let typeck_results = self.typeck_results.borrow();
446         let adjustments = typeck_results.expr_adjustments(&expr);
447         if adjustments.is_empty() {
448             return Ok(place);
449         }
450
451         debug!("constrain_adjustments: adjustments={:?}", adjustments);
452
453         // If necessary, constrain destructors in the unadjusted form of this
454         // expression.
455         self.check_safety_of_rvalue_destructor_if_necessary(&place, expr.span);
456
457         for adjustment in adjustments {
458             debug!("constrain_adjustments: adjustment={:?}, place={:?}", adjustment, place);
459
460             if let adjustment::Adjust::Deref(Some(deref)) = adjustment.kind {
461                 self.link_region(
462                     expr.span,
463                     deref.region,
464                     ty::BorrowKind::from_mutbl(deref.mutbl),
465                     &place,
466                 );
467             }
468
469             if let adjustment::Adjust::Borrow(ref autoref) = adjustment.kind {
470                 self.link_autoref(expr, &place, autoref);
471             }
472
473             place = self.with_mc(|mc| mc.cat_expr_adjusted(expr, place, &adjustment))?;
474         }
475
476         Ok(place)
477     }
478
479     fn check_safety_of_rvalue_destructor_if_necessary(
480         &mut self,
481         place_with_id: &PlaceWithHirId<'tcx>,
482         span: Span,
483     ) {
484         if let PlaceBase::Rvalue = place_with_id.place.base {
485             if place_with_id.place.projections.is_empty() {
486                 let typ = self.resolve_type(place_with_id.place.ty());
487                 let body_id = self.body_id;
488                 dropck::check_drop_obligations(self, typ, span, body_id);
489             }
490         }
491     }
492     /// Adds constraints to inference such that `T: 'a` holds (or
493     /// reports an error if it cannot).
494     ///
495     /// # Parameters
496     ///
497     /// - `origin`, the reason we need this constraint
498     /// - `ty`, the type `T`
499     /// - `region`, the region `'a`
500     pub fn type_must_outlive(
501         &self,
502         origin: infer::SubregionOrigin<'tcx>,
503         ty: Ty<'tcx>,
504         region: ty::Region<'tcx>,
505     ) {
506         self.infcx.register_region_obligation(
507             self.body_id,
508             RegionObligation { sub_region: region, sup_type: ty, origin },
509         );
510     }
511
512     /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
513     /// resulting pointer is linked to the lifetime of its guarantor (if any).
514     fn link_addr_of(
515         &mut self,
516         expr: &hir::Expr<'_>,
517         mutability: hir::Mutability,
518         base: &hir::Expr<'_>,
519     ) {
520         debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
521
522         let cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(base)));
523
524         debug!("link_addr_of: cmt={:?}", cmt);
525
526         self.link_region_from_node_type(expr.span, expr.hir_id, mutability, &cmt);
527     }
528
529     /// Computes the guarantors for any ref bindings in a `let` and
530     /// then ensures that the lifetime of the resulting pointer is
531     /// linked to the lifetime of the initialization expression.
532     fn link_local(&self, local: &hir::Local<'_>) {
533         debug!("regionck::for_local()");
534         let init_expr = match local.init {
535             None => {
536                 return;
537             }
538             Some(ref expr) => &**expr,
539         };
540         let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(init_expr)));
541         self.link_pattern(discr_cmt, &local.pat);
542     }
543
544     /// Computes the guarantors for any ref bindings in a match and
545     /// then ensures that the lifetime of the resulting pointer is
546     /// linked to the lifetime of its guarantor (if any).
547     fn link_match(&self, discr: &hir::Expr<'_>, arms: &[hir::Arm<'_>]) {
548         debug!("regionck::for_match()");
549         let discr_cmt = ignore_err!(self.with_mc(|mc| mc.cat_expr(discr)));
550         debug!("discr_cmt={:?}", discr_cmt);
551         for arm in arms {
552             self.link_pattern(discr_cmt.clone(), &arm.pat);
553         }
554     }
555
556     /// Computes the guarantors for any ref bindings in a match and
557     /// then ensures that the lifetime of the resulting pointer is
558     /// linked to the lifetime of its guarantor (if any).
559     fn link_fn_params(&self, params: &[hir::Param<'_>]) {
560         for param in params {
561             let param_ty = self.node_ty(param.hir_id);
562             let param_cmt =
563                 self.with_mc(|mc| mc.cat_rvalue(param.hir_id, param.pat.span, param_ty));
564             debug!("param_ty={:?} param_cmt={:?} param={:?}", param_ty, param_cmt, param);
565             self.link_pattern(param_cmt, &param.pat);
566         }
567     }
568
569     /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
570     /// in the discriminant, if needed.
571     fn link_pattern(&self, discr_cmt: PlaceWithHirId<'tcx>, root_pat: &hir::Pat<'_>) {
572         debug!("link_pattern(discr_cmt={:?}, root_pat={:?})", discr_cmt, root_pat);
573         ignore_err!(self.with_mc(|mc| {
574             mc.cat_pattern(discr_cmt, root_pat, |sub_cmt, hir::Pat { kind, span, hir_id, .. }| {
575                 // `ref x` pattern
576                 if let PatKind::Binding(..) = kind {
577                     if let Some(ty::BindByReference(mutbl)) =
578                         mc.typeck_results.extract_binding_mode(self.tcx.sess, *hir_id, *span)
579                     {
580                         self.link_region_from_node_type(*span, *hir_id, mutbl, &sub_cmt);
581                     }
582                 }
583             })
584         }));
585     }
586
587     /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
588     /// autoref'd.
589     fn link_autoref(
590         &self,
591         expr: &hir::Expr<'_>,
592         expr_cmt: &PlaceWithHirId<'tcx>,
593         autoref: &adjustment::AutoBorrow<'tcx>,
594     ) {
595         debug!("link_autoref(autoref={:?}, expr_cmt={:?})", autoref, expr_cmt);
596
597         match *autoref {
598             adjustment::AutoBorrow::Ref(r, m) => {
599                 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m.into()), expr_cmt);
600             }
601
602             adjustment::AutoBorrow::RawPtr(_) => {}
603         }
604     }
605
606     /// Like `link_region()`, except that the region is extracted from the type of `id`,
607     /// which must be some reference (`&T`, `&str`, etc).
608     fn link_region_from_node_type(
609         &self,
610         span: Span,
611         id: hir::HirId,
612         mutbl: hir::Mutability,
613         cmt_borrowed: &PlaceWithHirId<'tcx>,
614     ) {
615         debug!(
616             "link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
617             id, mutbl, cmt_borrowed
618         );
619
620         let rptr_ty = self.resolve_node_type(id);
621         if let ty::Ref(r, _, _) = rptr_ty.kind() {
622             debug!("rptr_ty={}", rptr_ty);
623             self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl), cmt_borrowed);
624         }
625     }
626
627     /// Informs the inference engine that `borrow_cmt` is being borrowed with
628     /// kind `borrow_kind` and lifetime `borrow_region`.
629     /// In order to ensure borrowck is satisfied, this may create constraints
630     /// between regions, as explained in `link_reborrowed_region()`.
631     fn link_region(
632         &self,
633         span: Span,
634         borrow_region: ty::Region<'tcx>,
635         borrow_kind: ty::BorrowKind,
636         borrow_place: &PlaceWithHirId<'tcx>,
637     ) {
638         let origin = infer::DataBorrowed(borrow_place.place.ty(), span);
639         self.type_must_outlive(origin, borrow_place.place.ty(), borrow_region);
640
641         for pointer_ty in borrow_place.place.deref_tys() {
642             debug!(
643                 "link_region(borrow_region={:?}, borrow_kind={:?}, pointer_ty={:?})",
644                 borrow_region, borrow_kind, borrow_place
645             );
646             match *pointer_ty.kind() {
647                 ty::RawPtr(_) => return,
648                 ty::Ref(ref_region, _, ref_mutability) => {
649                     if self.link_reborrowed_region(span, borrow_region, ref_region, ref_mutability)
650                     {
651                         return;
652                     }
653                 }
654                 _ => assert!(pointer_ty.is_box(), "unexpected built-in deref type {}", pointer_ty),
655             }
656         }
657         if let PlaceBase::Upvar(upvar_id) = borrow_place.place.base {
658             self.link_upvar_region(span, borrow_region, upvar_id);
659         }
660     }
661
662     /// This is the most complicated case: the path being borrowed is
663     /// itself the referent of a borrowed pointer. Let me give an
664     /// example fragment of code to make clear(er) the situation:
665     ///
666     /// ```ignore (incomplete Rust code)
667     /// let r: &'a mut T = ...;  // the original reference "r" has lifetime 'a
668     /// ...
669     /// &'z *r                   // the reborrow has lifetime 'z
670     /// ```
671     ///
672     /// Now, in this case, our primary job is to add the inference
673     /// constraint that `'z <= 'a`. Given this setup, let's clarify the
674     /// parameters in (roughly) terms of the example:
675     ///
676     /// ```plain,ignore (pseudo-Rust)
677     /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
678     /// borrow_region   ^~                 ref_region    ^~
679     /// borrow_kind        ^~               ref_kind        ^~
680     /// ref_cmt                 ^
681     /// ```
682     ///
683     /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
684     ///
685     /// There is a complication beyond the simple scenario I just painted: there
686     /// may in fact be more levels of reborrowing. In the example, I said the
687     /// borrow was like `&'z *r`, but it might in fact be a borrow like
688     /// `&'z **q` where `q` has type `&'a &'b mut T`. In that case, we want to
689     /// ensure that `'z <= 'a` and `'z <= 'b`.
690     ///
691     /// The return value of this function indicates whether we *don't* need to
692     /// the recurse to the next reference up.
693     ///
694     /// This is explained more below.
695     fn link_reborrowed_region(
696         &self,
697         span: Span,
698         borrow_region: ty::Region<'tcx>,
699         ref_region: ty::Region<'tcx>,
700         ref_mutability: hir::Mutability,
701     ) -> bool {
702         debug!("link_reborrowed_region: {:?} <= {:?}", borrow_region, ref_region);
703         self.sub_regions(infer::Reborrow(span), borrow_region, ref_region);
704
705         // Decide whether we need to recurse and link any regions within
706         // the `ref_cmt`. This is concerned for the case where the value
707         // being reborrowed is in fact a borrowed pointer found within
708         // another borrowed pointer. For example:
709         //
710         //    let p: &'b &'a mut T = ...;
711         //    ...
712         //    &'z **p
713         //
714         // What makes this case particularly tricky is that, if the data
715         // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
716         // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
717         // (otherwise the user might mutate through the `&mut T` reference
718         // after `'b` expires and invalidate the borrow we are looking at
719         // now).
720         //
721         // So let's re-examine our parameters in light of this more
722         // complicated (possible) scenario:
723         //
724         //     A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
725         //     borrow_region   ^~                 ref_region             ^~
726         //     borrow_kind        ^~               ref_kind                 ^~
727         //     ref_cmt                 ^~~
728         //
729         // (Note that since we have not examined `ref_cmt.cat`, we don't
730         // know whether this scenario has occurred; but I wanted to show
731         // how all the types get adjusted.)
732         match ref_mutability {
733             hir::Mutability::Not => {
734                 // The reference being reborrowed is a shareable ref of
735                 // type `&'a T`. In this case, it doesn't matter where we
736                 // *found* the `&T` pointer, the memory it references will
737                 // be valid and immutable for `'a`. So we can stop here.
738                 true
739             }
740
741             hir::Mutability::Mut => {
742                 // The reference being reborrowed is either an `&mut T`. This is
743                 // the case where recursion is needed.
744                 false
745             }
746         }
747     }
748
749     /// An upvar may be behind up to 2 references:
750     ///
751     /// * One can come from the reference to a "by-reference" upvar.
752     /// * Another one can come from the reference to the closure itself if it's
753     ///   a `FnMut` or `Fn` closure.
754     ///
755     /// This function links the lifetimes of those references to the lifetime
756     /// of the borrow that's provided. See [RegionCtxt::link_reborrowed_region] for some
757     /// more explanation of this in the general case.
758     ///
759     /// We also supply a *cause*, and in this case we set the cause to
760     /// indicate that the reference being "reborrowed" is itself an upvar. This
761     /// provides a nicer error message should something go wrong.
762     fn link_upvar_region(
763         &self,
764         span: Span,
765         borrow_region: ty::Region<'tcx>,
766         upvar_id: ty::UpvarId,
767     ) {
768         debug!("link_upvar_region(borrorw_region={:?}, upvar_id={:?}", borrow_region, upvar_id);
769         // A by-reference upvar can't be borrowed for longer than the
770         // upvar is borrowed from the environment.
771         let closure_local_def_id = upvar_id.closure_expr_id;
772         let mut all_captures_are_imm_borrow = true;
773         for captured_place in self
774             .typeck_results
775             .borrow()
776             .closure_min_captures
777             .get(&closure_local_def_id.to_def_id())
778             .and_then(|root_var_min_cap| root_var_min_cap.get(&upvar_id.var_path.hir_id))
779             .into_iter()
780             .flatten()
781         {
782             match captured_place.info.capture_kind {
783                 ty::UpvarCapture::ByRef(upvar_borrow) => {
784                     self.sub_regions(
785                         infer::ReborrowUpvar(span, upvar_id),
786                         borrow_region,
787                         upvar_borrow.region,
788                     );
789                     if let ty::ImmBorrow = upvar_borrow.kind {
790                         debug!("link_upvar_region: capture by shared ref");
791                     } else {
792                         all_captures_are_imm_borrow = false;
793                     }
794                 }
795                 ty::UpvarCapture::ByValue(_) => {
796                     all_captures_are_imm_borrow = false;
797                 }
798             }
799         }
800         if all_captures_are_imm_borrow {
801             return;
802         }
803         let fn_hir_id = self.tcx.hir().local_def_id_to_hir_id(closure_local_def_id);
804         let ty = self.resolve_node_type(fn_hir_id);
805         debug!("link_upvar_region: ty={:?}", ty);
806
807         // A closure capture can't be borrowed for longer than the
808         // reference to the closure.
809         if let ty::Closure(_, substs) = ty.kind() {
810             match self.infcx.closure_kind(substs) {
811                 Some(ty::ClosureKind::Fn | ty::ClosureKind::FnMut) => {
812                     // Region of environment pointer
813                     let env_region = self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
814                         scope: upvar_id.closure_expr_id.to_def_id(),
815                         bound_region: ty::BrEnv,
816                     }));
817                     self.sub_regions(
818                         infer::ReborrowUpvar(span, upvar_id),
819                         borrow_region,
820                         env_region,
821                     );
822                 }
823                 Some(ty::ClosureKind::FnOnce) => {}
824                 None => {
825                     span_bug!(span, "Have not inferred closure kind before regionck");
826                 }
827             }
828         }
829     }
830 }