mod.rs 86.9 KB
Newer Older
1 2 3 4
pub mod on_unimplemented;
pub mod suggestions;

use super::{
E
Ellen 已提交
5 6 7 8
    EvaluationResult, FulfillmentError, FulfillmentErrorCode, MismatchedProjectionTypes,
    Obligation, ObligationCause, ObligationCauseCode, OnUnimplementedDirective,
    OnUnimplementedNote, OutputTypeParameterMismatch, Overflow, PredicateObligation,
    SelectionContext, SelectionError, TraitNotObjectSafe,
9 10 11 12
};

use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
C
Camille GILLOT 已提交
13
use crate::infer::{self, InferCtxt, TyCtxtInferExt};
14
use rustc_data_structures::fx::FxHashMap;
15
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder, ErrorReported};
16
use rustc_hir as hir;
C
Camille GILLOT 已提交
17
use rustc_hir::def_id::DefId;
18
use rustc_hir::intravisit::Visitor;
19 20
use rustc_hir::GenericParam;
use rustc_hir::Item;
21
use rustc_hir::Node;
22
use rustc_middle::thir::abstract_const::NotConstEvaluatable;
M
Mazdak Farrokhzad 已提交
23 24 25
use rustc_middle::ty::error::ExpectedFound;
use rustc_middle::ty::fold::TypeFolder;
use rustc_middle::ty::{
26 27
    self, fast_reject, AdtKind, SubtypePredicate, ToPolyTraitRef, ToPredicate, Ty, TyCtxt,
    TypeFoldable, WithConstness,
28
};
29
use rustc_session::DiagnosticMessageId;
30
use rustc_span::symbol::{kw, sym};
31
use rustc_span::{ExpnKind, MultiSpan, Span, DUMMY_SP};
32
use std::fmt;
J
Josh Stone 已提交
33
use std::iter;
34

C
Camille GILLOT 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
use crate::traits::query::normalize::AtExt as _;
use on_unimplemented::InferCtxtExt as _;
use suggestions::InferCtxtExt as _;

pub use rustc_infer::traits::error_reporting::*;

pub trait InferCtxtExt<'tcx> {
    fn report_fulfillment_errors(
        &self,
        errors: &[FulfillmentError<'tcx>],
        body_id: Option<hir::BodyId>,
        fallback_has_occurred: bool,
    );

    fn report_overflow_error<T>(
        &self,
        obligation: &Obligation<'tcx, T>,
        suggest_increasing_limit: bool,
    ) -> !
    where
        T: fmt::Display + TypeFoldable<'tcx>;

    fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> !;

60 61 62
    /// The `root_obligation` parameter should be the `root_obligation` field
    /// from a `FulfillmentError`. If no `FulfillmentError` is available,
    /// then it should be the same as `obligation`.
C
Camille GILLOT 已提交
63 64
    fn report_selection_error(
        &self,
65 66
        obligation: PredicateObligation<'tcx>,
        root_obligation: &PredicateObligation<'tcx>,
C
Camille GILLOT 已提交
67 68 69 70 71 72 73 74 75
        error: &SelectionError<'tcx>,
        fallback_has_occurred: bool,
        points_at_arg: bool,
    );

    /// Given some node representing a fn-like thing in the HIR map,
    /// returns a span and `ArgKind` information that describes the
    /// arguments it expects. This can be supplied to
    /// `report_arg_count_mismatch`.
76
    fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)>;
C
Camille GILLOT 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

    /// Reports an error when the number of arguments needed by a
    /// trait match doesn't match the number that the expression
    /// provides.
    fn report_arg_count_mismatch(
        &self,
        span: Span,
        found_span: Option<Span>,
        expected_args: Vec<ArgKind>,
        found_args: Vec<ArgKind>,
        is_closure: bool,
    ) -> DiagnosticBuilder<'tcx>;
}

impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
    fn report_fulfillment_errors(
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
        &self,
        errors: &[FulfillmentError<'tcx>],
        body_id: Option<hir::BodyId>,
        fallback_has_occurred: bool,
    ) {
        #[derive(Debug)]
        struct ErrorDescriptor<'tcx> {
            predicate: ty::Predicate<'tcx>,
            index: Option<usize>, // None if this is an old error
        }

        let mut error_map: FxHashMap<_, Vec<_>> = self
            .reported_trait_errors
            .borrow()
            .iter()
            .map(|(&span, predicates)| {
                (
                    span,
                    predicates
                        .iter()
113
                        .map(|&predicate| ErrorDescriptor { predicate, index: None })
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
                        .collect(),
                )
            })
            .collect();

        for (index, error) in errors.iter().enumerate() {
            // We want to ignore desugarings here: spans are equivalent even
            // if one is the result of a desugaring and the other is not.
            let mut span = error.obligation.cause.span;
            let expn_data = span.ctxt().outer_expn_data();
            if let ExpnKind::Desugaring(_) = expn_data.kind {
                span = expn_data.call_site;
            }

            error_map.entry(span).or_default().push(ErrorDescriptor {
129
                predicate: error.obligation.predicate,
130 131 132 133 134 135 136
                index: Some(index),
            });

            self.reported_trait_errors
                .borrow_mut()
                .entry(span)
                .or_default()
137
                .push(error.obligation.predicate);
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
        }

        // We do this in 2 passes because we want to display errors in order, though
        // maybe it *is* better to sort errors by span or something.
        let mut is_suppressed = vec![false; errors.len()];
        for (_, error_set) in error_map.iter() {
            // We want to suppress "duplicate" errors with the same span.
            for error in error_set {
                if let Some(index) = error.index {
                    // Suppress errors that are either:
                    // 1) strictly implied by another error.
                    // 2) implied by an error with a smaller index.
                    for error2 in error_set {
                        if error2.index.map_or(false, |index2| is_suppressed[index2]) {
                            // Avoid errors being suppressed by already-suppressed
                            // errors, to prevent all errors from being suppressed
                            // at once.
                            continue;
                        }

158
                        if self.error_implies(error2.predicate, error.predicate)
159
                            && !(error2.index >= error.index
160
                                && self.error_implies(error.predicate, error2.predicate))
161 162 163 164 165 166 167 168 169 170
                        {
                            info!("skipping {:?} (implied by {:?})", error, error2);
                            is_suppressed[index] = true;
                            break;
                        }
                    }
                }
            }
        }

J
Josh Stone 已提交
171
        for (error, suppressed) in iter::zip(errors, is_suppressed) {
172 173 174 175 176 177
            if !suppressed {
                self.report_fulfillment_error(error, body_id, fallback_has_occurred);
            }
        }
    }

C
Camille GILLOT 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191
    /// Reports that an overflow has occurred and halts compilation. We
    /// halt compilation unconditionally because it is important that
    /// overflows never be masked -- they basically represent computations
    /// whose result could not be truly determined and thus we can't say
    /// if the program type checks or not -- and they are unusual
    /// occurrences in any case.
    fn report_overflow_error<T>(
        &self,
        obligation: &Obligation<'tcx, T>,
        suggest_increasing_limit: bool,
    ) -> !
    where
        T: fmt::Display + TypeFoldable<'tcx>,
    {
B
Bastian Kauschke 已提交
192
        let predicate = self.resolve_vars_if_possible(obligation.predicate.clone());
C
Camille GILLOT 已提交
193 194 195 196 197 198 199
        let mut err = struct_span_err!(
            self.tcx.sess,
            obligation.cause.span,
            E0275,
            "overflow evaluating the requirement `{}`",
            predicate
        );
200

C
Camille GILLOT 已提交
201 202
        if suggest_increasing_limit {
            self.suggest_new_overflow_limit(&mut err);
203 204
        }

C
Camille GILLOT 已提交
205 206 207 208 209
        self.note_obligation_cause_code(
            &mut err,
            &obligation.predicate,
            &obligation.cause.code,
            &mut vec![],
210
            &mut Default::default(),
C
Camille GILLOT 已提交
211 212 213 214 215
        );

        err.emit();
        self.tcx.sess.abort_if_errors();
        bug!();
216 217
    }

