mod.rs 41.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

S
Steve Klabnik 已提交
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
//! Error Reporting Code for the inference engine
//!
//! Because of the way inference, and in particular region inference,
//! works, it often happens that errors are not detected until far after
//! the relevant line of code has been type-checked. Therefore, there is
//! an elaborate system to track why a particular constraint in the
//! inference graph arose so that we can explain to the user what gave
//! rise to a particular error.
//!
//! The basis of the system are the "origin" types. An "origin" is the
//! reason that a constraint or inference variable arose. There are
//! different "origin" enums for different kinds of constraints/variables
//! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
//! a span, but also more information so that we can generate a meaningful
//! error message.
//!
//! Having a catalogue of all the different reasons an error can arise is
//! also useful for other reasons, like cross-referencing FAQs etc, though
//! we are not really taking advantage of this yet.
//!
//! # Region Inference
//!
//! Region inference is particularly tricky because it always succeeds "in
//! the moment" and simply registers a constraint. Then, at the end, we
//! can compute the full graph and report errors, so we need to be able to
//! store and later report what gave rise to the conflicting constraints.
//!
//! # Subtype Trace
//!
J
Joseph Crail 已提交
40
//! Determining whether `T1 <: T2` often involves a number of subtypes and
S
Steve Klabnik 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
//! subconstraints along the way. A "TypeTrace" is an extended version
//! of an origin that traces the types and other values that were being
//! compared. It is not necessarily comprehensive (in fact, at the time of
//! this writing it only tracks the root values being compared) but I'd
//! like to extend it to include significant "waypoints". For example, if
//! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
//! <: T4` fails, I'd like the trace to include enough information to say
//! "in the 2nd element of the tuple". Similarly, failures when comparing
//! arguments or return types in fn types should be able to cite the
//! specific position, etc.
//!
//! # Reality vs plan
//!
//! Of course, there is still a LOT of code in typeck that has yet to be
//! ported to this system, and which relies on string concatenation at the
//! time of error detection.

58 59 60 61
use infer;
use super::{InferCtxt, TypeTrace, SubregionOrigin, RegionVariableOrigin, ValuePairs};
use super::region_inference::{RegionResolutionError, ConcreteFailure, SubSupConflict,
                              GenericBoundFailure, GenericKind};
62

63
use std::fmt;
64
use hir;
65
use hir::map as hir_map;
66
use hir::def_id::DefId;
67
use middle::region;
68
use traits::{ObligationCause, ObligationCauseCode};
69
use ty::{self, Region, TyCtxt, TypeFoldable};
70
use ty::error::TypeError;
71
use syntax::ast::DUMMY_NODE_ID;
72
use syntax_pos::{Pos, Span};
73
use errors::{DiagnosticBuilder, DiagnosticStyledString};
G
Guillaume Gomez 已提交
74

75
mod note;
76

77
mod need_type_info;
78
mod util;
79
mod named_anon_conflict;
80
mod anon_anon_conflict;
81

82
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
83
    pub fn note_and_explain_region(self,
N
Nick Cameron 已提交
84
                                   err: &mut DiagnosticBuilder,
85
                                   prefix: &str,
N
Niko Matsakis 已提交
86
                                   region: ty::Region<'tcx>,
87
                                   suffix: &str) {
88
        fn item_scope_tag(item: &hir::Item) -> &'static str {
89
            match item.node {
90 91
                hir::ItemImpl(..) => "impl",
                hir::ItemStruct(..) => "struct",
92
                hir::ItemUnion(..) => "union",
93 94 95
                hir::ItemEnum(..) => "enum",
                hir::ItemTrait(..) => "trait",
                hir::ItemFn(..) => "function body",
96 97
                _ => "item"
            }
98 99
        }

100 101
        fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
            match item.node {
102 103 104
                hir::TraitItemKind::Method(..) => "method body",
                hir::TraitItemKind::Const(..) |
                hir::TraitItemKind::Type(..) => "associated item"
105 106 107 108 109 110 111 112 113 114 115
            }
        }

        fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
            match item.node {
                hir::ImplItemKind::Method(..) => "method body",
                hir::ImplItemKind::Const(..) |
                hir::ImplItemKind::Type(_) => "associated item"
            }
        }

116 117 118
        fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
                                        heading: &str, span: Span)
                                        -> (String, Option<Span>) {
119
            let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
120
            (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
121
             Some(span))
122 123
        }

