compare_method.rs 52.2 KB
Newer Older
1
use crate::errors::LifetimesOrBoundsMismatchOnTrait;
2
use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, ErrorReported};
3 4
use rustc_hir as hir;
use rustc_hir::def::{DefKind, Res};
5
use rustc_hir::intravisit;
6
use rustc_hir::{GenericParamKind, ImplItemKind, TraitItemKind};
C
Camille GILLOT 已提交
7
use rustc_infer::infer::{self, InferOk, TyCtxtInferExt};
8
use rustc_infer::traits::util;
9
use rustc_middle::ty;
10
use rustc_middle::ty::error::{ExpectedFound, TypeError};
11
use rustc_middle::ty::subst::{InternalSubsts, Subst};
12
use rustc_middle::ty::util::ExplicitSelf;
13
use rustc_middle::ty::{GenericParamDefKind, ToPredicate, TyCtxt};
14
use rustc_span::Span;
C
Camille GILLOT 已提交
15 16
use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
use rustc_trait_selection::traits::{self, ObligationCause, ObligationCauseCode, Reveal};
17

M
Mark Rousskov 已提交
18
use super::{potentially_plural_count, FnCtxt, Inherited};
19 20 21 22 23 24

/// Checks that a method from an impl conforms to the signature of
/// the same method as declared in the trait.
///
/// # Parameters
///
A
Alexander Regueiro 已提交
25 26 27 28
/// - `impl_m`: type of the method we are checking
/// - `impl_m_span`: span to use for reporting errors
/// - `trait_m`: the method in the trait
/// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation
29

30
crate fn compare_impl_method<'tcx>(
31
    tcx: TyCtxt<'tcx>,
