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