C
Camille GILLOT 已提交
218 219 220 221 222 223
    /// Reports that a cycle was detected which led to overflow and halts
    /// compilation. This is equivalent to `report_overflow_error` except
    /// that we can give a more helpful error message (and, in particular,
    /// we do not suggest increasing the overflow limit, which is not
    /// going to help).
    fn report_overflow_error_cycle(&self, cycle: &[PredicateObligation<'tcx>]) -> ! {
B
Bastian Kauschke 已提交
224
        let cycle = self.resolve_vars_if_possible(cycle.to_owned());
C
Camille GILLOT 已提交
225 226 227 228
        assert!(!cycle.is_empty());

        debug!("report_overflow_error_cycle: cycle={:?}", cycle);

229 230 231
        // The 'deepest' obligation is most likely to have a useful
        // cause 'backtrace'
        self.report_overflow_error(cycle.iter().max_by_key(|p| p.recursion_depth).unwrap(), false);
232 233
    }

C
Camille GILLOT 已提交
234
    fn report_selection_error(
235
        &self,
236 237
        mut obligation: PredicateObligation<'tcx>,
        root_obligation: &PredicateObligation<'tcx>,
C
Camille GILLOT 已提交
238 239 240
        error: &SelectionError<'tcx>,
        fallback_has_occurred: bool,
        points_at_arg: bool,
241
    ) {
C
Camille GILLOT 已提交
242
        let tcx = self.tcx;
243
        let mut span = obligation.cause.span;
244

C
Camille GILLOT 已提交
245 246
        let mut err = match *error {
            SelectionError::Unimplemented => {
247 248
                // If this obligation was generated as a result of well-formedness checking, see if we
                // can get a better error message by performing HIR-based well-formedness checking.
249
                if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
250 251
                    root_obligation.cause.code.peel_derives()
                {
252 253 254 255
                    if let Some(cause) = self.tcx.diagnostic_hir_wf_check((
                        tcx.erase_regions(obligation.predicate),
                        wf_loc.clone(),
                    )) {
256 257 258 259
                        obligation.cause = cause;
                        span = obligation.cause.span;
                    }
                }
C
Camille GILLOT 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
                if let ObligationCauseCode::CompareImplMethodObligation {
                    item_name,
                    impl_item_def_id,
                    trait_item_def_id,
                }
                | ObligationCauseCode::CompareImplTypeObligation {
                    item_name,
                    impl_item_def_id,
                    trait_item_def_id,
                } = obligation.cause.code
                {
                    self.report_extra_impl_obligation(
                        span,
                        item_name,
                        impl_item_def_id,
                        trait_item_def_id,
                        &format!("`{}`", obligation.predicate),
                    )
                    .emit();
                    return;
                }
281

J
Jack Huey 已提交
282
                let bound_predicate = obligation.predicate.kind();
283
                match bound_predicate.skip_binder() {
D
Deadbeef 已提交
284
                    ty::PredicateKind::Trait(trait_predicate) => {
J
Jack Huey 已提交
285
                        let trait_predicate = bound_predicate.rebind(trait_predicate);
B
Bastian Kauschke 已提交
286
                        let trait_predicate = self.resolve_vars_if_possible(trait_predicate);
287

C
Camille GILLOT 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301
                        if self.tcx.sess.has_errors() && trait_predicate.references_error() {
                            return;
                        }
                        let trait_ref = trait_predicate.to_poly_trait_ref();
                        let (post_message, pre_message, type_def) = self
                            .get_parent_trait_ref(&obligation.cause.code)
                            .map(|(t, s)| {
                                (
                                    format!(" in `{}`", t),
                                    format!("within `{}`, ", t),
                                    s.map(|s| (format!("within this `{}`", t), s)),
                                )
                            })
                            .unwrap_or_default();
302

C
Camille GILLOT 已提交
303
                        let OnUnimplementedNote { message, label, note, enclosing_scope } =
304
                            self.on_unimplemented_note(trait_ref, &obligation);
C
Camille GILLOT 已提交
305
                        let have_alt_message = message.is_some() || label.is_some();
306
                        let is_try_conversion = self.is_try_conversion(span, trait_ref.def_id());
307 308
                        let is_unsize =
                            { Some(trait_ref.def_id()) == self.tcx.lang_items().unsize_trait() };
309
                        let (message, note) = if is_try_conversion {
C
Camille GILLOT 已提交
310 311 312
                            (
                                Some(format!(
                                    "`?` couldn't convert the error to `{}`",
313
                                    trait_ref.skip_binder().self_ty(),
C
Camille GILLOT 已提交
314 315 316
                                )),
                                Some(
                                    "the question mark operation (`?`) implicitly performs a \
317
                                        conversion on the error value using the `From` trait"
C
Camille GILLOT 已提交
318 319 320 321 322 323
                                        .to_owned(),
                                ),
                            )
                        } else {
                            (message, note)
                        };
324

C
Camille GILLOT 已提交
325 326 327 328 329 330 331
                        let mut err = struct_span_err!(
                            self.tcx.sess,
                            span,
                            E0277,
                            "{}",
                            message.unwrap_or_else(|| format!(
                                "the trait bound `{}` is not satisfied{}",
332
                                trait_ref.without_const().to_predicate(tcx),
C
Camille GILLOT 已提交
333 334 335
                                post_message,
                            ))
                        );
336

337
                        if is_try_conversion {
338 339 340 341 342 343 344 345
                            let none_error = self
                                .tcx
                                .get_diagnostic_item(sym::none_error)
                                .map(|def_id| tcx.type_of(def_id));
                            let should_convert_option_to_result =
                                Some(trait_ref.skip_binder().substs.type_at(1)) == none_error;
                            let should_convert_result_to_option =
                                Some(trait_ref.self_ty().skip_binder()) == none_error;
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
                            if should_convert_option_to_result {
                                err.span_suggestion_verbose(
                                    span.shrink_to_lo(),
                                    "consider converting the `Option<T>` into a `Result<T, _>` \
                                     using `Option::ok_or` or `Option::ok_or_else`",
                                    ".ok_or_else(|| /* error value */)".to_string(),
                                    Applicability::HasPlaceholders,
                                );
                            } else if should_convert_result_to_option {
                                err.span_suggestion_verbose(
                                    span.shrink_to_lo(),
                                    "consider converting the `Result<T, _>` into an `Option<T>` \
                                     using `Result::ok`",
                                    ".ok()".to_string(),
                                    Applicability::MachineApplicable,
                                );
                            }
363
                            if let Some(ret_span) = self.return_type_span(&obligation) {
364 365
                                err.span_label(
                                    ret_span,
366 367 368 369
                                    &format!(
                                        "expected `{}` because of this",
                                        trait_ref.skip_binder().self_ty()
                                    ),
370 371
                                );
                            }
372 373
                        }

C
Camille GILLOT 已提交
374 375 376 377 378 379 380 381
                        let explanation =
                            if obligation.cause.code == ObligationCauseCode::MainFunctionType {
                                "consider using `()`, or a `Result`".to_owned()
                            } else {
                                format!(
                                    "{}the trait `{}` is not implemented for `{}`",
                                    pre_message,
                                    trait_ref.print_only_trait_path(),
382
                                    trait_ref.skip_binder().self_ty(),
C
Camille GILLOT 已提交
383 384 385 386 387 388 389 390 391 392
                                )
                            };

                        if self.suggest_add_reference_to_arg(
                            &obligation,
                            &mut err,
                            &trait_ref,
                            points_at_arg,
                            have_alt_message,
                        ) {
393
                            self.note_obligation_cause(&mut err, &obligation);
C
Camille GILLOT 已提交
394 395 396 397 398 399 400
                            err.emit();
                            return;
                        }
                        if let Some(ref s) = label {
                            // If it has a custom `#[rustc_on_unimplemented]`
                            // error message, let's display it as the label!
                            err.span_label(span, s.as_str());
L
LeSeulArtichaut 已提交
401
                            if !matches!(trait_ref.skip_binder().self_ty().kind(), ty::Param(_)) {
402 403 404 405 406
                                // When the self type is a type param We don't need to "the trait
                                // `std::marker::Sized` is not implemented for `T`" as we will point
                                // at the type param with a label to suggest constraining it.
                                err.help(&explanation);
                            }
C
Camille GILLOT 已提交
407 408 409 410 411 412 413 414 415 416 417
                        } else {
                            err.span_label(span, explanation);
                        }
                        if let Some((msg, span)) = type_def {
                            err.span_label(span, &msg);
                        }
                        if let Some(ref s) = note {
                            // If it has a custom `#[rustc_on_unimplemented]` note, let's display it
                            err.note(s.as_str());
                        }
                        if let Some(ref s) = enclosing_scope {
A
Aaron Hill 已提交
418 419 420 421 422 423
                            let body = tcx
                                .hir()
                                .opt_local_def_id(obligation.cause.body_id)
                                .unwrap_or_else(|| {
                                    tcx.hir().body_owner_def_id(hir::BodyId {
                                        hir_id: obligation.cause.body_id,
424
                                    })
A
Aaron Hill 已提交
425 426 427 428
                                });

                            let enclosing_scope_span =
                                tcx.hir().span_with_body(tcx.hir().local_def_id_to_hir_id(body));
C
Camille GILLOT 已提交
429 430 431 432

                            err.span_label(enclosing_scope_span, s.as_str());
                        }

B
Bastian Kauschke 已提交
433 434 435 436
                        self.suggest_dereferences(&obligation, &mut err, trait_ref, points_at_arg);
                        self.suggest_fn_call(&obligation, &mut err, trait_ref, points_at_arg);
                        self.suggest_remove_reference(&obligation, &mut err, trait_ref);
                        self.suggest_semicolon_removal(&obligation, &mut err, span, trait_ref);
C
Camille GILLOT 已提交
437
                        self.note_version_mismatch(&mut err, &trait_ref);
C
csmoe 已提交
438 439

                        if Some(trait_ref.def_id()) == tcx.lang_items().try_trait() {
B
Bastian Kauschke 已提交
440
                            self.suggest_await_before_try(&mut err, &obligation, trait_ref, span);
C
csmoe 已提交
441 442
                        }

B
Bastian Kauschke 已提交
443
                        if self.suggest_impl_trait(&mut err, span, &obligation, trait_ref) {
C
Camille GILLOT 已提交
444 445 446 447
                            err.emit();
                            return;
                        }

448 449 450 451 452 453 454 455 456 457 458
                        if is_unsize {
                            // If the obligation failed due to a missing implementation of the
                            // `Unsize` trait, give a pointer to why that might be the case
                            err.note(
                                "all implementations of `Unsize` are provided \
                                automatically by the compiler, see \
                                <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
                                for more information",
                            );
                        }

459 460 461 462 463 464
                        let is_fn_trait = [
                            self.tcx.lang_items().fn_trait(),
                            self.tcx.lang_items().fn_mut_trait(),
                            self.tcx.lang_items().fn_once_trait(),
                        ]
                        .contains(&Some(trait_ref.def_id()));
L
LeSeulArtichaut 已提交
465 466 467 468 469 470 471
                        let is_target_feature_fn = if let ty::FnDef(def_id, _) =
                            *trait_ref.skip_binder().self_ty().kind()
                        {
                            !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
                        } else {
                            false
                        };
472
                        if is_fn_trait && is_target_feature_fn {
473 474 475
                            err.note(
                                "`#[target_feature]` functions do not implement the `Fn` traits",
                            );
476 477
                        }

C
Camille GILLOT 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490
                        // Try to report a help message
                        if !trait_ref.has_infer_types_or_consts()
                            && self.predicate_can_apply(obligation.param_env, trait_ref)
                        {
                            // If a where-clause may be useful, remind the
                            // user that they can add it.
                            //
                            // don't display an on-unimplemented note, as
                            // these notes will often be of the form
                            //     "the type `T` can't be frobnicated"
                            // which is somewhat confusing.
                            self.suggest_restricting_param_bound(
                                &mut err,
E
Esteban Küber 已提交
491
                                trait_ref,
C
Camille GILLOT 已提交
492 493
                                obligation.cause.body_id,
                            );
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
                        } else if !have_alt_message {
                            // Can't show anything else useful, try to find similar impls.
                            let impl_candidates = self.find_similar_impl_candidates(trait_ref);
                            self.report_similar_impl_candidates(impl_candidates, &mut err);
                        }

                        // Changing mutability doesn't make a difference to whether we have
                        // an `Unsize` impl (Fixes ICE in #71036)
                        if !is_unsize {
                            self.suggest_change_mut(
                                &obligation,
                                &mut err,
                                trait_ref,
                                points_at_arg,
                            );
C
Camille GILLOT 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
                        }

                        // If this error is due to `!: Trait` not implemented but `(): Trait` is
                        // implemented, and fallback has occurred, then it could be due to a
                        // variable that used to fallback to `()` now falling back to `!`. Issue a
                        // note informing about the change in behaviour.
                        if trait_predicate.skip_binder().self_ty().is_never()
                            && fallback_has_occurred
                        {
                            let predicate = trait_predicate.map_bound(|mut trait_pred| {
                                trait_pred.trait_ref.substs = self.tcx.mk_substs_trait(
                                    self.tcx.mk_unit(),
                                    &trait_pred.trait_ref.substs[1..],
                                );
                                trait_pred
                            });
D
Deadbeef 已提交
525
                            let unit_obligation = obligation.with(predicate.to_predicate(tcx));
C
Camille GILLOT 已提交
526
                            if self.predicate_may_hold(&unit_obligation) {
T
teymour-aldridge 已提交
527
                                err.note("this trait is implemented for `()`.");
C
Camille GILLOT 已提交
528
                                err.note(
T
teymour-aldridge 已提交
529 530 531 532
                                    "this error might have been caused by changes to \
                                    Rust's type-inference algorithm (see issue #48950 \
                                    <https://github.com/rust-lang/rust/issues/48950> \
                                    for more information).",
C
Camille GILLOT 已提交
533
                                );
T
teymour-aldridge 已提交
534
                                err.help("did you intend to use the type `()` here instead?");
C
Camille GILLOT 已提交
535 536 537
                            }
                        }

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
                        // Return early if the trait is Debug or Display and the invocation
                        // originates within a standard library macro, because the output
                        // is otherwise overwhelming and unhelpful (see #85844 for an
                        // example).

                        let trait_is_debug =
                            self.tcx.is_diagnostic_item(sym::debug_trait, trait_ref.def_id());
                        let trait_is_display =
                            self.tcx.is_diagnostic_item(sym::display_trait, trait_ref.def_id());

                        let in_std_macro =
                            match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
                                Some(macro_def_id) => {
                                    let crate_name = tcx.crate_name(macro_def_id.krate);
                                    crate_name == sym::std || crate_name == sym::core
                                }
                                None => false,
                            };

                        if in_std_macro && (trait_is_debug || trait_is_display) {
                            err.emit();
                            return;
                        }

C
Camille GILLOT 已提交
562 563 564
                        err
                    }

J
Jack Huey 已提交
565
                    ty::PredicateKind::Subtype(predicate) => {
C
Camille GILLOT 已提交
566 567 568 569 570 571
                        // Errors for Subtype predicates show up as
                        // `FulfillmentErrorCode::CodeSubtypeError`,
                        // not selection error.
                        span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
                    }

N
Niko Matsakis 已提交
572 573 574 575 576 577 578
                    ty::PredicateKind::Coerce(predicate) => {
                        // Errors for Coerce predicates show up as
                        // `FulfillmentErrorCode::CodeSubtypeError`,
                        // not selection error.
                        span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
                    }

J
Jack Huey 已提交
579
                    ty::PredicateKind::RegionOutlives(predicate) => {
J
Jack Huey 已提交
580
                        let predicate = bound_predicate.rebind(predicate);
B
Bastian Kauschke 已提交
581
                        let predicate = self.resolve_vars_if_possible(predicate);
C
Camille GILLOT 已提交
582
                        let err = self
583
                            .region_outlives_predicate(&obligation.cause, predicate)
C
Camille GILLOT 已提交
584 585 586 587 588 589 590 591 592 593 594 595
                            .err()
                            .unwrap();
                        struct_span_err!(
                            self.tcx.sess,
                            span,
                            E0279,
                            "the requirement `{}` is not satisfied (`{}`)",
                            predicate,
                            err,
                        )
                    }

J
Jack Huey 已提交
596
                    ty::PredicateKind::Projection(..) | ty::PredicateKind::TypeOutlives(..) => {
B
Bastian Kauschke 已提交
597
                        let predicate = self.resolve_vars_if_possible(obligation.predicate);
C
Camille GILLOT 已提交
598 599 600 601 602 603 604 605 606
                        struct_span_err!(
                            self.tcx.sess,
                            span,
                            E0280,
                            "the requirement `{}` is not satisfied",
                            predicate
                        )
                    }

J
Jack Huey 已提交
607
                    ty::PredicateKind::ObjectSafe(trait_def_id) => {
C
Camille GILLOT 已提交
608 609 610 611
                        let violations = self.tcx.object_safety_violations(trait_def_id);
                        report_object_safety_error(self.tcx, span, trait_def_id, violations)
                    }

J
Jack Huey 已提交
612
                    ty::PredicateKind::ClosureKind(closure_def_id, closure_substs, kind) => {
613
                        let found_kind = self.closure_kind(closure_substs).unwrap();
614 615 616 617
                        let closure_span =
                            self.tcx.sess.source_map().guess_head_span(
                                self.tcx.hir().span_if_local(closure_def_id).unwrap(),
                            );
618 619
                        let hir_id =
                            self.tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local());
C
Camille GILLOT 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
                        let mut err = struct_span_err!(
                            self.tcx.sess,
                            closure_span,
                            E0525,
                            "expected a closure that implements the `{}` trait, \
                             but this closure only implements `{}`",
                            kind,
                            found_kind
                        );

                        err.span_label(
                            closure_span,
                            format!("this closure implements `{}`, not `{}`", found_kind, kind),
                        );
                        err.span_label(
                            obligation.cause.span,
                            format!("the requirement to implement `{}` derives from here", kind),
                        );

                        // Additional context information explaining why the closure only implements
                        // a particular trait.
641 642 643
                        if let Some(typeck_results) = self.in_progress_typeck_results {
                            let typeck_results = typeck_results.borrow();
                            match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
644
                                (ty::ClosureKind::FnOnce, Some((span, place))) => {
C
Camille GILLOT 已提交
645 646 647 648 649
                                    err.span_label(
                                        *span,
                                        format!(
                                            "closure is `FnOnce` because it moves the \
                                         variable `{}` out of its environment",
650
                                            ty::place_to_string_for_capture(tcx, place)
C
Camille GILLOT 已提交
651 652 653
                                        ),
                                    );
                                }
654
                                (ty::ClosureKind::FnMut, Some((span, place))) => {
C
Camille GILLOT 已提交
655 656 657 658 659
                                    err.span_label(
                                        *span,
                                        format!(
                                            "closure is `FnMut` because it mutates the \
                                         variable `{}` here",
660
                                            ty::place_to_string_for_capture(tcx, place)
C
Camille GILLOT 已提交
661 662 663 664 665 666 667 668 669 670 671
                                        ),
                                    );
                                }
                                _ => {}
                            }
                        }

                        err.emit();
                        return;
                    }

J
Jack Huey 已提交
672
                    ty::PredicateKind::WellFormed(ty) => {
J
Jack Huey 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
                        if !self.tcx.sess.opts.debugging_opts.chalk {
                            // WF predicates cannot themselves make
                            // errors. They can only block due to
                            // ambiguity; otherwise, they always
                            // degenerate into other obligations
                            // (which may fail).
                            span_bug!(span, "WF predicate not satisfied for {:?}", ty);
                        } else {
                            // FIXME: we'll need a better message which takes into account
                            // which bounds actually failed to hold.
                            self.tcx.sess.struct_span_err(
                                span,
                                &format!("the type `{}` is not well-formed (chalk)", ty),
                            )
                        }
C
Camille GILLOT 已提交
688 689
                    }

J
Jack Huey 已提交
690
                    ty::PredicateKind::ConstEvaluatable(..) => {
C
Camille GILLOT 已提交
691 692 693 694 695 696 697 698 699
                        // Errors for `ConstEvaluatable` predicates show up as
                        // `SelectionError::ConstEvalFailure`,
                        // not `Unimplemented`.
                        span_bug!(
                            span,
                            "const-evaluatable requirement gave wrong error: `{:?}`",
                            obligation
                        )
                    }
700

J
Jack Huey 已提交
701
                    ty::PredicateKind::ConstEquate(..) => {
702 703 704 705 706 707 708 709 710
                        // Errors for `ConstEquate` predicates show up as
                        // `SelectionError::ConstEvalFailure`,
                        // not `Unimplemented`.
                        span_bug!(
                            span,
                            "const-equate requirement gave wrong error: `{:?}`",
                            obligation
                        )
                    }
711

J
Jack Huey 已提交
712
                    ty::PredicateKind::TypeWellFormedFromEnv(..) => span_bug!(
713 714 715
                        span,
                        "TypeWellFormedFromEnv predicate should only exist in the environment"
                    ),
C
Camille GILLOT 已提交
716 717 718
                }
            }

