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.
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.
11 //! Error Reporting Code for the inference engine
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.
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
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.
31 //! # Region Inference
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.
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.
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.
58 use self::FreshOrKept::*;
62 use super::SubregionOrigin;
63 use super::RegionVariableOrigin;
64 use super::ValuePairs;
65 use super::region_inference::RegionResolutionError;
66 use super::region_inference::ConcreteFailure;
67 use super::region_inference::SubSupConflict;
68 use super::region_inference::SupSupConflict;
69 use super::region_inference::GenericBoundFailure;
70 use super::region_inference::GenericKind;
71 use super::region_inference::ProcessedErrors;
72 use super::region_inference::SameRegions;
74 use std::collections::HashSet;
78 use middle::ty::{self, Ty};
79 use middle::ty::{Region, ReFree};
80 use std::cell::{Cell, RefCell};
81 use std::char::from_u32;
83 use std::string::String;
86 use syntax::ast_util::{name_to_dummy_lifetime, PostExpansionMethod};
87 use syntax::owned_slice::OwnedSlice;
89 use syntax::parse::token;
90 use syntax::print::pprust;
92 use util::ppaux::bound_region_to_string;
93 use util::ppaux::note_and_explain_region;
95 // Note: only import UserString, not Repr, since user-facing error
96 // messages shouldn't include debug serializations.
97 use util::ppaux::UserString;
99 pub trait ErrorReporting<'tcx> {
100 fn report_region_errors(&self,
101 errors: &Vec<RegionResolutionError<'tcx>>);
103 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
104 -> Vec<RegionResolutionError<'tcx>>;
106 fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::type_err<'tcx>);
108 fn report_and_explain_type_error(&self,
109 trace: TypeTrace<'tcx>,
110 terr: &ty::type_err<'tcx>);
112 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String>;
114 fn expected_found_str<T: UserString<'tcx> + Resolvable<'tcx>>(
116 exp_found: &ty::expected_found<T>)
119 fn report_concrete_failure(&self,
120 origin: SubregionOrigin<'tcx>,
124 fn report_generic_bound_failure(&self,
125 origin: SubregionOrigin<'tcx>,
126 kind: GenericKind<'tcx>,
130 fn report_sub_sup_conflict(&self,
131 var_origin: RegionVariableOrigin,
132 sub_origin: SubregionOrigin<'tcx>,
134 sup_origin: SubregionOrigin<'tcx>,
137 fn report_sup_sup_conflict(&self,
138 var_origin: RegionVariableOrigin,
139 origin1: SubregionOrigin<'tcx>,
141 origin2: SubregionOrigin<'tcx>,
144 fn report_processed_errors(&self,
145 var_origin: &[RegionVariableOrigin],
146 trace_origin: &[(TypeTrace<'tcx>, ty::type_err<'tcx>)],
147 same_regions: &[SameRegions]);
149 fn give_suggestion(&self, same_regions: &[SameRegions]);
152 trait ErrorReportingHelpers<'tcx> {
153 fn report_inference_failure(&self,
154 var_origin: RegionVariableOrigin);
156 fn note_region_origin(&self,
157 origin: &SubregionOrigin<'tcx>);
159 fn give_expl_lifetime_param(&self,
161 unsafety: ast::Unsafety,
163 opt_explicit_self: Option<&ast::ExplicitSelf_>,
164 generics: &ast::Generics,
165 span: codemap::Span);
168 impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> {
169 fn report_region_errors(&self,
170 errors: &Vec<RegionResolutionError<'tcx>>) {
171 let p_errors = self.process_errors(errors);
172 let errors = if p_errors.is_empty() { errors } else { &p_errors };
173 for error in errors.iter() {
174 match error.clone() {
175 ConcreteFailure(origin, sub, sup) => {
176 self.report_concrete_failure(origin, sub, sup);
179 GenericBoundFailure(kind, param_ty, sub, sups) => {
180 self.report_generic_bound_failure(kind, param_ty, sub, sups);
183 SubSupConflict(var_origin,
185 sup_origin, sup_r) => {
186 self.report_sub_sup_conflict(var_origin,
191 SupSupConflict(var_origin,
194 self.report_sup_sup_conflict(var_origin,
199 ProcessedErrors(ref var_origins,
201 ref same_regions) => {
202 if !same_regions.is_empty() {
203 self.report_processed_errors(&var_origins[],
212 // This method goes through all the errors and try to group certain types
213 // of error together, for the purpose of suggesting explicit lifetime
214 // parameters to the user. This is done so that we can have a more
215 // complete view of what lifetimes should be the same.
216 // If the return value is an empty vector, it means that processing
217 // failed (so the return value of this method should not be used)
218 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
219 -> Vec<RegionResolutionError<'tcx>> {
220 debug!("process_errors()");
221 let mut var_origins = Vec::new();
222 let mut trace_origins = Vec::new();
223 let mut same_regions = Vec::new();
224 let mut processed_errors = Vec::new();
225 for error in errors.iter() {
226 match error.clone() {
227 ConcreteFailure(origin, sub, sup) => {
228 debug!("processing ConcreteFailure");
229 let trace = match origin {
230 infer::Subtype(trace) => Some(trace),
233 match free_regions_from_same_fn(self.tcx, sub, sup) {
234 Some(ref same_frs) if trace.is_some() => {
235 let trace = trace.unwrap();
236 let terr = ty::terr_regions_does_not_outlive(sup,
238 trace_origins.push((trace, terr));
239 append_to_same_regions(&mut same_regions, same_frs);
241 _ => processed_errors.push((*error).clone()),
244 SubSupConflict(var_origin, _, sub_r, _, sup_r) => {
245 debug!("processing SubSupConflict");
246 match free_regions_from_same_fn(self.tcx, sub_r, sup_r) {
247 Some(ref same_frs) => {
248 var_origins.push(var_origin);
249 append_to_same_regions(&mut same_regions, same_frs);
251 None => processed_errors.push((*error).clone()),
254 SupSupConflict(..) => processed_errors.push((*error).clone()),
255 _ => () // This shouldn't happen
258 if !same_regions.is_empty() {
259 let common_scope_id = same_regions[0].scope_id;
260 for sr in same_regions.iter() {
261 // Since ProcessedErrors is used to reconstruct the function
262 // declaration, we want to make sure that they are, in fact,
263 // from the same scope
264 if sr.scope_id != common_scope_id {
265 debug!("returning empty result from process_errors because
266 {} != {}", sr.scope_id, common_scope_id);
270 let pe = ProcessedErrors(var_origins, trace_origins, same_regions);
271 debug!("errors processed: {:?}", pe);
272 processed_errors.push(pe);
274 return processed_errors;
277 struct FreeRegionsFromSameFn {
278 sub_fr: ty::FreeRegion,
279 sup_fr: ty::FreeRegion,
280 scope_id: ast::NodeId
283 impl FreeRegionsFromSameFn {
284 fn new(sub_fr: ty::FreeRegion,
285 sup_fr: ty::FreeRegion,
286 scope_id: ast::NodeId)
287 -> FreeRegionsFromSameFn {
288 FreeRegionsFromSameFn {
296 fn free_regions_from_same_fn(tcx: &ty::ctxt,
299 -> Option<FreeRegionsFromSameFn> {
300 debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
301 let (scope_id, fr1, fr2) = match (sub, sup) {
302 (ReFree(fr1), ReFree(fr2)) => {
303 if fr1.scope != fr2.scope {
306 assert!(fr1.scope == fr2.scope);
307 (fr1.scope.node_id(), fr1, fr2)
311 let parent = tcx.map.get_parent(scope_id);
312 let parent_node = tcx.map.find(parent);
314 Some(node) => match node {
315 ast_map::NodeItem(item) => match item.node {
317 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
321 ast_map::NodeImplItem(..) |
322 ast_map::NodeTraitItem(..) => {
323 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
328 debug!("no parent node of scope_id {}", scope_id);
334 fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
335 same_frs: &FreeRegionsFromSameFn) {
336 let scope_id = same_frs.scope_id;
337 let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
338 for sr in same_regions.iter_mut() {
339 if sr.contains(&sup_fr.bound_region)
340 && scope_id == sr.scope_id {
341 sr.push(sub_fr.bound_region);
345 same_regions.push(SameRegions {
347 regions: vec!(sub_fr.bound_region, sup_fr.bound_region)
352 fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::type_err<'tcx>) {
353 let expected_found_str = match self.values_str(&trace.values) {
356 return; /* derived error */
360 let message_root_str = match trace.origin {
361 infer::Misc(_) => "mismatched types",
362 infer::MethodCompatCheck(_) => "method not compatible with trait",
363 infer::ExprAssignable(_) => "mismatched types",
364 infer::RelateTraitRefs(_) => "mismatched traits",
365 infer::RelateSelfType(_) => "mismatched types",
366 infer::RelateOutputImplTypes(_) => "mismatched types",
367 infer::MatchExpressionArm(_, _) => "match arms have incompatible types",
368 infer::IfExpression(_) => "if and else have incompatible types",
369 infer::IfExpressionWithNoElse(_) => "if may be missing an else clause",
370 infer::RangeExpression(_) => "start and end of range have incompatible types",
371 infer::EquatePredicate(_) => "equality predicate not satisfied",
374 self.tcx.sess.span_err(
376 &format!("{}: {} ({})",
379 ty::type_err_to_str(self.tcx, terr))[]);
382 infer::MatchExpressionArm(_, arm_span) =>
383 self.tcx.sess.span_note(arm_span, "match arm with an incompatible type"),
388 fn report_and_explain_type_error(&self,
389 trace: TypeTrace<'tcx>,
390 terr: &ty::type_err<'tcx>) {
391 self.report_type_error(trace, terr);
392 ty::note_and_explain_type_err(self.tcx, terr);
395 /// Returns a string of the form "expected `{}`, found `{}`", or None if this is a derived
397 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String> {
399 infer::Types(ref exp_found) => self.expected_found_str(exp_found),
400 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
401 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found)
405 fn expected_found_str<T: UserString<'tcx> + Resolvable<'tcx>>(
407 exp_found: &ty::expected_found<T>)
410 let expected = exp_found.expected.resolve(self);
411 if expected.contains_error() {
415 let found = exp_found.found.resolve(self);
416 if found.contains_error() {
420 Some(format!("expected `{}`, found `{}`",
421 expected.user_string(self.tcx),
422 found.user_string(self.tcx)))
425 fn report_generic_bound_failure(&self,
426 origin: SubregionOrigin<'tcx>,
427 bound_kind: GenericKind<'tcx>,
431 // FIXME: it would be better to report the first error message
432 // with the span of the parameter itself, rather than the span
433 // where the error was detected. But that span is not readily
436 let labeled_user_string = match bound_kind {
437 GenericKind::Param(ref p) =>
438 format!("the parameter type `{}`", p.user_string(self.tcx)),
439 GenericKind::Projection(ref p) =>
440 format!("the associated type `{}`", p.user_string(self.tcx)),
444 ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
445 // Does the required lifetime have a nice name we can print?
446 self.tcx.sess.span_err(
448 &format!("{} may not live long enough", labeled_user_string)[]);
449 self.tcx.sess.span_help(
452 "consider adding an explicit lifetime bound `{}: {}`...",
453 bound_kind.user_string(self.tcx),
454 sub.user_string(self.tcx))[]);
458 // Does the required lifetime have a nice name we can print?
459 self.tcx.sess.span_err(
461 &format!("{} may not live long enough", labeled_user_string)[]);
462 self.tcx.sess.span_help(
465 "consider adding an explicit lifetime bound `{}: 'static`...",
466 bound_kind.user_string(self.tcx))[]);
470 // If not, be less specific.
471 self.tcx.sess.span_err(
474 "{} may not live long enough",
475 labeled_user_string)[]);
476 self.tcx.sess.span_help(
479 "consider adding an explicit lifetime bound for `{}`",
480 bound_kind.user_string(self.tcx))[]);
481 note_and_explain_region(
483 &format!("{} must be valid for ", labeled_user_string)[],
489 self.note_region_origin(&origin);
492 fn report_concrete_failure(&self,
493 origin: SubregionOrigin<'tcx>,
497 infer::Subtype(trace) => {
498 let terr = ty::terr_regions_does_not_outlive(sup, sub);
499 self.report_and_explain_type_error(trace, &terr);
501 infer::Reborrow(span) => {
502 self.tcx.sess.span_err(
504 "lifetime of reference outlines \
505 lifetime of borrowed content...");
506 note_and_explain_region(
508 "...the reference is valid for ",
511 note_and_explain_region(
513 "...but the borrowed content is only valid for ",
517 infer::ReborrowUpvar(span, ref upvar_id) => {
518 self.tcx.sess.span_err(
520 &format!("lifetime of borrowed pointer outlives \
521 lifetime of captured variable `{}`...",
522 ty::local_var_name_str(self.tcx,
526 note_and_explain_region(
528 "...the borrowed pointer is valid for ",
531 note_and_explain_region(
533 &format!("...but `{}` is only valid for ",
534 ty::local_var_name_str(self.tcx,
541 infer::InfStackClosure(span) => {
542 self.tcx.sess.span_err(
544 "closure outlives stack frame");
545 note_and_explain_region(
547 "...the closure must be valid for ",
550 note_and_explain_region(
552 "...but the closure's stack frame is only valid for ",
556 infer::InvokeClosure(span) => {
557 self.tcx.sess.span_err(
559 "cannot invoke closure outside of its lifetime");
560 note_and_explain_region(
562 "the closure is only valid for ",
566 infer::DerefPointer(span) => {
567 self.tcx.sess.span_err(
569 "dereference of reference outside its lifetime");
570 note_and_explain_region(
572 "the reference is only valid for ",
576 infer::FreeVariable(span, id) => {
577 self.tcx.sess.span_err(
579 &format!("captured variable `{}` does not \
580 outlive the enclosing closure",
581 ty::local_var_name_str(self.tcx,
584 note_and_explain_region(
586 "captured variable is valid for ",
589 note_and_explain_region(
591 "closure is valid for ",
595 infer::IndexSlice(span) => {
596 self.tcx.sess.span_err(span,
597 "index of slice outside its lifetime");
598 note_and_explain_region(
600 "the slice is only valid for ",
604 infer::RelateObjectBound(span) => {
605 self.tcx.sess.span_err(
607 "lifetime of the source pointer does not outlive \
608 lifetime bound of the object type");
609 note_and_explain_region(
611 "object type is valid for ",
614 note_and_explain_region(
616 "source pointer is only valid for ",
620 infer::RelateParamBound(span, ty) => {
621 self.tcx.sess.span_err(
623 &format!("the type `{}` does not fulfill the \
625 self.ty_to_string(ty))[]);
626 note_and_explain_region(self.tcx,
627 "type must outlive ",
631 infer::RelateRegionParamBound(span) => {
632 self.tcx.sess.span_err(
634 "declared lifetime bound not satisfied");
635 note_and_explain_region(
637 "lifetime parameter instantiated with ",
640 note_and_explain_region(
642 "but lifetime parameter must outlive ",
646 infer::RelateDefaultParamBound(span, ty) => {
647 self.tcx.sess.span_err(
649 &format!("the type `{}` (provided as the value of \
650 a type parameter) is not valid at this point",
651 self.ty_to_string(ty))[]);
652 note_and_explain_region(self.tcx,
653 "type must outlive ",
657 infer::CallRcvr(span) => {
658 self.tcx.sess.span_err(
660 "lifetime of method receiver does not outlive \
662 note_and_explain_region(
664 "the receiver is only valid for ",
668 infer::CallArg(span) => {
669 self.tcx.sess.span_err(
671 "lifetime of function argument does not outlive \
673 note_and_explain_region(
675 "the function argument is only valid for ",
679 infer::CallReturn(span) => {
680 self.tcx.sess.span_err(
682 "lifetime of return value does not outlive \
684 note_and_explain_region(
686 "the return value is only valid for ",
690 infer::AddrOf(span) => {
691 self.tcx.sess.span_err(
693 "reference is not valid \
694 at the time of borrow");
695 note_and_explain_region(
697 "the borrow is only valid for ",
701 infer::AutoBorrow(span) => {
702 self.tcx.sess.span_err(
704 "automatically reference is not valid \
705 at the time of borrow");
706 note_and_explain_region(
708 "the automatic borrow is only valid for ",
712 infer::ExprTypeIsNotInScope(t, span) => {
713 self.tcx.sess.span_err(
715 &format!("type of expression contains references \
716 that are not valid during the expression: `{}`",
717 self.ty_to_string(t))[]);
718 note_and_explain_region(
720 "type is only valid for ",
724 infer::BindingTypeIsNotValidAtDecl(span) => {
725 self.tcx.sess.span_err(
727 "lifetime of variable does not enclose its declaration");
728 note_and_explain_region(
730 "the variable is only valid for ",
734 infer::ReferenceOutlivesReferent(ty, span) => {
735 self.tcx.sess.span_err(
737 &format!("in type `{}`, reference has a longer lifetime \
738 than the data it references",
739 self.ty_to_string(ty))[]);
740 note_and_explain_region(
742 "the pointer is valid for ",
745 note_and_explain_region(
747 "but the referenced data is only valid for ",
754 fn report_sub_sup_conflict(&self,
755 var_origin: RegionVariableOrigin,
756 sub_origin: SubregionOrigin<'tcx>,
758 sup_origin: SubregionOrigin<'tcx>,
759 sup_region: Region) {
760 self.report_inference_failure(var_origin);
762 note_and_explain_region(
764 "first, the lifetime cannot outlive ",
768 self.note_region_origin(&sup_origin);
770 note_and_explain_region(
772 "but, the lifetime must be valid for ",
776 self.note_region_origin(&sub_origin);
779 fn report_sup_sup_conflict(&self,
780 var_origin: RegionVariableOrigin,
781 origin1: SubregionOrigin<'tcx>,
783 origin2: SubregionOrigin<'tcx>,
785 self.report_inference_failure(var_origin);
787 note_and_explain_region(
789 "first, the lifetime must be contained by ",
793 self.note_region_origin(&origin1);
795 note_and_explain_region(
797 "but, the lifetime must also be contained by ",
801 self.note_region_origin(&origin2);
804 fn report_processed_errors(&self,
805 var_origins: &[RegionVariableOrigin],
806 trace_origins: &[(TypeTrace<'tcx>, ty::type_err<'tcx>)],
807 same_regions: &[SameRegions]) {
808 for vo in var_origins.iter() {
809 self.report_inference_failure(vo.clone());
811 self.give_suggestion(same_regions);
812 for &(ref trace, terr) in trace_origins.iter() {
813 self.report_type_error(trace.clone(), &terr);
817 fn give_suggestion(&self, same_regions: &[SameRegions]) {
818 let scope_id = same_regions[0].scope_id;
819 let parent = self.tcx.map.get_parent(scope_id);
820 let parent_node = self.tcx.map.find(parent);
821 let node_inner = match parent_node {
822 Some(ref node) => match *node {
823 ast_map::NodeItem(ref item) => {
825 ast::ItemFn(ref fn_decl, pur, _, ref gen, _) => {
826 Some((&**fn_decl, gen, pur, item.ident, None, item.span))
831 ast_map::NodeImplItem(ref item) => {
833 ast::MethodImplItem(ref m) => {
834 Some((m.pe_fn_decl(),
838 Some(&m.pe_explicit_self().node),
841 ast::TypeImplItem(_) => None,
844 ast_map::NodeTraitItem(ref item) => {
846 ast::ProvidedMethod(ref m) => {
847 Some((m.pe_fn_decl(),
851 Some(&m.pe_explicit_self().node),
861 let (fn_decl, generics, unsafety, ident, expl_self, span)
862 = node_inner.expect("expect item fn");
863 let taken = lifetimes_in_scope(self.tcx, scope_id);
864 let life_giver = LifeGiver::with_taken(&taken[]);
865 let rebuilder = Rebuilder::new(self.tcx, fn_decl, expl_self,
866 generics, same_regions, &life_giver);
867 let (fn_decl, expl_self, generics) = rebuilder.rebuild();
868 self.give_expl_lifetime_param(&fn_decl, unsafety, ident,
869 expl_self.as_ref(), &generics, span);
873 struct RebuildPathInfo<'a> {
875 // indexes to insert lifetime on path.lifetimes
877 // number of lifetimes we expect to see on the type referred by `path`
878 // (e.g., expected=1 for struct Foo<'a>)
880 anon_nums: &'a HashSet<u32>,
881 region_names: &'a HashSet<ast::Name>
884 struct Rebuilder<'a, 'tcx: 'a> {
885 tcx: &'a ty::ctxt<'tcx>,
886 fn_decl: &'a ast::FnDecl,
887 expl_self_opt: Option<&'a ast::ExplicitSelf_>,
888 generics: &'a ast::Generics,
889 same_regions: &'a [SameRegions],
890 life_giver: &'a LifeGiver,
892 inserted_anons: RefCell<HashSet<u32>>,
900 impl<'a, 'tcx> Rebuilder<'a, 'tcx> {
901 fn new(tcx: &'a ty::ctxt<'tcx>,
902 fn_decl: &'a ast::FnDecl,
903 expl_self_opt: Option<&'a ast::ExplicitSelf_>,
904 generics: &'a ast::Generics,
905 same_regions: &'a [SameRegions],
906 life_giver: &'a LifeGiver)
907 -> Rebuilder<'a, 'tcx> {
911 expl_self_opt: expl_self_opt,
913 same_regions: same_regions,
914 life_giver: life_giver,
915 cur_anon: Cell::new(0),
916 inserted_anons: RefCell::new(HashSet::new()),
921 -> (ast::FnDecl, Option<ast::ExplicitSelf_>, ast::Generics) {
922 let mut expl_self_opt = self.expl_self_opt.map(|x| x.clone());
923 let mut inputs = self.fn_decl.inputs.clone();
924 let mut output = self.fn_decl.output.clone();
925 let mut ty_params = self.generics.ty_params.clone();
926 let where_clause = self.generics.where_clause.clone();
927 let mut kept_lifetimes = HashSet::new();
928 for sr in self.same_regions.iter() {
929 self.cur_anon.set(0);
930 self.offset_cur_anon();
931 let (anon_nums, region_names) =
932 self.extract_anon_nums_and_names(sr);
933 let (lifetime, fresh_or_kept) = self.pick_lifetime(®ion_names);
934 match fresh_or_kept {
935 Kept => { kept_lifetimes.insert(lifetime.name); }
938 expl_self_opt = self.rebuild_expl_self(expl_self_opt, lifetime,
939 &anon_nums, ®ion_names);
940 inputs = self.rebuild_args_ty(&inputs[], lifetime,
941 &anon_nums, ®ion_names);
942 output = self.rebuild_output(&output, lifetime, &anon_nums, ®ion_names);
943 ty_params = self.rebuild_ty_params(ty_params, lifetime,
946 let fresh_lifetimes = self.life_giver.get_generated_lifetimes();
947 let all_region_names = self.extract_all_region_names();
948 let generics = self.rebuild_generics(self.generics,
954 let new_fn_decl = ast::FnDecl {
957 variadic: self.fn_decl.variadic
959 (new_fn_decl, expl_self_opt, generics)
962 fn pick_lifetime(&self,
963 region_names: &HashSet<ast::Name>)
964 -> (ast::Lifetime, FreshOrKept) {
965 if region_names.len() > 0 {
966 // It's not necessary to convert the set of region names to a
967 // vector of string and then sort them. However, it makes the
968 // choice of lifetime name deterministic and thus easier to test.
969 let mut names = Vec::new();
970 for rn in region_names.iter() {
971 let lt_name = token::get_name(*rn).get().to_string();
975 let name = token::str_to_ident(&names[0][]).name;
976 return (name_to_dummy_lifetime(name), Kept);
978 return (self.life_giver.give_lifetime(), Fresh);
981 fn extract_anon_nums_and_names(&self, same_regions: &SameRegions)
982 -> (HashSet<u32>, HashSet<ast::Name>) {
983 let mut anon_nums = HashSet::new();
984 let mut region_names = HashSet::new();
985 for br in same_regions.regions.iter() {
990 ty::BrNamed(_, name) => {
991 region_names.insert(name);
996 (anon_nums, region_names)
999 fn extract_all_region_names(&self) -> HashSet<ast::Name> {
1000 let mut all_region_names = HashSet::new();
1001 for sr in self.same_regions.iter() {
1002 for br in sr.regions.iter() {
1004 ty::BrNamed(_, name) => {
1005 all_region_names.insert(name);
1014 fn inc_cur_anon(&self, n: u32) {
1015 let anon = self.cur_anon.get();
1016 self.cur_anon.set(anon+n);
1019 fn offset_cur_anon(&self) {
1020 let mut anon = self.cur_anon.get();
1021 while self.inserted_anons.borrow().contains(&anon) {
1024 self.cur_anon.set(anon);
1027 fn inc_and_offset_cur_anon(&self, n: u32) {
1028 self.inc_cur_anon(n);
1029 self.offset_cur_anon();
1032 fn track_anon(&self, anon: u32) {
1033 self.inserted_anons.borrow_mut().insert(anon);
1036 fn rebuild_ty_params(&self,
1037 ty_params: OwnedSlice<ast::TyParam>,
1038 lifetime: ast::Lifetime,
1039 region_names: &HashSet<ast::Name>)
1040 -> OwnedSlice<ast::TyParam> {
1041 ty_params.map(|ty_param| {
1042 let bounds = self.rebuild_ty_param_bounds(ty_param.bounds.clone(),
1046 ident: ty_param.ident,
1049 default: ty_param.default.clone(),
1050 span: ty_param.span,
1055 fn rebuild_ty_param_bounds(&self,
1056 ty_param_bounds: OwnedSlice<ast::TyParamBound>,
1057 lifetime: ast::Lifetime,
1058 region_names: &HashSet<ast::Name>)
1059 -> OwnedSlice<ast::TyParamBound> {
1060 ty_param_bounds.map(|tpb| {
1062 &ast::RegionTyParamBound(lt) => {
1063 // FIXME -- it's unclear whether I'm supposed to
1064 // substitute lifetime here. I suspect we need to
1065 // be passing down a map.
1066 ast::RegionTyParamBound(lt)
1068 &ast::TraitTyParamBound(ref poly_tr, modifier) => {
1069 let tr = &poly_tr.trait_ref;
1070 let last_seg = tr.path.segments.last().unwrap();
1071 let mut insert = Vec::new();
1072 let lifetimes = last_seg.parameters.lifetimes();
1073 for (i, lt) in lifetimes.iter().enumerate() {
1074 if region_names.contains(<.name) {
1075 insert.push(i as u32);
1078 let rebuild_info = RebuildPathInfo {
1081 expected: lifetimes.len() as u32,
1082 anon_nums: &HashSet::new(),
1083 region_names: region_names
1085 let new_path = self.rebuild_path(rebuild_info, lifetime);
1086 ast::TraitTyParamBound(ast::PolyTraitRef {
1087 bound_lifetimes: poly_tr.bound_lifetimes.clone(),
1088 trait_ref: ast::TraitRef {
1098 fn rebuild_expl_self(&self,
1099 expl_self_opt: Option<ast::ExplicitSelf_>,
1100 lifetime: ast::Lifetime,
1101 anon_nums: &HashSet<u32>,
1102 region_names: &HashSet<ast::Name>)
1103 -> Option<ast::ExplicitSelf_> {
1104 match expl_self_opt {
1105 Some(ref expl_self) => match *expl_self {
1106 ast::SelfRegion(lt_opt, muta, id) => match lt_opt {
1107 Some(lt) => if region_names.contains(<.name) {
1108 return Some(ast::SelfRegion(Some(lifetime), muta, id));
1111 let anon = self.cur_anon.get();
1112 self.inc_and_offset_cur_anon(1);
1113 if anon_nums.contains(&anon) {
1114 self.track_anon(anon);
1115 return Some(ast::SelfRegion(Some(lifetime), muta, id));
1126 fn rebuild_generics(&self,
1127 generics: &ast::Generics,
1128 add: &Vec<ast::Lifetime>,
1129 keep: &HashSet<ast::Name>,
1130 remove: &HashSet<ast::Name>,
1131 ty_params: OwnedSlice<ast::TyParam>,
1132 where_clause: ast::WhereClause)
1134 let mut lifetimes = Vec::new();
1135 for lt in add.iter() {
1136 lifetimes.push(ast::LifetimeDef { lifetime: *lt,
1137 bounds: Vec::new() });
1139 for lt in generics.lifetimes.iter() {
1140 if keep.contains(<.lifetime.name) ||
1141 !remove.contains(<.lifetime.name) {
1142 lifetimes.push((*lt).clone());
1146 lifetimes: lifetimes,
1147 ty_params: ty_params,
1148 where_clause: where_clause,
1152 fn rebuild_args_ty(&self,
1153 inputs: &[ast::Arg],
1154 lifetime: ast::Lifetime,
1155 anon_nums: &HashSet<u32>,
1156 region_names: &HashSet<ast::Name>)
1158 let mut new_inputs = Vec::new();
1159 for arg in inputs.iter() {
1160 let new_ty = self.rebuild_arg_ty_or_output(&*arg.ty, lifetime,
1161 anon_nums, region_names);
1162 let possibly_new_arg = ast::Arg {
1164 pat: arg.pat.clone(),
1167 new_inputs.push(possibly_new_arg);
1172 fn rebuild_output(&self, ty: &ast::FunctionRetTy,
1173 lifetime: ast::Lifetime,
1174 anon_nums: &HashSet<u32>,
1175 region_names: &HashSet<ast::Name>) -> ast::FunctionRetTy {
1177 ast::Return(ref ret_ty) => ast::Return(
1178 self.rebuild_arg_ty_or_output(&**ret_ty, lifetime, anon_nums, region_names)
1180 ast::DefaultReturn(span) => ast::DefaultReturn(span),
1181 ast::NoReturn(span) => ast::NoReturn(span)
1185 fn rebuild_arg_ty_or_output(&self,
1187 lifetime: ast::Lifetime,
1188 anon_nums: &HashSet<u32>,
1189 region_names: &HashSet<ast::Name>)
1191 let mut new_ty = P(ty.clone());
1192 let mut ty_queue = vec!(ty);
1193 while !ty_queue.is_empty() {
1194 let cur_ty = ty_queue.remove(0);
1196 ast::TyRptr(lt_opt, ref mut_ty) => {
1197 let rebuild = match lt_opt {
1198 Some(lt) => region_names.contains(<.name),
1200 let anon = self.cur_anon.get();
1201 let rebuild = anon_nums.contains(&anon);
1203 self.track_anon(anon);
1205 self.inc_and_offset_cur_anon(1);
1212 node: ast::TyRptr(Some(lifetime), mut_ty.clone()),
1215 new_ty = self.rebuild_ty(new_ty, P(to));
1217 ty_queue.push(&*mut_ty.ty);
1219 ast::TyPath(ref path, id) => {
1220 let a_def = match self.tcx.def_map.borrow().get(&id) {
1226 pprust::path_to_string(path))[])
1231 def::DefTy(did, _) | def::DefStruct(did) => {
1232 let generics = ty::lookup_item_type(self.tcx, did).generics;
1235 generics.regions.len(subst::TypeSpace) as u32;
1237 path.segments.last().unwrap().parameters.lifetimes();
1238 let mut insert = Vec::new();
1239 if lifetimes.len() == 0 {
1240 let anon = self.cur_anon.get();
1241 for (i, a) in range(anon,
1242 anon+expected).enumerate() {
1243 if anon_nums.contains(&a) {
1244 insert.push(i as u32);
1248 self.inc_and_offset_cur_anon(expected);
1250 for (i, lt) in lifetimes.iter().enumerate() {
1251 if region_names.contains(<.name) {
1252 insert.push(i as u32);
1256 let rebuild_info = RebuildPathInfo {
1260 anon_nums: anon_nums,
1261 region_names: region_names
1263 let new_path = self.rebuild_path(rebuild_info, lifetime);
1266 node: ast::TyPath(new_path, id),
1269 new_ty = self.rebuild_ty(new_ty, P(to));
1276 ast::TyPtr(ref mut_ty) => {
1277 ty_queue.push(&*mut_ty.ty);
1279 ast::TyVec(ref ty) |
1280 ast::TyFixedLengthVec(ref ty, _) => {
1281 ty_queue.push(&**ty);
1283 ast::TyTup(ref tys) => ty_queue.extend(tys.iter().map(|ty| &**ty)),
1290 fn rebuild_ty(&self,
1295 fn build_to(from: P<ast::Ty>,
1296 to: &mut Option<P<ast::Ty>>)
1298 if Some(from.id) == to.as_ref().map(|ty| ty.id) {
1299 return to.take().expect("`to` type found more than once during rebuild");
1301 from.map(|ast::Ty {id, node, span}| {
1302 let new_node = match node {
1303 ast::TyRptr(lifetime, mut_ty) => {
1304 ast::TyRptr(lifetime, ast::MutTy {
1305 mutbl: mut_ty.mutbl,
1306 ty: build_to(mut_ty.ty, to),
1309 ast::TyPtr(mut_ty) => {
1310 ast::TyPtr(ast::MutTy {
1311 mutbl: mut_ty.mutbl,
1312 ty: build_to(mut_ty.ty, to),
1315 ast::TyVec(ty) => ast::TyVec(build_to(ty, to)),
1316 ast::TyFixedLengthVec(ty, e) => {
1317 ast::TyFixedLengthVec(build_to(ty, to), e)
1319 ast::TyTup(tys) => {
1320 ast::TyTup(tys.into_iter().map(|ty| build_to(ty, to)).collect())
1322 ast::TyParen(typ) => ast::TyParen(build_to(typ, to)),
1325 ast::Ty { id: id, node: new_node, span: span }
1329 build_to(from, &mut Some(to))
1332 fn rebuild_path(&self,
1333 rebuild_info: RebuildPathInfo,
1334 lifetime: ast::Lifetime)
1337 let RebuildPathInfo {
1345 let last_seg = path.segments.last().unwrap();
1346 let new_parameters = match last_seg.parameters {
1347 ast::ParenthesizedParameters(..) => {
1348 last_seg.parameters.clone()
1351 ast::AngleBracketedParameters(ref data) => {
1352 let mut new_lts = Vec::new();
1353 if data.lifetimes.len() == 0 {
1354 // traverse once to see if there's a need to insert lifetime
1355 let need_insert = range(0, expected).any(|i| {
1356 indexes.contains(&i)
1359 for i in range(0, expected) {
1360 if indexes.contains(&i) {
1361 new_lts.push(lifetime);
1363 new_lts.push(self.life_giver.give_lifetime());
1368 for (i, lt) in data.lifetimes.iter().enumerate() {
1369 if indexes.contains(&(i as u32)) {
1370 new_lts.push(lifetime);
1376 let new_types = data.types.map(|t| {
1377 self.rebuild_arg_ty_or_output(&**t, lifetime, anon_nums, region_names)
1379 let new_bindings = data.bindings.map(|b| {
1380 P(ast::TypeBinding {
1383 ty: self.rebuild_arg_ty_or_output(&*b.ty,
1390 ast::AngleBracketedParameters(ast::AngleBracketedParameterData {
1393 bindings: new_bindings,
1397 let new_seg = ast::PathSegment {
1398 identifier: last_seg.identifier,
1399 parameters: new_parameters
1401 let mut new_segs = Vec::new();
1402 new_segs.push_all(path.segments.init());
1403 new_segs.push(new_seg);
1406 global: path.global,
1412 impl<'a, 'tcx> ErrorReportingHelpers<'tcx> for InferCtxt<'a, 'tcx> {
1413 fn give_expl_lifetime_param(&self,
1415 unsafety: ast::Unsafety,
1417 opt_explicit_self: Option<&ast::ExplicitSelf_>,
1418 generics: &ast::Generics,
1419 span: codemap::Span) {
1420 let suggested_fn = pprust::fun_to_string(decl, unsafety, ident,
1421 opt_explicit_self, generics);
1422 let msg = format!("consider using an explicit lifetime \
1423 parameter as shown: {}", suggested_fn);
1424 self.tcx.sess.span_help(span, &msg[]);
1427 fn report_inference_failure(&self,
1428 var_origin: RegionVariableOrigin) {
1429 let var_description = match var_origin {
1430 infer::MiscVariable(_) => "".to_string(),
1431 infer::PatternRegion(_) => " for pattern".to_string(),
1432 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1433 infer::AddrOfSlice(_) => " for slice expression".to_string(),
1434 infer::Autoref(_) => " for autoref".to_string(),
1435 infer::Coercion(_) => " for automatic coercion".to_string(),
1436 infer::LateBoundRegion(_, br, infer::FnCall) => {
1437 format!(" for {}in function call",
1438 bound_region_to_string(self.tcx, "lifetime parameter ", true, br))
1440 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1441 format!(" for {}in generic type",
1442 bound_region_to_string(self.tcx, "lifetime parameter ", true, br))
1444 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1445 format!(" for {}in trait containing associated type `{}`",
1446 bound_region_to_string(self.tcx, "lifetime parameter ", true, br),
1447 token::get_name(type_name))
1449 infer::EarlyBoundRegion(_, name) => {
1450 format!(" for lifetime parameter `{}`",
1451 token::get_name(name).get())
1453 infer::BoundRegionInCoherence(name) => {
1454 format!(" for lifetime parameter `{}` in coherence check",
1455 token::get_name(name).get())
1457 infer::UpvarRegion(ref upvar_id, _) => {
1458 format!(" for capture of `{}` by closure",
1459 ty::local_var_name_str(self.tcx, upvar_id.var_id).get().to_string())
1463 self.tcx.sess.span_err(
1465 &format!("cannot infer an appropriate lifetime{} \
1466 due to conflicting requirements",
1467 var_description)[]);
1470 fn note_region_origin(&self, origin: &SubregionOrigin<'tcx>) {
1472 infer::Subtype(ref trace) => {
1473 let desc = match trace.origin {
1475 format!("types are compatible")
1477 infer::MethodCompatCheck(_) => {
1478 format!("method type is compatible with trait")
1480 infer::ExprAssignable(_) => {
1481 format!("expression is assignable")
1483 infer::RelateTraitRefs(_) => {
1484 format!("traits are compatible")
1486 infer::RelateSelfType(_) => {
1487 format!("self type matches impl self type")
1489 infer::RelateOutputImplTypes(_) => {
1490 format!("trait type parameters matches those \
1491 specified on the impl")
1493 infer::MatchExpressionArm(_, _) => {
1494 format!("match arms have compatible types")
1496 infer::IfExpression(_) => {
1497 format!("if and else have compatible types")
1499 infer::IfExpressionWithNoElse(_) => {
1500 format!("if may be missing an else clause")
1502 infer::RangeExpression(_) => {
1503 format!("start and end of range have compatible types")
1505 infer::EquatePredicate(_) => {
1506 format!("equality where clause is satisfied")
1510 match self.values_str(&trace.values) {
1511 Some(values_str) => {
1512 self.tcx.sess.span_note(
1513 trace.origin.span(),
1514 &format!("...so that {} ({})",
1515 desc, values_str)[]);
1518 // Really should avoid printing this error at
1519 // all, since it is derived, but that would
1520 // require more refactoring than I feel like
1521 // doing right now. - nmatsakis
1522 self.tcx.sess.span_note(
1523 trace.origin.span(),
1524 &format!("...so that {}", desc)[]);
1528 infer::Reborrow(span) => {
1529 self.tcx.sess.span_note(
1531 "...so that reference does not outlive \
1534 infer::ReborrowUpvar(span, ref upvar_id) => {
1535 self.tcx.sess.span_note(
1538 "...so that closure can access `{}`",
1539 ty::local_var_name_str(self.tcx, upvar_id.var_id)
1543 infer::InfStackClosure(span) => {
1544 self.tcx.sess.span_note(
1546 "...so that closure does not outlive its stack frame");
1548 infer::InvokeClosure(span) => {
1549 self.tcx.sess.span_note(
1551 "...so that closure is not invoked outside its lifetime");
1553 infer::DerefPointer(span) => {
1554 self.tcx.sess.span_note(
1556 "...so that pointer is not dereferenced \
1557 outside its lifetime");
1559 infer::FreeVariable(span, id) => {
1560 self.tcx.sess.span_note(
1562 &format!("...so that captured variable `{}` \
1563 does not outlive the enclosing closure",
1564 ty::local_var_name_str(
1566 id).get().to_string())[]);
1568 infer::IndexSlice(span) => {
1569 self.tcx.sess.span_note(
1571 "...so that slice is not indexed outside the lifetime");
1573 infer::RelateObjectBound(span) => {
1574 self.tcx.sess.span_note(
1576 "...so that it can be closed over into an object");
1578 infer::CallRcvr(span) => {
1579 self.tcx.sess.span_note(
1581 "...so that method receiver is valid for the method call");
1583 infer::CallArg(span) => {
1584 self.tcx.sess.span_note(
1586 "...so that argument is valid for the call");
1588 infer::CallReturn(span) => {
1589 self.tcx.sess.span_note(
1591 "...so that return value is valid for the call");
1593 infer::AddrOf(span) => {
1594 self.tcx.sess.span_note(
1596 "...so that reference is valid \
1597 at the time of borrow");
1599 infer::AutoBorrow(span) => {
1600 self.tcx.sess.span_note(
1602 "...so that auto-reference is valid \
1603 at the time of borrow");
1605 infer::ExprTypeIsNotInScope(t, span) => {
1606 self.tcx.sess.span_note(
1608 &format!("...so type `{}` of expression is valid during the \
1610 self.ty_to_string(t))[]);
1612 infer::BindingTypeIsNotValidAtDecl(span) => {
1613 self.tcx.sess.span_note(
1615 "...so that variable is valid at time of its declaration");
1617 infer::ReferenceOutlivesReferent(ty, span) => {
1618 self.tcx.sess.span_note(
1620 &format!("...so that the reference type `{}` \
1621 does not outlive the data it points at",
1622 self.ty_to_string(ty))[]);
1624 infer::RelateParamBound(span, t) => {
1625 self.tcx.sess.span_note(
1627 &format!("...so that the type `{}` \
1628 will meet the declared lifetime bounds",
1629 self.ty_to_string(t))[]);
1631 infer::RelateDefaultParamBound(span, t) => {
1632 self.tcx.sess.span_note(
1634 &format!("...so that type parameter \
1635 instantiated with `{}`, \
1636 will meet its declared lifetime bounds",
1637 self.ty_to_string(t))[]);
1639 infer::RelateRegionParamBound(span) => {
1640 self.tcx.sess.span_note(
1642 &format!("...so that the declared lifetime parameter bounds \
1649 pub trait Resolvable<'tcx> {
1650 fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Self;
1651 fn contains_error(&self) -> bool;
1654 impl<'tcx> Resolvable<'tcx> for Ty<'tcx> {
1655 fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>) -> Ty<'tcx> {
1656 infcx.resolve_type_vars_if_possible(self)
1658 fn contains_error(&self) -> bool {
1659 ty::type_is_error(*self)
1663 impl<'tcx> Resolvable<'tcx> for Rc<ty::TraitRef<'tcx>> {
1664 fn resolve<'a>(&self, infcx: &InferCtxt<'a, 'tcx>)
1665 -> Rc<ty::TraitRef<'tcx>> {
1666 Rc::new(infcx.resolve_type_vars_if_possible(&**self))
1668 fn contains_error(&self) -> bool {
1669 ty::trait_ref_contains_error(&**self)
1673 impl<'tcx> Resolvable<'tcx> for ty::PolyTraitRef<'tcx> {
1674 fn resolve<'a>(&self,
1675 infcx: &InferCtxt<'a, 'tcx>)
1676 -> ty::PolyTraitRef<'tcx>
1678 infcx.resolve_type_vars_if_possible(self)
1681 fn contains_error(&self) -> bool {
1682 ty::trait_ref_contains_error(&*self.0)
1686 fn lifetimes_in_scope(tcx: &ty::ctxt,
1687 scope_id: ast::NodeId)
1688 -> Vec<ast::LifetimeDef> {
1689 let mut taken = Vec::new();
1690 let parent = tcx.map.get_parent(scope_id);
1691 let method_id_opt = match tcx.map.find(parent) {
1692 Some(node) => match node {
1693 ast_map::NodeItem(item) => match item.node {
1694 ast::ItemFn(_, _, _, ref gen, _) => {
1695 taken.push_all(&gen.lifetimes[]);
1700 ast_map::NodeImplItem(ii) => {
1702 ast::MethodImplItem(ref m) => {
1703 taken.push_all(&m.pe_generics().lifetimes[]);
1706 ast::TypeImplItem(_) => None,
1713 if method_id_opt.is_some() {
1714 let method_id = method_id_opt.unwrap();
1715 let parent = tcx.map.get_parent(method_id);
1716 match tcx.map.find(parent) {
1717 Some(node) => match node {
1718 ast_map::NodeItem(item) => match item.node {
1719 ast::ItemImpl(_, _, ref gen, _, _, _) => {
1720 taken.push_all(gen.lifetimes.as_slice());
1732 // LifeGiver is responsible for generating fresh lifetime names
1734 taken: HashSet<String>,
1735 counter: Cell<uint>,
1736 generated: RefCell<Vec<ast::Lifetime>>,
1740 fn with_taken(taken: &[ast::LifetimeDef]) -> LifeGiver {
1741 let mut taken_ = HashSet::new();
1742 for lt in taken.iter() {
1743 let lt_name = token::get_name(lt.lifetime.name).get().to_string();
1744 taken_.insert(lt_name);
1748 counter: Cell::new(0),
1749 generated: RefCell::new(Vec::new()),
1753 fn inc_counter(&self) {
1754 let c = self.counter.get();
1755 self.counter.set(c+1);
1758 fn give_lifetime(&self) -> ast::Lifetime {
1761 let mut s = String::from_str("'");
1762 s.push_str(&num_to_string(self.counter.get())[]);
1763 if !self.taken.contains(&s) {
1764 lifetime = name_to_dummy_lifetime(
1765 token::str_to_ident(&s[]).name);
1766 self.generated.borrow_mut().push(lifetime);
1774 // 0 .. 25 generates a .. z, 26 .. 51 generates aa .. zz, and so on
1775 fn num_to_string(counter: uint) -> String {
1776 let mut s = String::new();
1777 let (n, r) = (counter/26 + 1, counter % 26);
1778 let letter: char = from_u32((r+97) as u32).unwrap();
1779 for _ in range(0, n) {
1786 fn get_generated_lifetimes(&self) -> Vec<ast::Lifetime> {
1787 self.generated.borrow().clone()