1 use crate::check
::{FnCtxt, Inherited}
;
2 use crate::constrained_generic_params
::{identify_constrained_generic_params, Parameter}
;
5 use rustc_data_structures
::fx
::{FxHashMap, FxHashSet}
;
6 use rustc_errors
::{struct_span_err, Applicability, DiagnosticBuilder}
;
8 use rustc_hir
::def_id
::{DefId, LocalDefId}
;
9 use rustc_hir
::intravisit
as hir_visit
;
10 use rustc_hir
::intravisit
::Visitor
;
11 use rustc_hir
::itemlikevisit
::ParItemLikeVisitor
;
12 use rustc_hir
::lang_items
::LangItem
;
13 use rustc_hir
::ItemKind
;
14 use rustc_middle
::hir
::map
as hir_map
;
15 use rustc_middle
::ty
::subst
::{GenericArgKind, InternalSubsts, Subst}
;
16 use rustc_middle
::ty
::trait_def
::TraitSpecializationKind
;
17 use rustc_middle
::ty
::{
18 self, AdtKind
, GenericParamDefKind
, ToPredicate
, Ty
, TyCtxt
, TypeFoldable
, WithConstness
,
20 use rustc_session
::parse
::feature_err
;
21 use rustc_span
::symbol
::{sym, Ident, Symbol}
;
23 use rustc_trait_selection
::opaque_types
::may_define_opaque_type
;
24 use rustc_trait_selection
::traits
::query
::evaluate_obligation
::InferCtxtExt
;
25 use rustc_trait_selection
::traits
::{self, ObligationCause, ObligationCauseCode, WellFormedLoc}
;
27 use std
::convert
::TryInto
;
29 use std
::ops
::ControlFlow
;
31 /// Helper type of a temporary returned by `.for_item(...)`.
32 /// This is necessary because we can't write the following bound:
35 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
37 struct CheckWfFcxBuilder
<'tcx
> {
38 inherited
: super::InheritedBuilder
<'tcx
>,
41 param_env
: ty
::ParamEnv
<'tcx
>,
44 impl<'tcx
> CheckWfFcxBuilder
<'tcx
> {
45 fn with_fcx
<F
>(&mut self, f
: F
)
47 F
: for<'b
> FnOnce(&FnCtxt
<'b
, 'tcx
>) -> Vec
<Ty
<'tcx
>>,
51 let param_env
= self.param_env
;
52 self.inherited
.enter(|inh
| {
53 let fcx
= FnCtxt
::new(&inh
, param_env
, id
);
54 if !inh
.tcx
.features().trivial_bounds
{
55 // As predicates are cached rather than obligations, this
56 // needs to be called first so that they are checked with an
58 check_false_global_bounds(&fcx
, span
, id
);
61 fcx
.select_all_obligations_or_error();
62 fcx
.regionck_item(id
, span
, &wf_tys
);
67 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
68 /// well-formed, meaning that they do not require any constraints not declared in the struct
69 /// definition itself. For example, this definition would be illegal:
72 /// struct Ref<'a, T> { x: &'a T }
75 /// because the type did not declare that `T:'a`.
77 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
78 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
80 pub fn check_item_well_formed(tcx
: TyCtxt
<'_
>, def_id
: LocalDefId
) {
81 let hir_id
= tcx
.hir().local_def_id_to_hir_id(def_id
);
82 let item
= tcx
.hir().expect_item(hir_id
);
85 "check_item_well_formed(it.def_id={:?}, it.name={})",
87 tcx
.def_path_str(def_id
.to_def_id())
91 // Right now we check that every default trait implementation
92 // has an implementation of itself. Basically, a case like:
94 // impl Trait for T {}
96 // has a requirement of `T: Trait` which was required for default
97 // method implementations. Although this could be improved now that
98 // there's a better infrastructure in place for this, it's being left
99 // for a follow-up work.
101 // Since there's such a requirement, we need to check *just* positive
102 // implementations, otherwise things like:
104 // impl !Send for T {}
106 // won't be allowed unless there's an *explicit* implementation of `Send`
108 hir
::ItemKind
::Impl(ref impl_
) => {
110 .impl_trait_ref(item
.def_id
)
111 .map_or(false, |trait_ref
| tcx
.trait_is_auto(trait_ref
.def_id
));
112 if let (hir
::Defaultness
::Default { .. }
, true) = (impl_
.defaultness
, is_auto
) {
113 let sp
= impl_
.of_trait
.as_ref().map_or(item
.span
, |t
| t
.path
.span
);
115 tcx
.sess
.struct_span_err(sp
, "impls of auto traits cannot be default");
116 err
.span_labels(impl_
.defaultness_span
, "default because of this");
117 err
.span_label(sp
, "auto trait");
120 // We match on both `ty::ImplPolarity` and `ast::ImplPolarity` just to get the `!` span.
121 match (tcx
.impl_polarity(def_id
), impl_
.polarity
) {
122 (ty
::ImplPolarity
::Positive
, _
) => {
123 check_impl(tcx
, item
, impl_
.self_ty
, &impl_
.of_trait
);
125 (ty
::ImplPolarity
::Negative
, ast
::ImplPolarity
::Negative(span
)) => {
126 // FIXME(#27579): what amount of WF checking do we need for neg impls?
127 if let hir
::Defaultness
::Default { .. }
= impl_
.defaultness
{
128 let mut spans
= vec
![span
];
129 spans
.extend(impl_
.defaultness_span
);
134 "negative impls cannot be default impls"
139 (ty
::ImplPolarity
::Reservation
, _
) => {
140 // FIXME: what amount of WF checking do we need for reservation impls?
145 hir
::ItemKind
::Fn(ref sig
, ..) => {
146 check_item_fn(tcx
, item
.hir_id(), item
.ident
, item
.span
, sig
.decl
);
148 hir
::ItemKind
::Static(ref ty
, ..) => {
149 check_item_type(tcx
, item
.hir_id(), ty
.span
, false);
151 hir
::ItemKind
::Const(ref ty
, ..) => {
152 check_item_type(tcx
, item
.hir_id(), ty
.span
, false);
154 hir
::ItemKind
::ForeignMod { items, .. }
=> {
155 for it
in items
.iter() {
156 let it
= tcx
.hir().foreign_item(it
.id
);
158 hir
::ForeignItemKind
::Fn(ref decl
, ..) => {
159 check_item_fn(tcx
, it
.hir_id(), it
.ident
, it
.span
, decl
)
161 hir
::ForeignItemKind
::Static(ref ty
, ..) => {
162 check_item_type(tcx
, it
.hir_id(), ty
.span
, true)
164 hir
::ForeignItemKind
::Type
=> (),
168 hir
::ItemKind
::Struct(ref struct_def
, ref ast_generics
) => {
169 check_type_defn(tcx
, item
, false, |fcx
| vec
![fcx
.non_enum_variant(struct_def
)]);
171 check_variances_for_type_defn(tcx
, item
, ast_generics
);
173 hir
::ItemKind
::Union(ref struct_def
, ref ast_generics
) => {
174 check_type_defn(tcx
, item
, true, |fcx
| vec
![fcx
.non_enum_variant(struct_def
)]);
176 check_variances_for_type_defn(tcx
, item
, ast_generics
);
178 hir
::ItemKind
::Enum(ref enum_def
, ref ast_generics
) => {
179 check_type_defn(tcx
, item
, true, |fcx
| fcx
.enum_variants(enum_def
));
181 check_variances_for_type_defn(tcx
, item
, ast_generics
);
183 hir
::ItemKind
::Trait(..) => {
184 check_trait(tcx
, item
);
186 hir
::ItemKind
::TraitAlias(..) => {
187 check_trait(tcx
, item
);
193 pub fn check_trait_item(tcx
: TyCtxt
<'_
>, def_id
: LocalDefId
) {
194 let hir_id
= tcx
.hir().local_def_id_to_hir_id(def_id
);
195 let trait_item
= tcx
.hir().expect_trait_item(hir_id
);
197 let (method_sig
, span
) = match trait_item
.kind
{
198 hir
::TraitItemKind
::Fn(ref sig
, _
) => (Some(sig
), trait_item
.span
),
199 hir
::TraitItemKind
::Type(_bounds
, Some(ty
)) => (None
, ty
.span
),
200 _
=> (None
, trait_item
.span
),
202 check_object_unsafe_self_trait_by_name(tcx
, &trait_item
);
203 check_associated_item(tcx
, trait_item
.hir_id(), span
, method_sig
);
206 fn could_be_self(trait_def_id
: LocalDefId
, ty
: &hir
::Ty
<'_
>) -> bool
{
208 hir
::TyKind
::TraitObject([trait_ref
], ..) => match trait_ref
.trait_ref
.path
.segments
{
209 [s
] => s
.res
.and_then(|r
| r
.opt_def_id()) == Some(trait_def_id
.to_def_id()),
216 /// Detect when an object unsafe trait is referring to itself in one of its associated items.
217 /// When this is done, suggest using `Self` instead.
218 fn check_object_unsafe_self_trait_by_name(tcx
: TyCtxt
<'_
>, item
: &hir
::TraitItem
<'_
>) {
219 let (trait_name
, trait_def_id
) = match tcx
.hir().get(tcx
.hir().get_parent_item(item
.hir_id())) {
220 hir
::Node
::Item(item
) => match item
.kind
{
221 hir
::ItemKind
::Trait(..) => (item
.ident
, item
.def_id
),
226 let mut trait_should_be_self
= vec
![];
228 hir
::TraitItemKind
::Const(ty
, _
) | hir
::TraitItemKind
::Type(_
, Some(ty
))
229 if could_be_self(trait_def_id
, ty
) =>
231 trait_should_be_self
.push(ty
.span
)
233 hir
::TraitItemKind
::Fn(sig
, _
) => {
234 for ty
in sig
.decl
.inputs
{
235 if could_be_self(trait_def_id
, ty
) {
236 trait_should_be_self
.push(ty
.span
);
239 match sig
.decl
.output
{
240 hir
::FnRetTy
::Return(ty
) if could_be_self(trait_def_id
, ty
) => {
241 trait_should_be_self
.push(ty
.span
);
248 if !trait_should_be_self
.is_empty() {
249 if tcx
.object_safety_violations(trait_def_id
).is_empty() {
252 let sugg
= trait_should_be_self
.iter().map(|span
| (*span
, "Self".to_string())).collect();
255 trait_should_be_self
,
256 "associated item referring to unboxed trait object for its own trait",
258 .span_label(trait_name
.span
, "in this trait")
259 .multipart_suggestion(
260 "you might have meant to use `Self` to refer to the implementing type",
262 Applicability
::MachineApplicable
,
268 pub fn check_impl_item(tcx
: TyCtxt
<'_
>, def_id
: LocalDefId
) {
269 let hir_id
= tcx
.hir().local_def_id_to_hir_id(def_id
);
270 let impl_item
= tcx
.hir().expect_impl_item(hir_id
);
272 let (method_sig
, span
) = match impl_item
.kind
{
273 hir
::ImplItemKind
::Fn(ref sig
, _
) => (Some(sig
), impl_item
.span
),
274 hir
::ImplItemKind
::TyAlias(ty
) => (None
, ty
.span
),
275 _
=> (None
, impl_item
.span
),
278 check_associated_item(tcx
, impl_item
.hir_id(), span
, method_sig
);
281 fn check_param_wf(tcx
: TyCtxt
<'_
>, param
: &hir
::GenericParam
<'_
>) {
283 // We currently only check wf of const params here.
284 hir
::GenericParamKind
::Lifetime { .. }
| hir
::GenericParamKind
::Type { .. }
=> (),
286 // Const parameters are well formed if their type is structural match.
287 // FIXME(const_generics_defaults): we also need to check that the `default` is wf.
288 hir
::GenericParamKind
::Const { ty: hir_ty, default: _ }
=> {
289 let ty
= tcx
.type_of(tcx
.hir().local_def_id(param
.hir_id
));
292 let mut is_ptr
= true;
293 let err
= if tcx
.features().adt_const_params
{
294 match ty
.peel_refs().kind() {
295 ty
::FnPtr(_
) => Some("function pointers"),
296 ty
::RawPtr(_
) => Some("raw pointers"),
301 ty
::Bool
| ty
::Char
| ty
::Int(_
) | ty
::Uint(_
) | ty
::Error(_
) => None
,
302 ty
::FnPtr(_
) => Some("function pointers"),
303 ty
::RawPtr(_
) => Some("raw pointers"),
306 err_ty_str
= format
!("`{}`", ty
);
307 Some(err_ty_str
.as_str())
311 if let Some(unsupported_type
) = err
{
316 "using {} as const generic parameters is forbidden",
321 let mut err
= tcx
.sess
.struct_span_err(
324 "{} is forbidden as the type of a const generic parameter",
328 err
.note("the only supported types are integers, `bool` and `char`");
329 if tcx
.sess
.is_nightly_build() {
331 "more complex types are supported with `#![feature(adt_const_params)]`",
338 if traits
::search_for_structural_match_violation(param
.hir_id
, param
.span
, tcx
, ty
)
341 // We use the same error code in both branches, because this is really the same
342 // issue: we just special-case the message for type parameters to make it
344 if let ty
::Param(_
) = ty
.peel_refs().kind() {
345 // Const parameters may not have type parameters as their types,
346 // because we cannot be sure that the type parameter derives `PartialEq`
347 // and `Eq` (just implementing them is not enough for `structural_match`).
352 "`{}` is not guaranteed to `#[derive(PartialEq, Eq)]`, so may not be \
353 used as the type of a const parameter",
358 format
!("`{}` may not derive both `PartialEq` and `Eq`", ty
),
361 "it is not currently possible to use a type parameter as the type of a \
370 "`{}` must be annotated with `#[derive(PartialEq, Eq)]` to be used as \
371 the type of a const parameter",
376 format
!("`{}` doesn't derive both `PartialEq` and `Eq`", ty
),
385 #[tracing::instrument(level = "debug", skip(tcx, span, sig_if_method))]
386 fn check_associated_item(
390 sig_if_method
: Option
<&hir
::FnSig
<'_
>>,
392 let code
= ObligationCauseCode
::WellFormed(Some(WellFormedLoc
::Ty(item_id
.expect_owner())));
393 for_id(tcx
, item_id
, span
).with_fcx(|fcx
| {
394 let item
= fcx
.tcx
.associated_item(fcx
.tcx
.hir().local_def_id(item_id
));
396 let (mut implied_bounds
, self_ty
) = match item
.container
{
397 ty
::TraitContainer(_
) => (vec
![], fcx
.tcx
.types
.self_param
),
398 ty
::ImplContainer(def_id
) => {
399 (fcx
.impl_implied_bounds(def_id
, span
), fcx
.tcx
.type_of(def_id
))
404 ty
::AssocKind
::Const
=> {
405 let ty
= fcx
.tcx
.type_of(item
.def_id
);
406 let ty
= fcx
.normalize_associated_types_in_wf(
409 WellFormedLoc
::Ty(item_id
.expect_owner()),
411 fcx
.register_wf_obligation(ty
.into(), span
, code
.clone());
413 ty
::AssocKind
::Fn
=> {
414 let sig
= fcx
.tcx
.fn_sig(item
.def_id
);
415 let hir_sig
= sig_if_method
.expect("bad signature for method");
424 check_method_receiver(fcx
, hir_sig
, &item
, self_ty
);
426 ty
::AssocKind
::Type
=> {
427 if let ty
::AssocItemContainer
::TraitContainer(_
) = item
.container
{
428 check_associated_type_bounds(fcx
, item
, span
)
430 if item
.defaultness
.has_value() {
431 let ty
= fcx
.tcx
.type_of(item
.def_id
);
432 let ty
= fcx
.normalize_associated_types_in_wf(
435 WellFormedLoc
::Ty(item_id
.expect_owner()),
437 fcx
.register_wf_obligation(ty
.into(), span
, code
.clone());
446 fn for_item
<'tcx
>(tcx
: TyCtxt
<'tcx
>, item
: &hir
::Item
<'_
>) -> CheckWfFcxBuilder
<'tcx
> {
447 for_id(tcx
, item
.hir_id(), item
.span
)
450 fn for_id(tcx
: TyCtxt
<'_
>, id
: hir
::HirId
, span
: Span
) -> CheckWfFcxBuilder
<'_
> {
451 let def_id
= tcx
.hir().local_def_id(id
);
453 inherited
: Inherited
::build(tcx
, def_id
),
456 param_env
: tcx
.param_env(def_id
),
460 fn item_adt_kind(kind
: &ItemKind
<'_
>) -> Option
<AdtKind
> {
462 ItemKind
::Struct(..) => Some(AdtKind
::Struct
),
463 ItemKind
::Union(..) => Some(AdtKind
::Union
),
464 ItemKind
::Enum(..) => Some(AdtKind
::Enum
),
469 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
470 fn check_type_defn
<'tcx
, F
>(
472 item
: &hir
::Item
<'tcx
>,
474 mut lookup_fields
: F
,
476 F
: for<'fcx
> FnMut(&FnCtxt
<'fcx
, 'tcx
>) -> Vec
<AdtVariant
<'tcx
>>,
478 for_item(tcx
, item
).with_fcx(|fcx
| {
479 let variants
= lookup_fields(fcx
);
480 let packed
= tcx
.adt_def(item
.def_id
).repr
.packed();
482 for variant
in &variants
{
483 // For DST, or when drop needs to copy things around, all
484 // intermediate types must be sized.
485 let needs_drop_copy
= || {
487 let ty
= variant
.fields
.last().unwrap().ty
;
488 let ty
= tcx
.erase_regions(ty
);
489 if ty
.needs_infer() {
491 .delay_span_bug(item
.span
, &format
!("inference variables in {:?}", ty
));
492 // Just treat unresolved type expression as if it needs drop.
495 ty
.needs_drop(tcx
, tcx
.param_env(item
.def_id
))
499 let all_sized
= all_sized
|| variant
.fields
.is_empty() || needs_drop_copy();
500 let unsized_len
= if all_sized { 0 }
else { 1 }
;
502 variant
.fields
[..variant
.fields
.len() - unsized_len
].iter().enumerate()
504 let last
= idx
== variant
.fields
.len() - 1;
507 tcx
.require_lang_item(LangItem
::Sized
, None
),
508 traits
::ObligationCause
::new(
512 adt_kind
: match item_adt_kind(&item
.kind
) {
523 // All field types must be well-formed.
524 for field
in &variant
.fields
{
525 fcx
.register_wf_obligation(
528 ObligationCauseCode
::WellFormed(Some(WellFormedLoc
::Ty(field
.def_id
))),
532 // Explicit `enum` discriminant values must const-evaluate successfully.
533 if let Some(discr_def_id
) = variant
.explicit_discr
{
534 let discr_substs
= InternalSubsts
::identity_for_item(tcx
, discr_def_id
.to_def_id());
536 let cause
= traits
::ObligationCause
::new(
537 tcx
.def_span(discr_def_id
),
539 traits
::MiscObligation
,
541 fcx
.register_predicate(traits
::Obligation
::new(
544 ty
::PredicateKind
::ConstEvaluatable(ty
::Unevaluated
::new(
545 ty
::WithOptConstParam
::unknown(discr_def_id
.to_def_id()),
553 check_where_clauses(fcx
, item
.span
, item
.def_id
.to_def_id(), None
);
555 // No implied bounds in a struct definition.
560 fn check_trait(tcx
: TyCtxt
<'_
>, item
: &hir
::Item
<'_
>) {
561 debug
!("check_trait: {:?}", item
.def_id
);
563 let trait_def
= tcx
.trait_def(item
.def_id
);
564 if trait_def
.is_marker
565 || matches
!(trait_def
.specialization_kind
, TraitSpecializationKind
::Marker
)
567 for associated_def_id
in &*tcx
.associated_item_def_ids(item
.def_id
) {
570 tcx
.def_span(*associated_def_id
),
572 "marker traits cannot have associated items",
578 // FIXME: this shouldn't use an `FnCtxt` at all.
579 for_item(tcx
, item
).with_fcx(|fcx
| {
580 check_where_clauses(fcx
, item
.span
, item
.def_id
.to_def_id(), None
);
586 /// Checks all associated type defaults of trait `trait_def_id`.
588 /// Assuming the defaults are used, check that all predicates (bounds on the
589 /// assoc type and where clauses on the trait) hold.
590 fn check_associated_type_bounds(fcx
: &FnCtxt
<'_
, '_
>, item
: &ty
::AssocItem
, span
: Span
) {
593 let bounds
= tcx
.explicit_item_bounds(item
.def_id
);
595 debug
!("check_associated_type_bounds: bounds={:?}", bounds
);
596 let wf_obligations
= bounds
.iter().flat_map(|&(bound
, bound_span
)| {
597 let normalized_bound
= fcx
.normalize_associated_types_in(span
, bound
);
598 traits
::wf
::predicate_obligations(
607 for obligation
in wf_obligations
{
608 debug
!("next obligation cause: {:?}", obligation
.cause
);
609 fcx
.register_predicate(obligation
);
618 decl
: &hir
::FnDecl
<'_
>,
620 for_id(tcx
, item_id
, span
).with_fcx(|fcx
| {
621 let def_id
= tcx
.hir().local_def_id(item_id
);
622 let sig
= tcx
.fn_sig(def_id
);
623 let mut implied_bounds
= vec
![];
624 check_fn_or_method(fcx
, ident
.span
, sig
, decl
, def_id
.to_def_id(), &mut implied_bounds
);
629 fn check_item_type(tcx
: TyCtxt
<'_
>, item_id
: hir
::HirId
, ty_span
: Span
, allow_foreign_ty
: bool
) {
630 debug
!("check_item_type: {:?}", item_id
);
632 for_id(tcx
, item_id
, ty_span
).with_fcx(|fcx
| {
633 let ty
= tcx
.type_of(tcx
.hir().local_def_id(item_id
));
634 let item_ty
= fcx
.normalize_associated_types_in_wf(
637 WellFormedLoc
::Ty(item_id
.expect_owner()),
640 let mut forbid_unsized
= true;
641 if allow_foreign_ty
{
642 let tail
= fcx
.tcx
.struct_tail_erasing_lifetimes(item_ty
, fcx
.param_env
);
643 if let ty
::Foreign(_
) = tail
.kind() {
644 forbid_unsized
= false;
648 fcx
.register_wf_obligation(
651 ObligationCauseCode
::WellFormed(Some(WellFormedLoc
::Ty(item_id
.expect_owner()))),
656 tcx
.require_lang_item(LangItem
::Sized
, None
),
657 traits
::ObligationCause
::new(ty_span
, fcx
.body_id
, traits
::MiscObligation
),
661 // No implied bounds in a const, etc.
666 #[tracing::instrument(level = "debug", skip(tcx, ast_self_ty, ast_trait_ref))]
669 item
: &'tcx hir
::Item
<'tcx
>,
670 ast_self_ty
: &hir
::Ty
<'_
>,
671 ast_trait_ref
: &Option
<hir
::TraitRef
<'_
>>,
673 for_item(tcx
, item
).with_fcx(|fcx
| {
674 match *ast_trait_ref
{
675 Some(ref ast_trait_ref
) => {
676 // `#[rustc_reservation_impl]` impls are not real impls and
677 // therefore don't need to be WF (the trait's `Self: Trait` predicate
679 let trait_ref
= tcx
.impl_trait_ref(item
.def_id
).unwrap();
681 fcx
.normalize_associated_types_in(ast_trait_ref
.path
.span
, trait_ref
);
682 let obligations
= traits
::wf
::trait_obligations(
687 ast_trait_ref
.path
.span
,
690 debug
!(?obligations
);
691 for obligation
in obligations
{
692 fcx
.register_predicate(obligation
);
696 let self_ty
= tcx
.type_of(item
.def_id
);
697 let self_ty
= fcx
.normalize_associated_types_in(item
.span
, self_ty
);
698 fcx
.register_wf_obligation(
701 ObligationCauseCode
::WellFormed(Some(WellFormedLoc
::Ty(
702 item
.hir_id().expect_owner(),
708 check_where_clauses(fcx
, item
.span
, item
.def_id
.to_def_id(), None
);
710 fcx
.impl_implied_bounds(item
.def_id
.to_def_id(), item
.span
)
714 /// Checks where-clauses and inline bounds that are declared on `def_id`.
715 fn check_where_clauses
<'tcx
, 'fcx
>(
716 fcx
: &FnCtxt
<'fcx
, 'tcx
>,
719 return_ty
: Option
<(Ty
<'tcx
>, Span
)>,
721 debug
!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id
, return_ty
);
724 let predicates
= tcx
.predicates_of(def_id
);
725 let generics
= tcx
.generics_of(def_id
);
727 let is_our_default
= |def
: &ty
::GenericParamDef
| match def
.kind
{
728 GenericParamDefKind
::Type { has_default, .. }
729 | GenericParamDefKind
::Const { has_default }
=> {
730 has_default
&& def
.index
>= generics
.parent_count
as u32
732 GenericParamDefKind
::Lifetime
=> unreachable
!(),
735 // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
736 // For example, this forbids the declaration:
738 // struct Foo<T = Vec<[u32]>> { .. }
740 // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
741 for param
in &generics
.params
{
743 GenericParamDefKind
::Type { .. }
=> {
744 if is_our_default(¶m
) {
745 let ty
= tcx
.type_of(param
.def_id
);
746 // Ignore dependent defaults -- that is, where the default of one type
747 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
748 // be sure if it will error or not as user might always specify the other.
749 if !ty
.definitely_needs_subst(tcx
) {
750 fcx
.register_wf_obligation(
752 tcx
.def_span(param
.def_id
),
753 ObligationCauseCode
::MiscObligation
,
758 GenericParamDefKind
::Const { .. }
=> {
759 if is_our_default(¶m
) {
760 // FIXME(const_generics_defaults): This
761 // is incorrect when dealing with unused substs, for example
762 // for `struct Foo<const N: usize, const M: usize = { 1 - 2 }>`
763 // we should eagerly error.
764 let default_ct
= tcx
.const_param_default(param
.def_id
);
765 if !default_ct
.definitely_needs_subst(tcx
) {
766 fcx
.register_wf_obligation(
768 tcx
.def_span(param
.def_id
),
769 ObligationCauseCode
::WellFormed(None
),
774 // Doesn't have defaults.
775 GenericParamDefKind
::Lifetime
=> {}
779 // Check that trait predicates are WF when params are substituted by their defaults.
780 // We don't want to overly constrain the predicates that may be written but we want to
781 // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
782 // Therefore we check if a predicate which contains a single type param
783 // with a concrete default is WF with that default substituted.
784 // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
786 // First we build the defaulted substitution.
787 let substs
= InternalSubsts
::for_item(tcx
, def_id
, |param
, _
| {
789 GenericParamDefKind
::Lifetime
=> {
790 // All regions are identity.
791 tcx
.mk_param_from_def(param
)
794 GenericParamDefKind
::Type { .. }
=> {
795 // If the param has a default, ...
796 if is_our_default(param
) {
797 let default_ty
= tcx
.type_of(param
.def_id
);
798 // ... and it's not a dependent default, ...
799 if !default_ty
.definitely_needs_subst(tcx
) {
800 // ... then substitute it with the default.
801 return default_ty
.into();
805 tcx
.mk_param_from_def(param
)
807 GenericParamDefKind
::Const { .. }
=> {
808 // If the param has a default, ...
809 if is_our_default(param
) {
810 let default_ct
= tcx
.const_param_default(param
.def_id
);
811 // ... and it's not a dependent default, ...
812 if !default_ct
.definitely_needs_subst(tcx
) {
813 // ... then substitute it with the default.
814 return default_ct
.into();
818 tcx
.mk_param_from_def(param
)
823 // Now we build the substituted predicates.
824 let default_obligations
= predicates
827 .flat_map(|&(pred
, sp
)| {
828 struct CountParams
<'tcx
> {
830 params
: FxHashSet
<u32>,
832 impl<'tcx
> ty
::fold
::TypeVisitor
<'tcx
> for CountParams
<'tcx
> {
834 fn tcx_for_anon_const_substs(&self) -> Option
<TyCtxt
<'tcx
>> {
838 fn visit_ty(&mut self, t
: Ty
<'tcx
>) -> ControlFlow
<Self::BreakTy
> {
839 if let ty
::Param(param
) = t
.kind() {
840 self.params
.insert(param
.index
);
842 t
.super_visit_with(self)
845 fn visit_region(&mut self, _
: ty
::Region
<'tcx
>) -> ControlFlow
<Self::BreakTy
> {
849 fn visit_const(&mut self, c
: &'tcx ty
::Const
<'tcx
>) -> ControlFlow
<Self::BreakTy
> {
850 if let ty
::ConstKind
::Param(param
) = c
.val
{
851 self.params
.insert(param
.index
);
853 c
.super_visit_with(self)
856 let mut param_count
= CountParams { tcx: fcx.tcx, params: FxHashSet::default() }
;
857 let has_region
= pred
.visit_with(&mut param_count
).is_break();
858 let substituted_pred
= pred
.subst(tcx
, substs
);
859 // Don't check non-defaulted params, dependent defaults (including lifetimes)
860 // or preds with multiple params.
861 if substituted_pred
.definitely_has_param_types_or_consts(tcx
)
862 || param_count
.params
.len() > 1
866 } else if predicates
.predicates
.iter().any(|&(p
, _
)| p
== substituted_pred
) {
867 // Avoid duplication of predicates that contain no parameters, for example.
870 Some((substituted_pred
, sp
))
874 // Convert each of those into an obligation. So if you have
875 // something like `struct Foo<T: Copy = String>`, we would
876 // take that predicate `T: Copy`, substitute to `String: Copy`
877 // (actually that happens in the previous `flat_map` call),
878 // and then try to prove it (in this case, we'll fail).
880 // Note the subtle difference from how we handle `predicates`
881 // below: there, we are not trying to prove those predicates
882 // to be *true* but merely *well-formed*.
883 let pred
= fcx
.normalize_associated_types_in(sp
, pred
);
885 traits
::ObligationCause
::new(sp
, fcx
.body_id
, traits
::ItemObligation(def_id
));
886 traits
::Obligation
::new(cause
, fcx
.param_env
, pred
)
889 let predicates
= predicates
.instantiate_identity(tcx
);
891 if let Some((mut return_ty
, span
)) = return_ty
{
892 if return_ty
.has_infer_types_or_consts() {
893 fcx
.select_obligations_where_possible(false, |_
| {}
);
894 return_ty
= fcx
.resolve_vars_if_possible(return_ty
);
896 check_opaque_types(fcx
, def_id
.expect_local(), span
, return_ty
);
899 let predicates
= fcx
.normalize_associated_types_in(span
, predicates
);
901 debug
!("check_where_clauses: predicates={:?}", predicates
.predicates
);
902 assert_eq
!(predicates
.predicates
.len(), predicates
.spans
.len());
904 iter
::zip(&predicates
.predicates
, &predicates
.spans
).flat_map(|(&p
, &sp
)| {
905 traits
::wf
::predicate_obligations(fcx
, fcx
.param_env
, fcx
.body_id
, p
, sp
)
908 for obligation
in wf_obligations
.chain(default_obligations
) {
909 debug
!("next obligation cause: {:?}", obligation
.cause
);
910 fcx
.register_predicate(obligation
);
914 #[tracing::instrument(level = "debug", skip(fcx, span, hir_decl))]
915 fn check_fn_or_method
<'fcx
, 'tcx
>(
916 fcx
: &FnCtxt
<'fcx
, 'tcx
>,
918 sig
: ty
::PolyFnSig
<'tcx
>,
919 hir_decl
: &hir
::FnDecl
<'_
>,
921 implied_bounds
: &mut Vec
<Ty
<'tcx
>>,
923 let sig
= fcx
.tcx
.liberate_late_bound_regions(def_id
, sig
);
925 // Unnormalized types in signature are WF too
926 implied_bounds
.extend(sig
.inputs());
927 // FIXME(#27579) return types should not be implied bounds
928 implied_bounds
.push(sig
.output());
930 // Normalize the input and output types one at a time, using a different
931 // `WellFormedLoc` for each. We cannot call `normalize_associated_types`
932 // on the entire `FnSig`, since this would use the same `WellFormedLoc`
933 // for each type, preventing the HIR wf check from generating
934 // a nice error message.
935 let ty
::FnSig { mut inputs_and_output, c_variadic, unsafety, abi }
= sig
;
937 fcx
.tcx
.mk_type_list(inputs_and_output
.iter().enumerate().map(|(i
, ty
)| {
938 fcx
.normalize_associated_types_in_wf(
941 WellFormedLoc
::Param
{
942 function
: def_id
.expect_local(),
943 // Note that the `param_idx` of the output type is
944 // one greater than the index of the last input type.
945 param_idx
: i
.try_into().unwrap(),
949 // Manually call `normalize_assocaited_types_in` on the other types
950 // in `FnSig`. This ensures that if the types of these fields
951 // ever change to include projections, we will start normalizing
952 // them automatically.
953 let sig
= ty
::FnSig
{
955 c_variadic
: fcx
.normalize_associated_types_in(span
, c_variadic
),
956 unsafety
: fcx
.normalize_associated_types_in(span
, unsafety
),
957 abi
: fcx
.normalize_associated_types_in(span
, abi
),
960 for (i
, (&input_ty
, ty
)) in iter
::zip(sig
.inputs(), hir_decl
.inputs
).enumerate() {
961 fcx
.register_wf_obligation(
964 ObligationCauseCode
::WellFormed(Some(WellFormedLoc
::Param
{
965 function
: def_id
.expect_local(),
966 param_idx
: i
.try_into().unwrap(),
971 implied_bounds
.extend(sig
.inputs());
973 fcx
.register_wf_obligation(
975 hir_decl
.output
.span(),
976 ObligationCauseCode
::ReturnType
,
979 // FIXME(#27579) return types should not be implied bounds
980 implied_bounds
.push(sig
.output());
982 debug
!(?implied_bounds
);
984 check_where_clauses(fcx
, span
, def_id
, Some((sig
.output(), hir_decl
.output
.span())));
987 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
988 /// laid for "higher-order pattern unification".
989 /// This ensures that inference is tractable.
990 /// In particular, definitions of opaque types can only use other generics as arguments,
991 /// and they cannot repeat an argument. Example:
994 /// type Foo<A, B> = impl Bar<A, B>;
996 /// // Okay -- `Foo` is applied to two distinct, generic types.
997 /// fn a<T, U>() -> Foo<T, U> { .. }
999 /// // Not okay -- `Foo` is applied to `T` twice.
1000 /// fn b<T>() -> Foo<T, T> { .. }
1002 /// // Not okay -- `Foo` is applied to a non-generic type.
1003 /// fn b<T>() -> Foo<T, u32> { .. }
1006 fn check_opaque_types
<'fcx
, 'tcx
>(
1007 fcx
: &FnCtxt
<'fcx
, 'tcx
>,
1008 fn_def_id
: LocalDefId
,
1012 trace
!("check_opaque_types(fn_def_id={:?}, ty={:?})", fn_def_id
, ty
);
1015 ty
.fold_with(&mut ty
::fold
::BottomUpFolder
{
1018 if let ty
::Opaque(def_id
, substs
) = *ty
.kind() {
1019 trace
!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id
, substs
);
1020 let generics
= tcx
.generics_of(def_id
);
1022 let opaque_hir_id
= if let Some(local_id
) = def_id
.as_local() {
1023 tcx
.hir().local_def_id_to_hir_id(local_id
)
1025 // Opaque types from other crates won't have defining uses in this crate.
1028 if let hir
::ItemKind
::OpaqueTy(hir
::OpaqueTy { impl_trait_fn: Some(_), .. }
) =
1029 tcx
.hir().expect_item(opaque_hir_id
).kind
1031 // No need to check return position impl trait (RPIT)
1032 // because for type and const parameters they are correct
1033 // by construction: we convert
1035 // fn foo<P0..Pn>() -> impl Trait
1039 // type Foo<P0...Pn>
1040 // fn foo<P0..Pn>() -> Foo<P0...Pn>.
1042 // For lifetime parameters we convert
1044 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
1048 // type foo::<'p0..'pn>::Foo<'q0..'qm>
1049 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
1051 // which would error here on all of the `'static` args.
1054 if !may_define_opaque_type(tcx
, fn_def_id
, opaque_hir_id
) {
1057 trace
!("check_opaque_types: may define, generics={:#?}", generics
);
1058 let mut seen_params
: FxHashMap
<_
, Vec
<_
>> = FxHashMap
::default();
1059 for (i
, arg
) in substs
.iter().enumerate() {
1060 let arg_is_param
= match arg
.unpack() {
1061 GenericArgKind
::Type(ty
) => matches
!(ty
.kind(), ty
::Param(_
)),
1063 GenericArgKind
::Lifetime(region
) if let ty
::ReStatic
= region
=> {
1067 "non-defining opaque type use in defining scope",
1070 tcx
.def_span(generics
.param_at(i
, tcx
).def_id
),
1071 "cannot use static lifetime; use a bound lifetime \
1072 instead or remove the lifetime parameter from the \
1079 GenericArgKind
::Lifetime(_
) => true,
1081 GenericArgKind
::Const(ct
) => matches
!(ct
.val
, ty
::ConstKind
::Param(_
)),
1085 seen_params
.entry(arg
).or_default().push(i
);
1087 // Prevent `fn foo() -> Foo<u32>` from being defining.
1088 let opaque_param
= generics
.param_at(i
, tcx
);
1090 .struct_span_err(span
, "non-defining opaque type use in defining scope")
1092 tcx
.def_span(opaque_param
.def_id
),
1094 "used non-generic {} `{}` for generic parameter",
1095 opaque_param
.kind
.descr(),
1101 } // for (arg, param)
1103 for (_
, indices
) in seen_params
{
1104 if indices
.len() > 1 {
1105 let descr
= generics
.param_at(indices
[0], tcx
).kind
.descr();
1106 let spans
: Vec
<_
> = indices
1108 .map(|i
| tcx
.def_span(generics
.param_at(i
, tcx
).def_id
))
1111 .struct_span_err(span
, "non-defining opaque type use in defining scope")
1112 .span_note(spans
, &format
!("{} used multiple times", descr
))
1124 const HELP_FOR_SELF_TYPE
: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
1125 `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
1126 of the previous types except `Self`)";
1128 #[tracing::instrument(level = "debug", skip(fcx))]
1129 fn check_method_receiver
<'fcx
, 'tcx
>(
1130 fcx
: &FnCtxt
<'fcx
, 'tcx
>,
1131 fn_sig
: &hir
::FnSig
<'_
>,
1132 method
: &ty
::AssocItem
,
1135 // Check that the method has a valid receiver type, given the type `Self`.
1136 debug
!("check_method_receiver({:?}, self_ty={:?})", method
, self_ty
);
1138 if !method
.fn_has_self_parameter
{
1142 let span
= fn_sig
.decl
.inputs
[0].span
;
1144 let sig
= fcx
.tcx
.fn_sig(method
.def_id
);
1145 let sig
= fcx
.tcx
.liberate_late_bound_regions(method
.def_id
, sig
);
1146 let sig
= fcx
.normalize_associated_types_in(span
, sig
);
1148 debug
!("check_method_receiver: sig={:?}", sig
);
1150 let self_ty
= fcx
.normalize_associated_types_in(span
, self_ty
);
1152 let receiver_ty
= sig
.inputs()[0];
1153 let receiver_ty
= fcx
.normalize_associated_types_in(span
, receiver_ty
);
1155 if fcx
.tcx
.features().arbitrary_self_types
{
1156 if !receiver_is_valid(fcx
, span
, receiver_ty
, self_ty
, true) {
1157 // Report error; `arbitrary_self_types` was enabled.
1158 e0307(fcx
, span
, receiver_ty
);
1161 if !receiver_is_valid(fcx
, span
, receiver_ty
, self_ty
, false) {
1162 if receiver_is_valid(fcx
, span
, receiver_ty
, self_ty
, true) {
1163 // Report error; would have worked with `arbitrary_self_types`.
1165 &fcx
.tcx
.sess
.parse_sess
,
1166 sym
::arbitrary_self_types
,
1169 "`{}` cannot be used as the type of `self` without \
1170 the `arbitrary_self_types` feature",
1174 .help(HELP_FOR_SELF_TYPE
)
1177 // Report error; would not have worked with `arbitrary_self_types`.
1178 e0307(fcx
, span
, receiver_ty
);
1184 fn e0307(fcx
: &FnCtxt
<'fcx
, 'tcx
>, span
: Span
, receiver_ty
: Ty
<'_
>) {
1186 fcx
.tcx
.sess
.diagnostic(),
1189 "invalid `self` parameter type: {}",
1192 .note("type of `self` must be `Self` or a type that dereferences to it")
1193 .help(HELP_FOR_SELF_TYPE
)
1197 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
1198 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
1199 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
1200 /// strict: `receiver_ty` must implement `Receiver` and directly implement
1201 /// `Deref<Target = self_ty>`.
1203 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
1204 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
1205 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
1206 fn receiver_is_valid
<'fcx
, 'tcx
>(
1207 fcx
: &FnCtxt
<'fcx
, 'tcx
>,
1209 receiver_ty
: Ty
<'tcx
>,
1211 arbitrary_self_types_enabled
: bool
,
1213 let cause
= fcx
.cause(span
, traits
::ObligationCauseCode
::MethodReceiver
);
1215 let can_eq_self
= |ty
| fcx
.infcx
.can_eq(fcx
.param_env
, self_ty
, ty
).is_ok();
1217 // `self: Self` is always valid.
1218 if can_eq_self(receiver_ty
) {
1219 if let Some(mut err
) = fcx
.demand_eqtype_with_origin(&cause
, self_ty
, receiver_ty
) {
1225 let mut autoderef
= fcx
.autoderef(span
, receiver_ty
);
1227 // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
1228 if arbitrary_self_types_enabled
{
1229 autoderef
= autoderef
.include_raw_pointers();
1232 // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
1235 let receiver_trait_def_id
= fcx
.tcx
.require_lang_item(LangItem
::Receiver
, None
);
1237 // Keep dereferencing `receiver_ty` until we get to `self_ty`.
1239 if let Some((potential_self_ty
, _
)) = autoderef
.next() {
1241 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
1242 potential_self_ty
, self_ty
1245 if can_eq_self(potential_self_ty
) {
1246 fcx
.register_predicates(autoderef
.into_obligations());
1248 if let Some(mut err
) =
1249 fcx
.demand_eqtype_with_origin(&cause
, self_ty
, potential_self_ty
)
1256 // Without `feature(arbitrary_self_types)`, we require that each step in the
1257 // deref chain implement `receiver`
1258 if !arbitrary_self_types_enabled
1259 && !receiver_is_implemented(
1261 receiver_trait_def_id
,
1270 debug
!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty
, self_ty
);
1271 // If he receiver already has errors reported due to it, consider it valid to avoid
1272 // unnecessary errors (#58712).
1273 return receiver_ty
.references_error();
1277 // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
1278 if !arbitrary_self_types_enabled
1279 && !receiver_is_implemented(fcx
, receiver_trait_def_id
, cause
.clone(), receiver_ty
)
1287 fn receiver_is_implemented(
1288 fcx
: &FnCtxt
<'_
, 'tcx
>,
1289 receiver_trait_def_id
: DefId
,
1290 cause
: ObligationCause
<'tcx
>,
1291 receiver_ty
: Ty
<'tcx
>,
1293 let trait_ref
= ty
::TraitRef
{
1294 def_id
: receiver_trait_def_id
,
1295 substs
: fcx
.tcx
.mk_substs_trait(receiver_ty
, &[]),
1298 let obligation
= traits
::Obligation
::new(
1301 trait_ref
.without_const().to_predicate(fcx
.tcx
),
1304 if fcx
.predicate_must_hold_modulo_regions(&obligation
) {
1308 "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
1315 fn check_variances_for_type_defn
<'tcx
>(
1317 item
: &hir
::Item
<'tcx
>,
1318 hir_generics
: &hir
::Generics
<'_
>,
1320 let ty
= tcx
.type_of(item
.def_id
);
1321 if tcx
.has_error_field(ty
) {
1325 let ty_predicates
= tcx
.predicates_of(item
.def_id
);
1326 assert_eq
!(ty_predicates
.parent
, None
);
1327 let variances
= tcx
.variances_of(item
.def_id
);
1329 let mut constrained_parameters
: FxHashSet
<_
> = variances
1332 .filter(|&(_
, &variance
)| variance
!= ty
::Bivariant
)
1333 .map(|(index
, _
)| Parameter(index
as u32))
1336 identify_constrained_generic_params(tcx
, ty_predicates
, None
, &mut constrained_parameters
);
1338 for (index
, _
) in variances
.iter().enumerate() {
1339 if constrained_parameters
.contains(&Parameter(index
as u32)) {
1343 let param
= &hir_generics
.params
[index
];
1346 hir
::ParamName
::Error
=> {}
1347 _
=> report_bivariance(tcx
, param
),
1352 fn report_bivariance(tcx
: TyCtxt
<'_
>, param
: &rustc_hir
::GenericParam
<'_
>) {
1353 let span
= param
.span
;
1354 let param_name
= param
.name
.ident().name
;
1355 let mut err
= error_392(tcx
, span
, param_name
);
1357 let suggested_marker_id
= tcx
.lang_items().phantom_data();
1358 // Help is available only in presence of lang items.
1359 let msg
= if let Some(def_id
) = suggested_marker_id
{
1361 "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1363 tcx
.def_path_str(def_id
),
1366 format
!("consider removing `{}` or referring to it in a field", param_name
)
1370 if matches
!(param
.kind
, rustc_hir
::GenericParamKind
::Type { .. }
) {
1372 "if you intended `{0}` to be a const parameter, use `const {0}: usize` instead",
1379 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1381 fn check_false_global_bounds(fcx
: &FnCtxt
<'_
, '_
>, span
: Span
, id
: hir
::HirId
) {
1382 let empty_env
= ty
::ParamEnv
::empty();
1384 let def_id
= fcx
.tcx
.hir().local_def_id(id
);
1385 let predicates
= fcx
.tcx
.predicates_of(def_id
).predicates
.iter().map(|(p
, _
)| *p
);
1386 // Check elaborated bounds.
1387 let implied_obligations
= traits
::elaborate_predicates(fcx
.tcx
, predicates
);
1389 for obligation
in implied_obligations
{
1390 let pred
= obligation
.predicate
;
1391 // Match the existing behavior.
1392 if pred
.is_global(fcx
.tcx
) && !pred
.has_late_bound_regions() {
1393 let pred
= fcx
.normalize_associated_types_in(span
, pred
);
1394 let obligation
= traits
::Obligation
::new(
1395 traits
::ObligationCause
::new(span
, id
, traits
::TrivialBound
),
1399 fcx
.register_predicate(obligation
);
1403 fcx
.select_all_obligations_or_error();
1406 #[derive(Clone, Copy)]
1407 pub struct CheckTypeWellFormedVisitor
<'tcx
> {
1411 impl CheckTypeWellFormedVisitor
<'tcx
> {
1412 pub fn new(tcx
: TyCtxt
<'tcx
>) -> CheckTypeWellFormedVisitor
<'tcx
> {
1413 CheckTypeWellFormedVisitor { tcx }
1417 impl ParItemLikeVisitor
<'tcx
> for CheckTypeWellFormedVisitor
<'tcx
> {
1418 fn visit_item(&self, i
: &'tcx hir
::Item
<'tcx
>) {
1419 Visitor
::visit_item(&mut self.clone(), i
);
1422 fn visit_trait_item(&self, trait_item
: &'tcx hir
::TraitItem
<'tcx
>) {
1423 Visitor
::visit_trait_item(&mut self.clone(), trait_item
);
1426 fn visit_impl_item(&self, impl_item
: &'tcx hir
::ImplItem
<'tcx
>) {
1427 Visitor
::visit_impl_item(&mut self.clone(), impl_item
);
1430 fn visit_foreign_item(&self, foreign_item
: &'tcx hir
::ForeignItem
<'tcx
>) {
1431 Visitor
::visit_foreign_item(&mut self.clone(), foreign_item
)
1435 impl Visitor
<'tcx
> for CheckTypeWellFormedVisitor
<'tcx
> {
1436 type Map
= hir_map
::Map
<'tcx
>;
1438 fn nested_visit_map(&mut self) -> hir_visit
::NestedVisitorMap
<Self::Map
> {
1439 hir_visit
::NestedVisitorMap
::OnlyBodies(self.tcx
.hir())
1442 fn visit_item(&mut self, i
: &'tcx hir
::Item
<'tcx
>) {
1443 debug
!("visit_item: {:?}", i
);
1444 self.tcx
.ensure().check_item_well_formed(i
.def_id
);
1445 hir_visit
::walk_item(self, i
);
1448 fn visit_trait_item(&mut self, trait_item
: &'tcx hir
::TraitItem
<'tcx
>) {
1449 debug
!("visit_trait_item: {:?}", trait_item
);
1450 self.tcx
.ensure().check_trait_item_well_formed(trait_item
.def_id
);
1451 hir_visit
::walk_trait_item(self, trait_item
);
1454 fn visit_impl_item(&mut self, impl_item
: &'tcx hir
::ImplItem
<'tcx
>) {
1455 debug
!("visit_impl_item: {:?}", impl_item
);
1456 self.tcx
.ensure().check_impl_item_well_formed(impl_item
.def_id
);
1457 hir_visit
::walk_impl_item(self, impl_item
);
1460 fn visit_generic_param(&mut self, p
: &'tcx hir
::GenericParam
<'tcx
>) {
1461 check_param_wf(self.tcx
, p
);
1462 hir_visit
::walk_generic_param(self, p
);
1466 ///////////////////////////////////////////////////////////////////////////
1469 // FIXME(eddyb) replace this with getting fields/discriminants through `ty::AdtDef`.
1470 struct AdtVariant
<'tcx
> {
1471 /// Types of fields in the variant, that must be well-formed.
1472 fields
: Vec
<AdtField
<'tcx
>>,
1474 /// Explicit discriminant of this variant (e.g. `A = 123`),
1475 /// that must evaluate to a constant value.
1476 explicit_discr
: Option
<LocalDefId
>,
1479 struct AdtField
<'tcx
> {
1485 impl<'a
, 'tcx
> FnCtxt
<'a
, 'tcx
> {
1486 // FIXME(eddyb) replace this with getting fields through `ty::AdtDef`.
1487 fn non_enum_variant(&self, struct_def
: &hir
::VariantData
<'_
>) -> AdtVariant
<'tcx
> {
1488 let fields
= struct_def
1492 let def_id
= self.tcx
.hir().local_def_id(field
.hir_id
);
1493 let field_ty
= self.tcx
.type_of(def_id
);
1494 let field_ty
= self.normalize_associated_types_in(field
.ty
.span
, field_ty
);
1495 let field_ty
= self.resolve_vars_if_possible(field_ty
);
1496 debug
!("non_enum_variant: type of field {:?} is {:?}", field
, field_ty
);
1497 AdtField { ty: field_ty, span: field.ty.span, def_id }
1500 AdtVariant { fields, explicit_discr: None }
1503 fn enum_variants(&self, enum_def
: &hir
::EnumDef
<'_
>) -> Vec
<AdtVariant
<'tcx
>> {
1507 .map(|variant
| AdtVariant
{
1508 fields
: self.non_enum_variant(&variant
.data
).fields
,
1509 explicit_discr
: variant
1511 .map(|explicit_discr
| self.tcx
.hir().local_def_id(explicit_discr
.hir_id
)),
1516 pub(super) fn impl_implied_bounds(&self, impl_def_id
: DefId
, span
: Span
) -> Vec
<Ty
<'tcx
>> {
1517 match self.tcx
.impl_trait_ref(impl_def_id
) {
1518 Some(trait_ref
) => {
1519 // Trait impl: take implied bounds from all types that
1520 // appear in the trait reference.
1521 let trait_ref
= self.normalize_associated_types_in(span
, trait_ref
);
1522 trait_ref
.substs
.types().collect()
1526 // Inherent impl: take implied bounds from the `self` type.
1527 let self_ty
= self.tcx
.type_of(impl_def_id
);
1528 let self_ty
= self.normalize_associated_types_in(span
, self_ty
);
1535 fn error_392(tcx
: TyCtxt
<'_
>, span
: Span
, param_name
: Symbol
) -> DiagnosticBuilder
<'_
> {
1537 struct_span_err
!(tcx
.sess
, span
, E0392
, "parameter `{}` is never used", param_name
);
1538 err
.span_label(span
, "unused parameter");