compare_impl_item.rs 90.4 KB
Newer Older
L
lcnr 已提交
1
use super::potentially_plural_count;
2
use crate::errors::LifetimesOrBoundsMismatchOnTrait;
B
Boxy 已提交
3
use hir::def_id::{DefId, LocalDefId};
4
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet};
5 6 7
use rustc_errors::{
    pluralize, struct_span_err, Applicability, DiagnosticId, ErrorGuaranteed, MultiSpan,
};
8 9
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
10
use rustc_hir::intravisit;
11
use rustc_hir::{GenericParamKind, ImplItemKind};
12
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
13
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
14
use rustc_infer::infer::{self, InferCtxt, TyCtxtInferExt};
15
use rustc_infer::traits::util;
16 17
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::util::ExplicitSelf;
18
use rustc_middle::ty::{
19
    self, GenericArgs, Ty, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt,
20
};
21
use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
22
use rustc_span::{Span, DUMMY_SP};
C
Cameron Steffen 已提交
23
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
24
use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
L
lcnr 已提交
25 26 27
use rustc_trait_selection::traits::{
    self, ObligationCause, ObligationCauseCode, ObligationCtxt, Reveal,
};
28
use std::borrow::Cow;
J
Josh Stone 已提交
29
use std::iter;
30 31 32 33 34 35

/// Checks that a method from an impl conforms to the signature of
/// the same method as declared in the trait.
///
/// # Parameters
///
A
Alexander Regueiro 已提交
36 37 38
/// - `impl_m`: type of the method we are checking
/// - `trait_m`: the method in the trait
/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
M
Michael Goulet 已提交
39
pub(super) fn compare_impl_method<'tcx>(
40
    tcx: TyCtxt<'tcx>,
41 42
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
43 44
    impl_trait_ref: ty::TraitRef<'tcx>,
) {
M
Mark Rousskov 已提交
45
    debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
46

47
    let _: Result<_, ErrorGuaranteed> = try {
48
        check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, false)?;
49 50 51 52 53 54 55 56
        compare_method_predicate_entailment(
            tcx,
            impl_m,
            trait_m,
            impl_trait_ref,
            CheckImpliedWfMode::Check,
        )?;
    };
N
Niko Matsakis 已提交
57 58
}

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/// Checks a bunch of different properties of the impl/trait methods for
/// compatibility, such as asyncness, number of argument, self receiver kind,
/// and number of early- and late-bound generics.
fn check_method_is_structurally_compatible<'tcx>(
    tcx: TyCtxt<'tcx>,
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
    delay: bool,
) -> Result<(), ErrorGuaranteed> {
    compare_self_type(tcx, impl_m, trait_m, impl_trait_ref, delay)?;
    compare_number_of_generics(tcx, impl_m, trait_m, delay)?;
    compare_generic_param_kinds(tcx, impl_m, trait_m, delay)?;
    compare_number_of_method_arguments(tcx, impl_m, trait_m, delay)?;
    compare_synthetic_generics(tcx, impl_m, trait_m, delay)?;
    compare_asyncness(tcx, impl_m, trait_m, delay)?;
    check_region_bounds_on_impl_item(tcx, impl_m, trait_m, delay)?;
    Ok(())
}

79
/// This function is best explained by example. Consider a trait with its implementation:
80
///
81 82 83 84 85
/// ```rust
/// trait Trait<'t, T> {
///     // `trait_m`
///     fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
/// }
86
///
87
/// struct Foo;
88
///
89 90 91 92 93
/// impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
///     // `impl_m`
///     fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo { Foo }
/// }
/// ```
94 95 96 97 98
///
/// We wish to decide if those two method types are compatible.
/// For this we have to show that, assuming the bounds of the impl hold, the
/// bounds of `trait_m` imply the bounds of `impl_m`.
///
99
/// We start out with `trait_to_impl_args`, that maps the trait
100 101 102
/// type parameters to impl type parameters. This is taken from the
/// impl trait reference:
///
103
/// ```rust,ignore (pseudo-Rust)
104
/// trait_to_impl_args = {'t => 'j, T => &'i U, Self => Foo}
105
/// ```
106
///
107
/// We create a mapping `dummy_args` that maps from the impl type
108 109 110 111 112 113
/// parameters to fresh types and regions. For type parameters,
/// this is the identity transform, but we could as well use any
/// placeholder types. For regions, we convert from bound to free
/// regions (Note: but only early-bound regions, i.e., those
/// declared on the impl or used in type parameter bounds).
///
114
/// ```rust,ignore (pseudo-Rust)
115
/// impl_to_placeholder_args = {'i => 'i0, U => U0, N => N0 }
116
/// ```
117
///
118
/// Now we can apply `placeholder_args` to the type of the impl method
119 120 121
/// to yield a new function type in terms of our fresh, placeholder
/// types:
///
122
/// ```rust,ignore (pseudo-Rust)
123
/// <'b> fn(t: &'i0 U0, m: &'b N0) -> Foo
124
/// ```
125 126 127
///
/// We now want to extract and substitute the type of the *trait*
/// method and compare it. To do so, we must create a compound
128 129
/// substitution by combining `trait_to_impl_args` and
/// `impl_to_placeholder_args`, and also adding a mapping for the method
130 131 132
/// type parameters. We extend the mapping to also include
/// the method parameters.
///
133
/// ```rust,ignore (pseudo-Rust)
134
/// trait_to_placeholder_args = { T => &'i0 U0, Self => Foo, M => N0 }
135
/// ```
136 137 138
///
/// Applying this to the trait method type yields:
///
139
/// ```rust,ignore (pseudo-Rust)
140
/// <'a> fn(t: &'i0 U0, m: &'a N0) -> Foo
141
/// ```
142 143
///
/// This type is also the same but the name of the bound region (`'a`
144
/// vs `'b`). However, the normal subtyping rules on fn types handle
145 146 147 148 149 150
/// this kind of equivalency just fine.
///
/// We now use these substitutions to ensure that all declared bounds are
/// satisfied by the implementation's method.
///
/// We do this by creating a parameter environment which contains a
151 152
/// substitution corresponding to `impl_to_placeholder_args`. We then build
/// `trait_to_placeholder_args` and use it to convert the predicates contained
153 154 155 156
/// in the `trait_m` generics to the placeholder form.
///
/// Finally we register each of these predicates as an obligation and check that
/// they hold.
157
#[instrument(level = "debug", skip(tcx, impl_trait_ref))]
158
fn compare_method_predicate_entailment<'tcx>(
159
    tcx: TyCtxt<'tcx>,
160 161
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
162
    impl_trait_ref: ty::TraitRef<'tcx>,
163
    check_implied_wf: CheckImpliedWfMode,
164
) -> Result<(), ErrorGuaranteed> {
165
    let trait_to_impl_args = impl_trait_ref.args;
166

T
Taylor Cramer 已提交
167
    // This node-id should be used for the `body_id` field on each
168 169 170 171
    // `ObligationCause` (and the `FnCtxt`).
    //
    // FIXME(@lcnr): remove that after removing `cause.body_id` from
    // obligations.
172
    let impl_m_def_id = impl_m.def_id.expect_local();
173
    let impl_m_span = tcx.def_span(impl_m_def_id);
M
Michael Goulet 已提交
174
    let cause = ObligationCause::new(
175
        impl_m_span,
176
        impl_m_def_id,
177
        ObligationCauseCode::CompareImplItemObligation {
178
            impl_item_def_id: impl_m_def_id,
179
            trait_item_def_id: trait_m.def_id,
180
            kind: impl_m.kind,
181
        },
182
    );
183

N
Niko Matsakis 已提交
184
    // Create mapping from impl to placeholder.
185
    let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id);
186

N
Niko Matsakis 已提交
187
    // Create mapping from trait to placeholder.
188 189 190
    let trait_to_placeholder_args =
        impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args);
    debug!("compare_impl_method: trait_to_placeholder_args={:?}", trait_to_placeholder_args);
191

192 193
    let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
    let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
194

N
Niko Matsakis 已提交
195 196 197 198 199
    // Create obligations for each predicate declared by the impl
    // definition in the context of the trait's parameter
    // environment. We can't just use `impl_env.caller_bounds`,
    // however, because we want to replace all late-bound regions with
    // region variables.
200
    let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
201
    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
N
Niko Matsakis 已提交
202 203 204 205 206 207 208 209 210 211

    debug!("compare_impl_method: impl_bounds={:?}", hybrid_preds);

    // This is the only tricky bit of the new way we check implementation methods
    // We need to build a set of predicates where only the method-level bounds
    // are from the trait and we assume all other bounds from the implementation
    // to be previously satisfied.
    //
    // We then register the obligations from the impl_m and check to see
    // if all constraints hold.
212 213
    hybrid_preds.predicates.extend(
        trait_m_predicates
214
            .instantiate_own(tcx, trait_to_placeholder_args)
215 216
            .map(|(predicate, _)| predicate),
    );
N
Niko Matsakis 已提交
217

N
Niko Matsakis 已提交
218
    // Construct trait parameter environment and then shift it into the placeholder viewpoint.
N
Niko Matsakis 已提交
219 220
    // The key step here is to update the caller_bounds's predicates to be
    // the new hybrid bounds we computed.
221
    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_def_id);
D
Deadbeef 已提交
222
    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds.predicates), Reveal::UserFacing);
L
lcnr 已提交
223
    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
224

225 226
    let infcx = &tcx.infer_ctxt().build();
    let ocx = ObligationCtxt::new(infcx);
227

228
    debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
229

230
    let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_args);
231
    for (predicate, span) in impl_m_own_bounds {
232
        let normalize_cause = traits::ObligationCause::misc(span, impl_m_def_id);
233
        let predicate = ocx.normalize(&normalize_cause, param_env, predicate);
234

235 236
        let cause = ObligationCause::new(
            span,
237
            impl_m_def_id,
238
            ObligationCauseCode::CompareImplItemObligation {
239
                impl_item_def_id: impl_m_def_id,
240 241 242
                trait_item_def_id: trait_m.def_id,
                kind: impl_m.kind,
            },
S
scalexm 已提交
243
        );
244
        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
245
    }
L
lcnr 已提交
246

247 248 249 250 251 252 253 254 255 256 257 258 259 260
    // We now need to check that the signature of the impl method is
    // compatible with that of the trait method. We do this by
    // checking that `impl_fty <: trait_fty`.
    //
    // FIXME. Unfortunately, this doesn't quite work right now because
    // associated type normalization is not integrated into subtype
    // checks. For the comparison to be valid, we need to
    // normalize the associated types in the impl/trait methods
    // first. However, because function types bind regions, just
    // calling `normalize_associated_types_in` would have no effect on
    // any associated types appearing in the fn arguments or return
    // type.

    // Compute placeholder form of impl and trait method tys.
261
    let mut wf_tys = FxIndexSet::default();
M
Mark Rousskov 已提交
262

263
    let unnormalized_impl_sig = infcx.instantiate_binder_with_fresh_vars(
264 265
        impl_m_span,
        infer::HigherRankedType,
266
        tcx.fn_sig(impl_m.def_id).instantiate_identity(),
267
    );
M
Mark Rousskov 已提交
268

269
    let norm_cause = ObligationCause::misc(impl_m_span, impl_m_def_id);
270 271
    let impl_sig = ocx.normalize(&norm_cause, param_env, unnormalized_impl_sig);
    debug!("compare_impl_method: impl_fty={:?}", impl_sig);
272

273
    let trait_sig = tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_placeholder_args);
274 275 276 277 278 279
    let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, trait_sig);

    // Next, add all inputs and output as well-formed tys. Importantly,
    // we have to do this before normalization, since the normalized ty may
    // not contain the input parameters. See issue #87748.
    wf_tys.extend(trait_sig.inputs_and_output.iter());
280
    let trait_sig = ocx.normalize(&norm_cause, param_env, trait_sig);
281 282 283
    // We also have to add the normalized trait signature
    // as we don't normalize during implied bounds computation.
    wf_tys.extend(trait_sig.inputs_and_output.iter());
284
    let trait_fty = Ty::new_fn_ptr(tcx, ty::Binder::dummy(trait_sig));