124
        let (description, span) = match *region {
125 126 127 128 129 130
            ty::ReScope(scope) => {
                let new_string;
                let unknown_scope = || {
                    format!("{}unknown scope: {:?}{}.  Please report a bug.",
                            prefix, scope, suffix)
                };
N
Niko Matsakis 已提交
131
                let span = match scope.span(&self.hir) {
132
                    Some(s) => s,
N
Nick Cameron 已提交
133 134 135 136
                    None => {
                        err.note(&unknown_scope());
                        return;
                    }
137
                };
N
Niko Matsakis 已提交
138
                let tag = match self.hir.find(scope.node_id()) {
139 140
                    Some(hir_map::NodeBlock(_)) => "block",
                    Some(hir_map::NodeExpr(expr)) => match expr.node {
141 142
                        hir::ExprCall(..) => "call",
                        hir::ExprMethodCall(..) => "method call",
V
Vadim Petrochenkov 已提交
143 144 145
                        hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
                        hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) =>  "while let",
                        hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) =>  "for",
146
                        hir::ExprMatch(..) => "match",
147 148
                        _ => "expression",
                    },
149 150 151 152
                    Some(hir_map::NodeStmt(_)) => "statement",
                    Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
                    Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
                    Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
153
                    Some(_) | None => {
N
Nick Cameron 已提交
154 155
                        err.span_note(span, &unknown_scope());
                        return;
156 157
                    }
                };
158 159 160
                let scope_decorated_tag = match scope {
                    region::CodeExtent::Misc(_) => tag,
                    region::CodeExtent::CallSiteScope(_) => {
161 162
                        "scope of call-site for function"
                    }
163
                    region::CodeExtent::ParameterScope(_) => {
164
                        "scope of function body"
165
                    }
166
                    region::CodeExtent::DestructionScope(_) => {
167 168 169
                        new_string = format!("destruction scope surrounding {}", tag);
                        &new_string[..]
                    }
170
                    region::CodeExtent::Remainder(r) => {
171 172 173 174 175 176 177
                        new_string = format!("block suffix following statement {}",
                                             r.first_statement_index);
                        &new_string[..]
                    }
                };
                explain_span(self, scope_decorated_tag, span)
            }
178

179 180 181 182 183
            ty::ReEarlyBound(_) |
            ty::ReFree(_) => {
                let scope = match *region {
                    ty::ReEarlyBound(ref br) => {
                        self.parent_def_id(br.def_id).unwrap()
184
                    }
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
                    ty::ReFree(ref fr) => fr.scope,
                    _ => bug!()
                };
                let prefix = match *region {
                    ty::ReEarlyBound(ref br) => {
                        format!("the lifetime {} as defined on", br.name)
                    }
                    ty::ReFree(ref fr) => {
                        match fr.bound_region {
                            ty::BrAnon(idx) => {
                                format!("the anonymous lifetime #{} defined on", idx + 1)
                            }
                            ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
                            _ => {
                                format!("the lifetime {} as defined on",
                                        fr.bound_region)
                            }
                        }
203
                    }
204
                    _ => bug!()
205 206
                };

207
                let node = self.hir.as_local_node_id(scope)
208
                                   .unwrap_or(DUMMY_NODE_ID);
209
                let unknown;
210
                let tag = match self.hir.find(node) {
211 212 213 214 215
                    Some(hir_map::NodeBlock(_)) |
                    Some(hir_map::NodeExpr(_)) => "body",
                    Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
                    Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
                    Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
216 217 218 219 220 221

                    // this really should not happen, but it does:
                    // FIXME(#27942)
                    Some(_) => {
                        unknown = format!("unexpected node ({}) for scope {:?}.  \
                                           Please report a bug.",
222
                                          self.hir.node_to_string(node), scope);
223
                        &unknown
224
                    }
225 226
                    None => {
                        unknown = format!("unknown node for scope {:?}.  \
227
                                           Please report a bug.", scope);
228
                        &unknown
229
                    }
230
                };
231
                let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
232
                (format!("{} {}", prefix, msg), opt_span)
233 234
            }

235
            ty::ReStatic => ("the static lifetime".to_owned(), None),
236

237
            ty::ReEmpty => ("the empty lifetime".to_owned(), None),
238

239 240 241 242
            // FIXME(#13998) ReSkolemized should probably print like
            // ReFree rather than dumping Debug output on the user.
            //
            // We shouldn't really be having unification failures with ReVar
A
Ariel Ben-Yehuda 已提交
243
            // and ReLateBound though.
244 245 246 247
            ty::ReSkolemized(..) |
            ty::ReVar(_) |
            ty::ReLateBound(..) |
            ty::ReErased => {
248 249 250 251 252
                (format!("lifetime {:?}", region), None)
            }
        };
        let message = format!("{}{}{}", prefix, description, suffix);
        if let Some(span) = span {
N
Nick Cameron 已提交
253
            err.span_note(span, &message);
254
        } else {
N
Nick Cameron 已提交
255
            err.note(&message);
256 257 258 259
        }
    }
}