32 33 34 35 36 37
    impl_m: &ty::AssocItem,
    impl_m_span: Span,
    trait_m: &ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
    trait_item_span: Option<Span>,
) {
M
Mark Rousskov 已提交
38
    debug!("compare_impl_method(impl_trait_ref={:?})", impl_trait_ref);
39

40
    let impl_m_span = tcx.sess.source_map().guess_head_span(impl_m_span);
41

M
Mark Rousskov 已提交
42 43
    if let Err(ErrorReported) = compare_self_type(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
    {
N
Niko Matsakis 已提交
44
        return;
45 46
    }

M
Mark Rousskov 已提交
47 48 49
    if let Err(ErrorReported) =
        compare_number_of_generics(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
    {
N
Niko Matsakis 已提交
50 51
        return;
    }
T
Tim Neumann 已提交
52

M
Mark Rousskov 已提交
53 54 55
    if let Err(ErrorReported) =
        compare_number_of_method_arguments(tcx, impl_m, impl_m_span, trait_m, trait_item_span)
    {
56 57 58
        return;
    }

M
Mark Rousskov 已提交
59
    if let Err(ErrorReported) = compare_synthetic_generics(tcx, impl_m, trait_m) {
60 61 62
        return;
    }

M
Mark Rousskov 已提交
63 64 65
    if let Err(ErrorReported) =
        compare_predicate_entailment(tcx, impl_m, impl_m_span, trait_m, impl_trait_ref)
    {
66 67
        return;
    }
N
Niko Matsakis 已提交
68 69
}

70
fn compare_predicate_entailment<'tcx>(
71
    tcx: TyCtxt<'tcx>,
72 73 74 75 76
    impl_m: &ty::AssocItem,
    impl_m_span: Span,
    trait_m: &ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorReported> {
77
    let trait_to_impl_substs = impl_trait_ref.substs;
78

T
Taylor Cramer 已提交
79 80 81
    // This node-id should be used for the `body_id` field on each
    // `ObligationCause` (and the `FnCtxt`). This is what
    // `regionck_item` expects.
82
    let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
T
Taylor Cramer 已提交
83

84 85 86 87 88
    // We sometimes modify the span further down.
    let mut cause = ObligationCause::new(
        impl_m_span,
        impl_m_hir_id,
        ObligationCauseCode::CompareImplMethodObligation {
89
            item_name: impl_m.ident.name,
90 91 92
            impl_item_def_id: impl_m.def_id,
            trait_item_def_id: trait_m.def_id,
        },
93
    );
94

95 96
    // This code is best explained by example. Consider a trait:
    //
B
Bastian Kauschke 已提交
97 98
    //     trait Trait<'t, T> {
    //         fn method<'a, M>(t: &'t T, m: &'a M) -> Self;
99 100 101 102 103
    //     }
    //
    // And an impl:
    //
    //     impl<'i, 'j, U> Trait<'j, &'i U> for Foo {
B
Bastian Kauschke 已提交
104
    //          fn method<'b, N>(t: &'j &'i U, m: &'b N) -> Foo;
105 106 107 108 109 110 111 112 113 114 115 116 117
    //     }
    //
    // We wish to decide if those two method types are compatible.
    //
    // We start out with trait_to_impl_substs, that maps the trait
    // type parameters to impl type parameters. This is taken from the
    // impl trait reference:
    //
    //     trait_to_impl_substs = {'t => 'j, T => &'i U, Self => Foo}
    //
    // We create a mapping `dummy_substs` that maps from the impl type
    // parameters to fresh types and regions. For type parameters,
    // this is the identity transform, but we could as well use any
N
Niko Matsakis 已提交
118
    // placeholder types. For regions, we convert from bound to free
119 120 121
    // regions (Note: but only early-bound regions, i.e., those
    // declared on the impl or used in type parameter bounds).
    //
B
Bastian Kauschke 已提交
122
    //     impl_to_placeholder_substs = {'i => 'i0, U => U0, N => N0 }
123
    //
B
Bastian Kauschke 已提交
124
    // Now we can apply placeholder_substs to the type of the impl method
N
Niko Matsakis 已提交
125
    // to yield a new function type in terms of our fresh, placeholder
126 127 128 129 130 131 132
    // types:
    //
    //     <'b> fn(t: &'i0 U0, m: &'b) -> Foo
    //
    // We now want to extract and substitute the type of the *trait*
    // method and compare it. To do so, we must create a compound
    // substitution by combining trait_to_impl_substs and
B
Bastian Kauschke 已提交
133
    // impl_to_placeholder_substs, and also adding a mapping for the method
134 135 136
    // type parameters. We extend the mapping to also include
    // the method parameters.
    //
B
Bastian Kauschke 已提交
137
    //     trait_to_placeholder_substs = { T => &'i0 U0, Self => Foo, M => N0 }
138 139 140 141 142 143 144 145 146
    //
    // Applying this to the trait method type yields:
    //
    //     <'a> fn(t: &'i0 U0, m: &'a) -> Foo
    //
    // This type is also the same but the name of the bound region ('a
    // vs 'b).  However, the normal subtyping rules on fn types handle
    // this kind of equivalency just fine.
    //
J
Joseph Crail 已提交
147
    // We now use these substitutions to ensure that all declared bounds are
148 149 150
    // satisfied by the implementation's method.
    //
    // We do this by creating a parameter environment which contains a
B
Bastian Kauschke 已提交
151 152
    // substitution corresponding to impl_to_placeholder_substs. We then build
    // trait_to_placeholder_substs and use it to convert the predicates contained
N
Niko Matsakis 已提交
153
    // in the trait_m.generics to the placeholder form.
154 155 156 157
    //
    // Finally we register each of these predicates as an obligation in
    // a fresh FulfillmentCtxt, and invoke select_all_or_error.

N
Niko Matsakis 已提交
158
    // Create mapping from impl to placeholder.
B
Bastian Kauschke 已提交
159
    let impl_to_placeholder_substs = InternalSubsts::identity_for_item(tcx, impl_m.def_id);
160

N
Niko Matsakis 已提交
161
    // Create mapping from trait to placeholder.
B
Bastian Kauschke 已提交
162 163 164
    let trait_to_placeholder_substs =
        impl_to_placeholder_substs.rebase_onto(tcx, impl_m.container.id(), trait_to_impl_substs);
    debug!("compare_impl_method: trait_to_placeholder_substs={:?}", trait_to_placeholder_substs);
165

166 167 168 169
    let impl_m_generics = tcx.generics_of(impl_m.def_id);
    let trait_m_generics = tcx.generics_of(trait_m.def_id);
    let impl_m_predicates = tcx.predicates_of(impl_m.def_id);
    let trait_m_predicates = tcx.predicates_of(trait_m.def_id);
170

N
Niko Matsakis 已提交
171
    // Check region bounds.
172 173 174 175 176 177 178 179
    check_region_bounds_on_impl_item(
        tcx,
        impl_m_span,
        impl_m,
        trait_m,
        &trait_m_generics,
        &impl_m_generics,
    )?;
N
Niko Matsakis 已提交
180 181 182 183 184 185

    // 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.
186
    let impl_predicates = tcx.predicates_of(impl_m_predicates.parent.unwrap());
187
    let mut hybrid_preds = impl_predicates.instantiate_identity(tcx);
N
Niko Matsakis 已提交
188 189 190 191 192 193 194 195 196 197

    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.
M
Mark Rousskov 已提交
198 199
    hybrid_preds
        .predicates
B
Bastian Kauschke 已提交
200
        .extend(trait_m_predicates.instantiate_own(tcx, trait_to_placeholder_substs).predicates);
N
Niko Matsakis 已提交
201

N
Niko Matsakis 已提交
202
    // Construct trait parameter environment and then shift it into the placeholder viewpoint.
N
Niko Matsakis 已提交
203 204
    // The key step here is to update the caller_bounds's predicates to be
    // the new hybrid bounds we computed.
L
ljedrz 已提交
205
    let normalize_cause = traits::ObligationCause::misc(impl_m_span, impl_m_hir_id);
206 207
    let param_env =
        ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing);
M
Mark Rousskov 已提交
208 209 210 211 212
    let param_env = traits::normalize_param_env_or_error(
        tcx,
        impl_m.def_id,
        param_env,
        normalize_cause.clone(),
S
scalexm 已提交
213
    );
214

215
    tcx.infer_ctxt().enter(|infcx| {
216
        let inh = Inherited::new(infcx, impl_m.def_id.expect_local());
217
        let infcx = &inh.infcx;
218

M
Mark Rousskov 已提交
219
        debug!("compare_impl_method: caller_bounds={:?}", param_env.caller_bounds());
220 221 222

        let mut selcx = traits::SelectionContext::new(&infcx);

B
Bastian Kauschke 已提交
223
        let impl_m_own_bounds = impl_m_predicates.instantiate_own(tcx, impl_to_placeholder_substs);
S
scalexm 已提交
224
        let (impl_m_own_bounds, _) = infcx.replace_bound_vars_with_fresh_vars(
225 226
            impl_m_span,
            infer::HigherRankedType,
B
Bastian Kauschke 已提交
227
            ty::Binder::bind(impl_m_own_bounds.predicates),
228
        );
229
        for predicate in impl_m_own_bounds {
230
            let traits::Normalized { value: predicate, obligations } =
B
Bastian Kauschke 已提交
231
                traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
232

233
            inh.register_predicates(obligations);
N
Niko Matsakis 已提交
234
            inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
235
        }
236

237 238 239 240 241 242 243 244 245 246 247 248 249
        // 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.

N
Niko Matsakis 已提交
250
        // Compute placeholder form of impl and trait method tys.
251 252
        let tcx = infcx.tcx;

S
scalexm 已提交
253 254 255
        let (impl_sig, _) = infcx.replace_bound_vars_with_fresh_vars(
            impl_m_span,
            infer::HigherRankedType,
B
Bastian Kauschke 已提交
256
            tcx.fn_sig(impl_m.def_id),
S
scalexm 已提交
257
        );
258
        let impl_sig =
B
Bastian Kauschke 已提交
259
            inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, impl_sig);
260
        let impl_fty = tcx.mk_fn_ptr(ty::Binder::bind(impl_sig));
261 262
        debug!("compare_impl_method: impl_fty={:?}", impl_fty);

B
Bastian Kauschke 已提交
263
        let trait_sig = tcx.liberate_late_bound_regions(impl_m.def_id, tcx.fn_sig(trait_m.def_id));
B
Bastian Kauschke 已提交
264
        let trait_sig = trait_sig.subst(tcx, trait_to_placeholder_substs);
265
        let trait_sig =
B
Bastian Kauschke 已提交
266
            inh.normalize_associated_types_in(impl_m_span, impl_m_hir_id, param_env, trait_sig);
267
        let trait_fty = tcx.mk_fn_ptr(ty::Binder::bind(trait_sig));
268 269 270

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

M
Mark Rousskov 已提交
271 272 273 274 275
        let sub_result = infcx.at(&cause, param_env).sup(trait_fty, impl_fty).map(
            |InferOk { obligations, .. }| {
                inh.register_predicates(obligations);
            },
        );
276 277

        if let Err(terr) = sub_result {
M
Mark Rousskov 已提交
278 279 280 281 282 283
            debug!("sub_types failed: impl ty {:?}, trait ty {:?}", impl_fty, trait_fty);

            let (impl_err_span, trait_err_span) = extract_spans_for_error_reporting(
                &infcx, param_env, &terr, &cause, impl_m, impl_sig, trait_m, trait_sig,
            );

284
            cause.make_mut().span = impl_err_span;
M
Mark Rousskov 已提交
285 286 287 288 289 290 291 292

            let mut diag = struct_span_err!(
                tcx.sess,
                cause.span(tcx),
                E0053,
                "method `{}` has an incompatible type for trait",
                trait_m.ident
            );
293 294
            if let TypeError::Mutability = terr {
                if let Some(trait_err_span) = trait_err_span {
M
Mark Rousskov 已提交
295 296
                    if let Ok(trait_err_str) = tcx.sess.source_map().span_to_snippet(trait_err_span)
                    {
297
                        diag.span_suggestion(
298
                            impl_err_span,
299
                            "consider changing the mutability to match the trait",
S
Shotaro Yamada 已提交
300
                            trait_err_str,
301
                            Applicability::MachineApplicable,
302 303 304 305
                        );
                    }
                }
            }
306

M
Mark Rousskov 已提交
307 308 309 310 311 312 313 314 315 316
            infcx.note_type_err(
                &mut diag,
                &cause,
                trait_err_span.map(|sp| (sp, "type in trait".to_owned())),
                Some(infer::ValuePairs::Types(ExpectedFound {
                    expected: trait_fty,
                    found: impl_fty,
                })),
                &terr,
            );
317
            diag.emit();
N
Niko Matsakis 已提交
318
            return Err(ErrorReported);
319 320
        }

321 322
        // Check that all obligations are satisfied by the implementation's
        // version.
323
        if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
324
            infcx.report_fulfillment_errors(errors, None, false);
N
Niko Matsakis 已提交
325
            return Err(ErrorReported);
326
        }
327

328
        // Finally, resolve all regions. This catches wily misuses of
329
        // lifetime parameters.
L
ljedrz 已提交
330
        let fcx = FnCtxt::new(&inh, param_env, impl_m_hir_id);
331
        fcx.regionck_item(impl_m_hir_id, impl_m_span, trait_sig.inputs_and_output);
N
Niko Matsakis 已提交
332 333 334 335 336

        Ok(())
    })
}

