]> git.proxmox.com Git - rustc.git/blame - src/librustc/middle/infer/error_reporting.rs
Imported Upstream version 1.8.0+dfsg1
[rustc.git] / src / librustc / middle / infer / error_reporting.rs
CommitLineData
1a4d82fc
JJ
1// Copyright 2012-2013 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//! Error Reporting Code for the inference engine
12//!
13//! Because of the way inference, and in particular region inference,
14//! works, it often happens that errors are not detected until far after
15//! the relevant line of code has been type-checked. Therefore, there is
16//! an elaborate system to track why a particular constraint in the
17//! inference graph arose so that we can explain to the user what gave
18//! rise to a particular error.
19//!
20//! The basis of the system are the "origin" types. An "origin" is the
21//! reason that a constraint or inference variable arose. There are
22//! different "origin" enums for different kinds of constraints/variables
23//! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
24//! a span, but also more information so that we can generate a meaningful
25//! error message.
26//!
27//! Having a catalogue of all the different reasons an error can arise is
28//! also useful for other reasons, like cross-referencing FAQs etc, though
29//! we are not really taking advantage of this yet.
30//!
31//! # Region Inference
32//!
33//! Region inference is particularly tricky because it always succeeds "in
34//! the moment" and simply registers a constraint. Then, at the end, we
35//! can compute the full graph and report errors, so we need to be able to
36//! store and later report what gave rise to the conflicting constraints.
37//!
38//! # Subtype Trace
39//!
40//! Determining whether `T1 <: T2` often involves a number of subtypes and
41//! subconstraints along the way. A "TypeTrace" is an extended version
42//! of an origin that traces the types and other values that were being
43//! compared. It is not necessarily comprehensive (in fact, at the time of
44//! this writing it only tracks the root values being compared) but I'd
45//! like to extend it to include significant "waypoints". For example, if
46//! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
47//! <: T4` fails, I'd like the trace to include enough information to say
48//! "in the 2nd element of the tuple". Similarly, failures when comparing
49//! arguments or return types in fn types should be able to cite the
50//! specific position, etc.
51//!
52//! # Reality vs plan
53//!
54//! Of course, there is still a LOT of code in typeck that has yet to be
55//! ported to this system, and which relies on string concatenation at the
56//! time of error detection.
57
58use self::FreshOrKept::*;
59
60use super::InferCtxt;
61use super::TypeTrace;
62use super::SubregionOrigin;
63use super::RegionVariableOrigin;
64use super::ValuePairs;
65use super::region_inference::RegionResolutionError;
66use super::region_inference::ConcreteFailure;
67use super::region_inference::SubSupConflict;
1a4d82fc
JJ
68use super::region_inference::GenericBoundFailure;
69use super::region_inference::GenericKind;
70use super::region_inference::ProcessedErrors;
71use super::region_inference::SameRegions;
72
73use std::collections::HashSet;
e9174d1e
SL
74
75use front::map as ast_map;
76use rustc_front::hir;
77use rustc_front::print::pprust;
78
92a42be0 79use middle::cstore::CrateStore;
7453a54e 80use middle::def::Def;
e9174d1e 81use middle::def_id::DefId;
92a42be0 82use middle::infer::{self, TypeOrigin};
62682a34 83use middle::region;
1a4d82fc 84use middle::subst;
9cc50fc6 85use middle::ty::{self, Ty, TypeFoldable};
1a4d82fc 86use middle::ty::{Region, ReFree};
e9174d1e 87use middle::ty::error::TypeError;
62682a34 88
1a4d82fc
JJ
89use std::cell::{Cell, RefCell};
90use std::char::from_u32;
62682a34 91use std::fmt;
1a4d82fc 92use syntax::ast;
9cc50fc6 93use syntax::errors::DiagnosticBuilder;
e9174d1e 94use syntax::codemap::{self, Pos, Span};
1a4d82fc 95use syntax::parse::token;
1a4d82fc 96use syntax::ptr::P;
1a4d82fc 97
c1a9b12d
SL
98impl<'tcx> ty::ctxt<'tcx> {
99 pub fn note_and_explain_region(&self,
9cc50fc6 100 err: &mut DiagnosticBuilder,
c1a9b12d
SL
101 prefix: &str,
102 region: ty::Region,
103 suffix: &str) {
e9174d1e 104 fn item_scope_tag(item: &hir::Item) -> &'static str {
c1a9b12d 105 match item.node {
e9174d1e
SL
106 hir::ItemImpl(..) => "impl",
107 hir::ItemStruct(..) => "struct",
108 hir::ItemEnum(..) => "enum",
109 hir::ItemTrait(..) => "trait",
110 hir::ItemFn(..) => "function body",
c1a9b12d
SL
111 _ => "item"
112 }
62682a34 113 }
62682a34 114
c1a9b12d
SL
115 fn explain_span(tcx: &ty::ctxt, heading: &str, span: Span)
116 -> (String, Option<Span>) {
117 let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
118 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
119 Some(span))
62682a34
SL
120 }
121
c1a9b12d
SL
122 let (description, span) = match region {
123 ty::ReScope(scope) => {
124 let new_string;
125 let unknown_scope = || {
126 format!("{}unknown scope: {:?}{}. Please report a bug.",
127 prefix, scope, suffix)
128 };
e9174d1e 129 let span = match scope.span(&self.region_maps, &self.map) {
c1a9b12d 130 Some(s) => s,
9cc50fc6
SL
131 None => {
132 err.note(&unknown_scope());
133 return;
134 }
c1a9b12d 135 };
e9174d1e 136 let tag = match self.map.find(scope.node_id(&self.region_maps)) {
c1a9b12d
SL
137 Some(ast_map::NodeBlock(_)) => "block",
138 Some(ast_map::NodeExpr(expr)) => match expr.node {
e9174d1e
SL
139 hir::ExprCall(..) => "call",
140 hir::ExprMethodCall(..) => "method call",
141 hir::ExprMatch(_, _, hir::MatchSource::IfLetDesugar { .. }) => "if let",
142 hir::ExprMatch(_, _, hir::MatchSource::WhileLetDesugar) => "while let",
143 hir::ExprMatch(_, _, hir::MatchSource::ForLoopDesugar) => "for",
144 hir::ExprMatch(..) => "match",
c1a9b12d
SL
145 _ => "expression",
146 },
147 Some(ast_map::NodeStmt(_)) => "statement",
7453a54e 148 Some(ast_map::NodeItem(it)) => item_scope_tag(&it),
c1a9b12d 149 Some(_) | None => {
9cc50fc6
SL
150 err.span_note(span, &unknown_scope());
151 return;
c1a9b12d
SL
152 }
153 };
e9174d1e
SL
154 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
155 region::CodeExtentData::Misc(_) => tag,
9cc50fc6
SL
156 region::CodeExtentData::CallSiteScope { .. } => {
157 "scope of call-site for function"
158 }
e9174d1e 159 region::CodeExtentData::ParameterScope { .. } => {
c1a9b12d
SL
160 "scope of parameters for function"
161 }
e9174d1e 162 region::CodeExtentData::DestructionScope(_) => {
c1a9b12d
SL
163 new_string = format!("destruction scope surrounding {}", tag);
164 &new_string[..]
165 }
e9174d1e 166 region::CodeExtentData::Remainder(r) => {
c1a9b12d
SL
167 new_string = format!("block suffix following statement {}",
168 r.first_statement_index);
169 &new_string[..]
170 }
171 };
172 explain_span(self, scope_decorated_tag, span)
173 }
62682a34 174
c1a9b12d
SL
175 ty::ReFree(ref fr) => {
176 let prefix = match fr.bound_region {
177 ty::BrAnon(idx) => {
178 format!("the anonymous lifetime #{} defined on", idx + 1)
179 }
180 ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
181 _ => {
182 format!("the lifetime {} as defined on",
183 fr.bound_region)
184 }
185 };
186
e9174d1e 187 match self.map.find(fr.scope.node_id(&self.region_maps)) {
c1a9b12d
SL
188 Some(ast_map::NodeBlock(ref blk)) => {
189 let (msg, opt_span) = explain_span(self, "block", blk.span);
190 (format!("{} {}", prefix, msg), opt_span)
191 }
192 Some(ast_map::NodeItem(it)) => {
7453a54e 193 let tag = item_scope_tag(&it);
c1a9b12d
SL
194 let (msg, opt_span) = explain_span(self, tag, it.span);
195 (format!("{} {}", prefix, msg), opt_span)
196 }
197 Some(_) | None => {
e9174d1e
SL
198 // this really should not happen, but it does:
199 // FIXME(#27942)
c1a9b12d
SL
200 (format!("{} unknown free region bounded by scope {:?}",
201 prefix, fr.scope), None)
202 }
62682a34
SL
203 }
204 }
62682a34 205
c1a9b12d 206 ty::ReStatic => ("the static lifetime".to_owned(), None),
62682a34 207
c1a9b12d 208 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
62682a34 209
c1a9b12d 210 ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
62682a34 211
e9174d1e
SL
212 // FIXME(#13998) ReSkolemized should probably print like
213 // ReFree rather than dumping Debug output on the user.
214 //
215 // We shouldn't really be having unification failures with ReVar
216 // and ReLateBound though.
217 ty::ReSkolemized(..) | ty::ReVar(_) | ty::ReLateBound(..) => {
c1a9b12d
SL
218 (format!("lifetime {:?}", region), None)
219 }
220 };
221 let message = format!("{}{}{}", prefix, description, suffix);
222 if let Some(span) = span {
9cc50fc6 223 err.span_note(span, &message);
c1a9b12d 224 } else {
9cc50fc6 225 err.note(&message);
62682a34 226 }
62682a34
SL
227 }
228}
1a4d82fc
JJ
229
230pub trait ErrorReporting<'tcx> {
231 fn report_region_errors(&self,
232 errors: &Vec<RegionResolutionError<'tcx>>);
233
234 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
235 -> Vec<RegionResolutionError<'tcx>>;
236
9cc50fc6
SL
237 fn report_type_error(&self,
238 trace: TypeTrace<'tcx>,
239 terr: &TypeError<'tcx>)
240 -> DiagnosticBuilder<'tcx>;
e9174d1e 241
9cc50fc6
SL
242 fn check_and_note_conflicting_crates(&self,
243 err: &mut DiagnosticBuilder,
244 terr: &TypeError<'tcx>,
245 sp: Span);
1a4d82fc
JJ
246
247 fn report_and_explain_type_error(&self,
248 trace: TypeTrace<'tcx>,
e9174d1e 249 terr: &TypeError<'tcx>);
1a4d82fc
JJ
250
251 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String>;
252
9cc50fc6 253 fn expected_found_str<T: fmt::Display + Resolvable<'tcx> + TypeFoldable<'tcx>>(
1a4d82fc 254 &self,
e9174d1e 255 exp_found: &ty::error::ExpectedFound<T>)
1a4d82fc
JJ
256 -> Option<String>;
257
258 fn report_concrete_failure(&self,
259 origin: SubregionOrigin<'tcx>,
260 sub: Region,
261 sup: Region);
262
263 fn report_generic_bound_failure(&self,
264 origin: SubregionOrigin<'tcx>,
265 kind: GenericKind<'tcx>,
e9174d1e 266 sub: Region);
1a4d82fc
JJ
267
268 fn report_sub_sup_conflict(&self,
269 var_origin: RegionVariableOrigin,
270 sub_origin: SubregionOrigin<'tcx>,
271 sub_region: Region,
272 sup_origin: SubregionOrigin<'tcx>,
273 sup_region: Region);
274
1a4d82fc
JJ
275 fn report_processed_errors(&self,
276 var_origin: &[RegionVariableOrigin],
e9174d1e 277 trace_origin: &[(TypeTrace<'tcx>, TypeError<'tcx>)],
1a4d82fc
JJ
278 same_regions: &[SameRegions]);
279
9cc50fc6 280 fn give_suggestion(&self, err: &mut DiagnosticBuilder, same_regions: &[SameRegions]);
1a4d82fc
JJ
281}
282
283trait ErrorReportingHelpers<'tcx> {
284 fn report_inference_failure(&self,
9cc50fc6
SL
285 var_origin: RegionVariableOrigin)
286 -> DiagnosticBuilder<'tcx>;
1a4d82fc
JJ
287
288 fn note_region_origin(&self,
9cc50fc6 289 err: &mut DiagnosticBuilder,
1a4d82fc
JJ
290 origin: &SubregionOrigin<'tcx>);
291
292 fn give_expl_lifetime_param(&self,
9cc50fc6 293 err: &mut DiagnosticBuilder,
e9174d1e
SL
294 decl: &hir::FnDecl,
295 unsafety: hir::Unsafety,
296 constness: hir::Constness,
b039eaaf 297 name: ast::Name,
e9174d1e
SL
298 opt_explicit_self: Option<&hir::ExplicitSelf_>,
299 generics: &hir::Generics,
62682a34 300 span: Span);
1a4d82fc
JJ
301}
302
303impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> {
304 fn report_region_errors(&self,
305 errors: &Vec<RegionResolutionError<'tcx>>) {
306 let p_errors = self.process_errors(errors);
307 let errors = if p_errors.is_empty() { errors } else { &p_errors };
85aaf69f 308 for error in errors {
1a4d82fc
JJ
309 match error.clone() {
310 ConcreteFailure(origin, sub, sup) => {
311 self.report_concrete_failure(origin, sub, sup);
312 }
313
e9174d1e
SL
314 GenericBoundFailure(kind, param_ty, sub) => {
315 self.report_generic_bound_failure(kind, param_ty, sub);
1a4d82fc
JJ
316 }
317
318 SubSupConflict(var_origin,
319 sub_origin, sub_r,
320 sup_origin, sup_r) => {
321 self.report_sub_sup_conflict(var_origin,
322 sub_origin, sub_r,
323 sup_origin, sup_r);
324 }
325
1a4d82fc
JJ
326 ProcessedErrors(ref var_origins,
327 ref trace_origins,
328 ref same_regions) => {
329 if !same_regions.is_empty() {
85aaf69f
SL
330 self.report_processed_errors(&var_origins[..],
331 &trace_origins[..],
332 &same_regions[..]);
1a4d82fc
JJ
333 }
334 }
335 }
336 }
337 }
338
339 // This method goes through all the errors and try to group certain types
340 // of error together, for the purpose of suggesting explicit lifetime
341 // parameters to the user. This is done so that we can have a more
342 // complete view of what lifetimes should be the same.
343 // If the return value is an empty vector, it means that processing
344 // failed (so the return value of this method should not be used)
345 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
346 -> Vec<RegionResolutionError<'tcx>> {
347 debug!("process_errors()");
348 let mut var_origins = Vec::new();
349 let mut trace_origins = Vec::new();
350 let mut same_regions = Vec::new();
351 let mut processed_errors = Vec::new();
85aaf69f 352 for error in errors {
1a4d82fc
JJ
353 match error.clone() {
354 ConcreteFailure(origin, sub, sup) => {
355 debug!("processing ConcreteFailure");
356 let trace = match origin {
357 infer::Subtype(trace) => Some(trace),
358 _ => None,
359 };
360 match free_regions_from_same_fn(self.tcx, sub, sup) {
361 Some(ref same_frs) if trace.is_some() => {
362 let trace = trace.unwrap();
c1a9b12d
SL
363 let terr = TypeError::RegionsDoesNotOutlive(sup,
364 sub);
1a4d82fc
JJ
365 trace_origins.push((trace, terr));
366 append_to_same_regions(&mut same_regions, same_frs);
367 }
368 _ => processed_errors.push((*error).clone()),
369 }
370 }
371 SubSupConflict(var_origin, _, sub_r, _, sup_r) => {
85aaf69f 372 debug!("processing SubSupConflict sub: {:?} sup: {:?}", sub_r, sup_r);
1a4d82fc
JJ
373 match free_regions_from_same_fn(self.tcx, sub_r, sup_r) {
374 Some(ref same_frs) => {
375 var_origins.push(var_origin);
376 append_to_same_regions(&mut same_regions, same_frs);
377 }
378 None => processed_errors.push((*error).clone()),
379 }
380 }
1a4d82fc
JJ
381 _ => () // This shouldn't happen
382 }
383 }
384 if !same_regions.is_empty() {
385 let common_scope_id = same_regions[0].scope_id;
85aaf69f 386 for sr in &same_regions {
1a4d82fc
JJ
387 // Since ProcessedErrors is used to reconstruct the function
388 // declaration, we want to make sure that they are, in fact,
389 // from the same scope
390 if sr.scope_id != common_scope_id {
391 debug!("returning empty result from process_errors because
392 {} != {}", sr.scope_id, common_scope_id);
393 return vec!();
394 }
395 }
396 let pe = ProcessedErrors(var_origins, trace_origins, same_regions);
397 debug!("errors processed: {:?}", pe);
398 processed_errors.push(pe);
399 }
400 return processed_errors;
401
402
403 struct FreeRegionsFromSameFn {
404 sub_fr: ty::FreeRegion,
405 sup_fr: ty::FreeRegion,
406 scope_id: ast::NodeId
407 }
408
409 impl FreeRegionsFromSameFn {
410 fn new(sub_fr: ty::FreeRegion,
411 sup_fr: ty::FreeRegion,
412 scope_id: ast::NodeId)
413 -> FreeRegionsFromSameFn {
414 FreeRegionsFromSameFn {
415 sub_fr: sub_fr,
416 sup_fr: sup_fr,
417 scope_id: scope_id
418 }
419 }
420 }
421
422 fn free_regions_from_same_fn(tcx: &ty::ctxt,
423 sub: Region,
424 sup: Region)
425 -> Option<FreeRegionsFromSameFn> {
426 debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
427 let (scope_id, fr1, fr2) = match (sub, sup) {
428 (ReFree(fr1), ReFree(fr2)) => {
429 if fr1.scope != fr2.scope {
430 return None
431 }
432 assert!(fr1.scope == fr2.scope);
e9174d1e 433 (fr1.scope.node_id(&tcx.region_maps), fr1, fr2)
1a4d82fc
JJ
434 },
435 _ => return None
436 };
437 let parent = tcx.map.get_parent(scope_id);
438 let parent_node = tcx.map.find(parent);
439 match parent_node {
440 Some(node) => match node {
441 ast_map::NodeItem(item) => match item.node {
e9174d1e 442 hir::ItemFn(..) => {
1a4d82fc
JJ
443 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
444 },
445 _ => None
446 },
447 ast_map::NodeImplItem(..) |
448 ast_map::NodeTraitItem(..) => {
449 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
450 },
451 _ => None
452 },
453 None => {
454 debug!("no parent node of scope_id {}", scope_id);
455 None
456 }
457 }
458 }
459
460 fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
461 same_frs: &FreeRegionsFromSameFn) {
462 let scope_id = same_frs.scope_id;
463 let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
85aaf69f 464 for sr in &mut *same_regions {
1a4d82fc
JJ
465 if sr.contains(&sup_fr.bound_region)
466 && scope_id == sr.scope_id {
467 sr.push(sub_fr.bound_region);
468 return
469 }
470 }
471 same_regions.push(SameRegions {
472 scope_id: scope_id,
473 regions: vec!(sub_fr.bound_region, sup_fr.bound_region)
474 })
475 }
476 }
477
9cc50fc6
SL
478 fn report_type_error(&self,
479 trace: TypeTrace<'tcx>,
480 terr: &TypeError<'tcx>)
481 -> DiagnosticBuilder<'tcx> {
1a4d82fc
JJ
482 let expected_found_str = match self.values_str(&trace.values) {
483 Some(v) => v,
484 None => {
9cc50fc6 485 return self.tcx.sess.diagnostic().struct_dummy(); /* derived error */
1a4d82fc
JJ
486 }
487 };
488
9cc50fc6
SL
489 let is_simple_error = if let &TypeError::Sorts(ref values) = terr {
490 values.expected.is_primitive() && values.found.is_primitive()
491 } else {
492 false
493 };
494
495 let expected_found_str = if is_simple_error {
496 expected_found_str
497 } else {
498 format!("{} ({})", expected_found_str, terr)
499 };
500
501 let mut err = struct_span_err!(self.tcx.sess,
502 trace.origin.span(),
503 E0308,
504 "{}: {}",
505 trace.origin,
506 expected_found_str);
1a4d82fc 507
9cc50fc6 508 self.check_and_note_conflicting_crates(&mut err, terr, trace.origin.span());
e9174d1e 509
1a4d82fc 510 match trace.origin {
92a42be0 511 TypeOrigin::MatchExpressionArm(_, arm_span, source) => match source {
9cc50fc6
SL
512 hir::MatchSource::IfLetDesugar{..} => {
513 err.span_note(arm_span, "`if let` arm with an incompatible type");
514 }
515 _ => {
516 err.span_note(arm_span, "match arm with an incompatible type");
517 }
92a42be0 518 },
1a4d82fc
JJ
519 _ => ()
520 }
9cc50fc6 521 err
1a4d82fc
JJ
522 }
523
e9174d1e 524 /// Adds a note if the types come from similarly named crates
9cc50fc6
SL
525 fn check_and_note_conflicting_crates(&self,
526 err: &mut DiagnosticBuilder,
527 terr: &TypeError<'tcx>,
528 sp: Span) {
529 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
e9174d1e
SL
530 // Only external crates, if either is from a local
531 // module we could have false positives
532 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
533 let exp_path = self.tcx.with_path(did1,
534 |p| p.map(|x| x.to_string())
535 .collect::<Vec<_>>());
536 let found_path = self.tcx.with_path(did2,
537 |p| p.map(|x| x.to_string())
538 .collect::<Vec<_>>());
539 // We compare strings because PathMod and PathName can be different
540 // for imported and non-imported crates
541 if exp_path == found_path {
92a42be0 542 let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
9cc50fc6
SL
543 err.span_note(sp, &format!("Perhaps two different versions \
544 of crate `{}` are being used?",
545 crate_name));
e9174d1e
SL
546 }
547 }
548 };
549 match *terr {
550 TypeError::Sorts(ref exp_found) => {
551 // if they are both "path types", there's a chance of ambiguity
552 // due to different versions of the same crate
553 match (&exp_found.expected.sty, &exp_found.found.sty) {
554 (&ty::TyEnum(ref exp_adt, _), &ty::TyEnum(ref found_adt, _)) |
555 (&ty::TyStruct(ref exp_adt, _), &ty::TyStruct(ref found_adt, _)) |
556 (&ty::TyEnum(ref exp_adt, _), &ty::TyStruct(ref found_adt, _)) |
557 (&ty::TyStruct(ref exp_adt, _), &ty::TyEnum(ref found_adt, _)) => {
9cc50fc6 558 report_path_match(err, exp_adt.did, found_adt.did);
e9174d1e
SL
559 },
560 _ => ()
561 }
562 },
563 TypeError::Traits(ref exp_found) => {
9cc50fc6 564 report_path_match(err, exp_found.expected, exp_found.found);
e9174d1e
SL
565 },
566 _ => () // FIXME(#22750) handle traits and stuff
567 }
568 }
569
1a4d82fc
JJ
570 fn report_and_explain_type_error(&self,
571 trace: TypeTrace<'tcx>,
e9174d1e 572 terr: &TypeError<'tcx>) {
9346a6ac 573 let span = trace.origin.span();
9cc50fc6
SL
574 let mut err = self.report_type_error(trace, terr);
575 self.tcx.note_and_explain_type_err(&mut err, terr, span);
576 err.emit();
1a4d82fc
JJ
577 }
578
579 /// Returns a string of the form "expected `{}`, found `{}`", or None if this is a derived
580 /// error.
581 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String> {
582 match *values {
583 infer::Types(ref exp_found) => self.expected_found_str(exp_found),
584 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
585 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found)
586 }
587 }
588
9cc50fc6 589 fn expected_found_str<T: fmt::Display + Resolvable<'tcx> + TypeFoldable<'tcx>>(
1a4d82fc 590 &self,
e9174d1e 591 exp_found: &ty::error::ExpectedFound<T>)
1a4d82fc
JJ
592 -> Option<String>
593 {
594 let expected = exp_found.expected.resolve(self);
c1a9b12d 595 if expected.references_error() {
1a4d82fc
JJ
596 return None;
597 }
598
599 let found = exp_found.found.resolve(self);
c1a9b12d 600 if found.references_error() {
1a4d82fc
JJ
601 return None;
602 }
603
604 Some(format!("expected `{}`, found `{}`",
62682a34
SL
605 expected,
606 found))
1a4d82fc
JJ
607 }
608
609 fn report_generic_bound_failure(&self,
610 origin: SubregionOrigin<'tcx>,
611 bound_kind: GenericKind<'tcx>,
e9174d1e 612 sub: Region)
1a4d82fc
JJ
613 {
614 // FIXME: it would be better to report the first error message
615 // with the span of the parameter itself, rather than the span
616 // where the error was detected. But that span is not readily
617 // accessible.
618
619 let labeled_user_string = match bound_kind {
620 GenericKind::Param(ref p) =>
62682a34 621 format!("the parameter type `{}`", p),
1a4d82fc 622 GenericKind::Projection(ref p) =>
62682a34 623 format!("the associated type `{}`", p),
1a4d82fc
JJ
624 };
625
9cc50fc6 626 let mut err = match sub {
1a4d82fc
JJ
627 ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
628 // Does the required lifetime have a nice name we can print?
9cc50fc6
SL
629 let mut err = struct_span_err!(self.tcx.sess,
630 origin.span(),
631 E0309,
632 "{} may not live long enough",
633 labeled_user_string);
634 err.fileline_help(origin.span(),
635 &format!("consider adding an explicit lifetime bound `{}: {}`...",
636 bound_kind,
637 sub));
638 err
1a4d82fc
JJ
639 }
640
641 ty::ReStatic => {
642 // Does the required lifetime have a nice name we can print?
9cc50fc6
SL
643 let mut err = struct_span_err!(self.tcx.sess,
644 origin.span(),
645 E0310,
646 "{} may not live long enough",
647 labeled_user_string);
648 err.fileline_help(origin.span(),
649 &format!("consider adding an explicit lifetime \
650 bound `{}: 'static`...",
651 bound_kind));
652 err
1a4d82fc
JJ
653 }
654
655 _ => {
656 // If not, be less specific.
9cc50fc6
SL
657 let mut err = struct_span_err!(self.tcx.sess,
658 origin.span(),
659 E0311,
660 "{} may not live long enough",
661 labeled_user_string);
662 err.fileline_help(origin.span(),
663 &format!("consider adding an explicit lifetime bound for `{}`",
664 bound_kind));
c1a9b12d 665 self.tcx.note_and_explain_region(
9cc50fc6 666 &mut err,
c34b1796 667 &format!("{} must be valid for ", labeled_user_string),
1a4d82fc
JJ
668 sub,
669 "...");
9cc50fc6 670 err
1a4d82fc 671 }
9cc50fc6 672 };
e9174d1e 673
9cc50fc6
SL
674 self.note_region_origin(&mut err, &origin);
675 err.emit();
1a4d82fc
JJ
676 }
677
678 fn report_concrete_failure(&self,
679 origin: SubregionOrigin<'tcx>,
680 sub: Region,
681 sup: Region) {
682 match origin {
c1a9b12d
SL
683 infer::Subtype(trace) => {
684 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
1a4d82fc
JJ
685 self.report_and_explain_type_error(trace, &terr);
686 }
687 infer::Reborrow(span) => {
9cc50fc6 688 let mut err = struct_span_err!(self.tcx.sess, span, E0312,
1a4d82fc
JJ
689 "lifetime of reference outlines \
690 lifetime of borrowed content...");
9cc50fc6 691 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
692 "...the reference is valid for ",
693 sub,
694 "...");
9cc50fc6 695 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
696 "...but the borrowed content is only valid for ",
697 sup,
698 "");
9cc50fc6 699 err.emit();
1a4d82fc
JJ
700 }
701 infer::ReborrowUpvar(span, ref upvar_id) => {
9cc50fc6 702 let mut err = struct_span_err!(self.tcx.sess, span, E0313,
85aaf69f 703 "lifetime of borrowed pointer outlives \
1a4d82fc 704 lifetime of captured variable `{}`...",
c1a9b12d 705 self.tcx.local_var_name_str(upvar_id.var_id));
9cc50fc6 706 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
707 "...the borrowed pointer is valid for ",
708 sub,
709 "...");
9cc50fc6 710 self.tcx.note_and_explain_region(&mut err,
1a4d82fc 711 &format!("...but `{}` is only valid for ",
c1a9b12d 712 self.tcx.local_var_name_str(upvar_id.var_id)),
1a4d82fc
JJ
713 sup,
714 "");
9cc50fc6 715 err.emit();
1a4d82fc
JJ
716 }
717 infer::InfStackClosure(span) => {
9cc50fc6 718 let mut err = struct_span_err!(self.tcx.sess, span, E0314,
1a4d82fc 719 "closure outlives stack frame");
9cc50fc6 720 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
721 "...the closure must be valid for ",
722 sub,
723 "...");
9cc50fc6 724 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
725 "...but the closure's stack frame is only valid for ",
726 sup,
727 "");
9cc50fc6 728 err.emit();
1a4d82fc
JJ
729 }
730 infer::InvokeClosure(span) => {
9cc50fc6 731 let mut err = struct_span_err!(self.tcx.sess, span, E0315,
1a4d82fc 732 "cannot invoke closure outside of its lifetime");
9cc50fc6 733 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
734 "the closure is only valid for ",
735 sup,
736 "");
9cc50fc6 737 err.emit();
1a4d82fc
JJ
738 }
739 infer::DerefPointer(span) => {
9cc50fc6 740 let mut err = struct_span_err!(self.tcx.sess, span, E0473,
b039eaaf 741 "dereference of reference outside its lifetime");
9cc50fc6 742 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
743 "the reference is only valid for ",
744 sup,
745 "");
9cc50fc6 746 err.emit();
1a4d82fc
JJ
747 }
748 infer::FreeVariable(span, id) => {
9cc50fc6 749 let mut err = struct_span_err!(self.tcx.sess, span, E0474,
b039eaaf
SL
750 "captured variable `{}` does not outlive the enclosing closure",
751 self.tcx.local_var_name_str(id));
9cc50fc6 752 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
753 "captured variable is valid for ",
754 sup,
755 "");
9cc50fc6 756 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
757 "closure is valid for ",
758 sub,
759 "");
9cc50fc6 760 err.emit();
1a4d82fc
JJ
761 }
762 infer::IndexSlice(span) => {
9cc50fc6 763 let mut err = struct_span_err!(self.tcx.sess, span, E0475,
b039eaaf 764 "index of slice outside its lifetime");
9cc50fc6 765 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
766 "the slice is only valid for ",
767 sup,
768 "");
9cc50fc6 769 err.emit();
1a4d82fc
JJ
770 }
771 infer::RelateObjectBound(span) => {
9cc50fc6 772 let mut err = struct_span_err!(self.tcx.sess, span, E0476,
b039eaaf
SL
773 "lifetime of the source pointer does not outlive \
774 lifetime bound of the object type");
9cc50fc6 775 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
776 "object type is valid for ",
777 sub,
778 "");
9cc50fc6 779 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
780 "source pointer is only valid for ",
781 sup,
782 "");
9cc50fc6 783 err.emit();
1a4d82fc
JJ
784 }
785 infer::RelateParamBound(span, ty) => {
9cc50fc6 786 let mut err = struct_span_err!(self.tcx.sess, span, E0477,
b039eaaf
SL
787 "the type `{}` does not fulfill the required lifetime",
788 self.ty_to_string(ty));
9cc50fc6 789 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
790 "type must outlive ",
791 sub,
792 "");
9cc50fc6 793 err.emit();
1a4d82fc
JJ
794 }
795 infer::RelateRegionParamBound(span) => {
9cc50fc6 796 let mut err = struct_span_err!(self.tcx.sess, span, E0478,
b039eaaf 797 "lifetime bound not satisfied");
9cc50fc6 798 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
799 "lifetime parameter instantiated with ",
800 sup,
801 "");
9cc50fc6 802 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
803 "but lifetime parameter must outlive ",
804 sub,
805 "");
9cc50fc6 806 err.emit();
1a4d82fc
JJ
807 }
808 infer::RelateDefaultParamBound(span, ty) => {
9cc50fc6 809 let mut err = struct_span_err!(self.tcx.sess, span, E0479,
b039eaaf
SL
810 "the type `{}` (provided as the value of \
811 a type parameter) is not valid at this point",
812 self.ty_to_string(ty));
9cc50fc6 813 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
814 "type must outlive ",
815 sub,
816 "");
9cc50fc6 817 err.emit();
1a4d82fc
JJ
818 }
819 infer::CallRcvr(span) => {
9cc50fc6 820 let mut err = struct_span_err!(self.tcx.sess, span, E0480,
b039eaaf
SL
821 "lifetime of method receiver does not outlive \
822 the method call");
9cc50fc6 823 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
824 "the receiver is only valid for ",
825 sup,
826 "");
9cc50fc6 827 err.emit();
1a4d82fc
JJ
828 }
829 infer::CallArg(span) => {
9cc50fc6 830 let mut err = struct_span_err!(self.tcx.sess, span, E0481,
b039eaaf
SL
831 "lifetime of function argument does not outlive \
832 the function call");
9cc50fc6 833 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
834 "the function argument is only valid for ",
835 sup,
836 "");
9cc50fc6 837 err.emit();
1a4d82fc
JJ
838 }
839 infer::CallReturn(span) => {
9cc50fc6 840 let mut err = struct_span_err!(self.tcx.sess, span, E0482,
b039eaaf
SL
841 "lifetime of return value does not outlive \
842 the function call");
9cc50fc6 843 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
844 "the return value is only valid for ",
845 sup,
846 "");
9cc50fc6 847 err.emit();
1a4d82fc 848 }
85aaf69f 849 infer::Operand(span) => {
9cc50fc6 850 let mut err = struct_span_err!(self.tcx.sess, span, E0483,
b039eaaf
SL
851 "lifetime of operand does not outlive \
852 the operation");
9cc50fc6 853 self.tcx.note_and_explain_region(&mut err,
85aaf69f
SL
854 "the operand is only valid for ",
855 sup,
856 "");
9cc50fc6 857 err.emit();
85aaf69f 858 }
1a4d82fc 859 infer::AddrOf(span) => {
9cc50fc6 860 let mut err = struct_span_err!(self.tcx.sess, span, E0484,
b039eaaf 861 "reference is not valid at the time of borrow");
9cc50fc6 862 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
863 "the borrow is only valid for ",
864 sup,
865 "");
9cc50fc6 866 err.emit();
1a4d82fc
JJ
867 }
868 infer::AutoBorrow(span) => {
9cc50fc6 869 let mut err = struct_span_err!(self.tcx.sess, span, E0485,
b039eaaf
SL
870 "automatically reference is not valid \
871 at the time of borrow");
9cc50fc6 872 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
873 "the automatic borrow is only valid for ",
874 sup,
875 "");
9cc50fc6 876 err.emit();
1a4d82fc
JJ
877 }
878 infer::ExprTypeIsNotInScope(t, span) => {
9cc50fc6 879 let mut err = struct_span_err!(self.tcx.sess, span, E0486,
b039eaaf
SL
880 "type of expression contains references \
881 that are not valid during the expression: `{}`",
882 self.ty_to_string(t));
9cc50fc6 883 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
884 "type is only valid for ",
885 sup,
886 "");
9cc50fc6 887 err.emit();
1a4d82fc 888 }
85aaf69f 889 infer::SafeDestructor(span) => {
9cc50fc6 890 let mut err = struct_span_err!(self.tcx.sess, span, E0487,
b039eaaf
SL
891 "unsafe use of destructor: destructor might be called \
892 while references are dead");
85aaf69f 893 // FIXME (22171): terms "super/subregion" are suboptimal
9cc50fc6 894 self.tcx.note_and_explain_region(&mut err,
85aaf69f
SL
895 "superregion: ",
896 sup,
897 "");
9cc50fc6 898 self.tcx.note_and_explain_region(&mut err,
85aaf69f
SL
899 "subregion: ",
900 sub,
901 "");
9cc50fc6 902 err.emit();
85aaf69f 903 }
1a4d82fc 904 infer::BindingTypeIsNotValidAtDecl(span) => {
9cc50fc6 905 let mut err = struct_span_err!(self.tcx.sess, span, E0488,
b039eaaf 906 "lifetime of variable does not enclose its declaration");
9cc50fc6 907 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
908 "the variable is only valid for ",
909 sup,
910 "");
9cc50fc6 911 err.emit();
1a4d82fc 912 }
e9174d1e 913 infer::ParameterInScope(_, span) => {
9cc50fc6 914 let mut err = struct_span_err!(self.tcx.sess, span, E0489,
b039eaaf 915 "type/lifetime parameter not in scope here");
9cc50fc6 916 self.tcx.note_and_explain_region(&mut err,
e9174d1e
SL
917 "the parameter is only valid for ",
918 sub,
919 "");
9cc50fc6 920 err.emit();
e9174d1e
SL
921 }
922 infer::DataBorrowed(ty, span) => {
9cc50fc6 923 let mut err = struct_span_err!(self.tcx.sess, span, E0490,
b039eaaf
SL
924 "a value of type `{}` is borrowed for too long",
925 self.ty_to_string(ty));
9cc50fc6
SL
926 self.tcx.note_and_explain_region(&mut err, "the type is valid for ", sub, "");
927 self.tcx.note_and_explain_region(&mut err, "but the borrow lasts for ", sup, "");
928 err.emit();
e9174d1e 929 }
1a4d82fc 930 infer::ReferenceOutlivesReferent(ty, span) => {
9cc50fc6 931 let mut err = struct_span_err!(self.tcx.sess, span, E0491,
b039eaaf
SL
932 "in type `{}`, reference has a longer lifetime \
933 than the data it references",
934 self.ty_to_string(ty));
9cc50fc6 935 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
936 "the pointer is valid for ",
937 sub,
938 "");
9cc50fc6 939 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
940 "but the referenced data is only valid for ",
941 sup,
942 "");
9cc50fc6 943 err.emit();
1a4d82fc
JJ
944 }
945 }
946 }
947
948 fn report_sub_sup_conflict(&self,
949 var_origin: RegionVariableOrigin,
950 sub_origin: SubregionOrigin<'tcx>,
951 sub_region: Region,
952 sup_origin: SubregionOrigin<'tcx>,
953 sup_region: Region) {
9cc50fc6 954 let mut err = self.report_inference_failure(var_origin);
1a4d82fc 955
9cc50fc6 956 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
957 "first, the lifetime cannot outlive ",
958 sup_region,
959 "...");
960
9cc50fc6 961 self.note_region_origin(&mut err, &sup_origin);
1a4d82fc 962
9cc50fc6 963 self.tcx.note_and_explain_region(&mut err,
1a4d82fc
JJ
964 "but, the lifetime must be valid for ",
965 sub_region,
966 "...");
967
9cc50fc6
SL
968 self.note_region_origin(&mut err, &sub_origin);
969 err.emit();
1a4d82fc
JJ
970 }
971
1a4d82fc
JJ
972 fn report_processed_errors(&self,
973 var_origins: &[RegionVariableOrigin],
e9174d1e 974 trace_origins: &[(TypeTrace<'tcx>, TypeError<'tcx>)],
1a4d82fc 975 same_regions: &[SameRegions]) {
9cc50fc6
SL
976 for (i, vo) in var_origins.iter().enumerate() {
977 let mut err = self.report_inference_failure(vo.clone());
978 if i == var_origins.len() - 1 {
979 self.give_suggestion(&mut err, same_regions);
980 }
981 err.emit();
1a4d82fc 982 }
9cc50fc6 983
c1a9b12d
SL
984 for &(ref trace, ref terr) in trace_origins {
985 self.report_and_explain_type_error(trace.clone(), terr);
1a4d82fc
JJ
986 }
987 }
988
9cc50fc6 989 fn give_suggestion(&self, err: &mut DiagnosticBuilder, same_regions: &[SameRegions]) {
1a4d82fc
JJ
990 let scope_id = same_regions[0].scope_id;
991 let parent = self.tcx.map.get_parent(scope_id);
992 let parent_node = self.tcx.map.find(parent);
85aaf69f
SL
993 let taken = lifetimes_in_scope(self.tcx, scope_id);
994 let life_giver = LifeGiver::with_taken(&taken[..]);
1a4d82fc
JJ
995 let node_inner = match parent_node {
996 Some(ref node) => match *node {
997 ast_map::NodeItem(ref item) => {
998 match item.node {
e9174d1e 999 hir::ItemFn(ref fn_decl, unsafety, constness, _, ref gen, _) => {
62682a34 1000 Some((fn_decl, gen, unsafety, constness,
b039eaaf 1001 item.name, None, item.span))
1a4d82fc
JJ
1002 },
1003 _ => None
1004 }
1005 }
c34b1796
AL
1006 ast_map::NodeImplItem(item) => {
1007 match item.node {
92a42be0 1008 hir::ImplItemKind::Method(ref sig, _) => {
c34b1796
AL
1009 Some((&sig.decl,
1010 &sig.generics,
1011 sig.unsafety,
62682a34 1012 sig.constness,
b039eaaf 1013 item.name,
c34b1796
AL
1014 Some(&sig.explicit_self.node),
1015 item.span))
1a4d82fc 1016 }
d9579d0f 1017 _ => None,
1a4d82fc
JJ
1018 }
1019 },
c34b1796
AL
1020 ast_map::NodeTraitItem(item) => {
1021 match item.node {
e9174d1e 1022 hir::MethodTraitItem(ref sig, Some(_)) => {
c34b1796
AL
1023 Some((&sig.decl,
1024 &sig.generics,
1025 sig.unsafety,
62682a34 1026 sig.constness,
b039eaaf 1027 item.name,
c34b1796
AL
1028 Some(&sig.explicit_self.node),
1029 item.span))
1a4d82fc
JJ
1030 }
1031 _ => None
1032 }
1033 }
1034 _ => None
1035 },
1036 None => None
1037 };
b039eaaf 1038 let (fn_decl, generics, unsafety, constness, name, expl_self, span)
1a4d82fc 1039 = node_inner.expect("expect item fn");
1a4d82fc
JJ
1040 let rebuilder = Rebuilder::new(self.tcx, fn_decl, expl_self,
1041 generics, same_regions, &life_giver);
1042 let (fn_decl, expl_self, generics) = rebuilder.rebuild();
9cc50fc6 1043 self.give_expl_lifetime_param(err, &fn_decl, unsafety, constness, name,
1a4d82fc
JJ
1044 expl_self.as_ref(), &generics, span);
1045 }
1046}
1047
1048struct RebuildPathInfo<'a> {
e9174d1e 1049 path: &'a hir::Path,
1a4d82fc
JJ
1050 // indexes to insert lifetime on path.lifetimes
1051 indexes: Vec<u32>,
1052 // number of lifetimes we expect to see on the type referred by `path`
1053 // (e.g., expected=1 for struct Foo<'a>)
1054 expected: u32,
1055 anon_nums: &'a HashSet<u32>,
1056 region_names: &'a HashSet<ast::Name>
1057}
1058
1059struct Rebuilder<'a, 'tcx: 'a> {
1060 tcx: &'a ty::ctxt<'tcx>,
e9174d1e
SL
1061 fn_decl: &'a hir::FnDecl,
1062 expl_self_opt: Option<&'a hir::ExplicitSelf_>,
1063 generics: &'a hir::Generics,
1a4d82fc
JJ
1064 same_regions: &'a [SameRegions],
1065 life_giver: &'a LifeGiver,
1066 cur_anon: Cell<u32>,
1067 inserted_anons: RefCell<HashSet<u32>>,
1068}
1069
1070enum FreshOrKept {
1071 Fresh,
1072 Kept
1073}
1074
1075impl<'a, 'tcx> Rebuilder<'a, 'tcx> {
1076 fn new(tcx: &'a ty::ctxt<'tcx>,
e9174d1e
SL
1077 fn_decl: &'a hir::FnDecl,
1078 expl_self_opt: Option<&'a hir::ExplicitSelf_>,
1079 generics: &'a hir::Generics,
1a4d82fc
JJ
1080 same_regions: &'a [SameRegions],
1081 life_giver: &'a LifeGiver)
1082 -> Rebuilder<'a, 'tcx> {
1083 Rebuilder {
1084 tcx: tcx,
1085 fn_decl: fn_decl,
1086 expl_self_opt: expl_self_opt,
1087 generics: generics,
1088 same_regions: same_regions,
1089 life_giver: life_giver,
1090 cur_anon: Cell::new(0),
1091 inserted_anons: RefCell::new(HashSet::new()),
1092 }
1093 }
1094
1095 fn rebuild(&self)
e9174d1e 1096 -> (hir::FnDecl, Option<hir::ExplicitSelf_>, hir::Generics) {
85aaf69f 1097 let mut expl_self_opt = self.expl_self_opt.cloned();
1a4d82fc
JJ
1098 let mut inputs = self.fn_decl.inputs.clone();
1099 let mut output = self.fn_decl.output.clone();
1100 let mut ty_params = self.generics.ty_params.clone();
1101 let where_clause = self.generics.where_clause.clone();
1102 let mut kept_lifetimes = HashSet::new();
85aaf69f 1103 for sr in self.same_regions {
1a4d82fc
JJ
1104 self.cur_anon.set(0);
1105 self.offset_cur_anon();
1106 let (anon_nums, region_names) =
1107 self.extract_anon_nums_and_names(sr);
1108 let (lifetime, fresh_or_kept) = self.pick_lifetime(&region_names);
1109 match fresh_or_kept {
1110 Kept => { kept_lifetimes.insert(lifetime.name); }
1111 _ => ()
1112 }
1113 expl_self_opt = self.rebuild_expl_self(expl_self_opt, lifetime,
1114 &anon_nums, &region_names);
85aaf69f 1115 inputs = self.rebuild_args_ty(&inputs[..], lifetime,
1a4d82fc
JJ
1116 &anon_nums, &region_names);
1117 output = self.rebuild_output(&output, lifetime, &anon_nums, &region_names);
1118 ty_params = self.rebuild_ty_params(ty_params, lifetime,
1119 &region_names);
1120 }
1121 let fresh_lifetimes = self.life_giver.get_generated_lifetimes();
1122 let all_region_names = self.extract_all_region_names();
1123 let generics = self.rebuild_generics(self.generics,
1124 &fresh_lifetimes,
1125 &kept_lifetimes,
1126 &all_region_names,
1127 ty_params,
1128 where_clause);
e9174d1e 1129 let new_fn_decl = hir::FnDecl {
1a4d82fc
JJ
1130 inputs: inputs,
1131 output: output,
1132 variadic: self.fn_decl.variadic
1133 };
1134 (new_fn_decl, expl_self_opt, generics)
1135 }
1136
1137 fn pick_lifetime(&self,
1138 region_names: &HashSet<ast::Name>)
e9174d1e 1139 -> (hir::Lifetime, FreshOrKept) {
9346a6ac 1140 if !region_names.is_empty() {
1a4d82fc
JJ
1141 // It's not necessary to convert the set of region names to a
1142 // vector of string and then sort them. However, it makes the
1143 // choice of lifetime name deterministic and thus easier to test.
1144 let mut names = Vec::new();
85aaf69f 1145 for rn in region_names {
c1a9b12d 1146 let lt_name = rn.to_string();
1a4d82fc
JJ
1147 names.push(lt_name);
1148 }
1149 names.sort();
b039eaaf 1150 let name = token::intern(&names[0]);
1a4d82fc
JJ
1151 return (name_to_dummy_lifetime(name), Kept);
1152 }
1153 return (self.life_giver.give_lifetime(), Fresh);
1154 }
1155
1156 fn extract_anon_nums_and_names(&self, same_regions: &SameRegions)
1157 -> (HashSet<u32>, HashSet<ast::Name>) {
1158 let mut anon_nums = HashSet::new();
1159 let mut region_names = HashSet::new();
85aaf69f 1160 for br in &same_regions.regions {
1a4d82fc
JJ
1161 match *br {
1162 ty::BrAnon(i) => {
1163 anon_nums.insert(i);
1164 }
1165 ty::BrNamed(_, name) => {
1166 region_names.insert(name);
1167 }
1168 _ => ()
1169 }
1170 }
1171 (anon_nums, region_names)
1172 }
1173
1174 fn extract_all_region_names(&self) -> HashSet<ast::Name> {
1175 let mut all_region_names = HashSet::new();
85aaf69f
SL
1176 for sr in self.same_regions {
1177 for br in &sr.regions {
1a4d82fc
JJ
1178 match *br {
1179 ty::BrNamed(_, name) => {
1180 all_region_names.insert(name);
1181 }
1182 _ => ()
1183 }
1184 }
1185 }
1186 all_region_names
1187 }
1188
1189 fn inc_cur_anon(&self, n: u32) {
1190 let anon = self.cur_anon.get();
1191 self.cur_anon.set(anon+n);
1192 }
1193
1194 fn offset_cur_anon(&self) {
1195 let mut anon = self.cur_anon.get();
1196 while self.inserted_anons.borrow().contains(&anon) {
1197 anon += 1;
1198 }
1199 self.cur_anon.set(anon);
1200 }
1201
1202 fn inc_and_offset_cur_anon(&self, n: u32) {
1203 self.inc_cur_anon(n);
1204 self.offset_cur_anon();
1205 }
1206
1207 fn track_anon(&self, anon: u32) {
1208 self.inserted_anons.borrow_mut().insert(anon);
1209 }
1210
1211 fn rebuild_ty_params(&self,
9cc50fc6 1212 ty_params: hir::HirVec<hir::TyParam>,
e9174d1e 1213 lifetime: hir::Lifetime,
1a4d82fc 1214 region_names: &HashSet<ast::Name>)
9cc50fc6
SL
1215 -> hir::HirVec<hir::TyParam> {
1216 ty_params.iter().map(|ty_param| {
1a4d82fc
JJ
1217 let bounds = self.rebuild_ty_param_bounds(ty_param.bounds.clone(),
1218 lifetime,
1219 region_names);
e9174d1e 1220 hir::TyParam {
b039eaaf 1221 name: ty_param.name,
1a4d82fc
JJ
1222 id: ty_param.id,
1223 bounds: bounds,
1224 default: ty_param.default.clone(),
1225 span: ty_param.span,
1226 }
9cc50fc6 1227 }).collect()
1a4d82fc
JJ
1228 }
1229
1230 fn rebuild_ty_param_bounds(&self,
9cc50fc6 1231 ty_param_bounds: hir::TyParamBounds,
e9174d1e 1232 lifetime: hir::Lifetime,
1a4d82fc 1233 region_names: &HashSet<ast::Name>)
9cc50fc6
SL
1234 -> hir::TyParamBounds {
1235 ty_param_bounds.iter().map(|tpb| {
1a4d82fc 1236 match tpb {
e9174d1e 1237 &hir::RegionTyParamBound(lt) => {
1a4d82fc
JJ
1238 // FIXME -- it's unclear whether I'm supposed to
1239 // substitute lifetime here. I suspect we need to
1240 // be passing down a map.
e9174d1e 1241 hir::RegionTyParamBound(lt)
1a4d82fc 1242 }
e9174d1e 1243 &hir::TraitTyParamBound(ref poly_tr, modifier) => {
1a4d82fc
JJ
1244 let tr = &poly_tr.trait_ref;
1245 let last_seg = tr.path.segments.last().unwrap();
1246 let mut insert = Vec::new();
1247 let lifetimes = last_seg.parameters.lifetimes();
1248 for (i, lt) in lifetimes.iter().enumerate() {
1249 if region_names.contains(&lt.name) {
1250 insert.push(i as u32);
1251 }
1252 }
1253 let rebuild_info = RebuildPathInfo {
1254 path: &tr.path,
1255 indexes: insert,
1256 expected: lifetimes.len() as u32,
1257 anon_nums: &HashSet::new(),
1258 region_names: region_names
1259 };
1260 let new_path = self.rebuild_path(rebuild_info, lifetime);
e9174d1e 1261 hir::TraitTyParamBound(hir::PolyTraitRef {
1a4d82fc 1262 bound_lifetimes: poly_tr.bound_lifetimes.clone(),
e9174d1e 1263 trait_ref: hir::TraitRef {
1a4d82fc
JJ
1264 path: new_path,
1265 ref_id: tr.ref_id,
85aaf69f
SL
1266 },
1267 span: poly_tr.span,
1a4d82fc
JJ
1268 }, modifier)
1269 }
1270 }
9cc50fc6 1271 }).collect()
1a4d82fc
JJ
1272 }
1273
1274 fn rebuild_expl_self(&self,
e9174d1e
SL
1275 expl_self_opt: Option<hir::ExplicitSelf_>,
1276 lifetime: hir::Lifetime,
1a4d82fc
JJ
1277 anon_nums: &HashSet<u32>,
1278 region_names: &HashSet<ast::Name>)
e9174d1e 1279 -> Option<hir::ExplicitSelf_> {
1a4d82fc
JJ
1280 match expl_self_opt {
1281 Some(ref expl_self) => match *expl_self {
e9174d1e 1282 hir::SelfRegion(lt_opt, muta, id) => match lt_opt {
1a4d82fc 1283 Some(lt) => if region_names.contains(&lt.name) {
e9174d1e 1284 return Some(hir::SelfRegion(Some(lifetime), muta, id));
1a4d82fc
JJ
1285 },
1286 None => {
1287 let anon = self.cur_anon.get();
1288 self.inc_and_offset_cur_anon(1);
1289 if anon_nums.contains(&anon) {
1290 self.track_anon(anon);
e9174d1e 1291 return Some(hir::SelfRegion(Some(lifetime), muta, id));
1a4d82fc
JJ
1292 }
1293 }
1294 },
1295 _ => ()
1296 },
1297 None => ()
1298 }
1299 expl_self_opt
1300 }
1301
1302 fn rebuild_generics(&self,
e9174d1e
SL
1303 generics: &hir::Generics,
1304 add: &Vec<hir::Lifetime>,
1a4d82fc
JJ
1305 keep: &HashSet<ast::Name>,
1306 remove: &HashSet<ast::Name>,
9cc50fc6 1307 ty_params: hir::HirVec<hir::TyParam>,
e9174d1e
SL
1308 where_clause: hir::WhereClause)
1309 -> hir::Generics {
1a4d82fc 1310 let mut lifetimes = Vec::new();
85aaf69f 1311 for lt in add {
e9174d1e 1312 lifetimes.push(hir::LifetimeDef { lifetime: *lt,
9cc50fc6 1313 bounds: hir::HirVec::new() });
1a4d82fc 1314 }
85aaf69f 1315 for lt in &generics.lifetimes {
1a4d82fc
JJ
1316 if keep.contains(&lt.lifetime.name) ||
1317 !remove.contains(&lt.lifetime.name) {
1318 lifetimes.push((*lt).clone());
1319 }
1320 }
e9174d1e 1321 hir::Generics {
9cc50fc6 1322 lifetimes: lifetimes.into(),
1a4d82fc
JJ
1323 ty_params: ty_params,
1324 where_clause: where_clause,
1325 }
1326 }
1327
1328 fn rebuild_args_ty(&self,
e9174d1e
SL
1329 inputs: &[hir::Arg],
1330 lifetime: hir::Lifetime,
1a4d82fc
JJ
1331 anon_nums: &HashSet<u32>,
1332 region_names: &HashSet<ast::Name>)
9cc50fc6 1333 -> hir::HirVec<hir::Arg> {
1a4d82fc 1334 let mut new_inputs = Vec::new();
85aaf69f 1335 for arg in inputs {
7453a54e 1336 let new_ty = self.rebuild_arg_ty_or_output(&arg.ty, lifetime,
1a4d82fc 1337 anon_nums, region_names);
e9174d1e 1338 let possibly_new_arg = hir::Arg {
1a4d82fc
JJ
1339 ty: new_ty,
1340 pat: arg.pat.clone(),
1341 id: arg.id
1342 };
1343 new_inputs.push(possibly_new_arg);
1344 }
9cc50fc6 1345 new_inputs.into()
1a4d82fc
JJ
1346 }
1347
e9174d1e
SL
1348 fn rebuild_output(&self, ty: &hir::FunctionRetTy,
1349 lifetime: hir::Lifetime,
1a4d82fc 1350 anon_nums: &HashSet<u32>,
e9174d1e 1351 region_names: &HashSet<ast::Name>) -> hir::FunctionRetTy {
1a4d82fc 1352 match *ty {
e9174d1e 1353 hir::Return(ref ret_ty) => hir::Return(
7453a54e 1354 self.rebuild_arg_ty_or_output(&ret_ty, lifetime, anon_nums, region_names)
1a4d82fc 1355 ),
e9174d1e
SL
1356 hir::DefaultReturn(span) => hir::DefaultReturn(span),
1357 hir::NoReturn(span) => hir::NoReturn(span)
1a4d82fc
JJ
1358 }
1359 }
1360
1361 fn rebuild_arg_ty_or_output(&self,
e9174d1e
SL
1362 ty: &hir::Ty,
1363 lifetime: hir::Lifetime,
1a4d82fc
JJ
1364 anon_nums: &HashSet<u32>,
1365 region_names: &HashSet<ast::Name>)
e9174d1e 1366 -> P<hir::Ty> {
1a4d82fc
JJ
1367 let mut new_ty = P(ty.clone());
1368 let mut ty_queue = vec!(ty);
1369 while !ty_queue.is_empty() {
1370 let cur_ty = ty_queue.remove(0);
1371 match cur_ty.node {
e9174d1e 1372 hir::TyRptr(lt_opt, ref mut_ty) => {
1a4d82fc
JJ
1373 let rebuild = match lt_opt {
1374 Some(lt) => region_names.contains(&lt.name),
1375 None => {
1376 let anon = self.cur_anon.get();
1377 let rebuild = anon_nums.contains(&anon);
1378 if rebuild {
1379 self.track_anon(anon);
1380 }
1381 self.inc_and_offset_cur_anon(1);
1382 rebuild
1383 }
1384 };
1385 if rebuild {
e9174d1e 1386 let to = hir::Ty {
1a4d82fc 1387 id: cur_ty.id,
e9174d1e 1388 node: hir::TyRptr(Some(lifetime), mut_ty.clone()),
1a4d82fc
JJ
1389 span: cur_ty.span
1390 };
1391 new_ty = self.rebuild_ty(new_ty, P(to));
1392 }
7453a54e 1393 ty_queue.push(&mut_ty.ty);
1a4d82fc 1394 }
e9174d1e 1395 hir::TyPath(ref maybe_qself, ref path) => {
c34b1796 1396 let a_def = match self.tcx.def_map.borrow().get(&cur_ty.id) {
1a4d82fc
JJ
1397 None => {
1398 self.tcx
1399 .sess
1400 .fatal(&format!(
1401 "unbound path {}",
c34b1796 1402 pprust::path_to_string(path)))
1a4d82fc 1403 }
c34b1796 1404 Some(d) => d.full_def()
1a4d82fc
JJ
1405 };
1406 match a_def {
7453a54e 1407 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) => {
c1a9b12d 1408 let generics = self.tcx.lookup_item_type(did).generics;
1a4d82fc
JJ
1409
1410 let expected =
1411 generics.regions.len(subst::TypeSpace) as u32;
1412 let lifetimes =
1413 path.segments.last().unwrap().parameters.lifetimes();
1414 let mut insert = Vec::new();
9346a6ac 1415 if lifetimes.is_empty() {
1a4d82fc 1416 let anon = self.cur_anon.get();
85aaf69f 1417 for (i, a) in (anon..anon+expected).enumerate() {
1a4d82fc
JJ
1418 if anon_nums.contains(&a) {
1419 insert.push(i as u32);
1420 }
1421 self.track_anon(a);
1422 }
1423 self.inc_and_offset_cur_anon(expected);
1424 } else {
1425 for (i, lt) in lifetimes.iter().enumerate() {
1426 if region_names.contains(&lt.name) {
1427 insert.push(i as u32);
1428 }
1429 }
1430 }
1431 let rebuild_info = RebuildPathInfo {
1432 path: path,
1433 indexes: insert,
1434 expected: expected,
1435 anon_nums: anon_nums,
1436 region_names: region_names
1437 };
1438 let new_path = self.rebuild_path(rebuild_info, lifetime);
c34b1796 1439 let qself = maybe_qself.as_ref().map(|qself| {
e9174d1e 1440 hir::QSelf {
c34b1796
AL
1441 ty: self.rebuild_arg_ty_or_output(&qself.ty, lifetime,
1442 anon_nums, region_names),
1443 position: qself.position
1444 }
1445 });
e9174d1e 1446 let to = hir::Ty {
1a4d82fc 1447 id: cur_ty.id,
e9174d1e 1448 node: hir::TyPath(qself, new_path),
1a4d82fc
JJ
1449 span: cur_ty.span
1450 };
1451 new_ty = self.rebuild_ty(new_ty, P(to));
1452 }
1453 _ => ()
1454 }
1a4d82fc
JJ
1455 }
1456
e9174d1e 1457 hir::TyPtr(ref mut_ty) => {
7453a54e 1458 ty_queue.push(&mut_ty.ty);
1a4d82fc 1459 }
e9174d1e
SL
1460 hir::TyVec(ref ty) |
1461 hir::TyFixedLengthVec(ref ty, _) => {
7453a54e 1462 ty_queue.push(&ty);
1a4d82fc 1463 }
e9174d1e 1464 hir::TyTup(ref tys) => ty_queue.extend(tys.iter().map(|ty| &**ty)),
1a4d82fc
JJ
1465 _ => {}
1466 }
1467 }
1468 new_ty
1469 }
1470
1471 fn rebuild_ty(&self,
e9174d1e
SL
1472 from: P<hir::Ty>,
1473 to: P<hir::Ty>)
1474 -> P<hir::Ty> {
1a4d82fc 1475
e9174d1e
SL
1476 fn build_to(from: P<hir::Ty>,
1477 to: &mut Option<P<hir::Ty>>)
1478 -> P<hir::Ty> {
1a4d82fc
JJ
1479 if Some(from.id) == to.as_ref().map(|ty| ty.id) {
1480 return to.take().expect("`to` type found more than once during rebuild");
1481 }
e9174d1e 1482 from.map(|hir::Ty {id, node, span}| {
1a4d82fc 1483 let new_node = match node {
e9174d1e
SL
1484 hir::TyRptr(lifetime, mut_ty) => {
1485 hir::TyRptr(lifetime, hir::MutTy {
1a4d82fc
JJ
1486 mutbl: mut_ty.mutbl,
1487 ty: build_to(mut_ty.ty, to),
1488 })
1489 }
e9174d1e
SL
1490 hir::TyPtr(mut_ty) => {
1491 hir::TyPtr(hir::MutTy {
1a4d82fc
JJ
1492 mutbl: mut_ty.mutbl,
1493 ty: build_to(mut_ty.ty, to),
1494 })
1495 }
e9174d1e
SL
1496 hir::TyVec(ty) => hir::TyVec(build_to(ty, to)),
1497 hir::TyFixedLengthVec(ty, e) => {
1498 hir::TyFixedLengthVec(build_to(ty, to), e)
1a4d82fc 1499 }
e9174d1e
SL
1500 hir::TyTup(tys) => {
1501 hir::TyTup(tys.into_iter().map(|ty| build_to(ty, to)).collect())
1a4d82fc 1502 }
1a4d82fc
JJ
1503 other => other
1504 };
e9174d1e 1505 hir::Ty { id: id, node: new_node, span: span }
1a4d82fc
JJ
1506 })
1507 }
1508
1509 build_to(from, &mut Some(to))
1510 }
1511
1512 fn rebuild_path(&self,
1513 rebuild_info: RebuildPathInfo,
e9174d1e
SL
1514 lifetime: hir::Lifetime)
1515 -> hir::Path
1a4d82fc
JJ
1516 {
1517 let RebuildPathInfo {
1518 path,
1519 indexes,
1520 expected,
1521 anon_nums,
1522 region_names,
1523 } = rebuild_info;
1524
1525 let last_seg = path.segments.last().unwrap();
1526 let new_parameters = match last_seg.parameters {
e9174d1e 1527 hir::ParenthesizedParameters(..) => {
1a4d82fc
JJ
1528 last_seg.parameters.clone()
1529 }
1530
e9174d1e 1531 hir::AngleBracketedParameters(ref data) => {
1a4d82fc 1532 let mut new_lts = Vec::new();
9346a6ac 1533 if data.lifetimes.is_empty() {
1a4d82fc 1534 // traverse once to see if there's a need to insert lifetime
85aaf69f 1535 let need_insert = (0..expected).any(|i| {
1a4d82fc
JJ
1536 indexes.contains(&i)
1537 });
1538 if need_insert {
85aaf69f 1539 for i in 0..expected {
1a4d82fc
JJ
1540 if indexes.contains(&i) {
1541 new_lts.push(lifetime);
1542 } else {
1543 new_lts.push(self.life_giver.give_lifetime());
1544 }
1545 }
1546 }
1547 } else {
1548 for (i, lt) in data.lifetimes.iter().enumerate() {
1549 if indexes.contains(&(i as u32)) {
1550 new_lts.push(lifetime);
1551 } else {
1552 new_lts.push(*lt);
1553 }
1554 }
1555 }
9cc50fc6 1556 let new_types = data.types.iter().map(|t| {
7453a54e 1557 self.rebuild_arg_ty_or_output(&t, lifetime, anon_nums, region_names)
9cc50fc6
SL
1558 }).collect();
1559 let new_bindings = data.bindings.iter().map(|b| {
92a42be0 1560 hir::TypeBinding {
1a4d82fc 1561 id: b.id,
b039eaaf 1562 name: b.name,
7453a54e 1563 ty: self.rebuild_arg_ty_or_output(&b.ty,
1a4d82fc
JJ
1564 lifetime,
1565 anon_nums,
1566 region_names),
1567 span: b.span
92a42be0 1568 }
9cc50fc6 1569 }).collect();
e9174d1e 1570 hir::AngleBracketedParameters(hir::AngleBracketedParameterData {
9cc50fc6 1571 lifetimes: new_lts.into(),
1a4d82fc
JJ
1572 types: new_types,
1573 bindings: new_bindings,
1574 })
1575 }
1576 };
e9174d1e 1577 let new_seg = hir::PathSegment {
1a4d82fc
JJ
1578 identifier: last_seg.identifier,
1579 parameters: new_parameters
1580 };
1581 let mut new_segs = Vec::new();
92a42be0 1582 new_segs.extend_from_slice(path.segments.split_last().unwrap().1);
1a4d82fc 1583 new_segs.push(new_seg);
e9174d1e 1584 hir::Path {
1a4d82fc
JJ
1585 span: path.span,
1586 global: path.global,
9cc50fc6 1587 segments: new_segs.into()
1a4d82fc
JJ
1588 }
1589 }
1590}
1591
1592impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> {
1593 fn give_expl_lifetime_param(&self,
9cc50fc6 1594 err: &mut DiagnosticBuilder,
e9174d1e
SL
1595 decl: &hir::FnDecl,
1596 unsafety: hir::Unsafety,
1597 constness: hir::Constness,
b039eaaf 1598 name: ast::Name,
e9174d1e
SL
1599 opt_explicit_self: Option<&hir::ExplicitSelf_>,
1600 generics: &hir::Generics,
62682a34 1601 span: Span) {
b039eaaf 1602 let suggested_fn = pprust::fun_to_string(decl, unsafety, constness, name,
62682a34 1603 opt_explicit_self, generics);
1a4d82fc
JJ
1604 let msg = format!("consider using an explicit lifetime \
1605 parameter as shown: {}", suggested_fn);
9cc50fc6 1606 err.span_help(span, &msg[..]);
1a4d82fc
JJ
1607 }
1608
1609 fn report_inference_failure(&self,
9cc50fc6
SL
1610 var_origin: RegionVariableOrigin)
1611 -> DiagnosticBuilder<'tcx> {
62682a34
SL
1612 let br_string = |br: ty::BoundRegion| {
1613 let mut s = br.to_string();
1614 if !s.is_empty() {
1615 s.push_str(" ");
1616 }
1617 s
1618 };
1a4d82fc
JJ
1619 let var_description = match var_origin {
1620 infer::MiscVariable(_) => "".to_string(),
1621 infer::PatternRegion(_) => " for pattern".to_string(),
1622 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1a4d82fc
JJ
1623 infer::Autoref(_) => " for autoref".to_string(),
1624 infer::Coercion(_) => " for automatic coercion".to_string(),
1625 infer::LateBoundRegion(_, br, infer::FnCall) => {
62682a34
SL
1626 format!(" for lifetime parameter {}in function call",
1627 br_string(br))
1a4d82fc
JJ
1628 }
1629 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
62682a34 1630 format!(" for lifetime parameter {}in generic type", br_string(br))
1a4d82fc
JJ
1631 }
1632 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
62682a34 1633 format!(" for lifetime parameter {}in trait containing associated type `{}`",
c1a9b12d 1634 br_string(br), type_name)
1a4d82fc
JJ
1635 }
1636 infer::EarlyBoundRegion(_, name) => {
1637 format!(" for lifetime parameter `{}`",
c1a9b12d 1638 name)
1a4d82fc
JJ
1639 }
1640 infer::BoundRegionInCoherence(name) => {
1641 format!(" for lifetime parameter `{}` in coherence check",
c1a9b12d 1642 name)
1a4d82fc
JJ
1643 }
1644 infer::UpvarRegion(ref upvar_id, _) => {
1645 format!(" for capture of `{}` by closure",
c1a9b12d 1646 self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1a4d82fc
JJ
1647 }
1648 };
1649
9cc50fc6 1650 struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
b039eaaf
SL
1651 "cannot infer an appropriate lifetime{} \
1652 due to conflicting requirements",
9cc50fc6 1653 var_description)
1a4d82fc
JJ
1654 }
1655
9cc50fc6 1656 fn note_region_origin(&self, err: &mut DiagnosticBuilder, origin: &SubregionOrigin<'tcx>) {
1a4d82fc 1657 match *origin {
c1a9b12d 1658 infer::Subtype(ref trace) => {
1a4d82fc 1659 let desc = match trace.origin {
92a42be0 1660 TypeOrigin::Misc(_) => {
c34b1796 1661 "types are compatible"
1a4d82fc 1662 }
92a42be0 1663 TypeOrigin::MethodCompatCheck(_) => {
c34b1796 1664 "method type is compatible with trait"
1a4d82fc 1665 }
92a42be0 1666 TypeOrigin::ExprAssignable(_) => {
c34b1796 1667 "expression is assignable"
1a4d82fc 1668 }
92a42be0 1669 TypeOrigin::RelateTraitRefs(_) => {
c34b1796 1670 "traits are compatible"
1a4d82fc 1671 }
92a42be0 1672 TypeOrigin::RelateSelfType(_) => {
c34b1796 1673 "self type matches impl self type"
1a4d82fc 1674 }
92a42be0 1675 TypeOrigin::RelateOutputImplTypes(_) => {
c34b1796
AL
1676 "trait type parameters matches those \
1677 specified on the impl"
1a4d82fc 1678 }
92a42be0 1679 TypeOrigin::MatchExpressionArm(_, _, _) => {
c34b1796 1680 "match arms have compatible types"
1a4d82fc 1681 }
92a42be0 1682 TypeOrigin::IfExpression(_) => {
c34b1796 1683 "if and else have compatible types"
1a4d82fc 1684 }
92a42be0 1685 TypeOrigin::IfExpressionWithNoElse(_) => {
c34b1796 1686 "if may be missing an else clause"
1a4d82fc 1687 }
92a42be0 1688 TypeOrigin::RangeExpression(_) => {
c34b1796 1689 "start and end of range have compatible types"
1a4d82fc 1690 }
92a42be0 1691 TypeOrigin::EquatePredicate(_) => {
c34b1796 1692 "equality where clause is satisfied"
1a4d82fc
JJ
1693 }
1694 };
1695
1696 match self.values_str(&trace.values) {
1697 Some(values_str) => {
9cc50fc6 1698 err.span_note(
1a4d82fc
JJ
1699 trace.origin.span(),
1700 &format!("...so that {} ({})",
c34b1796 1701 desc, values_str));
1a4d82fc
JJ
1702 }
1703 None => {
1704 // Really should avoid printing this error at
1705 // all, since it is derived, but that would
1706 // require more refactoring than I feel like
1707 // doing right now. - nmatsakis
9cc50fc6 1708 err.span_note(
1a4d82fc 1709 trace.origin.span(),
c34b1796 1710 &format!("...so that {}", desc));
1a4d82fc
JJ
1711 }
1712 }
1713 }
1714 infer::Reborrow(span) => {
9cc50fc6 1715 err.span_note(
1a4d82fc
JJ
1716 span,
1717 "...so that reference does not outlive \
1718 borrowed content");
1719 }
1720 infer::ReborrowUpvar(span, ref upvar_id) => {
9cc50fc6 1721 err.span_note(
1a4d82fc
JJ
1722 span,
1723 &format!(
1724 "...so that closure can access `{}`",
c1a9b12d 1725 self.tcx.local_var_name_str(upvar_id.var_id)
9cc50fc6 1726 .to_string()));
1a4d82fc
JJ
1727 }
1728 infer::InfStackClosure(span) => {
9cc50fc6 1729 err.span_note(
1a4d82fc
JJ
1730 span,
1731 "...so that closure does not outlive its stack frame");
1732 }
1733 infer::InvokeClosure(span) => {
9cc50fc6 1734 err.span_note(
1a4d82fc
JJ
1735 span,
1736 "...so that closure is not invoked outside its lifetime");
1737 }
1738 infer::DerefPointer(span) => {
9cc50fc6 1739 err.span_note(
1a4d82fc
JJ
1740 span,
1741 "...so that pointer is not dereferenced \
1742 outside its lifetime");
1743 }
1744 infer::FreeVariable(span, id) => {
9cc50fc6 1745 err.span_note(
1a4d82fc
JJ
1746 span,
1747 &format!("...so that captured variable `{}` \
1748 does not outlive the enclosing closure",
c1a9b12d 1749 self.tcx.local_var_name_str(id)));
1a4d82fc
JJ
1750 }
1751 infer::IndexSlice(span) => {
9cc50fc6 1752 err.span_note(
1a4d82fc
JJ
1753 span,
1754 "...so that slice is not indexed outside the lifetime");
1755 }
1756 infer::RelateObjectBound(span) => {
9cc50fc6 1757 err.span_note(
1a4d82fc
JJ
1758 span,
1759 "...so that it can be closed over into an object");
1760 }
1761 infer::CallRcvr(span) => {
9cc50fc6 1762 err.span_note(
1a4d82fc
JJ
1763 span,
1764 "...so that method receiver is valid for the method call");
1765 }
1766 infer::CallArg(span) => {
9cc50fc6 1767 err.span_note(
1a4d82fc
JJ
1768 span,
1769 "...so that argument is valid for the call");
1770 }
1771 infer::CallReturn(span) => {
9cc50fc6 1772 err.span_note(
1a4d82fc
JJ
1773 span,
1774 "...so that return value is valid for the call");
1775 }
85aaf69f 1776 infer::Operand(span) => {
9cc50fc6 1777 err.span_note(
85aaf69f
SL
1778 span,
1779 "...so that operand is valid for operation");
1780 }
1a4d82fc 1781 infer::AddrOf(span) => {
9cc50fc6 1782 err.span_note(
1a4d82fc
JJ
1783 span,
1784 "...so that reference is valid \
1785 at the time of borrow");
1786 }
1787 infer::AutoBorrow(span) => {
9cc50fc6 1788 err.span_note(
1a4d82fc
JJ
1789 span,
1790 "...so that auto-reference is valid \
1791 at the time of borrow");
1792 }
1793 infer::ExprTypeIsNotInScope(t, span) => {
9cc50fc6 1794 err.span_note(
1a4d82fc
JJ
1795 span,
1796 &format!("...so type `{}` of expression is valid during the \
1797 expression",
c34b1796 1798 self.ty_to_string(t)));
1a4d82fc
JJ
1799 }
1800 infer::BindingTypeIsNotValidAtDecl(span) => {
9cc50fc6 1801 err.span_note(
1a4d82fc
JJ
1802 span,
1803 "...so that variable is valid at time of its declaration");
1804 }
e9174d1e 1805 infer::ParameterInScope(_, span) => {
9cc50fc6 1806 err.span_note(
e9174d1e 1807 span,
92a42be0 1808 "...so that a type/lifetime parameter is in scope here");
e9174d1e
SL
1809 }
1810 infer::DataBorrowed(ty, span) => {
9cc50fc6 1811 err.span_note(
e9174d1e
SL
1812 span,
1813 &format!("...so that the type `{}` is not borrowed for too long",
1814 self.ty_to_string(ty)));
1815 }
1a4d82fc 1816 infer::ReferenceOutlivesReferent(ty, span) => {
9cc50fc6 1817 err.span_note(
1a4d82fc
JJ
1818 span,
1819 &format!("...so that the reference type `{}` \
1820 does not outlive the data it points at",
c34b1796 1821 self.ty_to_string(ty)));
1a4d82fc
JJ
1822 }
1823 infer::RelateParamBound(span, t) => {
9cc50fc6 1824 err.span_note(
1a4d82fc
JJ
1825 span,
1826 &format!("...so that the type `{}` \
85aaf69f 1827 will meet its required lifetime bounds",
c34b1796 1828 self.ty_to_string(t)));
1a4d82fc
JJ
1829 }
1830 infer::RelateDefaultParamBound(span, t) => {
9cc50fc6 1831 err.span_note(
1a4d82fc
JJ
1832 span,
1833 &format!("...so that type parameter \
1834 instantiated with `{}`, \
1835 will meet its declared lifetime bounds",
c34b1796 1836 self.ty_to_string(t)));
1a4d82fc
JJ
1837 }
1838 infer::RelateRegionParamBound(span) => {
9cc50fc6 1839 err.span_note(
1a4d82fc 1840 span,
c34b1796
AL
1841 "...so that the declared lifetime parameter bounds \
1842 are satisfied");
1a4d82fc 1843 }
85aaf69f 1844 infer::SafeDestructor(span) => {
9cc50fc6 1845 err.span_note(
85aaf69f
SL
1846 span,
1847 "...so that references are valid when the destructor \
9cc50fc6 1848 runs");
85aaf69f 1849 }
1a4d82fc
JJ
1850 }
1851 }
1852}
1853
1854pub trait Resolvable<'tcx> {
1855 fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Self;
1a4d82fc
JJ
1856}
1857
1858impl<'tcx> Resolvable<'tcx> for Ty<'tcx> {
1859 fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Ty<'tcx> {
1860 infcx.resolve_type_vars_if_possible(self)
1861 }
1a4d82fc
JJ
1862}
1863
d9579d0f 1864impl<'tcx> Resolvable<'tcx> for ty::TraitRef<'tcx> {
1a4d82fc 1865 fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>)
d9579d0f
AL
1866 -> ty::TraitRef<'tcx> {
1867 infcx.resolve_type_vars_if_possible(self)
1a4d82fc 1868 }
1a4d82fc
JJ
1869}
1870
1871impl<'tcx> Resolvable<'tcx> for ty::PolyTraitRef<'tcx> {
1872 fn resolve<'a>(&self,
1873 infcx: &InferCtxt<'a, 'tcx>)
1874 -> ty::PolyTraitRef<'tcx>
1875 {
1876 infcx.resolve_type_vars_if_possible(self)
1877 }
1a4d82fc
JJ
1878}
1879
1880fn lifetimes_in_scope(tcx: &ty::ctxt,
1881 scope_id: ast::NodeId)
e9174d1e 1882 -> Vec<hir::LifetimeDef> {
1a4d82fc
JJ
1883 let mut taken = Vec::new();
1884 let parent = tcx.map.get_parent(scope_id);
1885 let method_id_opt = match tcx.map.find(parent) {
1886 Some(node) => match node {
1887 ast_map::NodeItem(item) => match item.node {
e9174d1e 1888 hir::ItemFn(_, _, _, _, ref gen, _) => {
92a42be0 1889 taken.extend_from_slice(&gen.lifetimes);
1a4d82fc
JJ
1890 None
1891 },
1892 _ => None
1893 },
1894 ast_map::NodeImplItem(ii) => {
c34b1796 1895 match ii.node {
92a42be0
SL
1896 hir::ImplItemKind::Method(ref sig, _) => {
1897 taken.extend_from_slice(&sig.generics.lifetimes);
c34b1796 1898 Some(ii.id)
1a4d82fc 1899 }
d9579d0f 1900 _ => None,
1a4d82fc
JJ
1901 }
1902 }
1903 _ => None
1904 },
1905 None => None
1906 };
1907 if method_id_opt.is_some() {
1908 let method_id = method_id_opt.unwrap();
1909 let parent = tcx.map.get_parent(method_id);
1910 match tcx.map.find(parent) {
1911 Some(node) => match node {
1912 ast_map::NodeItem(item) => match item.node {
e9174d1e 1913 hir::ItemImpl(_, _, ref gen, _, _, _) => {
92a42be0 1914 taken.extend_from_slice(&gen.lifetimes);
1a4d82fc
JJ
1915 }
1916 _ => ()
1917 },
1918 _ => ()
1919 },
1920 None => ()
1921 }
1922 }
1923 return taken;
1924}
1925
1926// LifeGiver is responsible for generating fresh lifetime names
1927struct LifeGiver {
1928 taken: HashSet<String>,
c34b1796 1929 counter: Cell<usize>,
e9174d1e 1930 generated: RefCell<Vec<hir::Lifetime>>,
1a4d82fc
JJ
1931}
1932
1933impl LifeGiver {
e9174d1e 1934 fn with_taken(taken: &[hir::LifetimeDef]) -> LifeGiver {
1a4d82fc 1935 let mut taken_ = HashSet::new();
85aaf69f 1936 for lt in taken {
c1a9b12d 1937 let lt_name = lt.lifetime.name.to_string();
1a4d82fc
JJ
1938 taken_.insert(lt_name);
1939 }
1940 LifeGiver {
1941 taken: taken_,
1942 counter: Cell::new(0),
1943 generated: RefCell::new(Vec::new()),
1944 }
1945 }
1946
1947 fn inc_counter(&self) {
1948 let c = self.counter.get();
1949 self.counter.set(c+1);
1950 }
1951
e9174d1e 1952 fn give_lifetime(&self) -> hir::Lifetime {
c1a9b12d 1953 let lifetime;
1a4d82fc 1954 loop {
62682a34 1955 let mut s = String::from("'");
c34b1796 1956 s.push_str(&num_to_string(self.counter.get()));
1a4d82fc 1957 if !self.taken.contains(&s) {
b039eaaf 1958 lifetime = name_to_dummy_lifetime(token::intern(&s[..]));
1a4d82fc
JJ
1959 self.generated.borrow_mut().push(lifetime);
1960 break;
1961 }
1962 self.inc_counter();
1963 }
1964 self.inc_counter();
1965 return lifetime;
1966
1967 // 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on
c34b1796 1968 fn num_to_string(counter: usize) -> String {
1a4d82fc
JJ
1969 let mut s = String::new();
1970 let (n, r) = (counter/26 + 1, counter % 26);
1971 let letter: char = from_u32((r+97) as u32).unwrap();
85aaf69f 1972 for _ in 0..n {
1a4d82fc
JJ
1973 s.push(letter);
1974 }
1975 s
1976 }
1977 }
1978
e9174d1e 1979 fn get_generated_lifetimes(&self) -> Vec<hir::Lifetime> {
1a4d82fc
JJ
1980 self.generated.borrow().clone()
1981 }
1982}
e9174d1e
SL
1983
1984fn name_to_dummy_lifetime(name: ast::Name) -> hir::Lifetime {
1985 hir::Lifetime { id: ast::DUMMY_NODE_ID,
1986 span: codemap::DUMMY_SP,
1987 name: name }
1988}