]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/wfcheck.rs
Auto merge of #30036 - mitaa:doc_id, r=alexcrichton
[rust.git] / src / librustc_typeck / check / wfcheck.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use astconv::AstConv;
12 use check::{FnCtxt, Inherited, blank_fn_ctxt, regionck};
13 use constrained_type_params::{identify_constrained_type_params, Parameter};
14 use CrateCtxt;
15 use middle::def_id::DefId;
16 use middle::subst::{self, TypeSpace, FnSpace, ParamSpace, SelfSpace};
17 use middle::traits;
18 use middle::ty::{self, Ty};
19 use middle::ty::fold::{TypeFolder};
20
21 use std::cell::RefCell;
22 use std::collections::HashSet;
23 use std::rc::Rc;
24 use syntax::ast;
25 use syntax::codemap::{Span};
26 use syntax::parse::token::{special_idents};
27 use rustc_front::intravisit::{self, Visitor};
28 use rustc_front::hir;
29
30 pub struct CheckTypeWellFormedVisitor<'ccx, 'tcx:'ccx> {
31     ccx: &'ccx CrateCtxt<'ccx, 'tcx>,
32     code: traits::ObligationCauseCode<'tcx>,
33 }
34
35 impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
36     pub fn new(ccx: &'ccx CrateCtxt<'ccx, 'tcx>)
37                -> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
38         CheckTypeWellFormedVisitor {
39             ccx: ccx,
40             code: traits::ObligationCauseCode::RFC1214(
41                 Rc::new(traits::ObligationCauseCode::MiscObligation))
42         }
43     }
44
45     fn tcx(&self) -> &ty::ctxt<'tcx> {
46         self.ccx.tcx
47     }
48
49     /// Checks that the field types (in a struct def'n) or argument types (in an enum def'n) are
50     /// well-formed, meaning that they do not require any constraints not declared in the struct
51     /// definition itself. For example, this definition would be illegal:
52     ///
53     ///     struct Ref<'a, T> { x: &'a T }
54     ///
55     /// because the type did not declare that `T:'a`.
56     ///
57     /// We do this check as a pre-pass before checking fn bodies because if these constraints are
58     /// not included it frequently leads to confusing errors in fn bodies. So it's better to check
59     /// the types first.
60     fn check_item_well_formed(&mut self, item: &hir::Item) {
61         let ccx = self.ccx;
62         debug!("check_item_well_formed(it.id={}, it.name={})",
63                item.id,
64                ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(item.id)));
65
66         match item.node {
67             /// Right now we check that every default trait implementation
68             /// has an implementation of itself. Basically, a case like:
69             ///
70             /// `impl Trait for T {}`
71             ///
72             /// has a requirement of `T: Trait` which was required for default
73             /// method implementations. Although this could be improved now that
74             /// there's a better infrastructure in place for this, it's being left
75             /// for a follow-up work.
76             ///
77             /// Since there's such a requirement, we need to check *just* positive
78             /// implementations, otherwise things like:
79             ///
80             /// impl !Send for T {}
81             ///
82             /// won't be allowed unless there's an *explicit* implementation of `Send`
83             /// for `T`
84             hir::ItemImpl(_, hir::ImplPolarity::Positive, _,
85                           ref trait_ref, ref self_ty, _) => {
86                 self.check_impl(item, self_ty, trait_ref);
87             }
88             hir::ItemImpl(_, hir::ImplPolarity::Negative, _, Some(_), _, _) => {
89                 // FIXME(#27579) what amount of WF checking do we need for neg impls?
90
91                 let trait_ref = ccx.tcx.impl_trait_ref(ccx.tcx.map.local_def_id(item.id)).unwrap();
92                 ccx.tcx.populate_implementations_for_trait_if_necessary(trait_ref.def_id);
93                 match ccx.tcx.lang_items.to_builtin_kind(trait_ref.def_id) {
94                     Some(ty::BoundSend) | Some(ty::BoundSync) => {}
95                     Some(_) | None => {
96                         if !ccx.tcx.trait_has_default_impl(trait_ref.def_id) {
97                             error_192(ccx, item.span);
98                         }
99                     }
100                 }
101             }
102             hir::ItemFn(_, _, _, _, _, ref body) => {
103                 self.check_item_fn(item, body);
104             }
105             hir::ItemStatic(..) => {
106                 self.check_item_type(item);
107             }
108             hir::ItemConst(..) => {
109                 self.check_item_type(item);
110             }
111             hir::ItemStruct(ref struct_def, ref ast_generics) => {
112                 self.check_type_defn(item, |fcx| {
113                     vec![struct_variant(fcx, struct_def)]
114                 });
115
116                 self.check_variances_for_type_defn(item, ast_generics);
117             }
118             hir::ItemEnum(ref enum_def, ref ast_generics) => {
119                 self.check_type_defn(item, |fcx| {
120                     enum_variants(fcx, enum_def)
121                 });
122
123                 self.check_variances_for_type_defn(item, ast_generics);
124             }
125             hir::ItemTrait(_, _, _, ref items) => {
126                 self.check_trait(item, items);
127             }
128             _ => {}
129         }
130     }
131
132     fn check_trait_or_impl_item(&mut self, item_id: ast::NodeId, span: Span) {
133         let code = self.code.clone();
134         self.with_fcx(item_id, span, |fcx, this| {
135             let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
136             let free_id = fcx.inh.infcx.parameter_environment.free_id;
137
138             let item = fcx.tcx().impl_or_trait_item(fcx.tcx().map.local_def_id(item_id));
139
140             let mut implied_bounds = match item.container() {
141                 ty::TraitContainer(_) => vec![],
142                 ty::ImplContainer(def_id) => impl_implied_bounds(fcx, def_id, span)
143             };
144
145             match item {
146                 ty::ConstTraitItem(assoc_const) => {
147                     let ty = fcx.instantiate_type_scheme(span, free_substs, &assoc_const.ty);
148                     fcx.register_wf_obligation(ty, span, code.clone());
149                 }
150                 ty::MethodTraitItem(method) => {
151                     reject_shadowing_type_parameters(fcx.tcx(), span, &method.generics);
152                     let method_ty = fcx.instantiate_type_scheme(span, free_substs, &method.fty);
153                     let predicates = fcx.instantiate_bounds(span, free_substs, &method.predicates);
154                     this.check_fn_or_method(fcx, span, &method_ty, &predicates,
155                                             free_id, &mut implied_bounds);
156                 }
157                 ty::TypeTraitItem(assoc_type) => {
158                     if let Some(ref ty) = assoc_type.ty {
159                         let ty = fcx.instantiate_type_scheme(span, free_substs, ty);
160                         fcx.register_wf_obligation(ty, span, code.clone());
161                     }
162                 }
163             }
164
165             implied_bounds
166         })
167     }
168
169     fn with_item_fcx<F>(&mut self, item: &hir::Item, f: F) where
170         F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>,
171                            &mut CheckTypeWellFormedVisitor<'ccx,'tcx>) -> Vec<Ty<'tcx>>,
172     {
173         self.with_fcx(item.id, item.span, f)
174     }
175
176     fn with_fcx<F>(&mut self, id: ast::NodeId, span: Span, mut f: F) where
177         F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>,
178                            &mut CheckTypeWellFormedVisitor<'ccx,'tcx>) -> Vec<Ty<'tcx>>,
179     {
180         let ccx = self.ccx;
181         let param_env = ty::ParameterEnvironment::for_item(ccx.tcx, id);
182         let tables = RefCell::new(ty::Tables::empty());
183         let inh = Inherited::new(ccx.tcx, &tables, param_env);
184         let fcx = blank_fn_ctxt(ccx, &inh, ty::FnDiverging, id);
185         let wf_tys = f(&fcx, self);
186         fcx.select_all_obligations_or_error();
187         regionck::regionck_item(&fcx, id, span, &wf_tys);
188     }
189
190     /// In a type definition, we check that to ensure that the types of the fields are well-formed.
191     fn check_type_defn<F>(&mut self, item: &hir::Item, mut lookup_fields: F) where
192         F: for<'fcx> FnMut(&FnCtxt<'fcx, 'tcx>) -> Vec<AdtVariant<'tcx>>,
193     {
194         self.with_item_fcx(item, |fcx, this| {
195             let variants = lookup_fields(fcx);
196
197             for variant in &variants {
198                 // For DST, all intermediate types must be sized.
199                 if let Some((_, fields)) = variant.fields.split_last() {
200                     for field in fields {
201                         fcx.register_builtin_bound(
202                             field.ty,
203                             ty::BoundSized,
204                             traits::ObligationCause::new(field.span,
205                                                          fcx.body_id,
206                                                          traits::FieldSized));
207                     }
208                 }
209
210                 // All field types must be well-formed.
211                 for field in &variant.fields {
212                     fcx.register_wf_obligation(field.ty, field.span, this.code.clone())
213                 }
214             }
215
216             let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
217             let predicates = fcx.tcx().lookup_predicates(fcx.tcx().map.local_def_id(item.id));
218             let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
219             this.check_where_clauses(fcx, item.span, &predicates);
220
221             vec![] // no implied bounds in a struct def'n
222         });
223     }
224
225     fn check_trait(&mut self,
226                    item: &hir::Item,
227                    items: &[hir::TraitItem])
228     {
229         let trait_def_id = self.tcx().map.local_def_id(item.id);
230
231         if self.ccx.tcx.trait_has_default_impl(trait_def_id) {
232             if !items.is_empty() {
233                 error_380(self.ccx, item.span);
234             }
235         }
236
237         self.with_item_fcx(item, |fcx, this| {
238             let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
239             let predicates = fcx.tcx().lookup_predicates(trait_def_id);
240             let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
241             this.check_where_clauses(fcx, item.span, &predicates);
242             vec![]
243         });
244     }
245
246     fn check_item_fn(&mut self,
247                      item: &hir::Item,
248                      body: &hir::Block)
249     {
250         self.with_item_fcx(item, |fcx, this| {
251             let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
252             let type_scheme = fcx.tcx().lookup_item_type(fcx.tcx().map.local_def_id(item.id));
253             let item_ty = fcx.instantiate_type_scheme(item.span, free_substs, &type_scheme.ty);
254             let bare_fn_ty = match item_ty.sty {
255                 ty::TyBareFn(_, ref bare_fn_ty) => bare_fn_ty,
256                 _ => {
257                     this.tcx().sess.span_bug(item.span, "Fn item without bare fn type");
258                 }
259             };
260
261             let predicates = fcx.tcx().lookup_predicates(fcx.tcx().map.local_def_id(item.id));
262             let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
263
264             let mut implied_bounds = vec![];
265             this.check_fn_or_method(fcx, item.span, bare_fn_ty, &predicates,
266                                     body.id, &mut implied_bounds);
267             implied_bounds
268         })
269     }
270
271     fn check_item_type(&mut self,
272                        item: &hir::Item)
273     {
274         debug!("check_item_type: {:?}", item);
275
276         self.with_item_fcx(item, |fcx, this| {
277             let type_scheme = fcx.tcx().lookup_item_type(fcx.tcx().map.local_def_id(item.id));
278             let item_ty = fcx.instantiate_type_scheme(item.span,
279                                                       &fcx.inh
280                                                           .infcx
281                                                           .parameter_environment
282                                                           .free_substs,
283                                                       &type_scheme.ty);
284
285             fcx.register_wf_obligation(item_ty, item.span, this.code.clone());
286
287             vec![] // no implied bounds in a const etc
288         });
289     }
290
291     fn check_impl(&mut self,
292                   item: &hir::Item,
293                   ast_self_ty: &hir::Ty,
294                   ast_trait_ref: &Option<hir::TraitRef>)
295     {
296         debug!("check_impl: {:?}", item);
297
298         self.with_item_fcx(item, |fcx, this| {
299             let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
300             let item_def_id = fcx.tcx().map.local_def_id(item.id);
301
302             match *ast_trait_ref {
303                 Some(ref ast_trait_ref) => {
304                     let trait_ref = fcx.tcx().impl_trait_ref(item_def_id).unwrap();
305                     let trait_ref =
306                         fcx.instantiate_type_scheme(
307                             ast_trait_ref.path.span, free_substs, &trait_ref);
308                     let obligations =
309                         ty::wf::trait_obligations(fcx.infcx(),
310                                                   fcx.body_id,
311                                                   &trait_ref,
312                                                   ast_trait_ref.path.span,
313                                                   true);
314                     for obligation in obligations {
315                         fcx.register_predicate(obligation);
316                     }
317                 }
318                 None => {
319                     let self_ty = fcx.tcx().node_id_to_type(item.id);
320                     let self_ty = fcx.instantiate_type_scheme(item.span, free_substs, &self_ty);
321                     fcx.register_wf_obligation(self_ty, ast_self_ty.span, this.code.clone());
322                 }
323             }
324
325             let predicates = fcx.tcx().lookup_predicates(item_def_id);
326             let predicates = fcx.instantiate_bounds(item.span, free_substs, &predicates);
327             this.check_where_clauses(fcx, item.span, &predicates);
328
329             impl_implied_bounds(fcx, fcx.tcx().map.local_def_id(item.id), item.span)
330         });
331     }
332
333     fn check_where_clauses<'fcx>(&mut self,
334                                  fcx: &FnCtxt<'fcx,'tcx>,
335                                  span: Span,
336                                  predicates: &ty::InstantiatedPredicates<'tcx>)
337     {
338         let obligations =
339             predicates.predicates
340                       .iter()
341                       .flat_map(|p| ty::wf::predicate_obligations(fcx.infcx(),
342                                                                   fcx.body_id,
343                                                                   p,
344                                                                   span,
345                                                                   true));
346
347         for obligation in obligations {
348             fcx.register_predicate(obligation);
349         }
350     }
351
352     fn check_fn_or_method<'fcx>(&mut self,
353                                 fcx: &FnCtxt<'fcx,'tcx>,
354                                 span: Span,
355                                 fty: &ty::BareFnTy<'tcx>,
356                                 predicates: &ty::InstantiatedPredicates<'tcx>,
357                                 free_id: ast::NodeId,
358                                 implied_bounds: &mut Vec<Ty<'tcx>>)
359     {
360         let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
361         let fty = fcx.instantiate_type_scheme(span, free_substs, fty);
362         let free_id_outlive = fcx.tcx().region_maps.item_extent(free_id);
363         let sig = fcx.tcx().liberate_late_bound_regions(free_id_outlive, &fty.sig);
364
365         for &input_ty in &sig.inputs {
366             fcx.register_wf_obligation(input_ty, span, self.code.clone());
367         }
368         implied_bounds.extend(sig.inputs);
369
370         match sig.output {
371             ty::FnConverging(output) => {
372                 fcx.register_wf_obligation(output, span, self.code.clone());
373
374                 // FIXME(#25759) return types should not be implied bounds
375                 implied_bounds.push(output);
376             }
377             ty::FnDiverging => { }
378         }
379
380         self.check_where_clauses(fcx, span, predicates);
381     }
382
383     fn check_variances_for_type_defn(&self,
384                                      item: &hir::Item,
385                                      ast_generics: &hir::Generics)
386     {
387         let item_def_id = self.tcx().map.local_def_id(item.id);
388         let ty_predicates = self.tcx().lookup_predicates(item_def_id);
389         let variances = self.tcx().item_variances(item_def_id);
390
391         let mut constrained_parameters: HashSet<_> =
392             variances.types
393                      .iter_enumerated()
394                      .filter(|&(_, _, &variance)| variance != ty::Bivariant)
395                      .map(|(space, index, _)| self.param_ty(ast_generics, space, index))
396                      .map(|p| Parameter::Type(p))
397                      .collect();
398
399         identify_constrained_type_params(self.tcx(),
400                                          ty_predicates.predicates.as_slice(),
401                                          None,
402                                          &mut constrained_parameters);
403
404         for (space, index, _) in variances.types.iter_enumerated() {
405             let param_ty = self.param_ty(ast_generics, space, index);
406             if constrained_parameters.contains(&Parameter::Type(param_ty)) {
407                 continue;
408             }
409             let span = self.ty_param_span(ast_generics, item, space, index);
410             self.report_bivariance(span, param_ty.name);
411         }
412
413         for (space, index, &variance) in variances.regions.iter_enumerated() {
414             if variance != ty::Bivariant {
415                 continue;
416             }
417
418             assert_eq!(space, TypeSpace);
419             let span = ast_generics.lifetimes[index].lifetime.span;
420             let name = ast_generics.lifetimes[index].lifetime.name;
421             self.report_bivariance(span, name);
422         }
423     }
424
425     fn param_ty(&self,
426                 ast_generics: &hir::Generics,
427                 space: ParamSpace,
428                 index: usize)
429                 -> ty::ParamTy
430     {
431         let name = match space {
432             TypeSpace => ast_generics.ty_params[index].name,
433             SelfSpace => special_idents::type_self.name,
434             FnSpace => self.tcx().sess.bug("Fn space occupied?"),
435         };
436
437         ty::ParamTy { space: space, idx: index as u32, name: name }
438     }
439
440     fn ty_param_span(&self,
441                      ast_generics: &hir::Generics,
442                      item: &hir::Item,
443                      space: ParamSpace,
444                      index: usize)
445                      -> Span
446     {
447         match space {
448             TypeSpace => ast_generics.ty_params[index].span,
449             SelfSpace => item.span,
450             FnSpace => self.tcx().sess.span_bug(item.span, "Fn space occupied?"),
451         }
452     }
453
454     fn report_bivariance(&self,
455                          span: Span,
456                          param_name: ast::Name)
457     {
458         error_392(self.tcx(), span, param_name);
459
460         let suggested_marker_id = self.tcx().lang_items.phantom_data();
461         match suggested_marker_id {
462             Some(def_id) => {
463                 self.tcx().sess.fileline_help(
464                     span,
465                     &format!("consider removing `{}` or using a marker such as `{}`",
466                              param_name,
467                              self.tcx().item_path_str(def_id)));
468             }
469             None => {
470                 // no lang items, no help!
471             }
472         }
473     }
474 }
475
476 fn reject_shadowing_type_parameters<'tcx>(tcx: &ty::ctxt<'tcx>,
477                                           span: Span,
478                                           generics: &ty::Generics<'tcx>) {
479     let impl_params = generics.types.get_slice(subst::TypeSpace).iter()
480         .map(|tp| tp.name).collect::<HashSet<_>>();
481
482     for method_param in generics.types.get_slice(subst::FnSpace) {
483         if impl_params.contains(&method_param.name) {
484             error_194(tcx, span, method_param.name);
485         }
486     }
487 }
488
489 impl<'ccx, 'tcx, 'v> Visitor<'v> for CheckTypeWellFormedVisitor<'ccx, 'tcx> {
490     fn visit_item(&mut self, i: &hir::Item) {
491         debug!("visit_item: {:?}", i);
492         self.check_item_well_formed(i);
493         intravisit::walk_item(self, i);
494     }
495
496     fn visit_trait_item(&mut self, trait_item: &'v hir::TraitItem) {
497         debug!("visit_trait_item: {:?}", trait_item);
498         self.check_trait_or_impl_item(trait_item.id, trait_item.span);
499         intravisit::walk_trait_item(self, trait_item)
500     }
501
502     fn visit_impl_item(&mut self, impl_item: &'v hir::ImplItem) {
503         debug!("visit_impl_item: {:?}", impl_item);
504         self.check_trait_or_impl_item(impl_item.id, impl_item.span);
505         intravisit::walk_impl_item(self, impl_item)
506     }
507 }
508
509 ///////////////////////////////////////////////////////////////////////////
510 // ADT
511
512 struct AdtVariant<'tcx> {
513     fields: Vec<AdtField<'tcx>>,
514 }
515
516 struct AdtField<'tcx> {
517     ty: Ty<'tcx>,
518     span: Span,
519 }
520
521 fn struct_variant<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
522                             struct_def: &hir::VariantData)
523                             -> AdtVariant<'tcx> {
524     let fields =
525         struct_def.fields().iter()
526         .map(|field| {
527             let field_ty = fcx.tcx().node_id_to_type(field.node.id);
528             let field_ty = fcx.instantiate_type_scheme(field.span,
529                                                        &fcx.inh
530                                                            .infcx
531                                                            .parameter_environment
532                                                            .free_substs,
533                                                        &field_ty);
534             AdtField { ty: field_ty, span: field.span }
535         })
536         .collect();
537     AdtVariant { fields: fields }
538 }
539
540 fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
541                            enum_def: &hir::EnumDef)
542                            -> Vec<AdtVariant<'tcx>> {
543     enum_def.variants.iter()
544         .map(|variant| struct_variant(fcx, &variant.node.data))
545         .collect()
546 }
547
548 fn impl_implied_bounds<'fcx,'tcx>(fcx: &FnCtxt<'fcx, 'tcx>,
549                                   impl_def_id: DefId,
550                                   span: Span)
551                                   -> Vec<Ty<'tcx>>
552 {
553     let free_substs = &fcx.inh.infcx.parameter_environment.free_substs;
554     match fcx.tcx().impl_trait_ref(impl_def_id) {
555         Some(ref trait_ref) => {
556             // Trait impl: take implied bounds from all types that
557             // appear in the trait reference.
558             let trait_ref = fcx.instantiate_type_scheme(span, free_substs, trait_ref);
559             trait_ref.substs.types.as_slice().to_vec()
560         }
561
562         None => {
563             // Inherent impl: take implied bounds from the self type.
564             let self_ty = fcx.tcx().lookup_item_type(impl_def_id).ty;
565             let self_ty = fcx.instantiate_type_scheme(span, free_substs, &self_ty);
566             vec![self_ty]
567         }
568     }
569 }
570
571 pub fn error_192<'ccx,'tcx>(ccx: &'ccx CrateCtxt<'ccx, 'tcx>, span: Span) {
572     span_err!(ccx.tcx.sess, span, E0192,
573               "negative impls are only allowed for traits with \
574                default impls (e.g., `Send` and `Sync`)")
575 }
576
577 pub fn error_380<'ccx,'tcx>(ccx: &'ccx CrateCtxt<'ccx, 'tcx>, span: Span) {
578     span_err!(ccx.tcx.sess, span, E0380,
579               "traits with default impls (`e.g. unsafe impl \
580                Trait for ..`) must have no methods or associated items")
581 }
582
583 pub fn error_392<'tcx>(tcx: &ty::ctxt<'tcx>, span: Span, param_name: ast::Name)  {
584     span_err!(tcx.sess, span, E0392,
585               "parameter `{}` is never used", param_name);
586 }
587
588 pub fn error_194<'tcx>(tcx: &ty::ctxt<'tcx>, span: Span, name: ast::Name) {
589     span_err!(tcx.sess, span, E0194,
590               "type parameter `{}` shadows another type parameter of the same name",
591               name);
592 }