L
words  
lcnr 已提交
719 720 721
            OutputTypeParameterMismatch(found_trait_ref, expected_trait_ref, _) => {
                let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
                let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
C
Camille GILLOT 已提交
722 723 724 725 726

                if expected_trait_ref.self_ty().references_error() {
                    return;
                }

727 728 729 730
                let found_trait_ty = match found_trait_ref.self_ty().no_bound_vars() {
                    Some(ty) => ty,
                    None => return,
                };
C
Camille GILLOT 已提交
731

L
LeSeulArtichaut 已提交
732
                let found_did = match *found_trait_ty.kind() {
C
Camille GILLOT 已提交
733 734 735
                    ty::Closure(did, _) | ty::Foreign(did) | ty::FnDef(did, _) => Some(did),
                    ty::Adt(def, _) => Some(def.did),
                    _ => None,
736 737
                };

C
Camille GILLOT 已提交
738 739
                let found_span = found_did
                    .and_then(|did| self.tcx.hir().span_if_local(did))
740
                    .map(|sp| self.tcx.sess.source_map().guess_head_span(sp)); // the sp could be an fn def
741

C
Camille GILLOT 已提交
742 743 744 745 746 747 748 749
                if self.reported_closure_mismatch.borrow().contains(&(span, found_span)) {
                    // We check closures twice, with obligations flowing in different directions,
                    // but we want to complain about them only once.
                    return;
                }

                self.reported_closure_mismatch.borrow_mut().insert((span, found_span));

L
LeSeulArtichaut 已提交
750
                let found = match found_trait_ref.skip_binder().substs.type_at(1).kind() {
C
Camille GILLOT 已提交
751 752 753 754 755
                    ty::Tuple(ref tys) => vec![ArgKind::empty(); tys.len()],
                    _ => vec![ArgKind::empty()],
                };

                let expected_ty = expected_trait_ref.skip_binder().substs.type_at(1);
L
LeSeulArtichaut 已提交
756
                let expected = match expected_ty.kind() {
C
Camille GILLOT 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
                    ty::Tuple(ref tys) => tys
                        .iter()
                        .map(|t| ArgKind::from_expected_ty(t.expect_ty(), Some(span)))
                        .collect(),
                    _ => vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())],
                };

                if found.len() == expected.len() {
                    self.report_closure_arg_mismatch(
                        span,
                        found_span,
                        found_trait_ref,
                        expected_trait_ref,
                    )
                } else {
                    let (closure_span, found) = found_did
773 774 775 776
                        .and_then(|did| {
                            let node = self.tcx.hir().get_if_local(did)?;
                            let (found_span, found) = self.get_fn_like_arguments(node)?;
                            Some((Some(found_span), found))
C
Camille GILLOT 已提交
777 778 779 780 781 782 783 784 785 786
                        })
                        .unwrap_or((found_span, found));

                    self.report_arg_count_mismatch(
                        span,
                        closure_span,
                        expected,
                        found,
                        found_trait_ty.is_closure(),
                    )
787 788 789
                }
            }

