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.
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.
14 MismatchedProjectionTypes,
16 OutputTypeParameterMismatch,
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};
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);
36 fn report_fulfillment_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
37 error: &FulfillmentError<'tcx>) {
39 FulfillmentErrorCode::CodeSelectionError(ref e) => {
40 report_selection_error(infcx, &error.obligation, e);
42 FulfillmentErrorCode::CodeProjectionError(ref e) => {
43 report_projection_error(infcx, &error.obligation, e);
45 FulfillmentErrorCode::CodeAmbiguity => {
46 maybe_report_ambiguity(infcx, &error.obligation);
51 pub fn report_projection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
52 obligation: &PredicateObligation<'tcx>,
53 error: &MismatchedProjectionTypes<'tcx>)
56 infcx.resolve_type_vars_if_possible(&obligation.predicate);
57 if !predicate.references_error() {
58 infcx.tcx.sess.span_err(
59 obligation.cause.span,
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);
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 {
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| {
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()),
102 format!("the #[rustc_on_unimplemented] \
104 trait definition for {} refers to \
105 non-existent type parameter {}",
115 format!("the #[rustc_on_unimplemented] \
117 trait definition for {} must have named \
119 eg `#[rustc_on_unimplemented = \
121 trait_str).as_slice());
128 // Report only if the format string checks out
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());
145 pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
146 obligation: &PredicateObligation<'tcx>,
147 error: &SelectionError<'tcx>)
150 SelectionError::Overflow => {
151 // We could track the stack here more precisely if we wanted, I imagine.
153 infcx.resolve_type_vars_if_possible(&obligation.predicate);
154 infcx.tcx.sess.span_err(
155 obligation.cause.span,
157 "overflow evaluating the requirement `{}`",
158 predicate.user_string(infcx.tcx)).as_slice());
160 suggest_new_overflow_limit(infcx.tcx, obligation.cause.span);
162 note_obligation_cause(infcx, obligation);
164 SelectionError::Unimplemented => {
165 match obligation.predicate {
166 ty::Predicate::Trait(ref trait_predicate) => {
167 let trait_predicate =
168 infcx.resolve_type_vars_if_possible(trait_predicate);
169 if !trait_predicate.references_error() {
170 let trait_ref = trait_predicate.to_poly_trait_ref();
171 infcx.tcx.sess.span_err(
172 obligation.cause.span,
174 "the trait `{}` is not implemented for the type `{}`",
175 trait_ref.user_string(infcx.tcx),
176 trait_ref.self_ty().user_string(infcx.tcx)).as_slice());
177 // Check if it has a custom "#[rustc_on_unimplemented]" error message,
178 // report with that message if it does
179 let custom_note = report_on_unimplemented(infcx, &*trait_ref.0,
180 obligation.cause.span);
181 if let Some(s) = custom_note {
182 infcx.tcx.sess.span_note(obligation.cause.span,
188 ty::Predicate::Equate(ref predicate) => {
189 let predicate = infcx.resolve_type_vars_if_possible(predicate);
190 let err = infcx.equality_predicate(obligation.cause.span,
191 &predicate).unwrap_err();
192 infcx.tcx.sess.span_err(
193 obligation.cause.span,
195 "the requirement `{}` is not satisfied (`{}`)",
196 predicate.user_string(infcx.tcx),
197 ty::type_err_to_str(infcx.tcx, &err)).as_slice());
200 ty::Predicate::RegionOutlives(ref predicate) => {
201 let predicate = infcx.resolve_type_vars_if_possible(predicate);
202 let err = infcx.region_outlives_predicate(obligation.cause.span,
203 &predicate).unwrap_err();
204 infcx.tcx.sess.span_err(
205 obligation.cause.span,
207 "the requirement `{}` is not satisfied (`{}`)",
208 predicate.user_string(infcx.tcx),
209 ty::type_err_to_str(infcx.tcx, &err)).as_slice());
212 ty::Predicate::Projection(..) |
213 ty::Predicate::TypeOutlives(..) => {
215 infcx.resolve_type_vars_if_possible(&obligation.predicate);
216 infcx.tcx.sess.span_err(
217 obligation.cause.span,
219 "the requirement `{}` is not satisfied",
220 predicate.user_string(infcx.tcx)).as_slice());
224 OutputTypeParameterMismatch(ref expected_trait_ref, ref actual_trait_ref, ref e) => {
225 let expected_trait_ref = infcx.resolve_type_vars_if_possible(&*expected_trait_ref);
226 let actual_trait_ref = infcx.resolve_type_vars_if_possible(&*actual_trait_ref);
227 if !ty::type_is_error(actual_trait_ref.self_ty()) {
228 infcx.tcx.sess.span_err(
229 obligation.cause.span,
231 "type mismatch: the type `{}` implements the trait `{}`, \
232 but the trait `{}` is required ({})",
233 expected_trait_ref.self_ty().user_string(infcx.tcx),
234 expected_trait_ref.user_string(infcx.tcx),
235 actual_trait_ref.user_string(infcx.tcx),
236 ty::type_err_to_str(infcx.tcx, e)).as_slice());
237 note_obligation_cause(infcx, obligation);
243 pub fn maybe_report_ambiguity<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
244 obligation: &PredicateObligation<'tcx>) {
245 // Unable to successfully determine, probably means
246 // insufficient type information, but could mean
247 // ambiguous impls. The latter *ought* to be a
248 // coherence violation, so we don't report it here.
250 let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate);
252 debug!("maybe_report_ambiguity(predicate={}, obligation={})",
253 predicate.repr(infcx.tcx),
254 obligation.repr(infcx.tcx));
257 ty::Predicate::Trait(ref data) => {
258 let trait_ref = data.to_poly_trait_ref();
259 let self_ty = trait_ref.self_ty();
260 let all_types = &trait_ref.substs().types;
261 if all_types.iter().any(|&t| ty::type_is_error(t)) {
262 } else if all_types.iter().any(|&t| ty::type_needs_infer(t)) {
263 // This is kind of a hack: it frequently happens that some earlier
264 // error prevents types from being fully inferred, and then we get
265 // a bunch of uninteresting errors saying something like "<generic
266 // #0> doesn't implement Sized". It may even be true that we
267 // could just skip over all checks where the self-ty is an
268 // inference variable, but I was afraid that there might be an
269 // inference variable created, registered as an obligation, and
270 // then never forced by writeback, and hence by skipping here we'd
271 // be ignoring the fact that we don't KNOW the type works
272 // out. Though even that would probably be harmless, given that
273 // we're only talking about builtin traits, which are known to be
274 // inhabited. But in any case I just threw in this check for
275 // has_errors() to be sure that compilation isn't happening
276 // anyway. In that case, why inundate the user.
277 if !infcx.tcx.sess.has_errors() {
279 infcx.tcx.lang_items.sized_trait()
280 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
282 infcx.tcx.sess.span_err(
283 obligation.cause.span,
285 "unable to infer enough type information about `{}`; \
286 type annotations required",
287 self_ty.user_string(infcx.tcx)).as_slice());
289 infcx.tcx.sess.span_err(
290 obligation.cause.span,
292 "type annotations required: cannot resolve `{}`",
293 predicate.user_string(infcx.tcx)).as_slice());
294 note_obligation_cause(infcx, obligation);
297 } else if !infcx.tcx.sess.has_errors() {
298 // Ambiguity. Coherence should have reported an error.
299 infcx.tcx.sess.span_bug(
300 obligation.cause.span,
302 "coherence failed to report ambiguity: \
303 cannot locate the impl of the trait `{}` for \
305 trait_ref.user_string(infcx.tcx),
306 self_ty.user_string(infcx.tcx)).as_slice());
311 if !infcx.tcx.sess.has_errors() {
312 infcx.tcx.sess.span_err(
313 obligation.cause.span,
315 "type annotations required: cannot resolve `{}`",
316 predicate.user_string(infcx.tcx)).as_slice());
317 note_obligation_cause(infcx, obligation);
323 fn note_obligation_cause<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
324 obligation: &PredicateObligation<'tcx>)
326 note_obligation_cause_code(infcx,
327 &obligation.predicate,
328 obligation.cause.span,
329 &obligation.cause.code);
332 fn note_obligation_cause_code<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
333 _predicate: &ty::Predicate<'tcx>,
335 cause_code: &ObligationCauseCode<'tcx>)
339 ObligationCauseCode::MiscObligation => { }
340 ObligationCauseCode::ItemObligation(item_def_id) => {
341 let item_name = ty::item_path_str(tcx, item_def_id);
344 format!("required by `{}`", item_name).as_slice());
346 ObligationCauseCode::ObjectCastObligation(object_ty) => {
350 "required for the cast to the object type `{}`",
351 infcx.ty_to_string(object_ty)).as_slice());
353 ObligationCauseCode::RepeatVec => {
356 "the `Copy` trait is required because the \
357 repeated element will be copied");
359 ObligationCauseCode::VariableType(_) => {
362 "all local variables must have a statically known size");
364 ObligationCauseCode::ReturnType => {
367 "the return type of a function must have a \
368 statically known size");
370 ObligationCauseCode::AssignmentLhsSized => {
373 "the left-hand-side of an assignment must have a statically known size");
375 ObligationCauseCode::StructInitializerSized => {
378 "structs must have a statically known size to be initialized");
380 ObligationCauseCode::ClosureCapture(var_id, closure_span, builtin_bound) => {
381 let def_id = tcx.lang_items.from_builtin_kind(builtin_bound).unwrap();
382 let trait_name = ty::item_path_str(tcx, def_id);
383 let name = ty::local_var_name_str(tcx, var_id);
384 span_note!(tcx.sess, closure_span,
385 "the closure that captures `{}` requires that all captured variables \
386 implement the trait `{}`",
390 ObligationCauseCode::FieldSized => {
391 span_note!(tcx.sess, cause_span,
392 "only the last field of a struct or enum variant \
393 may have a dynamically sized type")
395 ObligationCauseCode::ObjectSized => {
396 span_note!(tcx.sess, cause_span,
397 "only sized types can be made into objects");
399 ObligationCauseCode::SharedStatic => {
400 span_note!(tcx.sess, cause_span,
401 "shared static variables must have a type that implements `Sync`");
403 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
404 let parent_trait_ref = infcx.resolve_type_vars_if_possible(&data.parent_trait_ref);
405 span_note!(tcx.sess, cause_span,
406 "required because it appears within the type `{}`",
407 parent_trait_ref.0.self_ty().user_string(infcx.tcx));
408 let parent_predicate = parent_trait_ref.as_predicate();
409 note_obligation_cause_code(infcx, &parent_predicate, cause_span, &*data.parent_code);
411 ObligationCauseCode::ImplDerivedObligation(ref data) => {
412 let parent_trait_ref = infcx.resolve_type_vars_if_possible(&data.parent_trait_ref);
413 span_note!(tcx.sess, cause_span,
414 "required because of the requirements on the impl of `{}` for `{}`",
415 parent_trait_ref.user_string(infcx.tcx),
416 parent_trait_ref.0.self_ty().user_string(infcx.tcx));
417 let parent_predicate = parent_trait_ref.as_predicate();
418 note_obligation_cause_code(infcx, &parent_predicate, cause_span, &*data.parent_code);
423 pub fn suggest_new_overflow_limit(tcx: &ty::ctxt, span: Span) {
424 let current_limit = tcx.sess.recursion_limit.get();
425 let suggested_limit = current_limit * 2;
429 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",