285 286 287 288 289 290 291 292 293

    debug!("compare_impl_method: trait_fty={:?}", trait_fty);

    // FIXME: We'd want to keep more accurate spans than "the method signature" when
    // processing the comparison between the trait and impl fn, but we sadly lose them
    // and point at the whole signature when a trait bound or specific input or output
    // type would be more appropriate. In other places we have a `Vec<Span>`
    // corresponding to their `Vec<Predicate>`, but we don't have that here.
    // Fixing this would improve the output of test `issue-83765.rs`.
294
    let result = ocx.sup(&cause, param_env, trait_sig, impl_sig);
M
Mark Rousskov 已提交
295

296
    if let Err(terr) = result {
297
        debug!(?impl_sig, ?trait_sig, ?terr, "sub_types failed");
298

299 300
        let emitted = report_trait_method_mismatch(
            &infcx,
M
Michael Goulet 已提交
301
            cause,
302
            terr,
303 304
            (trait_m, trait_sig),
            (impl_m, impl_sig),
M
Michael Goulet 已提交
305
            impl_trait_ref,
306
        );
307
        return Err(emitted);
308
    }
309

310
    if check_implied_wf == CheckImpliedWfMode::Check && !(impl_sig, trait_sig).references_error() {
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        // See #108544. Annoying, we can end up in cases where, because of winnowing,
        // we pick param env candidates over a more general impl, leading to more
        // stricter lifetime requirements than we would otherwise need. This can
        // trigger the lint. Instead, let's only consider type outlives and
        // region outlives obligations.
        //
        // FIXME(-Ztrait-solver=next): Try removing this hack again once
        // the new solver is stable.
        let mut wf_args: smallvec::SmallVec<[_; 4]> =
            unnormalized_impl_sig.inputs_and_output.iter().map(|ty| ty.into()).collect();
        // Annoyingly, asking for the WF predicates of an array (with an unevaluated const (only?))
        // will give back the well-formed predicate of the same array.
        let mut wf_args_seen: FxHashSet<_> = wf_args.iter().copied().collect();
        while let Some(arg) = wf_args.pop() {
            let Some(obligations) = rustc_trait_selection::traits::wf::obligations(
                infcx,
                param_env,
                impl_m_def_id,
                0,
                arg,
                impl_m_span,
            ) else {
                continue;
            };
            for obligation in obligations {
                match obligation.predicate.kind().skip_binder() {
                    ty::PredicateKind::Clause(
                        ty::ClauseKind::RegionOutlives(..) | ty::ClauseKind::TypeOutlives(..),
                    ) => ocx.register_obligation(obligation),
                    ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(arg)) => {
                        if wf_args_seen.insert(arg) {
                            wf_args.push(arg)
                        }
                    }
                    _ => {}
                }
            }
        }
349
    }
350

351 352
    // Check that all obligations are satisfied by the implementation's
    // version.
353 354
    let errors = ocx.select_all_or_error();
    if !errors.is_empty() {
355 356
        match check_implied_wf {
            CheckImpliedWfMode::Check => {
357
                let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id);
358
                return compare_method_predicate_entailment(
359 360 361 362 363 364 365 366
                    tcx,
                    impl_m,
                    trait_m,
                    impl_trait_ref,
                    CheckImpliedWfMode::Skip,
                )
                .map(|()| {
                    // If the skip-mode was successful, emit a lint.
367
                    emit_implied_wf_lint(infcx.tcx, impl_m, impl_m_hir_id, vec![]);
368 369 370
                });
            }
            CheckImpliedWfMode::Skip => {
371
                let reported = infcx.err_ctxt().report_fulfillment_errors(&errors);
372 373 374
                return Err(reported);
            }
        }
375 376
    }

377 378 379
    // Finally, resolve all regions. This catches wily misuses of
    // lifetime parameters.
    let outlives_env = OutlivesEnvironment::with_bounds(
380
        param_env,
381
        infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys.clone()),
382
    );
383 384 385 386
    let errors = infcx.resolve_regions(&outlives_env);
    if !errors.is_empty() {
        // FIXME(compiler-errors): This can be simplified when IMPLIED_BOUNDS_ENTAILMENT
        // becomes a hard error (i.e. ideally we'd just call `resolve_regions_and_report_errors`
387
        let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id);
388 389
        match check_implied_wf {
            CheckImpliedWfMode::Check => {
390
                return compare_method_predicate_entailment(
391 392 393 394 395 396 397
                    tcx,
                    impl_m,
                    trait_m,
                    impl_trait_ref,
                    CheckImpliedWfMode::Skip,
                )
                .map(|()| {
398 399 400 401 402 403 404 405
                    let bad_args = extract_bad_args_for_implies_lint(
                        tcx,
                        &errors,
                        (trait_m, trait_sig),
                        // Unnormalized impl sig corresponds to the HIR types written
                        (impl_m, unnormalized_impl_sig),
                        impl_m_hir_id,
                    );
406
                    // If the skip-mode was successful, emit a lint.
407
                    emit_implied_wf_lint(tcx, impl_m, impl_m_hir_id, bad_args);
408 409 410 411
                });
            }
            CheckImpliedWfMode::Skip => {
                if infcx.tainted_by_errors().is_none() {
412
                    infcx.err_ctxt().report_region_errors(impl_m_def_id, &errors);
413 414 415 416 417 418
                }
                return Err(tcx
                    .sess
                    .delay_span_bug(rustc_span::DUMMY_SP, "error should have been emitted"));
            }
        }
419
    }
420 421 422 423

    Ok(())
}

424 425 426
fn extract_bad_args_for_implies_lint<'tcx>(
    tcx: TyCtxt<'tcx>,
    errors: &[infer::RegionResolutionError<'tcx>],
427 428
    (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
    (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    hir_id: hir::HirId,
) -> Vec<(Span, Option<String>)> {
    let mut blame_generics = vec![];
    for error in errors {
        // Look for the subregion origin that contains an input/output type
        let origin = match error {
            infer::RegionResolutionError::ConcreteFailure(o, ..) => o,
            infer::RegionResolutionError::GenericBoundFailure(o, ..) => o,
            infer::RegionResolutionError::SubSupConflict(_, _, o, ..) => o,
            infer::RegionResolutionError::UpperBoundUniverseConflict(.., o, _) => o,
        };
        // Extract (possible) input/output types from origin
        match origin {
            infer::SubregionOrigin::Subtype(trace) => {
                if let Some((a, b)) = trace.values.ty() {
                    blame_generics.extend([a, b]);
                }
            }
            infer::SubregionOrigin::RelateParamBound(_, ty, _) => blame_generics.push(*ty),
            infer::SubregionOrigin::ReferenceOutlivesReferent(ty, _) => blame_generics.push(*ty),
            _ => {}
        }
    }

    let fn_decl = tcx.hir().fn_decl_by_hir_id(hir_id).unwrap();
    let opt_ret_ty = match fn_decl.output {
        hir::FnRetTy::DefaultReturn(_) => None,
        hir::FnRetTy::Return(ty) => Some(ty),
    };

    // Map late-bound regions from trait to impl, so the names are right.
    let mapping = std::iter::zip(
461 462
        tcx.fn_sig(trait_m.def_id).skip_binder().bound_vars(),
        tcx.fn_sig(impl_m.def_id).skip_binder().bound_vars(),
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    )
    .filter_map(|(impl_bv, trait_bv)| {
        if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
            && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
        {
            Some((impl_bv, trait_bv))
        } else {
            None
        }
    })
    .collect();

    // For each arg, see if it was in the "blame" of any of the region errors.
    // If so, then try to produce a suggestion to replace the argument type with
    // one from the trait.
    let mut bad_args = vec![];
    for (idx, (ty, hir_ty)) in
        std::iter::zip(impl_sig.inputs_and_output, fn_decl.inputs.iter().chain(opt_ret_ty))
            .enumerate()
    {
        let expected_ty = trait_sig.inputs_and_output[idx]
            .fold_with(&mut RemapLateBound { tcx, mapping: &mapping });
        if blame_generics.iter().any(|blame| ty.contains(*blame)) {
            let expected_ty_sugg = expected_ty.to_string();
            bad_args.push((
                hir_ty.span,
                // Only suggest something if it actually changed.
                (expected_ty_sugg != ty.to_string()).then_some(expected_ty_sugg),
            ));
        }
    }

    bad_args
}

struct RemapLateBound<'a, 'tcx> {
    tcx: TyCtxt<'tcx>,
    mapping: &'a FxHashMap<ty::BoundRegionKind, ty::BoundRegionKind>,
}

503
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for RemapLateBound<'_, 'tcx> {
504
    fn interner(&self) -> TyCtxt<'tcx> {
505 506 507 508 509
        self.tcx
    }

    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
        if let ty::ReFree(fr) = *r {
510 511
            ty::Region::new_free(
                self.tcx,
512 513 514
                fr.scope,
                self.mapping.get(&fr.bound_region).copied().unwrap_or(fr.bound_region),
            )
515 516 517 518 519 520 521 522
        } else {
            r
        }
    }
}

fn emit_implied_wf_lint<'tcx>(
    tcx: TyCtxt<'tcx>,
523
    impl_m: ty::AssocItem,
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
    hir_id: hir::HirId,
    bad_args: Vec<(Span, Option<String>)>,
) {
    let span: MultiSpan = if bad_args.is_empty() {
        tcx.def_span(impl_m.def_id).into()
    } else {
        bad_args.iter().map(|(span, _)| *span).collect::<Vec<_>>().into()
    };
    tcx.struct_span_lint_hir(
        rustc_session::lint::builtin::IMPLIED_BOUNDS_ENTAILMENT,
        hir_id,
        span,
        "impl method assumes more implied bounds than the corresponding trait method",
        |lint| {
            let bad_args: Vec<_> =
                bad_args.into_iter().filter_map(|(span, sugg)| Some((span, sugg?))).collect();
            if !bad_args.is_empty() {
                lint.multipart_suggestion(
                    format!(
                        "replace {} type{} to make the impl signature compatible",
                        pluralize!("this", bad_args.len()),
                        pluralize!(bad_args.len())
                    ),
                    bad_args,
                    Applicability::MaybeIncorrect,
                );
            }
            lint
        },
    );
}

556 557 558 559 560 561
#[derive(Debug, PartialEq, Eq)]
enum CheckImpliedWfMode {
    /// Checks implied well-formedness of the impl method. If it fails, we will
    /// re-check with `Skip`, and emit a lint if it succeeds.
    Check,
    /// Skips checking implied well-formedness of the impl method, but will emit
562
    /// a lint if the `compare_method_predicate_entailment` succeeded. This means that
563 564 565
    /// the reason that we had failed earlier during `Check` was due to the impl
    /// having stronger requirements than the trait.
    Skip,
566 567
}

568 569
fn compare_asyncness<'tcx>(
    tcx: TyCtxt<'tcx>,
570 571
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
572
    delay: bool,
573 574
) -> Result<(), ErrorGuaranteed> {
    if tcx.asyncness(trait_m.def_id) == hir::IsAsync::Async {
575
        match tcx.fn_sig(impl_m.def_id).skip_binder().skip_binder().output().kind() {
576 577 578
            ty::Alias(ty::Opaque, ..) => {
                // allow both `async fn foo()` and `fn foo() -> impl Future`
            }
579
            ty::Error(_) => {
580 581 582
                // We don't know if it's ok, but at least it's already an error.
            }
            _ => {
583 584 585 586 587 588 589 590
                return Err(tcx
                    .sess
                    .create_err(crate::errors::AsyncTraitImplShouldBeAsync {
                        span: tcx.def_span(impl_m.def_id),
                        method_name: trait_m.name,
                        trait_item_span: tcx.hir().span_if_local(trait_m.def_id),
                    })
                    .emit_unless(delay));
591 592 593 594 595 596 597
            }
        };
    }

    Ok(())
}