260
impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
261 262

    pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
263 264 265 266
        debug!("report_region_errors(): {} errors to start", errors.len());

        // try to pre-process the errors, which will group some of them
        // together into a `ProcessedErrors` group:
267
        let errors = self.process_errors(errors);
268

G
Guillaume Gomez 已提交
269
        debug!("report_region_errors: {} errors after preprocessing", errors.len());
270

271
        for error in errors {
272
            debug!("report_region_errors: error = {:?}", error);
273

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
            if !self.try_report_named_anon_conflict(&error) &&
               !self.try_report_anon_anon_conflict(&error) {

               match error.clone() {
                  // These errors could indicate all manner of different
                  // problems with many different solutions. Rather
                  // than generate a "one size fits all" error, what we
                  // attempt to do is go through a number of specific
                  // scenarios and try to find the best way to present
                  // the error. If all of these fails, we fall back to a rather
                  // general bit of code that displays the error information
                  ConcreteFailure(origin, sub, sup) => {

                      self.report_concrete_failure(origin, sub, sup).emit();
                  }

                  GenericBoundFailure(kind, param_ty, sub) => {
                      self.report_generic_bound_failure(kind, param_ty, sub);
                  }

                  SubSupConflict(var_origin, sub_origin, sub_r, sup_origin, sup_r) => {
G
Guillaume Gomez 已提交
295
                        self.report_sub_sup_conflict(var_origin,
296 297 298 299 300 301
                                                     sub_origin,
                                                     sub_r,
                                                     sup_origin,
                                                     sup_r);
                  }
               }
302 303 304 305
            }
        }
    }

306 307 308 309 310
    // This method goes through all the errors and try to group certain types
    // of error together, for the purpose of suggesting explicit lifetime
    // parameters to the user. This is done so that we can have a more
    // complete view of what lifetimes should be the same.
    // If the return value is an empty vector, it means that processing
311 312 313 314 315
    // failed (so the return value of this method should not be used).
    //
    // The method also attempts to weed out messages that seem like
    // duplicates that will be unhelpful to the end-user. But
    // obviously it never weeds out ALL errors.
316
    fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
317
                      -> Vec<RegionResolutionError<'tcx>> {
318
        debug!("process_errors()");
319

320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
        // We want to avoid reporting generic-bound failures if we can
        // avoid it: these have a very high rate of being unhelpful in
        // practice. This is because they are basically secondary
        // checks that test the state of the region graph after the
        // rest of inference is done, and the other kinds of errors
        // indicate that the region constraint graph is internally
        // inconsistent, so these test results are likely to be
        // meaningless.
        //
        // Therefore, we filter them out of the list unless they are
        // the only thing in the list.

        let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
            ConcreteFailure(..) => false,
            SubSupConflict(..) => false,
            GenericBoundFailure(..) => true,
        };
337

338 339 340 341
        if errors.iter().all(|e| is_bound_failure(e)) {
            errors.clone()
        } else {
            errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
342 343 344
        }
    }

345
    /// Adds a note if the types come from similarly named crates
N
Nick Cameron 已提交
346 347 348 349 350
    fn check_and_note_conflicting_crates(&self,
                                         err: &mut DiagnosticBuilder,
                                         terr: &TypeError<'tcx>,
                                         sp: Span) {
        let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
M
Manish Goregaokar 已提交
351 352
            // Only external crates, if either is from a local
            // module we could have false positives
M
Manish Goregaokar 已提交
353
            if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
354 355
                let exp_path = self.tcx.item_path_str(did1);
                let found_path = self.tcx.item_path_str(did2);
356 357
                let exp_abs_path = self.tcx.absolute_item_path_str(did1);
                let found_abs_path = self.tcx.absolute_item_path_str(did2);
358
                // We compare strings because DefPath can be different
M
Manish Goregaokar 已提交
359
                // for imported and non-imported crates
360 361
                if exp_path == found_path
                || exp_abs_path == found_abs_path {
362
                    let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
N
Nick Cameron 已提交
363 364 365
                    err.span_note(sp, &format!("Perhaps two different versions \
                                                of crate `{}` are being used?",
                                               crate_name));
M
Manish Goregaokar 已提交
366 367 368
                }
            }
        };
