]> git.lizzy.rs Git - rust.git/blob - src/librustc/traits/error_reporting.rs
Fix invalid associated type rendering in rustdoc
[rust.git] / src / librustc / traits / error_reporting.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use super::{
12     FulfillmentError,
13     FulfillmentErrorCode,
14     MismatchedProjectionTypes,
15     Obligation,
16     ObligationCause,
17     ObligationCauseCode,
18     OutputTypeParameterMismatch,
19     TraitNotObjectSafe,
20     PredicateObligation,
21     SelectionContext,
22     SelectionError,
23     ObjectSafetyViolation,
24 };
25
26 use errors::DiagnosticBuilder;
27 use fmt_macros::{Parser, Piece, Position};
28 use hir::{intravisit, Local, Pat};
29 use hir::intravisit::{Visitor, NestedVisitorMap};
30 use hir::map::NodeExpr;
31 use hir::def_id::DefId;
32 use infer::{self, InferCtxt};
33 use infer::type_variable::TypeVariableOrigin;
34 use rustc::lint::builtin::EXTRA_REQUIREMENT_IN_IMPL;
35 use std::fmt;
36 use syntax::ast;
37 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
38 use ty::error::ExpectedFound;
39 use ty::fast_reject;
40 use ty::fold::TypeFolder;
41 use ty::subst::Subst;
42 use util::nodemap::{FxHashMap, FxHashSet};
43
44 use syntax_pos::{DUMMY_SP, Span};
45
46
47 #[derive(Debug, PartialEq, Eq, Hash)]
48 pub struct TraitErrorKey<'tcx> {
49     span: Span,
50     predicate: ty::Predicate<'tcx>
51 }
52
53 impl<'a, 'gcx, 'tcx> TraitErrorKey<'tcx> {
54     fn from_error(infcx: &InferCtxt<'a, 'gcx, 'tcx>,
55                   e: &FulfillmentError<'tcx>) -> Self {
56         let predicate =
57             infcx.resolve_type_vars_if_possible(&e.obligation.predicate);
58         TraitErrorKey {
59             span: e.obligation.cause.span,
60             predicate: infcx.tcx.erase_regions(&predicate)
61         }
62     }
63 }
64
65 struct FindLocalByTypeVisitor<'a, 'gcx: 'a + 'tcx, 'tcx: 'a> {
66     infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
67     target_ty: &'a Ty<'tcx>,
68     found_pattern: Option<&'a Pat>,
69 }
70
71 impl<'a, 'gcx, 'tcx> Visitor<'a> for FindLocalByTypeVisitor<'a, 'gcx, 'tcx> {
72     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'a> {
73         NestedVisitorMap::None
74     }
75
76     fn visit_local(&mut self, local: &'a Local) {
77         if let Some(&ty) = self.infcx.tables.borrow().node_types.get(&local.id) {
78             let ty = self.infcx.resolve_type_vars_if_possible(&ty);
79             let is_match = ty.walk().any(|t| t == *self.target_ty);
80
81             if is_match && self.found_pattern.is_none() {
82                 self.found_pattern = Some(&*local.pat);
83             }
84         }
85         intravisit::walk_local(self, local);
86     }
87 }
88
89 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
90     pub fn report_fulfillment_errors(&self, errors: &Vec<FulfillmentError<'tcx>>) {
91         for error in errors {
92             self.report_fulfillment_error(error);
93         }
94     }
95
96     fn report_fulfillment_error(&self,
97                                 error: &FulfillmentError<'tcx>) {
98         let error_key = TraitErrorKey::from_error(self, error);
99         debug!("report_fulfillment_errors({:?}) - key={:?}",
100                error, error_key);
101         if !self.reported_trait_errors.borrow_mut().insert(error_key) {
102             debug!("report_fulfillment_errors: skipping duplicate");
103             return;
104         }
105         match error.code {
106             FulfillmentErrorCode::CodeSelectionError(ref e) => {
107                 self.report_selection_error(&error.obligation, e);
108             }
109             FulfillmentErrorCode::CodeProjectionError(ref e) => {
110                 self.report_projection_error(&error.obligation, e);
111             }
112             FulfillmentErrorCode::CodeAmbiguity => {
113                 self.maybe_report_ambiguity(&error.obligation);
114             }
115         }
116     }
117
118     fn report_projection_error(&self,
119                                obligation: &PredicateObligation<'tcx>,
120                                error: &MismatchedProjectionTypes<'tcx>)
121     {
122         let predicate =
123             self.resolve_type_vars_if_possible(&obligation.predicate);
124
125         if predicate.references_error() {
126             return
127         }
128
129         self.probe(|_| {
130             let err_buf;
131             let mut err = &error.err;
132             let mut values = None;
133
134             // try to find the mismatched types to report the error with.
135             //
136             // this can fail if the problem was higher-ranked, in which
137             // cause I have no idea for a good error message.
138             if let ty::Predicate::Projection(ref data) = predicate {
139                 let mut selcx = SelectionContext::new(self);
140                 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
141                     obligation.cause.span,
142                     infer::LateBoundRegionConversionTime::HigherRankedType,
143                     data);
144                 let normalized = super::normalize_projection_type(
145                     &mut selcx,
146                     data.projection_ty,
147                     obligation.cause.clone(),
148                     0
149                 );
150                 if let Err(error) = self.eq_types(
151                     false, &obligation.cause,
152                     data.ty, normalized.value
153                 ) {
154                     values = Some(infer::ValuePairs::Types(ExpectedFound {
155                         expected: normalized.value,
156                         found: data.ty,
157                     }));
158                     err_buf = error;
159                     err = &err_buf;
160                 }
161             }
162
163             let mut diag = struct_span_err!(
164                 self.tcx.sess, obligation.cause.span, E0271,
165                 "type mismatch resolving `{}`", predicate
166             );
167             self.note_type_err(&mut diag, &obligation.cause, None, values, err);
168             self.note_obligation_cause(&mut diag, obligation);
169             diag.emit();
170         });
171     }
172
173     fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
174         /// returns the fuzzy category of a given type, or None
175         /// if the type can be equated to any type.
176         fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
177             match t.sty {
178                 ty::TyBool => Some(0),
179                 ty::TyChar => Some(1),
180                 ty::TyStr => Some(2),
181                 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
182                 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
183                 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
184                 ty::TyArray(..) | ty::TySlice(..) => Some(6),
185                 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
186                 ty::TyDynamic(..) => Some(8),
187                 ty::TyClosure(..) => Some(9),
188                 ty::TyTuple(..) => Some(10),
189                 ty::TyProjection(..) => Some(11),
190                 ty::TyParam(..) => Some(12),
191                 ty::TyAnon(..) => Some(13),
192                 ty::TyNever => Some(14),
193                 ty::TyAdt(adt, ..) => match adt.adt_kind() {
194                     AdtKind::Struct => Some(15),
195                     AdtKind::Union => Some(16),
196                     AdtKind::Enum => Some(17),
197                 },
198                 ty::TyInfer(..) | ty::TyError => None
199             }
200         }
201
202         match (type_category(a), type_category(b)) {
203             (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
204                 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
205                 _ => cat_a == cat_b
206             },
207             // infer and error can be equated to all types
208             _ => true
209         }
210     }
211
212     fn impl_similar_to(&self,
213                        trait_ref: ty::PolyTraitRef<'tcx>,
214                        obligation: &PredicateObligation<'tcx>)
215                        -> Option<DefId>
216     {
217         let tcx = self.tcx;
218
219         let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
220         let trait_self_ty = trait_ref.self_ty();
221
222         let mut self_match_impls = vec![];
223         let mut fuzzy_match_impls = vec![];
224
225         self.tcx.lookup_trait_def(trait_ref.def_id)
226             .for_each_relevant_impl(self.tcx, trait_self_ty, |def_id| {
227                 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
228                 let impl_trait_ref = tcx
229                     .impl_trait_ref(def_id)
230                     .unwrap()
231                     .subst(tcx, impl_substs);
232
233                 let impl_self_ty = impl_trait_ref.self_ty();
234
235                 if let Ok(..) = self.can_equate(&trait_self_ty, &impl_self_ty) {
236                     self_match_impls.push(def_id);
237
238                     if trait_ref.substs.types().skip(1)
239                         .zip(impl_trait_ref.substs.types().skip(1))
240                         .all(|(u,v)| self.fuzzy_match_tys(u, v))
241                     {
242                         fuzzy_match_impls.push(def_id);
243                     }
244                 }
245             });
246
247         let impl_def_id = if self_match_impls.len() == 1 {
248             self_match_impls[0]
249         } else if fuzzy_match_impls.len() == 1 {
250             fuzzy_match_impls[0]
251         } else {
252             return None
253         };
254
255         if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
256             Some(impl_def_id)
257         } else {
258             None
259         }
260     }
261
262     fn on_unimplemented_note(&self,
263                              trait_ref: ty::PolyTraitRef<'tcx>,
264                              obligation: &PredicateObligation<'tcx>) -> Option<String> {
265         let def_id = self.impl_similar_to(trait_ref, obligation)
266             .unwrap_or(trait_ref.def_id());
267         let trait_ref = trait_ref.skip_binder();
268
269         let span = obligation.cause.span;
270         let mut report = None;
271         if let Some(item) = self.tcx
272             .get_attrs(def_id)
273             .into_iter()
274             .filter(|a| a.check_name("rustc_on_unimplemented"))
275             .next()
276         {
277             let err_sp = item.span.substitute_dummy(span);
278             let trait_str = self.tcx.item_path_str(trait_ref.def_id);
279             if let Some(istring) = item.value_str() {
280                 let istring = &*istring.as_str();
281                 let generics = self.tcx.item_generics(trait_ref.def_id);
282                 let generic_map = generics.types.iter().map(|param| {
283                     (param.name.as_str().to_string(),
284                         trait_ref.substs.type_for_def(param).to_string())
285                 }).collect::<FxHashMap<String, String>>();
286                 let parser = Parser::new(istring);
287                 let mut errored = false;
288                 let err: String = parser.filter_map(|p| {
289                     match p {
290                         Piece::String(s) => Some(s),
291                         Piece::NextArgument(a) => match a.position {
292                             Position::ArgumentNamed(s) => match generic_map.get(s) {
293                                 Some(val) => Some(val),
294                                 None => {
295                                     span_err!(self.tcx.sess, err_sp, E0272,
296                                                     "the #[rustc_on_unimplemented] \
297                                                             attribute on \
298                                                             trait definition for {} refers to \
299                                                             non-existent type parameter {}",
300                                                             trait_str, s);
301                                     errored = true;
302                                     None
303                                 }
304                             },
305                             _ => {
306                                 span_err!(self.tcx.sess, err_sp, E0273,
307                                             "the #[rustc_on_unimplemented] attribute \
308                                             on trait definition for {} must have \
309                                             named format arguments, eg \
310                                             `#[rustc_on_unimplemented = \
311                                             \"foo {{T}}\"]`", trait_str);
312                                 errored = true;
313                                 None
314                             }
315                         }
316                     }
317                 }).collect();
318                 // Report only if the format string checks out
319                 if !errored {
320                     report = Some(err);
321                 }
322             } else {
323                 span_err!(self.tcx.sess, err_sp, E0274,
324                                         "the #[rustc_on_unimplemented] attribute on \
325                                                     trait definition for {} must have a value, \
326                                                     eg `#[rustc_on_unimplemented = \"foo\"]`",
327                                                     trait_str);
328             }
329         }
330         report
331     }
332
333     fn find_similar_impl_candidates(&self,
334                                     trait_ref: ty::PolyTraitRef<'tcx>)
335                                     -> Vec<ty::TraitRef<'tcx>>
336     {
337         let simp = fast_reject::simplify_type(self.tcx,
338                                               trait_ref.skip_binder().self_ty(),
339                                               true);
340         let mut impl_candidates = Vec::new();
341         let trait_def = self.tcx.lookup_trait_def(trait_ref.def_id());
342
343         match simp {
344             Some(simp) => trait_def.for_each_impl(self.tcx, |def_id| {
345                 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
346                 let imp_simp = fast_reject::simplify_type(self.tcx,
347                                                           imp.self_ty(),
348                                                           true);
349                 if let Some(imp_simp) = imp_simp {
350                     if simp != imp_simp {
351                         return;
352                     }
353                 }
354                 impl_candidates.push(imp);
355             }),
356             None => trait_def.for_each_impl(self.tcx, |def_id| {
357                 impl_candidates.push(
358                     self.tcx.impl_trait_ref(def_id).unwrap());
359             })
360         };
361         impl_candidates
362     }
363
364     fn report_similar_impl_candidates(&self,
365                                       impl_candidates: Vec<ty::TraitRef<'tcx>>,
366                                       err: &mut DiagnosticBuilder)
367     {
368         if impl_candidates.is_empty() {
369             return;
370         }
371
372         let end = if impl_candidates.len() <= 5 {
373             impl_candidates.len()
374         } else {
375             4
376         };
377         err.help(&format!("the following implementations were found:{}{}",
378                           &impl_candidates[0..end].iter().map(|candidate| {
379                               format!("\n  {:?}", candidate)
380                           }).collect::<String>(),
381                           if impl_candidates.len() > 5 {
382                               format!("\nand {} others", impl_candidates.len() - 4)
383                           } else {
384                               "".to_owned()
385                           }
386                           ));
387     }
388
389     /// Reports that an overflow has occurred and halts compilation. We
390     /// halt compilation unconditionally because it is important that
391     /// overflows never be masked -- they basically represent computations
392     /// whose result could not be truly determined and thus we can't say
393     /// if the program type checks or not -- and they are unusual
394     /// occurrences in any case.
395     pub fn report_overflow_error<T>(&self,
396                                     obligation: &Obligation<'tcx, T>,
397                                     suggest_increasing_limit: bool) -> !
398         where T: fmt::Display + TypeFoldable<'tcx>
399     {
400         let predicate =
401             self.resolve_type_vars_if_possible(&obligation.predicate);
402         let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
403                                        "overflow evaluating the requirement `{}`",
404                                        predicate);
405
406         if suggest_increasing_limit {
407             self.suggest_new_overflow_limit(&mut err);
408         }
409
410         self.note_obligation_cause(&mut err, obligation);
411
412         err.emit();
413         self.tcx.sess.abort_if_errors();
414         bug!();
415     }
416
417     /// Reports that a cycle was detected which led to overflow and halts
418     /// compilation. This is equivalent to `report_overflow_error` except
419     /// that we can give a more helpful error message (and, in particular,
420     /// we do not suggest increasing the overflow limit, which is not
421     /// going to help).
422     pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
423         let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
424         assert!(cycle.len() > 0);
425
426         debug!("report_overflow_error_cycle: cycle={:?}", cycle);
427
428         self.report_overflow_error(&cycle[0], false);
429     }
430
431     pub fn report_extra_impl_obligation(&self,
432                                         error_span: Span,
433                                         item_name: ast::Name,
434                                         _impl_item_def_id: DefId,
435                                         trait_item_def_id: DefId,
436                                         requirement: &fmt::Display,
437                                         lint_id: Option<ast::NodeId>) // (*)
438                                         -> DiagnosticBuilder<'tcx>
439     {
440         // (*) This parameter is temporary and used only for phasing
441         // in the bug fix to #18937. If it is `Some`, it has a kind of
442         // weird effect -- the diagnostic is reported as a lint, and
443         // the builder which is returned is marked as canceled.
444
445         let mut err =
446             struct_span_err!(self.tcx.sess,
447                              error_span,
448                              E0276,
449                              "impl has stricter requirements than trait");
450
451         if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
452             err.span_label(trait_item_span,
453                            &format!("definition of `{}` from trait", item_name));
454         }
455
456         err.span_label(
457             error_span,
458             &format!("impl has extra requirement {}", requirement));
459
460         if let Some(node_id) = lint_id {
461             self.tcx.sess.add_lint_diagnostic(EXTRA_REQUIREMENT_IN_IMPL,
462                                               node_id,
463                                               (*err).clone());
464             err.cancel();
465         }
466
467         err
468     }
469
470
471     /// Get the parent trait chain start
472     fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
473         match code {
474             &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
475                 let parent_trait_ref = self.resolve_type_vars_if_possible(
476                     &data.parent_trait_ref);
477                 match self.get_parent_trait_ref(&data.parent_code) {
478                     Some(t) => Some(t),
479                     None => Some(format!("{}", parent_trait_ref.0.self_ty())),
480                 }
481             }
482             _ => None,
483         }
484     }
485
486     pub fn report_selection_error(&self,
487                                   obligation: &PredicateObligation<'tcx>,
488                                   error: &SelectionError<'tcx>)
489     {
490         let span = obligation.cause.span;
491
492         let mut err = match *error {
493             SelectionError::Unimplemented => {
494                 if let ObligationCauseCode::CompareImplMethodObligation {
495                     item_name, impl_item_def_id, trait_item_def_id, lint_id
496                 } = obligation.cause.code {
497                     self.report_extra_impl_obligation(
498                         span,
499                         item_name,
500                         impl_item_def_id,
501                         trait_item_def_id,
502                         &format!("`{}`", obligation.predicate),
503                         lint_id)
504                         .emit();
505                     return;
506                 }
507                 match obligation.predicate {
508                     ty::Predicate::Trait(ref trait_predicate) => {
509                         let trait_predicate =
510                             self.resolve_type_vars_if_possible(trait_predicate);
511
512                         if self.tcx.sess.has_errors() && trait_predicate.references_error() {
513                             return;
514                         }
515                         let trait_ref = trait_predicate.to_poly_trait_ref();
516                         let (post_message, pre_message) =
517                             self.get_parent_trait_ref(&obligation.cause.code)
518                                 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
519                                 .unwrap_or((String::new(), String::new()));
520                         let mut err = struct_span_err!(
521                             self.tcx.sess,
522                             span,
523                             E0277,
524                             "the trait bound `{}` is not satisfied{}",
525                             trait_ref.to_predicate(),
526                             post_message);
527
528                         // Try to report a help message
529                         if !trait_ref.has_infer_types() &&
530                             self.predicate_can_apply(trait_ref) {
531                             // If a where-clause may be useful, remind the
532                             // user that they can add it.
533                             //
534                             // don't display an on-unimplemented note, as
535                             // these notes will often be of the form
536                             //     "the type `T` can't be frobnicated"
537                             // which is somewhat confusing.
538                             err.help(&format!("consider adding a `where {}` bound",
539                                                 trait_ref.to_predicate()));
540                         } else if let Some(s) = self.on_unimplemented_note(trait_ref, obligation) {
541                             // If it has a custom "#[rustc_on_unimplemented]"
542                             // error message, let's display it!
543                             err.note(&s);
544                         } else {
545                             // Can't show anything else useful, try to find similar impls.
546                             let impl_candidates = self.find_similar_impl_candidates(trait_ref);
547                             self.report_similar_impl_candidates(impl_candidates, &mut err);
548                         }
549
550                         err.span_label(span,
551                                        &format!("{}the trait `{}` is not implemented for `{}`",
552                                                 pre_message,
553                                                 trait_ref,
554                                                 trait_ref.self_ty()));
555                         err
556                     }
557
558                     ty::Predicate::Equate(ref predicate) => {
559                         let predicate = self.resolve_type_vars_if_possible(predicate);
560                         let err = self.equality_predicate(&obligation.cause,
561                                                             &predicate).err().unwrap();
562                         struct_span_err!(self.tcx.sess, span, E0278,
563                             "the requirement `{}` is not satisfied (`{}`)",
564                             predicate, err)
565                     }
566
567                     ty::Predicate::RegionOutlives(ref predicate) => {
568                         let predicate = self.resolve_type_vars_if_possible(predicate);
569                         let err = self.region_outlives_predicate(&obligation.cause,
570                                                                     &predicate).err().unwrap();
571                         struct_span_err!(self.tcx.sess, span, E0279,
572                             "the requirement `{}` is not satisfied (`{}`)",
573                             predicate, err)
574                     }
575
576                     ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
577                         let predicate =
578                             self.resolve_type_vars_if_possible(&obligation.predicate);
579                         struct_span_err!(self.tcx.sess, span, E0280,
580                             "the requirement `{}` is not satisfied",
581                             predicate)
582                     }
583
584                     ty::Predicate::ObjectSafe(trait_def_id) => {
585                         let violations = self.tcx.object_safety_violations(trait_def_id);
586                         self.tcx.report_object_safety_error(span,
587                                                             trait_def_id,
588                                                             violations)
589                     }
590
591                     ty::Predicate::ClosureKind(closure_def_id, kind) => {
592                         let found_kind = self.closure_kind(closure_def_id).unwrap();
593                         let closure_span = self.tcx.hir.span_if_local(closure_def_id).unwrap();
594                         let mut err = struct_span_err!(
595                             self.tcx.sess, closure_span, E0525,
596                             "expected a closure that implements the `{}` trait, \
597                                 but this closure only implements `{}`",
598                             kind,
599                             found_kind);
600                         err.span_note(
601                             obligation.cause.span,
602                             &format!("the requirement to implement \
603                                         `{}` derives from here", kind));
604                         err.emit();
605                         return;
606                     }
607
608                     ty::Predicate::WellFormed(ty) => {
609                         // WF predicates cannot themselves make
610                         // errors. They can only block due to
611                         // ambiguity; otherwise, they always
612                         // degenerate into other obligations
613                         // (which may fail).
614                         span_bug!(span, "WF predicate not satisfied for {:?}", ty);
615                     }
616                 }
617             }
618
619             OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
620                 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
621                 let actual_trait_ref = self.resolve_type_vars_if_possible(&*actual_trait_ref);
622                 if actual_trait_ref.self_ty().references_error() {
623                     return;
624                 }
625                 struct_span_err!(self.tcx.sess, span, E0281,
626                     "type mismatch: the type `{}` implements the trait `{}`, \
627                      but the trait `{}` is required ({})",
628                     expected_trait_ref.self_ty(),
629                     expected_trait_ref,
630                     actual_trait_ref,
631                     e)
632             }
633
634             TraitNotObjectSafe(did) => {
635                 let violations = self.tcx.object_safety_violations(did);
636                 self.tcx.report_object_safety_error(span, did,
637                                                     violations)
638             }
639         };
640         self.note_obligation_cause(&mut err, obligation);
641         err.emit();
642     }
643 }
644
645 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
646     pub fn recursive_type_with_infinite_size_error(self,
647                                                    type_def_id: DefId)
648                                                    -> DiagnosticBuilder<'tcx>
649     {
650         assert!(type_def_id.is_local());
651         let span = self.hir.span_if_local(type_def_id).unwrap();
652         let mut err = struct_span_err!(self.sess, span, E0072,
653                                        "recursive type `{}` has infinite size",
654                                        self.item_path_str(type_def_id));
655         err.span_label(span, &format!("recursive type has infinite size"));
656         err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
657                            at some point to make `{}` representable",
658                           self.item_path_str(type_def_id)));
659         err
660     }
661
662     pub fn report_object_safety_error(self,
663                                       span: Span,
664                                       trait_def_id: DefId,
665                                       violations: Vec<ObjectSafetyViolation>)
666                                       -> DiagnosticBuilder<'tcx>
667     {
668         let trait_str = self.item_path_str(trait_def_id);
669         let mut err = struct_span_err!(
670             self.sess, span, E0038,
671             "the trait `{}` cannot be made into an object",
672             trait_str);
673         err.span_label(span, &format!(
674             "the trait `{}` cannot be made into an object", trait_str
675         ));
676
677         let mut reported_violations = FxHashSet();
678         for violation in violations {
679             if !reported_violations.insert(violation.clone()) {
680                 continue;
681             }
682             err.note(&violation.error_msg());
683         }
684         err
685     }
686 }
687
688 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
689     fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>) {
690         // Unable to successfully determine, probably means
691         // insufficient type information, but could mean
692         // ambiguous impls. The latter *ought* to be a
693         // coherence violation, so we don't report it here.
694
695         let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
696
697         debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
698                predicate,
699                obligation);
700
701         // Ambiguity errors are often caused as fallout from earlier
702         // errors. So just ignore them if this infcx is tainted.
703         if self.is_tainted_by_errors() {
704             return;
705         }
706
707         match predicate {
708             ty::Predicate::Trait(ref data) => {
709                 let trait_ref = data.to_poly_trait_ref();
710                 let self_ty = trait_ref.self_ty();
711                 if predicate.references_error() {
712                     return;
713                 }
714                 // Typically, this ambiguity should only happen if
715                 // there are unresolved type inference variables
716                 // (otherwise it would suggest a coherence
717                 // failure). But given #21974 that is not necessarily
718                 // the case -- we can have multiple where clauses that
719                 // are only distinguished by a region, which results
720                 // in an ambiguity even when all types are fully
721                 // known, since we don't dispatch based on region
722                 // relationships.
723
724                 // This is kind of a hack: it frequently happens that some earlier
725                 // error prevents types from being fully inferred, and then we get
726                 // a bunch of uninteresting errors saying something like "<generic
727                 // #0> doesn't implement Sized".  It may even be true that we
728                 // could just skip over all checks where the self-ty is an
729                 // inference variable, but I was afraid that there might be an
730                 // inference variable created, registered as an obligation, and
731                 // then never forced by writeback, and hence by skipping here we'd
732                 // be ignoring the fact that we don't KNOW the type works
733                 // out. Though even that would probably be harmless, given that
734                 // we're only talking about builtin traits, which are known to be
735                 // inhabited. But in any case I just threw in this check for
736                 // has_errors() to be sure that compilation isn't happening
737                 // anyway. In that case, why inundate the user.
738                 if !self.tcx.sess.has_errors() {
739                     if
740                         self.tcx.lang_items.sized_trait()
741                         .map_or(false, |sized_id| sized_id == trait_ref.def_id())
742                     {
743                         self.need_type_info(obligation, self_ty);
744                     } else {
745                         let mut err = struct_span_err!(self.tcx.sess,
746                                                         obligation.cause.span, E0283,
747                                                         "type annotations required: \
748                                                         cannot resolve `{}`",
749                                                         predicate);
750                         self.note_obligation_cause(&mut err, obligation);
751                         err.emit();
752                     }
753                 }
754             }
755
756             ty::Predicate::WellFormed(ty) => {
757                 // Same hacky approach as above to avoid deluging user
758                 // with error messages.
759                 if !ty.references_error() && !self.tcx.sess.has_errors() {
760                     self.need_type_info(obligation, ty);
761                 }
762             }
763
764             _ => {
765                 if !self.tcx.sess.has_errors() {
766                     let mut err = struct_span_err!(self.tcx.sess,
767                                                    obligation.cause.span, E0284,
768                                                    "type annotations required: \
769                                                     cannot resolve `{}`",
770                                                    predicate);
771                     self.note_obligation_cause(&mut err, obligation);
772                     err.emit();
773                 }
774             }
775         }
776     }
777
778     /// Returns whether the trait predicate may apply for *some* assignment
779     /// to the type parameters.
780     fn predicate_can_apply(&self, pred: ty::PolyTraitRef<'tcx>) -> bool {
781         struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
782             infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
783             var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
784         }
785
786         impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
787             fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
788
789             fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
790                 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
791                     let infcx = self.infcx;
792                     self.var_map.entry(ty).or_insert_with(||
793                         infcx.next_ty_var(
794                             TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
795                 } else {
796                     ty.super_fold_with(self)
797                 }
798             }
799         }
800
801         self.probe(|_| {
802             let mut selcx = SelectionContext::new(self);
803
804             let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
805                 infcx: self,
806                 var_map: FxHashMap()
807             });
808
809             let cleaned_pred = super::project::normalize(
810                 &mut selcx,
811                 ObligationCause::dummy(),
812                 &cleaned_pred
813             ).value;
814
815             let obligation = Obligation::new(
816                 ObligationCause::dummy(),
817                 cleaned_pred.to_predicate()
818             );
819
820             selcx.evaluate_obligation(&obligation)
821         })
822     }
823
824     fn extract_type_name(&self, ty: &'a Ty<'tcx>) -> String {
825         if let ty::TyInfer(ty::TyVar(ty_vid)) = (*ty).sty {
826             let ty_vars = self.type_variables.borrow();
827             if let TypeVariableOrigin::TypeParameterDefinition(_, name) =
828                 *ty_vars.var_origin(ty_vid) {
829                 name.to_string()
830             } else {
831                 ty.to_string()
832             }
833         } else {
834             ty.to_string()
835         }
836     }
837
838     fn need_type_info(&self, obligation: &PredicateObligation<'tcx>, ty: Ty<'tcx>) {
839         let ty = self.resolve_type_vars_if_possible(&ty);
840         let name = self.extract_type_name(&ty);
841         let ref cause = obligation.cause;
842
843         let mut err = struct_span_err!(self.tcx.sess,
844                                        cause.span,
845                                        E0282,
846                                        "type annotations needed");
847
848         err.span_label(cause.span, &format!("cannot infer type for `{}`", name));
849
850         let mut local_visitor = FindLocalByTypeVisitor {
851             infcx: &self,
852             target_ty: &ty,
853             found_pattern: None,
854         };
855
856         // #40294: cause.body_id can also be a fn declaration.
857         // Currently, if it's anything other than NodeExpr, we just ignore it
858         match self.tcx.hir.find(cause.body_id) {
859             Some(NodeExpr(expr)) => local_visitor.visit_expr(expr),
860             _ => ()
861         }
862
863         if let Some(pattern) = local_visitor.found_pattern {
864             let pattern_span = pattern.span;
865             if let Some(simple_name) = pattern.simple_name() {
866                 err.span_label(pattern_span,
867                                &format!("consider giving `{}` a type",
868                                         simple_name));
869             } else {
870                 err.span_label(pattern_span, &format!("consider giving a type to pattern"));
871             }
872         }
873
874         err.emit();
875     }
876
877     fn note_obligation_cause<T>(&self,
878                                 err: &mut DiagnosticBuilder,
879                                 obligation: &Obligation<'tcx, T>)
880         where T: fmt::Display
881     {
882         self.note_obligation_cause_code(err,
883                                         &obligation.predicate,
884                                         &obligation.cause.code);
885     }
886
887     fn note_obligation_cause_code<T>(&self,
888                                      err: &mut DiagnosticBuilder,
889                                      predicate: &T,
890                                      cause_code: &ObligationCauseCode<'tcx>)
891         where T: fmt::Display
892     {
893         let tcx = self.tcx;
894         match *cause_code {
895             ObligationCauseCode::ExprAssignable |
896             ObligationCauseCode::MatchExpressionArm { .. } |
897             ObligationCauseCode::IfExpression |
898             ObligationCauseCode::IfExpressionWithNoElse |
899             ObligationCauseCode::EquatePredicate |
900             ObligationCauseCode::MainFunctionType |
901             ObligationCauseCode::StartFunctionType |
902             ObligationCauseCode::IntrinsicType |
903             ObligationCauseCode::MethodReceiver |
904             ObligationCauseCode::ReturnNoExpression |
905             ObligationCauseCode::MiscObligation => {
906             }
907             ObligationCauseCode::SliceOrArrayElem => {
908                 err.note("slice and array elements must have `Sized` type");
909             }
910             ObligationCauseCode::TupleElem => {
911                 err.note("tuple elements must have `Sized` type");
912             }
913             ObligationCauseCode::ProjectionWf(data) => {
914                 err.note(&format!("required so that the projection `{}` is well-formed",
915                                   data));
916             }
917             ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
918                 err.note(&format!("required so that reference `{}` does not outlive its referent",
919                                   ref_ty));
920             }
921             ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
922                 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
923                                    is satisfied",
924                                   region, object_ty));
925             }
926             ObligationCauseCode::ItemObligation(item_def_id) => {
927                 let item_name = tcx.item_path_str(item_def_id);
928                 err.note(&format!("required by `{}`", item_name));
929             }
930             ObligationCauseCode::ObjectCastObligation(object_ty) => {
931                 err.note(&format!("required for the cast to the object type `{}`",
932                                   self.ty_to_string(object_ty)));
933             }
934             ObligationCauseCode::RepeatVec => {
935                 err.note("the `Copy` trait is required because the \
936                           repeated element will be copied");
937             }
938             ObligationCauseCode::VariableType(_) => {
939                 err.note("all local variables must have a statically known size");
940             }
941             ObligationCauseCode::ReturnType => {
942                 err.note("the return type of a function must have a \
943                           statically known size");
944             }
945             ObligationCauseCode::AssignmentLhsSized => {
946                 err.note("the left-hand-side of an assignment must have a statically known size");
947             }
948             ObligationCauseCode::StructInitializerSized => {
949                 err.note("structs must have a statically known size to be initialized");
950             }
951             ObligationCauseCode::FieldSized => {
952                 err.note("only the last field of a struct may have a dynamically sized type");
953             }
954             ObligationCauseCode::ConstSized => {
955                 err.note("constant expressions must have a statically known size");
956             }
957             ObligationCauseCode::SharedStatic => {
958                 err.note("shared static variables must have a type that implements `Sync`");
959             }
960             ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
961                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
962                 err.note(&format!("required because it appears within the type `{}`",
963                                   parent_trait_ref.0.self_ty()));
964                 let parent_predicate = parent_trait_ref.to_predicate();
965                 self.note_obligation_cause_code(err,
966                                                 &parent_predicate,
967                                                 &data.parent_code);
968             }
969             ObligationCauseCode::ImplDerivedObligation(ref data) => {
970                 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
971                 err.note(
972                     &format!("required because of the requirements on the impl of `{}` for `{}`",
973                              parent_trait_ref,
974                              parent_trait_ref.0.self_ty()));
975                 let parent_predicate = parent_trait_ref.to_predicate();
976                 self.note_obligation_cause_code(err,
977                                                 &parent_predicate,
978                                                 &data.parent_code);
979             }
980             ObligationCauseCode::CompareImplMethodObligation { .. } => {
981                 err.note(
982                     &format!("the requirement `{}` appears on the impl method \
983                               but not on the corresponding trait method",
984                              predicate));
985             }
986         }
987     }
988
989     fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
990         let current_limit = self.tcx.sess.recursion_limit.get();
991         let suggested_limit = current_limit * 2;
992         err.help(&format!(
993                           "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
994                           suggested_limit));
995     }
996 }
997