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