369
        match *terr {
370
            TypeError::Sorts(ref exp_found) => {
371 372 373
                // if they are both "path types", there's a chance of ambiguity
                // due to different versions of the same crate
                match (&exp_found.expected.sty, &exp_found.found.sty) {
374
                    (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
N
Nick Cameron 已提交
375
                        report_path_match(err, exp_adt.did, found_adt.did);
376 377 378
                    },
                    _ => ()
                }
M
Manish Goregaokar 已提交
379
            },
380
            TypeError::Traits(ref exp_found) => {
N
Nick Cameron 已提交
381
                report_path_match(err, exp_found.expected, exp_found.found);
M
Manish Goregaokar 已提交
382
            },
M
Manish Goregaokar 已提交
383
            _ => () // FIXME(#22750) handle traits and stuff
384 385 386
        }
    }

A
Ariel Ben-Yehuda 已提交
387 388
    fn note_error_origin(&self,
                         err: &mut DiagnosticBuilder<'tcx>,
389
                         cause: &ObligationCause<'tcx>)
A
Ariel Ben-Yehuda 已提交
390
    {
391 392
        match cause.code {
            ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
A
Ariel Ben-Yehuda 已提交
393 394 395 396 397 398 399 400 401 402 403
                hir::MatchSource::IfLetDesugar {..} => {
                    err.span_note(arm_span, "`if let` arm with an incompatible type");
                }
                _ => {
                    err.span_note(arm_span, "match arm with an incompatible type");
                }
            },
            _ => ()
        }
    }

