]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
compiletest: Do not run debuginfo tests with gdb on msvc targets
[rust.git] / src / librustc_typeck / check / wfcheck.rs
1 use crate::check::{FnCtxt, Inherited};
2 use crate::constrained_generic_params::{identify_constrained_generic_params, Parameter};
3
4 use rustc::infer::opaque_types::may_define_opaque_type;
5 use rustc::middle::lang_items;
6 use rustc::session::parse::feature_err;
7 use rustc::traits::{self, ObligationCause, ObligationCauseCode};
8 use rustc::ty::subst::{InternalSubsts, Subst};
9 use rustc::ty::{self, AdtKind, GenericParamDefKind, ToPredicate, Ty, TyCtxt, TypeFoldable};
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_errors::{struct_span_err, DiagnosticBuilder};
12 use rustc_hir::def_id::DefId;
13 use rustc_hir::ItemKind;
14 use rustc_span::symbol::sym;
15 use rustc_span::Span;
16 use syntax::ast;
17
18 use rustc_hir as hir;
19 use rustc_hir::itemlikevisit::ParItemLikeVisitor;
20
21 /// Helper type of a temporary returned by `.for_item(...)`.
22 /// This is necessary because we can't write the following bound:
23 ///
24 /// ```rust
25 /// F: for<'b, 'tcx> where 'tcx FnOnce(FnCtxt<'b, 'tcx>)
26 /// ```
27 struct CheckWfFcxBuilder<'tcx> {
28     inherited: super::InheritedBuilder<'tcx>,
29     id: hir::HirId,
30     span: Span,
31     param_env: ty::ParamEnv<'tcx>,
32 }
33
34 impl<'tcx> CheckWfFcxBuilder<'tcx> {
35     fn with_fcx<F>(&mut self, f: F)
36     where
37         F: for<'b> FnOnce(&FnCtxt<'b, 'tcx>, TyCtxt<'tcx>) -> Vec<Ty<'tcx>>,
38     {
39         let id = self.id;
40         let span = self.span;
41         let param_env = self.param_env;
42         self.inherited.enter(|inh| {
43             let fcx = FnCtxt::new(&inh, param_env, id);
44             if !inh.tcx.features().trivial_bounds {
45                 // As predicates are cached rather than obligations, this
46                 // needsto be called first so that they are checked with an
47                 // empty `param_env`.
48                 check_false_global_bounds(&fcx, span, id);
49             }
50             let wf_tys = f(&fcx, fcx.tcx);
51             fcx.select_all_obligations_or_error();
52             fcx.regionck_item(id, span, &wf_tys);
53         });
54     }
55 }
56
57 /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
58 /// well-formed, meaning that they do not require any constraints not declared in the struct
59 /// definition itself. For example, this definition would be illegal:
60 ///
61 /// ```rust
62 /// struct Ref<'a, T> { x: &'a T }
63 /// ```
64 ///
65 /// because the type did not declare that `T:'a`.
66 ///
67 /// We do this check as a pre-pass before checking fn bodies because if these constraints are
68 /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
69 /// the types first.
70 pub fn check_item_well_formed(tcx: TyCtxt<'_>, def_id: DefId) {
71     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
72     let item = tcx.hir().expect_item(hir_id);
73
74     debug!(
75         "check_item_well_formed(it.hir_id={:?}, it.name={})",
76         item.hir_id,
77         tcx.def_path_str(def_id)
78     );
79
80     match item.kind {
81         // Right now we check that every default trait implementation
82         // has an implementation of itself. Basically, a case like:
83         //
84         //     impl Trait for T {}
85         //
86         // has a requirement of `T: Trait` which was required for default
87         // method implementations. Although this could be improved now that
88         // there's a better infrastructure in place for this, it's being left
89         // for a follow-up work.
90         //
91         // Since there's such a requirement, we need to check *just* positive
92         // implementations, otherwise things like:
93         //
94         //     impl !Send for T {}
95         //
96         // won't be allowed unless there's an *explicit* implementation of `Send`
97         // for `T`
98         hir::ItemKind::Impl { defaultness, ref of_trait, ref self_ty, .. } => {
99             let is_auto = tcx
100                 .impl_trait_ref(tcx.hir().local_def_id(item.hir_id))
101                 .map_or(false, |trait_ref| tcx.trait_is_auto(trait_ref.def_id));
102             let polarity = tcx.impl_polarity(def_id);
103             if let (hir::Defaultness::Default { .. }, true) = (defaultness, is_auto) {
104                 tcx.sess.span_err(item.span, "impls of auto traits cannot be default");
105             }
106             match polarity {
107                 ty::ImplPolarity::Positive => {
108                     check_impl(tcx, item, self_ty, of_trait);
109                 }
110                 ty::ImplPolarity::Negative => {
111                     // FIXME(#27579): what amount of WF checking do we need for neg impls?
112                     if of_trait.is_some() && !is_auto {
113                         struct_span_err!(
114                             tcx.sess,
115                             item.span,
116                             E0192,
117                             "negative impls are only allowed for \
118                                    auto traits (e.g., `Send` and `Sync`)"
119                         )
120                         .emit()
121                     }
122                 }
123                 ty::ImplPolarity::Reservation => {
124                     // FIXME: what amount of WF checking do we need for reservation impls?
125                 }
126             }
127         }
128         hir::ItemKind::Fn(..) => {
129             check_item_fn(tcx, item);
130         }
131         hir::ItemKind::Static(ref ty, ..) => {
132             check_item_type(tcx, item.hir_id, ty.span, false);
133         }
134         hir::ItemKind::Const(ref ty, ..) => {
135             check_item_type(tcx, item.hir_id, ty.span, false);
136         }
137         hir::ItemKind::ForeignMod(ref module) => {
138             for it in module.items.iter() {
139                 if let hir::ForeignItemKind::Static(ref ty, ..) = it.kind {
140                     check_item_type(tcx, it.hir_id, ty.span, true);
141                 }
142             }
143         }
144         hir::ItemKind::Struct(ref struct_def, ref ast_generics) => {
145             check_type_defn(tcx, item, false, |fcx| vec![fcx.non_enum_variant(struct_def)]);
146
147             check_variances_for_type_defn(tcx, item, ast_generics);
148         }
149         hir::ItemKind::Union(ref struct_def, ref ast_generics) => {
150             check_type_defn(tcx, item, true, |fcx| vec![fcx.non_enum_variant(struct_def)]);
151
152             check_variances_for_type_defn(tcx, item, ast_generics);
153         }
154         hir::ItemKind::Enum(ref enum_def, ref ast_generics) => {
155             check_type_defn(tcx, item, true, |fcx| fcx.enum_variants(enum_def));
156
157             check_variances_for_type_defn(tcx, item, ast_generics);
158         }
159         hir::ItemKind::Trait(..) => {
160             check_trait(tcx, item);
161         }
162         hir::ItemKind::TraitAlias(..) => {
163             check_trait(tcx, item);
164         }
165         _ => {}
166     }
167 }
168
169 pub fn check_trait_item(tcx: TyCtxt<'_>, def_id: DefId) {
170     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
171     let trait_item = tcx.hir().expect_trait_item(hir_id);
172
173     let method_sig = match trait_item.kind {
174         hir::TraitItemKind::Method(ref sig, _) => Some(sig),
175         _ => None,
176     };
177     check_associated_item(tcx, trait_item.hir_id, trait_item.span, method_sig);
178 }
179
180 pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) {
181     let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
182     let impl_item = tcx.hir().expect_impl_item(hir_id);
183
184     let method_sig = match impl_item.kind {
185         hir::ImplItemKind::Method(ref sig, _) => Some(sig),
186         _ => None,
187     };
188
189     check_associated_item(tcx, impl_item.hir_id, impl_item.span, method_sig);
190 }
191
192 fn check_associated_item(
193     tcx: TyCtxt<'_>,
194     item_id: hir::HirId,
195     span: Span,
196     sig_if_method: Option<&hir::FnSig<'_>>,
197 ) {
198     debug!("check_associated_item: {:?}", item_id);
199
200     let code = ObligationCauseCode::MiscObligation;
201     for_id(tcx, item_id, span).with_fcx(|fcx, tcx| {
202         let item = fcx.tcx.associated_item(fcx.tcx.hir().local_def_id(item_id));
203
204         let (mut implied_bounds, self_ty) = match item.container {
205             ty::TraitContainer(_) => (vec![], fcx.tcx.types.self_param),
206             ty::ImplContainer(def_id) => {
207                 (fcx.impl_implied_bounds(def_id, span), fcx.tcx.type_of(def_id))
208             }
209         };
210
211         match item.kind {
212             ty::AssocKind::Const => {
213                 let ty = fcx.tcx.type_of(item.def_id);
214                 let ty = fcx.normalize_associated_types_in(span, &ty);
215                 fcx.register_wf_obligation(ty, span, code.clone());
216             }
217             ty::AssocKind::Method => {
218                 let sig = fcx.tcx.fn_sig(item.def_id);
219                 let sig = fcx.normalize_associated_types_in(span, &sig);
220                 check_fn_or_method(tcx, fcx, span, sig, item.def_id, &mut implied_bounds);
221                 let sig_if_method = sig_if_method.expect("bad signature for method");
222                 check_method_receiver(fcx, sig_if_method, &item, self_ty);
223             }
224             ty::AssocKind::Type => {
225                 if item.defaultness.has_value() {
226                     let ty = fcx.tcx.type_of(item.def_id);
227                     let ty = fcx.normalize_associated_types_in(span, &ty);
228                     fcx.register_wf_obligation(ty, span, code.clone());
229                 }
230             }
231             ty::AssocKind::OpaqueTy => {
232                 // Do nothing: opaque types check themselves.
233             }
234         }
235
236         implied_bounds
237     })
238 }
239
240 fn for_item<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'_>) -> CheckWfFcxBuilder<'tcx> {
241     for_id(tcx, item.hir_id, item.span)
242 }
243
244 fn for_id(tcx: TyCtxt<'_>, id: hir::HirId, span: Span) -> CheckWfFcxBuilder<'_> {
245     let def_id = tcx.hir().local_def_id(id);
246     CheckWfFcxBuilder {
247         inherited: Inherited::build(tcx, def_id),
248         id,
249         span,
250         param_env: tcx.param_env(def_id),
251     }
252 }
253
254 fn item_adt_kind(kind: &ItemKind<'_>) -> Option<AdtKind> {
255     match kind {
256         ItemKind::Struct(..) => Some(AdtKind::Struct),
257         ItemKind::Union(..) => Some(AdtKind::Union),
258         ItemKind::Enum(..) => Some(AdtKind::Enum),
259         _ => None,
260     }
261 }
262
263 /// In a type definition, we check that to ensure that the types of the fields are well-formed.
264 fn check_type_defn<'tcx, F>(
265     tcx: TyCtxt<'tcx>,
266     item: &hir::Item<'tcx>,
267     all_sized: bool,
268     mut lookup_fields: F,
269 ) where
270     F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
271 {
272     for_item(tcx, item).with_fcx(|fcx, fcx_tcx| {
273         let variants = lookup_fields(fcx);
274         let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
275         let packed = fcx.tcx.adt_def(def_id).repr.packed();
276
277         for variant in &variants {
278             // For DST, or when drop needs to copy things around, all
279             // intermediate types must be sized.
280             let needs_drop_copy = || {
281                 packed && {
282                     let ty = variant.fields.last().unwrap().ty;
283                     let ty = fcx.tcx.erase_regions(&ty);
284                     if ty.has_local_value() {
285                         fcx_tcx
286                             .sess
287                             .delay_span_bug(item.span, &format!("inference variables in {:?}", ty));
288                         // Just treat unresolved type expression as if it needs drop.
289                         true
290                     } else {
291                         ty.needs_drop(fcx_tcx, fcx_tcx.param_env(def_id))
292                     }
293                 }
294             };
295             let all_sized = all_sized || variant.fields.is_empty() || needs_drop_copy();
296             let unsized_len = if all_sized { 0 } else { 1 };
297             for (idx, field) in
298                 variant.fields[..variant.fields.len() - unsized_len].iter().enumerate()
299             {
300                 let last = idx == variant.fields.len() - 1;
301                 fcx.register_bound(
302                     field.ty,
303                     fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
304                     traits::ObligationCause::new(
305                         field.span,
306                         fcx.body_id,
307                         traits::FieldSized {
308                             adt_kind: match item_adt_kind(&item.kind) {
309                                 Some(i) => i,
310                                 None => bug!(),
311                             },
312                             last,
313                         },
314                     ),
315                 );
316             }
317
318             // All field types must be well-formed.
319             for field in &variant.fields {
320                 fcx.register_wf_obligation(
321                     field.ty,
322                     field.span,
323                     ObligationCauseCode::MiscObligation,
324                 )
325             }
326         }
327
328         check_where_clauses(tcx, fcx, item.span, def_id, None);
329
330         // No implied bounds in a struct definition.
331         vec![]
332     });
333 }
334
335 fn check_trait(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
336     debug!("check_trait: {:?}", item.hir_id);
337
338     let trait_def_id = tcx.hir().local_def_id(item.hir_id);
339
340     let trait_def = tcx.trait_def(trait_def_id);
341     if trait_def.is_marker {
342         for associated_def_id in &*tcx.associated_item_def_ids(trait_def_id) {
343             struct_span_err!(
344                 tcx.sess,
345                 tcx.def_span(*associated_def_id),
346                 E0714,
347                 "marker traits cannot have associated items",
348             )
349             .emit();
350         }
351     }
352
353     for_item(tcx, item).with_fcx(|fcx, _| {
354         check_where_clauses(tcx, fcx, item.span, trait_def_id, None);
355         vec![]
356     });
357 }
358
359 fn check_item_fn(tcx: TyCtxt<'_>, item: &hir::Item<'_>) {
360     for_item(tcx, item).with_fcx(|fcx, tcx| {
361         let def_id = fcx.tcx.hir().local_def_id(item.hir_id);
362         let sig = fcx.tcx.fn_sig(def_id);
363         let sig = fcx.normalize_associated_types_in(item.span, &sig);
364         let mut implied_bounds = vec![];
365         check_fn_or_method(tcx, fcx, item.span, sig, def_id, &mut implied_bounds);
366         implied_bounds
367     })
368 }
369
370 fn check_item_type(tcx: TyCtxt<'_>, item_id: hir::HirId, ty_span: Span, allow_foreign_ty: bool) {
371     debug!("check_item_type: {:?}", item_id);
372
373     for_id(tcx, item_id, ty_span).with_fcx(|fcx, tcx| {
374         let ty = tcx.type_of(tcx.hir().local_def_id(item_id));
375         let item_ty = fcx.normalize_associated_types_in(ty_span, &ty);
376
377         let mut forbid_unsized = true;
378         if allow_foreign_ty {
379             let tail = fcx.tcx.struct_tail_erasing_lifetimes(item_ty, fcx.param_env);
380             if let ty::Foreign(_) = tail.kind {
381                 forbid_unsized = false;
382             }
383         }
384
385         fcx.register_wf_obligation(item_ty, ty_span, ObligationCauseCode::MiscObligation);
386         if forbid_unsized {
387             fcx.register_bound(
388                 item_ty,
389                 fcx.tcx.require_lang_item(lang_items::SizedTraitLangItem, None),
390                 traits::ObligationCause::new(ty_span, fcx.body_id, traits::MiscObligation),
391             );
392         }
393
394         // No implied bounds in a const, etc.
395         vec![]
396     });
397 }
398
399 fn check_impl<'tcx>(
400     tcx: TyCtxt<'tcx>,
401     item: &'tcx hir::Item<'tcx>,
402     ast_self_ty: &hir::Ty<'_>,
403     ast_trait_ref: &Option<hir::TraitRef<'_>>,
404 ) {
405     debug!("check_impl: {:?}", item);
406
407     for_item(tcx, item).with_fcx(|fcx, tcx| {
408         let item_def_id = fcx.tcx.hir().local_def_id(item.hir_id);
409
410         match *ast_trait_ref {
411             Some(ref ast_trait_ref) => {
412                 // `#[rustc_reservation_impl]` impls are not real impls and
413                 // therefore don't need to be WF (the trait's `Self: Trait` predicate
414                 // won't hold).
415                 let trait_ref = fcx.tcx.impl_trait_ref(item_def_id).unwrap();
416                 let trait_ref =
417                     fcx.normalize_associated_types_in(ast_trait_ref.path.span, &trait_ref);
418                 let obligations = traits::wf::trait_obligations(
419                     fcx,
420                     fcx.param_env,
421                     fcx.body_id,
422                     &trait_ref,
423                     ast_trait_ref.path.span,
424                     Some(item),
425                 );
426                 for obligation in obligations {
427                     fcx.register_predicate(obligation);
428                 }
429             }
430             None => {
431                 let self_ty = fcx.tcx.type_of(item_def_id);
432                 let self_ty = fcx.normalize_associated_types_in(item.span, &self_ty);
433                 fcx.register_wf_obligation(
434                     self_ty,
435                     ast_self_ty.span,
436                     ObligationCauseCode::MiscObligation,
437                 );
438             }
439         }
440
441         check_where_clauses(tcx, fcx, item.span, item_def_id, None);
442
443         fcx.impl_implied_bounds(item_def_id, item.span)
444     });
445 }
446
447 /// Checks where-clauses and inline bounds that are declared on `def_id`.
448 fn check_where_clauses<'tcx, 'fcx>(
449     tcx: TyCtxt<'tcx>,
450     fcx: &FnCtxt<'fcx, 'tcx>,
451     span: Span,
452     def_id: DefId,
453     return_ty: Option<Ty<'tcx>>,
454 ) {
455     debug!("check_where_clauses(def_id={:?}, return_ty={:?})", def_id, return_ty);
456
457     let predicates = fcx.tcx.predicates_of(def_id);
458     let generics = tcx.generics_of(def_id);
459
460     let is_our_default = |def: &ty::GenericParamDef| match def.kind {
461         GenericParamDefKind::Type { has_default, .. } => {
462             has_default && def.index >= generics.parent_count as u32
463         }
464         _ => unreachable!(),
465     };
466
467     // Check that concrete defaults are well-formed. See test `type-check-defaults.rs`.
468     // For example, this forbids the declaration:
469     //
470     //     struct Foo<T = Vec<[u32]>> { .. }
471     //
472     // Here, the default `Vec<[u32]>` is not WF because `[u32]: Sized` does not hold.
473     for param in &generics.params {
474         if let GenericParamDefKind::Type { .. } = param.kind {
475             if is_our_default(&param) {
476                 let ty = fcx.tcx.type_of(param.def_id);
477                 // Ignore dependent defaults -- that is, where the default of one type
478                 // parameter includes another (e.g., `<T, U = T>`). In those cases, we can't
479                 // be sure if it will error or not as user might always specify the other.
480                 if !ty.needs_subst() {
481                     fcx.register_wf_obligation(
482                         ty,
483                         fcx.tcx.def_span(param.def_id),
484                         ObligationCauseCode::MiscObligation,
485                     );
486                 }
487             }
488         }
489     }
490
491     // Check that trait predicates are WF when params are substituted by their defaults.
492     // We don't want to overly constrain the predicates that may be written but we want to
493     // catch cases where a default my never be applied such as `struct Foo<T: Copy = String>`.
494     // Therefore we check if a predicate which contains a single type param
495     // with a concrete default is WF with that default substituted.
496     // For more examples see tests `defaults-well-formedness.rs` and `type-check-defaults.rs`.
497     //
498     // First we build the defaulted substitution.
499     let substs = InternalSubsts::for_item(fcx.tcx, def_id, |param, _| {
500         match param.kind {
501             GenericParamDefKind::Lifetime => {
502                 // All regions are identity.
503                 fcx.tcx.mk_param_from_def(param)
504             }
505
506             GenericParamDefKind::Type { .. } => {
507                 // If the param has a default, ...
508                 if is_our_default(param) {
509                     let default_ty = fcx.tcx.type_of(param.def_id);
510                     // ... and it's not a dependent default, ...
511                     if !default_ty.needs_subst() {
512                         // ... then substitute it with the default.
513                         return default_ty.into();
514                     }
515                 }
516                 // Mark unwanted params as error.
517                 fcx.tcx.types.err.into()
518             }
519
520             GenericParamDefKind::Const => {
521                 // FIXME(const_generics:defaults)
522                 fcx.tcx.consts.err.into()
523             }
524         }
525     });
526
527     // Now we build the substituted predicates.
528     let default_obligations = predicates
529         .predicates
530         .iter()
531         .flat_map(|&(pred, sp)| {
532             #[derive(Default)]
533             struct CountParams {
534                 params: FxHashSet<u32>,
535             }
536             impl<'tcx> ty::fold::TypeVisitor<'tcx> for CountParams {
537                 fn visit_ty(&mut self, t: Ty<'tcx>) -> bool {
538                     if let ty::Param(param) = t.kind {
539                         self.params.insert(param.index);
540                     }
541                     t.super_visit_with(self)
542                 }
543
544                 fn visit_region(&mut self, _: ty::Region<'tcx>) -> bool {
545                     true
546                 }
547
548                 fn visit_const(&mut self, c: &'tcx ty::Const<'tcx>) -> bool {
549                     if let ty::ConstKind::Param(param) = c.val {
550                         self.params.insert(param.index);
551                     }
552                     c.super_visit_with(self)
553                 }
554             }
555             let mut param_count = CountParams::default();
556             let has_region = pred.visit_with(&mut param_count);
557             let substituted_pred = pred.subst(fcx.tcx, substs);
558             // Don't check non-defaulted params, dependent defaults (including lifetimes)
559             // or preds with multiple params.
560             if substituted_pred.references_error() || param_count.params.len() > 1 || has_region {
561                 None
562             } else if predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
563                 // Avoid duplication of predicates that contain no parameters, for example.
564                 None
565             } else {
566                 Some((substituted_pred, sp))
567             }
568         })
569         .map(|(pred, sp)| {
570             // Convert each of those into an obligation. So if you have
571             // something like `struct Foo<T: Copy = String>`, we would
572             // take that predicate `T: Copy`, substitute to `String: Copy`
573             // (actually that happens in the previous `flat_map` call),
574             // and then try to prove it (in this case, we'll fail).
575             //
576             // Note the subtle difference from how we handle `predicates`
577             // below: there, we are not trying to prove those predicates
578             // to be *true* but merely *well-formed*.
579             let pred = fcx.normalize_associated_types_in(sp, &pred);
580             let cause =
581                 traits::ObligationCause::new(sp, fcx.body_id, traits::ItemObligation(def_id));
582             traits::Obligation::new(cause, fcx.param_env, pred)
583         });
584
585     let mut predicates = predicates.instantiate_identity(fcx.tcx);
586
587     if let Some(return_ty) = return_ty {
588         predicates.predicates.extend(check_opaque_types(tcx, fcx, def_id, span, return_ty));
589     }
590
591     let predicates = fcx.normalize_associated_types_in(span, &predicates);
592
593     debug!("check_where_clauses: predicates={:?}", predicates.predicates);
594     let wf_obligations = predicates
595         .predicates
596         .iter()
597         .flat_map(|p| traits::wf::predicate_obligations(fcx, fcx.param_env, fcx.body_id, p, span));
598
599     for obligation in wf_obligations.chain(default_obligations) {
600         debug!("next obligation cause: {:?}", obligation.cause);
601         fcx.register_predicate(obligation);
602     }
603 }
604
605 fn check_fn_or_method<'fcx, 'tcx>(
606     tcx: TyCtxt<'tcx>,
607     fcx: &FnCtxt<'fcx, 'tcx>,
608     span: Span,
609     sig: ty::PolyFnSig<'tcx>,
610     def_id: DefId,
611     implied_bounds: &mut Vec<Ty<'tcx>>,
612 ) {
613     let sig = fcx.normalize_associated_types_in(span, &sig);
614     let sig = fcx.tcx.liberate_late_bound_regions(def_id, &sig);
615
616     for input_ty in sig.inputs() {
617         fcx.register_wf_obligation(&input_ty, span, ObligationCauseCode::MiscObligation);
618     }
619     implied_bounds.extend(sig.inputs());
620
621     fcx.register_wf_obligation(sig.output(), span, ObligationCauseCode::ReturnType);
622
623     // FIXME(#25759) return types should not be implied bounds
624     implied_bounds.push(sig.output());
625
626     check_where_clauses(tcx, fcx, span, def_id, Some(sig.output()));
627 }
628
629 /// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
630 /// laid for "higher-order pattern unification".
631 /// This ensures that inference is tractable.
632 /// In particular, definitions of opaque types can only use other generics as arguments,
633 /// and they cannot repeat an argument. Example:
634 ///
635 /// ```rust
636 /// type Foo<A, B> = impl Bar<A, B>;
637 ///
638 /// // Okay -- `Foo` is applied to two distinct, generic types.
639 /// fn a<T, U>() -> Foo<T, U> { .. }
640 ///
641 /// // Not okay -- `Foo` is applied to `T` twice.
642 /// fn b<T>() -> Foo<T, T> { .. }
643 ///
644 /// // Not okay -- `Foo` is applied to a non-generic type.
645 /// fn b<T>() -> Foo<T, u32> { .. }
646 /// ```
647 ///
648 fn check_opaque_types<'fcx, 'tcx>(
649     tcx: TyCtxt<'tcx>,
650     fcx: &FnCtxt<'fcx, 'tcx>,
651     fn_def_id: DefId,
652     span: Span,
653     ty: Ty<'tcx>,
654 ) -> Vec<ty::Predicate<'tcx>> {
655     trace!("check_opaque_types(ty={:?})", ty);
656     let mut substituted_predicates = Vec::new();
657     ty.fold_with(&mut ty::fold::BottomUpFolder {
658         tcx: fcx.tcx,
659         ty_op: |ty| {
660             if let ty::Opaque(def_id, substs) = ty.kind {
661                 trace!("check_opaque_types: opaque_ty, {:?}, {:?}", def_id, substs);
662                 let generics = tcx.generics_of(def_id);
663                 // Only check named `impl Trait` types defined in this crate.
664                 if generics.parent.is_none() && def_id.is_local() {
665                     let opaque_hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
666                     if may_define_opaque_type(tcx, fn_def_id, opaque_hir_id) {
667                         trace!("check_opaque_types: may define, generics={:#?}", generics);
668                         let mut seen: FxHashMap<_, Vec<_>> = FxHashMap::default();
669                         for (subst, param) in substs.iter().zip(&generics.params) {
670                             match subst.unpack() {
671                                 ty::subst::GenericArgKind::Type(ty) => match ty.kind {
672                                     ty::Param(..) => {}
673                                     // Prevent `fn foo() -> Foo<u32>` from being defining.
674                                     _ => {
675                                         tcx.sess
676                                             .struct_span_err(
677                                                 span,
678                                                 "non-defining opaque type use \
679                                                  in defining scope",
680                                             )
681                                             .span_note(
682                                                 tcx.def_span(param.def_id),
683                                                 &format!(
684                                                     "used non-generic type {} for \
685                                                      generic parameter",
686                                                     ty,
687                                                 ),
688                                             )
689                                             .emit();
690                                     }
691                                 },
692
693                                 ty::subst::GenericArgKind::Lifetime(region) => {
694                                     let param_span = tcx.def_span(param.def_id);
695                                     if let ty::ReStatic = region {
696                                         tcx.sess
697                                             .struct_span_err(
698                                                 span,
699                                                 "non-defining opaque type use \
700                                                     in defining scope",
701                                             )
702                                             .span_label(
703                                                 param_span,
704                                                 "cannot use static lifetime; use a bound lifetime \
705                                                 instead or remove the lifetime parameter from the \
706                                                 opaque type",
707                                             )
708                                             .emit();
709                                     } else {
710                                         seen.entry(region).or_default().push(param_span);
711                                     }
712                                 }
713
714                                 ty::subst::GenericArgKind::Const(ct) => match ct.val {
715                                     ty::ConstKind::Param(_) => {}
716                                     _ => {
717                                         tcx.sess
718                                             .struct_span_err(
719                                                 span,
720                                                 "non-defining opaque type use \
721                                                 in defining scope",
722                                             )
723                                             .span_note(
724                                                 tcx.def_span(param.def_id),
725                                                 &format!(
726                                                     "used non-generic const {} for \
727                                                     generic parameter",
728                                                     ty,
729                                                 ),
730                                             )
731                                             .emit();
732                                     }
733                                 },
734                             } // match subst
735                         } // for (subst, param)
736                         for (_, spans) in seen {
737                             if spans.len() > 1 {
738                                 tcx.sess
739                                     .struct_span_err(
740                                         span,
741                                         "non-defining opaque type use \
742                                             in defining scope",
743                                     )
744                                     .span_note(spans, "lifetime used multiple times")
745                                     .emit();
746                             }
747                         }
748                     } // if may_define_opaque_type
749
750                     // Now register the bounds on the parameters of the opaque type
751                     // so the parameters given by the function need to fulfill them.
752                     //
753                     //     type Foo<T: Bar> = impl Baz + 'static;
754                     //     fn foo<U>() -> Foo<U> { .. *}
755                     //
756                     // becomes
757                     //
758                     //     type Foo<T: Bar> = impl Baz + 'static;
759                     //     fn foo<U: Bar>() -> Foo<U> { .. *}
760                     let predicates = tcx.predicates_of(def_id);
761                     trace!("check_opaque_types: may define, predicates={:#?}", predicates,);
762                     for &(pred, _) in predicates.predicates {
763                         let substituted_pred = pred.subst(fcx.tcx, substs);
764                         // Avoid duplication of predicates that contain no parameters, for example.
765                         if !predicates.predicates.iter().any(|&(p, _)| p == substituted_pred) {
766                             substituted_predicates.push(substituted_pred);
767                         }
768                     }
769                 } // if is_named_opaque_type
770             } // if let Opaque
771             ty
772         },
773         lt_op: |lt| lt,
774         ct_op: |ct| ct,
775     });
776     substituted_predicates
777 }
778
779 const HELP_FOR_SELF_TYPE: &str = "consider changing to `self`, `&self`, `&mut self`, `self: Box<Self>`, \
780      `self: Rc<Self>`, `self: Arc<Self>`, or `self: Pin<P>` (where P is one \
781      of the previous types except `Self`)";
782
783 fn check_method_receiver<'fcx, 'tcx>(
784     fcx: &FnCtxt<'fcx, 'tcx>,
785     fn_sig: &hir::FnSig<'_>,
786     method: &ty::AssocItem,
787     self_ty: Ty<'tcx>,
788 ) {
789     // Check that the method has a valid receiver type, given the type `Self`.
790     debug!("check_method_receiver({:?}, self_ty={:?})", method, self_ty);
791
792     if !method.method_has_self_argument {
793         return;
794     }
795
796     let span = fn_sig.decl.inputs[0].span;
797
798     let sig = fcx.tcx.fn_sig(method.def_id);
799     let sig = fcx.normalize_associated_types_in(span, &sig);
800     let sig = fcx.tcx.liberate_late_bound_regions(method.def_id, &sig);
801
802     debug!("check_method_receiver: sig={:?}", sig);
803
804     let self_ty = fcx.normalize_associated_types_in(span, &self_ty);
805     let self_ty = fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(self_ty));
806
807     let receiver_ty = sig.inputs()[0];
808
809     let receiver_ty = fcx.normalize_associated_types_in(span, &receiver_ty);
810     let receiver_ty =
811         fcx.tcx.liberate_late_bound_regions(method.def_id, &ty::Binder::bind(receiver_ty));
812
813     if fcx.tcx.features().arbitrary_self_types {
814         if !receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
815             // Report error; `arbitrary_self_types` was enabled.
816             e0307(fcx, span, receiver_ty);
817         }
818     } else {
819         if !receiver_is_valid(fcx, span, receiver_ty, self_ty, false) {
820             if receiver_is_valid(fcx, span, receiver_ty, self_ty, true) {
821                 // Report error; would have worked with `arbitrary_self_types`.
822                 feature_err(
823                     &fcx.tcx.sess.parse_sess,
824                     sym::arbitrary_self_types,
825                     span,
826                     &format!(
827                         "`{}` cannot be used as the type of `self` without \
828                             the `arbitrary_self_types` feature",
829                         receiver_ty,
830                     ),
831                 )
832                 .help(HELP_FOR_SELF_TYPE)
833                 .emit();
834             } else {
835                 // Report error; would not have worked with `arbitrary_self_types`.
836                 e0307(fcx, span, receiver_ty);
837             }
838         }
839     }
840 }
841
842 fn e0307(fcx: &FnCtxt<'fcx, 'tcx>, span: Span, receiver_ty: Ty<'_>) {
843     struct_span_err!(
844         fcx.tcx.sess.diagnostic(),
845         span,
846         E0307,
847         "invalid `self` parameter type: {:?}",
848         receiver_ty,
849     )
850     .note("type of `self` must be `Self` or a type that dereferences to it")
851     .help(HELP_FOR_SELF_TYPE)
852     .emit();
853 }
854
855 /// Returns whether `receiver_ty` would be considered a valid receiver type for `self_ty`. If
856 /// `arbitrary_self_types` is enabled, `receiver_ty` must transitively deref to `self_ty`, possibly
857 /// through a `*const/mut T` raw pointer. If the feature is not enabled, the requirements are more
858 /// strict: `receiver_ty` must implement `Receiver` and directly implement
859 /// `Deref<Target = self_ty>`.
860 ///
861 /// N.B., there are cases this function returns `true` but causes an error to be emitted,
862 /// particularly when `receiver_ty` derefs to a type that is the same as `self_ty` but has the
863 /// wrong lifetime. Be careful of this if you are calling this function speculatively.
864 fn receiver_is_valid<'fcx, 'tcx>(
865     fcx: &FnCtxt<'fcx, 'tcx>,
866     span: Span,
867     receiver_ty: Ty<'tcx>,
868     self_ty: Ty<'tcx>,
869     arbitrary_self_types_enabled: bool,
870 ) -> bool {
871     let cause = fcx.cause(span, traits::ObligationCauseCode::MethodReceiver);
872
873     let can_eq_self = |ty| fcx.infcx.can_eq(fcx.param_env, self_ty, ty).is_ok();
874
875     // `self: Self` is always valid.
876     if can_eq_self(receiver_ty) {
877         if let Some(mut err) = fcx.demand_eqtype_with_origin(&cause, self_ty, receiver_ty) {
878             err.emit();
879         }
880         return true;
881     }
882
883     let mut autoderef = fcx.autoderef(span, receiver_ty);
884
885     // The `arbitrary_self_types` feature allows raw pointer receivers like `self: *const Self`.
886     if arbitrary_self_types_enabled {
887         autoderef = autoderef.include_raw_pointers();
888     }
889
890     // The first type is `receiver_ty`, which we know its not equal to `self_ty`; skip it.
891     autoderef.next();
892
893     let receiver_trait_def_id = fcx.tcx.require_lang_item(lang_items::ReceiverTraitLangItem, None);
894
895     // Keep dereferencing `receiver_ty` until we get to `self_ty`.
896     loop {
897         if let Some((potential_self_ty, _)) = autoderef.next() {
898             debug!(
899                 "receiver_is_valid: potential self type `{:?}` to match `{:?}`",
900                 potential_self_ty, self_ty
901             );
902
903             if can_eq_self(potential_self_ty) {
904                 autoderef.finalize(fcx);
905
906                 if let Some(mut err) =
907                     fcx.demand_eqtype_with_origin(&cause, self_ty, potential_self_ty)
908                 {
909                     err.emit();
910                 }
911
912                 break;
913             } else {
914                 // Without `feature(arbitrary_self_types)`, we require that each step in the
915                 // deref chain implement `receiver`
916                 if !arbitrary_self_types_enabled
917                     && !receiver_is_implemented(
918                         fcx,
919                         receiver_trait_def_id,
920                         cause.clone(),
921                         potential_self_ty,
922                     )
923                 {
924                     return false;
925                 }
926             }
927         } else {
928             debug!("receiver_is_valid: type `{:?}` does not deref to `{:?}`", receiver_ty, self_ty);
929             // If he receiver already has errors reported due to it, consider it valid to avoid
930             // unnecessary errors (#58712).
931             return receiver_ty.references_error();
932         }
933     }
934
935     // Without `feature(arbitrary_self_types)`, we require that `receiver_ty` implements `Receiver`.
936     if !arbitrary_self_types_enabled
937         && !receiver_is_implemented(fcx, receiver_trait_def_id, cause.clone(), receiver_ty)
938     {
939         return false;
940     }
941
942     true
943 }
944
945 fn receiver_is_implemented(
946     fcx: &FnCtxt<'_, 'tcx>,
947     receiver_trait_def_id: DefId,
948     cause: ObligationCause<'tcx>,
949     receiver_ty: Ty<'tcx>,
950 ) -> bool {
951     let trait_ref = ty::TraitRef {
952         def_id: receiver_trait_def_id,
953         substs: fcx.tcx.mk_substs_trait(receiver_ty, &[]),
954     };
955
956     let obligation = traits::Obligation::new(cause, fcx.param_env, trait_ref.to_predicate());
957
958     if fcx.predicate_must_hold_modulo_regions(&obligation) {
959         true
960     } else {
961         debug!(
962             "receiver_is_implemented: type `{:?}` does not implement `Receiver` trait",
963             receiver_ty
964         );
965         false
966     }
967 }
968
969 fn check_variances_for_type_defn<'tcx>(
970     tcx: TyCtxt<'tcx>,
971     item: &hir::Item<'tcx>,
972     hir_generics: &hir::Generics<'_>,
973 ) {
974     let item_def_id = tcx.hir().local_def_id(item.hir_id);
975     let ty = tcx.type_of(item_def_id);
976     if tcx.has_error_field(ty) {
977         return;
978     }
979
980     let ty_predicates = tcx.predicates_of(item_def_id);
981     assert_eq!(ty_predicates.parent, None);
982     let variances = tcx.variances_of(item_def_id);
983
984     let mut constrained_parameters: FxHashSet<_> = variances
985         .iter()
986         .enumerate()
987         .filter(|&(_, &variance)| variance != ty::Bivariant)
988         .map(|(index, _)| Parameter(index as u32))
989         .collect();
990
991     identify_constrained_generic_params(tcx, ty_predicates, None, &mut constrained_parameters);
992
993     for (index, _) in variances.iter().enumerate() {
994         if constrained_parameters.contains(&Parameter(index as u32)) {
995             continue;
996         }
997
998         let param = &hir_generics.params[index];
999
1000         match param.name {
1001             hir::ParamName::Error => {}
1002             _ => report_bivariance(tcx, param.span, param.name.ident().name),
1003         }
1004     }
1005 }
1006
1007 fn report_bivariance(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) {
1008     let mut err = error_392(tcx, span, param_name);
1009
1010     let suggested_marker_id = tcx.lang_items().phantom_data();
1011     // Help is available only in presence of lang items.
1012     let msg = if let Some(def_id) = suggested_marker_id {
1013         format!(
1014             "consider removing `{}`, referring to it in a field, or using a marker such as `{}`",
1015             param_name,
1016             tcx.def_path_str(def_id),
1017         )
1018     } else {
1019         format!("consider removing `{}` or referring to it in a field", param_name)
1020     };
1021     err.help(&msg);
1022     err.emit();
1023 }
1024
1025 /// Feature gates RFC 2056 -- trivial bounds, checking for global bounds that
1026 /// aren't true.
1027 fn check_false_global_bounds(fcx: &FnCtxt<'_, '_>, span: Span, id: hir::HirId) {
1028     let empty_env = ty::ParamEnv::empty();
1029
1030     let def_id = fcx.tcx.hir().local_def_id(id);
1031     let predicates = fcx.tcx.predicates_of(def_id).predicates.iter().map(|(p, _)| *p).collect();
1032     // Check elaborated bounds.
1033     let implied_obligations = traits::elaborate_predicates(fcx.tcx, predicates);
1034
1035     for pred in implied_obligations {
1036         // Match the existing behavior.
1037         if pred.is_global() && !pred.has_late_bound_regions() {
1038             let pred = fcx.normalize_associated_types_in(span, &pred);
1039             let obligation = traits::Obligation::new(
1040                 traits::ObligationCause::new(span, id, traits::TrivialBound),
1041                 empty_env,
1042                 pred,
1043             );
1044             fcx.register_predicate(obligation);
1045         }
1046     }
1047
1048     fcx.select_all_obligations_or_error();
1049 }
1050
1051 pub struct CheckTypeWellFormedVisitor<'tcx> {
1052     tcx: TyCtxt<'tcx>,
1053 }
1054
1055 impl CheckTypeWellFormedVisitor<'tcx> {
1056     pub fn new(tcx: TyCtxt<'tcx>) -> CheckTypeWellFormedVisitor<'tcx> {
1057         CheckTypeWellFormedVisitor { tcx }
1058     }
1059 }
1060
1061 impl ParItemLikeVisitor<'tcx> for CheckTypeWellFormedVisitor<'tcx> {
1062     fn visit_item(&self, i: &'tcx hir::Item<'tcx>) {
1063         debug!("visit_item: {:?}", i);
1064         let def_id = self.tcx.hir().local_def_id(i.hir_id);
1065         self.tcx.ensure().check_item_well_formed(def_id);
1066     }
1067
1068     fn visit_trait_item(&self, trait_item: &'tcx hir::TraitItem<'tcx>) {
1069         debug!("visit_trait_item: {:?}", trait_item);
1070         let def_id = self.tcx.hir().local_def_id(trait_item.hir_id);
1071         self.tcx.ensure().check_trait_item_well_formed(def_id);
1072     }
1073
1074     fn visit_impl_item(&self, impl_item: &'tcx hir::ImplItem<'tcx>) {
1075         debug!("visit_impl_item: {:?}", impl_item);
1076         let def_id = self.tcx.hir().local_def_id(impl_item.hir_id);
1077         self.tcx.ensure().check_impl_item_well_formed(def_id);
1078     }
1079 }
1080
1081 ///////////////////////////////////////////////////////////////////////////
1082 // ADT
1083
1084 struct AdtVariant<'tcx> {
1085     fields: Vec<AdtField<'tcx>>,
1086 }
1087
1088 struct AdtField<'tcx> {
1089     ty: Ty<'tcx>,
1090     span: Span,
1091 }
1092
1093 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
1094     fn non_enum_variant(&self, struct_def: &hir::VariantData<'_>) -> AdtVariant<'tcx> {
1095         let fields = struct_def
1096             .fields()
1097             .iter()
1098             .map(|field| {
1099                 let field_ty = self.tcx.type_of(self.tcx.hir().local_def_id(field.hir_id));
1100                 let field_ty = self.normalize_associated_types_in(field.span, &field_ty);
1101                 let field_ty = self.resolve_vars_if_possible(&field_ty);
1102                 debug!("non_enum_variant: type of field {:?} is {:?}", field, field_ty);
1103                 AdtField { ty: field_ty, span: field.span }
1104             })
1105             .collect();
1106         AdtVariant { fields }
1107     }
1108
1109     fn enum_variants(&self, enum_def: &hir::EnumDef<'_>) -> Vec<AdtVariant<'tcx>> {
1110         enum_def.variants.iter().map(|variant| self.non_enum_variant(&variant.data)).collect()
1111     }
1112
1113     fn impl_implied_bounds(&self, impl_def_id: DefId, span: Span) -> Vec<Ty<'tcx>> {
1114         match self.tcx.impl_trait_ref(impl_def_id) {
1115             Some(ref trait_ref) => {
1116                 // Trait impl: take implied bounds from all types that
1117                 // appear in the trait reference.
1118                 let trait_ref = self.normalize_associated_types_in(span, trait_ref);
1119                 trait_ref.substs.types().collect()
1120             }
1121
1122             None => {
1123                 // Inherent impl: take implied bounds from the `self` type.
1124                 let self_ty = self.tcx.type_of(impl_def_id);
1125                 let self_ty = self.normalize_associated_types_in(span, &self_ty);
1126                 vec![self_ty]
1127             }
1128         }
1129     }
1130 }
1131
1132 fn error_392(tcx: TyCtxt<'_>, span: Span, param_name: ast::Name) -> DiagnosticBuilder<'_> {
1133     let mut err =
1134         struct_span_err!(tcx.sess, span, E0392, "parameter `{}` is never used", param_name);
1135     err.span_label(span, "unused parameter");
1136     err
1137 }