337
fn check_region_bounds_on_impl_item<'tcx>(
338
    tcx: TyCtxt<'tcx>,
339 340 341 342 343 344
    span: Span,
    impl_m: &ty::AssocItem,
    trait_m: &ty::AssocItem,
    trait_generics: &ty::Generics,
    impl_generics: &ty::Generics,
) -> Result<(), ErrorReported> {
V
varkor 已提交
345 346
    let trait_params = trait_generics.own_counts().lifetimes;
    let impl_params = impl_generics.own_counts().lifetimes;
N
Niko Matsakis 已提交
347

M
Mark Rousskov 已提交
348 349
    debug!(
        "check_region_bounds_on_impl_item: \
N
Niko Matsakis 已提交
350
            trait_generics={:?} \
351
            impl_generics={:?}",
M
Mark Rousskov 已提交
352 353
        trait_generics, impl_generics
    );
N
Niko Matsakis 已提交
354 355 356 357 358 359 360 361 362 363

    // Must have same number of early-bound lifetime parameters.
    // Unfortunately, if the user screws up the bounds, then this
    // will change classification between early and late.  E.g.,
    // 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.
364
    if trait_params != impl_params {
365
        let item_kind = assoc_item_kind_str(impl_m);
366
        let def_span = tcx.sess.source_map().guess_head_span(span);
367
        let span = tcx.hir().get_generics(impl_m.def_id).map_or(def_span, |g| g.span);
368
        let generics_span = tcx.hir().span_if_local(trait_m.def_id).map(|sp| {
369
            let def_sp = tcx.sess.source_map().guess_head_span(sp);
370 371
            tcx.hir().get_generics(trait_m.def_id).map_or(def_sp, |g| g.span)
        });
372

373
        tcx.sess.emit_err(LifetimesOrBoundsMismatchOnTrait {
374
            span,
375
            item_kind,
376 377 378
            ident: impl_m.ident,
            generics_span,
        });
N
Niko Matsakis 已提交
379 380 381
        return Err(ErrorReported);
    }

382
    Ok(())
N
Niko Matsakis 已提交
383 384
}

385 386 387 388 389 390 391 392 393 394
fn extract_spans_for_error_reporting<'a, 'tcx>(
    infcx: &infer::InferCtxt<'a, 'tcx>,
    param_env: ty::ParamEnv<'tcx>,
    terr: &TypeError<'_>,
    cause: &ObligationCause<'tcx>,
    impl_m: &ty::AssocItem,
    impl_sig: ty::FnSig<'tcx>,
    trait_m: &ty::AssocItem,
    trait_sig: ty::FnSig<'tcx>,
) -> (Span, Option<Span>) {
N
Niko Matsakis 已提交
395
    let tcx = infcx.tcx;
396
    let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
M
Mark Rousskov 已提交
397
    let (impl_m_output, impl_m_iter) = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
M
Mark Mansi 已提交
398
        ImplItemKind::Fn(ref impl_m_sig, _) => {
N
Niko Matsakis 已提交
399 400 401 402 403 404 405
            (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter())
        }
        _ => bug!("{:?} is not a method", impl_m),
    };

    match *terr {
        TypeError::Mutability => {
M
marmeladema 已提交
406
            if let Some(def_id) = trait_m.def_id.as_local() {
407
                let trait_m_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
M
Mark Rousskov 已提交
408
                let trait_m_iter = match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
M
Mark Mansi 已提交
409 410
                    TraitItemKind::Fn(ref trait_m_sig, _) => trait_m_sig.decl.inputs.iter(),
                    _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
N
Niko Matsakis 已提交
411 412
                };

M
Mark Rousskov 已提交
413 414 415 416 417 418 419 420 421 422 423 424
                impl_m_iter
                    .zip(trait_m_iter)
                    .find(|&(ref impl_arg, ref trait_arg)| {
                        match (&impl_arg.kind, &trait_arg.kind) {
                            (
                                &hir::TyKind::Rptr(_, ref impl_mt),
                                &hir::TyKind::Rptr(_, ref trait_mt),
                            )
                            | (&hir::TyKind::Ptr(ref impl_mt), &hir::TyKind::Ptr(ref trait_mt)) => {
                                impl_mt.mutbl != trait_mt.mutbl
                            }
                            _ => false,
425
                        }
M
Mark Rousskov 已提交
426 427 428
                    })
                    .map(|(ref impl_arg, ref trait_arg)| (impl_arg.span, Some(trait_arg.span)))
                    .unwrap_or_else(|| (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)))
N
Niko Matsakis 已提交
429
            } else {
F
flip1995 已提交
430
                (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
N
Niko Matsakis 已提交
431
            }
432
        }