C
Camille GILLOT 已提交
790 791 792 793
            TraitNotObjectSafe(did) => {
                let violations = self.tcx.object_safety_violations(did);
                report_object_safety_error(self.tcx, span, did, violations)
            }
E
Ellen 已提交
794 795 796 797 798

            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
                bug!(
                    "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
                )
799
            }
E
Ellen 已提交
800
            SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
801
                if !self.tcx.features().generic_const_exprs {
E
Ellen 已提交
802 803 804 805 806 807 808 809
                    let mut err = self.tcx.sess.struct_span_err(
                        span,
                        "constant expression depends on a generic parameter",
                    );
                    // FIXME(const_generics): we should suggest to the user how they can resolve this
                    // issue. However, this is currently not actually possible
                    // (see https://github.com/rust-lang/rust/issues/66962#issuecomment-575907083).
                    //
810
                    // Note that with `feature(generic_const_exprs)` this case should not
E
Ellen 已提交
811 812 813 814 815 816 817
                    // be reachable.
                    err.note("this may fail depending on what value the parameter takes");
                    err.emit();
                    return;
                }

                match obligation.predicate.kind().skip_binder() {
818
                    ty::PredicateKind::ConstEvaluatable(uv) => {
E
Ellen 已提交
819 820
                        let mut err =
                            self.tcx.sess.struct_span_err(span, "unconstrained generic constant");
821
                        let const_span = self.tcx.def_span(uv.def.did);
E
Ellen 已提交
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
                        match self.tcx.sess.source_map().span_to_snippet(const_span) {
                            Ok(snippet) => err.help(&format!(
                                "try adding a `where` bound using this expression: `where [(); {}]:`",
                                snippet
                            )),
                            _ => err.help("consider adding a `where` bound using this expression"),
                        };
                        err
                    }
                    _ => {
                        span_bug!(
                            span,
                            "unexpected non-ConstEvaluatable predicate, this should not be reachable"
                        )
                    }
                }
            }

C
Camille GILLOT 已提交
840
            // Already reported in the query.
E
Ellen 已提交
841
            SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(ErrorReported)) => {
842 843 844 845 846
                // FIXME(eddyb) remove this once `ErrorReported` becomes a proof token.
                self.tcx.sess.delay_span_bug(span, "`ErrorReported` without an error");
                return;
            }

C
Camille GILLOT 已提交
847 848 849 850
            Overflow => {
                bug!("overflow should be handled before the `report_selection_error` path");
            }
        };
851

852
        self.note_obligation_cause(&mut err, &obligation);
C
Camille GILLOT 已提交
853
        self.point_at_returns_when_relevant(&mut err, &obligation);
854

C
Camille GILLOT 已提交
855 856
        err.emit();
    }
857

C
Camille GILLOT 已提交
858 859 860 861
    /// Given some node representing a fn-like thing in the HIR map,
    /// returns a span and `ArgKind` information that describes the
    /// arguments it expects. This can be supplied to
    /// `report_arg_count_mismatch`.
862 863 864 865
    fn get_fn_like_arguments(&self, node: Node<'_>) -> Option<(Span, Vec<ArgKind>)> {
        let sm = self.tcx.sess.source_map();
        let hir = self.tcx.hir();
        Some(match node {
C
Camille GILLOT 已提交
866 867 868 869
            Node::Expr(&hir::Expr {
                kind: hir::ExprKind::Closure(_, ref _decl, id, span, _),
                ..
            }) => (
870 871
                sm.guess_head_span(span),
                hir.body(id)
C
Camille GILLOT 已提交
872 873 874 875 876 877
                    .params
                    .iter()
                    .map(|arg| {
                        if let hir::Pat { kind: hir::PatKind::Tuple(ref args, _), span, .. } =
                            *arg.pat
                        {
878
                            Some(ArgKind::Tuple(
C
Camille GILLOT 已提交
879 880 881
                                Some(span),
                                args.iter()
                                    .map(|pat| {
882 883 884
                                        sm.span_to_snippet(pat.span)
                                            .ok()
                                            .map(|snippet| (snippet, "_".to_owned()))
C
Camille GILLOT 已提交
885
                                    })
886 887
                                    .collect::<Option<Vec<_>>>()?,
                            ))
C
Camille GILLOT 已提交
888
                        } else {
889 890
                            let name = sm.span_to_snippet(arg.pat.span).ok()?;
                            Some(ArgKind::Arg(name, "_".to_owned()))
891
                        }
C
Camille GILLOT 已提交
892
                    })
893
                    .collect::<Option<Vec<ArgKind>>>()?,
C
Camille GILLOT 已提交
894 895 896 897
            ),
            Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. })
            | Node::ImplItem(&hir::ImplItem {
                span,
M
Mark Mansi 已提交
898
                kind: hir::ImplItemKind::Fn(ref sig, _),
C
Camille GILLOT 已提交
899 900 901 902 903 904 905
                ..
            })
            | Node::TraitItem(&hir::TraitItem {
                span,
                kind: hir::TraitItemKind::Fn(ref sig, _),
                ..
            }) => (
906
                sm.guess_head_span(span),
C
Camille GILLOT 已提交
907 908 909
                sig.decl
                    .inputs
                    .iter()
R
Ryan Levick 已提交
910
                    .map(|arg| match arg.kind {
C
Camille GILLOT 已提交
911 912 913 914 915 916 917 918 919
                        hir::TyKind::Tup(ref tys) => ArgKind::Tuple(
                            Some(arg.span),
                            vec![("_".to_owned(), "_".to_owned()); tys.len()],
                        ),
                        _ => ArgKind::empty(),
                    })
                    .collect::<Vec<ArgKind>>(),
            ),
            Node::Ctor(ref variant_data) => {
920
                let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
921
                let span = sm.guess_head_span(span);
C
Camille GILLOT 已提交
922
                (span, vec![ArgKind::empty(); variant_data.fields().len()])
923
            }
C
Camille GILLOT 已提交
924
            _ => panic!("non-FnLike node found: {:?}", node),
925
        })
926 927
    }

C
Camille GILLOT 已提交
928 929 930 931
    /// Reports an error when the number of arguments needed by a
    /// trait match doesn't match the number that the expression
    /// provides.
    fn report_arg_count_mismatch(
932
        &self,
C
Camille GILLOT 已提交
933 934 935 936 937 938 939
        span: Span,
        found_span: Option<Span>,
        expected_args: Vec<ArgKind>,
        found_args: Vec<ArgKind>,
        is_closure: bool,
    ) -> DiagnosticBuilder<'tcx> {
        let kind = if is_closure { "closure" } else { "function" };
940

C
Camille GILLOT 已提交
941 942
        let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
            let arg_length = arguments.len();
943
            let distinct = matches!(other, &[ArgKind::Tuple(..)]);
C
Camille GILLOT 已提交
944 945 946
            match (arg_length, arguments.get(0)) {
                (1, Some(&ArgKind::Tuple(_, ref fields))) => {
                    format!("a single {}-tuple as argument", fields.len())
947
                }
C
Camille GILLOT 已提交
948 949 950 951 952 953 954
                _ => format!(
                    "{} {}argument{}",
                    arg_length,
                    if distinct && arg_length > 1 { "distinct " } else { "" },
                    pluralize!(arg_length)
                ),
            }
955 956
        };

C
Camille GILLOT 已提交
957 958
        let expected_str = args_str(&expected_args, &found_args);
        let found_str = args_str(&found_args, &expected_args);
959 960 961

        let mut err = struct_span_err!(
            self.tcx.sess,
C
Camille GILLOT 已提交
962 963 964 965 966 967
            span,
            E0593,
            "{} is expected to take {}, but it takes {}",
            kind,
            expected_str,
            found_str,
968 969
        );

C
Camille GILLOT 已提交
970
        err.span_label(span, format!("expected {} that takes {}", kind, expected_str));
971

C
Camille GILLOT 已提交
972 973
        if let Some(found_span) = found_span {
            err.span_label(found_span, format!("takes {}", found_str));
974

C
Camille GILLOT 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
            // move |_| { ... }
            // ^^^^^^^^-- def_span
            //
            // move |_| { ... }
            // ^^^^^-- prefix
            let prefix_span = self.tcx.sess.source_map().span_until_non_whitespace(found_span);
            // move |_| { ... }
            //      ^^^-- pipe_span
            let pipe_span =
                if let Some(span) = found_span.trim_start(prefix_span) { span } else { found_span };

            // Suggest to take and ignore the arguments with expected_args_length `_`s if
            // found arguments is empty (assume the user just wants to ignore args in this case).
            // For example, if `expected_args_length` is 2, suggest `|_, _|`.
            if found_args.is_empty() && is_closure {
                let underscores = vec!["_"; expected_args.len()].join(", ");
991
                err.span_suggestion_verbose(
C
Camille GILLOT 已提交
992 993 994
                    pipe_span,
                    &format!(
                        "consider changing the closure to take and ignore the expected argument{}",
995
                        pluralize!(expected_args.len())
C
Camille GILLOT 已提交
996 997 998 999 1000
                    ),
                    format!("|{}|", underscores),
                    Applicability::MachineApplicable,
                );
            }
1001

C
Camille GILLOT 已提交
1002 1003 1004 1005 1006 1007 1008
            if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
                if fields.len() == expected_args.len() {
                    let sugg = fields
                        .iter()
                        .map(|(name, _)| name.to_owned())
                        .collect::<Vec<String>>()
                        .join(", ");
1009
                    err.span_suggestion_verbose(
C
Camille GILLOT 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
                        found_span,
                        "change the closure to take multiple arguments instead of a single tuple",
                        format!("|{}|", sugg),
                        Applicability::MachineApplicable,
                    );
                }
            }
            if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..] {
                if fields.len() == found_args.len() && is_closure {
                    let sugg = format!(
                        "|({}){}|",
                        found_args
                            .iter()
                            .map(|arg| match arg {
                                ArgKind::Arg(name, _) => name.to_owned(),
                                _ => "_".to_owned(),
                            })
                            .collect::<Vec<String>>()
                            .join(", "),
                        // add type annotations if available
                        if found_args.iter().any(|arg| match arg {
                            ArgKind::Arg(_, ty) => ty != "_",
                            _ => false,
                        }) {
                            format!(
                                ": ({})",
                                fields
                                    .iter()
                                    .map(|(_, ty)| ty.to_owned())
                                    .collect::<Vec<String>>()
                                    .join(", ")
                            )
                        } else {
                            String::new()
                        },
                    );
1046
                    err.span_suggestion_verbose(
C
Camille GILLOT 已提交
1047 1048 1049 1050 1051 1052 1053 1054
                        found_span,
                        "change the closure to accept a tuple instead of individual arguments",
                        sugg,
                        Applicability::MachineApplicable,
                    );
                }
            }
        }