404 405 406 407 408 409 410 411 412 413 414 415 416 417
    /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
    /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
    /// populate `other_value` with `other_ty`.
    ///
    /// ```text
    /// Foo<Bar<Qux>>
    /// ^^^^--------^ this is highlighted
    /// |   |
    /// |   this type argument is exactly the same as the other type, not highlighted
    /// this is highlighted
    /// Bar<Qux>
    /// -------- this type is the same as a type argument in the other type, not highlighted
    /// ```
    fn highlight_outer(&self,
418 419
                       value: &mut DiagnosticStyledString,
                       other_value: &mut DiagnosticStyledString,
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
                       name: String,
                       sub: &ty::subst::Substs<'tcx>,
                       pos: usize,
                       other_ty: &ty::Ty<'tcx>) {
        // `value` and `other_value` hold two incomplete type representation for display.
        // `name` is the path of both types being compared. `sub`
        value.push_highlighted(name);
        let len = sub.len();
        if len > 0 {
            value.push_highlighted("<");
        }

        // Output the lifetimes fot the first type
        let lifetimes = sub.regions().map(|lifetime| {
            let s = format!("{}", lifetime);
            if s.is_empty() {
                "'_".to_string()
            } else {
                s
            }
        }).collect::<Vec<_>>().join(", ");
        if !lifetimes.is_empty() {
            if sub.regions().count() < len {
                value.push_normal(lifetimes + &", ");
            } else {
                value.push_normal(lifetimes);
            }
        }

        // Highlight all the type arguments that aren't at `pos` and compare the type argument at
        // `pos` and `other_ty`.
        for (i, type_arg) in sub.types().enumerate() {
            if i == pos {
                let values = self.cmp(type_arg, other_ty);
                value.0.extend((values.0).0);
                other_value.0.extend((values.1).0);
            } else {
                value.push_highlighted(format!("{}", type_arg));
            }

            if len > 0 && i != len - 1 {
                value.push_normal(", ");
            }
            //self.push_comma(&mut value, &mut other_value, len, i);
        }
        if len > 0 {
            value.push_highlighted(">");
        }
    }

    /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
    /// as that is the difference to the other type.
    ///
    /// For the following code:
    ///
    /// ```norun
    /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
    /// ```
    ///
    /// The type error output will behave in the following way:
    ///
    /// ```text
    /// Foo<Bar<Qux>>
    /// ^^^^--------^ this is highlighted
    /// |   |
    /// |   this type argument is exactly the same as the other type, not highlighted
    /// this is highlighted
    /// Bar<Qux>
    /// -------- this type is the same as a type argument in the other type, not highlighted
    /// ```
    fn cmp_type_arg(&self,
                    mut t1_out: &mut DiagnosticStyledString,
                    mut t2_out: &mut DiagnosticStyledString,
                    path: String,
                    sub: &ty::subst::Substs<'tcx>,
                    other_path: String,
                    other_ty: &ty::Ty<'tcx>) -> Option<()> {
        for (i, ta) in sub.types().enumerate() {
            if &ta == other_ty {
                self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
                return Some(());
            }
            if let &ty::TyAdt(def, _) = &ta.sty {
                let path_ = self.tcx.item_path_str(def.did.clone());
                if path_ == other_path {
                    self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
                    return Some(());
                }
            }
        }
        None
    }

    /// Add a `,` to the type representation only if it is appropriate.
    fn push_comma(&self,
                  value: &mut DiagnosticStyledString,
                  other_value: &mut DiagnosticStyledString,
                  len: usize,
                  pos: usize) {
        if len > 0 && pos != len - 1 {
            value.push_normal(", ");
            other_value.push_normal(", ");
        }
    }

    /// Compare two given types, eliding parts that are the same between them and highlighting
    /// relevant differences, and return two representation of those types for highlighted printing.
    fn cmp(&self, t1: ty::Ty<'tcx>, t2: ty::Ty<'tcx>)
        -> (DiagnosticStyledString, DiagnosticStyledString)
    {
        match (&t1.sty, &t2.sty) {
            (&ty::TyAdt(def1, sub1), &ty::TyAdt(def2, sub2)) => {
                let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
                let path1 = self.tcx.item_path_str(def1.did.clone());
                let path2 = self.tcx.item_path_str(def2.did.clone());
                if def1.did == def2.did {
                    // Easy case. Replace same types with `_` to shorten the output and highlight
                    // the differing ones.
                    //     let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
                    //     Foo<Bar, _>
                    //     Foo<Quz, _>
                    //         ---  ^ type argument elided
                    //         |
                    //         highlighted in output
                    values.0.push_normal(path1);
                    values.1.push_normal(path2);

                    // Only draw `<...>` if there're lifetime/type arguments.
                    let len = sub1.len();
                    if len > 0 {
                        values.0.push_normal("<");
                        values.1.push_normal("<");
                    }

N
Niko Matsakis 已提交
554
                    fn lifetime_display(lifetime: Region) -> String {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
                        let s = format!("{}", lifetime);
                        if s.is_empty() {
                            "'_".to_string()
                        } else {
                            s
                        }
                    }
                    // At one point we'd like to elide all lifetimes here, they are irrelevant for
                    // all diagnostics that use this output
                    //
                    //     Foo<'x, '_, Bar>
                    //     Foo<'y, '_, Qux>
                    //         ^^  ^^  --- type arguments are not elided
                    //         |   |
                    //         |   elided as they were the same
                    //         not elided, they were different, but irrelevant
                    let lifetimes = sub1.regions().zip(sub2.regions());
                    for (i, lifetimes) in lifetimes.enumerate() {
                        let l1 = lifetime_display(lifetimes.0);
                        let l2 = lifetime_display(lifetimes.1);
                        if l1 == l2 {
                            values.0.push_normal("'_");
                            values.1.push_normal("'_");
                        } else {
                            values.0.push_highlighted(l1);
                            values.1.push_highlighted(l2);
                        }
                        self.push_comma(&mut values.0, &mut values.1, len, i);
                    }

                    // We're comparing two types with the same path, so we compare the type
                    // arguments for both. If they are the same, do not highlight and elide from the
                    // output.
                    //     Foo<_, Bar>
                    //     Foo<_, Qux>
                    //         ^ elided type as this type argument was the same in both sides
                    let type_arguments = sub1.types().zip(sub2.types());
                    let regions_len = sub1.regions().collect::<Vec<_>>().len();
                    for (i, (ta1, ta2)) in type_arguments.enumerate() {
                        let i = i + regions_len;
                        if ta1 == ta2 {
                            values.0.push_normal("_");
                            values.1.push_normal("_");
                        } else {
                            let (x1, x2) = self.cmp(ta1, ta2);
                            (values.0).0.extend(x1.0);
                            (values.1).0.extend(x2.0);
                        }
                        self.push_comma(&mut values.0, &mut values.1, len, i);
                    }

                    // Close the type argument bracket.
                    // Only draw `<...>` if there're lifetime/type arguments.
                    if len > 0 {
                        values.0.push_normal(">");
                        values.1.push_normal(">");
                    }
                    values
                } else {
                    // Check for case:
                    //     let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
                    //     Foo<Bar<Qux>
                    //         ------- this type argument is exactly the same as the other type
                    //     Bar<Qux>
                    if self.cmp_type_arg(&mut values.0,
                                         &mut values.1,
                                         path1.clone(),
                                         sub1,
                                         path2.clone(),
                                         &t2).is_some() {
                        return values;
                    }
                    // Check for case:
                    //     let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
                    //     Bar<Qux>
                    //     Foo<Bar<Qux>>
                    //         ------- this type argument is exactly the same as the other type
                    if self.cmp_type_arg(&mut values.1,
                                         &mut values.0,
                                         path2,
                                         sub2,
                                         path1,
                                         &t1).is_some() {
                        return values;
                    }

                    // We couldn't find anything in common, highlight everything.
                    //     let x: Bar<Qux> = y::<Foo<Zar>>();
                    (DiagnosticStyledString::highlighted(format!("{}", t1)),
                     DiagnosticStyledString::highlighted(format!("{}", t2)))
                }
            }
            _ => {
                if t1 == t2 {
                    // The two types are the same, elide and don't highlight.
                    (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
                } else {
                    // We couldn't find anything in common, highlight everything.
                    (DiagnosticStyledString::highlighted(format!("{}", t1)),
                     DiagnosticStyledString::highlighted(format!("{}", t2)))
                }
            }
        }
    }

660 661
    pub fn note_type_err(&self,
                         diag: &mut DiagnosticBuilder<'tcx>,
662
                         cause: &ObligationCause<'tcx>,
663
                         secondary_span: Option<(Span, String)>,
664 665
                         values: Option<ValuePairs<'tcx>>,
                         terr: &TypeError<'tcx>)
A
Ariel Ben-Yehuda 已提交
666
    {
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
        let (expected_found, is_simple_error) = match values {
            None => (None, false),
            Some(values) => {
                let is_simple_error = match values {
                    ValuePairs::Types(exp_found) => {
                        exp_found.expected.is_primitive() && exp_found.found.is_primitive()
                    }
                    _ => false,
                };
                let vals = match self.values_str(&values) {
                    Some((expected, found)) => Some((expected, found)),
                    None => {
                        // Derived error. Cancel the emitter.
                        self.tcx.sess.diagnostic().cancel(diag);
                        return
                    }
                };
                (vals, is_simple_error)
685
            }
A
Ariel Ben-Yehuda 已提交
686 687
        };

688
        let span = cause.span;
A
Ariel Ben-Yehuda 已提交
689

690
        if let Some((expected, found)) = expected_found {
691
            match (terr, is_simple_error, expected == found) {
692
                (&TypeError::Sorts(ref values), false, true) => {
693
                    diag.note_expected_found_extra(
694
                        &"type", expected, found,
695 696 697 698
                        &format!(" ({})", values.expected.sort_string(self.tcx)),
                        &format!(" ({})", values.found.sort_string(self.tcx)));
                }
                (_, false,  _) => {
699
                    diag.note_expected_found(&"type", expected, found);
700
                }
701
                _ => (),
702
            }
A
Ariel Ben-Yehuda 已提交
703 704
        }

705
        diag.span_label(span, terr.to_string());
706
        if let Some((sp, msg)) = secondary_span {
707
            diag.span_label(sp, msg);
708
        }
A
Ariel Ben-Yehuda 已提交
709

710
        self.note_error_origin(diag, &cause);
711 712
        self.check_and_note_conflicting_crates(diag, terr, span);
        self.tcx.note_and_explain_type_err(diag, terr, span);
713 714
    }

A
Ariel Ben-Yehuda 已提交
715 716 717 718 719
    pub fn report_and_explain_type_error(&self,
                                         trace: TypeTrace<'tcx>,
                                         terr: &TypeError<'tcx>)
                                         -> DiagnosticBuilder<'tcx>
    {
720 721 722 723
        let span = trace.cause.span;
        let failure_str = trace.cause.as_failure_str();
        let mut diag = match trace.cause.code {
            ObligationCauseCode::IfExpressionWithNoElse => {
724
                struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
725 726
            }
            ObligationCauseCode::MainFunctionType => {
G
Guillaume Gomez 已提交
727
                struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
728
            }
729 730
            _ => {
                struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
731
            }
732
        };
733
        self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
734
        diag
A
Ariel Ben-Yehuda 已提交
735 736
    }

737 738 739
    fn values_str(&self, values: &ValuePairs<'tcx>)
        -> Option<(DiagnosticStyledString, DiagnosticStyledString)>
    {
740
        match *values {
741
            infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
742
            infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
A
Ariel Ben-Yehuda 已提交
743
            infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
744 745 746
        }
    }

747 748 749 750 751 752 753 754 755 756 757 758
    fn expected_found_str_ty(&self,
                             exp_found: &ty::error::ExpectedFound<ty::Ty<'tcx>>)
                             -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
        let exp_found = self.resolve_type_vars_if_possible(exp_found);
        if exp_found.references_error() {
            return None;
        }

        Some(self.cmp(exp_found.expected, exp_found.found))
    }

    /// Returns a string of the form "expected `{}`, found `{}`".
A
Ariel Ben-Yehuda 已提交
759
    fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
E
Eduard Burtescu 已提交
760
        &self,
761
        exp_found: &ty::error::ExpectedFound<T>)
762
        -> Option<(DiagnosticStyledString, DiagnosticStyledString)>
763
    {
A
Ariel Ben-Yehuda 已提交
764 765
        let exp_found = self.resolve_type_vars_if_possible(exp_found);
        if exp_found.references_error() {
766 767 768
            return None;
        }

769 770
        Some((DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
              DiagnosticStyledString::highlighted(format!("{}", exp_found.found))))
771 772
    }

773 774 775
    fn report_generic_bound_failure(&self,
                                    origin: SubregionOrigin<'tcx>,
                                    bound_kind: GenericKind<'tcx>,
N
Niko Matsakis 已提交
776
                                    sub: Region<'tcx>)
777
    {
778 779 780 781 782
        // FIXME: it would be better to report the first error message
        // with the span of the parameter itself, rather than the span
        // where the error was detected. But that span is not readily
        // accessible.

783 784
        let labeled_user_string = match bound_kind {
            GenericKind::Param(ref p) =>
785
                format!("the parameter type `{}`", p),
786
            GenericKind::Projection(ref p) =>
787
                format!("the associated type `{}`", p),
788 789
        };

790
        if let SubregionOrigin::CompareImplMethodObligation {
N
Niko Matsakis 已提交
791
            span, item_name, impl_item_def_id, trait_item_def_id, lint_id
792 793 794 795 796
        } = origin {
            self.report_extra_impl_obligation(span,
                                              item_name,
                                              impl_item_def_id,
                                              trait_item_def_id,
N
Niko Matsakis 已提交
797 798
                                              &format!("`{}: {}`", bound_kind, sub),
                                              lint_id)
799 800 801 802
                .emit();
            return;
        }

803
        let mut err = match *sub {
804
            ty::ReEarlyBound(_) |
805 806
            ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
                // Does the required lifetime have a nice name we can print?
N
Nick Cameron 已提交
807 808 809 810 811
                let mut err = struct_span_err!(self.tcx.sess,
                                               origin.span(),
                                               E0309,
                                               "{} may not live long enough",
                                               labeled_user_string);
812 813 814
                err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
                         bound_kind,
                         sub));
N
Nick Cameron 已提交
815
                err
816 817 818 819
            }

            ty::ReStatic => {
                // Does the required lifetime have a nice name we can print?
N
Nick Cameron 已提交
820 821 822 823 824
                let mut err = struct_span_err!(self.tcx.sess,
                                               origin.span(),
                                               E0310,
                                               "{} may not live long enough",
                                               labeled_user_string);
825 826 827
                err.help(&format!("consider adding an explicit lifetime \
                                   bound `{}: 'static`...",
                                  bound_kind));
N
Nick Cameron 已提交
828
                err
829 830 831 832
            }

            _ => {
                // If not, be less specific.
N
Nick Cameron 已提交
833 834 835 836 837
                let mut err = struct_span_err!(self.tcx.sess,
                                               origin.span(),
                                               E0311,
                                               "{} may not live long enough",
                                               labeled_user_string);
838 839
                err.help(&format!("consider adding an explicit lifetime bound for `{}`",
                                  bound_kind));
840
                self.tcx.note_and_explain_region(
N
Nick Cameron 已提交
841
                    &mut err,
842
                    &format!("{} must be valid for ", labeled_user_string),
843 844
                    sub,
                    "...");
N
Nick Cameron 已提交
845
                err
846
            }
N
Nick Cameron 已提交
847
        };
848

N
Nick Cameron 已提交
849 850
        self.note_region_origin(&mut err, &origin);
        err.emit();
851 852
    }

E
Eduard Burtescu 已提交
853
    fn report_sub_sup_conflict(&self,
854
                               var_origin: RegionVariableOrigin,
855
                               sub_origin: SubregionOrigin<'tcx>,
N
Niko Matsakis 已提交
856
                               sub_region: Region<'tcx>,
857
                               sup_origin: SubregionOrigin<'tcx>,
N
Niko Matsakis 已提交
858
                               sup_region: Region<'tcx>) {
N
Nick Cameron 已提交
859
        let mut err = self.report_inference_failure(var_origin);
860

N
Nick Cameron 已提交
861
        self.tcx.note_and_explain_region(&mut err,
862 863 864 865
            "first, the lifetime cannot outlive ",
            sup_region,
            "...");

N
Nick Cameron 已提交
866
        self.note_region_origin(&mut err, &sup_origin);
867

N
Nick Cameron 已提交
868
        self.tcx.note_and_explain_region(&mut err,
869 870 871 872
            "but, the lifetime must be valid for ",
            sub_region,
            "...");

N
Nick Cameron 已提交
873 874
        self.note_region_origin(&mut err, &sub_origin);
        err.emit();
875
    }
876 877
}

