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.
59 use super::{InferCtxt, TypeTrace, SubregionOrigin, RegionVariableOrigin, ValuePairs};
60 use super::region_inference::{RegionResolutionError, ConcreteFailure, SubSupConflict,
61 GenericBoundFailure, GenericKind};
65 use hir::map as hir_map;
66 use hir::def_id::DefId;
68 use traits::{ObligationCause, ObligationCauseCode};
69 use ty::{self, TyCtxt, TypeFoldable};
70 use ty::{Region, Issue32330};
71 use ty::error::TypeError;
72 use syntax_pos::{Pos, Span};
73 use errors::DiagnosticBuilder;
77 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
78 pub fn note_and_explain_region(self,
79 err: &mut DiagnosticBuilder,
81 region: &'tcx ty::Region,
83 fn item_scope_tag(item: &hir::Item) -> &'static str {
85 hir::ItemImpl(..) => "impl",
86 hir::ItemStruct(..) => "struct",
87 hir::ItemUnion(..) => "union",
88 hir::ItemEnum(..) => "enum",
89 hir::ItemTrait(..) => "trait",
90 hir::ItemFn(..) => "function body",
95 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
97 hir::TraitItemKind::Method(..) => "method body",
98 hir::TraitItemKind::Const(..) |
99 hir::TraitItemKind::Type(..) => "associated item"
103 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
105 hir::ImplItemKind::Method(..) => "method body",
106 hir::ImplItemKind::Const(..) |
107 hir::ImplItemKind::Type(_) => "associated item"
111 fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
112 heading: &str, span: Span)
113 -> (String, Option<Span>) {
114 let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
115 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
119 let (description, span) = match *region {
120 ty::ReScope(scope) => {
122 let unknown_scope = || {
123 format!("{}unknown scope: {:?}{}. Please report a bug.",
124 prefix, scope, suffix)
126 let span = match scope.span(&self.region_maps, &self.hir) {
129 err.note(&unknown_scope());
133 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
134 Some(hir_map::NodeBlock(_)) => "block",
135 Some(hir_map::NodeExpr(expr)) => match expr.node {
136 hir::ExprCall(..) => "call",
137 hir::ExprMethodCall(..) => "method call",
138 hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
139 hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
140 hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
141 hir::ExprMatch(..) => "match",
144 Some(hir_map::NodeStmt(_)) => "statement",
145 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
146 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
147 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
149 err.span_note(span, &unknown_scope());
153 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
154 region::CodeExtentData::Misc(_) => tag,
155 region::CodeExtentData::CallSiteScope { .. } => {
156 "scope of call-site for function"
158 region::CodeExtentData::ParameterScope { .. } => {
159 "scope of function body"
161 region::CodeExtentData::DestructionScope(_) => {
162 new_string = format!("destruction scope surrounding {}", tag);
165 region::CodeExtentData::Remainder(r) => {
166 new_string = format!("block suffix following statement {}",
167 r.first_statement_index);
171 explain_span(self, scope_decorated_tag, span)
174 ty::ReFree(ref fr) => {
175 let prefix = match fr.bound_region {
177 format!("the anonymous lifetime #{} defined on", idx + 1)
179 ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
181 format!("the lifetime {} as defined on",
186 let node = fr.scope.node_id(&self.region_maps);
188 let tag = match self.hir.find(node) {
189 Some(hir_map::NodeBlock(_)) |
190 Some(hir_map::NodeExpr(_)) => "body",
191 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
192 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
193 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
195 // this really should not happen, but it does:
198 unknown = format!("unexpected node ({}) for scope {:?}. \
199 Please report a bug.",
200 self.hir.node_to_string(node), fr.scope);
204 unknown = format!("unknown node for scope {:?}. \
205 Please report a bug.", fr.scope);
209 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
210 (format!("{} {}", prefix, msg), opt_span)
213 ty::ReStatic => ("the static lifetime".to_owned(), None),
215 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
217 ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
219 // FIXME(#13998) ReSkolemized should probably print like
220 // ReFree rather than dumping Debug output on the user.
222 // We shouldn't really be having unification failures with ReVar
223 // and ReLateBound though.
224 ty::ReSkolemized(..) |
226 ty::ReLateBound(..) |
228 (format!("lifetime {:?}", region), None)
231 let message = format!("{}{}{}", prefix, description, suffix);
232 if let Some(span) = span {
233 err.span_note(span, &message);
240 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
241 pub fn report_region_errors(&self,
242 errors: &Vec<RegionResolutionError<'tcx>>) {
243 debug!("report_region_errors(): {} errors to start", errors.len());
245 // try to pre-process the errors, which will group some of them
246 // together into a `ProcessedErrors` group:
247 let errors = self.process_errors(errors);
249 debug!("report_region_errors: {} errors after preprocessing", errors.len());
251 for error in errors {
252 debug!("report_region_errors: error = {:?}", error);
253 match error.clone() {
254 ConcreteFailure(origin, sub, sup) => {
255 self.report_concrete_failure(origin, sub, sup).emit();
258 GenericBoundFailure(kind, param_ty, sub) => {
259 self.report_generic_bound_failure(kind, param_ty, sub);
262 SubSupConflict(var_origin,
264 sup_origin, sup_r) => {
265 self.report_sub_sup_conflict(var_origin,
273 // This method goes through all the errors and try to group certain types
274 // of error together, for the purpose of suggesting explicit lifetime
275 // parameters to the user. This is done so that we can have a more
276 // complete view of what lifetimes should be the same.
277 // If the return value is an empty vector, it means that processing
278 // failed (so the return value of this method should not be used).
280 // The method also attempts to weed out messages that seem like
281 // duplicates that will be unhelpful to the end-user. But
282 // obviously it never weeds out ALL errors.
283 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
284 -> Vec<RegionResolutionError<'tcx>> {
285 debug!("process_errors()");
287 // We want to avoid reporting generic-bound failures if we can
288 // avoid it: these have a very high rate of being unhelpful in
289 // practice. This is because they are basically secondary
290 // checks that test the state of the region graph after the
291 // rest of inference is done, and the other kinds of errors
292 // indicate that the region constraint graph is internally
293 // inconsistent, so these test results are likely to be
296 // Therefore, we filter them out of the list unless they are
297 // the only thing in the list.
299 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
300 ConcreteFailure(..) => false,
301 SubSupConflict(..) => false,
302 GenericBoundFailure(..) => true,
305 if errors.iter().all(|e| is_bound_failure(e)) {
308 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
312 /// Adds a note if the types come from similarly named crates
313 fn check_and_note_conflicting_crates(&self,
314 err: &mut DiagnosticBuilder,
315 terr: &TypeError<'tcx>,
317 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
318 // Only external crates, if either is from a local
319 // module we could have false positives
320 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
321 let exp_path = self.tcx.item_path_str(did1);
322 let found_path = self.tcx.item_path_str(did2);
323 // We compare strings because DefPath can be different
324 // for imported and non-imported crates
325 if exp_path == found_path {
326 let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
327 err.span_note(sp, &format!("Perhaps two different versions \
328 of crate `{}` are being used?",
334 TypeError::Sorts(ref exp_found) => {
335 // if they are both "path types", there's a chance of ambiguity
336 // due to different versions of the same crate
337 match (&exp_found.expected.sty, &exp_found.found.sty) {
338 (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
339 report_path_match(err, exp_adt.did, found_adt.did);
344 TypeError::Traits(ref exp_found) => {
345 report_path_match(err, exp_found.expected, exp_found.found);
347 _ => () // FIXME(#22750) handle traits and stuff
351 fn note_error_origin(&self,
352 err: &mut DiagnosticBuilder<'tcx>,
353 cause: &ObligationCause<'tcx>)
356 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
357 hir::MatchSource::IfLetDesugar {..} => {
358 err.span_note(arm_span, "`if let` arm with an incompatible type");
361 err.span_note(arm_span, "match arm with an incompatible type");
368 pub fn note_type_err(&self,
369 diag: &mut DiagnosticBuilder<'tcx>,
370 cause: &ObligationCause<'tcx>,
371 secondary_span: Option<(Span, String)>,
372 values: Option<ValuePairs<'tcx>>,
373 terr: &TypeError<'tcx>)
375 let (expected_found, is_simple_error) = match values {
376 None => (None, false),
378 let is_simple_error = match values {
379 ValuePairs::Types(exp_found) => {
380 exp_found.expected.is_primitive() && exp_found.found.is_primitive()
384 let vals = match self.values_str(&values) {
385 Some((expected, found)) => Some((expected, found)),
387 // Derived error. Cancel the emitter.
388 self.tcx.sess.diagnostic().cancel(diag);
392 (vals, is_simple_error)
396 let span = cause.span;
398 if let Some((expected, found)) = expected_found {
399 match (terr, is_simple_error, expected == found) {
400 (&TypeError::Sorts(ref values), false, true) => {
401 diag.note_expected_found_extra(
402 &"type", &expected, &found,
403 &format!(" ({})", values.expected.sort_string(self.tcx)),
404 &format!(" ({})", values.found.sort_string(self.tcx)));
407 diag.note_expected_found(&"type", &expected, &found);
413 diag.span_label(span, &terr);
414 if let Some((sp, msg)) = secondary_span {
415 diag.span_label(sp, &msg);
418 self.note_error_origin(diag, &cause);
419 self.check_and_note_conflicting_crates(diag, terr, span);
420 self.tcx.note_and_explain_type_err(diag, terr, span);
423 pub fn note_issue_32330(&self,
424 diag: &mut DiagnosticBuilder<'tcx>,
425 terr: &TypeError<'tcx>)
427 debug!("note_issue_32330: terr={:?}", terr);
429 TypeError::RegionsInsufficientlyPolymorphic(_, _, Some(box Issue32330 {
430 fn_def_id, region_name
432 TypeError::RegionsOverlyPolymorphic(_, _, Some(box Issue32330 {
433 fn_def_id, region_name
436 &format!("lifetime parameter `{0}` declared on fn `{1}` \
437 appears only in the return type, \
438 but here is required to be higher-ranked, \
439 which means that `{0}` must appear in both \
440 argument and return types",
442 self.tcx.item_path_str(fn_def_id)));
444 &format!("this error is the result of a recent bug fix; \
445 for more information, see issue #33685 \
446 <https://github.com/rust-lang/rust/issues/33685>"));
452 pub fn report_and_explain_type_error(&self,
453 trace: TypeTrace<'tcx>,
454 terr: &TypeError<'tcx>)
455 -> DiagnosticBuilder<'tcx>
457 let span = trace.cause.span;
458 let failure_str = trace.cause.as_failure_str();
459 let mut diag = match trace.cause.code {
460 ObligationCauseCode::IfExpressionWithNoElse => {
461 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
463 ObligationCauseCode::MainFunctionType => {
464 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
467 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
470 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
471 self.note_issue_32330(&mut diag, terr);
475 /// Returns a string of the form "expected `{}`, found `{}`".
476 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
478 infer::Types(ref exp_found) => self.expected_found_str(exp_found),
479 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
480 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
484 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
486 exp_found: &ty::error::ExpectedFound<T>)
487 -> Option<(String, String)>
489 let exp_found = self.resolve_type_vars_if_possible(exp_found);
490 if exp_found.references_error() {
494 Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
497 fn report_generic_bound_failure(&self,
498 origin: SubregionOrigin<'tcx>,
499 bound_kind: GenericKind<'tcx>,
502 // FIXME: it would be better to report the first error message
503 // with the span of the parameter itself, rather than the span
504 // where the error was detected. But that span is not readily
507 let labeled_user_string = match bound_kind {
508 GenericKind::Param(ref p) =>
509 format!("the parameter type `{}`", p),
510 GenericKind::Projection(ref p) =>
511 format!("the associated type `{}`", p),
514 if let SubregionOrigin::CompareImplMethodObligation {
515 span, item_name, impl_item_def_id, trait_item_def_id, lint_id
517 self.report_extra_impl_obligation(span,
521 &format!("`{}: {}`", bound_kind, sub),
527 let mut err = match *sub {
528 ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
529 // Does the required lifetime have a nice name we can print?
530 let mut err = struct_span_err!(self.tcx.sess,
533 "{} may not live long enough",
534 labeled_user_string);
535 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
542 // Does the required lifetime have a nice name we can print?
543 let mut err = struct_span_err!(self.tcx.sess,
546 "{} may not live long enough",
547 labeled_user_string);
548 err.help(&format!("consider adding an explicit lifetime \
549 bound `{}: 'static`...",
555 // If not, be less specific.
556 let mut err = struct_span_err!(self.tcx.sess,
559 "{} may not live long enough",
560 labeled_user_string);
561 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
563 self.tcx.note_and_explain_region(
565 &format!("{} must be valid for ", labeled_user_string),
572 self.note_region_origin(&mut err, &origin);
576 fn report_sub_sup_conflict(&self,
577 var_origin: RegionVariableOrigin,
578 sub_origin: SubregionOrigin<'tcx>,
579 sub_region: &'tcx Region,
580 sup_origin: SubregionOrigin<'tcx>,
581 sup_region: &'tcx Region) {
582 let mut err = self.report_inference_failure(var_origin);
584 self.tcx.note_and_explain_region(&mut err,
585 "first, the lifetime cannot outlive ",
589 self.note_region_origin(&mut err, &sup_origin);
591 self.tcx.note_and_explain_region(&mut err,
592 "but, the lifetime must be valid for ",
596 self.note_region_origin(&mut err, &sub_origin);
601 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
602 fn report_inference_failure(&self,
603 var_origin: RegionVariableOrigin)
604 -> DiagnosticBuilder<'tcx> {
605 let br_string = |br: ty::BoundRegion| {
606 let mut s = br.to_string();
612 let var_description = match var_origin {
613 infer::MiscVariable(_) => "".to_string(),
614 infer::PatternRegion(_) => " for pattern".to_string(),
615 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
616 infer::Autoref(_) => " for autoref".to_string(),
617 infer::Coercion(_) => " for automatic coercion".to_string(),
618 infer::LateBoundRegion(_, br, infer::FnCall) => {
619 format!(" for lifetime parameter {}in function call",
622 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
623 format!(" for lifetime parameter {}in generic type", br_string(br))
625 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
626 format!(" for lifetime parameter {}in trait containing associated type `{}`",
627 br_string(br), type_name)
629 infer::EarlyBoundRegion(_, name, _) => {
630 format!(" for lifetime parameter `{}`",
633 infer::BoundRegionInCoherence(name) => {
634 format!(" for lifetime parameter `{}` in coherence check",
637 infer::UpvarRegion(ref upvar_id, _) => {
638 format!(" for capture of `{}` by closure",
639 self.tcx.local_var_name_str(upvar_id.var_id).to_string())
643 struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
644 "cannot infer an appropriate lifetime{} \
645 due to conflicting requirements",
650 impl<'tcx> ObligationCause<'tcx> {
651 fn as_failure_str(&self) -> &'static str {
652 use traits::ObligationCauseCode::*;
654 CompareImplMethodObligation { .. } => "method not compatible with trait",
655 MatchExpressionArm { source, .. } => match source {
656 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
657 _ => "match arms have incompatible types",
659 IfExpression => "if and else have incompatible types",
660 IfExpressionWithNoElse => "if may be missing an else clause",
661 EquatePredicate => "equality predicate not satisfied",
662 MainFunctionType => "main function has wrong type",
663 StartFunctionType => "start function has wrong type",
664 IntrinsicType => "intrinsic has wrong type",
665 MethodReceiver => "mismatched method receiver",
666 _ => "mismatched types",
670 fn as_requirement_str(&self) -> &'static str {
671 use traits::ObligationCauseCode::*;
673 CompareImplMethodObligation { .. } => "method type is compatible with trait",
674 ExprAssignable => "expression is assignable",
675 MatchExpressionArm { source, .. } => match source {
676 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
677 _ => "match arms have compatible types",
679 IfExpression => "if and else have compatible types",
680 IfExpressionWithNoElse => "if missing an else returns ()",
681 EquatePredicate => "equality where clause is satisfied",
682 MainFunctionType => "`main` function has the correct type",
683 StartFunctionType => "`start` function has the correct type",
684 IntrinsicType => "intrinsic has the correct type",
685 MethodReceiver => "method receiver has the correct type",
686 _ => "types are compatible",