1055

C
Camille GILLOT 已提交
1056
        err
1057
    }
C
Camille GILLOT 已提交
1058 1059 1060 1061 1062
}

trait InferCtxtPrivExt<'tcx> {
    // returns if `cond` not occurring implies that `error` does not occur - i.e., that
    // `error` occurring implies that `cond` occurs.
1063
    fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool;
1064

C
Camille GILLOT 已提交
1065
    fn report_fulfillment_error(
1066
        &self,
C
Camille GILLOT 已提交
1067 1068 1069 1070
        error: &FulfillmentError<'tcx>,
        body_id: Option<hir::BodyId>,
        fallback_has_occurred: bool,
    );
1071

C
Camille GILLOT 已提交
1072 1073 1074 1075 1076
    fn report_projection_error(
        &self,
        obligation: &PredicateObligation<'tcx>,
        error: &MismatchedProjectionTypes<'tcx>,
    );
1077

C
Camille GILLOT 已提交
1078
    fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool;
1079

C
Camille GILLOT 已提交
1080
    fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str>;
1081

C
Camille GILLOT 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
    fn find_similar_impl_candidates(
        &self,
        trait_ref: ty::PolyTraitRef<'tcx>,
    ) -> Vec<ty::TraitRef<'tcx>>;

    fn report_similar_impl_candidates(
        &self,
        impl_candidates: Vec<ty::TraitRef<'tcx>>,
        err: &mut DiagnosticBuilder<'_>,
    );
1092 1093 1094 1095 1096

    /// Gets the parent trait chain start
    fn get_parent_trait_ref(
        &self,
        code: &ObligationCauseCode<'tcx>,
C
Camille GILLOT 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
    ) -> Option<(String, Option<Span>)>;

    /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
    /// with the same path as `trait_ref`, a help message about
    /// a probable version mismatch is added to `err`
    fn note_version_mismatch(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: &ty::PolyTraitRef<'tcx>,
    );

1108 1109 1110 1111
    /// Creates a `PredicateObligation` with `new_self_ty` replacing the existing type in the
    /// `trait_ref`.
    ///
    /// For this to work, `new_self_ty` must have no escaping bound variables.
1112
    fn mk_trait_obligation_with_new_self_ty(
C
Camille GILLOT 已提交
1113 1114
        &self,
        param_env: ty::ParamEnv<'tcx>,
B
Bastian Kauschke 已提交
1115
        trait_ref: ty::PolyTraitRef<'tcx>,
1116
        new_self_ty: Ty<'tcx>,
C
Camille GILLOT 已提交
1117
    ) -> PredicateObligation<'tcx>;
1118

C
Camille GILLOT 已提交
1119
    fn maybe_report_ambiguity(
1120 1121
        &self,
        obligation: &PredicateObligation<'tcx>,
C
Camille GILLOT 已提交
1122 1123
        body_id: Option<hir::BodyId>,
    );
1124

C
Camille GILLOT 已提交
1125 1126 1127 1128 1129
    fn predicate_can_apply(
        &self,
        param_env: ty::ParamEnv<'tcx>,
        pred: ty::PolyTraitRef<'tcx>,
    ) -> bool;
1130

C
Camille GILLOT 已提交
1131 1132
    fn note_obligation_cause(
        &self,
1133
        err: &mut DiagnosticBuilder<'tcx>,
C
Camille GILLOT 已提交
1134 1135
        obligation: &PredicateObligation<'tcx>,
    );
1136

C
Camille GILLOT 已提交
1137 1138
    fn suggest_unsized_bound_if_applicable(
        &self,
1139
        err: &mut DiagnosticBuilder<'tcx>,
C
Camille GILLOT 已提交
1140 1141
        obligation: &PredicateObligation<'tcx>,
    );
1142

1143 1144 1145 1146 1147 1148 1149
    fn maybe_suggest_unsized_generics(
        &self,
        err: &mut DiagnosticBuilder<'tcx>,
        span: Span,
        node: Node<'hir>,
    );

1150 1151 1152 1153 1154 1155 1156
    fn maybe_indirection_for_unsized(
        &self,
        err: &mut DiagnosticBuilder<'tcx>,
        item: &'hir Item<'hir>,
        param: &'hir GenericParam<'hir>,
    ) -> bool;

C
Camille GILLOT 已提交
1157 1158 1159 1160 1161 1162
    fn is_recursive_obligation(
        &self,
        obligated_types: &mut Vec<&ty::TyS<'tcx>>,
        cause_code: &ObligationCauseCode<'tcx>,
    ) -> bool;
}
1163

C
Camille GILLOT 已提交
1164 1165 1166
impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
    // returns if `cond` not occurring implies that `error` does not occur - i.e., that
    // `error` occurring implies that `cond` occurs.
1167
    fn error_implies(&self, cond: ty::Predicate<'tcx>, error: ty::Predicate<'tcx>) -> bool {
C
Camille GILLOT 已提交
1168 1169 1170
        if cond == error {
            return true;
        }
1171

1172
        // FIXME: It should be possible to deal with `ForAll` in a cleaner way.
J
Jack Huey 已提交
1173 1174
        let bound_error = error.kind();
        let (cond, error) = match (cond.kind().skip_binder(), bound_error.skip_binder()) {
D
Deadbeef 已提交
1175
            (ty::PredicateKind::Trait(..), ty::PredicateKind::Trait(error)) => {
J
Jack Huey 已提交
1176
                (cond, bound_error.rebind(error))
1177
            }
C
Camille GILLOT 已提交
1178 1179 1180 1181 1182
            _ => {
                // FIXME: make this work in other cases too.
                return false;
            }
        };
1183

1184
        for obligation in super::elaborate_predicates(self.tcx, std::iter::once(cond)) {
J
Jack Huey 已提交
1185
            let bound_predicate = obligation.predicate.kind();
D
Deadbeef 已提交
1186
            if let ty::PredicateKind::Trait(implication) = bound_predicate.skip_binder() {
C
Camille GILLOT 已提交
1187
                let error = error.to_poly_trait_ref();
J
Jack Huey 已提交
1188
                let implication = bound_predicate.rebind(implication.trait_ref);
C
Camille GILLOT 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
                // FIXME: I'm just not taking associated types at all here.
                // Eventually I'll need to implement param-env-aware
                // `Γ₁ ⊦ φ₁ => Γ₂ ⊦ φ₂` logic.
                let param_env = ty::ParamEnv::empty();
                if self.can_sub(param_env, error, implication).is_ok() {
                    debug!("error_implies: {:?} -> {:?} -> {:?}", cond, error, implication);
                    return true;
                }
            }
        }
1199

C
Camille GILLOT 已提交
1200 1201
        false
    }
1202

C
Camille GILLOT 已提交
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    fn report_fulfillment_error(
        &self,
        error: &FulfillmentError<'tcx>,
        body_id: Option<hir::BodyId>,
        fallback_has_occurred: bool,
    ) {
        debug!("report_fulfillment_error({:?})", error);
        match error.code {
            FulfillmentErrorCode::CodeSelectionError(ref selection_error) => {
                self.report_selection_error(
1213 1214
                    error.obligation.clone(),
                    &error.root_obligation,
C
Camille GILLOT 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
                    selection_error,
                    fallback_has_occurred,
                    error.points_at_arg_span,
                );
            }
            FulfillmentErrorCode::CodeProjectionError(ref e) => {
                self.report_projection_error(&error.obligation, e);
            }
            FulfillmentErrorCode::CodeAmbiguity => {
                self.maybe_report_ambiguity(&error.obligation, body_id);
            }
            FulfillmentErrorCode::CodeSubtypeError(ref expected_found, ref err) => {
                self.report_mismatched_types(
                    &error.obligation.cause,
                    expected_found.expected,
                    expected_found.found,
                    err.clone(),
                )
                .emit();
            }
1235 1236 1237 1238 1239 1240 1241 1242 1243
            FulfillmentErrorCode::CodeConstEquateError(ref expected_found, ref err) => {
                self.report_mismatched_consts(
                    &error.obligation.cause,
                    expected_found.expected,
                    expected_found.found,
                    err.clone(),
                )
                .emit();
            }
C
Camille GILLOT 已提交
1244 1245
        }
    }
1246

C
Camille GILLOT 已提交
1247 1248 1249 1250 1251
    fn report_projection_error(
        &self,
        obligation: &PredicateObligation<'tcx>,
        error: &MismatchedProjectionTypes<'tcx>,
    ) {
B
Bastian Kauschke 已提交
1252
        let predicate = self.resolve_vars_if_possible(obligation.predicate);
1253

C
Camille GILLOT 已提交
1254 1255 1256
        if predicate.references_error() {
            return;
        }
1257

C
Camille GILLOT 已提交
1258 1259 1260 1261
        self.probe(|_| {
            let err_buf;
            let mut err = &error.err;
            let mut values = None;
1262

C
Camille GILLOT 已提交
1263 1264 1265 1266
            // try to find the mismatched types to report the error with.
            //
            // this can fail if the problem was higher-ranked, in which
            // cause I have no idea for a good error message.
J
Jack Huey 已提交
1267 1268
            let bound_predicate = predicate.kind();
            if let ty::PredicateKind::Projection(data) = bound_predicate.skip_binder() {
C
Camille GILLOT 已提交
1269 1270 1271 1272
                let mut selcx = SelectionContext::new(self);
                let (data, _) = self.replace_bound_vars_with_fresh_vars(
                    obligation.cause.span,
                    infer::LateBoundRegionConversionTime::HigherRankedType,
B
Bastian Kauschke 已提交
1273
                    bound_predicate.rebind(data),
C
Camille GILLOT 已提交
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
                );
                let mut obligations = vec![];
                let normalized_ty = super::normalize_projection_type(
                    &mut selcx,
                    obligation.param_env,
                    data.projection_ty,
                    obligation.cause.clone(),
                    0,
                    &mut obligations,
                );
1284

C
Camille GILLOT 已提交
1285 1286 1287 1288
                debug!(
                    "report_projection_error obligation.cause={:?} obligation.param_env={:?}",
                    obligation.cause, obligation.param_env
                );
1289

C
Camille GILLOT 已提交
1290 1291 1292 1293
                debug!(
                    "report_projection_error normalized_ty={:?} data.ty={:?}",
                    normalized_ty, data.ty
                );
1294

M
Mark Rousskov 已提交
1295
                let is_normalized_ty_expected = !matches!(
1296
                    obligation.cause.code.peel_derives(),
M
Mark Rousskov 已提交
1297 1298 1299
                    ObligationCauseCode::ItemObligation(_)
                        | ObligationCauseCode::BindingObligation(_, _)
                        | ObligationCauseCode::ObjectCastObligation(_)
1300
                        | ObligationCauseCode::OpaqueType
M
Mark Rousskov 已提交
1301
                );
1302

C
Camille GILLOT 已提交
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                if let Err(error) = self.at(&obligation.cause, obligation.param_env).eq_exp(
                    is_normalized_ty_expected,
                    normalized_ty,
                    data.ty,
                ) {
                    values = Some(infer::ValuePairs::Types(ExpectedFound::new(
                        is_normalized_ty_expected,
                        normalized_ty,
                        data.ty,
                    )));
1313

C
Camille GILLOT 已提交
1314 1315
                    err_buf = error;
                    err = &err_buf;
1316 1317 1318
                }
            }

C
Camille GILLOT 已提交
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
            let msg = format!("type mismatch resolving `{}`", predicate);
            let error_id = (DiagnosticMessageId::ErrorId(271), Some(obligation.cause.span), msg);
            let fresh = self.tcx.sess.one_time_diagnostics.borrow_mut().insert(error_id);
            if fresh {
                let mut diag = struct_span_err!(
                    self.tcx.sess,
                    obligation.cause.span,
                    E0271,
                    "type mismatch resolving `{}`",
                    predicate
                );
                self.note_type_err(&mut diag, &obligation.cause, None, values, err);
                self.note_obligation_cause(&mut diag, obligation);
                diag.emit();
            }
        });
    }