M
Michael Goulet 已提交
598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
/// Given a method def-id in an impl, compare the method signature of the impl
/// against the trait that it's implementing. In doing so, infer the hidden types
/// that this method's signature provides to satisfy each return-position `impl Trait`
/// in the trait signature.
///
/// The method is also responsible for making sure that the hidden types for each
/// RPITIT actually satisfy the bounds of the `impl Trait`, i.e. that if we infer
/// `impl Trait = Foo`, that `Foo: Trait` holds.
///
/// For example, given the sample code:
///
/// ```
/// #![feature(return_position_impl_trait_in_trait)]
///
/// use std::ops::Deref;
///
/// trait Foo {
///     fn bar() -> impl Deref<Target = impl Sized>;
///              // ^- RPITIT #1        ^- RPITIT #2
/// }
///
/// impl Foo for () {
///     fn bar() -> Box<String> { Box::new(String::new()) }
/// }
/// ```
///
/// The hidden types for the RPITITs in `bar` would be inferred to:
///     * `impl Deref` (RPITIT #1) = `Box<String>`
///     * `impl Sized` (RPITIT #2) = `String`
///
/// The relationship between these two types is straightforward in this case, but
/// may be more tenuously connected via other `impl`s and normalization rules for
/// cases of more complicated nested RPITITs.
631
#[instrument(skip(tcx), level = "debug", ret)]
M
Michael Goulet 已提交
632
pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>(
633
    tcx: TyCtxt<'tcx>,
M
Michael Goulet 已提交
634
    impl_m_def_id: LocalDefId,
635
) -> Result<&'tcx FxHashMap<DefId, ty::EarlyBinder<Ty<'tcx>>>, ErrorGuaranteed> {
M
Michael Goulet 已提交
636
    let impl_m = tcx.opt_associated_item(impl_m_def_id.to_def_id()).unwrap();
637
    let trait_m = tcx.opt_associated_item(impl_m.trait_item_def_id.unwrap()).unwrap();
638
    let impl_trait_ref =
639
        tcx.impl_trait_ref(impl_m.impl_container(tcx).unwrap()).unwrap().instantiate_identity();
M
Michael Goulet 已提交
640
    let param_env = tcx.param_env(impl_m_def_id);
641

642 643
    // First, check a few of the same things as `compare_impl_method`,
    // just so we don't ICE during substitution later.
644
    check_method_is_structurally_compatible(tcx, impl_m, trait_m, impl_trait_ref, true)?;
645

646
    let trait_to_impl_args = impl_trait_ref.args;
647

648
    let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m_def_id);
649
    let return_span = tcx.hir().fn_decl_by_hir_id(impl_m_hir_id).unwrap().output.span();
M
Michael Goulet 已提交
650
    let cause = ObligationCause::new(
651
        return_span,
652
        impl_m_def_id,
653
        ObligationCauseCode::CompareImplItemObligation {
654
            impl_item_def_id: impl_m_def_id,
655 656 657 658 659 660
            trait_item_def_id: trait_m.def_id,
            kind: impl_m.kind,
        },
    );

    // Create mapping from impl to placeholder.
661
    let impl_to_placeholder_args = GenericArgs::identity_for_item(tcx, impl_m.def_id);
662 663

    // Create mapping from trait to placeholder.
664 665
    let trait_to_placeholder_args =
        impl_to_placeholder_args.rebase_onto(tcx, impl_m.container_id(tcx), trait_to_impl_args);
666

667 668
    let infcx = &tcx.infer_ctxt().build();
    let ocx = ObligationCtxt::new(infcx);
669

670
    // Normalize the impl signature with fresh variables for lifetime inference.
671
    let norm_cause = ObligationCause::misc(return_span, impl_m_def_id);
672
    let impl_sig = ocx.normalize(
673
        &norm_cause,
674
        param_env,
675 676 677 678
        tcx.liberate_late_bound_regions(
            impl_m.def_id,
            tcx.fn_sig(impl_m.def_id).instantiate_identity(),
        ),
679
    );
680
    impl_sig.error_reported()?;
681
    let impl_return_ty = impl_sig.output();
682

683 684 685 686
    // Normalize the trait signature with liberated bound vars, passing it through
    // the ImplTraitInTraitCollector, which gathers all of the RPITITs and replaces
    // them with inference variables.
    // We will use these inference variables to collect the hidden types of RPITITs.
687
    let mut collector = ImplTraitInTraitCollector::new(&ocx, return_span, param_env, impl_m_def_id);
688 689 690 691
    let unnormalized_trait_sig = infcx
        .instantiate_binder_with_fresh_vars(
            return_span,
            infer::HigherRankedType,
692
            tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_to_placeholder_args),
693 694
        )
        .fold_with(&mut collector);
695

696 697 698 699 700 701 702
    if !unnormalized_trait_sig.output().references_error() {
        debug_assert_ne!(
            collector.types.len(),
            0,
            "expect >1 RPITITs in call to `collect_return_position_impl_trait_in_trait_tys`"
        );
    }
703

704
    let trait_sig = ocx.normalize(&norm_cause, param_env, unnormalized_trait_sig);
705
    trait_sig.error_reported()?;
706
    let trait_return_ty = trait_sig.output();
707

708
    let wf_tys = FxIndexSet::from_iter(
709 710
        unnormalized_trait_sig.inputs_and_output.iter().chain(trait_sig.inputs_and_output.iter()),
    );
711

L
lcnr 已提交
712 713
    match ocx.eq(&cause, param_env, trait_return_ty, impl_return_ty) {
        Ok(()) => {}
714 715 716 717 718 719 720 721 722 723 724 725 726 727
        Err(terr) => {
            let mut diag = struct_span_err!(
                tcx.sess,
                cause.span(),
                E0053,
                "method `{}` has an incompatible return type for trait",
                trait_m.name
            );
            let hir = tcx.hir();
            infcx.err_ctxt().note_type_err(
                &mut diag,
                &cause,
                hir.get_if_local(impl_m.def_id)
                    .and_then(|node| node.fn_decl())
728
                    .map(|decl| (decl.output.span(), Cow::from("return type in trait"))),
729 730 731 732 733 734 735 736 737 738 739
                Some(infer::ValuePairs::Terms(ExpectedFound {
                    expected: trait_return_ty.into(),
                    found: impl_return_ty.into(),
                })),
                terr,
                false,
                false,
            );
            return Err(diag.emit());
        }
    }
740

741 742
    debug!(?trait_sig, ?impl_sig, "equating function signatures");

743 744 745
    // Unify the whole function signature. We need to do this to fully infer
    // the lifetimes of the return type, but do this after unifying just the
    // return types, since we want to avoid duplicating errors from
746
    // `compare_method_predicate_entailment`.
747
    match ocx.eq(&cause, param_env, trait_sig, impl_sig) {
L
lcnr 已提交
748
        Ok(()) => {}
749
        Err(terr) => {
750
            // This function gets called during `compare_method_predicate_entailment` when normalizing a
751
            // signature that contains RPITIT. When the method signatures don't match, we have to
752
            // emit an error now because `compare_method_predicate_entailment` will not report the error
753 754 755
            // when normalization fails.
            let emitted = report_trait_method_mismatch(
                infcx,
M
Michael Goulet 已提交
756
                cause,
757
                terr,
758 759
                (trait_m, trait_sig),
                (impl_m, impl_sig),
M
Michael Goulet 已提交
760
                impl_trait_ref,
761
            );
762
            return Err(emitted);
763 764 765
        }
    }

766 767 768 769
    // Check that all obligations are satisfied by the implementation's
    // RPITs.
    let errors = ocx.select_all_or_error();
    if !errors.is_empty() {
770
        let reported = infcx.err_ctxt().report_fulfillment_errors(&errors);
771 772
        return Err(reported);
    }
773

L
lcnr 已提交
774 775
    let collected_types = collector.types;

776 777
    // Finally, resolve all regions. This catches wily misuses of
    // lifetime parameters.
L
lcnr 已提交
778
    let outlives_env = OutlivesEnvironment::with_bounds(
779
        param_env,
780
        infcx.implied_bounds_tys(param_env, impl_m_def_id, wf_tys),
781
    );
L
lcnr 已提交
782
    ocx.resolve_regions_and_report_errors(impl_m_def_id, &outlives_env)?;
783

784
    let mut remapped_types = FxHashMap::default();
785 786 787
    for (def_id, (ty, args)) in collected_types {
        match infcx.fully_resolve((ty, args)) {
            Ok((ty, args)) => {
788
                // `ty` contains free regions that we created earlier while liberating the
789
                // trait fn signature. However, projection normalization expects `ty` to
790
                // contains `def_id`'s early-bound regions.
791 792 793
                let id_args = GenericArgs::identity_for_item(tcx, def_id);
                debug!(?id_args, ?args);
                let map: FxHashMap<_, _> = std::iter::zip(args, id_args)
794 795 796
                    .skip(tcx.generics_of(trait_m.def_id).count())
                    .filter_map(|(a, b)| Some((a.as_region()?, b.as_region()?)))
                    .collect();
797 798
                debug!(?map);

M
Michael Goulet 已提交
799
                // NOTE(compiler-errors): RPITITs, like all other RPITs, have early-bound
800 801
                // region args that are synthesized during AST lowering. These are args
                // that are appended to the parent args (trait and trait method). However,
M
Michael Goulet 已提交
802
                // we're trying to infer the unsubstituted type value of the RPITIT inside
803
                // the *impl*, so we can later use the impl's method args to normalize
M
typos  
Michael Goulet 已提交
804
                // an RPITIT to a concrete type (`confirm_impl_trait_in_trait_candidate`).
M
Michael Goulet 已提交
805 806
                //
                // Due to the design of RPITITs, during AST lowering, we have no idea that
M
typos  
Michael Goulet 已提交
807
                // an impl method corresponds to a trait method with RPITITs in it. Therefore,
808
                // we don't have a list of early-bound region args for the RPITIT in the impl.
M
Michael Goulet 已提交
809
                // Since early region parameters are index-based, we can't just rebase these
810 811 812 813
                // (trait method) early-bound region args onto the impl, and there's no
                // guarantee that the indices from the trait args and impl args line up.
                // So to fix this, we subtract the number of trait args and add the number of
                // impl args to *renumber* these early-bound regions to their corresponding
M
typos  
Michael Goulet 已提交
814
                // indices in the impl's substitutions list.
M
Michael Goulet 已提交
815
                //
816
                // Also, we only need to account for a difference in trait and impl args,
M
Michael Goulet 已提交
817 818
                // since we previously enforce that the trait method and impl method have the
                // same generics.
819 820
                let num_trait_args = trait_to_impl_args.len();
                let num_impl_args = tcx.generics_of(impl_m.container_id(tcx)).params.len();
821 822 823
                let ty = match ty.try_fold_with(&mut RemapHiddenTyRegions {
                    tcx,
                    map,
824 825
                    num_trait_args,
                    num_impl_args,
826 827 828 829 830 831
                    def_id,
                    impl_def_id: impl_m.container_id(tcx),
                    ty,
                    return_span,
                }) {
                    Ok(ty) => ty,
832
                    Err(guar) => Ty::new_error(tcx, guar),
833
                };
834
                remapped_types.insert(def_id, ty::EarlyBinder::bind(ty));
835 836
            }
            Err(err) => {
837
                let reported = tcx.sess.delay_span_bug(
838 839 840
                    return_span,
                    format!("could not fully resolve: {ty} => {err:?}"),
                );
841
                remapped_types.insert(def_id, ty::EarlyBinder::bind(Ty::new_error(tcx, reported)));
842 843
            }
        }
844
    }
845

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    // We may not collect all RPITITs that we see in the HIR for a trait signature
    // because an RPITIT was located within a missing item. Like if we have a sig
    // returning `-> Missing<impl Sized>`, that gets converted to `-> [type error]`,
    // and when walking through the signature we end up never collecting the def id
    // of the `impl Sized`. Insert that here, so we don't ICE later.
    for assoc_item in tcx.associated_types_for_impl_traits_in_associated_fn(trait_m.def_id) {
        if !remapped_types.contains_key(assoc_item) {
            remapped_types.insert(
                *assoc_item,
                ty::EarlyBinder::bind(Ty::new_error_with_message(
                    tcx,
                    return_span,
                    "missing synthetic item for RPITIT",
                )),
            );
        }
    }

    Ok(&*tcx.arena.alloc(remapped_types))
N
Niko Matsakis 已提交
865 866
}

867 868
struct ImplTraitInTraitCollector<'a, 'tcx> {
    ocx: &'a ObligationCtxt<'a, 'tcx>,
869
    types: FxHashMap<DefId, (Ty<'tcx>, ty::GenericArgsRef<'tcx>)>,
870 871
    span: Span,
    param_env: ty::ParamEnv<'tcx>,
872
    body_id: LocalDefId,
873 874 875 876 877 878 879
}