N
Niko Matsakis 已提交
433
        TypeError::Sorts(ExpectedFound { .. }) => {
M
marmeladema 已提交
434
            if let Some(def_id) = trait_m.def_id.as_local() {
435
                let trait_m_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
N
Niko Matsakis 已提交
436
                let (trait_m_output, trait_m_iter) =
437
                    match tcx.hir().expect_trait_item(trait_m_hir_id).kind {
M
Mark Mansi 已提交
438
                        TraitItemKind::Fn(ref trait_m_sig, _) => {
N
Niko Matsakis 已提交
439 440
                            (&trait_m_sig.decl.output, trait_m_sig.decl.inputs.iter())
                        }
M
Mark Mansi 已提交
441
                        _ => bug!("{:?} is not a TraitItemKind::Fn", trait_m),
N
Niko Matsakis 已提交
442
                    };
443

444 445
                let impl_iter = impl_sig.inputs().iter();
                let trait_iter = trait_sig.inputs().iter();
M
Mark Rousskov 已提交
446 447 448 449
                impl_iter
                    .zip(trait_iter)
                    .zip(impl_m_iter)
                    .zip(trait_m_iter)
450 451 452 453 454 455 456
                    .find_map(|(((&impl_arg_ty, &trait_arg_ty), impl_arg), trait_arg)| match infcx
                        .at(&cause, param_env)
                        .sub(trait_arg_ty, impl_arg_ty)
                    {
                        Ok(_) => None,
                        Err(_) => Some((impl_arg.span, Some(trait_arg.span))),
                    })
M
Mark Rousskov 已提交
457 458 459 460 461 462 463 464 465 466 467
                    .unwrap_or_else(|| {
                        if infcx
                            .at(&cause, param_env)
                            .sup(trait_sig.output(), impl_sig.output())
                            .is_err()
                        {
                            (impl_m_output.span(), Some(trait_m_output.span()))
                        } else {
                            (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
                        }
                    })
N
Niko Matsakis 已提交
468
            } else {
F
flip1995 已提交
469
                (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id))
N
Niko Matsakis 已提交
470 471
            }
        }
F
flip1995 已提交
472
        _ => (cause.span(tcx), tcx.hir().span_if_local(trait_m.def_id)),
473
    }
N
Niko Matsakis 已提交
474
}
475

476
fn compare_self_type<'tcx>(
477
    tcx: TyCtxt<'tcx>,
478 479 480 481 482
    impl_m: &ty::AssocItem,
    impl_m_span: Span,
    trait_m: &ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorReported> {
N
Niko Matsakis 已提交
483 484 485 486 487 488 489
    // Try to give more informative error messages about self typing
    // mismatches.  Note that any mismatch will also be detected
    // below, where we construct a canonical function type that
    // includes the self parameter as a normal parameter.  It's just
    // that the error messages you get out of this code are a bit more
    // inscrutable, particularly for cases where one method has no
    // self.
490

A
Andrew Xu 已提交
491
    let self_string = |method: &ty::AssocItem| {
492 493
        let untransformed_self_ty = match method.container {
            ty::ImplContainer(_) => impl_trait_ref.self_ty(),
M
Mark Rousskov 已提交
494
            ty::TraitContainer(_) => tcx.types.self_param,
495
        };
J
Jack Huey 已提交
496
        let self_arg_ty = tcx.fn_sig(method.def_id).input(0);
497
        let param_env = ty::ParamEnv::reveal_all();
498

499
        tcx.infer_ctxt().enter(|infcx| {
J
Jack Huey 已提交
500
            let self_arg_ty = tcx.liberate_late_bound_regions(method.def_id, self_arg_ty);
501 502
            let can_eq_self = |ty| infcx.can_eq(param_env, untransformed_self_ty, ty).is_ok();
            match ExplicitSelf::determine(self_arg_ty, can_eq_self) {
503
                ExplicitSelf::ByValue => "self".to_owned(),
504 505
                ExplicitSelf::ByReference(_, hir::Mutability::Not) => "&self".to_owned(),
                ExplicitSelf::ByReference(_, hir::Mutability::Mut) => "&mut self".to_owned(),
M
Mark Rousskov 已提交
506
                _ => format!("self: {}", self_arg_ty),
507 508
            }
        })
509 510
    };

511
    match (trait_m.fn_has_self_parameter, impl_m.fn_has_self_parameter) {
512 513 514 515
        (false, false) | (true, true) => {}

        (false, true) => {
            let self_descr = self_string(impl_m);
M
Mark Rousskov 已提交
516 517 518 519 520
            let mut err = struct_span_err!(
                tcx.sess,
                impl_m_span,
                E0185,
                "method `{}` has a `{}` declaration in the impl, but \
N
Niko Matsakis 已提交
521
                                            not in the trait",
M
Mark Rousskov 已提交
522 523 524
                trait_m.ident,
                self_descr
            );
525
            err.span_label(impl_m_span, format!("`{}` used in impl", self_descr));
526
            if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
E
Esteban Küber 已提交
527 528
                err.span_label(span, format!("trait method declared without `{}`", self_descr));
            } else {
M
Mark Rousskov 已提交
529
                err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
N
Niko Matsakis 已提交
530 531 532 533
            }
            err.emit();
            return Err(ErrorReported);
        }
534 535 536

        (true, false) => {
            let self_descr = self_string(trait_m);
M
Mark Rousskov 已提交
537 538 539 540 541
            let mut err = struct_span_err!(
                tcx.sess,
                impl_m_span,
                E0186,
                "method `{}` has a `{}` declaration in the trait, but \
N
Niko Matsakis 已提交
542
                                            not in the impl",
M
Mark Rousskov 已提交
543 544 545
                trait_m.ident,
                self_descr
            );
E
Esteban Küber 已提交
546
            err.span_label(impl_m_span, format!("expected `{}` in impl", self_descr));
547
            if let Some(span) = tcx.hir().span_if_local(trait_m.def_id) {
548
                err.span_label(span, format!("`{}` used in trait", self_descr));
549
            } else {
M
Mark Rousskov 已提交
550
                err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
N
Niko Matsakis 已提交
551 552 553 554 555 556 557 558 559
            }
            err.emit();
            return Err(ErrorReported);
        }
    }

    Ok(())
}

560
fn compare_number_of_generics<'tcx>(
561
    tcx: TyCtxt<'tcx>,
A
Andrew Xu 已提交
562
    impl_: &ty::AssocItem,
563
    _impl_span: Span,
A
Andrew Xu 已提交
564
    trait_: &ty::AssocItem,
