]> git.proxmox.com Git - rustc.git/blame - src/librustc_typeck/check/regionck.rs
New upstream version 1.14.0+dfsg1
[rustc.git] / src / librustc_typeck / check / regionck.rs
CommitLineData
1a4d82fc
JJ
1// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! The region check is a final pass that runs over the AST after we have
12//! inferred the type constraints but before we have actually finalized
13//! the types. Its purpose is to embed a variety of region constraints.
14//! Inserting these constraints as a separate pass is good because (1) it
15//! localizes the code that has to do with region inference and (2) often
16//! we cannot know what constraints are needed until the basic types have
17//! been inferred.
18//!
19//! ### Interaction with the borrow checker
20//!
21//! In general, the job of the borrowck module (which runs later) is to
22//! check that all soundness criteria are met, given a particular set of
23//! regions. The job of *this* module is to anticipate the needs of the
24//! borrow checker and infer regions that will satisfy its requirements.
25//! It is generally true that the inference doesn't need to be sound,
26//! meaning that if there is a bug and we inferred bad regions, the borrow
27//! checker should catch it. This is not entirely true though; for
28//! example, the borrow checker doesn't check subtyping, and it doesn't
29//! check that region pointers are always live when they are used. It
30//! might be worthwhile to fix this so that borrowck serves as a kind of
31//! verification step -- that would add confidence in the overall
32//! correctness of the compiler, at the cost of duplicating some type
33//! checks and effort.
34//!
35//! ### Inferring the duration of borrows, automatic and otherwise
36//!
37//! Whenever we introduce a borrowed pointer, for example as the result of
38//! a borrow expression `let x = &data`, the lifetime of the pointer `x`
39//! is always specified as a region inference variable. `regionck` has the
40//! job of adding constraints such that this inference variable is as
41//! narrow as possible while still accommodating all uses (that is, every
42//! dereference of the resulting pointer must be within the lifetime).
43//!
44//! #### Reborrows
45//!
46//! Generally speaking, `regionck` does NOT try to ensure that the data
47//! `data` will outlive the pointer `x`. That is the job of borrowck. The
48//! one exception is when "re-borrowing" the contents of another borrowed
49//! pointer. For example, imagine you have a borrowed pointer `b` with
50//! lifetime L1 and you have an expression `&*b`. The result of this
51//! expression will be another borrowed pointer with lifetime L2 (which is
52//! an inference variable). The borrow checker is going to enforce the
53//! constraint that L2 < L1, because otherwise you are re-borrowing data
54//! for a lifetime larger than the original loan. However, without the
55//! routines in this module, the region inferencer would not know of this
56//! dependency and thus it might infer the lifetime of L2 to be greater
57//! than L1 (issue #3148).
58//!
59//! There are a number of troublesome scenarios in the tests
60//! `region-dependent-*.rs`, but here is one example:
61//!
92a42be0 62//! struct Foo { i: i32 }
1a4d82fc 63//! struct Bar { foo: Foo }
9cc50fc6 64//! fn get_i<'a>(x: &'a Bar) -> &'a i32 {
1a4d82fc
JJ
65//! let foo = &x.foo; // Lifetime L1
66//! &foo.i // Lifetime L2
67//! }
68//!
69//! Note that this comes up either with `&` expressions, `ref`
70//! bindings, and `autorefs`, which are the three ways to introduce
71//! a borrow.
72//!
73//! The key point here is that when you are borrowing a value that
74//! is "guaranteed" by a borrowed pointer, you must link the
75//! lifetime of that borrowed pointer (L1, here) to the lifetime of
76//! the borrow itself (L2). What do I mean by "guaranteed" by a
77//! borrowed pointer? I mean any data that is reached by first
78//! dereferencing a borrowed pointer and then either traversing
62682a34 79//! interior offsets or boxes. We say that the guarantor
b039eaaf 80//! of such data is the region of the borrowed pointer that was
1a4d82fc
JJ
81//! traversed. This is essentially the same as the ownership
82//! relation, except that a borrowed pointer never owns its
83//! contents.
84
85aaf69f 85use check::dropck;
1a4d82fc 86use check::FnCtxt;
bd371182 87use middle::free_region::FreeRegionMap;
1a4d82fc 88use middle::mem_categorization as mc;
92a42be0 89use middle::mem_categorization::Categorization;
9cc50fc6 90use middle::region::{self, CodeExtent};
54a0048b
SL
91use rustc::ty::subst::Substs;
92use rustc::traits;
a7813a04
XL
93use rustc::ty::{self, Ty, MethodCall, TypeFoldable};
94use rustc::infer::{self, GenericKind, InferOk, SubregionOrigin, TypeOrigin, VerifyBound};
54a0048b
SL
95use hir::pat_util;
96use rustc::ty::adjustment;
97use rustc::ty::wf::ImpliedBound;
1a4d82fc 98
85aaf69f 99use std::mem;
a7813a04 100use std::ops::Deref;
e9174d1e 101use syntax::ast;
3157f602 102use syntax_pos::Span;
54a0048b
SL
103use rustc::hir::intravisit::{self, Visitor};
104use rustc::hir::{self, PatKind};
1a4d82fc 105
1a4d82fc
JJ
106use self::SubjectNode::Subject;
107
108// a variation on try that just returns unit
109macro_rules! ignore_err {
110 ($e:expr) => (match $e { Ok(e) => e, Err(_) => return () })
111}
112
113///////////////////////////////////////////////////////////////////////////
114// PUBLIC ENTRY POINTS
115
a7813a04
XL
116impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
117 pub fn regionck_expr(&self, e: &hir::Expr) {
118 let mut rcx = RegionCtxt::new(self, RepeatingScope(e.id), e.id, Subject(e.id));
119 if self.err_count_since_creation() == 0 {
120 // regionck assumes typeck succeeded
121 rcx.visit_expr(e);
122 rcx.visit_region_obligations(e.id);
123 }
124 rcx.resolve_regions_and_report_errors();
1a4d82fc 125 }
1a4d82fc 126
a7813a04
XL
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,
130 item_id: ast::NodeId,
131 span: Span,
132 wf_tys: &[Ty<'tcx>]) {
133 debug!("regionck_item(item.id={:?}, wf_tys={:?}", item_id, wf_tys);
134 let mut rcx = RegionCtxt::new(self, RepeatingScope(item_id), item_id, Subject(item_id));
135 rcx.free_region_map.relate_free_regions_from_predicates(
136 &self.parameter_environment.caller_bounds);
137 rcx.relate_free_regions(wf_tys, item_id, span);
138 rcx.visit_region_obligations(item_id);
139 rcx.resolve_regions_and_report_errors();
1a4d82fc
JJ
140 }
141
a7813a04
XL
142 pub fn regionck_fn(&self,
143 fn_id: ast::NodeId,
a7813a04
XL
144 decl: &hir::FnDecl,
145 blk: &hir::Block) {
146 debug!("regionck_fn(id={})", fn_id);
147 let mut rcx = RegionCtxt::new(self, RepeatingScope(blk.id), blk.id, Subject(fn_id));
148
149 if self.err_count_since_creation() == 0 {
150 // regionck assumes typeck succeeded
5bcae85e 151 rcx.visit_fn_body(fn_id, decl, blk, self.tcx.map.span(fn_id));
a7813a04
XL
152 }
153
154 rcx.free_region_map.relate_free_regions_from_predicates(
155 &self.parameter_environment.caller_bounds);
bd371182 156
a7813a04 157 rcx.resolve_regions_and_report_errors();
bd371182 158
a7813a04
XL
159 // For the top-level fn, store the free-region-map. We don't store
160 // any map for closures; they just share the same map as the
161 // function that created them.
162 self.tcx.store_free_region_map(fn_id, rcx.free_region_map);
163 }
1a4d82fc
JJ
164}
165
1a4d82fc
JJ
166///////////////////////////////////////////////////////////////////////////
167// INTERNALS
168
a7813a04
XL
169pub struct RegionCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
170 pub fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
1a4d82fc 171
9e0c209e 172 region_bound_pairs: Vec<(&'tcx ty::Region, GenericKind<'tcx>)>,
1a4d82fc 173
bd371182
AL
174 free_region_map: FreeRegionMap,
175
85aaf69f
SL
176 // id of innermost fn body id
177 body_id: ast::NodeId,
178
9cc50fc6
SL
179 // call_site scope of innermost fn
180 call_site_scope: Option<CodeExtent>,
181
1a4d82fc
JJ
182 // id of innermost fn or loop
183 repeating_scope: ast::NodeId,
184
185 // id of AST node being analyzed (the subject of the analysis).
186 subject: SubjectNode,
85aaf69f 187
1a4d82fc
JJ
188}
189
a7813a04
XL
190impl<'a, 'gcx, 'tcx> Deref for RegionCtxt<'a, 'gcx, 'tcx> {
191 type Target = FnCtxt<'a, 'gcx, 'tcx>;
192 fn deref(&self) -> &Self::Target {
193 &self.fcx
194 }
195}
196
c34b1796 197pub struct RepeatingScope(ast::NodeId);
1a4d82fc
JJ
198pub enum SubjectNode { Subject(ast::NodeId), None }
199
a7813a04
XL
200impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
201 pub fn new(fcx: &'a FnCtxt<'a, 'gcx, 'tcx>,
1a4d82fc 202 initial_repeating_scope: RepeatingScope,
85aaf69f 203 initial_body_id: ast::NodeId,
a7813a04 204 subject: SubjectNode) -> RegionCtxt<'a, 'gcx, 'tcx> {
85aaf69f 205 let RepeatingScope(initial_repeating_scope) = initial_repeating_scope;
a7813a04
XL
206 RegionCtxt {
207 fcx: fcx,
208 repeating_scope: initial_repeating_scope,
209 body_id: initial_body_id,
210 call_site_scope: None,
211 subject: subject,
212 region_bound_pairs: Vec::new(),
213 free_region_map: FreeRegionMap::new(),
85aaf69f 214 }
1a4d82fc
JJ
215 }
216
9cc50fc6
SL
217 fn set_call_site_scope(&mut self, call_site_scope: Option<CodeExtent>) -> Option<CodeExtent> {
218 mem::replace(&mut self.call_site_scope, call_site_scope)
219 }
220
85aaf69f
SL
221 fn set_body_id(&mut self, body_id: ast::NodeId) -> ast::NodeId {
222 mem::replace(&mut self.body_id, body_id)
223 }
224
225 fn set_repeating_scope(&mut self, scope: ast::NodeId) -> ast::NodeId {
226 mem::replace(&mut self.repeating_scope, scope)
1a4d82fc
JJ
227 }
228
229 /// Try to resolve the type for the given node, returning t_err if an error results. Note that
230 /// we never care about the details of the error, the same error will be detected and reported
231 /// in the writeback phase.
232 ///
233 /// Note one important point: we do not attempt to resolve *region variables* here. This is
234 /// because regionck is essentially adding constraints to those region variables and so may yet
235 /// influence how they are resolved.
236 ///
237 /// Consider this silly example:
238 ///
239 /// ```
92a42be0
SL
240 /// fn borrow(x: &i32) -> &i32 {x}
241 /// fn foo(x: @i32) -> i32 { // block: B
1a4d82fc
JJ
242 /// let b = borrow(x); // region: <R0>
243 /// *b
244 /// }
245 /// ```
246 ///
c34b1796 247 /// Here, the region of `b` will be `<R0>`. `<R0>` is constrained to be some subregion of the
1a4d82fc
JJ
248 /// block B and some superregion of the call. If we forced it now, we'd choose the smaller
249 /// region (the call). But that would make the *b illegal. Since we don't resolve, the type
92a42be0 250 /// of b will be `&<R0>.i32` and then `*b` will require that `<R0>` be bigger than the let and
1a4d82fc
JJ
251 /// the `*b` expression, so we will effectively resolve `<R0>` to be the block B.
252 pub fn resolve_type(&self, unresolved_ty: Ty<'tcx>) -> Ty<'tcx> {
a7813a04 253 self.resolve_type_vars_if_possible(&unresolved_ty)
1a4d82fc
JJ
254 }
255
256 /// Try to resolve the type for the given node.
257 fn resolve_node_type(&self, id: ast::NodeId) -> Ty<'tcx> {
a7813a04 258 let t = self.node_ty(id);
1a4d82fc
JJ
259 self.resolve_type(t)
260 }
261
1a4d82fc 262 /// Try to resolve the type for the given node.
e9174d1e 263 pub fn resolve_expr_type_adjusted(&mut self, expr: &hir::Expr) -> Ty<'tcx> {
c30ab7b3
SL
264 let ty = self.tables.borrow().expr_ty_adjusted(expr);
265 self.resolve_type(ty)
1a4d82fc
JJ
266 }
267
268 fn visit_fn_body(&mut self,
9cc50fc6 269 id: ast::NodeId, // the id of the fn itself
e9174d1e
SL
270 fn_decl: &hir::FnDecl,
271 body: &hir::Block,
85aaf69f 272 span: Span)
1a4d82fc
JJ
273 {
274 // When we enter a function, we can derive
85aaf69f 275 debug!("visit_fn_body(id={})", id);
1a4d82fc 276
a7813a04 277 let call_site = self.tcx.region_maps.lookup_code_extent(
9cc50fc6
SL
278 region::CodeExtentData::CallSiteScope { fn_id: id, body_id: body.id });
279 let old_call_site_scope = self.set_call_site_scope(Some(call_site));
280
92a42be0 281 let fn_sig = {
a7813a04 282 let fn_sig_map = &self.tables.borrow().liberated_fn_sigs;
92a42be0
SL
283 match fn_sig_map.get(&id) {
284 Some(f) => f.clone(),
285 None => {
54a0048b 286 bug!("No fn-sig entry for id={}", id);
92a42be0 287 }
1a4d82fc
JJ
288 }
289 };
290
bd371182
AL
291 let old_region_bounds_pairs_len = self.region_bound_pairs.len();
292
92a42be0
SL
293 // Collect the types from which we create inferred bounds.
294 // For the return type, if diverging, substitute `bool` just
295 // because it will have no effect.
296 //
9cc50fc6 297 // FIXME(#27579) return types should not be implied bounds
92a42be0
SL
298 let fn_sig_tys: Vec<_> =
299 fn_sig.inputs.iter()
300 .cloned()
5bcae85e 301 .chain(Some(fn_sig.output))
92a42be0
SL
302 .collect();
303
85aaf69f 304 let old_body_id = self.set_body_id(body.id);
92a42be0 305 self.relate_free_regions(&fn_sig_tys[..], body.id, span);
a7813a04
XL
306 self.link_fn_args(self.tcx.region_maps.node_extent(body.id),
307 &fn_decl.inputs[..]);
1a4d82fc
JJ
308 self.visit_block(body);
309 self.visit_region_obligations(body.id);
bd371182 310
9cc50fc6
SL
311 let call_site_scope = self.call_site_scope.unwrap();
312 debug!("visit_fn_body body.id {} call_site_scope: {:?}",
313 body.id, call_site_scope);
9e0c209e 314 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope));
a7813a04
XL
315 self.type_of_node_must_outlive(infer::CallReturn(span),
316 body.id,
9e0c209e 317 call_site_region);
9cc50fc6 318
bd371182
AL
319 self.region_bound_pairs.truncate(old_region_bounds_pairs_len);
320
85aaf69f 321 self.set_body_id(old_body_id);
9cc50fc6 322 self.set_call_site_scope(old_call_site_scope);
1a4d82fc
JJ
323 }
324
325 fn visit_region_obligations(&mut self, node_id: ast::NodeId)
326 {
327 debug!("visit_region_obligations: node_id={}", node_id);
85aaf69f
SL
328
329 // region checking can introduce new pending obligations
330 // which, when processed, might generate new region
331 // obligations. So make sure we process those.
a7813a04 332 self.select_all_obligations_or_error();
85aaf69f
SL
333
334 // Make a copy of the region obligations vec because we'll need
335 // to be able to borrow the fulfillment-cx below when projecting.
336 let region_obligations =
a7813a04 337 self.fulfillment_cx
c1a9b12d
SL
338 .borrow()
339 .region_obligations(node_id)
340 .to_vec();
85aaf69f
SL
341
342 for r_o in &region_obligations {
e9174d1e
SL
343 debug!("visit_region_obligations: r_o={:?} cause={:?}",
344 r_o, r_o.cause);
1a4d82fc 345 let sup_type = self.resolve_type(r_o.sup_type);
c30ab7b3 346 let origin = self.code_to_origin(&r_o.cause, sup_type);
a7813a04 347 self.type_must_outlive(origin, sup_type, r_o.sub_region);
1a4d82fc 348 }
85aaf69f
SL
349
350 // Processing the region obligations should not cause the list to grow further:
351 assert_eq!(region_obligations.len(),
a7813a04 352 self.fulfillment_cx.borrow().region_obligations(node_id).len());
e9174d1e
SL
353 }
354
355 fn code_to_origin(&self,
c30ab7b3
SL
356 cause: &traits::ObligationCause<'tcx>,
357 sup_type: Ty<'tcx>)
e9174d1e 358 -> SubregionOrigin<'tcx> {
c30ab7b3
SL
359 SubregionOrigin::from_obligation_cause(cause,
360 || infer::RelateParamBound(cause.span, sup_type))
e9174d1e
SL
361 }
362
1a4d82fc
JJ
363 /// This method populates the region map's `free_region_map`. It walks over the transformed
364 /// argument and return types for each function just before we check the body of that function,
365 /// looking for types where you have a borrowed pointer to other borrowed data (e.g., `&'a &'b
c34b1796 366 /// [usize]`. We do not allow references to outlive the things they point at, so we can assume
1a4d82fc
JJ
367 /// that `'a <= 'b`. This holds for both the argument and return types, basically because, on
368 /// the caller side, the caller is responsible for checking that the type of every expression
369 /// (including the actual values for the arguments, as well as the return type of the fn call)
370 /// is well-formed.
371 ///
372 /// Tests: `src/test/compile-fail/regions-free-region-ordering-*.rs`
373 fn relate_free_regions(&mut self,
374 fn_sig_tys: &[Ty<'tcx>],
85aaf69f
SL
375 body_id: ast::NodeId,
376 span: Span) {
1a4d82fc 377 debug!("relate_free_regions >>");
1a4d82fc 378
85aaf69f 379 for &ty in fn_sig_tys {
1a4d82fc 380 let ty = self.resolve_type(ty);
62682a34 381 debug!("relate_free_regions(t={:?})", ty);
a7813a04 382 let implied_bounds = ty::wf::implied_bounds(self, body_id, ty, span);
bd371182
AL
383
384 // Record any relations between free regions that we observe into the free-region-map.
e9174d1e 385 self.free_region_map.relate_free_regions_from_implied_bounds(&implied_bounds);
bd371182
AL
386
387 // But also record other relationships, such as `T:'x`,
388 // that don't go into the free-region-map but which we use
389 // here.
e9174d1e 390 for implication in implied_bounds {
62682a34 391 debug!("implication: {:?}", implication);
85aaf69f 392 match implication {
9e0c209e
SL
393 ImpliedBound::RegionSubRegion(&ty::ReFree(free_a),
394 &ty::ReVar(vid_b)) => {
a7813a04 395 self.add_given(free_a, vid_b);
1a4d82fc 396 }
e9174d1e
SL
397 ImpliedBound::RegionSubParam(r_a, param_b) => {
398 self.region_bound_pairs.push((r_a, GenericKind::Param(param_b)));
c34b1796 399 }
e9174d1e
SL
400 ImpliedBound::RegionSubProjection(r_a, projection_b) => {
401 self.region_bound_pairs.push((r_a, GenericKind::Projection(projection_b)));
402 }
403 ImpliedBound::RegionSubRegion(..) => {
1a4d82fc
JJ
404 // In principle, we could record (and take
405 // advantage of) every relationship here, but
406 // we are also free not to -- it simply means
407 // strictly less that we can successfully type
408 // check. (It may also be that we should
409 // revise our inference system to be more
410 // general and to make use of *every*
411 // relationship that arises here, but
412 // presently we do not.)
413 }
1a4d82fc
JJ
414 }
415 }
416 }
417
418 debug!("<< relate_free_regions");
419 }
420
421 fn resolve_regions_and_report_errors(&self) {
422 let subject_node_id = match self.subject {
423 Subject(s) => s,
424 SubjectNode::None => {
54a0048b
SL
425 bug!("cannot resolve_regions_and_report_errors \
426 without subject node");
1a4d82fc
JJ
427 }
428 };
429
a7813a04
XL
430 self.fcx.resolve_regions_and_report_errors(&self.free_region_map,
431 subject_node_id);
432 }
433
434 fn constrain_bindings_in_pat(&mut self, pat: &hir::Pat) {
435 let tcx = self.tcx;
436 debug!("regionck::visit_pat(pat={:?})", pat);
3157f602 437 pat_util::pat_bindings(pat, |_, id, span, _| {
a7813a04
XL
438 // If we have a variable that contains region'd data, that
439 // data will be accessible from anywhere that the variable is
440 // accessed. We must be wary of loops like this:
441 //
442 // // from src/test/compile-fail/borrowck-lend-flow.rs
443 // let mut v = box 3, w = box 4;
444 // let mut x = &mut w;
445 // loop {
446 // **x += 1; // (2)
447 // borrow(v); //~ ERROR cannot borrow
448 // x = &mut v; // (1)
449 // }
450 //
451 // Typically, we try to determine the region of a borrow from
452 // those points where it is dereferenced. In this case, one
453 // might imagine that the lifetime of `x` need only be the
454 // body of the loop. But of course this is incorrect because
455 // the pointer that is created at point (1) is consumed at
456 // point (2), meaning that it must be live across the loop
457 // iteration. The easiest way to guarantee this is to require
458 // that the lifetime of any regions that appear in a
459 // variable's type enclose at least the variable's scope.
460
461 let var_scope = tcx.region_maps.var_scope(id);
9e0c209e 462 let var_region = self.tcx.mk_region(ty::ReScope(var_scope));
a7813a04
XL
463
464 let origin = infer::BindingTypeIsNotValidAtDecl(span);
9e0c209e 465 self.type_of_node_must_outlive(origin, id, var_region);
a7813a04
XL
466
467 let typ = self.resolve_node_type(id);
468 dropck::check_safety_of_destructor_if_necessary(self, typ, span, var_scope);
469 })
1a4d82fc
JJ
470 }
471}
472
a7813a04 473impl<'a, 'gcx, 'tcx, 'v> Visitor<'v> for RegionCtxt<'a, 'gcx, 'tcx> {
1a4d82fc
JJ
474 // (..) FIXME(#3238) should use visit_pat, not visit_arm/visit_local,
475 // However, right now we run into an issue whereby some free
476 // regions are not properly related if they appear within the
477 // types of arguments that must be inferred. This could be
478 // addressed by deferring the construction of the region
479 // hierarchy, and in particular the relationships between free
480 // regions, until regionck, as described in #3238.
481
92a42be0 482 fn visit_fn(&mut self, _fk: intravisit::FnKind<'v>, fd: &'v hir::FnDecl,
e9174d1e 483 b: &'v hir::Block, span: Span, id: ast::NodeId) {
85aaf69f 484 self.visit_fn_body(id, fd, b, span)
1a4d82fc
JJ
485 }
486
1a4d82fc
JJ
487 //visit_pat: visit_pat, // (..) see above
488
a7813a04
XL
489 fn visit_arm(&mut self, arm: &hir::Arm) {
490 // see above
491 for p in &arm.pats {
492 self.constrain_bindings_in_pat(p);
493 }
494 intravisit::walk_arm(self, arm);
1a4d82fc
JJ
495 }
496
a7813a04
XL
497 fn visit_local(&mut self, l: &hir::Local) {
498 // see above
499 self.constrain_bindings_in_pat(&l.pat);
500 self.link_local(l);
501 intravisit::walk_local(self, l);
502 }
1a4d82fc 503
a7813a04
XL
504 fn visit_expr(&mut self, expr: &hir::Expr) {
505 debug!("regionck::visit_expr(e={:?}, repeating_scope={})",
506 expr, self.repeating_scope);
507
508 // No matter what, the type of each expression must outlive the
509 // scope of that expression. This also guarantees basic WF.
510 let expr_ty = self.resolve_node_type(expr.id);
511 // the region corresponding to this expression
9e0c209e 512 let expr_region = self.tcx.node_scope_region(expr.id);
a7813a04
XL
513 self.type_must_outlive(infer::ExprTypeIsNotInScope(expr_ty, expr.span),
514 expr_ty, expr_region);
515
516 let method_call = MethodCall::expr(expr.id);
517 let opt_method_callee = self.tables.borrow().method_map.get(&method_call).cloned();
518 let has_method_map = opt_method_callee.is_some();
519
520 // If we are calling a method (either explicitly or via an
521 // overloaded operator), check that all of the types provided as
522 // arguments for its type parameters are well-formed, and all the regions
523 // provided as arguments outlive the call.
524 if let Some(callee) = opt_method_callee {
525 let origin = match expr.node {
526 hir::ExprMethodCall(..) =>
527 infer::ParameterOrigin::MethodCall,
528 hir::ExprUnary(op, _) if op == hir::UnDeref =>
529 infer::ParameterOrigin::OverloadedDeref,
530 _ =>
531 infer::ParameterOrigin::OverloadedOperator
532 };
1a4d82fc 533
a7813a04
XL
534 self.substs_wf_in_scope(origin, &callee.substs, expr.span, expr_region);
535 self.type_must_outlive(infer::ExprTypeIsNotInScope(callee.ty, expr.span),
536 callee.ty, expr_region);
537 }
1a4d82fc 538
a7813a04
XL
539 // Check any autoderefs or autorefs that appear.
540 let adjustment = self.tables.borrow().adjustments.get(&expr.id).map(|a| a.clone());
541 if let Some(adjustment) = adjustment {
542 debug!("adjustment={:?}", adjustment);
c30ab7b3
SL
543 match adjustment.kind {
544 adjustment::Adjust::DerefRef { autoderefs, ref autoref, .. } => {
a7813a04
XL
545 let expr_ty = self.resolve_node_type(expr.id);
546 self.constrain_autoderefs(expr, autoderefs, expr_ty);
547 if let Some(ref autoref) = *autoref {
548 self.link_autoref(expr, autoderefs, autoref);
549
550 // Require that the resulting region encompasses
551 // the current node.
552 //
553 // FIXME(#6268) remove to support nested method calls
554 self.type_of_node_must_outlive(infer::AutoBorrow(expr.span),
555 expr.id, expr_region);
556 }
557 }
558 /*
9e0c209e 559 adjustment::AutoObject(_, ref bounds, ..) => {
a7813a04
XL
560 // Determine if we are casting `expr` to a trait
561 // instance. If so, we have to be sure that the type
562 // of the source obeys the new region bound.
563 let source_ty = self.resolve_node_type(expr.id);
564 self.type_must_outlive(infer::RelateObjectBound(expr.span),
565 source_ty, bounds.region_bound);
1a4d82fc 566 }
a7813a04
XL
567 */
568 _ => {}
1a4d82fc 569 }
a7813a04
XL
570
571 // If necessary, constrain destructors in the unadjusted form of this
572 // expression.
573 let cmt_result = {
574 let mc = mc::MemCategorizationContext::new(self);
575 mc.cat_expr_unadjusted(expr)
576 };
577 match cmt_result {
578 Ok(head_cmt) => {
579 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt,
580 expr.span);
581 }
582 Err(..) => {
583 self.tcx.sess.delay_span_bug(expr.span, "cat_expr_unadjusted Errd");
584 }
1a4d82fc 585 }
1a4d82fc 586 }
85aaf69f 587
a7813a04
XL
588 // If necessary, constrain destructors in this expression. This will be
589 // the adjusted form if there is an adjustment.
85aaf69f 590 let cmt_result = {
a7813a04
XL
591 let mc = mc::MemCategorizationContext::new(self);
592 mc.cat_expr(expr)
85aaf69f
SL
593 };
594 match cmt_result {
595 Ok(head_cmt) => {
a7813a04 596 self.check_safety_of_rvalue_destructor_if_necessary(head_cmt, expr.span);
85aaf69f
SL
597 }
598 Err(..) => {
a7813a04 599 self.tcx.sess.delay_span_bug(expr.span, "cat_expr Errd");
85aaf69f
SL
600 }
601 }
85aaf69f 602
a7813a04
XL
603 debug!("regionck::visit_expr(e={:?}, repeating_scope={}) - visiting subexprs",
604 expr, self.repeating_scope);
605 match expr.node {
606 hir::ExprPath(..) => {
607 self.fcx.opt_node_ty_substs(expr.id, |item_substs| {
608 let origin = infer::ParameterOrigin::Path;
609 self.substs_wf_in_scope(origin, &item_substs.substs, expr.span, expr_region);
610 });
1a4d82fc
JJ
611 }
612
a7813a04
XL
613 hir::ExprCall(ref callee, ref args) => {
614 if has_method_map {
615 self.constrain_call(expr, Some(&callee),
616 args.iter().map(|e| &**e), false);
617 } else {
618 self.constrain_callee(callee.id, expr, &callee);
619 self.constrain_call(expr, None,
620 args.iter().map(|e| &**e), false);
621 }
1a4d82fc 622
a7813a04
XL
623 intravisit::walk_expr(self, expr);
624 }
1a4d82fc 625
9e0c209e 626 hir::ExprMethodCall(.., ref args) => {
a7813a04
XL
627 self.constrain_call(expr, Some(&args[0]),
628 args[1..].iter().map(|e| &**e), false);
1a4d82fc 629
a7813a04 630 intravisit::walk_expr(self, expr);
1a4d82fc
JJ
631 }
632
a7813a04
XL
633 hir::ExprAssignOp(_, ref lhs, ref rhs) => {
634 if has_method_map {
635 self.constrain_call(expr, Some(&lhs),
636 Some(&**rhs).into_iter(), false);
637 }
1a4d82fc 638
a7813a04
XL
639 intravisit::walk_expr(self, expr);
640 }
1a4d82fc 641
a7813a04
XL
642 hir::ExprIndex(ref lhs, ref rhs) if has_method_map => {
643 self.constrain_call(expr, Some(&lhs),
644 Some(&**rhs).into_iter(), true);
1a4d82fc 645
a7813a04
XL
646 intravisit::walk_expr(self, expr);
647 },
1a4d82fc 648
a7813a04
XL
649 hir::ExprBinary(op, ref lhs, ref rhs) if has_method_map => {
650 let implicitly_ref_args = !op.node.is_by_value();
1a4d82fc 651
a7813a04
XL
652 // As `expr_method_call`, but the call is via an
653 // overloaded op. Note that we (sadly) currently use an
654 // implicit "by ref" sort of passing style here. This
655 // should be converted to an adjustment!
656 self.constrain_call(expr, Some(&lhs),
657 Some(&**rhs).into_iter(), implicitly_ref_args);
1a4d82fc 658
a7813a04 659 intravisit::walk_expr(self, expr);
85aaf69f 660 }
85aaf69f 661
a7813a04
XL
662 hir::ExprBinary(_, ref lhs, ref rhs) => {
663 // If you do `x OP y`, then the types of `x` and `y` must
664 // outlive the operation you are performing.
665 let lhs_ty = self.resolve_expr_type_adjusted(&lhs);
666 let rhs_ty = self.resolve_expr_type_adjusted(&rhs);
667 for &ty in &[lhs_ty, rhs_ty] {
668 self.type_must_outlive(infer::Operand(expr.span),
669 ty, expr_region);
670 }
671 intravisit::walk_expr(self, expr);
672 }
1a4d82fc 673
a7813a04
XL
674 hir::ExprUnary(op, ref lhs) if has_method_map => {
675 let implicitly_ref_args = !op.is_by_value();
1a4d82fc 676
a7813a04
XL
677 // As above.
678 self.constrain_call(expr, Some(&lhs),
679 None::<hir::Expr>.iter(), implicitly_ref_args);
1a4d82fc 680
a7813a04 681 intravisit::walk_expr(self, expr);
1a4d82fc
JJ
682 }
683
a7813a04
XL
684 hir::ExprUnary(hir::UnDeref, ref base) => {
685 // For *a, the lifetime of a must enclose the deref
686 let method_call = MethodCall::expr(expr.id);
687 let base_ty = match self.tables.borrow().method_map.get(&method_call) {
688 Some(method) => {
689 self.constrain_call(expr, Some(&base),
690 None::<hir::Expr>.iter(), true);
691 // late-bound regions in overloaded method calls are instantiated
692 let fn_ret = self.tcx.no_late_bound_regions(&method.ty.fn_ret());
5bcae85e 693 fn_ret.unwrap()
a7813a04
XL
694 }
695 None => self.resolve_node_type(base.id)
696 };
697 if let ty::TyRef(r_ptr, _) = base_ty.sty {
9e0c209e 698 self.mk_subregion_due_to_dereference(expr.span, expr_region, r_ptr);
a7813a04 699 }
1a4d82fc 700
a7813a04
XL
701 intravisit::walk_expr(self, expr);
702 }
1a4d82fc 703
a7813a04
XL
704 hir::ExprIndex(ref vec_expr, _) => {
705 // For a[b], the lifetime of a must enclose the deref
706 let vec_type = self.resolve_expr_type_adjusted(&vec_expr);
707 self.constrain_index(expr, vec_type);
1a4d82fc 708
a7813a04
XL
709 intravisit::walk_expr(self, expr);
710 }
1a4d82fc 711
a7813a04
XL
712 hir::ExprCast(ref source, _) => {
713 // Determine if we are casting `source` to a trait
714 // instance. If so, we have to be sure that the type of
715 // the source obeys the trait's region bound.
716 self.constrain_cast(expr, &source);
717 intravisit::walk_expr(self, expr);
718 }
1a4d82fc 719
a7813a04
XL
720 hir::ExprAddrOf(m, ref base) => {
721 self.link_addr_of(expr, m, &base);
722
723 // Require that when you write a `&expr` expression, the
724 // resulting pointer has a lifetime that encompasses the
725 // `&expr` expression itself. Note that we constraining
726 // the type of the node expr.id here *before applying
727 // adjustments*.
728 //
729 // FIXME(#6268) nested method calls requires that this rule change
730 let ty0 = self.resolve_node_type(expr.id);
731 self.type_must_outlive(infer::AddrOf(expr.span), ty0, expr_region);
732 intravisit::walk_expr(self, expr);
733 }
1a4d82fc 734
a7813a04
XL
735 hir::ExprMatch(ref discr, ref arms, _) => {
736 self.link_match(&discr, &arms[..]);
1a4d82fc 737
a7813a04
XL
738 intravisit::walk_expr(self, expr);
739 }
1a4d82fc 740
9e0c209e 741 hir::ExprClosure(.., ref body, _) => {
a7813a04
XL
742 self.check_expr_fn_block(expr, &body);
743 }
1a4d82fc 744
a7813a04
XL
745 hir::ExprLoop(ref body, _) => {
746 let repeating_scope = self.set_repeating_scope(body.id);
747 intravisit::walk_expr(self, expr);
748 self.set_repeating_scope(repeating_scope);
749 }
1a4d82fc 750
a7813a04
XL
751 hir::ExprWhile(ref cond, ref body, _) => {
752 let repeating_scope = self.set_repeating_scope(cond.id);
753 self.visit_expr(&cond);
1a4d82fc 754
a7813a04
XL
755 self.set_repeating_scope(body.id);
756 self.visit_block(&body);
1a4d82fc 757
a7813a04
XL
758 self.set_repeating_scope(repeating_scope);
759 }
1a4d82fc 760
a7813a04
XL
761 hir::ExprRet(Some(ref ret_expr)) => {
762 let call_site_scope = self.call_site_scope;
763 debug!("visit_expr ExprRet ret_expr.id {} call_site_scope: {:?}",
764 ret_expr.id, call_site_scope);
9e0c209e 765 let call_site_region = self.tcx.mk_region(ty::ReScope(call_site_scope.unwrap()));
a7813a04
XL
766 self.type_of_node_must_outlive(infer::CallReturn(ret_expr.span),
767 ret_expr.id,
9e0c209e 768 call_site_region);
a7813a04
XL
769 intravisit::walk_expr(self, expr);
770 }
9cc50fc6 771
a7813a04
XL
772 _ => {
773 intravisit::walk_expr(self, expr);
774 }
1a4d82fc
JJ
775 }
776 }
777}
778
a7813a04
XL
779impl<'a, 'gcx, 'tcx> RegionCtxt<'a, 'gcx, 'tcx> {
780 fn constrain_cast(&mut self,
781 cast_expr: &hir::Expr,
782 source_expr: &hir::Expr)
783 {
784 debug!("constrain_cast(cast_expr={:?}, source_expr={:?})",
785 cast_expr,
786 source_expr);
1a4d82fc 787
a7813a04
XL
788 let source_ty = self.resolve_node_type(source_expr.id);
789 let target_ty = self.resolve_node_type(cast_expr.id);
1a4d82fc 790
a7813a04
XL
791 self.walk_cast(cast_expr, source_ty, target_ty);
792 }
1a4d82fc 793
a7813a04
XL
794 fn walk_cast(&mut self,
795 cast_expr: &hir::Expr,
796 from_ty: Ty<'tcx>,
797 to_ty: Ty<'tcx>) {
62682a34
SL
798 debug!("walk_cast(from_ty={:?}, to_ty={:?})",
799 from_ty,
800 to_ty);
1a4d82fc 801 match (&from_ty.sty, &to_ty.sty) {
62682a34
SL
802 /*From:*/ (&ty::TyRef(from_r, ref from_mt),
803 /*To: */ &ty::TyRef(to_r, ref to_mt)) => {
1a4d82fc 804 // Target cannot outlive source, naturally.
9e0c209e 805 self.sub_regions(infer::Reborrow(cast_expr.span), to_r, from_r);
a7813a04 806 self.walk_cast(cast_expr, from_mt.ty, to_mt.ty);
1a4d82fc
JJ
807 }
808
809 /*From:*/ (_,
9e0c209e 810 /*To: */ &ty::TyTrait(ref obj)) => {
1a4d82fc
JJ
811 // When T is existentially quantified as a trait
812 // `Foo+'to`, it must outlive the region bound `'to`.
a7813a04 813 self.type_must_outlive(infer::RelateObjectBound(cast_expr.span),
9e0c209e 814 from_ty, obj.region_bound);
1a4d82fc
JJ
815 }
816
62682a34
SL
817 /*From:*/ (&ty::TyBox(from_referent_ty),
818 /*To: */ &ty::TyBox(to_referent_ty)) => {
a7813a04 819 self.walk_cast(cast_expr, from_referent_ty, to_referent_ty);
1a4d82fc
JJ
820 }
821
822 _ => { }
823 }
824 }
1a4d82fc 825
a7813a04
XL
826 fn check_expr_fn_block(&mut self,
827 expr: &hir::Expr,
828 body: &hir::Block) {
829 let repeating_scope = self.set_repeating_scope(body.id);
830 intravisit::walk_expr(self, expr);
831 self.set_repeating_scope(repeating_scope);
832 }
1a4d82fc 833
a7813a04
XL
834 fn constrain_callee(&mut self,
835 callee_id: ast::NodeId,
836 _call_expr: &hir::Expr,
837 _callee_expr: &hir::Expr) {
838 let callee_ty = self.resolve_node_type(callee_id);
839 match callee_ty.sty {
840 ty::TyFnDef(..) | ty::TyFnPtr(_) => { }
841 _ => {
842 // this should not happen, but it does if the program is
843 // erroneous
844 //
845 // bug!(
846 // callee_expr.span,
847 // "Calling non-function: {}",
848 // callee_ty);
849 }
1a4d82fc
JJ
850 }
851 }
1a4d82fc 852
a7813a04
XL
853 fn constrain_call<'b, I: Iterator<Item=&'b hir::Expr>>(&mut self,
854 call_expr: &hir::Expr,
855 receiver: Option<&hir::Expr>,
856 arg_exprs: I,
857 implicitly_ref_args: bool) {
858 //! Invoked on every call site (i.e., normal calls, method calls,
859 //! and overloaded operators). Constrains the regions which appear
860 //! in the type of the function. Also constrains the regions that
861 //! appear in the arguments appropriately.
862
863 debug!("constrain_call(call_expr={:?}, \
864 receiver={:?}, \
865 implicitly_ref_args={})",
866 call_expr,
867 receiver,
868 implicitly_ref_args);
869
870 // `callee_region` is the scope representing the time in which the
871 // call occurs.
872 //
873 // FIXME(#6268) to support nested method calls, should be callee_id
874 let callee_scope = self.tcx.region_maps.node_extent(call_expr.id);
9e0c209e 875 let callee_region = self.tcx.mk_region(ty::ReScope(callee_scope));
a7813a04
XL
876
877 debug!("callee_region={:?}", callee_region);
878
879 for arg_expr in arg_exprs {
880 debug!("Argument: {:?}", arg_expr);
881
882 // ensure that any regions appearing in the argument type are
883 // valid for at least the lifetime of the function:
884 self.type_of_node_must_outlive(infer::CallArg(arg_expr.span),
885 arg_expr.id, callee_region);
886
887 // unfortunately, there are two means of taking implicit
888 // references, and we need to propagate constraints as a
889 // result. modes are going away and the "DerefArgs" code
890 // should be ported to use adjustments
891 if implicitly_ref_args {
892 self.link_by_ref(arg_expr, callee_scope);
893 }
1a4d82fc 894 }
1a4d82fc 895
a7813a04
XL
896 // as loop above, but for receiver
897 if let Some(r) = receiver {
898 debug!("receiver: {:?}", r);
899 self.type_of_node_must_outlive(infer::CallRcvr(r.span),
900 r.id, callee_region);
901 if implicitly_ref_args {
902 self.link_by_ref(&r, callee_scope);
903 }
1a4d82fc
JJ
904 }
905 }
1a4d82fc 906
a7813a04
XL
907 /// Invoked on any auto-dereference that occurs. Checks that if this is a region pointer being
908 /// dereferenced, the lifetime of the pointer includes the deref expr.
909 fn constrain_autoderefs(&mut self,
910 deref_expr: &hir::Expr,
911 derefs: usize,
912 mut derefd_ty: Ty<'tcx>)
913 {
914 debug!("constrain_autoderefs(deref_expr={:?}, derefs={}, derefd_ty={:?})",
915 deref_expr,
916 derefs,
917 derefd_ty);
1a4d82fc 918
9e0c209e 919 let r_deref_expr = self.tcx.node_scope_region(deref_expr.id);
a7813a04
XL
920 for i in 0..derefs {
921 let method_call = MethodCall::autoderef(deref_expr.id, i as u32);
922 debug!("constrain_autoderefs: method_call={:?} (of {:?} total)", method_call, derefs);
1a4d82fc 923
a7813a04
XL
924 let method = self.tables.borrow().method_map.get(&method_call).map(|m| m.clone());
925
926 derefd_ty = match method {
927 Some(method) => {
928 debug!("constrain_autoderefs: #{} is overloaded, method={:?}",
929 i, method);
930
931 let origin = infer::ParameterOrigin::OverloadedDeref;
932 self.substs_wf_in_scope(origin, method.substs, deref_expr.span, r_deref_expr);
933
c30ab7b3 934 // Treat overloaded autoderefs as if an AutoBorrow adjustment
a7813a04
XL
935 // was applied on the base type, as that is always the case.
936 let fn_sig = method.ty.fn_sig();
937 let fn_sig = // late-bound regions should have been instantiated
938 self.tcx.no_late_bound_regions(fn_sig).unwrap();
939 let self_ty = fn_sig.inputs[0];
940 let (m, r) = match self_ty.sty {
941 ty::TyRef(r, ref m) => (m.mutbl, r),
942 _ => {
943 span_bug!(
944 deref_expr.span,
945 "bad overloaded deref type {:?}",
946 method.ty)
947 }
948 };
949
950 debug!("constrain_autoderefs: receiver r={:?} m={:?}",
951 r, m);
952
953 {
954 let mc = mc::MemCategorizationContext::new(self);
955 let self_cmt = ignore_err!(mc.cat_expr_autoderefd(deref_expr, i));
956 debug!("constrain_autoderefs: self_cmt={:?}",
957 self_cmt);
958 self.link_region(deref_expr.span, r,
959 ty::BorrowKind::from_mutbl(m), self_cmt);
960 }
1a4d82fc 961
a7813a04
XL
962 // Specialized version of constrain_call.
963 self.type_must_outlive(infer::CallRcvr(deref_expr.span),
964 self_ty, r_deref_expr);
5bcae85e
SL
965 self.type_must_outlive(infer::CallReturn(deref_expr.span),
966 fn_sig.output, r_deref_expr);
967 fn_sig.output
1a4d82fc 968 }
a7813a04
XL
969 None => derefd_ty
970 };
1a4d82fc 971
a7813a04
XL
972 if let ty::TyRef(r_ptr, _) = derefd_ty.sty {
973 self.mk_subregion_due_to_dereference(deref_expr.span,
9e0c209e 974 r_deref_expr, r_ptr);
a7813a04 975 }
1a4d82fc 976
a7813a04
XL
977 match derefd_ty.builtin_deref(true, ty::NoPreference) {
978 Some(mt) => derefd_ty = mt.ty,
979 /* if this type can't be dereferenced, then there's already an error
980 in the session saying so. Just bail out for now */
981 None => break
982 }
1a4d82fc
JJ
983 }
984 }
1a4d82fc 985
a7813a04
XL
986 pub fn mk_subregion_due_to_dereference(&mut self,
987 deref_span: Span,
9e0c209e
SL
988 minimum_lifetime: &'tcx ty::Region,
989 maximum_lifetime: &'tcx ty::Region) {
a7813a04
XL
990 self.sub_regions(infer::DerefPointer(deref_span),
991 minimum_lifetime, maximum_lifetime)
992 }
1a4d82fc 993
a7813a04
XL
994 fn check_safety_of_rvalue_destructor_if_necessary(&mut self,
995 cmt: mc::cmt<'tcx>,
996 span: Span) {
997 match cmt.cat {
998 Categorization::Rvalue(region) => {
9e0c209e 999 match *region {
a7813a04
XL
1000 ty::ReScope(rvalue_scope) => {
1001 let typ = self.resolve_type(cmt.ty);
1002 dropck::check_safety_of_destructor_if_necessary(self,
1003 typ,
1004 span,
1005 rvalue_scope);
1006 }
1007 ty::ReStatic => {}
9e0c209e 1008 _ => {
a7813a04
XL
1009 span_bug!(span,
1010 "unexpected rvalue region in rvalue \
1011 destructor safety checking: `{:?}`",
1012 region);
1013 }
85aaf69f
SL
1014 }
1015 }
a7813a04 1016 _ => {}
85aaf69f 1017 }
85aaf69f 1018 }
1a4d82fc 1019
a7813a04
XL
1020 /// Invoked on any index expression that occurs. Checks that if this is a slice
1021 /// being indexed, the lifetime of the pointer includes the deref expr.
1022 fn constrain_index(&mut self,
1023 index_expr: &hir::Expr,
1024 indexed_ty: Ty<'tcx>)
1025 {
1026 debug!("constrain_index(index_expr=?, indexed_ty={}",
1027 self.ty_to_string(indexed_ty));
1028
1029 let r_index_expr = ty::ReScope(self.tcx.region_maps.node_extent(index_expr.id));
1030 if let ty::TyRef(r_ptr, mt) = indexed_ty.sty {
1031 match mt.ty.sty {
1032 ty::TySlice(_) | ty::TyStr => {
1033 self.sub_regions(infer::IndexSlice(index_expr.span),
9e0c209e 1034 self.tcx.mk_region(r_index_expr), r_ptr);
a7813a04
XL
1035 }
1036 _ => {}
1a4d82fc 1037 }
1a4d82fc
JJ
1038 }
1039 }
1a4d82fc 1040
a7813a04
XL
1041 /// Guarantees that any lifetimes which appear in the type of the node `id` (after applying
1042 /// adjustments) are valid for at least `minimum_lifetime`
1043 fn type_of_node_must_outlive(&mut self,
1044 origin: infer::SubregionOrigin<'tcx>,
1045 id: ast::NodeId,
9e0c209e 1046 minimum_lifetime: &'tcx ty::Region)
a7813a04 1047 {
a7813a04
XL
1048 // Try to resolve the type. If we encounter an error, then typeck
1049 // is going to fail anyway, so just stop here and let typeck
1050 // report errors later on in the writeback phase.
1051 let ty0 = self.resolve_node_type(id);
c30ab7b3
SL
1052 let ty = self.tables.borrow().adjustments.get(&id).map_or(ty0, |adj| adj.target);
1053 let ty = self.resolve_type(ty);
a7813a04
XL
1054 debug!("constrain_regions_in_type_of_node(\
1055 ty={}, ty0={}, id={}, minimum_lifetime={:?})",
1056 ty, ty0,
1057 id, minimum_lifetime);
1058 self.type_must_outlive(origin, ty, minimum_lifetime);
1059 }
1a4d82fc 1060
a7813a04
XL
1061 /// Computes the guarantor for an expression `&base` and then ensures that the lifetime of the
1062 /// resulting pointer is linked to the lifetime of its guarantor (if any).
1063 fn link_addr_of(&mut self, expr: &hir::Expr,
1064 mutability: hir::Mutability, base: &hir::Expr) {
1065 debug!("link_addr_of(expr={:?}, base={:?})", expr, base);
1a4d82fc 1066
a7813a04
XL
1067 let cmt = {
1068 let mc = mc::MemCategorizationContext::new(self);
1069 ignore_err!(mc.cat_expr(base))
1070 };
1a4d82fc 1071
a7813a04 1072 debug!("link_addr_of: cmt={:?}", cmt);
1a4d82fc 1073
a7813a04
XL
1074 self.link_region_from_node_type(expr.span, expr.id, mutability, cmt);
1075 }
1a4d82fc 1076
a7813a04
XL
1077 /// Computes the guarantors for any ref bindings in a `let` and
1078 /// then ensures that the lifetime of the resulting pointer is
1079 /// linked to the lifetime of the initialization expression.
1080 fn link_local(&self, local: &hir::Local) {
1081 debug!("regionck::for_local()");
1082 let init_expr = match local.init {
1083 None => { return; }
1084 Some(ref expr) => &**expr,
1085 };
1086 let mc = mc::MemCategorizationContext::new(self);
1087 let discr_cmt = ignore_err!(mc.cat_expr(init_expr));
1088 self.link_pattern(mc, discr_cmt, &local.pat);
1089 }
1a4d82fc 1090
a7813a04
XL
1091 /// Computes the guarantors for any ref bindings in a match and
1092 /// then ensures that the lifetime of the resulting pointer is
1093 /// linked to the lifetime of its guarantor (if any).
1094 fn link_match(&self, discr: &hir::Expr, arms: &[hir::Arm]) {
1095 debug!("regionck::for_match()");
1096 let mc = mc::MemCategorizationContext::new(self);
1097 let discr_cmt = ignore_err!(mc.cat_expr(discr));
1098 debug!("discr_cmt={:?}", discr_cmt);
1099 for arm in arms {
1100 for root_pat in &arm.pats {
1101 self.link_pattern(mc, discr_cmt.clone(), &root_pat);
1102 }
1a4d82fc
JJ
1103 }
1104 }
1a4d82fc 1105
a7813a04
XL
1106 /// Computes the guarantors for any ref bindings in a match and
1107 /// then ensures that the lifetime of the resulting pointer is
1108 /// linked to the lifetime of its guarantor (if any).
1109 fn link_fn_args(&self, body_scope: CodeExtent, args: &[hir::Arg]) {
1110 debug!("regionck::link_fn_args(body_scope={:?})", body_scope);
1111 let mc = mc::MemCategorizationContext::new(self);
1112 for arg in args {
1113 let arg_ty = self.node_ty(arg.id);
9e0c209e 1114 let re_scope = self.tcx.mk_region(ty::ReScope(body_scope));
a7813a04
XL
1115 let arg_cmt = mc.cat_rvalue(arg.id, arg.ty.span, re_scope, arg_ty);
1116 debug!("arg_ty={:?} arg_cmt={:?} arg={:?}",
1117 arg_ty,
1118 arg_cmt,
1119 arg);
1120 self.link_pattern(mc, arg_cmt, &arg.pat);
1121 }
1a4d82fc 1122 }
1a4d82fc 1123
a7813a04
XL
1124 /// Link lifetimes of any ref bindings in `root_pat` to the pointers found
1125 /// in the discriminant, if needed.
1126 fn link_pattern<'t>(&self,
1127 mc: mc::MemCategorizationContext<'a, 'gcx, 'tcx>,
1128 discr_cmt: mc::cmt<'tcx>,
1129 root_pat: &hir::Pat) {
1130 debug!("link_pattern(discr_cmt={:?}, root_pat={:?})",
1131 discr_cmt,
1132 root_pat);
3157f602 1133 let _ = mc.cat_pattern(discr_cmt, root_pat, |_, sub_cmt, sub_pat| {
a7813a04
XL
1134 match sub_pat.node {
1135 // `ref x` pattern
9e0c209e 1136 PatKind::Binding(hir::BindByRef(mutbl), ..) => {
a7813a04
XL
1137 self.link_region_from_node_type(sub_pat.span, sub_pat.id,
1138 mutbl, sub_cmt);
1139 }
a7813a04 1140 _ => {}
1a4d82fc 1141 }
a7813a04
XL
1142 });
1143 }
1a4d82fc 1144
a7813a04
XL
1145 /// Link lifetime of borrowed pointer resulting from autoref to lifetimes in the value being
1146 /// autoref'd.
1147 fn link_autoref(&self,
1148 expr: &hir::Expr,
1149 autoderefs: usize,
c30ab7b3 1150 autoref: &adjustment::AutoBorrow<'tcx>)
a7813a04
XL
1151 {
1152 debug!("link_autoref(autoref={:?})", autoref);
1153 let mc = mc::MemCategorizationContext::new(self);
1154 let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs));
1155 debug!("expr_cmt={:?}", expr_cmt);
1156
1157 match *autoref {
c30ab7b3 1158 adjustment::AutoBorrow::Ref(r, m) => {
a7813a04
XL
1159 self.link_region(expr.span, r,
1160 ty::BorrowKind::from_mutbl(m), expr_cmt);
1161 }
1a4d82fc 1162
c30ab7b3 1163 adjustment::AutoBorrow::RawPtr(m) => {
9e0c209e
SL
1164 let r = self.tcx.node_scope_region(expr.id);
1165 self.link_region(expr.span, r, ty::BorrowKind::from_mutbl(m), expr_cmt);
a7813a04 1166 }
9346a6ac 1167 }
1a4d82fc 1168 }
1a4d82fc 1169
a7813a04
XL
1170 /// Computes the guarantor for cases where the `expr` is being passed by implicit reference and
1171 /// must outlive `callee_scope`.
1172 fn link_by_ref(&self,
1173 expr: &hir::Expr,
1174 callee_scope: CodeExtent) {
1175 debug!("link_by_ref(expr={:?}, callee_scope={:?})",
1176 expr, callee_scope);
1177 let mc = mc::MemCategorizationContext::new(self);
1178 let expr_cmt = ignore_err!(mc.cat_expr(expr));
9e0c209e
SL
1179 let borrow_region = self.tcx.mk_region(ty::ReScope(callee_scope));
1180 self.link_region(expr.span, borrow_region, ty::ImmBorrow, expr_cmt);
a7813a04 1181 }
1a4d82fc 1182
a7813a04
XL
1183 /// Like `link_region()`, except that the region is extracted from the type of `id`,
1184 /// which must be some reference (`&T`, `&str`, etc).
1185 fn link_region_from_node_type(&self,
1186 span: Span,
1187 id: ast::NodeId,
1188 mutbl: hir::Mutability,
1189 cmt_borrowed: mc::cmt<'tcx>) {
1190 debug!("link_region_from_node_type(id={:?}, mutbl={:?}, cmt_borrowed={:?})",
1191 id, mutbl, cmt_borrowed);
1192
1193 let rptr_ty = self.resolve_node_type(id);
9e0c209e 1194 if let ty::TyRef(r, _) = rptr_ty.sty {
a7813a04 1195 debug!("rptr_ty={}", rptr_ty);
9e0c209e 1196 self.link_region(span, r, ty::BorrowKind::from_mutbl(mutbl),
a7813a04
XL
1197 cmt_borrowed);
1198 }
1a4d82fc 1199 }
1a4d82fc 1200
a7813a04
XL
1201 /// Informs the inference engine that `borrow_cmt` is being borrowed with
1202 /// kind `borrow_kind` and lifetime `borrow_region`.
1203 /// In order to ensure borrowck is satisfied, this may create constraints
1204 /// between regions, as explained in `link_reborrowed_region()`.
1205 fn link_region(&self,
1206 span: Span,
9e0c209e 1207 borrow_region: &'tcx ty::Region,
a7813a04
XL
1208 borrow_kind: ty::BorrowKind,
1209 borrow_cmt: mc::cmt<'tcx>) {
1210 let mut borrow_cmt = borrow_cmt;
1211 let mut borrow_kind = borrow_kind;
1212
1213 let origin = infer::DataBorrowed(borrow_cmt.ty, span);
9e0c209e 1214 self.type_must_outlive(origin, borrow_cmt.ty, borrow_region);
a7813a04
XL
1215
1216 loop {
1217 debug!("link_region(borrow_region={:?}, borrow_kind={:?}, borrow_cmt={:?})",
1218 borrow_region,
1219 borrow_kind,
1220 borrow_cmt);
1221 match borrow_cmt.cat.clone() {
1222 Categorization::Deref(ref_cmt, _,
1223 mc::Implicit(ref_kind, ref_region)) |
1224 Categorization::Deref(ref_cmt, _,
1225 mc::BorrowedPtr(ref_kind, ref_region)) => {
1226 match self.link_reborrowed_region(span,
1227 borrow_region, borrow_kind,
1228 ref_cmt, ref_region, ref_kind,
1229 borrow_cmt.note) {
1230 Some((c, k)) => {
1231 borrow_cmt = c;
1232 borrow_kind = k;
1233 }
1234 None => {
1235 return;
1236 }
1237 }
1238 }
1a4d82fc 1239
a7813a04
XL
1240 Categorization::Downcast(cmt_base, _) |
1241 Categorization::Deref(cmt_base, _, mc::Unique) |
1242 Categorization::Interior(cmt_base, _) => {
1243 // Borrowing interior or owned data requires the base
1244 // to be valid and borrowable in the same fashion.
1245 borrow_cmt = cmt_base;
1246 borrow_kind = borrow_kind;
1247 }
e9174d1e 1248
9e0c209e 1249 Categorization::Deref(.., mc::UnsafePtr(..)) |
a7813a04
XL
1250 Categorization::StaticItem |
1251 Categorization::Upvar(..) |
1252 Categorization::Local(..) |
1253 Categorization::Rvalue(..) => {
1254 // These are all "base cases" with independent lifetimes
1255 // that are not subject to inference
1256 return;
1257 }
1258 }
1259 }
1260 }
1261
1262 /// This is the most complicated case: the path being borrowed is
1263 /// itself the referent of a borrowed pointer. Let me give an
1264 /// example fragment of code to make clear(er) the situation:
1265 ///
1266 /// let r: &'a mut T = ...; // the original reference "r" has lifetime 'a
1267 /// ...
1268 /// &'z *r // the reborrow has lifetime 'z
1269 ///
1270 /// Now, in this case, our primary job is to add the inference
1271 /// constraint that `'z <= 'a`. Given this setup, let's clarify the
1272 /// parameters in (roughly) terms of the example:
1273 ///
1274 /// A borrow of: `& 'z bk * r` where `r` has type `& 'a bk T`
1275 /// borrow_region ^~ ref_region ^~
1276 /// borrow_kind ^~ ref_kind ^~
1277 /// ref_cmt ^
1278 ///
1279 /// Here `bk` stands for some borrow-kind (e.g., `mut`, `uniq`, etc).
1280 ///
1281 /// Unfortunately, there are some complications beyond the simple
1282 /// scenario I just painted:
1283 ///
1284 /// 1. The reference `r` might in fact be a "by-ref" upvar. In that
1285 /// case, we have two jobs. First, we are inferring whether this reference
1286 /// should be an `&T`, `&mut T`, or `&uniq T` reference, and we must
1287 /// adjust that based on this borrow (e.g., if this is an `&mut` borrow,
1288 /// then `r` must be an `&mut` reference). Second, whenever we link
1289 /// two regions (here, `'z <= 'a`), we supply a *cause*, and in this
1290 /// case we adjust the cause to indicate that the reference being
1291 /// "reborrowed" is itself an upvar. This provides a nicer error message
1292 /// should something go wrong.
1293 ///
1294 /// 2. There may in fact be more levels of reborrowing. In the
1295 /// example, I said the borrow was like `&'z *r`, but it might
1296 /// in fact be a borrow like `&'z **q` where `q` has type `&'a
1297 /// &'b mut T`. In that case, we want to ensure that `'z <= 'a`
1298 /// and `'z <= 'b`. This is explained more below.
1299 ///
1300 /// The return value of this function indicates whether we need to
1301 /// recurse and process `ref_cmt` (see case 2 above).
1302 fn link_reborrowed_region(&self,
1303 span: Span,
9e0c209e 1304 borrow_region: &'tcx ty::Region,
a7813a04
XL
1305 borrow_kind: ty::BorrowKind,
1306 ref_cmt: mc::cmt<'tcx>,
9e0c209e 1307 ref_region: &'tcx ty::Region,
a7813a04
XL
1308 mut ref_kind: ty::BorrowKind,
1309 note: mc::Note)
1310 -> Option<(mc::cmt<'tcx>, ty::BorrowKind)>
1311 {
1312 // Possible upvar ID we may need later to create an entry in the
1313 // maybe link map.
1314
1315 // Detect by-ref upvar `x`:
1316 let cause = match note {
1317 mc::NoteUpvarRef(ref upvar_id) => {
1318 let upvar_capture_map = &self.tables.borrow_mut().upvar_capture_map;
1319 match upvar_capture_map.get(upvar_id) {
1320 Some(&ty::UpvarCapture::ByRef(ref upvar_borrow)) => {
1321 // The mutability of the upvar may have been modified
1322 // by the above adjustment, so update our local variable.
1323 ref_kind = upvar_borrow.kind;
1324
1325 infer::ReborrowUpvar(span, *upvar_id)
1a4d82fc 1326 }
a7813a04
XL
1327 _ => {
1328 span_bug!( span, "Illegal upvar id: {:?}", upvar_id);
1a4d82fc
JJ
1329 }
1330 }
1331 }
a7813a04
XL
1332 mc::NoteClosureEnv(ref upvar_id) => {
1333 // We don't have any mutability changes to propagate, but
1334 // we do want to note that an upvar reborrow caused this
1335 // link
1336 infer::ReborrowUpvar(span, *upvar_id)
1337 }
1338 _ => {
1339 infer::Reborrow(span)
1340 }
1341 };
1a4d82fc 1342
a7813a04
XL
1343 debug!("link_reborrowed_region: {:?} <= {:?}",
1344 borrow_region,
1345 ref_region);
9e0c209e 1346 self.sub_regions(cause, borrow_region, ref_region);
a7813a04
XL
1347
1348 // If we end up needing to recurse and establish a region link
1349 // with `ref_cmt`, calculate what borrow kind we will end up
1350 // needing. This will be used below.
1351 //
1352 // One interesting twist is that we can weaken the borrow kind
1353 // when we recurse: to reborrow an `&mut` referent as mutable,
1354 // borrowck requires a unique path to the `&mut` reference but not
1355 // necessarily a *mutable* path.
1356 let new_borrow_kind = match borrow_kind {
1357 ty::ImmBorrow =>
1358 ty::ImmBorrow,
1359 ty::MutBorrow | ty::UniqueImmBorrow =>
1360 ty::UniqueImmBorrow
1361 };
1362
1363 // Decide whether we need to recurse and link any regions within
1364 // the `ref_cmt`. This is concerned for the case where the value
1365 // being reborrowed is in fact a borrowed pointer found within
1366 // another borrowed pointer. For example:
1367 //
1368 // let p: &'b &'a mut T = ...;
1369 // ...
1370 // &'z **p
1371 //
1372 // What makes this case particularly tricky is that, if the data
1373 // being borrowed is a `&mut` or `&uniq` borrow, borrowck requires
1374 // not only that `'z <= 'a`, (as before) but also `'z <= 'b`
1375 // (otherwise the user might mutate through the `&mut T` reference
1376 // after `'b` expires and invalidate the borrow we are looking at
1377 // now).
1378 //
1379 // So let's re-examine our parameters in light of this more
1380 // complicated (possible) scenario:
1381 //
1382 // A borrow of: `& 'z bk * * p` where `p` has type `&'b bk & 'a bk T`
1383 // borrow_region ^~ ref_region ^~
1384 // borrow_kind ^~ ref_kind ^~
1385 // ref_cmt ^~~
1386 //
1387 // (Note that since we have not examined `ref_cmt.cat`, we don't
1388 // know whether this scenario has occurred; but I wanted to show
1389 // how all the types get adjusted.)
1390 match ref_kind {
1391 ty::ImmBorrow => {
1392 // The reference being reborrowed is a sharable ref of
1393 // type `&'a T`. In this case, it doesn't matter where we
1394 // *found* the `&T` pointer, the memory it references will
1395 // be valid and immutable for `'a`. So we can stop here.
1396 //
1397 // (Note that the `borrow_kind` must also be ImmBorrow or
1398 // else the user is borrowed imm memory as mut memory,
1399 // which means they'll get an error downstream in borrowck
1400 // anyhow.)
1401 return None;
1a4d82fc
JJ
1402 }
1403
a7813a04
XL
1404 ty::MutBorrow | ty::UniqueImmBorrow => {
1405 // The reference being reborrowed is either an `&mut T` or
1406 // `&uniq T`. This is the case where recursion is needed.
1407 return Some((ref_cmt, new_borrow_kind));
1a4d82fc
JJ
1408 }
1409 }
1410 }
1a4d82fc 1411
a7813a04
XL
1412 /// Checks that the values provided for type/region arguments in a given
1413 /// expression are well-formed and in-scope.
1414 fn substs_wf_in_scope(&mut self,
1415 origin: infer::ParameterOrigin,
1416 substs: &Substs<'tcx>,
1417 expr_span: Span,
9e0c209e 1418 expr_region: &'tcx ty::Region) {
a7813a04
XL
1419 debug!("substs_wf_in_scope(substs={:?}, \
1420 expr_region={:?}, \
1421 origin={:?}, \
1422 expr_span={:?})",
1423 substs, expr_region, origin, expr_span);
1424
1425 let origin = infer::ParameterInScope(origin, expr_span);
1426
9e0c209e 1427 for region in substs.regions() {
a7813a04 1428 self.sub_regions(origin.clone(), expr_region, region);
1a4d82fc
JJ
1429 }
1430
9e0c209e 1431 for ty in substs.types() {
a7813a04
XL
1432 let ty = self.resolve_type(ty);
1433 self.type_must_outlive(origin.clone(), ty, expr_region);
1a4d82fc
JJ
1434 }
1435 }
1a4d82fc 1436
a7813a04
XL
1437 /// Ensures that type is well-formed in `region`, which implies (among
1438 /// other things) that all borrowed data reachable via `ty` outlives
1439 /// `region`.
1440 pub fn type_must_outlive(&self,
1441 origin: infer::SubregionOrigin<'tcx>,
1442 ty: Ty<'tcx>,
9e0c209e 1443 region: &'tcx ty::Region)
a7813a04
XL
1444 {
1445 let ty = self.resolve_type(ty);
e9174d1e 1446
a7813a04
XL
1447 debug!("type_must_outlive(ty={:?}, region={:?}, origin={:?})",
1448 ty,
1449 region,
1450 origin);
e9174d1e 1451
a7813a04 1452 assert!(!ty.has_escaping_regions());
e9174d1e 1453
c30ab7b3 1454 let components = self.tcx.outlives_components(ty);
a7813a04
XL
1455 self.components_must_outlive(origin, components, region);
1456 }
1457
1458 fn components_must_outlive(&self,
1459 origin: infer::SubregionOrigin<'tcx>,
1460 components: Vec<ty::outlives::Component<'tcx>>,
9e0c209e 1461 region: &'tcx ty::Region)
a7813a04
XL
1462 {
1463 for component in components {
1464 let origin = origin.clone();
1465 match component {
1466 ty::outlives::Component::Region(region1) => {
1467 self.sub_regions(origin, region, region1);
1468 }
1469 ty::outlives::Component::Param(param_ty) => {
1470 self.param_ty_must_outlive(origin, region, param_ty);
1471 }
1472 ty::outlives::Component::Projection(projection_ty) => {
1473 self.projection_must_outlive(origin, region, projection_ty);
1474 }
1475 ty::outlives::Component::EscapingProjection(subcomponents) => {
1476 self.components_must_outlive(origin, subcomponents, region);
1477 }
1478 ty::outlives::Component::UnresolvedInferenceVariable(v) => {
1479 // ignore this, we presume it will yield an error
1480 // later, since if a type variable is not resolved by
1481 // this point it never will be
1482 self.tcx.sess.delay_span_bug(
1483 origin.span(),
1484 &format!("unresolved inference variable in outlives: {:?}", v));
1485 }
1a4d82fc
JJ
1486 }
1487 }
1488 }
1a4d82fc 1489
a7813a04
XL
1490 fn param_ty_must_outlive(&self,
1491 origin: infer::SubregionOrigin<'tcx>,
9e0c209e 1492 region: &'tcx ty::Region,
a7813a04
XL
1493 param_ty: ty::ParamTy) {
1494 debug!("param_ty_must_outlive(region={:?}, param_ty={:?}, origin={:?})",
1495 region, param_ty, origin);
1a4d82fc 1496
a7813a04
XL
1497 let verify_bound = self.param_bound(param_ty);
1498 let generic = GenericKind::Param(param_ty);
1499 self.verify_generic_bound(origin, generic, region, verify_bound);
e9174d1e 1500 }
85aaf69f 1501
a7813a04
XL
1502 fn projection_must_outlive(&self,
1503 origin: infer::SubregionOrigin<'tcx>,
9e0c209e 1504 region: &'tcx ty::Region,
a7813a04
XL
1505 projection_ty: ty::ProjectionTy<'tcx>)
1506 {
1507 debug!("projection_must_outlive(region={:?}, projection_ty={:?}, origin={:?})",
1508 region, projection_ty, origin);
1509
1510 // This case is thorny for inference. The fundamental problem is
1511 // that there are many cases where we have choice, and inference
1512 // doesn't like choice (the current region inference in
1513 // particular). :) First off, we have to choose between using the
1514 // OutlivesProjectionEnv, OutlivesProjectionTraitDef, and
1515 // OutlivesProjectionComponent rules, any one of which is
1516 // sufficient. If there are no inference variables involved, it's
1517 // not hard to pick the right rule, but if there are, we're in a
1518 // bit of a catch 22: if we picked which rule we were going to
1519 // use, we could add constraints to the region inference graph
1520 // that make it apply, but if we don't add those constraints, the
1521 // rule might not apply (but another rule might). For now, we err
1522 // on the side of adding too few edges into the graph.
1523
1524 // Compute the bounds we can derive from the environment or trait
1525 // definition. We know that the projection outlives all the
1526 // regions in this list.
1527 let env_bounds = self.projection_declared_bounds(origin.span(), projection_ty);
1528
1529 debug!("projection_must_outlive: env_bounds={:?}",
1530 env_bounds);
1531
1532 // If we know that the projection outlives 'static, then we're
1533 // done here.
9e0c209e 1534 if env_bounds.contains(&&ty::ReStatic) {
a7813a04
XL
1535 debug!("projection_must_outlive: 'static as declared bound");
1536 return;
e9174d1e
SL
1537 }
1538
a7813a04
XL
1539 // If declared bounds list is empty, the only applicable rule is
1540 // OutlivesProjectionComponent. If there are inference variables,
1541 // then, we can break down the outlives into more primitive
1542 // components without adding unnecessary edges.
1543 //
1544 // If there are *no* inference variables, however, we COULD do
1545 // this, but we choose not to, because the error messages are less
1546 // good. For example, a requirement like `T::Item: 'r` would be
1547 // translated to a requirement that `T: 'r`; when this is reported
1548 // to the user, it will thus say "T: 'r must hold so that T::Item:
1549 // 'r holds". But that makes it sound like the only way to fix
1550 // the problem is to add `T: 'r`, which isn't true. So, if there are no
1551 // inference variables, we use a verify constraint instead of adding
1552 // edges, which winds up enforcing the same condition.
9e0c209e 1553 let needs_infer = projection_ty.trait_ref.needs_infer();
a7813a04
XL
1554 if env_bounds.is_empty() && needs_infer {
1555 debug!("projection_must_outlive: no declared bounds");
e9174d1e 1556
9e0c209e 1557 for component_ty in projection_ty.trait_ref.substs.types() {
a7813a04
XL
1558 self.type_must_outlive(origin.clone(), component_ty, region);
1559 }
1560
9e0c209e 1561 for r in projection_ty.trait_ref.substs.regions() {
a7813a04
XL
1562 self.sub_regions(origin.clone(), region, r);
1563 }
e9174d1e 1564
e9174d1e 1565 return;
85aaf69f 1566 }
1a4d82fc 1567
a7813a04
XL
1568 // If we find that there is a unique declared bound `'b`, and this bound
1569 // appears in the trait reference, then the best action is to require that `'b:'r`,
1570 // so do that. This is best no matter what rule we use:
1571 //
1572 // - OutlivesProjectionEnv or OutlivesProjectionTraitDef: these would translate to
1573 // the requirement that `'b:'r`
1574 // - OutlivesProjectionComponent: this would require `'b:'r` in addition to
1575 // other conditions
1576 if !env_bounds.is_empty() && env_bounds[1..].iter().all(|b| *b == env_bounds[0]) {
1577 let unique_bound = env_bounds[0];
1578 debug!("projection_must_outlive: unique declared bound = {:?}", unique_bound);
9e0c209e 1579 if projection_ty.trait_ref.substs.regions().any(|r| env_bounds.contains(&r)) {
a7813a04
XL
1580 debug!("projection_must_outlive: unique declared bound appears in trait ref");
1581 self.sub_regions(origin.clone(), region, unique_bound);
1582 return;
1583 }
e9174d1e 1584 }
a7813a04
XL
1585
1586 // Fallback to verifying after the fact that there exists a
1587 // declared bound, or that all the components appearing in the
1588 // projection outlive; in some cases, this may add insufficient
1589 // edges into the inference graph, leading to inference failures
1590 // even though a satisfactory solution exists.
1591 let verify_bound = self.projection_bound(origin.span(), env_bounds, projection_ty);
1592 let generic = GenericKind::Projection(projection_ty);
1593 self.verify_generic_bound(origin, generic.clone(), region, verify_bound);
1594 }
1595
9e0c209e 1596 fn type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
a7813a04
XL
1597 match ty.sty {
1598 ty::TyParam(p) => {
1599 self.param_bound(p)
1600 }
1601 ty::TyProjection(data) => {
1602 let declared_bounds = self.projection_declared_bounds(span, data);
1603 self.projection_bound(span, declared_bounds, data)
1604 }
1605 _ => {
1606 self.recursive_type_bound(span, ty)
1607 }
e9174d1e
SL
1608 }
1609 }
e9174d1e 1610
9e0c209e 1611 fn param_bound(&self, param_ty: ty::ParamTy) -> VerifyBound<'tcx> {
a7813a04 1612 let param_env = &self.parameter_environment;
e9174d1e 1613
a7813a04
XL
1614 debug!("param_bound(param_ty={:?})",
1615 param_ty);
e9174d1e 1616
a7813a04 1617 let mut param_bounds = self.declared_generic_bounds_from_env(GenericKind::Param(param_ty));
e9174d1e 1618
a7813a04
XL
1619 // Add in the default bound of fn body that applies to all in
1620 // scope type parameters:
1621 param_bounds.push(param_env.implicit_region_bound);
1a4d82fc 1622
a7813a04
XL
1623 VerifyBound::AnyRegion(param_bounds)
1624 }
e9174d1e 1625
a7813a04
XL
1626 fn projection_declared_bounds(&self,
1627 span: Span,
1628 projection_ty: ty::ProjectionTy<'tcx>)
9e0c209e 1629 -> Vec<&'tcx ty::Region>
a7813a04
XL
1630 {
1631 // First assemble bounds from where clauses and traits.
e9174d1e 1632
a7813a04
XL
1633 let mut declared_bounds =
1634 self.declared_generic_bounds_from_env(GenericKind::Projection(projection_ty));
e9174d1e 1635
a7813a04
XL
1636 declared_bounds.extend_from_slice(
1637 &self.declared_projection_bounds_from_trait(span, projection_ty));
e9174d1e 1638
a7813a04
XL
1639 declared_bounds
1640 }
e9174d1e 1641
a7813a04
XL
1642 fn projection_bound(&self,
1643 span: Span,
9e0c209e 1644 declared_bounds: Vec<&'tcx ty::Region>,
a7813a04 1645 projection_ty: ty::ProjectionTy<'tcx>)
9e0c209e 1646 -> VerifyBound<'tcx> {
a7813a04
XL
1647 debug!("projection_bound(declared_bounds={:?}, projection_ty={:?})",
1648 declared_bounds, projection_ty);
e9174d1e 1649
a7813a04 1650 // see the extensive comment in projection_must_outlive
e9174d1e 1651
a7813a04
XL
1652 let ty = self.tcx.mk_projection(projection_ty.trait_ref, projection_ty.item_name);
1653 let recursive_bound = self.recursive_type_bound(span, ty);
e9174d1e 1654
a7813a04
XL
1655 VerifyBound::AnyRegion(declared_bounds).or(recursive_bound)
1656 }
e9174d1e 1657
9e0c209e 1658 fn recursive_type_bound(&self, span: Span, ty: Ty<'tcx>) -> VerifyBound<'tcx> {
a7813a04 1659 let mut bounds = vec![];
e9174d1e 1660
a7813a04
XL
1661 for subty in ty.walk_shallow() {
1662 bounds.push(self.type_bound(span, subty));
1663 }
e9174d1e 1664
a7813a04
XL
1665 let mut regions = ty.regions();
1666 regions.retain(|r| !r.is_bound()); // ignore late-bound regions
1667 bounds.push(VerifyBound::AllRegions(regions));
e9174d1e 1668
a7813a04
XL
1669 // remove bounds that must hold, since they are not interesting
1670 bounds.retain(|b| !b.must_hold());
e9174d1e 1671
a7813a04
XL
1672 if bounds.len() == 1 {
1673 bounds.pop().unwrap()
1674 } else {
1675 VerifyBound::AllBounds(bounds)
1676 }
e9174d1e 1677 }
e9174d1e 1678
a7813a04 1679 fn declared_generic_bounds_from_env(&self, generic: GenericKind<'tcx>)
9e0c209e 1680 -> Vec<&'tcx ty::Region>
a7813a04
XL
1681 {
1682 let param_env = &self.parameter_environment;
1683
1684 // To start, collect bounds from user:
1685 let mut param_bounds = self.tcx.required_region_bounds(generic.to_ty(self.tcx),
1686 param_env.caller_bounds.clone());
1687
1688 // Next, collect regions we scraped from the well-formedness
1689 // constraints in the fn signature. To do that, we walk the list
1690 // of known relations from the fn ctxt.
1691 //
1692 // This is crucial because otherwise code like this fails:
1693 //
1694 // fn foo<'a, A>(x: &'a A) { x.bar() }
1695 //
1696 // The problem is that the type of `x` is `&'a A`. To be
1697 // well-formed, then, A must be lower-generic by `'a`, but we
1698 // don't know that this holds from first principles.
1699 for &(r, p) in &self.region_bound_pairs {
1700 debug!("generic={:?} p={:?}",
1701 generic,
1702 p);
1703 if generic == p {
1704 param_bounds.push(r);
1705 }
1a4d82fc 1706 }
1a4d82fc 1707
a7813a04
XL
1708 param_bounds
1709 }
85aaf69f 1710
a7813a04
XL
1711 fn declared_projection_bounds_from_trait(&self,
1712 span: Span,
1713 projection_ty: ty::ProjectionTy<'tcx>)
9e0c209e 1714 -> Vec<&'tcx ty::Region>
a7813a04
XL
1715 {
1716 debug!("projection_bounds(projection_ty={:?})",
1717 projection_ty);
85aaf69f 1718
a7813a04
XL
1719 let ty = self.tcx.mk_projection(projection_ty.trait_ref.clone(),
1720 projection_ty.item_name);
85aaf69f 1721
a7813a04
XL
1722 // Say we have a projection `<T as SomeTrait<'a>>::SomeType`. We are interested
1723 // in looking for a trait definition like:
1724 //
1725 // ```
1726 // trait SomeTrait<'a> {
1727 // type SomeType : 'a;
1728 // }
1729 // ```
1730 //
1731 // we can thus deduce that `<T as SomeTrait<'a>>::SomeType : 'a`.
1732 let trait_predicates = self.tcx.lookup_predicates(projection_ty.trait_ref.def_id);
9e0c209e 1733 assert_eq!(trait_predicates.parent, None);
a7813a04
XL
1734 let predicates = trait_predicates.predicates.as_slice().to_vec();
1735 traits::elaborate_predicates(self.tcx, predicates)
1736 .filter_map(|predicate| {
1737 // we're only interesting in `T : 'a` style predicates:
1738 let outlives = match predicate {
1739 ty::Predicate::TypeOutlives(data) => data,
1740 _ => { return None; }
1741 };
85aaf69f 1742
a7813a04
XL
1743 debug!("projection_bounds: outlives={:?} (1)",
1744 outlives);
85aaf69f 1745
a7813a04
XL
1746 // apply the substitutions (and normalize any projected types)
1747 let outlives = self.instantiate_type_scheme(span,
1748 projection_ty.trait_ref.substs,
1749 &outlives);
85aaf69f 1750
a7813a04 1751 debug!("projection_bounds: outlives={:?} (2)",
62682a34 1752 outlives);
85aaf69f 1753
a7813a04
XL
1754 let region_result = self.commit_if_ok(|_| {
1755 let (outlives, _) =
1756 self.replace_late_bound_regions_with_fresh_var(
1757 span,
1758 infer::AssocTypeProjection(projection_ty.item_name),
1759 &outlives);
1760
1761 debug!("projection_bounds: outlives={:?} (3)",
1762 outlives);
1763
1764 // check whether this predicate applies to our current projection
1765 match self.eq_types(false, TypeOrigin::Misc(span), ty, outlives.0) {
1766 Ok(InferOk { obligations, .. }) => {
1767 // FIXME(#32730) propagate obligations
1768 assert!(obligations.is_empty());
1769 Ok(outlives.1)
1770 }
1771 Err(_) => { Err(()) }
54a0048b 1772 }
a7813a04 1773 });
85aaf69f 1774
a7813a04
XL
1775 debug!("projection_bounds: region_result={:?}",
1776 region_result);
85aaf69f 1777
a7813a04
XL
1778 region_result.ok()
1779 })
1780 .collect()
1781 }
85aaf69f 1782}