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 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);
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 {
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| {
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()),
98 span_err!(infcx.tcx.sess, err_sp, E0272,
99 "the #[rustc_on_unimplemented] \
101 trait definition for {} refers to \
102 non-existent type parameter {}",
109 span_err!(infcx.tcx.sess, err_sp, E0273,
110 "the #[rustc_on_unimplemented] \
112 trait definition for {} must have named \
114 eg `#[rustc_on_unimplemented = \
123 // Report only if the format string checks out
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\"]`",
140 pub fn report_selection_error<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
141 obligation: &PredicateObligation<'tcx>,
142 error: &SelectionError<'tcx>)
145 SelectionError::Overflow => {
146 // We could track the stack here more precisely if we wanted, I imagine.
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));
153 suggest_new_overflow_limit(infcx.tcx, obligation.cause.span);
155 note_obligation_cause(infcx, obligation);
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));;
167 match obligation.predicate {
168 ty::Predicate::Trait(ref trait_predicate) => {
169 let trait_predicate =
170 infcx.resolve_type_vars_if_possible(trait_predicate);
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,
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));
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));
209 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
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));
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);
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.
245 let predicate = infcx.resolve_type_vars_if_possible(&obligation.predicate);
247 debug!("maybe_report_ambiguity(predicate={}, obligation={})",
248 predicate.repr(infcx.tcx),
249 obligation.repr(infcx.tcx));
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() {
274 infcx.tcx.lang_items.sized_trait()
275 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
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));
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);
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,
293 "coherence failed to report ambiguity: \
294 cannot locate the impl of the trait `{}` for \
296 trait_ref.user_string(infcx.tcx),
297 self_ty.user_string(infcx.tcx)).as_slice());
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);
312 fn note_obligation_cause<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
313 obligation: &PredicateObligation<'tcx>)
315 note_obligation_cause_code(infcx,
316 &obligation.predicate,
317 obligation.cause.span,
318 &obligation.cause.code);
321 fn note_obligation_cause_code<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>,
322 predicate: &ty::Predicate<'tcx>,
324 cause_code: &ObligationCauseCode<'tcx>)
328 ObligationCauseCode::MiscObligation => { }
329 ObligationCauseCode::ItemObligation(item_def_id) => {
330 let item_name = ty::item_path_str(tcx, item_def_id);
333 format!("required by `{}`", item_name).as_slice());
335 ObligationCauseCode::ObjectCastObligation(object_ty) => {
339 "required for the cast to the object type `{}`",
340 infcx.ty_to_string(object_ty)).as_slice());
342 ObligationCauseCode::RepeatVec => {
345 "the `Copy` trait is required because the \
346 repeated element will be copied");
348 ObligationCauseCode::VariableType(_) => {
351 "all local variables must have a statically known size");
353 ObligationCauseCode::ReturnType => {
356 "the return type of a function must have a \
357 statically known size");
359 ObligationCauseCode::AssignmentLhsSized => {
362 "the left-hand-side of an assignment must have a statically known size");
364 ObligationCauseCode::StructInitializerSized => {
367 "structs must have a statically known size to be initialized");
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 `{}`",
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")
384 ObligationCauseCode::ObjectSized => {
385 span_note!(tcx.sess, cause_span,
386 "only sized types can be made into objects");
388 ObligationCauseCode::SharedStatic => {
389 span_note!(tcx.sess, cause_span,
390 "shared static variables must have a type that implements `Sync`");
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);
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);
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));
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;
424 "consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",