1336

C
Camille GILLOT 已提交
1337 1338 1339 1340
    fn fuzzy_match_tys(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
        /// returns the fuzzy category of a given type, or None
        /// if the type can be equated to any type.
        fn type_category(t: Ty<'_>) -> Option<u32> {
L
LeSeulArtichaut 已提交
1341
            match t.kind() {
C
Camille GILLOT 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
                ty::Bool => Some(0),
                ty::Char => Some(1),
                ty::Str => Some(2),
                ty::Int(..) | ty::Uint(..) | ty::Infer(ty::IntVar(..)) => Some(3),
                ty::Float(..) | ty::Infer(ty::FloatVar(..)) => Some(4),
                ty::Ref(..) | ty::RawPtr(..) => Some(5),
                ty::Array(..) | ty::Slice(..) => Some(6),
                ty::FnDef(..) | ty::FnPtr(..) => Some(7),
                ty::Dynamic(..) => Some(8),
                ty::Closure(..) => Some(9),
                ty::Tuple(..) => Some(10),
                ty::Projection(..) => Some(11),
                ty::Param(..) => Some(12),
                ty::Opaque(..) => Some(13),
                ty::Never => Some(14),
                ty::Adt(adt, ..) => match adt.adt_kind() {
                    AdtKind::Struct => Some(15),
                    AdtKind::Union => Some(16),
                    AdtKind::Enum => Some(17),
                },
                ty::Generator(..) => Some(18),
                ty::Foreign(..) => Some(19),
                ty::GeneratorWitness(..) => Some(20),
1365
                ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
C
Camille GILLOT 已提交
1366 1367
            }
        }
1368

C
Camille GILLOT 已提交
1369
        match (type_category(a), type_category(b)) {
L
LeSeulArtichaut 已提交
1370
            (Some(cat_a), Some(cat_b)) => match (a.kind(), b.kind()) {
C
Camille GILLOT 已提交
1371 1372 1373 1374 1375 1376 1377
                (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) => def_a == def_b,
                _ => cat_a == cat_b,
            },
            // infer and error can be equated to all types
            _ => true,
        }
    }
1378

C
Camille GILLOT 已提交
1379 1380 1381 1382 1383 1384 1385 1386
    fn describe_generator(&self, body_id: hir::BodyId) -> Option<&'static str> {
        self.tcx.hir().body(body_id).generator_kind.map(|gen_kind| match gen_kind {
            hir::GeneratorKind::Gen => "a generator",
            hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block) => "an async block",
            hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn) => "an async function",
            hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Closure) => "an async closure",
        })
    }
1387

C
Camille GILLOT 已提交
1388 1389 1390 1391 1392 1393
    fn find_similar_impl_candidates(
        &self,
        trait_ref: ty::PolyTraitRef<'tcx>,
    ) -> Vec<ty::TraitRef<'tcx>> {
        let simp = fast_reject::simplify_type(self.tcx, trait_ref.skip_binder().self_ty(), true);
        let all_impls = self.tcx.all_impls(trait_ref.def_id());
1394

C
Camille GILLOT 已提交
1395 1396
        match simp {
            Some(simp) => all_impls
1397
                .filter_map(|def_id| {
C
Camille GILLOT 已提交
1398 1399 1400 1401 1402 1403 1404
                    let imp = self.tcx.impl_trait_ref(def_id).unwrap();
                    let imp_simp = fast_reject::simplify_type(self.tcx, imp.self_ty(), true);
                    if let Some(imp_simp) = imp_simp {
                        if simp != imp_simp {
                            return None;
                        }
                    }
1405 1406 1407
                    if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative {
                        return None;
                    }
C
Camille GILLOT 已提交
1408 1409 1410
                    Some(imp)
                })
                .collect(),
1411 1412 1413 1414 1415 1416 1417 1418
            None => all_impls
                .filter_map(|def_id| {
                    if self.tcx.impl_polarity(def_id) == ty::ImplPolarity::Negative {
                        return None;
                    }
                    self.tcx.impl_trait_ref(def_id)
                })
                .collect(),
C
Camille GILLOT 已提交
1419 1420
        }
    }
1421

C
Camille GILLOT 已提交
1422 1423 1424 1425 1426 1427 1428 1429
    fn report_similar_impl_candidates(
        &self,
        impl_candidates: Vec<ty::TraitRef<'tcx>>,
        err: &mut DiagnosticBuilder<'_>,
    ) {
        if impl_candidates.is_empty() {
            return;
        }
1430

C
Camille GILLOT 已提交
1431 1432
        let len = impl_candidates.len();
        let end = if impl_candidates.len() <= 5 { impl_candidates.len() } else { 4 };
1433

C
Camille GILLOT 已提交
1434 1435 1436 1437 1438 1439 1440
        let normalize = |candidate| {
            self.tcx.infer_ctxt().enter(|ref infcx| {
                let normalized = infcx
                    .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
                    .normalize(candidate)
                    .ok();
                match normalized {
1441 1442
                    Some(normalized) => format!("\n  {}", normalized.value),
                    None => format!("\n  {}", candidate),
1443
                }
C
Camille GILLOT 已提交
1444 1445
            })
        };
1446

C
Camille GILLOT 已提交
1447 1448
        // Sort impl candidates so that ordering is consistent for UI tests.
        let mut normalized_impl_candidates =
B
Bastian Kauschke 已提交
1449
            impl_candidates.iter().copied().map(normalize).collect::<Vec<String>>();
1450

C
Camille GILLOT 已提交
1451 1452 1453 1454
        // Sort before taking the `..end` range,
        // because the ordering of `impl_candidates` may not be deterministic:
        // https://github.com/rust-lang/rust/pull/57475#issuecomment-455519507
        normalized_impl_candidates.sort();
1455

C
Camille GILLOT 已提交
1456 1457 1458 1459 1460 1461
        err.help(&format!(
            "the following implementations were found:{}{}",
            normalized_impl_candidates[..end].join(""),
            if len > 5 { format!("\nand {} others", len - 4) } else { String::new() }
        ));
    }
1462

C
Camille GILLOT 已提交
1463 1464 1465 1466 1467 1468
    /// Gets the parent trait chain start
    fn get_parent_trait_ref(
        &self,
        code: &ObligationCauseCode<'tcx>,
    ) -> Option<(String, Option<Span>)> {
        match code {
1469
            ObligationCauseCode::BuiltinDerivedObligation(data) => {
B
Bastian Kauschke 已提交
1470
                let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
C
Camille GILLOT 已提交
1471 1472 1473 1474
                match self.get_parent_trait_ref(&data.parent_code) {
                    Some(t) => Some(t),
                    None => {
                        let ty = parent_trait_ref.skip_binder().self_ty();
1475 1476
                        let span = TyCategory::from_ty(self.tcx, ty)
                            .map(|(_, def_id)| self.tcx.def_span(def_id));
C
Camille GILLOT 已提交
1477 1478 1479
                        Some((ty.to_string(), span))
                    }
                }
1480
            }
C
Camille GILLOT 已提交
1481 1482
            _ => None,
        }
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
    }

    /// If the `Self` type of the unsatisfied trait `trait_ref` implements a trait
    /// with the same path as `trait_ref`, a help message about
    /// a probable version mismatch is added to `err`
    fn note_version_mismatch(
        &self,
        err: &mut DiagnosticBuilder<'_>,
        trait_ref: &ty::PolyTraitRef<'tcx>,
    ) {
        let get_trait_impl = |trait_def_id| {
1494
            self.tcx.find_map_relevant_impl(trait_def_id, trait_ref.skip_binder().self_ty(), Some)
1495 1496
        };
        let required_trait_path = self.tcx.def_path_str(trait_ref.def_id());
C
Camille GILLOT 已提交
1497
        let all_traits = self.tcx.all_traits(());
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
        let traits_with_same_path: std::collections::BTreeSet<_> = all_traits
            .iter()
            .filter(|trait_def_id| **trait_def_id != trait_ref.def_id())
            .filter(|trait_def_id| self.tcx.def_path_str(**trait_def_id) == required_trait_path)
            .collect();
        for trait_with_same_path in traits_with_same_path {
            if let Some(impl_def_id) = get_trait_impl(*trait_with_same_path) {
                let impl_span = self.tcx.def_span(impl_def_id);
                err.span_help(impl_span, "trait impl with same name found");
                let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
                let crate_msg = format!(
                    "perhaps two different versions of crate `{}` are being used?",
                    trait_crate
                );
                err.note(&crate_msg);
            }
        }
    }

1517
    fn mk_trait_obligation_with_new_self_ty(
1518 1519
        &self,
        param_env: ty::ParamEnv<'tcx>,
B
Bastian Kauschke 已提交
1520
        trait_ref: ty::PolyTraitRef<'tcx>,
1521
        new_self_ty: Ty<'tcx>,
1522
    ) -> PredicateObligation<'tcx> {
