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,
18 OnUnimplementedDirective,
20 OutputTypeParameterMismatch,
26 ObjectSafetyViolation,
30 use errors::{Applicability, DiagnosticBuilder};
32 use hir::def_id::DefId;
33 use infer::{self, InferCtxt};
34 use infer::type_variable::TypeVariableOrigin;
37 use session::DiagnosticMessageId;
38 use ty::{self, AdtKind, ToPredicate, ToPolyTraitRef, Ty, TyCtxt, TypeFoldable};
39 use ty::GenericParamDefKind;
40 use ty::error::ExpectedFound;
42 use ty::fold::TypeFolder;
44 use ty::SubtypePredicate;
45 use util::nodemap::{FxHashMap, FxHashSet};
47 use syntax_pos::{DUMMY_SP, Span};
49 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
50 pub fn report_fulfillment_errors(&self,
51 errors: &Vec<FulfillmentError<'tcx>>,
52 body_id: Option<hir::BodyId>,
53 fallback_has_occurred: bool) {
55 struct ErrorDescriptor<'tcx> {
56 predicate: ty::Predicate<'tcx>,
57 index: Option<usize>, // None if this is an old error
60 let mut error_map : FxHashMap<_, _> =
61 self.reported_trait_errors.borrow().iter().map(|(&span, predicates)| {
62 (span, predicates.iter().map(|predicate| ErrorDescriptor {
63 predicate: predicate.clone(),
68 for (index, error) in errors.iter().enumerate() {
69 error_map.entry(error.obligation.cause.span).or_insert(Vec::new()).push(
71 predicate: error.obligation.predicate.clone(),
75 self.reported_trait_errors.borrow_mut()
76 .entry(error.obligation.cause.span).or_insert(Vec::new())
77 .push(error.obligation.predicate.clone());
80 // We do this in 2 passes because we want to display errors in order, tho
81 // maybe it *is* better to sort errors by span or something.
82 let mut is_suppressed: Vec<bool> = errors.iter().map(|_| false).collect();
83 for (_, error_set) in error_map.iter() {
84 // We want to suppress "duplicate" errors with the same span.
85 for error in error_set {
86 if let Some(index) = error.index {
87 // Suppress errors that are either:
88 // 1) strictly implied by another error.
89 // 2) implied by an error with a smaller index.
90 for error2 in error_set {
91 if error2.index.map_or(false, |index2| is_suppressed[index2]) {
92 // Avoid errors being suppressed by already-suppressed
93 // errors, to prevent all errors from being suppressed
98 if self.error_implies(&error2.predicate, &error.predicate) &&
99 !(error2.index >= error.index &&
100 self.error_implies(&error.predicate, &error2.predicate))
102 info!("skipping {:?} (implied by {:?})", error, error2);
103 is_suppressed[index] = true;
111 for (error, suppressed) in errors.iter().zip(is_suppressed) {
113 self.report_fulfillment_error(error, body_id, fallback_has_occurred);
118 // returns if `cond` not occurring implies that `error` does not occur - i.e. that
119 // `error` occurring implies that `cond` occurs.
120 fn error_implies(&self,
121 cond: &ty::Predicate<'tcx>,
122 error: &ty::Predicate<'tcx>)
129 let (cond, error) = match (cond, error) {
130 (&ty::Predicate::Trait(..), &ty::Predicate::Trait(ref error))
133 // FIXME: make this work in other cases too.
138 for implication in super::elaborate_predicates(self.tcx, vec![cond.clone()]) {
139 if let ty::Predicate::Trait(implication) = implication {
140 let error = error.to_poly_trait_ref();
141 let implication = implication.to_poly_trait_ref();
142 // FIXME: I'm just not taking associated types at all here.
143 // Eventually I'll need to implement param-env-aware
144 // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
145 let param_env = ty::ParamEnv::empty();
146 if let Ok(_) = self.can_sub(param_env, error, implication) {
147 debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
156 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>,
157 body_id: Option<hir::BodyId>,
158 fallback_has_occurred: bool) {
159 debug!("report_fulfillment_errors({:?})", error);
161 FulfillmentErrorCode::CodeSelectionError(ref e) => {
162 self.report_selection_error(&error.obligation, e, fallback_has_occurred);
164 FulfillmentErrorCode::CodeProjectionError(ref e) => {
165 self.report_projection_error(&error.obligation, e);
167 FulfillmentErrorCode::CodeAmbiguity => {
168 self.maybe_report_ambiguity(&error.obligation, body_id);
170 FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
171 self.report_mismatched_types(&error.obligation.cause,
172 expected_found.expected,
173 expected_found.found,
180 fn report_projection_error(&self,
181 obligation: &PredicateObligation<'tcx>,
182 error: &MismatchedProjectionTypes<'tcx>)
185 self.resolve_type_vars_if_possible(&obligation.predicate);
187 if predicate.references_error() {
193 let mut err = &error.err;
194 let mut values = None;
196 // try to find the mismatched types to report the error with.
198 // this can fail if the problem was higher-ranked, in which
199 // cause I have no idea for a good error message.
200 if let ty::Predicate::Projection(ref data) = predicate {
201 let mut selcx = SelectionContext::new(self);
202 let (data, _) = self.replace_late_bound_regions_with_fresh_var(
203 obligation.cause.span,
204 infer::LateBoundRegionConversionTime::HigherRankedType,
206 let mut obligations = vec![];
207 let normalized_ty = super::normalize_projection_type(
209 obligation.param_env,
211 obligation.cause.clone(),
215 if let Err(error) = self.at(&obligation.cause, obligation.param_env)
216 .eq(normalized_ty, data.ty) {
217 values = Some(infer::ValuePairs::Types(ExpectedFound {
218 expected: normalized_ty,
226 let msg = format!("type mismatch resolving `{}`", predicate);
227 let error_id = (DiagnosticMessageId::ErrorId(271),
228 Some(obligation.cause.span), msg.clone());
229 let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
231 let mut diag = struct_span_err!(
232 self.tcx.sess, obligation.cause.span, E0271,
233 "type mismatch resolving `{}`", predicate
235 self.note_type_err(&mut diag, &obligation.cause, None, values, err);
236 self.note_obligation_cause(&mut diag, obligation);
242 fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
243 /// returns the fuzzy category of a given type, or None
244 /// if the type can be equated to any type.
245 fn type_category<'tcx>(t: Ty<'tcx>) -> Option<u32> {
247 ty::TyBool => Some(0),
248 ty::TyChar => Some(1),
249 ty::TyStr => Some(2),
250 ty::TyInt(..) | ty::TyUint(..) | ty::TyInfer(ty::IntVar(..)) => Some(3),
251 ty::TyFloat(..) | ty::TyInfer(ty::FloatVar(..)) => Some(4),
252 ty::TyRef(..) | ty::TyRawPtr(..) => Some(5),
253 ty::TyArray(..) | ty::TySlice(..) => Some(6),
254 ty::TyFnDef(..) | ty::TyFnPtr(..) => Some(7),
255 ty::TyDynamic(..) => Some(8),
256 ty::TyClosure(..) => Some(9),
257 ty::TyTuple(..) => Some(10),
258 ty::TyProjection(..) => Some(11),
259 ty::TyParam(..) => Some(12),
260 ty::TyAnon(..) => Some(13),
261 ty::TyNever => Some(14),
262 ty::TyAdt(adt, ..) => match adt.adt_kind() {
263 AdtKind::Struct => Some(15),
264 AdtKind::Union => Some(16),
265 AdtKind::Enum => Some(17),
267 ty::TyGenerator(..) => Some(18),
268 ty::TyForeign(..) => Some(19),
269 ty::TyGeneratorWitness(..) => Some(20),
270 ty::TyInfer(..) | ty::TyError => None
274 match (type_category(a), type_category(b)) {
275 (Some(cat_a), Some(cat_b)) => match (&a.sty, &b.sty) {
276 (&ty::TyAdt(def_a, _), &ty::TyAdt(def_b, _)) => def_a == def_b,
279 // infer and error can be equated to all types
284 fn impl_similar_to(&self,
285 trait_ref: ty::PolyTraitRef<'tcx>,
286 obligation: &PredicateObligation<'tcx>)
290 let param_env = obligation.param_env;
291 let trait_ref = tcx.erase_late_bound_regions(&trait_ref);
292 let trait_self_ty = trait_ref.self_ty();
294 let mut self_match_impls = vec![];
295 let mut fuzzy_match_impls = vec![];
297 self.tcx.for_each_relevant_impl(
298 trait_ref.def_id, trait_self_ty, |def_id| {
299 let impl_substs = self.fresh_substs_for_item(obligation.cause.span, def_id);
300 let impl_trait_ref = tcx
301 .impl_trait_ref(def_id)
303 .subst(tcx, impl_substs);
305 let impl_self_ty = impl_trait_ref.self_ty();
307 if let Ok(..) = self.can_eq(param_env, trait_self_ty, impl_self_ty) {
308 self_match_impls.push(def_id);
310 if trait_ref.substs.types().skip(1)
311 .zip(impl_trait_ref.substs.types().skip(1))
312 .all(|(u,v)| self.fuzzy_match_tys(u, v))
314 fuzzy_match_impls.push(def_id);
319 let impl_def_id = if self_match_impls.len() == 1 {
321 } else if fuzzy_match_impls.len() == 1 {
327 if tcx.has_attr(impl_def_id, "rustc_on_unimplemented") {
334 fn on_unimplemented_note(
336 trait_ref: ty::PolyTraitRef<'tcx>,
337 obligation: &PredicateObligation<'tcx>) ->
340 let def_id = self.impl_similar_to(trait_ref, obligation)
341 .unwrap_or(trait_ref.def_id());
342 let trait_ref = *trait_ref.skip_binder();
344 let mut flags = vec![];
345 match obligation.cause.code {
346 ObligationCauseCode::BuiltinDerivedObligation(..) |
347 ObligationCauseCode::ImplDerivedObligation(..) => {}
349 // this is a "direct", user-specified, rather than derived,
351 flags.push(("direct".to_string(), None));
355 if let ObligationCauseCode::ItemObligation(item) = obligation.cause.code {
356 // FIXME: maybe also have some way of handling methods
357 // from other traits? That would require name resolution,
358 // which we might want to be some sort of hygienic.
360 // Currently I'm leaving it for what I need for `try`.
361 if self.tcx.trait_of_item(item) == Some(trait_ref.def_id) {
362 let method = self.tcx.item_name(item);
363 flags.push(("from_method".to_string(), None));
364 flags.push(("from_method".to_string(), Some(method.to_string())));
368 if let Some(k) = obligation.cause.span.compiler_desugaring_kind() {
369 flags.push(("from_desugaring".to_string(), None));
370 flags.push(("from_desugaring".to_string(), Some(k.name().to_string())));
372 let generics = self.tcx.generics_of(def_id);
373 let self_ty = trait_ref.self_ty();
374 // This is also included through the generics list as `Self`,
375 // but the parser won't allow you to use it
376 flags.push(("_Self".to_string(), Some(self_ty.to_string())));
377 if let Some(def) = self_ty.ty_adt_def() {
378 // We also want to be able to select self's original
379 // signature with no type arguments resolved
380 flags.push(("_Self".to_string(), Some(self.tcx.type_of(def.did).to_string())));
383 for param in generics.params.iter() {
384 let value = match param.kind {
385 GenericParamDefKind::Type {..} => {
386 trait_ref.substs[param.index as usize].to_string()
388 GenericParamDefKind::Lifetime => continue,
390 let name = param.name.to_string();
391 flags.push((name, Some(value)));
394 if let Some(true) = self_ty.ty_to_def_id().map(|def_id| def_id.is_local()) {
395 flags.push(("crate_local".to_string(), None));
398 if let Ok(Some(command)) = OnUnimplementedDirective::of_item(
399 self.tcx, trait_ref.def_id, def_id
401 command.evaluate(self.tcx, trait_ref, &flags[..])
403 OnUnimplementedNote::empty()
407 fn find_similar_impl_candidates(&self,
408 trait_ref: ty::PolyTraitRef<'tcx>)
409 -> Vec<ty::TraitRef<'tcx>>
411 let simp = fast_reject::simplify_type(self.tcx,
412 trait_ref.skip_binder().self_ty(),
414 let mut impl_candidates = Vec::new();
417 Some(simp) => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
418 let imp = self.tcx.impl_trait_ref(def_id).unwrap();
419 let imp_simp = fast_reject::simplify_type(self.tcx,
422 if let Some(imp_simp) = imp_simp {
423 if simp != imp_simp {
427 impl_candidates.push(imp);
429 None => self.tcx.for_each_impl(trait_ref.def_id(), |def_id| {
430 impl_candidates.push(
431 self.tcx.impl_trait_ref(def_id).unwrap());
437 fn report_similar_impl_candidates(&self,
438 impl_candidates: Vec<ty::TraitRef<'tcx>>,
439 err: &mut DiagnosticBuilder)
441 if impl_candidates.is_empty() {
445 let end = if impl_candidates.len() <= 5 {
446 impl_candidates.len()
451 let normalize = |candidate| self.tcx.global_tcx().infer_ctxt().enter(|ref infcx| {
452 let normalized = infcx
453 .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
454 .normalize(candidate)
457 Some(normalized) => format!("\n {:?}", normalized.value),
458 None => format!("\n {:?}", candidate),
462 err.help(&format!("the following implementations were found:{}{}",
463 &impl_candidates[0..end].iter().map(normalize).collect::<String>(),
464 if impl_candidates.len() > 5 {
465 format!("\nand {} others", impl_candidates.len() - 4)
472 /// Reports that an overflow has occurred and halts compilation. We
473 /// halt compilation unconditionally because it is important that
474 /// overflows never be masked -- they basically represent computations
475 /// whose result could not be truly determined and thus we can't say
476 /// if the program type checks or not -- and they are unusual
477 /// occurrences in any case.
478 pub fn report_overflow_error<T>(&self,
479 obligation: &Obligation<'tcx, T>,
480 suggest_increasing_limit: bool) -> !
481 where T: fmt::Display + TypeFoldable<'tcx>
484 self.resolve_type_vars_if_possible(&obligation.predicate);
485 let mut err = struct_span_err!(self.tcx.sess, obligation.cause.span, E0275,
486 "overflow evaluating the requirement `{}`",
489 if suggest_increasing_limit {
490 self.suggest_new_overflow_limit(&mut err);
493 self.note_obligation_cause(&mut err, obligation);
496 self.tcx.sess.abort_if_errors();
500 /// Reports that a cycle was detected which led to overflow and halts
501 /// compilation. This is equivalent to `report_overflow_error` except
502 /// that we can give a more helpful error message (and, in particular,
503 /// we do not suggest increasing the overflow limit, which is not
505 pub fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
506 let cycle = self.resolve_type_vars_if_possible(&cycle.to_owned());
507 assert!(cycle.len() > 0);
509 debug!("report_overflow_error_cycle: cycle={:?}", cycle);
511 self.report_overflow_error(&cycle[0], false);
514 pub fn report_extra_impl_obligation(&self,
516 item_name: ast::Name,
517 _impl_item_def_id: DefId,
518 trait_item_def_id: DefId,
519 requirement: &dyn fmt::Display)
520 -> DiagnosticBuilder<'tcx>
522 let msg = "impl has stricter requirements than trait";
523 let sp = self.tcx.sess.codemap().def_span(error_span);
525 let mut err = struct_span_err!(self.tcx.sess, sp, E0276, "{}", msg);
527 if let Some(trait_item_span) = self.tcx.hir.span_if_local(trait_item_def_id) {
528 let span = self.tcx.sess.codemap().def_span(trait_item_span);
529 err.span_label(span, format!("definition of `{}` from trait", item_name));
532 err.span_label(sp, format!("impl has extra requirement {}", requirement));
538 /// Get the parent trait chain start
539 fn get_parent_trait_ref(&self, code: &ObligationCauseCode<'tcx>) -> Option<String> {
541 &ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
542 let parent_trait_ref = self.resolve_type_vars_if_possible(
543 &data.parent_trait_ref);
544 match self.get_parent_trait_ref(&data.parent_code) {
546 None => Some(format!("{}", parent_trait_ref.skip_binder().self_ty())),
553 pub fn report_selection_error(&self,
554 obligation: &PredicateObligation<'tcx>,
555 error: &SelectionError<'tcx>,
556 fallback_has_occurred: bool)
558 let span = obligation.cause.span;
560 let mut err = match *error {
561 SelectionError::Unimplemented => {
562 if let ObligationCauseCode::CompareImplMethodObligation {
563 item_name, impl_item_def_id, trait_item_def_id,
564 } = obligation.cause.code {
565 self.report_extra_impl_obligation(
570 &format!("`{}`", obligation.predicate))
574 match obligation.predicate {
575 ty::Predicate::Trait(ref trait_predicate) => {
576 let trait_predicate =
577 self.resolve_type_vars_if_possible(trait_predicate);
579 if self.tcx.sess.has_errors() && trait_predicate.references_error() {
582 let trait_ref = trait_predicate.to_poly_trait_ref();
583 let (post_message, pre_message) =
584 self.get_parent_trait_ref(&obligation.cause.code)
585 .map(|t| (format!(" in `{}`", t), format!("within `{}`, ", t)))
586 .unwrap_or((String::new(), String::new()));
588 let OnUnimplementedNote { message, label, note }
589 = self.on_unimplemented_note(trait_ref, obligation);
590 let have_alt_message = message.is_some() || label.is_some();
592 let mut err = struct_span_err!(
597 message.unwrap_or_else(|| {
598 format!("the trait bound `{}` is not satisfied{}",
599 trait_ref.to_predicate(), post_message)
603 if obligation.cause.code == ObligationCauseCode::MainFunctionType {
604 "consider using `()`, or a `Result`".to_owned()
606 format!("{}the trait `{}` is not implemented for `{}`",
612 if let Some(ref s) = label {
613 // If it has a custom "#[rustc_on_unimplemented]"
614 // error message, let's display it as the label!
615 err.span_label(span, s.as_str());
616 err.help(&explanation);
618 err.span_label(span, explanation);
620 if let Some(ref s) = note {
621 // If it has a custom "#[rustc_on_unimplemented]" note, let's display it
622 err.note(s.as_str());
625 self.suggest_borrow_on_unsized_slice(&obligation.cause.code, &mut err);
626 self.suggest_remove_reference(&obligation, &mut err, &trait_ref);
628 // Try to report a help message
629 if !trait_ref.has_infer_types() &&
630 self.predicate_can_apply(obligation.param_env, trait_ref) {
631 // If a where-clause may be useful, remind the
632 // user that they can add it.
634 // don't display an on-unimplemented note, as
635 // these notes will often be of the form
636 // "the type `T` can't be frobnicated"
637 // which is somewhat confusing.
638 err.help(&format!("consider adding a `where {}` bound",
639 trait_ref.to_predicate()));
640 } else if !have_alt_message {
641 // Can't show anything else useful, try to find similar impls.
642 let impl_candidates = self.find_similar_impl_candidates(trait_ref);
643 self.report_similar_impl_candidates(impl_candidates, &mut err);
646 // If this error is due to `!: Trait` not implemented but `(): Trait` is
647 // implemented, and fallback has occured, then it could be due to a
648 // variable that used to fallback to `()` now falling back to `!`. Issue a
649 // note informing about the change in behaviour.
650 if trait_predicate.skip_binder().self_ty().is_never()
651 && fallback_has_occurred
653 let predicate = trait_predicate.map_bound(|mut trait_pred| {
654 trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
656 &trait_pred.trait_ref.substs[1..],
660 let unit_obligation = Obligation {
661 predicate: ty::Predicate::Trait(predicate),
662 .. obligation.clone()
664 if self.predicate_may_hold(&unit_obligation) {
665 err.note("the trait is implemented for `()`. \
666 Possibly this error has been caused by changes to \
667 Rust's type-inference algorithm \
668 (see: https://github.com/rust-lang/rust/issues/48950 \
669 for more info). Consider whether you meant to use the \
670 type `()` here instead.");
677 ty::Predicate::Subtype(ref predicate) => {
678 // Errors for Subtype predicates show up as
679 // `FulfillmentErrorCode::CodeSubtypeError`,
680 // not selection error.
681 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
684 ty::Predicate::RegionOutlives(ref predicate) => {
685 let predicate = self.resolve_type_vars_if_possible(predicate);
686 let err = self.region_outlives_predicate(&obligation.cause,
687 &predicate).err().unwrap();
688 struct_span_err!(self.tcx.sess, span, E0279,
689 "the requirement `{}` is not satisfied (`{}`)",
693 ty::Predicate::Projection(..) | ty::Predicate::TypeOutlives(..) => {
695 self.resolve_type_vars_if_possible(&obligation.predicate);
696 struct_span_err!(self.tcx.sess, span, E0280,
697 "the requirement `{}` is not satisfied",
701 ty::Predicate::ObjectSafe(trait_def_id) => {
702 let violations = self.tcx.object_safety_violations(trait_def_id);
703 self.tcx.report_object_safety_error(span,
708 ty::Predicate::ClosureKind(closure_def_id, closure_substs, kind) => {
709 let found_kind = self.closure_kind(closure_def_id, closure_substs).unwrap();
710 let closure_span = self.tcx.sess.codemap()
711 .def_span(self.tcx.hir.span_if_local(closure_def_id).unwrap());
712 let node_id = self.tcx.hir.as_local_node_id(closure_def_id).unwrap();
713 let mut err = struct_span_err!(
714 self.tcx.sess, closure_span, E0525,
715 "expected a closure that implements the `{}` trait, \
716 but this closure only implements `{}`",
722 format!("this closure implements `{}`, not `{}`", found_kind, kind));
724 obligation.cause.span,
725 format!("the requirement to implement `{}` derives from here", kind));
727 // Additional context information explaining why the closure only implements
728 // a particular trait.
729 if let Some(tables) = self.in_progress_tables {
730 let tables = tables.borrow();
731 let closure_hir_id = self.tcx.hir.node_to_hir_id(node_id);
732 match (found_kind, tables.closure_kind_origins().get(closure_hir_id)) {
733 (ty::ClosureKind::FnOnce, Some((span, name))) => {
734 err.span_label(*span, format!(
735 "closure is `FnOnce` because it moves the \
736 variable `{}` out of its environment", name));
738 (ty::ClosureKind::FnMut, Some((span, name))) => {
739 err.span_label(*span, format!(
740 "closure is `FnMut` because it mutates the \
741 variable `{}` here", name));
751 ty::Predicate::WellFormed(ty) => {
752 // WF predicates cannot themselves make
753 // errors. They can only block due to
754 // ambiguity; otherwise, they always
755 // degenerate into other obligations
757 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
760 ty::Predicate::ConstEvaluatable(..) => {
761 // Errors for `ConstEvaluatable` predicates show up as
762 // `SelectionError::ConstEvalFailure`,
763 // not `Unimplemented`.
765 "const-evaluatable requirement gave wrong error: `{:?}`", obligation)
770 OutputTypeParameterMismatch(ref found_trait_ref, ref expected_trait_ref, _) => {
771 let found_trait_ref = self.resolve_type_vars_if_possible(&*found_trait_ref);
772 let expected_trait_ref = self.resolve_type_vars_if_possible(&*expected_trait_ref);
773 if expected_trait_ref.self_ty().references_error() {
776 let found_trait_ty = found_trait_ref.self_ty();
778 let found_did = found_trait_ty.ty_to_def_id();
779 let found_span = found_did.and_then(|did| {
780 self.tcx.hir.span_if_local(did)
781 }).map(|sp| self.tcx.sess.codemap().def_span(sp)); // the sp could be an fn def
783 let found = match found_trait_ref.skip_binder().substs.type_at(1).sty {
784 ty::TyTuple(ref tys) => tys.iter()
785 .map(|_| ArgKind::empty()).collect::<Vec<_>>(),
786 _ => vec![ArgKind::empty()],
788 let expected = match expected_trait_ref.skip_binder().substs.type_at(1).sty {
789 ty::TyTuple(ref tys) => tys.iter()
790 .map(|t| match t.sty {
791 ty::TypeVariants::TyTuple(ref tys) => ArgKind::Tuple(
794 .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
797 _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),
799 ref sty => vec![ArgKind::Arg("_".to_owned(), format!("{}", sty))],
801 if found.len() == expected.len() {
802 self.report_closure_arg_mismatch(span,
807 let (closure_span, found) = found_did
808 .and_then(|did| self.tcx.hir.get_if_local(did))
810 let (found_span, found) = self.get_fn_like_arguments(node);
811 (Some(found_span), found)
812 }).unwrap_or((found_span, found));
814 self.report_arg_count_mismatch(span,
818 found_trait_ty.is_closure())
822 TraitNotObjectSafe(did) => {
823 let violations = self.tcx.object_safety_violations(did);
824 self.tcx.report_object_safety_error(span, did,
828 ConstEvalFailure(ref err) => {
829 match err.struct_error(
831 "could not evaluate constant expression",
839 bug!("overflow should be handled before the `report_selection_error` path");
842 self.note_obligation_cause(&mut err, obligation);
846 /// When encountering an assignment of an unsized trait, like `let x = ""[..];`, provide a
847 /// suggestion to borrow the initializer in order to use have a slice instead.
848 fn suggest_borrow_on_unsized_slice(&self,
849 code: &ObligationCauseCode<'tcx>,
850 err: &mut DiagnosticBuilder<'tcx>) {
851 if let &ObligationCauseCode::VariableType(node_id) = code {
852 let parent_node = self.tcx.hir.get_parent_node(node_id);
853 if let Some(hir::map::NodeLocal(ref local)) = self.tcx.hir.find(parent_node) {
854 if let Some(ref expr) = local.init {
855 if let hir::ExprIndex(_, _) = expr.node {
856 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(expr.span) {
857 err.span_suggestion_with_applicability(
859 "consider borrowing here",
860 format!("&{}", snippet),
861 Applicability::MachineApplicable
870 /// Whenever references are used by mistake, like `for (i, e) in &vec.iter().enumerate()`,
871 /// suggest removing these references until we reach a type that implements the trait.
872 fn suggest_remove_reference(&self,
873 obligation: &PredicateObligation<'tcx>,
874 err: &mut DiagnosticBuilder<'tcx>,
875 trait_ref: &ty::Binder<ty::TraitRef<'tcx>>) {
876 let trait_ref = trait_ref.skip_binder();
877 let span = obligation.cause.span;
879 if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
880 let refs_number = snippet.chars()
881 .filter(|c| !c.is_whitespace())
882 .take_while(|c| *c == '&')
885 let mut trait_type = trait_ref.self_ty();
887 for refs_remaining in 0..refs_number {
888 if let ty::TypeVariants::TyRef(_, t_type, _) = trait_type.sty {
891 let substs = self.tcx.mk_substs_trait(trait_type, &[]);
892 let new_trait_ref = ty::TraitRef::new(trait_ref.def_id, substs);
893 let new_obligation = Obligation::new(ObligationCause::dummy(),
894 obligation.param_env,
895 new_trait_ref.to_predicate());
897 if self.predicate_may_hold(&new_obligation) {
898 let sp = self.tcx.sess.codemap()
899 .span_take_while(span, |c| c.is_whitespace() || *c == '&');
901 let remove_refs = refs_remaining + 1;
902 let format_str = format!("consider removing {} leading `&`-references",
905 err.span_suggestion_short_with_applicability(
906 sp, &format_str, String::from(""), Applicability::MachineApplicable
917 /// Given some node representing a fn-like thing in the HIR map,
918 /// returns a span and `ArgKind` information that describes the
919 /// arguments it expects. This can be supplied to
920 /// `report_arg_count_mismatch`.
921 pub fn get_fn_like_arguments(&self, node: hir::map::Node) -> (Span, Vec<ArgKind>) {
923 hir::map::NodeExpr(&hir::Expr {
924 node: hir::ExprClosure(_, ref _decl, id, span, _),
927 (self.tcx.sess.codemap().def_span(span), self.tcx.hir.body(id).arguments.iter()
930 node: hir::PatKind::Tuple(args, _),
933 } = arg.pat.clone().into_inner() {
936 args.iter().map(|pat| {
937 let snippet = self.tcx.sess.codemap()
938 .span_to_snippet(pat.span).unwrap();
939 (snippet, "_".to_owned())
940 }).collect::<Vec<_>>(),
943 let name = self.tcx.sess.codemap()
944 .span_to_snippet(arg.pat.span).unwrap();
945 ArgKind::Arg(name, "_".to_owned())
948 .collect::<Vec<ArgKind>>())
950 hir::map::NodeItem(&hir::Item {
952 node: hir::ItemFn(ref decl, ..),
955 hir::map::NodeImplItem(&hir::ImplItem {
957 node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, _),
960 hir::map::NodeTraitItem(&hir::TraitItem {
962 node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, _),
965 (self.tcx.sess.codemap().def_span(span), decl.inputs.iter()
966 .map(|arg| match arg.clone().node {
967 hir::TyTup(ref tys) => ArgKind::Tuple(
970 .map(|_| ("_".to_owned(), "_".to_owned()))
971 .collect::<Vec<_>>(),
973 _ => ArgKind::Arg("_".to_owned(), "_".to_owned())
974 }).collect::<Vec<ArgKind>>())
976 hir::map::NodeVariant(&hir::Variant {
978 node: hir::Variant_ {
979 data: hir::VariantData::Tuple(ref fields, _),
984 (self.tcx.sess.codemap().def_span(span),
985 fields.iter().map(|field| {
986 ArgKind::Arg(format!("{}", field.ident), "_".to_string())
987 }).collect::<Vec<_>>())
989 hir::map::NodeStructCtor(ref variant_data) => {
990 (self.tcx.sess.codemap().def_span(self.tcx.hir.span(variant_data.id())),
991 variant_data.fields()
992 .iter().map(|_| ArgKind::Arg("_".to_owned(), "_".to_owned()))
995 _ => panic!("non-FnLike node found: {:?}", node),
999 /// Reports an error when the number of arguments needed by a
1000 /// trait match doesn't match the number that the expression
1002 pub fn report_arg_count_mismatch(
1005 found_span: Option<Span>,
1006 expected_args: Vec<ArgKind>,
1007 found_args: Vec<ArgKind>,
1009 ) -> DiagnosticBuilder<'tcx> {
1010 let kind = if is_closure { "closure" } else { "function" };
1012 let args_str = |arguments: &Vec<ArgKind>, other: &Vec<ArgKind>| {
1013 let arg_length = arguments.len();
1014 let distinct = match &other[..] {
1015 &[ArgKind::Tuple(..)] => true,
1018 match (arg_length, arguments.get(0)) {
1019 (1, Some(&ArgKind::Tuple(_, ref fields))) => {
1020 format!("a single {}-tuple as argument", fields.len())
1022 _ => format!("{} {}argument{}",
1024 if distinct && arg_length > 1 { "distinct " } else { "" },
1025 if arg_length == 1 { "" } else { "s" }),
1029 let expected_str = args_str(&expected_args, &found_args);
1030 let found_str = args_str(&found_args, &expected_args);
1032 let mut err = struct_span_err!(
1036 "{} is expected to take {}, but it takes {}",
1042 err.span_label(span, format!( "expected {} that takes {}", kind, expected_str));
1044 if let Some(found_span) = found_span {
1045 err.span_label(found_span, format!("takes {}", found_str));
1047 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
1048 if fields.len() == expected_args.len() {
1049 let sugg = fields.iter()
1050 .map(|(name, _)| name.to_owned())
1051 .collect::<Vec<String>>().join(", ");
1052 err.span_suggestion_with_applicability(found_span,
1053 "change the closure to take multiple \
1054 arguments instead of a single tuple",
1055 format!("|{}|", sugg),
1056 Applicability::MachineApplicable);
1059 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
1060 if fields.len() == found_args.len() && is_closure {
1064 .map(|arg| match arg {
1065 ArgKind::Arg(name, _) => name.to_owned(),
1066 _ => "_".to_owned(),
1068 .collect::<Vec<String>>()
1070 // add type annotations if available
1071 if found_args.iter().any(|arg| match arg {
1072 ArgKind::Arg(_, ty) => ty != "_",
1077 .map(|(_, ty)| ty.to_owned())
1078 .collect::<Vec<String>>()
1084 err.span_suggestion_with_applicability(
1086 "change the closure to accept a tuple instead of \
1087 individual arguments",
1089 Applicability::MachineApplicable
1098 fn report_closure_arg_mismatch(&self,
1100 found_span: Option<Span>,
1101 expected_ref: ty::PolyTraitRef<'tcx>,
1102 found: ty::PolyTraitRef<'tcx>)
1103 -> DiagnosticBuilder<'tcx>
1105 fn build_fn_sig_string<'a, 'gcx, 'tcx>(tcx: ty::TyCtxt<'a, 'gcx, 'tcx>,
1106 trait_ref: &ty::TraitRef<'tcx>) -> String {
1107 let inputs = trait_ref.substs.type_at(1);
1108 let sig = if let ty::TyTuple(inputs) = inputs.sty {
1110 inputs.iter().map(|&x| x),
1111 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1113 hir::Unsafety::Normal,
1114 ::rustc_target::spec::abi::Abi::Rust
1118 ::std::iter::once(inputs),
1119 tcx.mk_infer(ty::TyVar(ty::TyVid { index: 0 })),
1121 hir::Unsafety::Normal,
1122 ::rustc_target::spec::abi::Abi::Rust
1125 format!("{}", ty::Binder::bind(sig))
1128 let argument_is_closure = expected_ref.skip_binder().substs.type_at(0).is_closure();
1129 let mut err = struct_span_err!(self.tcx.sess, span, E0631,
1130 "type mismatch in {} arguments",
1131 if argument_is_closure { "closure" } else { "function" });
1133 let found_str = format!(
1134 "expected signature of `{}`",
1135 build_fn_sig_string(self.tcx, found.skip_binder())
1137 err.span_label(span, found_str);
1139 let found_span = found_span.unwrap_or(span);
1140 let expected_str = format!(
1141 "found signature of `{}`",
1142 build_fn_sig_string(self.tcx, expected_ref.skip_binder())
1144 err.span_label(found_span, expected_str);
1150 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
1151 pub fn recursive_type_with_infinite_size_error(self,
1153 -> DiagnosticBuilder<'tcx>
1155 assert!(type_def_id.is_local());
1156 let span = self.hir.span_if_local(type_def_id).unwrap();
1157 let span = self.sess.codemap().def_span(span);
1158 let mut err = struct_span_err!(self.sess, span, E0072,
1159 "recursive type `{}` has infinite size",
1160 self.item_path_str(type_def_id));
1161 err.span_label(span, "recursive type has infinite size");
1162 err.help(&format!("insert indirection (e.g., a `Box`, `Rc`, or `&`) \
1163 at some point to make `{}` representable",
1164 self.item_path_str(type_def_id)));
1168 pub fn report_object_safety_error(self,
1170 trait_def_id: DefId,
1171 violations: Vec<ObjectSafetyViolation>)
1172 -> DiagnosticBuilder<'tcx>
1174 let trait_str = self.item_path_str(trait_def_id);
1175 let span = self.sess.codemap().def_span(span);
1176 let mut err = struct_span_err!(
1177 self.sess, span, E0038,
1178 "the trait `{}` cannot be made into an object",
1180 err.span_label(span, format!("the trait `{}` cannot be made into an object", trait_str));
1182 let mut reported_violations = FxHashSet();
1183 for violation in violations {
1184 if !reported_violations.insert(violation.clone()) {
1187 err.note(&violation.error_msg());
1193 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1194 fn maybe_report_ambiguity(&self, obligation: &PredicateObligation<'tcx>,
1195 body_id: Option<hir::BodyId>) {
1196 // Unable to successfully determine, probably means
1197 // insufficient type information, but could mean
1198 // ambiguous impls. The latter *ought* to be a
1199 // coherence violation, so we don't report it here.
1201 let predicate = self.resolve_type_vars_if_possible(&obligation.predicate);
1202 let span = obligation.cause.span;
1204 debug!("maybe_report_ambiguity(predicate={:?}, obligation={:?})",
1208 // Ambiguity errors are often caused as fallout from earlier
1209 // errors. So just ignore them if this infcx is tainted.
1210 if self.is_tainted_by_errors() {
1215 ty::Predicate::Trait(ref data) => {
1216 let trait_ref = data.to_poly_trait_ref();
1217 let self_ty = trait_ref.self_ty();
1218 if predicate.references_error() {
1221 // Typically, this ambiguity should only happen if
1222 // there are unresolved type inference variables
1223 // (otherwise it would suggest a coherence
1224 // failure). But given #21974 that is not necessarily
1225 // the case -- we can have multiple where clauses that
1226 // are only distinguished by a region, which results
1227 // in an ambiguity even when all types are fully
1228 // known, since we don't dispatch based on region
1231 // This is kind of a hack: it frequently happens that some earlier
1232 // error prevents types from being fully inferred, and then we get
1233 // a bunch of uninteresting errors saying something like "<generic
1234 // #0> doesn't implement Sized". It may even be true that we
1235 // could just skip over all checks where the self-ty is an
1236 // inference variable, but I was afraid that there might be an
1237 // inference variable created, registered as an obligation, and
1238 // then never forced by writeback, and hence by skipping here we'd
1239 // be ignoring the fact that we don't KNOW the type works
1240 // out. Though even that would probably be harmless, given that
1241 // we're only talking about builtin traits, which are known to be
1242 // inhabited. But in any case I just threw in this check for
1243 // has_errors() to be sure that compilation isn't happening
1244 // anyway. In that case, why inundate the user.
1245 if !self.tcx.sess.has_errors() {
1247 self.tcx.lang_items().sized_trait()
1248 .map_or(false, |sized_id| sized_id == trait_ref.def_id())
1250 self.need_type_info_err(body_id, span, self_ty).emit();
1252 let mut err = struct_span_err!(self.tcx.sess,
1254 "type annotations required: \
1255 cannot resolve `{}`",
1257 self.note_obligation_cause(&mut err, obligation);
1263 ty::Predicate::WellFormed(ty) => {
1264 // Same hacky approach as above to avoid deluging user
1265 // with error messages.
1266 if !ty.references_error() && !self.tcx.sess.has_errors() {
1267 self.need_type_info_err(body_id, span, ty).emit();
1271 ty::Predicate::Subtype(ref data) => {
1272 if data.references_error() || self.tcx.sess.has_errors() {
1273 // no need to overload user in such cases
1275 let &SubtypePredicate { a_is_expected: _, a, b } = data.skip_binder();
1276 // both must be type variables, or the other would've been instantiated
1277 assert!(a.is_ty_var() && b.is_ty_var());
1278 self.need_type_info_err(body_id,
1279 obligation.cause.span,
1285 if !self.tcx.sess.has_errors() {
1286 let mut err = struct_span_err!(self.tcx.sess,
1287 obligation.cause.span, E0284,
1288 "type annotations required: \
1289 cannot resolve `{}`",
1291 self.note_obligation_cause(&mut err, obligation);
1298 /// Returns whether the trait predicate may apply for *some* assignment
1299 /// to the type parameters.
1300 fn predicate_can_apply(&self,
1301 param_env: ty::ParamEnv<'tcx>,
1302 pred: ty::PolyTraitRef<'tcx>)
1304 struct ParamToVarFolder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
1305 infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
1306 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>
1309 impl<'a, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for ParamToVarFolder<'a, 'gcx, 'tcx> {
1310 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.infcx.tcx }
1312 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1313 if let ty::TyParam(ty::ParamTy {name, ..}) = ty.sty {
1314 let infcx = self.infcx;
1315 self.var_map.entry(ty).or_insert_with(||
1317 TypeVariableOrigin::TypeParameterDefinition(DUMMY_SP, name)))
1319 ty.super_fold_with(self)
1325 let mut selcx = SelectionContext::new(self);
1327 let cleaned_pred = pred.fold_with(&mut ParamToVarFolder {
1329 var_map: FxHashMap()
1332 let cleaned_pred = super::project::normalize(
1335 ObligationCause::dummy(),
1339 let obligation = Obligation::new(
1340 ObligationCause::dummy(),
1342 cleaned_pred.to_predicate()
1345 self.predicate_may_hold(&obligation)
1349 fn note_obligation_cause<T>(&self,
1350 err: &mut DiagnosticBuilder,
1351 obligation: &Obligation<'tcx, T>)
1352 where T: fmt::Display
1354 self.note_obligation_cause_code(err,
1355 &obligation.predicate,
1356 &obligation.cause.code,
1360 fn note_obligation_cause_code<T>(&self,
1361 err: &mut DiagnosticBuilder,
1363 cause_code: &ObligationCauseCode<'tcx>,
1364 obligated_types: &mut Vec<&ty::TyS<'tcx>>)
1365 where T: fmt::Display
1369 ObligationCauseCode::ExprAssignable |
1370 ObligationCauseCode::MatchExpressionArm { .. } |
1371 ObligationCauseCode::IfExpression |
1372 ObligationCauseCode::IfExpressionWithNoElse |
1373 ObligationCauseCode::MainFunctionType |
1374 ObligationCauseCode::StartFunctionType |
1375 ObligationCauseCode::IntrinsicType |
1376 ObligationCauseCode::MethodReceiver |
1377 ObligationCauseCode::ReturnNoExpression |
1378 ObligationCauseCode::MiscObligation => {
1380 ObligationCauseCode::SliceOrArrayElem => {
1381 err.note("slice and array elements must have `Sized` type");
1383 ObligationCauseCode::TupleElem => {
1384 err.note("only the last element of a tuple may have a dynamically sized type");
1386 ObligationCauseCode::ProjectionWf(data) => {
1387 err.note(&format!("required so that the projection `{}` is well-formed",
1390 ObligationCauseCode::ReferenceOutlivesReferent(ref_ty) => {
1391 err.note(&format!("required so that reference `{}` does not outlive its referent",
1394 ObligationCauseCode::ObjectTypeBound(object_ty, region) => {
1395 err.note(&format!("required so that the lifetime bound of `{}` for `{}` \
1397 region, object_ty));
1399 ObligationCauseCode::ItemObligation(item_def_id) => {
1400 let item_name = tcx.item_path_str(item_def_id);
1401 let msg = format!("required by `{}`", item_name);
1402 if let Some(sp) = tcx.hir.span_if_local(item_def_id) {
1403 let sp = tcx.sess.codemap().def_span(sp);
1404 err.span_note(sp, &msg);
1409 ObligationCauseCode::ObjectCastObligation(object_ty) => {
1410 err.note(&format!("required for the cast to the object type `{}`",
1411 self.ty_to_string(object_ty)));
1413 ObligationCauseCode::RepeatVec => {
1414 err.note("the `Copy` trait is required because the \
1415 repeated element will be copied");
1417 ObligationCauseCode::VariableType(_) => {
1418 err.note("all local variables must have a statically known size");
1420 ObligationCauseCode::SizedReturnType => {
1421 err.note("the return type of a function must have a \
1422 statically known size");
1424 ObligationCauseCode::SizedYieldType => {
1425 err.note("the yield type of a generator must have a \
1426 statically known size");
1428 ObligationCauseCode::AssignmentLhsSized => {
1429 err.note("the left-hand-side of an assignment must have a statically known size");
1431 ObligationCauseCode::TupleInitializerSized => {
1432 err.note("tuples must have a statically known size to be initialized");
1434 ObligationCauseCode::StructInitializerSized => {
1435 err.note("structs must have a statically known size to be initialized");
1437 ObligationCauseCode::FieldSized(ref item) => {
1439 AdtKind::Struct => {
1440 err.note("only the last field of a struct may have a dynamically \
1444 err.note("no field of a union may have a dynamically sized type");
1447 err.note("no field of an enum variant may have a dynamically sized type");
1451 ObligationCauseCode::ConstSized => {
1452 err.note("constant expressions must have a statically known size");
1454 ObligationCauseCode::SharedStatic => {
1455 err.note("shared static variables must have a type that implements `Sync`");
1457 ObligationCauseCode::BuiltinDerivedObligation(ref data) => {
1458 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1459 let ty = parent_trait_ref.skip_binder().self_ty();
1460 err.note(&format!("required because it appears within the type `{}`", ty));
1461 obligated_types.push(ty);
1463 let parent_predicate = parent_trait_ref.to_predicate();
1464 if !self.is_recursive_obligation(obligated_types, &data.parent_code) {
1465 self.note_obligation_cause_code(err,
1471 ObligationCauseCode::ImplDerivedObligation(ref data) => {
1472 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1474 &format!("required because of the requirements on the impl of `{}` for `{}`",
1476 parent_trait_ref.skip_binder().self_ty()));
1477 let parent_predicate = parent_trait_ref.to_predicate();
1478 self.note_obligation_cause_code(err,
1483 ObligationCauseCode::CompareImplMethodObligation { .. } => {
1485 &format!("the requirement `{}` appears on the impl method \
1486 but not on the corresponding trait method",
1489 ObligationCauseCode::ReturnType(_) |
1490 ObligationCauseCode::BlockTailExpression(_) => (),
1491 ObligationCauseCode::TrivialBound => {
1492 err.help("see issue #48214");
1493 if tcx.sess.opts.unstable_features.is_nightly_build() {
1494 err.help("add #![feature(trivial_bounds)] to the \
1495 crate attributes to enable",
1502 fn suggest_new_overflow_limit(&self, err: &mut DiagnosticBuilder) {
1503 let current_limit = self.tcx.sess.recursion_limit.get();
1504 let suggested_limit = current_limit * 2;
1505 err.help(&format!("consider adding a `#![recursion_limit=\"{}\"]` attribute to your crate",
1509 fn is_recursive_obligation(&self,
1510 obligated_types: &mut Vec<&ty::TyS<'tcx>>,
1511 cause_code: &ObligationCauseCode<'tcx>) -> bool {
1512 if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
1513 let parent_trait_ref = self.resolve_type_vars_if_possible(&data.parent_trait_ref);
1514 for obligated_type in obligated_types {
1515 if obligated_type == &parent_trait_ref.skip_binder().self_ty() {
1524 /// Summarizes information
1526 /// An argument of non-tuple type. Parameters are (name, ty)
1527 Arg(String, String),
1529 /// An argument of tuple type. For a "found" argument, the span is
1530 /// the locationo in the source of the pattern. For a "expected"
1531 /// argument, it will be None. The vector is a list of (name, ty)
1532 /// strings for the components of the tuple.
1533 Tuple(Option<Span>, Vec<(String, String)>),
1537 fn empty() -> ArgKind {
1538 ArgKind::Arg("_".to_owned(), "_".to_owned())
1541 /// Creates an `ArgKind` from the expected type of an
1542 /// argument. This has no name (`_`) and no source spans..
1543 pub fn from_expected_ty(t: Ty<'_>) -> ArgKind {
1545 ty::TyTuple(ref tys) => ArgKind::Tuple(
1548 .map(|ty| ("_".to_owned(), format!("{}", ty.sty)))
1549 .collect::<Vec<_>>()
1551 _ => ArgKind::Arg("_".to_owned(), format!("{}", t.sty)),