impl<'a, 'tcx> ImplTraitInTraitCollector<'a, 'tcx> {
    fn new(
        ocx: &'a ObligationCtxt<'a, 'tcx>,
        span: Span,
        param_env: ty::ParamEnv<'tcx>,
880
        body_id: LocalDefId,
881 882 883 884 885
    ) -> Self {
        ImplTraitInTraitCollector { ocx, types: FxHashMap::default(), span, param_env, body_id }
    }
}

886
impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'_, 'tcx> {
887
    fn interner(&self) -> TyCtxt<'tcx> {
888 889 890 891
        self.ocx.infcx.tcx
    }

    fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
892
        if let ty::Alias(ty::Projection, proj) = ty.kind()
893
            && self.interner().is_impl_trait_in_trait(proj.def_id)
894
        {
895
            if let Some((ty, _)) = self.types.get(&proj.def_id) {
896 897
                return *ty;
            }
898 899
            //FIXME(RPITIT): Deny nested RPITIT in args too
            if proj.args.has_escaping_bound_vars() {
900 901 902 903 904 905 906
                bug!("FIXME(RPITIT): error here");
            }
            // Replace with infer var
            let infer_ty = self.ocx.infcx.next_ty_var(TypeVariableOrigin {
                span: self.span,
                kind: TypeVariableOriginKind::MiscVariable,
            });
907
            self.types.insert(proj.def_id, (infer_ty, proj.args));
908
            // Recurse into bounds
909
            for (pred, pred_span) in self.interner().explicit_item_bounds(proj.def_id).iter_instantiated_copied(self.interner(), proj.args) {
910 911
                let pred = pred.fold_with(self);
                let pred = self.ocx.normalize(
912
                    &ObligationCause::misc(self.span, self.body_id),
913 914 915 916 917
                    self.param_env,
                    pred,
                );

                self.ocx.register_obligation(traits::Obligation::new(
918
                    self.interner(),
919 920 921
                    ObligationCause::new(
                        self.span,
                        self.body_id,
922
                        ObligationCauseCode::BindingObligation(proj.def_id, pred_span),
923 924 925 926 927 928 929 930 931 932 933 934
                    ),
                    self.param_env,
                    pred,
                ));
            }
            infer_ty
        } else {
            ty.super_fold_with(self)
        }
    }
}

935 936 937
struct RemapHiddenTyRegions<'tcx> {
    tcx: TyCtxt<'tcx>,
    map: FxHashMap<ty::Region<'tcx>, ty::Region<'tcx>>,
938 939
    num_trait_args: usize,
    num_impl_args: usize,
940 941 942 943 944 945 946 947 948 949 950 951 952 953
    def_id: DefId,
    impl_def_id: DefId,
    ty: Ty<'tcx>,
    return_span: Span,
}

impl<'tcx> ty::FallibleTypeFolder<TyCtxt<'tcx>> for RemapHiddenTyRegions<'tcx> {
    type Error = ErrorGuaranteed;

    fn interner(&self) -> TyCtxt<'tcx> {
        self.tcx
    }

    fn try_fold_ty(&mut self, t: Ty<'tcx>) -> Result<Ty<'tcx>, Self::Error> {
954 955 956 957 958
        if let ty::Alias(ty::Opaque, ty::AliasTy { args, def_id, .. }) = *t.kind() {
            let mut mapped_args = Vec::with_capacity(args.len());
            for (arg, v) in std::iter::zip(args, self.tcx.variances_of(def_id)) {
                mapped_args.push(match (arg.unpack(), v) {
                    // Skip uncaptured opaque args
959 960 961 962
                    (ty::GenericArgKind::Lifetime(_), ty::Bivariant) => arg,
                    _ => arg.try_fold_with(self)?,
                });
            }
963
            Ok(Ty::new_opaque(self.tcx, def_id, self.tcx.mk_args(&mapped_args)))
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
        } else {
            t.try_super_fold_with(self)
        }
    }

    fn try_fold_region(
        &mut self,
        region: ty::Region<'tcx>,
    ) -> Result<ty::Region<'tcx>, Self::Error> {
        match region.kind() {
            // Remap all free regions, which correspond to late-bound regions in the function.
            ty::ReFree(_) => {}
            // Remap early-bound regions as long as they don't come from the `impl` itself,
            // in which case we don't really need to renumber them.
            ty::ReEarlyBound(ebr) if self.tcx.parent(ebr.def_id) != self.impl_def_id => {}
            _ => return Ok(region),
        }

        let e = if let Some(region) = self.map.get(&region) {
            if let ty::ReEarlyBound(e) = region.kind() { e } else { bug!() }
        } else {
            let guar = match region.kind() {
                ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. })
                | ty::ReFree(ty::FreeRegion {
                    bound_region: ty::BoundRegionKind::BrNamed(def_id, _),
                    ..
                }) => {
                    let return_span = if let ty::Alias(ty::Opaque, opaque_ty) = self.ty.kind() {
                        self.tcx.def_span(opaque_ty.def_id)
                    } else {
                        self.return_span
                    };
                    self.tcx
                        .sess
                        .struct_span_err(
                            return_span,
                            "return type captures more lifetimes than trait definition",
                        )
                        .span_label(self.tcx.def_span(def_id), "this lifetime was captured")
                        .span_note(
                            self.tcx.def_span(self.def_id),
                            "hidden type must only reference lifetimes captured by this impl trait",
                        )
                        .note(format!("hidden type inferred to be `{}`", self.ty))
                        .emit()
                }
                _ => self.tcx.sess.delay_span_bug(DUMMY_SP, "should've been able to remap region"),
            };
            return Err(guar);
        };

        Ok(ty::Region::new_early_bound(
            self.tcx,
            ty::EarlyBoundRegion {
                def_id: e.def_id,
                name: e.name,
1020
                index: (e.index as usize - self.num_trait_args + self.num_impl_args) as u32,
1021 1022 1023 1024 1025
            },
        ))
    }
}

1026 1027
fn report_trait_method_mismatch<'tcx>(
    infcx: &InferCtxt<'tcx>,
M
Michael Goulet 已提交
1028
    mut cause: ObligationCause<'tcx>,
1029
    terr: TypeError<'tcx>,
1030 1031
    (trait_m, trait_sig): (ty::AssocItem, ty::FnSig<'tcx>),
    (impl_m, impl_sig): (ty::AssocItem, ty::FnSig<'tcx>),
M
Michael Goulet 已提交
1032
    impl_trait_ref: ty::TraitRef<'tcx>,
1033
) -> ErrorGuaranteed {
M
Michael Goulet 已提交
1034
    let tcx = infcx.tcx;
1035 1036 1037 1038 1039
    let (impl_err_span, trait_err_span) =
        extract_spans_for_error_reporting(&infcx, terr, &cause, impl_m, trait_m);

    let mut diag = struct_span_err!(
        tcx.sess,
M
Michael Goulet 已提交
1040
        impl_err_span,
1041 1042 1043 1044 1045 1046 1047 1048 1049
        E0053,
        "method `{}` has an incompatible type for trait",
        trait_m.name
    );
    match &terr {
        TypeError::ArgumentMutability(0) | TypeError::ArgumentSorts(_, 0)
            if trait_m.fn_has_self_parameter =>
        {
            let ty = trait_sig.inputs()[0];
1050
            let sugg = match ExplicitSelf::determine(ty, |ty| ty == impl_trait_ref.self_ty()) {
1051 1052 1053 1054 1055 1056 1057 1058 1059
                ExplicitSelf::ByValue => "self".to_owned(),
                ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
                ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
                _ => format!("self: {ty}"),
            };

            // When the `impl` receiver is an arbitrary self type, like `self: Box<Self>`, the
            // span points only at the type `Box<Self`>, but we want to cover the whole
            // argument pattern and type.
1060
            let (sig, body) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1061 1062 1063 1064 1065 1066 1067
            let span = tcx
                .hir()
                .body_param_names(body)
                .zip(sig.decl.inputs.iter())
                .map(|(param, ty)| param.span.to(ty.span))
                .next()
                .unwrap_or(impl_err_span);
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079

            diag.span_suggestion(
                span,
                "change the self-receiver type to match the trait",
                sugg,
                Applicability::MachineApplicable,
            );
        }
        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(_, i) => {
            if trait_sig.inputs().len() == *i {
                // Suggestion to change output type. We do not suggest in `async` functions
                // to avoid complex logic or incorrect output.
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094
                if let ImplItemKind::Fn(sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).kind
                    && !sig.header.asyncness.is_async()
                {
                    let msg = "change the output type to match the trait";
                    let ap = Applicability::MachineApplicable;
                    match sig.decl.output {
                        hir::FnRetTy::DefaultReturn(sp) => {
                            let sugg = format!("-> {} ", trait_sig.output());
                            diag.span_suggestion_verbose(sp, msg, sugg, ap);
                        }
                        hir::FnRetTy::Return(hir_ty) => {
                            let sugg = trait_sig.output();
                            diag.span_suggestion(hir_ty.span, msg, sugg, ap);
                        }
                    };
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
                };
            } else if let Some(trait_ty) = trait_sig.inputs().get(*i) {
                diag.span_suggestion(
                    impl_err_span,
                    "change the parameter type to match the trait",
                    trait_ty,
                    Applicability::MachineApplicable,
                );
            }
        }
        _ => {}
    }

M
Michael Goulet 已提交
1108
    cause.span = impl_err_span;
1109 1110 1111
    infcx.err_ctxt().note_type_err(
        &mut diag,
        &cause,
1112
        trait_err_span.map(|sp| (sp, Cow::from("type in trait"))),
1113
        Some(infer::ValuePairs::Sigs(ExpectedFound { expected: trait_sig, found: impl_sig })),
1114 1115 1116 1117 1118 1119 1120 1121
        terr,
        false,
        false,
    );

    return diag.emit();
}

1122
fn check_region_bounds_on_impl_item<'tcx>(
1123
    tcx: TyCtxt<'tcx>,
1124 1125
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
1126
    delay: bool,
M
mark 已提交
1127
) -> Result<(), ErrorGuaranteed> {
1128
    let impl_generics = tcx.generics_of(impl_m.def_id);
V
varkor 已提交
1129
    let impl_params = impl_generics.own_counts().lifetimes;
N
Niko Matsakis 已提交
1130

1131 1132 1133
    let trait_generics = tcx.generics_of(trait_m.def_id);
    let trait_params = trait_generics.own_counts().lifetimes;

M
Mark Rousskov 已提交
1134 1135
    debug!(
        "check_region_bounds_on_impl_item: \
N
Niko Matsakis 已提交
1136
            trait_generics={:?} \
1137
            impl_generics={:?}",
M
Mark Rousskov 已提交
1138 1139
        trait_generics, impl_generics
    );
N
Niko Matsakis 已提交
1140 1141 1142

    // Must have same number of early-bound lifetime parameters.
    // Unfortunately, if the user screws up the bounds, then this
1143
    // will change classification between early and late. E.g.,
N
Niko Matsakis 已提交
1144 1145 1146 1147 1148 1149
    // if in trait we have `<'a,'b:'a>`, and in impl we just have
    // `<'a,'b>`, then we have 2 early-bound lifetime parameters
    // in trait but 0 in the impl. But if we report "expected 2
    // but found 0" it's confusing, because it looks like there
    // are zero. Since I don't quite know how to phrase things at
    // the moment, give a kind of vague error message.
1150
    if trait_params != impl_params {
1151 1152 1153 1154 1155
        let span = tcx
            .hir()
            .get_generics(impl_m.def_id.expect_local())
            .expect("expected impl item to have generics or else we can't compare them")
            .span;
1156

1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
        let mut generics_span = None;
        let mut bounds_span = vec![];
        let mut where_span = None;
        if let Some(trait_node) = tcx.hir().get_if_local(trait_m.def_id)
            && let Some(trait_generics) = trait_node.generics()
        {
            generics_span = Some(trait_generics.span);
            // FIXME: we could potentially look at the impl's bounds to not point at bounds that
            // *are* present in the impl.
            for p in trait_generics.predicates {
                if let hir::WherePredicate::BoundPredicate(pred) = p {
                    for b in pred.bounds {
                        if let hir::GenericBound::Outlives(lt) = b {
                            bounds_span.push(lt.ident.span);
                        }
                    }
                }
            }
            if let Some(impl_node) = tcx.hir().get_if_local(impl_m.def_id)
                && let Some(impl_generics) = impl_node.generics()
            {
                let mut impl_bounds = 0;
                for p in impl_generics.predicates {
                    if let hir::WherePredicate::BoundPredicate(pred) = p {
                        for b in pred.bounds {
                            if let hir::GenericBound::Outlives(_) = b {
                                impl_bounds += 1;
                            }
                        }
                    }
                }
                if impl_bounds == bounds_span.len() {
                    bounds_span = vec![];
                } else if impl_generics.has_where_clause_predicates {
                    where_span = Some(impl_generics.where_clause_span);
                }
            }
        }
1195 1196 1197 1198
        let reported = tcx
            .sess
            .create_err(LifetimesOrBoundsMismatchOnTrait {
                span,
1199
                item_kind: assoc_item_kind_str(&impl_m),
1200 1201
                ident: impl_m.ident(tcx),
                generics_span,
1202 1203
                bounds_span,
                where_span,
1204 1205
            })
            .emit_unless(delay);
1206
        return Err(reported);
N
Niko Matsakis 已提交
1207 1208
    }

1209
    Ok(())
N
Niko Matsakis 已提交
1210 1211
}