1523 1524
        assert!(!new_self_ty.has_escaping_bound_vars());

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
        let trait_ref = trait_ref.map_bound_ref(|tr| ty::TraitRef {
            substs: self.tcx.mk_substs_trait(new_self_ty, &tr.substs[1..]),
            ..*tr
        });

        Obligation::new(
            ObligationCause::dummy(),
            param_env,
            trait_ref.without_const().to_predicate(self.tcx),
        )
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
    }

    fn maybe_report_ambiguity(
        &self,
        obligation: &PredicateObligation<'tcx>,
        body_id: Option<hir::BodyId>,
    ) {
        // Unable to successfully determine, probably means
        // insufficient type information, but could mean
        // ambiguous impls. The latter *ought* to be a
        // coherence violation, so we don't report it here.

B
Bastian Kauschke 已提交
1547
        let predicate = self.resolve_vars_if_possible(obligation.predicate);
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
        let span = obligation.cause.span;

        debug!(
            "maybe_report_ambiguity(predicate={:?}, obligation={:?} body_id={:?}, code={:?})",
            predicate, obligation, body_id, obligation.cause.code,
        );

        // Ambiguity errors are often caused as fallout from earlier
        // errors. So just ignore them if this infcx is tainted.
        if self.is_tainted_by_errors() {
            return;
        }

J
Jack Huey 已提交
1561
        let bound_predicate = predicate.kind();
1562
        let mut err = match bound_predicate.skip_binder() {
D
Deadbeef 已提交
1563
            ty::PredicateKind::Trait(data) => {
J
Jack Huey 已提交
1564
                let trait_ref = bound_predicate.rebind(data.trait_ref);
1565
                debug!("trait_ref {:?}", trait_ref);
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

                if predicate.references_error() {
                    return;
                }
                // Typically, this ambiguity should only happen if
                // there are unresolved type inference variables
                // (otherwise it would suggest a coherence
                // failure). But given #21974 that is not necessarily
                // the case -- we can have multiple where clauses that
                // are only distinguished by a region, which results
                // in an ambiguity even when all types are fully
                // known, since we don't dispatch based on region
                // relationships.

1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590
                // Pick the first substitution that still contains inference variables as the one
                // we're going to emit an error for. If there are none (see above), fall back to
                // the substitution for `Self`.
                let subst = {
                    let substs = data.trait_ref.substs;
                    substs
                        .iter()
                        .find(|s| s.has_infer_types_or_consts())
                        .unwrap_or_else(|| substs[0])
                };

1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
                // This is kind of a hack: it frequently happens that some earlier
                // error prevents types from being fully inferred, and then we get
                // a bunch of uninteresting errors saying something like "<generic
                // #0> doesn't implement Sized".  It may even be true that we
                // could just skip over all checks where the self-ty is an
                // inference variable, but I was afraid that there might be an
                // inference variable created, registered as an obligation, and
                // then never forced by writeback, and hence by skipping here we'd
                // be ignoring the fact that we don't KNOW the type works
                // out. Though even that would probably be harmless, given that
                // we're only talking about builtin traits, which are known to be
                // inhabited. We used to check for `self.tcx.sess.has_errors()` to
                // avoid inundating the user with unnecessary errors, but we now
M
Matthias Krüger 已提交
1604
                // check upstream for type errors and don't add the obligations to
1605
                // begin with in those cases.
1606
                if self.tcx.lang_items().sized_trait() == Some(trait_ref.def_id()) {
1607 1608
                    self.emit_inference_failure_err(body_id, span, subst, vec![], ErrorCode::E0282)
                        .emit();
1609 1610
                    return;
                }
1611 1612 1613 1614 1615 1616 1617 1618
                let impl_candidates = self.find_similar_impl_candidates(trait_ref);
                let mut err = self.emit_inference_failure_err(
                    body_id,
                    span,
                    subst,
                    impl_candidates,
                    ErrorCode::E0283,
                );
1619
                err.note(&format!("cannot satisfy `{}`", predicate));
1620 1621 1622 1623 1624 1625 1626 1627 1628
                if let ObligationCauseCode::ItemObligation(def_id) = obligation.cause.code {
                    self.suggest_fully_qualified_path(&mut err, def_id, span, trait_ref.def_id());
                } else if let (
                    Ok(ref snippet),
                    ObligationCauseCode::BindingObligation(ref def_id, _),
                ) =
                    (self.tcx.sess.source_map().span_to_snippet(span), &obligation.cause.code)
                {
                    let generics = self.tcx.generics_of(*def_id);
1629
                    if generics.params.iter().any(|p| p.name != kw::SelfUpper)
1630
                        && !snippet.ends_with('>')
1631
                        && !generics.has_impl_trait()
1632
                        && !self.tcx.fn_trait_kind_from_lang_item(*def_id).is_some()
1633
                    {
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
                        // FIXME: To avoid spurious suggestions in functions where type arguments
                        // where already supplied, we check the snippet to make sure it doesn't
                        // end with a turbofish. Ideally we would have access to a `PathSegment`
                        // instead. Otherwise we would produce the following output:
                        //
                        // error[E0283]: type annotations needed
                        //   --> $DIR/issue-54954.rs:3:24
                        //    |
                        // LL | const ARR_LEN: usize = Tt::const_val::<[i8; 123]>();
                        //    |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^
                        //    |                        |
                        //    |                        cannot infer type
                        //    |                        help: consider specifying the type argument
                        //    |                        in the function call:
                        //    |                        `Tt::const_val::<[i8; 123]>::<T>`
                        // ...
                        // LL |     const fn const_val<T: Sized>() -> usize {
1651
                        //    |                        - required by this bound in `Tt::const_val`
1652
                        //    |
1653
                        //    = note: cannot satisfy `_: Tt`
1654

1655 1656
                        err.span_suggestion_verbose(
                            span.shrink_to_hi(),
1657 1658
                            &format!(
                                "consider specifying the type argument{} in the function call",
1659
                                pluralize!(generics.params.len()),
1660 1661
                            ),
                            format!(
1662
                                "::<{}>",
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
                                generics
                                    .params
                                    .iter()
                                    .map(|p| p.name.to_string())
                                    .collect::<Vec<String>>()
                                    .join(", ")
                            ),
                            Applicability::HasPlaceholders,
                        );
                    }
                }
                err
            }

J
Jack Huey 已提交
1677
            ty::PredicateKind::WellFormed(arg) => {
1678 1679
                // Same hacky approach as above to avoid deluging user
                // with error messages.
1680
                if arg.references_error() || self.tcx.sess.has_errors() {
1681 1682 1683
                    return;
                }

1684
                self.emit_inference_failure_err(body_id, span, arg, vec![], ErrorCode::E0282)
B
Bastian Kauschke 已提交
1685 1686
            }

J
Jack Huey 已提交
1687
            ty::PredicateKind::Subtype(data) => {
1688 1689 1690 1691
                if data.references_error() || self.tcx.sess.has_errors() {
                    // no need to overload user in such cases
                    return;
                }
B
Bastian Kauschke 已提交
1692
                let SubtypePredicate { a_is_expected: _, a, b } = data;
1693 1694
                // both must be type variables, or the other would've been instantiated
                assert!(a.is_ty_var() && b.is_ty_var());
1695
                self.emit_inference_failure_err(body_id, span, a.into(), vec![], ErrorCode::E0282)
1696
            }
J
Jack Huey 已提交
1697
            ty::PredicateKind::Projection(data) => {
1698
                let self_ty = data.projection_ty.self_ty();
1699
                let ty = data.ty;
1700 1701 1702
                if predicate.references_error() {
                    return;
                }
1703 1704
                if self_ty.needs_infer() && ty.needs_infer() {
                    // We do this for the `foo.collect()?` case to produce a suggestion.
B
Bastian Kauschke 已提交
1705 1706 1707 1708
                    let mut err = self.emit_inference_failure_err(
                        body_id,
                        span,
                        self_ty.into(),
1709
                        vec![],
B
Bastian Kauschke 已提交
1710 1711
                        ErrorCode::E0284,
                    );
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
                    err.note(&format!("cannot satisfy `{}`", predicate));
                    err
                } else {
                    let mut err = struct_span_err!(
                        self.tcx.sess,
                        span,
                        E0284,
                        "type annotations needed: cannot satisfy `{}`",
                        predicate,
                    );
                    err.span_label(span, &format!("cannot satisfy `{}`", predicate));
                    err
                }
1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
            }

            _ => {
                if self.tcx.sess.has_errors() {
                    return;
                }
                let mut err = struct_span_err!(
                    self.tcx.sess,
                    span,
                    E0284,
1735
                    "type annotations needed: cannot satisfy `{}`",
1736 1737
                    predicate,
                );
1738
                err.span_label(span, &format!("cannot satisfy `{}`", predicate));
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763
                err
            }
        };
        self.note_obligation_cause(&mut err, obligation);
        err.emit();
    }

    /// Returns `true` if the trait predicate may apply for *some* assignment
    /// to the type parameters.
    fn predicate_can_apply(
        &self,
        param_env: ty::ParamEnv<'tcx>,
        pred: ty::PolyTraitRef<'tcx>,
    ) -> bool {
        struct ParamToVarFolder<'a, 'tcx> {
            infcx: &'a InferCtxt<'a, 'tcx>,
            var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
        }

        impl<'a, 'tcx> TypeFolder<'tcx> for ParamToVarFolder<'a, 'tcx> {
            fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
                self.infcx.tcx
            }

            fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
L
LeSeulArtichaut 已提交
1764
                if let ty::Param(ty::ParamTy { name, .. }) = *ty.kind() {
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787
                    let infcx = self.infcx;
                    self.var_map.entry(ty).or_insert_with(|| {
                        infcx.next_ty_var(TypeVariableOrigin {
                            kind: TypeVariableOriginKind::TypeParameterDefinition(name, None),
                            span: DUMMY_SP,
                        })
                    })
                } else {
                    ty.super_fold_with(self)
                }
            }
        }

        self.probe(|_| {
            let mut selcx = SelectionContext::new(self);

            let cleaned_pred =
                pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });

            let cleaned_pred = super::project::normalize(
                &mut selcx,
                param_env,
                ObligationCause::dummy(),
B
Bastian Kauschke 已提交
1788
                cleaned_pred,
1789 1790 1791
            )
            .value;

1792 1793 1794
            let obligation = Obligation::new(
                ObligationCause::dummy(),
                param_env,
1795
                cleaned_pred.without_const().to_predicate(selcx.tcx()),
1796
            );