V
varkor 已提交
565 566 567 568 569 570 571 572 573 574
    trait_span: Option<Span>,
) -> Result<(), ErrorReported> {
    let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts();
    let impl_own_counts = tcx.generics_of(impl_.def_id).own_counts();

    let matchings = [
        ("type", trait_own_counts.types, impl_own_counts.types),
        ("const", trait_own_counts.consts, impl_own_counts.consts),
    ];

575 576
    let item_kind = assoc_item_kind_str(impl_);

V
varkor 已提交
577 578 579 580 581
    let mut err_occurred = false;
    for &(kind, trait_count, impl_count) in &matchings {
        if impl_count != trait_count {
            err_occurred = true;

M
marmeladema 已提交
582
            let (trait_spans, impl_trait_spans) = if let Some(def_id) = trait_.def_id.as_local() {
583
                let trait_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
584 585 586
                let trait_item = tcx.hir().expect_trait_item(trait_hir_id);
                if trait_item.generics.params.is_empty() {
                    (Some(vec![trait_item.generics.span]), vec![])
587
                } else {
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
                    let arg_spans: Vec<Span> =
                        trait_item.generics.params.iter().map(|p| p.span).collect();
                    let impl_trait_spans: Vec<Span> = trait_item
                        .generics
                        .params
                        .iter()
                        .filter_map(|p| match p.kind {
                            GenericParamKind::Type {
                                synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
                                ..
                            } => Some(p.span),
                            _ => None,
                        })
                        .collect();
                    (Some(arg_spans), impl_trait_spans)
                }
            } else {
                (trait_span.map(|s| vec![s]), vec![])
            };
607

608
            let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_.def_id.expect_local());
609
            let impl_item = tcx.hir().expect_impl_item(impl_hir_id);
M
Mark Rousskov 已提交
610 611 612 613
            let impl_item_impl_trait_spans: Vec<Span> = impl_item
                .generics
                .params
                .iter()
614 615
                .filter_map(|p| match p.kind {
                    GenericParamKind::Type {
M
Mark Rousskov 已提交
616 617
                        synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
                        ..
618 619
                    } => Some(p.span),
                    _ => None,
M
Mark Rousskov 已提交
620 621
                })
                .collect();
622 623 624
            let spans = impl_item.generics.spans();
            let span = spans.primary_span();

V
varkor 已提交
625
            let mut err = tcx.sess.struct_span_err_with_code(
626
                spans,
V
varkor 已提交
627
                &format!(
628
                    "{} `{}` has {} {kind} parameter{} but its trait \
V
varkor 已提交
629
                     declaration has {} {kind} parameter{}",
630
                    item_kind,
V
varkor 已提交
631 632
                    trait_.ident,
                    impl_count,
633
                    pluralize!(impl_count),
V
varkor 已提交
634
                    trait_count,
635
                    pluralize!(trait_count),
V
varkor 已提交
636 637 638 639
                    kind = kind,
                ),
                DiagnosticId::Error("E0049".into()),
            );
640

V
varkor 已提交
641
            let mut suffix = None;
N
Niko Matsakis 已提交
642

643 644 645
            if let Some(spans) = trait_spans {
                let mut spans = spans.iter();
                if let Some(span) = spans.next() {
M
Mark Rousskov 已提交
646 647 648 649 650 651 652 653 654
                    err.span_label(
                        *span,
                        format!(
                            "expected {} {} parameter{}",
                            trait_count,
                            kind,
                            pluralize!(trait_count),
                        ),
                    );
655 656 657 658
                }
                for span in spans {
                    err.span_label(*span, "");
                }
V
varkor 已提交
659 660 661
            } else {
                suffix = Some(format!(", expected {}", trait_count));
            }
N
Niko Matsakis 已提交
662

663
            if let Some(span) = span {
M
Mark Rousskov 已提交
664 665 666 667 668 669 670
                err.span_label(
                    span,
                    format!(
                        "found {} {} parameter{}{}",
                        impl_count,
                        kind,
                        pluralize!(impl_count),
671
                        suffix.unwrap_or_else(String::new),
M
Mark Rousskov 已提交
672 673
                    ),
                );
674
            }
N
Niko Matsakis 已提交
675

676 677 678 679
            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");
            }

V
varkor 已提交
680 681
            err.emit();
        }
N
Niko Matsakis 已提交
682 683
    }

M
Mark Rousskov 已提交
684
    if err_occurred { Err(ErrorReported) } else { Ok(()) }
N
Niko Matsakis 已提交
685 686
}

687
fn compare_number_of_method_arguments<'tcx>(
688
    tcx: TyCtxt<'tcx>,
689 690 691 692 693
    impl_m: &ty::AssocItem,
    impl_m_span: Span,
    trait_m: &ty::AssocItem,
    trait_item_span: Option<Span>,
) -> Result<(), ErrorReported> {
694 695
    let impl_m_fty = tcx.fn_sig(impl_m.def_id);
    let trait_m_fty = tcx.fn_sig(trait_m.def_id);
696 697
    let trait_number_args = trait_m_fty.inputs().skip_binder().len();
    let impl_number_args = impl_m_fty.inputs().skip_binder().len();
698
    if trait_number_args != impl_number_args {
699
        let trait_span = if let Some(def_id) = trait_m.def_id.as_local() {
700
            let trait_id = tcx.hir().local_def_id_to_hir_id(def_id);
701
            match tcx.hir().expect_trait_item(trait_id).kind {
M
Mark Mansi 已提交
702
                TraitItemKind::Fn(ref trait_m_sig, _) => {
M
Mark Rousskov 已提交
703
                    let pos = if trait_number_args > 0 { trait_number_args - 1 } else { 0 };
704 705 706 707
                    if let Some(arg) = trait_m_sig.decl.inputs.get(pos) {
                        Some(if pos == 0 {
                            arg.span
                        } else {
M
Mark Rousskov 已提交
708 709 710 711 712
                            Span::new(
                                trait_m_sig.decl.inputs[0].span.lo(),
                                arg.span.hi(),
                                arg.span.ctxt(),
                            )
713
                        })
N
Niko Matsakis 已提交
714 715 716
                    } else {
                        trait_item_span
                    }
717
                }
N
Niko Matsakis 已提交
718
                _ => bug!("{:?} is not a method", impl_m),
719
            }
N
Niko Matsakis 已提交
720 721 722
        } else {
            trait_item_span
        };
723
        let impl_m_hir_id = tcx.hir().local_def_id_to_hir_id(impl_m.def_id.expect_local());
724
        let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind {
M
Mark Mansi 已提交
725
            ImplItemKind::Fn(ref impl_m_sig, _) => {
M
Mark Rousskov 已提交
726
                let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 };
727 728 729 730
                if let Some(arg) = impl_m_sig.decl.inputs.get(pos) {
                    if pos == 0 {
                        arg.span
                    } else {
M
Mark Rousskov 已提交
731 732 733 734 735
                        Span::new(
                            impl_m_sig.decl.inputs[0].span.lo(),
                            arg.span.hi(),
                            arg.span.ctxt(),
                        )
736
                    }
N
Niko Matsakis 已提交
737 738
                } else {
                    impl_m_span
739 740
                }
            }
N
Niko Matsakis 已提交
741 742
            _ => bug!("{:?} is not a method", impl_m),
        };
M
Mark Rousskov 已提交
743 744 745 746 747
        let mut err = struct_span_err!(
            tcx.sess,
            impl_span,
            E0050,
            "method `{}` has {} but the declaration in \
N
Niko Matsakis 已提交
748
                                        trait `{}` has {}",
M
Mark Rousskov 已提交
749 750 751 752 753
            trait_m.ident,
            potentially_plural_count(impl_number_args, "parameter"),
            tcx.def_path_str(trait_m.def_id),
            trait_number_args
        );
N
Niko Matsakis 已提交
754
        if let Some(trait_span) = trait_span {
M
Mark Rousskov 已提交
755 756 757 758 759 760 761
            err.span_label(
                trait_span,
                format!(
                    "trait requires {}",
                    potentially_plural_count(trait_number_args, "parameter")
                ),
            );
762
        } else {
M
Mark Rousskov 已提交
763
            err.note_trait_signature(trait_m.ident.to_string(), trait_m.signature(tcx));
764
        }
M
Mark Rousskov 已提交
765 766 767 768 769 770 771 772
        err.span_label(
            impl_span,
            format!(
                "expected {}, found {}",
                potentially_plural_count(trait_number_args, "parameter"),
                impl_number_args
            ),
        );
N
Niko Matsakis 已提交
773 774
        err.emit();
        return Err(ErrorReported);
775
    }