878
impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
E
Eduard Burtescu 已提交
879
    fn report_inference_failure(&self,
N
Nick Cameron 已提交
880 881
                                var_origin: RegionVariableOrigin)
                                -> DiagnosticBuilder<'tcx> {
882
        let br_string = |br: ty::BoundRegion| {
883
            let mut s = br.to_string();
884 885 886 887 888
            if !s.is_empty() {
                s.push_str(" ");
            }
            s
        };
889
        let var_description = match var_origin {
890 891 892 893 894
            infer::MiscVariable(_) => "".to_string(),
            infer::PatternRegion(_) => " for pattern".to_string(),
            infer::AddrOfRegion(_) => " for borrow expression".to_string(),
            infer::Autoref(_) => " for autoref".to_string(),
            infer::Coercion(_) => " for automatic coercion".to_string(),
895
            infer::LateBoundRegion(_, br, infer::FnCall) => {
896 897
                format!(" for lifetime parameter {}in function call",
                        br_string(br))
898
            }
899
            infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
900
                format!(" for lifetime parameter {}in generic type", br_string(br))
901
            }
902
            infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
903
                format!(" for lifetime parameter {}in trait containing associated type `{}`",
904
                        br_string(br), type_name)
905
            }
906
            infer::EarlyBoundRegion(_, name) => {
907
                format!(" for lifetime parameter `{}`",
908
                        name)
909
            }
