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