N
Niko Matsakis 已提交
776 777

    Ok(())
778
}
779

780
fn compare_synthetic_generics<'tcx>(
781
    tcx: TyCtxt<'tcx>,
782 783 784
    impl_m: &ty::AssocItem,
    trait_m: &ty::AssocItem,
) -> Result<(), ErrorReported> {
785
    // FIXME(chrisvittal) Clean up this function, list of FIXME items:
786
    //     1. Better messages for the span labels
787 788 789 790 791 792
    //     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.
    let mut error_found = false;
    let impl_m_generics = tcx.generics_of(impl_m.def_id);
    let trait_m_generics = tcx.generics_of(trait_m.def_id);
793 794
    let impl_m_type_params = impl_m_generics.params.iter().filter_map(|param| match param.kind {
        GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
795
        GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
V
varkor 已提交
796
    });
M
Mark Rousskov 已提交
797 798
    let trait_m_type_params = trait_m_generics.params.iter().filter_map(|param| match param.kind {
        GenericParamDefKind::Type { synthetic, .. } => Some((param.def_id, synthetic)),
799
        GenericParamDefKind::Lifetime | GenericParamDefKind::Const { .. } => None,
V
varkor 已提交
800
    });
M
Mark Rousskov 已提交
801 802
    for ((impl_def_id, impl_synthetic), (trait_def_id, trait_synthetic)) in
        impl_m_type_params.zip(trait_m_type_params)
803
    {
V
varkor 已提交
804
        if impl_synthetic != trait_synthetic {
805
            let impl_hir_id = tcx.hir().local_def_id_to_hir_id(impl_def_id.expect_local());
806
            let impl_span = tcx.hir().span(impl_hir_id);
V
varkor 已提交
807
            let trait_span = tcx.def_span(trait_def_id);
M
Mark Rousskov 已提交
808 809 810 811 812 813 814
            let mut err = struct_span_err!(
                tcx.sess,
                impl_span,
                E0643,
                "method `{}` has incompatible signature for trait",
                trait_m.ident
            );
815 816 817 818 819 820 821 822 823 824
            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
                (Some(hir::SyntheticTyParamKind::ImplTrait), None) => {
                    err.span_label(impl_span, "expected generic parameter, found `impl Trait`");
                    (|| {
                        // try taking the name from the trait impl
                        // FIXME: this is obviously suboptimal since the name can already be used
                        // as another generic argument
M
Mark Rousskov 已提交
825
                        let new_name = tcx.sess.source_map().span_to_snippet(trait_span).ok()?;
826 827
                        let trait_m = trait_m.def_id.as_local()?;
                        let trait_m = tcx.hir().trait_item(hir::TraitItemId { def_id: trait_m });
828

829 830
                        let impl_m = impl_m.def_id.as_local()?;
                        let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
831 832 833

                        // in case there are no generics, take the spot between the function name
                        // and the opening paren of the argument list
M
Mark Rousskov 已提交
834 835
                        let new_generics_span =
                            tcx.sess.source_map().generate_fn_name_span(impl_span)?.shrink_to_hi();
836
                        // in case there are generics, just replace them
M
Mark Rousskov 已提交
837 838
                        let generics_span =
                            impl_m.generics.span.substitute_dummy(new_generics_span);
839
                        // replace with the generics from the trait
M
Mark Rousskov 已提交
840 841
                        let new_generics =
                            tcx.sess.source_map().span_to_snippet(trait_m.generics.span).ok()?;
842

843
                        err.multipart_suggestion(
844 845 846 847 848 849 850 851 852
                            "try changing the `impl Trait` argument to a generic parameter",
                            vec![
                                // replace `impl Trait` with `T`
                                (impl_span, new_name),
                                // 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),
                            ],
853
                            Applicability::MaybeIncorrect,
854 855 856
                        );
                        Some(())
                    })();
M
Mark Rousskov 已提交
857
                }
858 859 860 861 862
                // The case where the trait method uses `impl Trait`, but the impl method uses
                // explicit generics.
                (None, Some(hir::SyntheticTyParamKind::ImplTrait)) => {
                    err.span_label(impl_span, "expected `impl Trait`, found generic parameter");
                    (|| {
863 864
                        let impl_m = impl_m.def_id.as_local()?;
                        let impl_m = tcx.hir().impl_item(hir::ImplItemId { def_id: impl_m });
865
                        let input_tys = match impl_m.kind {
M
Mark Mansi 已提交
866
                            hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs,
867 868 869
                            _ => unreachable!(),
                        };
                        struct Visitor(Option<Span>, hir::def_id::DefId);
870
                        impl<'v> intravisit::Visitor<'v> for Visitor {
C
Camille GILLOT 已提交
871
                            fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
872
                                intravisit::walk_ty(self, ty);
M
Mark Rousskov 已提交
873 874
                                if let hir::TyKind::Path(hir::QPath::Resolved(None, ref path)) =
                                    ty.kind
875
                                {
876
                                    if let Res::Def(DefKind::TyParam, def_id) = path.res {
877 878
                                        if def_id == self.1 {
                                            self.0 = Some(ty.span);
879
                                        }
880
                                    }
881 882
                                }
                            }
883
                            type Map = intravisit::ErasedMap<'v>;
884 885
                            fn nested_visit_map(
                                &mut self,
886
                            ) -> intravisit::NestedVisitorMap<Self::Map>
M
Mark Rousskov 已提交
887
                            {
888
                                intravisit::NestedVisitorMap::None
889 890 891 892
                            }
                        }
                        let mut visitor = Visitor(None, impl_def_id);
                        for ty in input_tys {
893
                            intravisit::Visitor::visit_ty(&mut visitor, ty);
894 895 896
                        }
                        let span = visitor.0?;

M
Mark Rousskov 已提交
897 898
                        let bounds =
                            impl_m.generics.params.iter().find_map(|param| match param.kind {
V
varkor 已提交
899
                                GenericParamKind::Lifetime { .. } => None,
M
Mark Rousskov 已提交
900
                                GenericParamKind::Type { .. } | GenericParamKind::Const { .. } => {
V
varkor 已提交
901
                                    if param.hir_id == impl_hir_id {
V
varkor 已提交
902
                                        Some(&param.bounds)
903 904 905
                                    } else {
                                        None
                                    }
V
varkor 已提交
906
                                }
M
Mark Rousskov 已提交
907
                            })?;
V
varkor 已提交
908
                        let bounds = bounds.first()?.span().to(bounds.last()?.span());
M
Mark Rousskov 已提交
909
                        let bounds = tcx.sess.source_map().span_to_snippet(bounds).ok()?;
910

911
                        err.multipart_suggestion(
912 913 914 915 916 917 918
                            "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`
                                (span, format!("impl {}", bounds)),
                            ],
919
                            Applicability::MaybeIncorrect,
920 921 922
                        );
                        Some(())
                    })();
M
Mark Rousskov 已提交
923
                }
924 925
                _ => unreachable!(),
            }
