]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/traits/error_reporting.rs
auto merge of #20990 : estsauver/rust/playpen_20732, r=alexcrichton
[rust.git] / src / librustc / middle / 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     ObligationCauseCode,
16     OutputTypeParameterMismatch,
17     PredicateObligation,
18     SelectionError,
19 };
20
21 use fmt_macros::{Parser, Piece, Position};
22 use middle::infer::InferCtxt;
23 use middle::ty::{self, AsPredicate, ReferencesError, ToPolyTraitRef, TraitRef};
24 use std::collections::HashMap;
25 use syntax::codemap::{DUMMY_SP, Span};
26 use syntax::attr::{AttributeMethods, AttrMetaMethods};
27 use util::ppaux::{Repr, UserString};
28
29 pub fn report_fulfillment_errors<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
30                                            errors: &Vec<FulfillmentError<'tcx>>) {
31     for error in errors.iter() {
32         report_fulfillment_error(infcx, error);
33     }
34 }
35
36 fn report_fulfillment_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
37                                       error: &FulfillmentError<'tcx>) {
38     match error.code {
39         FulfillmentErrorCode::CodeSelectionError(ref e) => {
40             report_selection_error(infcx, &error.obligation, e);
41         }
42         FulfillmentErrorCode::CodeProjectionError(ref e) => {
43             report_projection_error(infcx, &error.obligation, e);
44         }
45         FulfillmentErrorCode::CodeAmbiguity => {
46             maybe_report_ambiguity(infcx, &error.obligation);
47         }
48     }
49 }
50
51 pub fn report_projection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
52                                          obligation: &PredicateObligation<'tcx>,
53                                          error: &MismatchedProjectionTypes<'tcx>)
54 {
55     let predicate =
56         infcx.resolve_type_vars_if_possible(&obligation.predicate);
57     if !predicate.references_error() {
58         infcx.tcx.sess.span_err(
59             obligation.cause.span,
60             format!(
61                 "type mismatch resolving `{}`: {}",
62                 predicate.user_string(infcx.tcx),
63                 ty::type_err_to_str(infcx.tcx, &error.err)).as_slice());
64         note_obligation_cause(infcx, obligation);
65     }
66 }
67
68 fn report_on_unimplemented<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
69                                      trait_ref: &TraitRef<'tcx>,
70                                      span: Span) -> Option<String> {
71     let def_id = trait_ref.def_id;
72     let mut report = None;
73     for item in ty::get_attrs(infcx.tcx, def_id).iter() {
74         if item.check_name("rustc_on_unimplemented") {
75             let err_sp = if item.meta().span == DUMMY_SP {
76                 span
77             } else {
78                 item.meta().span
79             };
80             let def = ty::lookup_trait_def(infcx.tcx, def_id);
81             let trait_str = def.trait_ref.user_string(infcx.tcx);
82             if let Some(ref istring) = item.value_str() {
83                 let mut generic_map = def.generics.types.iter_enumerated()
84                                          .map(|(param, i, gen)| {
85                                                (gen.name.as_str().to_string(),
86                                                 trait_ref.substs.types.get(param, i)
87                                                          .user_string(infcx.tcx))
88                                               }).collect::<HashMap<String, String>>();
89                 generic_map.insert("Self".to_string(),
90                                    trait_ref.self_ty().user_string(infcx.tcx));
91                 let parser = Parser::new(istring.get());
92                 let mut errored = false;
93                 let err: String = parser.filter_map(|p| {
94                     match p {
95                         Piece::String(s) => Some(s),
96                         Piece::NextArgument(a) => match a.position {
97                             Position::ArgumentNamed(s) => match generic_map.get(s) {
98                                 Some(val) => Some(val.as_slice()),
99                                 None => {
100                                     infcx.tcx.sess
101                                          .span_err(err_sp,
102                                                    format!("the #[rustc_on_unimplemented] \
103                                                             attribute on \
104                                                             trait definition for {} refers to \
105                                                             non-existent type parameter {}",
106                                                            trait_str, s)
107                                                    .as_slice());
108                                     errored = true;
109                                     None
110                                 }
111                             },
112                             _ => {
113                                 infcx.tcx.sess
114                                      .span_err(err_sp,
115                                                format!("the #[rustc_on_unimplemented] \
116                                                         attribute on \
117                                                         trait definition for {} must have named \
118                                                         format arguments, \
119                                                         eg `#[rustc_on_unimplemented = \
120                                                         \"foo {{T}}\"]`",
121                                                        trait_str).as_slice());
122                                 errored = true;
123                                 None
124                             }
125                         }
126                     }
127                 }).collect();
128                 // Report only if the format string checks out
129                 if !errored {
130                     report = Some(err);
131                 }
132             } else {
133                 infcx.tcx.sess.span_err(err_sp,
134                                         format!("the #[rustc_on_unimplemented] attribute on \
135                                                  trait definition for {} must have a value, \
136                                                  eg `#[rustc_on_unimplemented = \"foo\"]`",
137                                                  trait_str).as_slice());
138             }
139             break;
140         }
141     }
142     report
143 }
144
145 pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
146                                         obligation: &PredicateObligation<'tcx>,
147                                         error: &SelectionError<'tcx>)
148 {
149     match *error {
150         SelectionError::Overflow => {
151             // We could track the stack here more precisely if we wanted, I imagine.
152             let predicate =
153                 infcx.resolve_type_vars_if_possible(&obligation.predicate);
154             infcx.tcx.sess.span_err(
155                 obligation.cause.span,
156                 format!(
157                     "overflow evaluating the requirement `{}`",
158                     predicate.user_string(infcx.tcx)).as_slice());
159
160             suggest_new_overflow_limit(infcx.tcx, obligation.cause.span);
161
162             note_obligation_cause(infcx, obligation);
163         }
164
165         SelectionError::Unimplemented => {
166             match &obligation.cause.code {
167                 &ObligationCauseCode::CompareImplMethodObligation => {
168                     infcx.tcx.sess.span_err(
169                         obligation.cause.span,
170                         format!(
171                             "the requirement `{}` appears on the impl \
172                             method but not on the corresponding trait method",
173                             obligation.predicate.user_string(infcx.tcx)).as_slice());
174                 }
175                 _ => {
176                     match obligation.predicate {
177                         ty::Predicate::Trait(ref trait_predicate) => {
178                             let trait_predicate =
179                                 infcx.resolve_type_vars_if_possible(trait_predicate);
180
181                             if !trait_predicate.references_error() {
182                                 let trait_ref = trait_predicate.to_poly_trait_ref();
183                                 infcx.tcx.sess.span_err(
184                                     obligation.cause.span,
185                                     format!(
186                                         "the trait `{}` is not implemented for the type `{}`",
187                                         trait_ref.user_string(infcx.tcx),
188                                         trait_ref.self_ty().user_string(infcx.tcx)).as_slice());
189                                 // Check if it has a custom "#[rustc_on_unimplemented]"
190                                 // error message, report with that message if it does
191                                 let custom_note = report_on_unimplemented(infcx, &*trait_ref.0,
192                                                                           obligation.cause.span);
193                                 if let Some(s) = custom_note {
194                                     infcx.tcx.sess.span_note(obligation.cause.span,
195                                                              s.as_slice());
196                                 }
197                             }
198                         }
199
200                         ty::Predicate::Equate(ref predicate) => {
201                             let predicate = infcx.resolve_type_vars_if_possible(predicate);
202                             let err = infcx.equality_predicate(obligation.cause.span,
203                                                                &predicate).unwrap_err();
204                             infcx.tcx.sess.span_err(
205                                 obligation.cause.span,
206                                 format!(
207                                     "the requirement `{}` is not satisfied (`{}`)",
208                                     predicate.user_string(infcx.tcx),
209                                     ty::type_err_to_str(infcx.tcx, &err)).as_slice());
210                         }
211
212                         ty::Predicate::RegionOutlives(ref predicate) => {
213                             let predicate = infcx.resolve_type_vars_if_possible(predicate);
214                             let err = infcx.region_outlives_predicate(obligation.cause.span,
215                                                                       &predicate).unwrap_err();
216                             infcx.tcx.sess.span_err(
217                                 obligation.cause.span,
218                                 format!(
219                                     "the requirement `{}` is not satisfied (`{}`)",
220                                     predicate.user_string(infcx.tcx),
221                                     ty::type_err_to_str(infcx.tcx, &err)).as_slice());
222                         }
223
224                         ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
225                                 let predicate =
226                                     infcx.resolve_type_vars_if_possible(&obligation.predicate);
227                                 infcx.tcx.sess.span_err(
228                                     obligation.cause.span,
229                                     format!(
230                                         "the requirement `{}` is not satisfied",
231                                         predicate.user_string(infcx.tcx)).as_slice());
232                         }
233                     }
234                 }
235             }
236         }
237
238         OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
239             let expected_trait_ref = infcx.resolve_type_vars_if_possible(&*expected_trait_ref);
240             let actual_trait_ref = infcx.resolve_type_vars_if_possible(&*actual_trait_ref);
241             if !ty::type_is_error(actual_trait_ref.self_ty()) {
242                 infcx.tcx.sess.span_err(
243                     obligation.cause.span,
244                     format!(
245                         "type mismatch: the type `{}` implements the trait `{}`, \
246                         but the trait `{}` is required ({})",
247                         expected_trait_ref.self_ty().user_string(infcx.tcx),
248                         expected_trait_ref.user_string(infcx.tcx),
249                         actual_trait_ref.user_string(infcx.tcx),
250                         ty::type_err_to_str(infcx.tcx, e)).as_slice());
251                     note_obligation_cause(infcx, obligation);
252             }
253         }
254     }
255 }
256
257 pub fn maybe_report_ambiguity<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
258                                         obligation: &PredicateObligation<'tcx>) {
259     // Unable to successfully determine, probably means
260     // insufficient type information, but could mean
261     // ambiguous impls. The latter *ought* to be a
262     // coherence violation, so we don't report it here.
263
264     let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate);
265
266     debug!("maybe_report_ambiguity(predicate={}, obligation={})",
267            predicate.repr(infcx.tcx),
268            obligation.repr(infcx.tcx));
269
270     match predicate {
271         ty::Predicate::Trait(ref data) => {
272             let trait_ref = data.to_poly_trait_ref();
273             let self_ty = trait_ref.self_ty();
274             let all_types = &trait_ref.substs().types;
275             if all_types.iter().any(|&t| ty::type_is_error(t)) {
276             } else if all_types.iter().any(|&t| ty::type_needs_infer(t)) {
277                 // This is kind of a hack: it frequently happens that some earlier
278                 // error prevents types from being fully inferred, and then we get
279                 // a bunch of uninteresting errors saying something like "<generic
280                 // #0> doesn't implement Sized".  It may even be true that we
281                 // could just skip over all checks where the self-ty is an
282                 // inference variable, but I was afraid that there might be an
283                 // inference variable created, registered as an obligation, and
284                 // then never forced by writeback, and hence by skipping here we'd
285                 // be ignoring the fact that we don't KNOW the type works
286                 // out. Though even that would probably be harmless, given that
287                 // we're only talking about builtin traits, which are known to be
288                 // inhabited. But in any case I just threw in this check for
289                 // has_errors() to be sure that compilation isn't happening
290                 // anyway. In that case, why inundate the user.
291                 if !infcx.tcx.sess.has_errors() {
292                     if
293                         infcx.tcx.lang_items.sized_trait()
294                         .map_or(false, |sized_id| sized_id == trait_ref.def_id())
295                     {
296                         infcx.tcx.sess.span_err(
297                             obligation.cause.span,
298                             format!(
299                                 "unable to infer enough type information about `{}`; \
300                                  type annotations required",
301                                 self_ty.user_string(infcx.tcx)).as_slice());
302                     } else {
303                         infcx.tcx.sess.span_err(
304                             obligation.cause.span,
305                             format!(
306                                 "type annotations required: cannot resolve `{}`",
307                                 predicate.user_string(infcx.tcx)).as_slice());
308                         note_obligation_cause(infcx, obligation);
309                     }
310                 }
311             } else if !infcx.tcx.sess.has_errors() {
312                 // Ambiguity. Coherence should have reported an error.
313                 infcx.tcx.sess.span_bug(
314                     obligation.cause.span,
315                     format!(
316                         "coherence failed to report ambiguity: \
317                          cannot locate the impl of the trait `{}` for \
318                          the type `{}`",
319                         trait_ref.user_string(infcx.tcx),
320                         self_ty.user_string(infcx.tcx)).as_slice());
321             }
322         }
323
324         _ => {
325             if !infcx.tcx.sess.has_errors() {
326                 infcx.tcx.sess.span_err(
327                     obligation.cause.span,
328                     format!(
329                         "type annotations required: cannot resolve `{}`",
330                         predicate.user_string(infcx.tcx)).as_slice());
331                 note_obligation_cause(infcx, obligation);
332             }
333         }
334     }
335 }
336
337 fn note_obligation_cause<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
338                                    obligation: &PredicateObligation<'tcx>)
339 {
340     note_obligation_cause_code(infcx,
341                                &obligation.predicate,
342                                obligation.cause.span,
343                                &obligation.cause.code);
344 }
345
346 fn note_obligation_cause_code<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
347                                         predicate: &ty::Predicate<'tcx>,
348                                         cause_span: Span,
349                                         cause_code: &ObligationCauseCode<'tcx>)
350 {
351     let tcx = infcx.tcx;
352     match *cause_code {
353         ObligationCauseCode::MiscObligation => { }
354         ObligationCauseCode::ItemObligation(item_def_id) => {
355             let item_name = ty::item_path_str(tcx, item_def_id);
356             tcx.sess.span_note(
357                 cause_span,
358                 format!("required by `{}`", item_name).as_slice());
359         }
360         ObligationCauseCode::ObjectCastObligation(object_ty) => {
361             tcx.sess.span_note(
362                 cause_span,
363                 format!(
364                     "required for the cast to the object type `{}`",
365                     infcx.ty_to_string(object_ty)).as_slice());
366         }
367         ObligationCauseCode::RepeatVec => {
368             tcx.sess.span_note(
369                 cause_span,
370                 "the `Copy` trait is required because the \
371                  repeated element will be copied");
372         }
373         ObligationCauseCode::VariableType(_) => {
374             tcx.sess.span_note(
375                 cause_span,
376                 "all local variables must have a statically known size");
377         }
378         ObligationCauseCode::ReturnType => {
379             tcx.sess.span_note(
380                 cause_span,
381                 "the return type of a function must have a \
382                  statically known size");
383         }
384         ObligationCauseCode::AssignmentLhsSized => {
385             tcx.sess.span_note(
386                 cause_span,
387                 "the left-hand-side of an assignment must have a statically known size");
388         }
389         ObligationCauseCode::StructInitializerSized => {
390             tcx.sess.span_note(
391                 cause_span,
392                 "structs must have a statically known size to be initialized");
393         }
394         ObligationCauseCode::ClosureCapture(var_id, closure_span, builtin_bound) => {
395             let def_id = tcx.lang_items.from_builtin_kind(builtin_bound).unwrap();
396             let trait_name = ty::item_path_str(tcx, def_id);
397             let name = ty::local_var_name_str(tcx, var_id);
398             span_note!(tcx.sess, closure_span,
399                        "the closure that captures `{}` requires that all captured variables \
400                        implement the trait `{}`",
401                        name,
402                        trait_name);
403         }
404         ObligationCauseCode::FieldSized => {
405             span_note!(tcx.sess, cause_span,
406                        "only the last field of a struct or enum variant \
407                        may have a dynamically sized type")
408         }
409         ObligationCauseCode::ObjectSized => {
410             span_note!(tcx.sess, cause_span,
411                        "only sized types can be made into objects");
412         }
413         ObligationCauseCode::SharedStatic => {
414             span_note!(tcx.sess, cause_span,
415                        "shared static variables must have a type that implements `Sync`");
416         }
417         ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
418             let parent_trait_ref = infcx.resolve_type_vars_if_possible(&data.parent_trait_ref);
419             span_note!(tcx.sess, cause_span,
420                        "required because it appears within the type `{}`",
421                        parent_trait_ref.0.self_ty().user_string(infcx.tcx));
422             let parent_predicate = parent_trait_ref.as_predicate();
423             note_obligation_cause_code(infcx, &parent_predicate, cause_span, &*data.parent_code);
424         }
425         ObligationCauseCode::ImplDerivedObligation(ref data) => {
426             let parent_trait_ref = infcx.resolve_type_vars_if_possible(&data.parent_trait_ref);
427             span_note!(tcx.sess, cause_span,
428                        "required because of the requirements on the impl of `{}` for `{}`",
429                        parent_trait_ref.user_string(infcx.tcx),
430                        parent_trait_ref.0.self_ty().user_string(infcx.tcx));
431             let parent_predicate = parent_trait_ref.as_predicate();
432             note_obligation_cause_code(infcx, &parent_predicate, cause_span, &*data.parent_code);
433         }
434         ObligationCauseCode::CompareImplMethodObligation => {
435             span_note!(tcx.sess, cause_span,
436                       "the requirement `{}` appears on the impl method\
437                       but not on the corresponding trait method",
438                       predicate.user_string(infcx.tcx));
439         }
440     }
441 }
442
443 pub fn suggest_new_overflow_limit(tcx: &ty::ctxt, span: Span) {
444     let current_limit = tcx.sess.recursion_limit.get();
445     let suggested_limit = current_limit * 2;
446     tcx.sess.span_note(
447         span,
448         &format!(
449             "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
450             suggested_limit)[]);
451 }