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::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>) -> 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| {
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()),
94 .span_err(item.meta().span,
95 format!("there is no type parameter \
98 .user_string(infcx.tcx))
105 infcx.tcx.sess.span_err(item.meta().span,
106 "only named substitution \
107 parameters are allowed");
114 // Report only if the format string checks out
119 infcx.tcx.sess.span_err(item.meta().span,
120 "this attribute must have a value, \
121 eg `#[on_unimplemented = \"foo\"]`")
131 pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
132 obligation: &PredicateObligation<'tcx>,
133 error: &SelectionError<'tcx>)
136 SelectionError::Overflow => {
137 // We could track the stack here more precisely if we wanted, I imagine.
139 infcx.resolve_type_vars_if_possible(&obligation.predicate);
140 infcx.tcx.sess.span_err(
141 obligation.cause.span,
143 "overflow evaluating the requirement `{}`",
144 predicate.user_string(infcx.tcx)).as_slice());
146 suggest_new_overflow_limit(infcx.tcx, obligation.cause.span);
148 note_obligation_cause(infcx, obligation);
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,
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,
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,
181 "the requirement `{}` is not satisfied (`{}`)",
182 predicate.user_string(infcx.tcx),
183 ty::type_err_to_str(infcx.tcx, &err)).as_slice());
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,
193 "the requirement `{}` is not satisfied (`{}`)",
194 predicate.user_string(infcx.tcx),
195 ty::type_err_to_str(infcx.tcx, &err)).as_slice());
198 ty::Predicate::Projection(..) |
199 ty::Predicate::TypeOutlives(..) => {
201 infcx.resolve_type_vars_if_possible(&obligation.predicate);
202 infcx.tcx.sess.span_err(
203 obligation.cause.span,
205 "the requirement `{}` is not satisfied",
206 predicate.user_string(infcx.tcx)).as_slice());
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,
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);
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.
236 let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate);
238 debug!("maybe_report_ambiguity(predicate={}, obligation={})",
239 predicate.repr(infcx.tcx),
240 obligation.repr(infcx.tcx));
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() {
265 infcx.tcx.lang_items.sized_trait()
266 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
268 infcx.tcx.sess.span_err(
269 obligation.cause.span,
271 "unable to infer enough type information about `{}`; \
272 type annotations required",
273 self_ty.user_string(infcx.tcx)).as_slice());
275 infcx.tcx.sess.span_err(
276 obligation.cause.span,
278 "type annotations required: cannot resolve `{}`",
279 predicate.user_string(infcx.tcx)).as_slice());
280 note_obligation_cause(infcx, obligation);
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,
288 "coherence failed to report ambiguity: \
289 cannot locate the impl of the trait `{}` for \
291 trait_ref.user_string(infcx.tcx),
292 self_ty.user_string(infcx.tcx)).as_slice());
297 if !infcx.tcx.sess.has_errors() {
298 infcx.tcx.sess.span_err(
299 obligation.cause.span,
301 "type annotations required: cannot resolve `{}`",
302 predicate.user_string(infcx.tcx)).as_slice());
303 note_obligation_cause(infcx, obligation);
309 fn note_obligation_cause<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
310 obligation: &PredicateObligation<'tcx>)
312 note_obligation_cause_code(infcx,
313 &obligation.predicate,
314 obligation.cause.span,
315 &obligation.cause.code);
318 fn note_obligation_cause_code<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
319 _predicate: &ty::Predicate<'tcx>,
321 cause_code: &ObligationCauseCode<'tcx>)
325 ObligationCauseCode::MiscObligation => { }
326 ObligationCauseCode::ItemObligation(item_def_id) => {
327 let item_name = ty::item_path_str(tcx, item_def_id);
330 format!("required by `{}`", item_name).as_slice());
332 ObligationCauseCode::ObjectCastObligation(object_ty) => {
336 "required for the cast to the object type `{}`",
337 infcx.ty_to_string(object_ty)).as_slice());
339 ObligationCauseCode::RepeatVec => {
342 "the `Copy` trait is required because the \
343 repeated element will be copied");
345 ObligationCauseCode::VariableType(_) => {
348 "all local variables must have a statically known size");
350 ObligationCauseCode::ReturnType => {
353 "the return type of a function must have a \
354 statically known size");
356 ObligationCauseCode::AssignmentLhsSized => {
359 "the left-hand-side of an assignment must have a statically known size");
361 ObligationCauseCode::StructInitializerSized => {
364 "structs must have a statically known size to be initialized");
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 `{}`",
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")
381 ObligationCauseCode::ObjectSized => {
382 span_note!(tcx.sess, cause_span,
383 "only sized types can be made into objects");
385 ObligationCauseCode::SharedStatic => {
386 span_note!(tcx.sess, cause_span,
387 "shared static variables must have a type that implements `Sync`");
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);
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);
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;
415 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",