926 927 928 929
            err.emit();
            error_found = true;
        }
    }
M
Mark Rousskov 已提交
930
    if error_found { Err(ErrorReported) } else { Ok(()) }
931 932
}

933
crate fn compare_const_impl<'tcx>(
934
    tcx: TyCtxt<'tcx>,
935 936 937 938 939
    impl_c: &ty::AssocItem,
    impl_c_span: Span,
    trait_c: &ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
) {
940
    debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref);
941

942
    tcx.infer_ctxt().enter(|infcx| {
K
kyren 已提交
943
        let param_env = tcx.param_env(impl_c.def_id);
944
        let inh = Inherited::new(infcx, impl_c.def_id.expect_local());
945
        let infcx = &inh.infcx;
946 947 948 949 950 951

        // 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...
952
        let trait_to_impl_substs = impl_trait_ref.substs;
953 954 955

        // Create a parameter environment that represents the implementation's
        // method.
956
        let impl_c_hir_id = tcx.hir().local_def_id_to_hir_id(impl_c.def_id.expect_local());
957

N
Niko Matsakis 已提交
958
        // Compute placeholder form of impl and trait const tys.
959 960
        let impl_ty = tcx.type_of(impl_c.def_id);
        let trait_ty = tcx.type_of(trait_c.def_id).subst(tcx, trait_to_impl_substs);
961 962 963 964 965
        let mut cause = ObligationCause::new(
            impl_c_span,
            impl_c_hir_id,
            ObligationCauseCode::CompareImplConstObligation,
        );
966

967
        // There is no "body" here, so just pass dummy id.
M
Mark Rousskov 已提交
968
        let impl_ty =
B
Bastian Kauschke 已提交
969
            inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, impl_ty);
970

971
        debug!("compare_const_impl: impl_ty={:?}", impl_ty);
972

M
Mark Rousskov 已提交
973
        let trait_ty =
B
Bastian Kauschke 已提交
974
            inh.normalize_associated_types_in(impl_c_span, impl_c_hir_id, param_env, trait_ty);
975

976
        debug!("compare_const_impl: trait_ty={:?}", trait_ty);
977

M
Mark Rousskov 已提交
978 979 980 981
        let err = infcx
            .at(&cause, param_env)
            .sup(trait_ty, impl_ty)
            .map(|ok| inh.register_infer_ok_obligations(ok));
982

983
        if let Err(terr) = err {
M
Mark Rousskov 已提交
984 985 986 987
            debug!(
                "checking associated const for compatibility: impl ty {:?}, trait ty {:?}",
                impl_ty, trait_ty
            );
T
trixnz 已提交
988 989

            // Locate the Span containing just the type of the offending impl
990
            match tcx.hir().expect_impl_item(impl_c_hir_id).kind {
991
                ImplItemKind::Const(ref ty, _) => cause.make_mut().span = ty.span,
992
                _ => bug!("{:?} is not a impl const", impl_c),
T
trixnz 已提交
993 994
            }

M
Mark Rousskov 已提交
995 996 997 998 999
            let mut diag = struct_span_err!(
                tcx.sess,
                cause.span,
                E0326,
                "implemented const `{}` has an incompatible type for \
1000
                                             trait",
M
Mark Rousskov 已提交
1001 1002
                trait_c.ident
            );
T
trixnz 已提交
1003

1004
            let trait_c_hir_id =
1005
                trait_c.def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id));
1006
            let trait_c_span = trait_c_hir_id.map(|trait_c_hir_id| {
1007
                // Add a label to the Span containing just the type of the const
1008
                match tcx.hir().expect_trait_item(trait_c_hir_id).kind {
1009 1010 1011 1012
                    TraitItemKind::Const(ref ty, _) => ty.span,
                    _ => bug!("{:?} is not a trait const", trait_c),
                }
            });
T
trixnz 已提交
1013

M
Mark Rousskov 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
            infcx.note_type_err(
                &mut diag,
                &cause,
                trait_c_span.map(|span| (span, "type in trait".to_owned())),
                Some(infer::ValuePairs::Types(ExpectedFound {
                    expected: trait_ty,
                    found: impl_ty,
                })),
                &terr,
            );
1024
            diag.emit();
1025
        }
1026

1027 1028 1029
        // Check that all obligations are satisfied by the implementation's
        // version.
        if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
1030
            infcx.report_fulfillment_errors(errors, None, false);
1031 1032 1033
            return;
        }

L
ljedrz 已提交
1034 1035
        let fcx = FnCtxt::new(&inh, param_env, impl_c_hir_id);
        fcx.regionck_item(impl_c_hir_id, impl_c_span, &[]);
1036
    });
1037
}
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

crate fn compare_ty_impl<'tcx>(
    tcx: TyCtxt<'tcx>,
    impl_ty: &ty::AssocItem,
    impl_ty_span: Span,
    trait_ty: &ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
    trait_item_span: Option<Span>,
) {
    debug!("compare_impl_type(impl_trait_ref={:?})", impl_trait_ref);

    let _: Result<(), ErrorReported> = (|| {
        compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;

1052 1053
        compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)?;

1054
        check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
1055 1056 1057 1058 1059
    })();
}

/// The equivalent of [compare_predicate_entailment], but for associated types
/// instead of associated functions.
1060
fn compare_type_predicate_entailment<'tcx>(
1061 1062 1063 1064 1065 1066 1067
    tcx: TyCtxt<'tcx>,
    impl_ty: &ty::AssocItem,
    impl_ty_span: Span,
    trait_ty: &ty::AssocItem,
    impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorReported> {
    let impl_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
M
Mark Rousskov 已提交
1068 1069
    let trait_to_impl_substs =
        impl_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094

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

    check_region_bounds_on_impl_item(
        tcx,
        impl_ty_span,
        impl_ty,
        trait_ty,
        &trait_ty_generics,
        &impl_ty_generics,
    )?;

    let impl_ty_own_bounds = impl_ty_predicates.instantiate_own(tcx, impl_substs);

    if impl_ty_own_bounds.is_empty() {
        // Nothing to check.
        return Ok(());
    }

    // This `HirId` should be used for the `body_id` field on each
    // `ObligationCause` (and the `FnCtxt`). This is what
    // `regionck_item` expects.
1095
    let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1096 1097 1098 1099
    let cause = ObligationCause::new(
        impl_ty_span,
        impl_ty_hir_id,
        ObligationCauseCode::CompareImplTypeObligation {
1100 1101 1102 1103
            item_name: impl_ty.ident.name,
            impl_item_def_id: impl_ty.def_id,
            trait_item_def_id: trait_ty.def_id,
        },
1104
    );
1105 1106 1107 1108 1109 1110 1111

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

    // 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);
M
Mark Rousskov 已提交
1112 1113 1114
    hybrid_preds
        .predicates
        .extend(trait_ty_predicates.instantiate_own(tcx, trait_to_impl_substs).predicates);
1115 1116 1117 1118

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

    let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
1119 1120
    let param_env =
        ty::ParamEnv::new(tcx.intern_predicates(&hybrid_preds.predicates), Reveal::UserFacing);
M
Mark Rousskov 已提交
1121 1122 1123 1124 1125
    let param_env = traits::normalize_param_env_or_error(
        tcx,
        impl_ty.def_id,
        param_env,
        normalize_cause.clone(),
1126 1127
    );
    tcx.infer_ctxt().enter(|infcx| {
1128
        let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
1129 1130
        let infcx = &inh.infcx;

M
Mark Rousskov 已提交
1131
        debug!("compare_type_predicate_entailment: caller_bounds={:?}", param_env.caller_bounds());
1132 1133 1134 1135 1136

        let mut selcx = traits::SelectionContext::new(&infcx);

        for predicate in impl_ty_own_bounds.predicates {
            let traits::Normalized { value: predicate, obligations } =
B
Bastian Kauschke 已提交
1137
                traits::normalize(&mut selcx, param_env, normalize_cause.clone(), predicate);
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158

            inh.register_predicates(obligations);
            inh.register_predicate(traits::Obligation::new(cause.clone(), param_env, predicate));
        }

        // Check that all obligations are satisfied by the implementation's
        // version.
        if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
            infcx.report_fulfillment_errors(errors, None, false);
            return Err(ErrorReported);
        }

        // Finally, resolve all regions. This catches wily misuses of
        // lifetime parameters.
        let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
        fcx.regionck_item(impl_ty_hir_id, impl_ty_span, &[]);

        Ok(())
    })
}