1797 1798 1799 1800 1801 1802 1803

            self.predicate_may_hold(&obligation)
        })
    }

    fn note_obligation_cause(
        &self,
1804
        err: &mut DiagnosticBuilder<'tcx>,
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814
        obligation: &PredicateObligation<'tcx>,
    ) {
        // First, attempt to add note to this error with an async-await-specific
        // message, and fall back to regular note otherwise.
        if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
            self.note_obligation_cause_code(
                err,
                &obligation.predicate,
                &obligation.cause.code,
                &mut vec![],
1815
                &mut Default::default(),
1816
            );
1817 1818 1819 1820 1821 1822
            self.suggest_unsized_bound_if_applicable(err, obligation);
        }
    }

    fn suggest_unsized_bound_if_applicable(
        &self,
1823
        err: &mut DiagnosticBuilder<'tcx>,
1824 1825
        obligation: &PredicateObligation<'tcx>,
    ) {
B
Bastian Kauschke 已提交
1826
        let (pred, item_def_id, span) =
J
Jack Huey 已提交
1827 1828
            match (obligation.predicate.kind().skip_binder(), obligation.cause.code.peel_derives())
            {
B
Bastian Kauschke 已提交
1829
                (
D
Deadbeef 已提交
1830
                    ty::PredicateKind::Trait(pred),
B
Bastian Kauschke 已提交
1831 1832 1833 1834
                    &ObligationCauseCode::BindingObligation(item_def_id, span),
                ) => (pred, item_def_id, span),
                _ => return,
            };
1835 1836 1837 1838
        debug!(
            "suggest_unsized_bound_if_applicable: pred={:?} item_def_id={:?} span={:?}",
            pred, item_def_id, span
        );
1839
        let node = match (
1840
            self.tcx.hir().get_if_local(item_def_id),
1841 1842 1843 1844 1845
            Some(pred.def_id()) == self.tcx.lang_items().sized_trait(),
        ) {
            (Some(node), true) => node,
            _ => return,
        };
1846 1847 1848 1849 1850 1851 1852 1853 1854
        self.maybe_suggest_unsized_generics(err, span, node);
    }

    fn maybe_suggest_unsized_generics(
        &self,
        err: &mut DiagnosticBuilder<'tcx>,
        span: Span,
        node: Node<'hir>,
    ) {
1855 1856 1857 1858
        let generics = match node.generics() {
            Some(generics) => generics,
            None => return,
        };
T
Taylor Yu 已提交
1859 1860 1861 1862 1863 1864 1865 1866
        let sized_trait = self.tcx.lang_items().sized_trait();
        debug!("maybe_suggest_unsized_generics: generics.params={:?}", generics.params);
        debug!("maybe_suggest_unsized_generics: generics.where_clause={:?}", generics.where_clause);
        let param = generics
            .params
            .iter()
            .filter(|param| param.span == span)
            .filter(|param| {
1867 1868
                // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
                // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
T
Taylor Yu 已提交
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
                param
                    .bounds
                    .iter()
                    .all(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) != sized_trait)
            })
            .next();
        let param = match param {
            Some(param) => param,
            _ => return,
        };
        debug!("maybe_suggest_unsized_generics: param={:?}", param);
        match node {
            hir::Node::Item(
                item
                @
                hir::Item {
1885
                    // Only suggest indirection for uses of type parameters in ADTs.
T
Taylor Yu 已提交
1886 1887 1888 1889 1890 1891 1892
                    kind:
                        hir::ItemKind::Enum(..) | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..),
                    ..
                },
            ) => {
                if self.maybe_indirection_for_unsized(err, item, param) {
                    return;
1893 1894
                }
            }
T
Taylor Yu 已提交
1895 1896
            _ => {}
        };
1897
        // Didn't add an indirection suggestion, so add a general suggestion to relax `Sized`.
T
Taylor Yu 已提交
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
        let (span, separator) = match param.bounds {
            [] => (span.shrink_to_hi(), ":"),
            [.., bound] => (bound.span().shrink_to_hi(), " +"),
        };
        err.span_suggestion_verbose(
            span,
            "consider relaxing the implicit `Sized` restriction",
            format!("{} ?Sized", separator),
            Applicability::MachineApplicable,
        );
1908 1909
    }

1910 1911 1912 1913 1914 1915 1916 1917
    fn maybe_indirection_for_unsized(
        &self,
        err: &mut DiagnosticBuilder<'tcx>,
        item: &'hir Item<'hir>,
        param: &'hir GenericParam<'hir>,
    ) -> bool {
        // Suggesting `T: ?Sized` is only valid in an ADT if `T` is only used in a
        // borrow. `struct S<'a, T: ?Sized>(&'a T);` is valid, `struct S<T: ?Sized>(T);`
1918
        // is not. Look for invalid "bare" parameter uses, and suggest using indirection.
1919 1920 1921
        let mut visitor =
            FindTypeParam { param: param.name.ident().name, invalid_spans: vec![], nested: false };
        visitor.visit_item(item);
T
Taylor Yu 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930
        if visitor.invalid_spans.is_empty() {
            return false;
        }
        let mut multispan: MultiSpan = param.span.into();
        multispan.push_span_label(
            param.span,
            format!("this could be changed to `{}: ?Sized`...", param.name.ident()),
        );
        for sp in visitor.invalid_spans {
1931
            multispan.push_span_label(
T
Taylor Yu 已提交
1932 1933
                sp,
                format!("...if indirection were used here: `Box<{}>`", param.name.ident()),
1934
            );
1935
        }
T
Taylor Yu 已提交
1936 1937 1938 1939 1940 1941 1942 1943 1944
        err.span_help(
            multispan,
            &format!(
                "you could relax the implicit `Sized` bound on `{T}` if it were \
                used through indirection like `&{T}` or `Box<{T}>`",
                T = param.name.ident(),
            ),
        );
        true
1945 1946 1947 1948 1949 1950 1951 1952
    }

    fn is_recursive_obligation(
        &self,
        obligated_types: &mut Vec<&ty::TyS<'tcx>>,
        cause_code: &ObligationCauseCode<'tcx>,
    ) -> bool {
        if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
B
Bastian Kauschke 已提交
1953
            let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);
1954 1955 1956 1957 1958 1959 1960 1961 1962

            if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
                return true;
            }
        }
        false
    }
}

1963 1964 1965 1966
/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
/// `param: ?Sized` would be a valid constraint.
struct FindTypeParam {
    param: rustc_span::Symbol,
1967 1968
    invalid_spans: Vec<Span>,
    nested: bool,
1969 1970 1971 1972 1973 1974 1975 1976 1977
}

impl<'v> Visitor<'v> for FindTypeParam {
    type Map = rustc_hir::intravisit::ErasedMap<'v>;

    fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
        hir::intravisit::NestedVisitorMap::None
    }

1978 1979 1980 1981
    fn visit_where_predicate(&mut self, _: &'v hir::WherePredicate<'v>) {
        // Skip where-clauses, to avoid suggesting indirection for type parameters found there.
    }

1982
    fn visit_ty(&mut self, ty: &hir::Ty<'_>) {
E
Esteban Küber 已提交
1983 1984 1985 1986 1987 1988
        // We collect the spans of all uses of the "bare" type param, like in `field: T` or
        // `field: (T, T)` where we could make `T: ?Sized` while skipping cases that are known to be
        // valid like `field: &'a T` or `field: *mut T` and cases that *might* have further `Sized`
        // obligations like `Box<T>` and `Vec<T>`, but we perform no extra analysis for those cases
        // and suggest `T: ?Sized` regardless of their obligations. This is fine because the errors
        // in that case should make what happened clear enough.
1989
        match ty.kind {
1990
            hir::TyKind::Ptr(_) | hir::TyKind::Rptr(..) | hir::TyKind::TraitObject(..) => {}
1991 1992 1993
            hir::TyKind::Path(hir::QPath::Resolved(None, path))
                if path.segments.len() == 1 && path.segments[0].ident.name == self.param =>
            {
1994
                if !self.nested {
1995
                    debug!("FindTypeParam::visit_ty: ty={:?}", ty);
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006
                    self.invalid_spans.push(ty.span);
                }
            }
            hir::TyKind::Path(_) => {
                let prev = self.nested;
                self.nested = true;
                hir::intravisit::walk_ty(self, ty);
                self.nested = prev;
            }
            _ => {
                hir::intravisit::walk_ty(self, ty);
2007 2008 2009 2010 2011
            }
        }
    }
}

C
Camille GILLOT 已提交
2012 2013 2014
pub fn recursive_type_with_infinite_size_error(
    tcx: TyCtxt<'tcx>,
    type_def_id: DefId,
2015 2016
    spans: Vec<Span>,
) {
C
Camille GILLOT 已提交
2017 2018
    assert!(type_def_id.is_local());
    let span = tcx.hir().span_if_local(type_def_id).unwrap();
2019
    let span = tcx.sess.source_map().guess_head_span(span);
2020 2021 2022
    let path = tcx.def_path_str(type_def_id);
    let mut err =
        struct_span_err!(tcx.sess, span, E0072, "recursive type `{}` has infinite size", path);
C
Camille GILLOT 已提交
2023
    err.span_label(span, "recursive type has infinite size");
2024 2025 2026 2027 2028 2029 2030
    for &span in &spans {
        err.span_label(span, "recursive without indirection");
    }
    let msg = format!(
        "insert some indirection (e.g., a `Box`, `Rc`, or `&`) to make `{}` representable",
        path,
    );
2031 2032 2033 2034 2035 2036
    if spans.len() <= 4 {
        err.multipart_suggestion(
            &msg,
            spans
                .iter()
                .flat_map(|&span| {
2037 2038 2039
                    vec![
                        (span.shrink_to_lo(), "Box<".to_string()),
                        (span.shrink_to_hi(), ">".to_string()),
2040 2041 2042 2043 2044 2045 2046 2047
                    ]
                    .into_iter()
                })
                .collect(),
            Applicability::HasPlaceholders,
        );
    } else {
        err.help(&msg);
2048 2049
    }
    err.emit();
C
Camille GILLOT 已提交
2050 2051
}

2052 2053 2054 2055 2056 2057 2058
/// Summarizes information
#[derive(Clone)]
pub enum ArgKind {
    /// An argument of non-tuple type. Parameters are (name, ty)
    Arg(String, String),

    /// An argument of tuple type. For a "found" argument, the span is
F
Frank Steffahn 已提交
2059
    /// the location in the source of the pattern. For an "expected"
2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
    /// argument, it will be None. The vector is a list of (name, ty)
    /// strings for the components of the tuple.
    Tuple(Option<Span>, Vec<(String, String)>),
}

impl ArgKind {
    fn empty() -> ArgKind {
        ArgKind::Arg("_".to_owned(), "_".to_owned())
    }

    /// Creates an `ArgKind` from the expected type of an
    /// argument. It has no name (`_`) and an optional source span.
    pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
L
LeSeulArtichaut 已提交
2073 2074
        match t.kind() {
            ty::Tuple(tys) => ArgKind::Tuple(
2075 2076 2077 2078 2079 2080 2081
                span,
                tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
            ),
            _ => ArgKind::Arg("_".to_owned(), t.to_string()),
        }
    }
}