910
            infer::BoundRegionInCoherence(name) => {
911
                format!(" for lifetime parameter `{}` in coherence check",
912
                        name)
913
            }
914 915
            infer::UpvarRegion(ref upvar_id, _) => {
                format!(" for capture of `{}` by closure",
916
                        self.tcx.local_var_name_str(upvar_id.var_id).to_string())
917
            }
918 919
        };

N
Nick Cameron 已提交
920
        struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
921 922
                  "cannot infer an appropriate lifetime{} \
                   due to conflicting requirements",
N
Nick Cameron 已提交
923
                  var_description)
924
    }
925 926
}

927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
impl<'tcx> ObligationCause<'tcx> {
    fn as_failure_str(&self) -> &'static str {
        use traits::ObligationCauseCode::*;
        match self.code {
            CompareImplMethodObligation { .. } => "method not compatible with trait",
            MatchExpressionArm { source, .. } => match source {
                hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
                _ => "match arms have incompatible types",
            },
            IfExpression => "if and else have incompatible types",
            IfExpressionWithNoElse => "if may be missing an else clause",
            EquatePredicate => "equality predicate not satisfied",
            MainFunctionType => "main function has wrong type",
            StartFunctionType => "start function has wrong type",
            IntrinsicType => "intrinsic has wrong type",
            MethodReceiver => "mismatched method receiver",
            _ => "mismatched types",
        }
    }

    fn as_requirement_str(&self) -> &'static str {
        use traits::ObligationCauseCode::*;
        match self.code {
            CompareImplMethodObligation { .. } => "method type is compatible with trait",
            ExprAssignable => "expression is assignable",
            MatchExpressionArm { source, .. } => match source {
                hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
                _ => "match arms have compatible types",
            },
            IfExpression => "if and else have compatible types",
            IfExpressionWithNoElse => "if missing an else returns ()",
            EquatePredicate => "equality where clause is satisfied",
            MainFunctionType => "`main` function has the correct type",
            StartFunctionType => "`start` function has the correct type",
            IntrinsicType => "intrinsic has the correct type",
            MethodReceiver => "method receiver has the correct type",
            _ => "types are compatible",
        }
    }
}