1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
/// 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; }
///
/// We are able to normalize `<T as X>::U` to `S`, and so when we check the
/// 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.
1172
pub fn check_type_bounds<'tcx>(
1173 1174 1175 1176 1177 1178
    tcx: TyCtxt<'tcx>,
    trait_ty: &ty::AssocItem,
    impl_ty: &ty::AssocItem,
    impl_ty_span: Span,
    impl_trait_ref: ty::TraitRef<'tcx>,
) -> Result<(), ErrorReported> {
1179 1180 1181 1182 1183 1184 1185 1186 1187
    // Given
    //
    // impl<A, B> Foo<u32> for (A, B) {
    //     type Bar<C> =...
    // }
    //
    // - `impl_substs` would be `[A, B, C]`
    // - `rebased_substs` would be `[(A, B), u32, C]`, combining the substs from
    //    the *trait* with the generic associated type parameters.
1188 1189 1190
    let impl_ty_substs = InternalSubsts::identity_for_item(tcx, impl_ty.def_id);
    let rebased_substs =
        impl_ty_substs.rebase_onto(tcx, impl_ty.container.id(), impl_trait_ref.substs);
1191 1192
    let impl_ty_value = tcx.type_of(impl_ty.def_id);

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    let param_env = tcx.param_env(impl_ty.def_id);

    // 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.
1204
    let normalize_param_env = {
1205
        let mut predicates = param_env.caller_bounds().iter().collect::<Vec<_>>();
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
        match impl_ty_value.kind() {
            ty::Projection(proj)
                if proj.item_def_id == trait_ty.def_id && proj.substs == rebased_substs =>
            {
                // 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(
                ty::Binder::dummy(ty::ProjectionPredicate {
                    projection_ty: ty::ProjectionTy {
                        item_def_id: trait_ty.def_id,
                        substs: rebased_substs,
                    },
                    ty: impl_ty_value,
                })
                .to_predicate(tcx),
            ),
        };
1227
        ty::ParamEnv::new(tcx.intern_predicates(&predicates), Reveal::UserFacing)
1228 1229
    };

1230 1231 1232 1233 1234
    tcx.infer_ctxt().enter(move |infcx| {
        let inh = Inherited::new(infcx, impl_ty.def_id.expect_local());
        let infcx = &inh.infcx;
        let mut selcx = traits::SelectionContext::new(&infcx);

1235
        let impl_ty_hir_id = tcx.hir().local_def_id_to_hir_id(impl_ty.def_id.expect_local());
1236
        let normalize_cause = traits::ObligationCause::misc(impl_ty_span, impl_ty_hir_id);
M
Matthew Jasper 已提交
1237 1238 1239 1240 1241 1242 1243
        let mk_cause = |span| {
            ObligationCause::new(
                impl_ty_span,
                impl_ty_hir_id,
                ObligationCauseCode::BindingObligation(trait_ty.def_id, span),
            )
        };
1244

1245 1246 1247 1248
        let obligations = tcx
            .explicit_item_bounds(trait_ty.def_id)
            .iter()
            .map(|&(bound, span)| {
M
Matthew Jasper 已提交
1249
                let concrete_ty_bound = bound.subst(tcx, rebased_substs);
1250
                debug!("check_type_bounds: concrete_ty_bound = {:?}", concrete_ty_bound);
1251

1252 1253 1254 1255 1256
                traits::Obligation::new(mk_cause(span), param_env, concrete_ty_bound)
            })
            .collect();
        debug!("check_type_bounds: item_bounds={:?}", obligations);

M
Matthew Jasper 已提交
1257
        for mut obligation in util::elaborate_obligations(tcx, obligations) {
1258 1259
            let traits::Normalized { value: normalized_predicate, obligations } = traits::normalize(
                &mut selcx,
1260
                normalize_param_env,
1261
                normalize_cause.clone(),
B
Bastian Kauschke 已提交
1262
                obligation.predicate,
1263 1264
            );
            debug!("compare_projection_bounds: normalized predicate = {:?}", normalized_predicate);
M
Matthew Jasper 已提交
1265
            obligation.predicate = normalized_predicate;
1266

M
Matthew Jasper 已提交
1267
            inh.register_predicates(obligations);
1268
            inh.register_predicate(obligation);
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
        }

        // Check that all obligations are satisfied by the implementation's
        // version.
        if let Err(ref errors) = inh.fulfillment_cx.borrow_mut().select_all_or_error(&infcx) {
            infcx.report_fulfillment_errors(errors, None, false);
            return Err(ErrorReported);
        }

        // Finally, resolve all regions. This catches wily misuses of
        // lifetime parameters.
        let fcx = FnCtxt::new(&inh, param_env, impl_ty_hir_id);
1281 1282 1283 1284 1285
        let implied_bounds = match impl_ty.container {
            ty::TraitContainer(_) => vec![],
            ty::ImplContainer(def_id) => fcx.impl_implied_bounds(def_id, impl_ty_span),
        };
        fcx.regionck_item(impl_ty_hir_id, impl_ty_span, &implied_bounds);
1286 1287 1288 1289 1290

        Ok(())
    })
}

1291 1292 1293
fn assoc_item_kind_str(impl_item: &ty::AssocItem) -> &'static str {
    match impl_item.kind {
        ty::AssocKind::Const => "const",
1294
        ty::AssocKind::Fn => "method",
M
Matthew Jasper 已提交
1295
        ty::AssocKind::Type => "type",
1296 1297
    }
}