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