E
Ellen 已提交
1212
#[instrument(level = "debug", skip(infcx))]
1213 1214
fn extract_spans_for_error_reporting<'tcx>(
    infcx: &infer::InferCtxt<'tcx>,
M
Michael Goulet 已提交
1215
    terr: TypeError<'_>,
1216
    cause: &ObligationCause<'tcx>,
1217 1218
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
1219
) -> (Span, Option<Span>) {
N
Niko Matsakis 已提交
1220
    let tcx = infcx.tcx;
1221
    let mut impl_args = {
1222
        let (sig, _) = tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
1223
        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
N
Niko Matsakis 已提交
1224
    };
1225 1226

    let trait_args = trait_m.def_id.as_local().map(|def_id| {
1227
        let (sig, _) = tcx.hir().expect_trait_item(def_id).expect_fn();
1228 1229
        sig.decl.inputs.iter().map(|t| t.span).chain(iter::once(sig.decl.output.span()))
    });
N
Niko Matsakis 已提交
1230

M
Michael Goulet 已提交
1231
    match terr {
1232
        TypeError::ArgumentMutability(i) | TypeError::ArgumentSorts(ExpectedFound { .. }, i) => {
1233
            (impl_args.nth(i).unwrap(), trait_args.and_then(|mut args| args.nth(i)))
N
Niko Matsakis 已提交
1234
        }
1235
        _ => (cause.span(), tcx.hir().span_if_local(trait_m.def_id)),
1236
    }
N
Niko Matsakis 已提交
1237
}
1238

1239
fn compare_self_type<'tcx>(
1240
    tcx: TyCtxt<'tcx>,
1241 1242
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
1243
    impl_trait_ref: ty::TraitRef<'tcx>,
1244
    delay: bool,
M
mark 已提交
1245
) -> Result<(), ErrorGuaranteed> {
N
Niko Matsakis 已提交
1246
    // Try to give more informative error messages about self typing
1247
    // mismatches. Note that any mismatch will also be detected
N
Niko Matsakis 已提交
1248
    // below, where we construct a canonical function type that
1249
    // includes the self parameter as a normal parameter. It's just
N
Niko Matsakis 已提交
1250 1251 1252
    // that the error messages you get out of this code are a bit more
    // inscrutable, particularly for cases where one method has no
    // self.
1253

1254
    let self_string = |method: ty::AssocItem| {
1255
        let untransformed_self_ty = match method.container {
1256 1257
            ty::ImplContainer => impl_trait_ref.self_ty(),
            ty::TraitContainer => tcx.types.self_param,
1258
        };
1259
        let self_arg_ty = tcx.fn_sig(method.def_id).instantiate_identity().input(0);
1260
        let param_env = ty::ParamEnv::reveal_all();
1261

1262 1263
        let infcx = tcx.infer_ctxt().build();
        let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
1264
        let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty);
1265 1266 1267 1268 1269 1270
        match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
            ExplicitSelf::ByValue => "self".to_owned(),
            ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
            ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
            _ => format!("self: {self_arg_ty}"),
        }
1271 1272
    };

1273
    match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
1274 1275 1276 1277
        (false, false) | (true, true) => {}

        (false, true) => {
            let self_descr = self_string(impl_m);
1278
            let impl_m_span = tcx.def_span(impl_m.def_id);
M
Mark Rousskov 已提交
1279 1280 1281 1282
            let mut err = struct_span_err!(
                tcx.sess,
                impl_m_span,
                E0185,
1283
                "method `{}` has a `{}` declaration in the impl, but not in the trait",
1284
                trait_m.name,
M
Mark Rousskov 已提交
1285 1286
                self_descr
            );
1287
            err.span_label(impl_m_span, format!("`{self_descr}` used in impl"));
1288
            if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1289
                err.span_label(span, format!("trait method declared without `{self_descr}`"));
E
Esteban Küber 已提交
1290
            } else {
1291
                err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
N
Niko Matsakis 已提交
1292
            }
1293
            return Err(err.emit_unless(delay));
N
Niko Matsakis 已提交
1294
        }
1295 1296 1297

        (true, false) => {
            let self_descr = self_string(trait_m);
1298
            let impl_m_span = tcx.def_span(impl_m.def_id);
M
Mark Rousskov 已提交
1299 1300 1301 1302
            let mut err = struct_span_err!(
                tcx.sess,
                impl_m_span,
                E0186,
1303
                "method `{}` has a `{}` declaration in the trait, but not in the impl",
1304
                trait_m.name,
M
Mark Rousskov 已提交
1305 1306
                self_descr
            );
1307
            err.span_label(impl_m_span, format!("expected `{self_descr}` in impl"));
1308
            if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
1309
                err.span_label(span, format!("`{self_descr}` used in trait"));
1310
            } else {
1311
                err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
N
Niko Matsakis 已提交
1312
            }
1313

1314
            return Err(err.emit_unless(delay));
N
Niko Matsakis 已提交
1315 1316 1317 1318 1319 1320
        }
    }

    Ok(())
}

1321 1322 1323 1324
/// Checks that the number of generics on a given assoc item in a trait impl is the same
/// as the number of generics on the respective assoc item in the trait definition.
///
/// For example this code emits the errors in the following code:
1325
/// ```rust,compile_fail
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
/// trait Trait {
///     fn foo();
///     type Assoc<T>;
/// }
///
/// impl Trait for () {
///     fn foo<T>() {}
///     //~^ error
///     type Assoc = u32;
///     //~^ error
/// }
/// ```
///
/// Notably this does not error on `foo<T>` implemented as `foo<const N: u8>` or
/// `foo<const N: u8>` implemented as `foo<const N: u32>`. This is handled in
/// [`compare_generic_param_kinds`]. This function also does not handle lifetime parameters
1342
fn compare_number_of_generics<'tcx>(
1343
    tcx: TyCtxt<'tcx>,
1344 1345
    impl_: ty::AssocItem,
    trait_: ty::AssocItem,
1346
    delay: bool,
M
mark 已提交
1347
) -> Result<(), ErrorGuaranteed> {
V
varkor 已提交
1348 1349 1350
    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();

1351 1352 1353 1354 1355 1356 1357 1358 1359
    // This avoids us erroring on `foo<T>` implemented as `foo<const N: u8>` as this is implemented
    // in `compare_generic_param_kinds` which will give a nicer error message than something like:
    // "expected 1 type parameter, found 0 type parameters"
    if (trait_own_counts.types + trait_own_counts.consts)
        == (impl_own_counts.types + impl_own_counts.consts)
    {
        return Ok(());
    }

1360 1361 1362 1363
    // We never need to emit a separate error for RPITITs, since if an RPITIT
    // has mismatched type or const generic arguments, then the method that it's
    // inheriting the generics from will also have mismatched arguments, and
    // we'll report an error for that instead. Delay a bug for safety, though.
1364
    if trait_.is_impl_trait_in_trait() {
1365 1366 1367 1368 1369 1370
        return Err(tcx.sess.delay_span_bug(
            rustc_span::DUMMY_SP,
            "errors comparing numbers of generics of trait/impl functions were not emitted",
        ));
    }

V
varkor 已提交
1371 1372 1373 1374 1375
    let matchings = [
        ("type", trait_own_counts.types, impl_own_counts.types),
        ("const", trait_own_counts.consts, impl_own_counts.consts),
    ];

1376
    let item_kind = assoc_item_kind_str(&impl_);
1377

1378
    let mut err_occurred = None;
1379
    for (kind, trait_count, impl_count) in matchings {
V
varkor 已提交
1380
        if impl_count != trait_count {
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
            let arg_spans = |kind: ty::AssocKind, generics: &hir::Generics<'_>| {
                let mut spans = generics
                    .params
                    .iter()
                    .filter(|p| match p.kind {
                        hir::GenericParamKind::Lifetime {
                            kind: hir::LifetimeParamKind::Elided,
                        } => {
                            // A fn can have an arbitrary number of extra elided lifetimes for the
                            // same signature.
                            !matches!(kind, ty::AssocKind::Fn)
                        }
                        _ => true,
                    })
                    .map(|p| p.span)
                    .collect::<Vec<Span>>();
                if spans.is_empty() {
                    spans = vec![generics.span]
                }
                spans
            };
M
marmeladema 已提交
1402
            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
1403
                let trait_item = tcx.hir().expect_trait_item(def_id);
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
                let arg_spans: Vec<Span> = arg_spans(trait_.kind, trait_item.generics);
                let impl_trait_spans: Vec<Span> = trait_item
                    .generics
                    .params
                    .iter()
                    .filter_map(|p| match p.kind {
                        GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
                        _ => None,
                    })
                    .collect();
                (Some(arg_spans), impl_trait_spans)
1415
            } else {
1416
                let trait_span = tcx.hir().span_if_local(trait_.def_id);
1417 1418
                (trait_span.map(|s| vec![s]), vec![])
            };
1419

1420
            let impl_item = tcx.hir().expect_impl_item(impl_.def_id.expect_local());
M
Mark Rousskov 已提交
1421 1422 1423 1424
            let impl_item_impl_trait_spans: Vec<Span> = impl_item
                .generics
                .params
                .iter()
1425
                .filter_map(|p| match p.kind {
1426
                    GenericParamKind::Type { synthetic: true, .. } => Some(p.span),
1427
                    _ => None,
M
Mark Rousskov 已提交
1428 1429
                })
                .collect();
1430
            let spans = arg_spans(impl_.kind, impl_item.generics);
1431
            let span = spans.first().copied();
1432

V
varkor 已提交
1433
            let mut err = tcx.sess.struct_span_err_with_code(
1434
                spans,
1435
                format!(
1436
                    "{} `{}` has {} {kind} parameter{} but its trait \
V
varkor 已提交
1437
                     declaration has {} {kind} parameter{}",
1438
                    item_kind,
1439
                    trait_.name,
V
varkor 已提交
1440
                    impl_count,
1441
                    pluralize!(impl_count),
V
varkor 已提交
1442
                    trait_count,
1443
                    pluralize!(trait_count),
V
varkor 已提交
1444 1445 1446 1447
                    kind = kind,
                ),
                DiagnosticId::Error("E0049".into()),
            );
1448

V
varkor 已提交
1449
            let mut suffix = None;
N
Niko Matsakis 已提交
1450

1451 1452 1453
            if let Some(spans) = trait_spans {
                let mut spans = spans.iter();
                if let Some(span) = spans.next() {
M
Mark Rousskov 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462
                    err.span_label(
                        *span,
                        format!(
                            "expected {} {} parameter{}",
                            trait_count,
                            kind,
                            pluralize!(trait_count),
                        ),
                    );
1463 1464 1465 1466
                }
                for span in spans {
                    err.span_label(*span, "");
                }
V
varkor 已提交
1467
            } else {
1468
                suffix = Some(format!(", expected {trait_count}"));
V
varkor 已提交
1469
            }
N
Niko Matsakis 已提交
1470

1471
            if let Some(span) = span {
M
Mark Rousskov 已提交
1472 1473 1474 1475 1476 1477 1478
                err.span_label(
                    span,
                    format!(
                        "found {} {} parameter{}{}",
                        impl_count,
                        kind,
                        pluralize!(impl_count),
1479
                        suffix.unwrap_or_default(),
M
Mark Rousskov 已提交
1480 1481
                    ),
                );
1482
            }
N
Niko Matsakis 已提交
1483

1484 1485 1486 1487
            for span in impl_trait_spans.iter().chain(impl_item_impl_trait_spans.iter()) {
                err.span_label(*span, "`impl Trait` introduces an implicit type parameter");
            }

1488
            let reported = err.emit_unless(delay);
1489
            err_occurred = Some(reported);
V
varkor 已提交
1490
        }
N
Niko Matsakis 已提交
1491 1492
    }

1493
    if let Some(reported) = err_occurred { Err(reported) } else { Ok(()) }
N
Niko Matsakis 已提交
1494 1495
}

1496
fn compare_number_of_method_arguments<'tcx>(
1497
    tcx: TyCtxt<'tcx>,
1498 1499
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
1500
    delay: bool,
M
mark 已提交
1501
) -> Result<(), ErrorGuaranteed> {
1502 1503
    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
1504 1505
    let trait_number_args = trait_m_fty.skip_binder().inputs().skip_binder().len();
    let impl_number_args = impl_m_fty.skip_binder().inputs().skip_binder().len();
1506

1507
    if trait_number_args != impl_number_args {
1508 1509 1510 1511
        let trait_span = trait_m
            .def_id
            .as_local()
            .and_then(|def_id| {
1512
                let (trait_m_sig, _) = &tcx.hir().expect_trait_item(def_id).expect_fn();
1513 1514
                let pos = trait_number_args.saturating_sub(1);
                trait_m_sig.decl.inputs.get(pos).map(|arg| {
1515 1516 1517
                    if pos == 0 {
                        arg.span
                    } else {
1518
                        arg.span.with_lo(trait_m_sig.decl.inputs[0].span.lo())
1519
                    }
1520 1521
                })
            })
1522
            .or_else(|| tcx.hir().span_if_local(trait_m.def_id));
1523

1524
        let (impl_m_sig, _) = &tcx.hir().expect_impl_item(impl_m.def_id.expect_local()).expect_fn();
M
Maybe Waffle 已提交
1525 1526 1527 1528 1529 1530 1531 1532
        let pos = impl_number_args.saturating_sub(1);
        let impl_span = impl_m_sig
            .decl
            .inputs
            .get(pos)
            .map(|arg| {
                if pos == 0 {
                    arg.span
N
Niko Matsakis 已提交
1533
                } else {
M
Maybe Waffle 已提交
1534
                    arg.span.with_lo(impl_m_sig.decl.inputs[0].span.lo())
1535
                }
M
Maybe Waffle 已提交
1536
            })
1537
            .unwrap_or_else(|| tcx.def_span(impl_m.def_id));
1538

M
Mark Rousskov 已提交
1539 1540 1541 1542
        let mut err = struct_span_err!(
            tcx.sess,
            impl_span,
            E0050,
E
Esteban Kuber 已提交
1543
            "method `{}` has {} but the declaration in trait `{}` has {}",
1544
            trait_m.name,
M
Mark Rousskov 已提交
1545 1546 1547 1548
            potentially_plural_count(impl_number_args, "parameter"),
            tcx.def_path_str(trait_m.def_id),
            trait_number_args
        );
1549

N
Niko Matsakis 已提交
1550
        if let Some(trait_span) = trait_span {
M
Mark Rousskov 已提交
1551 1552 1553 1554 1555 1556 1557
            err.span_label(
                trait_span,
                format!(
                    "trait requires {}",
                    potentially_plural_count(trait_number_args, "parameter")
                ),
            );
1558
        } else {
1559
            err.note_trait_signature(trait_m.name, trait_m.signature(tcx));
1560
        }
1561

M
Mark Rousskov 已提交
1562 1563 1564 1565 1566 1567 1568 1569
        err.span_label(
            impl_span,
            format!(
                "expected {}, found {}",
                potentially_plural_count(trait_number_args, "parameter"),
                impl_number_args
            ),
        );
1570

1571
        return Err(err.emit_unless(delay));
1572
    }
N
Niko Matsakis 已提交
1573 1574

    Ok(())
1575
}
1576

1577
fn compare_synthetic_generics<'tcx>(
1578
    tcx: TyCtxt<'tcx>,
1579 1580
    impl_m: ty::AssocItem,
    trait_m: ty::AssocItem,
1581
    delay: bool,
M
mark 已提交
1582
) -> Result<(), ErrorGuaranteed> {
1583
    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
1584
    //     1. Better messages for the span labels
1585 1586 1587
    //     2. Explanation as to what is going on
    // If we get here, we already have the same number of generics, so the zip will
    // be okay.
1588
    let mut error_found = None;
1589 1590
    let impl_m_generics = tcx.generics_of(impl_m.def_id);
    let trait_m_generics = tcx.generics_of(trait_m.def_id);
1591 1592
    let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
        GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1593
        GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
V
varkor 已提交
1594
    });
M
Mark Rousskov 已提交
1595 1596
    let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
        GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
1597
        GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
V
varkor 已提交
1598
    });
M
Mark Rousskov 已提交
1599
    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
J
Josh Stone 已提交
1600
        iter::zip(impl_m_type_params, trait_m_type_params)
1601
    {
V
varkor 已提交
1602
        if impl_synthetic != trait_synthetic {
1603
            let impl_def_id = impl_def_id.expect_local();
1604
            let impl_span = tcx.def_span(impl_def_id);
V
varkor 已提交
1605
            let trait_span = tcx.def_span(trait_def_id);
M
Mark Rousskov 已提交
1606 1607 1608 1609 1610
            let mut err = struct_span_err!(
                tcx.sess,
                impl_span,
                E0643,
                "method `{}` has incompatible signature for trait",
1611
                trait_m.name
M
Mark Rousskov 已提交
1612
            );
1613 1614 1615 1616
            err.span_label(trait_span, "declaration in trait here");
            match (impl_synthetic, trait_synthetic) {
                // The case where the impl method uses `impl Trait` but the trait method uses
                // explicit generics
1617
                (true, false) => {
1618
                    err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
1619
                    let _: Option<_> = try {
1620 1621 1622
                        // try taking the name from the trait impl
                        // FIXME: this is obviously suboptimal since the name can already be used
                        // as another generic argument
1623
                        let new_name = tcx.opt_item_name(trait_def_id)?;
1624
                        let trait_m = trait_m.def_id.as_local()?;
1625
                        let trait_m = tcx.hir().expect_trait_item(trait_m);
1626

1627
                        let impl_m = impl_m.def_id.as_local()?;
1628
                        let impl_m = tcx.hir().expect_impl_item(impl_m);
1629 1630 1631

                        // in case there are no generics, take the spot between the function name
                        // and the opening paren of the argument list
1632
                        let new_generics_span = tcx.def_ident_span(impl_def_id)?.shrink_to_hi();
1633
                        // in case there are generics, just replace them
M
Mark Rousskov 已提交
1634 1635
                        let generics_span =
                            impl_m.generics.span.substitute_dummy(new_generics_span);
1636
                        // replace with the generics from the trait
M
Mark Rousskov 已提交
1637 1638
                        let new_generics =
                            tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
1639

1640
                        err.multipart_suggestion(
1641 1642 1643
                            "try changing the `impl Trait` argument to a generic parameter",
                            vec![
                                // replace `impl Trait` with `T`
1644
                                (impl_span, new_name.to_string()),
1645 1646 1647 1648 1649
                                // replace impl method generics with trait method generics
                                // This isn't quite right, as users might have changed the names
                                // of the generics, but it works for the common case
                                (generics_span, new_generics),
                            ],
1650
                            Applicability::MaybeIncorrect,
1651
                        );
1652
                    };
M
Mark Rousskov 已提交
1653
                }
1654 1655
                // The case where the trait method uses `impl Trait`, but the impl method uses
                // explicit generics.
1656
                (false, true) => {
1657
                    err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
1658
                    let _: Option<_> = try {
1659
                        let impl_m = impl_m.def_id.as_local()?;
1660
                        let impl_m = tcx.hir().expect_impl_item(impl_m);
1661
                        let (sig, _) = impl_m.expect_fn();
1662 1663
                        let input_tys = sig.decl.inputs;

1664
                        struct Visitor(Option<Span>, hir::def_id::LocalDefId);
1665
                        impl<'v> intravisit::Visitor<'v> for Visitor {
C
Camille GILLOT 已提交
1666
                            fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
1667
                                intravisit::walk_ty(self, ty);
1668
                                if let hir::TyKind::Path(hir::QPath::Resolved(None, path)) = ty.kind
1669
                                    && let Res::Def(DefKind::TyParam, def_id) = path.res
1670
                                    && def_id == self.1.to_def_id()
1671
                                {
1672
                                    self.0 = Some(ty.span);
1673 1674 1675
                                }
                            }
                        }
1676

1677 1678
                        let mut visitor = Visitor(None, impl_def_id);
                        for ty in input_tys {
1679
                            intravisit::Visitor::visit_ty(&mut visitor, ty);
1680 1681 1682
                        }
                        let span = visitor.0?;

1683
                        let bounds = impl_m.generics.bounds_for_param(impl_def_id).next()?.bounds;
V
varkor 已提交
1684
                        let bounds = bounds.first()?.span().to(bounds.last()?.span());
M
Mark Rousskov 已提交
1685
                        let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
1686

1687
                        err.multipart_suggestion(
1688 1689 1690 1691 1692
                            "try removing the generic parameter and using `impl Trait` instead",
                            vec![
                                // delete generic parameters
                                (impl_m.generics.span, String::new()),
                                // replace param usage with `impl Trait`
1693
                                (span, format!("impl {bounds}")),
1694
                            ],
1695
                            Applicability::MaybeIncorrect,
1696
                        );
1697
                    };
M
Mark Rousskov 已提交
1698
                }
1699 1700
                _ => unreachable!(),
            }
1701
            error_found = Some(err.emit_unless(delay));
1702 1703
        }
    }
1704
    if let Some(reported) = error_found { Err(reported) } else { Ok(()) }
1705 1706
}

1707 1708 1709 1710
/// Checks that all parameters in the generics of a given assoc item in a trait impl have
/// the same kind as the respective generic parameter in the trait def.
///
/// For example all 4 errors in the following code are emitted here:
1711
/// ```rust,ignore (pseudo-Rust)
1712 1713
/// trait Foo {
///     fn foo<const N: u8>();
1714
///     type Bar<const N: u8>;
1715
///     fn baz<const N: u32>();
1716
///     type Blah<T>;
1717 1718 1719 1720 1721
/// }
///
/// impl Foo for () {
///     fn foo<const N: u64>() {}
///     //~^ error
1722
///     type Bar<const N: u64> = ();
1723 1724 1725
///     //~^ error
///     fn baz<T>() {}
///     //~^ error
1726
///     type Blah<const N: i64> = u32;
1727 1728 1729 1730 1731 1732
///     //~^ error
/// }
/// ```
///
/// This function does not handle lifetime parameters
fn compare_generic_param_kinds<'tcx>(
1733
    tcx: TyCtxt<'tcx>,
1734 1735
    impl_item: ty::AssocItem,
    trait_item: ty::AssocItem,
1736
    delay: bool,
M
mark 已提交
1737
) -> Result<(), ErrorGuaranteed> {
1738 1739 1740 1741 1742 1743 1744 1745
    assert_eq!(impl_item.kind, trait_item.kind);

    let ty_const_params_of = |def_id| {
        tcx.generics_of(def_id).params.iter().filter(|param| {
            matches!(
                param.kind,
                GenericParamDefKind::Const { .. } | GenericParamDefKind::Type { .. }
            )
1746 1747
        })
    };
1748

1749 1750 1751 1752 1753 1754
    for (param_impl, param_trait) in
        iter::zip(ty_const_params_of(impl_item.def_id), ty_const_params_of(trait_item.def_id))
    {
        use GenericParamDefKind::*;
        if match (&param_impl.kind, &param_trait.kind) {
            (Const { .. }, Const { .. })
1755
                if tcx.type_of(param_impl.def_id) != tcx.type_of(param_trait.def_id) =>
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
            {
                true
            }
            (Const { .. }, Type { .. }) | (Type { .. }, Const { .. }) => true,
            // this is exhaustive so that anyone adding new generic param kinds knows
            // to make sure this error is reported for them.
            (Const { .. }, Const { .. }) | (Type { .. }, Type { .. }) => false,
            (Lifetime { .. }, _) | (_, Lifetime { .. }) => unreachable!(),
        } {
            let param_impl_span = tcx.def_span(param_impl.def_id);
            let param_trait_span = tcx.def_span(param_trait.def_id);
1767

1768 1769 1770 1771
            let mut err = struct_span_err!(
                tcx.sess,
                param_impl_span,
                E0053,
E
Ellen 已提交
1772
                "{} `{}` has an incompatible generic parameter for trait `{}`",
1773 1774 1775 1776
                assoc_item_kind_str(&impl_item),
                trait_item.name,
                &tcx.def_path_str(tcx.parent(trait_item.def_id))
            );
1777

E
Ellen 已提交
1778 1779
            let make_param_message = |prefix: &str, param: &ty::GenericParamDef| match param.kind {
                Const { .. } => {
1780 1781 1782
                    format!(
                        "{} const parameter of type `{}`",
                        prefix,
1783
                        tcx.type_of(param.def_id).instantiate_identity()
1784
                    )
E
Ellen 已提交
1785
                }
1786
                Type { .. } => format!("{prefix} type parameter"),
E
Ellen 已提交
1787 1788 1789
                Lifetime { .. } => unreachable!(),
            };

1790 1791 1792 1793
            let trait_header_span = tcx.def_ident_span(tcx.parent(trait_item.def_id)).unwrap();
            err.span_label(trait_header_span, "");
            err.span_label(param_trait_span, make_param_message("expected", param_trait));

1794
            let impl_header_span = tcx.def_span(tcx.parent(impl_item.def_id));
1795 1796 1797
            err.span_label(impl_header_span, "");
            err.span_label(param_impl_span, make_param_message("found", param_impl));

1798
            let reported = err.emit_unless(delay);
1799
            return Err(reported);
1800 1801 1802 1803 1804 1805
        }
    }

    Ok(())
}

1806
/// Use `tcx.compare_impl_const` instead
M
Michael Goulet 已提交
1807
pub(super) fn compare_impl_const_raw(
J
Jeremy Stucki 已提交
1808
    tcx: TyCtxt<'_>,
B
Boxy 已提交
1809
    (impl_const_item_def, trait_const_item_def): (LocalDefId, DefId),
1810
) -> Result<(), ErrorGuaranteed> {
B
Boxy 已提交
1811 1812
    let impl_const_item = tcx.associated_item(impl_const_item_def);
    let trait_const_item = tcx.associated_item(trait_const_item_def);
1813
    let impl_trait_ref =
1814
        tcx.impl_trait_ref(impl_const_item.container_id(tcx)).unwrap().instantiate_identity();
1815

1816
    debug!("compare_impl_const(impl_trait_ref={:?})", impl_trait_ref);
1817

1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
    compare_number_of_generics(tcx, impl_const_item, trait_const_item, false)?;
    compare_generic_param_kinds(tcx, impl_const_item, trait_const_item, false)?;
    compare_const_predicate_entailment(tcx, impl_const_item, trait_const_item, impl_trait_ref)
}

/// The equivalent of [compare_method_predicate_entailment], but for associated constants
/// instead of associated functions.
// FIXME(generic_const_items): If possible extract the common parts of `compare_{type,const}_predicate_entailment`.
fn compare_const_predicate_entailment<'tcx>(
    tcx: TyCtxt<'tcx>,
    impl_ct: ty::AssocItem,
    trait_ct: ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorGuaranteed> {
    let impl_ct_def_id = impl_ct.def_id.expect_local();
    let impl_ct_span = tcx.def_span(impl_ct_def_id);
1834

1835 1836 1837 1838 1839
    // The below is for the most part highly similar to the procedure
    // for methods above. It is simpler in many respects, especially
    // because we shouldn't really have to deal with lifetimes or
    // predicates. In fact some of this should probably be put into
    // shared functions because of DRY violations...
1840 1841 1842
    let impl_args = GenericArgs::identity_for_item(tcx, impl_ct.def_id);
    let trait_to_impl_args =
        impl_args.rebase_onto(tcx, impl_ct.container_id(tcx), impl_trait_ref.args);
1843

1844 1845 1846
    // Create a parameter environment that represents the implementation's
    // method.
    // Compute placeholder form of impl and trait const tys.
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
    let impl_ty = tcx.type_of(impl_ct_def_id).instantiate_identity();

    let trait_ty = tcx.type_of(trait_ct.def_id).instantiate(tcx, trait_to_impl_args);
    let code = ObligationCauseCode::CompareImplItemObligation {
        impl_item_def_id: impl_ct_def_id,
        trait_item_def_id: trait_ct.def_id,
        kind: impl_ct.kind,
    };
    let mut cause = ObligationCause::new(impl_ct_span, impl_ct_def_id, code.clone());

    let impl_ct_predicates = tcx.predicates_of(impl_ct.def_id);
    let trait_ct_predicates = tcx.predicates_of(trait_ct.def_id);

    check_region_bounds_on_impl_item(tcx, impl_ct, trait_ct, false)?;

    // The predicates declared by the impl definition, the trait and the
    // associated const in the trait are assumed.
    let impl_predicates = tcx.predicates_of(impl_ct_predicates.parent.unwrap());
    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
    hybrid_preds.predicates.extend(
        trait_ct_predicates
            .instantiate_own(tcx, trait_to_impl_args)
            .map(|(predicate, _)| predicate),
    );

    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds.predicates), Reveal::UserFacing);
    let param_env = traits::normalize_param_env_or_error(
        tcx,
        param_env,
        ObligationCause::misc(impl_ct_span, impl_ct_def_id),
1877
    );
1878

1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
    let infcx = tcx.infer_ctxt().build();
    let ocx = ObligationCtxt::new(&infcx);

    let impl_ct_own_bounds = impl_ct_predicates.instantiate_own(tcx, impl_args);
    for (predicate, span) in impl_ct_own_bounds {
        let cause = ObligationCause::misc(span, impl_ct_def_id);
        let predicate = ocx.normalize(&cause, param_env, predicate);

        let cause = ObligationCause::new(span, impl_ct_def_id, code.clone());
        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
    }

1891
    // There is no "body" here, so just pass dummy id.
1892
    let impl_ty = ocx.normalize(&cause, param_env, impl_ty);
1893

1894
    debug!("compare_const_impl: impl_ty={:?}", impl_ty);
1895

1896
    let trait_ty = ocx.normalize(&cause, param_env, trait_ty);
T
trixnz 已提交
1897

1898
    debug!("compare_const_impl: trait_ty={:?}", trait_ty);
T
trixnz 已提交
1899

1900
    let err = ocx.sup(&cause, param_env, trait_ty, impl_ty);
T
trixnz 已提交
1901

1902 1903 1904 1905 1906
    if let Err(terr) = err {
        debug!(
            "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
            impl_ty, trait_ty
        );
B
reviews  
Boxy 已提交
1907

1908
        // Locate the Span containing just the type of the offending impl
1909
        let (ty, _) = tcx.hir().expect_impl_item(impl_ct_def_id).expect_const();
1910
        cause.span = ty.span;
1911

1912 1913 1914 1915 1916
        let mut diag = struct_span_err!(
            tcx.sess,
            cause.span,
            E0326,
            "implemented const `{}` has an incompatible type for trait",
1917
            trait_ct.name
1918 1919
        );

1920
        let trait_c_span = trait_ct.def_id.as_local().map(|trait_ct_def_id| {
1921
            // Add a label to the Span containing just the type of the const
1922
            let (ty, _) = tcx.hir().expect_trait_item(trait_ct_def_id).expect_const();
1923
            ty.span
1924 1925 1926 1927 1928
        });

        infcx.err_ctxt().note_type_err(
            &mut diag,
            &cause,
1929
            trait_c_span.map(|span| (span, Cow::from("type in trait"))),
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
            Some(infer::ValuePairs::Terms(ExpectedFound {
                expected: trait_ty.into(),
                found: impl_ty.into(),
            })),
            terr,
            false,
            false,
        );
        return Err(diag.emit());
    };

    // Check that all obligations are satisfied by the implementation's
    // version.
    let errors = ocx.select_all_or_error();
    if !errors.is_empty() {
1945
        return Err(infcx.err_ctxt().report_fulfillment_errors(&errors));
1946 1947
    }

L
lcnr 已提交
1948
    let outlives_env = OutlivesEnvironment::new(param_env);
1949
    ocx.resolve_regions_and_report_errors(impl_ct_def_id, &outlives_env)
1950
}
1951

M
Michael Goulet 已提交
1952
pub(super) fn compare_impl_ty<'tcx>(
1953
    tcx: TyCtxt<'tcx>,
1954 1955
    impl_ty: ty::AssocItem,
    trait_ty: ty::AssocItem,
1956 1957 1958 1959
    impl_trait_ref: ty::TraitRef<'tcx>,
) {
    debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);

1960
    let _: Result<(), ErrorGuaranteed> = try {
1961
        compare_number_of_generics(tcx, impl_ty, trait_ty, false)?;
1962
        compare_generic_param_kinds(tcx, impl_ty, trait_ty, false)?;
1963 1964
        compare_type_predicate_entailment(tcx, impl_ty, trait_ty, impl_trait_ref)?;
        check_type_bounds(tcx, trait_ty, impl_ty, impl_trait_ref)?;
1965
    };
1966 1967
}

1968
/// The equivalent of [compare_method_predicate_entailment], but for associated types
1969
/// instead of associated functions.
1970
fn compare_type_predicate_entailment<'tcx>(
1971
    tcx: TyCtxt<'tcx>,
1972 1973
    impl_ty: ty::AssocItem,
    trait_ty: ty::AssocItem,
1974
    impl_trait_ref: ty::TraitRef<'tcx>,
M
mark 已提交
1975
) -> Result<(), ErrorGuaranteed> {
1976 1977 1978
    let impl_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
    let trait_to_impl_args =
        impl_args.rebase_onto(tcx, impl_ty.container_id(tcx), impl_trait_ref.args);
1979 1980 1981 1982

    let impl_ty_predicates = tcx.predicates_of(impl_ty.def_id);
    let trait_ty_predicates = tcx.predicates_of(trait_ty.def_id);

1983
    check_region_bounds_on_impl_item(tcx, impl_ty, trait_ty, false)?;
1984

1985
    let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_args);
1986
    if impl_ty_own_bounds.len() == 0 {
1987 1988 1989 1990
        // Nothing to check.
        return Ok(());
    }

1991
    // This `DefId` should be used for the `body_id` field on each
1992 1993
    // `ObligationCause` (and the `FnCtxt`). This is what
    // `regionck_item` expects.
1994
    let impl_ty_def_id = impl_ty.def_id.expect_local();
1995
    debug!("compare_type_predicate_entailment: trait_to_impl_args={:?}", trait_to_impl_args);
1996 1997 1998 1999 2000

    // The predicates declared by the impl definition, the trait and the
    // associated type in the trait are assumed.
    let impl_predicates = tcx.predicates_of(impl_ty_predicates.parent.unwrap());
    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
2001 2002
    hybrid_preds.predicates.extend(
        trait_ty_predicates
2003
            .instantiate_own(tcx, trait_to_impl_args)
2004 2005
            .map(|(predicate, _)| predicate),
    );
2006 2007 2008

    debug!("compare_type_predicate_entailment: bounds={:?}", hybrid_preds);

2009
    let impl_ty_span = tcx.def_span(impl_ty_def_id);
2010
    let normalize_cause = ObligationCause::misc(impl_ty_span, impl_ty_def_id);
D
Deadbeef 已提交
2011
    let param_env = ty::ParamEnv::new(tcx.mk_clauses(&hybrid_preds.predicates), Reveal::UserFacing);
2012
    let param_env = traits::normalize_param_env_or_error(tcx, param_env, normalize_cause);
2013 2014
    let infcx = tcx.infer_ctxt().build();
    let ocx = ObligationCtxt::new(&infcx);
2015

2016
    debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
2017

2018
    for (predicate, span) in impl_ty_own_bounds {
2019
        let cause = ObligationCause::misc(span, impl_ty_def_id);
2020
        let predicate = ocx.normalize(&cause, param_env, predicate);
2021

2022 2023
        let cause = ObligationCause::new(
            span,
2024
            impl_ty_def_id,
2025 2026 2027 2028 2029
            ObligationCauseCode::CompareImplItemObligation {
                impl_item_def_id: impl_ty.def_id.expect_local(),
                trait_item_def_id: trait_ty.def_id,
                kind: impl_ty.kind,
            },
2030
        );
2031
        ocx.register_obligation(traits::Obligation::new(tcx, cause, param_env, predicate));
2032
    }
2033

2034 2035 2036 2037
    // Check that all obligations are satisfied by the implementation's
    // version.
    let errors = ocx.select_all_or_error();
    if !errors.is_empty() {
2038
        let reported = infcx.err_ctxt().report_fulfillment_errors(&errors);
2039 2040 2041 2042 2043
        return Err(reported);
    }

    // Finally, resolve all regions. This catches wily misuses of
    // lifetime parameters.
L
lcnr 已提交
2044 2045
    let outlives_env = OutlivesEnvironment::new(param_env);
    ocx.resolve_regions_and_report_errors(impl_ty_def_id, &outlives_env)
2046 2047
}

2048 2049 2050 2051 2052 2053 2054
/// Validate that `ProjectionCandidate`s created for this associated type will
/// be valid.
///
/// Usually given
///
/// trait X { type Y: Copy } impl X for T { type Y = S; }
///
2055
/// We are able to normalize `<T as X>::Y` to `S`, and so when we check the
2056 2057 2058 2059 2060
/// impl is well-formed we have to prove `S: Copy`.
///
/// For default associated types the normalization is not possible (the value
/// from the impl could be overridden). We also can't normalize generic
/// associated types (yet) because they contain bound parameters.
2061
#[instrument(level = "debug", skip(tcx))]
M
Michael Goulet 已提交
2062
pub(super) fn check_type_bounds<'tcx>(
2063
    tcx: TyCtxt<'tcx>,
2064 2065
    trait_ty: ty::AssocItem,
    impl_ty: ty::AssocItem,
2066
    impl_trait_ref: ty::TraitRef<'tcx>,
M
mark 已提交
2067
) -> Result<(), ErrorGuaranteed> {
M
Michael Goulet 已提交
2068 2069
    let param_env = tcx.param_env(impl_ty.def_id);
    let container_id = impl_ty.container_id(tcx);
2070 2071 2072
    // Given
    //
    // impl<A, B> Foo<u32> for (A, B) {
M
Michael Goulet 已提交
2073
    //     type Bar<C> = Wrapper<A, B, C>
2074 2075
    // }
    //
2076
    // - `impl_trait_ref` would be `<(A, B) as Foo<u32>>`
2077
    // - `normalize_impl_ty_args` would be `[A, B, ^0.0]` (`^0.0` here is the bound var with db 0 and index 0)
M
Michael Goulet 已提交
2078
    // - `normalize_impl_ty` would be `Wrapper<A, B, ^0.0>`
2079
    // - `rebased_args` would be `[(A, B), u32, ^0.0]`, combining the args from
2080
    //    the *trait* with the generic associated type parameters (as bound vars).
J
jackh726 已提交
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
    //
    // A note regarding the use of bound vars here:
    // Imagine as an example
    // ```
    // trait Family {
    //     type Member<C: Eq>;
    // }
    //
    // impl Family for VecFamily {
    //     type Member<C: Eq> = i32;
    // }
    // ```
    // Here, we would generate
    // ```notrust
    // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) }
    // ```
    // when we really would like to generate
    // ```notrust
    // forall<C> { Normalize(<VecFamily as Family>::Member<C> => i32) :- Implemented(C: Eq) }
    // ```
    // But, this is probably fine, because although the first clause can be used with types C that
    // do not implement Eq, for it to cause some kind of problem, there would have to be a
    // VecFamily::Member<X> for some type X where !(X: Eq), that appears in the value of type
    // Member<C: Eq> = .... That type would fail a well-formedness check that we ought to be doing
    // elsewhere, which would check that any <T as Family>::Member<X> meets the bounds declared in
    // the trait (notably, that X: Eq and T: Family).
2107
    let mut bound_vars: smallvec::SmallVec<[ty::BoundVariableKind; 8]> =
M
Michael Goulet 已提交
2108
        smallvec::SmallVec::with_capacity(tcx.generics_of(impl_ty.def_id).params.len());
2109 2110 2111 2112 2113
    // Extend the impl's identity args with late-bound GAT vars
    let normalize_impl_ty_args = ty::GenericArgs::identity_for_item(tcx, container_id).extend_to(
        tcx,
        impl_ty.def_id,
        |param, _| match param.kind {
M
Michael Goulet 已提交
2114 2115 2116 2117
            GenericParamDefKind::Type { .. } => {
                let kind = ty::BoundTyKind::Param(param.def_id, param.name);
                let bound_var = ty::BoundVariableKind::Ty(kind);
                bound_vars.push(bound_var);
2118 2119
                Ty::new_bound(
                    tcx,
M
Michael Goulet 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128
                    ty::INNERMOST,
                    ty::BoundTy { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
                )
                .into()
            }
            GenericParamDefKind::Lifetime => {
                let kind = ty::BoundRegionKind::BrNamed(param.def_id, param.name);
                let bound_var = ty::BoundVariableKind::Region(kind);
                bound_vars.push(bound_var);
2129 2130
                ty::Region::new_late_bound(
                    tcx,
M
Michael Goulet 已提交
2131 2132 2133 2134 2135 2136 2137 2138
                    ty::INNERMOST,
                    ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind },
                )
                .into()
            }
            GenericParamDefKind::Const { .. } => {
                let bound_var = ty::BoundVariableKind::Const;
                bound_vars.push(bound_var);
2139 2140 2141 2142
                ty::Const::new_bound(
                    tcx,
                    ty::INNERMOST,
                    ty::BoundVar::from_usize(bound_vars.len() - 1),
M
Michael Goulet 已提交
2143 2144 2145 2146 2147 2148
                    tcx.type_of(param.def_id)
                        .no_bound_vars()
                        .expect("const parameter types cannot be generic"),
                )
                .into()
            }
2149 2150
        },
    );
2151 2152 2153 2154 2155 2156 2157 2158 2159
    // When checking something like
    //
    // trait X { type Y: PartialEq<<Self as X>::Y> }
    // impl X for T { default type Y = S; }
    //
    // We will have to prove the bound S: PartialEq<<T as X>::Y>. In this case
    // we want <T as X>::Y to normalize to S. This is valid because we are
    // checking the default value specifically here. Add this equality to the
    // ParamEnv for normalization specifically.
2160 2161
    let normalize_impl_ty = tcx.type_of(impl_ty.def_id).instantiate(tcx, normalize_impl_ty_args);
    let rebased_args = normalize_impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
M
Michael Goulet 已提交
2162
    let bound_vars = tcx.mk_bound_variable_kinds(&bound_vars);
2163
    let normalize_param_env = {
2164
        let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
M
Michael Goulet 已提交
2165
        match normalize_impl_ty.kind() {
2166
            ty::Alias(ty::Projection, proj)
2167
                if proj.def_id == trait_ty.def_id && proj.args == rebased_args =>
2168 2169 2170 2171 2172 2173 2174 2175
            {
                // Don't include this predicate if the projected type is
                // exactly the same as the projection. This can occur in
                // (somewhat dubious) code like this:
                //
                // impl<T> X for T where T: X { type Y = <T as X>::Y; }
            }
            _ => predicates.push(
2176 2177
                ty::Binder::bind_with_vars(
                    ty::ProjectionPredicate {
2178
                        projection_ty: tcx.mk_alias_ty(trait_ty.def_id, rebased_args),
M
Michael Goulet 已提交
2179
                        term: normalize_impl_ty.into(),
2180
                    },
2181 2182
                    bound_vars,
                )
2183 2184 2185
                .to_predicate(tcx),
            ),
        };
D
Deadbeef 已提交
2186
        ty::ParamEnv::new(tcx.mk_clauses(&predicates), Reveal::UserFacing)
2187
    };
2188 2189
    debug!(?normalize_param_env);

2190
    let impl_ty_def_id = impl_ty.def_id.expect_local();
2191 2192
    let impl_ty_args = GenericArgs::identity_for_item(tcx, impl_ty.def_id);
    let rebased_args = impl_ty_args.rebase_onto(tcx, container_id, impl_trait_ref.args);
2193

2194 2195
    let infcx = tcx.infer_ctxt().build();
    let ocx = ObligationCtxt::new(&infcx);
2196

2197 2198 2199
    // A synthetic impl Trait for RPITIT desugaring has no HIR, which we currently use to get the
    // span for an impl's associated type. Instead, for these, use the def_span for the synthesized
    // associated type.
2200
    let impl_ty_span = if impl_ty.is_impl_trait_in_trait() {
2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
        tcx.def_span(impl_ty_def_id)
    } else {
        match tcx.hir().get_by_def_id(impl_ty_def_id) {
            hir::Node::TraitItem(hir::TraitItem {
                kind: hir::TraitItemKind::Type(_, Some(ty)),
                ..
            }) => ty.span,
            hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Type(ty), .. }) => ty.span,
            _ => bug!(),
        }
2211
    };
2212
    let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl_ty_def_id)?;
L
lcnr 已提交
2213

2214 2215
    let normalize_cause = ObligationCause::new(
        impl_ty_span,
2216
        impl_ty_def_id,
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
        ObligationCauseCode::CheckAssociatedTypeBounds {
            impl_item_def_id: impl_ty.def_id.expect_local(),
            trait_item_def_id: trait_ty.def_id,
        },
    );
    let mk_cause = |span: Span| {
        let code = if span.is_dummy() {
            traits::ItemObligation(trait_ty.def_id)
        } else {
            traits::BindingObligation(trait_ty.def_id, span)
M
Matthew Jasper 已提交
2227
        };
2228
        ObligationCause::new(impl_ty_span, impl_ty_def_id, code)
2229
    };
2230

M
Michael Goulet 已提交
2231
    let obligations: Vec<_> = tcx
2232
        .explicit_item_bounds(trait_ty.def_id)
2233
        .iter_instantiated_copied(tcx, rebased_args)
2234
        .map(|(concrete_ty_bound, span)| {
2235
            debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
2236
            traits::Obligation::new(tcx, mk_cause(span), param_env, concrete_ty_bound)
2237 2238 2239 2240
        })
        .collect();
    debug!("check_type_bounds: item_bounds={:?}", obligations);

M
Michael Goulet 已提交
2241
    for mut obligation in util::elaborate(tcx, obligations) {
S
Santiago Pastorino 已提交
2242
        let normalized_predicate =
2243
            ocx.normalize(&normalize_cause, normalize_param_env, obligation.predicate);
2244 2245
        debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
        obligation.predicate = normalized_predicate;
2246

2247 2248 2249 2250 2251 2252
        ocx.register_obligation(obligation);
    }
    // Check that all obligations are satisfied by the implementation's
    // version.
    let errors = ocx.select_all_or_error();
    if !errors.is_empty() {
2253
        let reported = infcx.err_ctxt().report_fulfillment_errors(&errors);
2254 2255
        return Err(reported);
    }
2256

2257 2258
    // Finally, resolve all regions. This catches wily misuses of
    // lifetime parameters.
2259
    let implied_bounds = infcx.implied_bounds_tys(param_env, impl_ty_def_id, assumed_wf_types);
L
lcnr 已提交
2260 2261
    let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
    ocx.resolve_regions_and_report_errors(impl_ty_def_id, &outlives_env)
2262 2263
}

2264 2265 2266
fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
    match impl_item.kind {
        ty::AssocKind::Const => "const",
2267
        ty::AssocKind::Fn => "method",
M
Matthew Jasper 已提交
2268
        ty::AssocKind::Type => "type",
2269 2270
    }
}