]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
6423d65a4c23fc7175ee598ef365ae7ed90c3ce1
[rust.git] / src / librustc_lint / builtin.rs
1 // Copyright 2012-2015 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 //! Lints in the Rust compiler.
12 //!
13 //! This contains lints which can feasibly be implemented as their own
14 //! AST visitor. Also see `rustc::lint::builtin`, which contains the
15 //! definitions of lints that are emitted directly inside the main
16 //! compiler.
17 //!
18 //! To add a new lint to rustc, declare it here using `declare_lint!()`.
19 //! Then add code to emit the new lint in the appropriate circumstances.
20 //! You can do that in an existing `LintPass` if it makes sense, or in a
21 //! new `LintPass`, or using `Session::add_lint` elsewhere in the
22 //! compiler. Only do the latter if the check can't be written cleanly as a
23 //! `LintPass` (also, note that such lints will need to be defined in
24 //! `rustc::lint::builtin`, not here).
25 //!
26 //! If you define a new `LintPass`, you will also need to add it to the
27 //! `add_builtin!` or `add_builtin_with_new!` invocation in `lib.rs`.
28 //! Use the former for unit-like structs and the latter for structs with
29 //! a `pub fn new()`.
30
31 use rustc::hir::def::Def;
32 use rustc::hir::def_id::DefId;
33 use rustc::cfg;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{self, Ty, TyCtxt};
36 use rustc::traits::{self, Reveal};
37 use rustc::hir::map as hir_map;
38 use util::nodemap::NodeSet;
39 use lint::{Level, LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
41
42 use std::collections::HashSet;
43
44 use syntax::ast;
45 use syntax::attr;
46 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
47 use syntax_pos::Span;
48 use syntax::symbol::keywords;
49
50 use rustc::hir::{self, PatKind};
51 use rustc::hir::intravisit::FnKind;
52
53 use bad_style::{MethodLateContext, method_context};
54
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
57
58 declare_lint! {
59     WHILE_TRUE,
60     Warn,
61     "suggest using `loop { }` instead of `while true { }`"
62 }
63
64 #[derive(Copy, Clone)]
65 pub struct WhileTrue;
66
67 impl LintPass for WhileTrue {
68     fn get_lints(&self) -> LintArray {
69         lint_array!(WHILE_TRUE)
70     }
71 }
72
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
74     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
75         if let hir::ExprWhile(ref cond, ..) = e.node {
76             if let hir::ExprLit(ref lit) = cond.node {
77                 if let ast::LitKind::Bool(true) = lit.node {
78                     cx.span_lint(WHILE_TRUE,
79                                  e.span,
80                                  "denote infinite loops with loop { ... }");
81                 }
82             }
83         }
84     }
85 }
86
87 declare_lint! {
88     BOX_POINTERS,
89     Allow,
90     "use of owned (Box type) heap memory"
91 }
92
93 #[derive(Copy, Clone)]
94 pub struct BoxPointers;
95
96 impl BoxPointers {
97     fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
98         for leaf_ty in ty.walk() {
99             if leaf_ty.is_box() {
100                 let m = format!("type uses owned (Box type) pointers: {}", ty);
101                 cx.span_lint(BOX_POINTERS, span, &m);
102             }
103         }
104     }
105 }
106
107 impl LintPass for BoxPointers {
108     fn get_lints(&self) -> LintArray {
109         lint_array!(BOX_POINTERS)
110     }
111 }
112
113 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
114     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
115         match it.node {
116             hir::ItemFn(..) |
117             hir::ItemTy(..) |
118             hir::ItemEnum(..) |
119             hir::ItemStruct(..) |
120             hir::ItemUnion(..) => {
121                 let def_id = cx.tcx.hir.local_def_id(it.id);
122                 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
123             }
124             _ => ()
125         }
126
127         // If it's a struct, we also have to check the fields' types
128         match it.node {
129             hir::ItemStruct(ref struct_def, _) |
130             hir::ItemUnion(ref struct_def, _) => {
131                 for struct_field in struct_def.fields() {
132                     let def_id = cx.tcx.hir.local_def_id(struct_field.id);
133                     self.check_heap_type(cx, struct_field.span,
134                                          cx.tcx.type_of(def_id));
135                 }
136             }
137             _ => (),
138         }
139     }
140
141     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
142         let ty = cx.tables.node_id_to_type(e.id);
143         self.check_heap_type(cx, e.span, ty);
144     }
145 }
146
147 declare_lint! {
148     NON_SHORTHAND_FIELD_PATTERNS,
149     Warn,
150     "using `Struct { x: x }` instead of `Struct { x }`"
151 }
152
153 #[derive(Copy, Clone)]
154 pub struct NonShorthandFieldPatterns;
155
156 impl LintPass for NonShorthandFieldPatterns {
157     fn get_lints(&self) -> LintArray {
158         lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
159     }
160 }
161
162 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
163     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
164         if let PatKind::Struct(_, ref field_pats, _) = pat.node {
165             for fieldpat in field_pats {
166                 if fieldpat.node.is_shorthand {
167                     continue;
168                 }
169                 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
170                     if ident.node == fieldpat.node.name {
171                         cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
172                                      fieldpat.span,
173                                      &format!("the `{}:` in this pattern is redundant and can \
174                                               be removed",
175                                               ident.node))
176                     }
177                 }
178             }
179         }
180     }
181 }
182
183 declare_lint! {
184     UNSAFE_CODE,
185     Allow,
186     "usage of `unsafe` code"
187 }
188
189 #[derive(Copy, Clone)]
190 pub struct UnsafeCode;
191
192 impl LintPass for UnsafeCode {
193     fn get_lints(&self) -> LintArray {
194         lint_array!(UNSAFE_CODE)
195     }
196 }
197
198 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
199     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
200         if let hir::ExprBlock(ref blk) = e.node {
201             // Don't warn about generated blocks, that'll just pollute the output.
202             if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
203                 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
204             }
205         }
206     }
207
208     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
209         match it.node {
210             hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
211                 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait")
212             }
213
214             hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
215                 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait")
216             }
217
218             _ => return,
219         }
220     }
221
222     fn check_fn(&mut self,
223                 cx: &LateContext,
224                 fk: FnKind<'tcx>,
225                 _: &hir::FnDecl,
226                 _: &hir::Body,
227                 span: Span,
228                 _: ast::NodeId) {
229         match fk {
230             FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
231                 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function")
232             }
233
234             FnKind::Method(_, sig, ..) => {
235                 if sig.unsafety == hir::Unsafety::Unsafe {
236                     cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
237                 }
238             }
239
240             _ => (),
241         }
242     }
243
244     fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
245         if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
246             if sig.unsafety == hir::Unsafety::Unsafe {
247                 cx.span_lint(UNSAFE_CODE,
248                              item.span,
249                              "declaration of an `unsafe` method")
250             }
251         }
252     }
253 }
254
255 declare_lint! {
256     MISSING_DOCS,
257     Allow,
258     "detects missing documentation for public members"
259 }
260
261 pub struct MissingDoc {
262     /// Stack of IDs of struct definitions.
263     struct_def_stack: Vec<ast::NodeId>,
264
265     /// True if inside variant definition
266     in_variant: bool,
267
268     /// Stack of whether #[doc(hidden)] is set
269     /// at each level which has lint attributes.
270     doc_hidden_stack: Vec<bool>,
271
272     /// Private traits or trait items that leaked through. Don't check their methods.
273     private_traits: HashSet<ast::NodeId>,
274 }
275
276 impl MissingDoc {
277     pub fn new() -> MissingDoc {
278         MissingDoc {
279             struct_def_stack: vec![],
280             in_variant: false,
281             doc_hidden_stack: vec![false],
282             private_traits: HashSet::new(),
283         }
284     }
285
286     fn doc_hidden(&self) -> bool {
287         *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
288     }
289
290     fn check_missing_docs_attrs(&self,
291                                 cx: &LateContext,
292                                 id: Option<ast::NodeId>,
293                                 attrs: &[ast::Attribute],
294                                 sp: Span,
295                                 desc: &'static str) {
296         // If we're building a test harness, then warning about
297         // documentation is probably not really relevant right now.
298         if cx.sess().opts.test {
299             return;
300         }
301
302         // `#[doc(hidden)]` disables missing_docs check.
303         if self.doc_hidden() {
304             return;
305         }
306
307         // Only check publicly-visible items, using the result from the privacy pass.
308         // It's an option so the crate root can also use this function (it doesn't
309         // have a NodeId).
310         if let Some(id) = id {
311             if !cx.access_levels.is_exported(id) {
312                 return;
313             }
314         }
315
316         let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
317         if !has_doc {
318             cx.span_lint(MISSING_DOCS,
319                          sp,
320                          &format!("missing documentation for {}", desc));
321         }
322     }
323 }
324
325 impl LintPass for MissingDoc {
326     fn get_lints(&self) -> LintArray {
327         lint_array!(MISSING_DOCS)
328     }
329 }
330
331 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
332     fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
333         let doc_hidden = self.doc_hidden() ||
334                          attrs.iter().any(|attr| {
335             attr.check_name("doc") &&
336             match attr.meta_item_list() {
337                 None => false,
338                 Some(l) => attr::list_contains_name(&l, "hidden"),
339             }
340         });
341         self.doc_hidden_stack.push(doc_hidden);
342     }
343
344     fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
345         self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
346     }
347
348     fn check_struct_def(&mut self,
349                         _: &LateContext,
350                         _: &hir::VariantData,
351                         _: ast::Name,
352                         _: &hir::Generics,
353                         item_id: ast::NodeId) {
354         self.struct_def_stack.push(item_id);
355     }
356
357     fn check_struct_def_post(&mut self,
358                              _: &LateContext,
359                              _: &hir::VariantData,
360                              _: ast::Name,
361                              _: &hir::Generics,
362                              item_id: ast::NodeId) {
363         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
364         assert!(popped == item_id);
365     }
366
367     fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
368         self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
369     }
370
371     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
372         let desc = match it.node {
373             hir::ItemFn(..) => "a function",
374             hir::ItemMod(..) => "a module",
375             hir::ItemEnum(..) => "an enum",
376             hir::ItemStruct(..) => "a struct",
377             hir::ItemUnion(..) => "a union",
378             hir::ItemTrait(.., ref trait_item_refs) => {
379                 // Issue #11592, traits are always considered exported, even when private.
380                 if it.vis == hir::Visibility::Inherited {
381                     self.private_traits.insert(it.id);
382                     for trait_item_ref in trait_item_refs {
383                         self.private_traits.insert(trait_item_ref.id.node_id);
384                     }
385                     return;
386                 }
387                 "a trait"
388             }
389             hir::ItemTy(..) => "a type alias",
390             hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
391                 // If the trait is private, add the impl items to private_traits so they don't get
392                 // reported for missing docs.
393                 let real_trait = trait_ref.path.def.def_id();
394                 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
395                     match cx.tcx.hir.find(node_id) {
396                         Some(hir_map::NodeItem(item)) => {
397                             if item.vis == hir::Visibility::Inherited {
398                                 for impl_item_ref in impl_item_refs {
399                                     self.private_traits.insert(impl_item_ref.id.node_id);
400                                 }
401                             }
402                         }
403                         _ => {}
404                     }
405                 }
406                 return;
407             }
408             hir::ItemConst(..) => "a constant",
409             hir::ItemStatic(..) => "a static",
410             _ => return,
411         };
412
413         self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
414     }
415
416     fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
417         if self.private_traits.contains(&trait_item.id) {
418             return;
419         }
420
421         let desc = match trait_item.node {
422             hir::TraitItemKind::Const(..) => "an associated constant",
423             hir::TraitItemKind::Method(..) => "a trait method",
424             hir::TraitItemKind::Type(..) => "an associated type",
425         };
426
427         self.check_missing_docs_attrs(cx,
428                                       Some(trait_item.id),
429                                       &trait_item.attrs,
430                                       trait_item.span,
431                                       desc);
432     }
433
434     fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
435         // If the method is an impl for a trait, don't doc.
436         if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
437             return;
438         }
439
440         let desc = match impl_item.node {
441             hir::ImplItemKind::Const(..) => "an associated constant",
442             hir::ImplItemKind::Method(..) => "a method",
443             hir::ImplItemKind::Type(_) => "an associated type",
444         };
445         self.check_missing_docs_attrs(cx,
446                                       Some(impl_item.id),
447                                       &impl_item.attrs,
448                                       impl_item.span,
449                                       desc);
450     }
451
452     fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
453         if !sf.is_positional() {
454             if sf.vis == hir::Public || self.in_variant {
455                 let cur_struct_def = *self.struct_def_stack
456                     .last()
457                     .expect("empty struct_def_stack");
458                 self.check_missing_docs_attrs(cx,
459                                               Some(cur_struct_def),
460                                               &sf.attrs,
461                                               sf.span,
462                                               "a struct field")
463             }
464         }
465     }
466
467     fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
468         self.check_missing_docs_attrs(cx,
469                                       Some(v.node.data.id()),
470                                       &v.node.attrs,
471                                       v.span,
472                                       "a variant");
473         assert!(!self.in_variant);
474         self.in_variant = true;
475     }
476
477     fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
478         assert!(self.in_variant);
479         self.in_variant = false;
480     }
481 }
482
483 declare_lint! {
484     pub MISSING_COPY_IMPLEMENTATIONS,
485     Allow,
486     "detects potentially-forgotten implementations of `Copy`"
487 }
488
489 #[derive(Copy, Clone)]
490 pub struct MissingCopyImplementations;
491
492 impl LintPass for MissingCopyImplementations {
493     fn get_lints(&self) -> LintArray {
494         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
495     }
496 }
497
498 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
499     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
500         if !cx.access_levels.is_reachable(item.id) {
501             return;
502         }
503         let (def, ty) = match item.node {
504             hir::ItemStruct(_, ref ast_generics) => {
505                 if ast_generics.is_parameterized() {
506                     return;
507                 }
508                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
509                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
510             }
511             hir::ItemUnion(_, ref ast_generics) => {
512                 if ast_generics.is_parameterized() {
513                     return;
514                 }
515                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
516                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
517             }
518             hir::ItemEnum(_, ref ast_generics) => {
519                 if ast_generics.is_parameterized() {
520                     return;
521                 }
522                 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
523                 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
524             }
525             _ => return,
526         };
527         if def.has_dtor(cx.tcx) {
528             return;
529         }
530         let parameter_environment = cx.tcx.empty_parameter_environment();
531         // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
532         // method
533         if !ty.moves_by_default(cx.tcx, &parameter_environment, item.span) {
534             return;
535         }
536         if parameter_environment.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
537             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
538                          item.span,
539                          "type could implement `Copy`; consider adding `impl \
540                           Copy`")
541         }
542     }
543 }
544
545 declare_lint! {
546     MISSING_DEBUG_IMPLEMENTATIONS,
547     Allow,
548     "detects missing implementations of fmt::Debug"
549 }
550
551 pub struct MissingDebugImplementations {
552     impling_types: Option<NodeSet>,
553 }
554
555 impl MissingDebugImplementations {
556     pub fn new() -> MissingDebugImplementations {
557         MissingDebugImplementations { impling_types: None }
558     }
559 }
560
561 impl LintPass for MissingDebugImplementations {
562     fn get_lints(&self) -> LintArray {
563         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
564     }
565 }
566
567 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
568     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
569         if !cx.access_levels.is_reachable(item.id) {
570             return;
571         }
572
573         match item.node {
574             hir::ItemStruct(..) |
575             hir::ItemUnion(..) |
576             hir::ItemEnum(..) => {}
577             _ => return,
578         }
579
580         let debug = match cx.tcx.lang_items.debug_trait() {
581             Some(debug) => debug,
582             None => return,
583         };
584
585         if self.impling_types.is_none() {
586             let debug_def = cx.tcx.trait_def(debug);
587             let mut impls = NodeSet();
588             debug_def.for_each_impl(cx.tcx, |d| {
589                 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
590                     if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
591                         impls.insert(node_id);
592                     }
593                 }
594             });
595
596             self.impling_types = Some(impls);
597             debug!("{:?}", self.impling_types);
598         }
599
600         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
601             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
602                          item.span,
603                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
604                           or a manual implementation")
605         }
606     }
607 }
608
609 declare_lint! {
610     pub ANONYMOUS_PARAMETERS,
611     Allow,
612     "detects anonymous parameters"
613 }
614
615 /// Checks for use of anonymous parameters (RFC 1685)
616 #[derive(Clone)]
617 pub struct AnonymousParameters;
618
619 impl LintPass for AnonymousParameters {
620     fn get_lints(&self) -> LintArray {
621         lint_array!(ANONYMOUS_PARAMETERS)
622     }
623 }
624
625 impl EarlyLintPass for AnonymousParameters {
626     fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
627         match it.node {
628             ast::TraitItemKind::Method(ref sig, _) => {
629                 for arg in sig.decl.inputs.iter() {
630                     match arg.pat.node {
631                         ast::PatKind::Ident(_, ident, None) => {
632                             if ident.node.name == keywords::Invalid.name() {
633                                 cx.span_lint(ANONYMOUS_PARAMETERS,
634                                              arg.pat.span,
635                                              "use of deprecated anonymous parameter");
636                             }
637                         }
638                         _ => (),
639                     }
640                 }
641             },
642             _ => (),
643         }
644     }
645 }
646
647 declare_lint! {
648     DEPRECATED_ATTR,
649     Warn,
650     "detects use of deprecated attributes"
651 }
652
653 /// Checks for use of attributes which have been deprecated.
654 #[derive(Clone)]
655 pub struct DeprecatedAttr {
656     // This is not free to compute, so we want to keep it around, rather than
657     // compute it for every attribute.
658     depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
659 }
660
661 impl DeprecatedAttr {
662     pub fn new() -> DeprecatedAttr {
663         DeprecatedAttr {
664             depr_attrs: deprecated_attributes(),
665         }
666     }
667 }
668
669 impl LintPass for DeprecatedAttr {
670     fn get_lints(&self) -> LintArray {
671         lint_array!(DEPRECATED_ATTR)
672     }
673 }
674
675 impl EarlyLintPass for DeprecatedAttr {
676     fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
677         let name = unwrap_or!(attr.name(), return);
678         for &&(n, _, ref g) in &self.depr_attrs {
679             if name == n {
680                 if let &AttributeGate::Gated(Stability::Deprecated(link),
681                                              ref name,
682                                              ref reason,
683                                              _) = g {
684                     cx.span_lint(DEPRECATED,
685                                  attr.span,
686                                  &format!("use of deprecated attribute `{}`: {}. See {}",
687                                           name, reason, link));
688                 }
689                 return;
690             }
691         }
692     }
693 }
694
695 declare_lint! {
696     pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
697     Warn,
698     "floating-point literals cannot be used in patterns"
699 }
700
701 /// Checks for floating point literals in patterns.
702 #[derive(Clone)]
703 pub struct IllegalFloatLiteralPattern;
704
705 impl LintPass for IllegalFloatLiteralPattern {
706     fn get_lints(&self) -> LintArray {
707         lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
708     }
709 }
710
711 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
712     use self::ast::{ExprKind, LitKind};
713     match expr.node {
714         ExprKind::Lit(ref l) => {
715             match l.node {
716                 LitKind::FloatUnsuffixed(..) |
717                 LitKind::Float(..) => {
718                     cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
719                                  l.span,
720                                  "floating-point literals cannot be used in patterns");
721                     },
722                 _ => (),
723             }
724         }
725         // These may occur in patterns
726         // and can maybe contain float literals
727         ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
728         // These may occur in patterns
729         // and can't contain float literals
730         ExprKind::Path(..) => (),
731         // If something unhandled is encountered, we need to expand the
732         // search or ignore more ExprKinds.
733         _ => span_bug!(expr.span, "Unhandled expression {:?} in float lit pattern lint",
734                        expr.node),
735     }
736 }
737
738 impl EarlyLintPass for IllegalFloatLiteralPattern {
739     fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
740         use self::ast::PatKind;
741         pat.walk(&mut |p| {
742             match p.node {
743                 // Wildcard patterns and paths are uninteresting for the lint
744                 PatKind::Wild |
745                 PatKind::Path(..) => (),
746
747                 // The walk logic recurses inside these
748                 PatKind::Ident(..) |
749                 PatKind::Struct(..) |
750                 PatKind::Tuple(..) |
751                 PatKind::TupleStruct(..) |
752                 PatKind::Ref(..) |
753                 PatKind::Box(..) |
754                 PatKind::Slice(..) => (),
755
756                 // Extract the expressions and check them
757                 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
758                 PatKind::Range(ref st, ref en, _) => {
759                     fl_lit_check_expr(cx, st);
760                     fl_lit_check_expr(cx, en);
761                 },
762
763                 PatKind::Mac(_) => bug!("lint must run post-expansion"),
764             }
765             true
766         });
767     }
768 }
769
770 declare_lint! {
771     pub UNCONDITIONAL_RECURSION,
772     Warn,
773     "functions that cannot return without calling themselves"
774 }
775
776 #[derive(Copy, Clone)]
777 pub struct UnconditionalRecursion;
778
779
780 impl LintPass for UnconditionalRecursion {
781     fn get_lints(&self) -> LintArray {
782         lint_array![UNCONDITIONAL_RECURSION]
783     }
784 }
785
786 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
787     fn check_fn(&mut self,
788                 cx: &LateContext,
789                 fn_kind: FnKind,
790                 _: &hir::FnDecl,
791                 body: &hir::Body,
792                 sp: Span,
793                 id: ast::NodeId) {
794         let method = match fn_kind {
795             FnKind::ItemFn(..) => None,
796             FnKind::Method(..) => {
797                 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
798             }
799             // closures can't recur, so they don't matter.
800             FnKind::Closure(_) => return,
801         };
802
803         // Walk through this function (say `f`) looking to see if
804         // every possible path references itself, i.e. the function is
805         // called recursively unconditionally. This is done by trying
806         // to find a path from the entry node to the exit node that
807         // *doesn't* call `f` by traversing from the entry while
808         // pretending that calls of `f` are sinks (i.e. ignoring any
809         // exit edges from them).
810         //
811         // NB. this has an edge case with non-returning statements,
812         // like `loop {}` or `panic!()`: control flow never reaches
813         // the exit node through these, so one can have a function
814         // that never actually calls itselfs but is still picked up by
815         // this lint:
816         //
817         //     fn f(cond: bool) {
818         //         if !cond { panic!() } // could come from `assert!(cond)`
819         //         f(false)
820         //     }
821         //
822         // In general, functions of that form may be able to call
823         // itself a finite number of times and then diverge. The lint
824         // considers this to be an error for two reasons, (a) it is
825         // easier to implement, and (b) it seems rare to actually want
826         // to have behaviour like the above, rather than
827         // e.g. accidentally recurring after an assert.
828
829         let cfg = cfg::CFG::new(cx.tcx, &body);
830
831         let mut work_queue = vec![cfg.entry];
832         let mut reached_exit_without_self_call = false;
833         let mut self_call_spans = vec![];
834         let mut visited = HashSet::new();
835
836         while let Some(idx) = work_queue.pop() {
837             if idx == cfg.exit {
838                 // found a path!
839                 reached_exit_without_self_call = true;
840                 break;
841             }
842
843             let cfg_id = idx.node_id();
844             if visited.contains(&cfg_id) {
845                 // already done
846                 continue;
847             }
848             visited.insert(cfg_id);
849
850             let node_id = cfg.graph.node_data(idx).id();
851
852             // is this a recursive call?
853             let self_recursive = if node_id != ast::DUMMY_NODE_ID {
854                 match method {
855                     Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
856                     None => expr_refers_to_this_fn(cx, id, node_id),
857                 }
858             } else {
859                 false
860             };
861             if self_recursive {
862                 self_call_spans.push(cx.tcx.hir.span(node_id));
863                 // this is a self call, so we shouldn't explore past
864                 // this node in the CFG.
865                 continue;
866             }
867             // add the successors of this node to explore the graph further.
868             for (_, edge) in cfg.graph.outgoing_edges(idx) {
869                 let target_idx = edge.target();
870                 let target_cfg_id = target_idx.node_id();
871                 if !visited.contains(&target_cfg_id) {
872                     work_queue.push(target_idx)
873                 }
874             }
875         }
876
877         // Check the number of self calls because a function that
878         // doesn't return (e.g. calls a `-> !` function or `loop { /*
879         // no break */ }`) shouldn't be linted unless it actually
880         // recurs.
881         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
882             let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
883                                              sp,
884                                              "function cannot return without recurring");
885
886             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
887             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
888                 // offer some help to the programmer.
889                 for call in &self_call_spans {
890                     db.span_note(*call, "recursive call site");
891                 }
892                 db.help("a `loop` may express intention \
893                          better if this is on purpose");
894             }
895             db.emit();
896         }
897
898         // all done
899         return;
900
901         // Functions for identifying if the given Expr NodeId `id`
902         // represents a call to the function `fn_id`/method `method`.
903
904         fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
905             match cx.tcx.hir.get(id) {
906                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
907                     let def = if let hir::ExprPath(ref qpath) = callee.node {
908                         cx.tables.qpath_def(qpath, callee.id)
909                     } else {
910                         return false;
911                     };
912                     def.def_id() == cx.tcx.hir.local_def_id(fn_id)
913                 }
914                 _ => false,
915             }
916         }
917
918         // Check if the expression `id` performs a call to `method`.
919         fn expr_refers_to_this_method(cx: &LateContext,
920                                       method: &ty::AssociatedItem,
921                                       id: ast::NodeId)
922                                       -> bool {
923             use rustc::ty::adjustment::*;
924
925             // Check for method calls and overloaded operators.
926             let opt_m = cx.tables.method_map.get(&ty::MethodCall::expr(id)).cloned();
927             if let Some(m) = opt_m {
928                 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
929                     return true;
930                 }
931             }
932
933             // Check for overloaded autoderef method calls.
934             let opt_adj = cx.tables.adjustments.get(&id).cloned();
935             if let Some(Adjustment { kind: Adjust::DerefRef { autoderefs, .. }, .. }) = opt_adj {
936                 for i in 0..autoderefs {
937                     let method_call = ty::MethodCall::autoderef(id, i as u32);
938                     if let Some(m) = cx.tables.method_map.get(&method_call).cloned() {
939                         if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
940                             return true;
941                         }
942                     }
943                 }
944             }
945
946             // Check for calls to methods via explicit paths (e.g. `T::method()`).
947             match cx.tcx.hir.get(id) {
948                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
949                     let def = if let hir::ExprPath(ref qpath) = callee.node {
950                         cx.tables.qpath_def(qpath, callee.id)
951                     } else {
952                         return false;
953                     };
954                     match def {
955                         Def::Method(def_id) => {
956                             let substs = cx.tables.node_id_item_substs(callee.id)
957                                 .unwrap_or_else(|| cx.tcx.intern_substs(&[]));
958                             method_call_refers_to_method(
959                                 cx.tcx, method, def_id, substs, id)
960                         }
961                         _ => false,
962                     }
963                 }
964                 _ => false,
965             }
966         }
967
968         // Check if the method call to the method with the ID `callee_id`
969         // and instantiated with `callee_substs` refers to method `method`.
970         fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
971                                                   method: &ty::AssociatedItem,
972                                                   callee_id: DefId,
973                                                   callee_substs: &Substs<'tcx>,
974                                                   expr_id: ast::NodeId)
975                                                   -> bool {
976             let callee_item = tcx.associated_item(callee_id);
977
978             match callee_item.container {
979                 // This is an inherent method, so the `def_id` refers
980                 // directly to the method definition.
981                 ty::ImplContainer(_) => callee_id == method.def_id,
982
983                 // A trait method, from any number of possible sources.
984                 // Attempt to select a concrete impl before checking.
985                 ty::TraitContainer(trait_def_id) => {
986                     let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
987                     let trait_ref = ty::Binder(trait_ref);
988                     let span = tcx.hir.span(expr_id);
989                     let obligation =
990                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
991                                                 trait_ref.to_poly_trait_predicate());
992
993                     let param_env = tcx.parameter_environment(method.def_id);
994                     tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
995                         let mut selcx = traits::SelectionContext::new(&infcx);
996                         match selcx.select(&obligation) {
997                             // The method comes from a `T: Trait` bound.
998                             // If `T` is `Self`, then this call is inside
999                             // a default method definition.
1000                             Ok(Some(traits::VtableParam(_))) => {
1001                                 let on_self = trait_ref.self_ty().is_self();
1002                                 // We can only be recurring in a default
1003                                 // method if we're being called literally
1004                                 // on the `Self` type.
1005                                 on_self && callee_id == method.def_id
1006                             }
1007
1008                             // The `impl` is known, so we check that with a
1009                             // special case:
1010                             Ok(Some(traits::VtableImpl(vtable_impl))) => {
1011                                 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1012                                 // It matches if it comes from the same impl,
1013                                 // and has the same method name.
1014                                 container == method.container && callee_item.name == method.name
1015                             }
1016
1017                             // There's no way to know if this call is
1018                             // recursive, so we assume it's not.
1019                             _ => false,
1020                         }
1021                     })
1022                 }
1023             }
1024         }
1025     }
1026 }
1027
1028 declare_lint! {
1029     PLUGIN_AS_LIBRARY,
1030     Warn,
1031     "compiler plugin used as ordinary library in non-plugin crate"
1032 }
1033
1034 #[derive(Copy, Clone)]
1035 pub struct PluginAsLibrary;
1036
1037 impl LintPass for PluginAsLibrary {
1038     fn get_lints(&self) -> LintArray {
1039         lint_array![PLUGIN_AS_LIBRARY]
1040     }
1041 }
1042
1043 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1044     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1045         if cx.sess().plugin_registrar_fn.get().is_some() {
1046             // We're compiling a plugin; it's fine to link other plugins.
1047             return;
1048         }
1049
1050         match it.node {
1051             hir::ItemExternCrate(..) => (),
1052             _ => return,
1053         };
1054
1055         let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
1056             Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
1057             None => {
1058                 // Probably means we aren't linking the crate for some reason.
1059                 //
1060                 // Not sure if / when this could happen.
1061                 return;
1062             }
1063         };
1064
1065         if prfn.is_some() {
1066             cx.span_lint(PLUGIN_AS_LIBRARY,
1067                          it.span,
1068                          "compiler plugin used as an ordinary library");
1069         }
1070     }
1071 }
1072
1073 declare_lint! {
1074     PRIVATE_NO_MANGLE_FNS,
1075     Warn,
1076     "functions marked #[no_mangle] should be exported"
1077 }
1078
1079 declare_lint! {
1080     PRIVATE_NO_MANGLE_STATICS,
1081     Warn,
1082     "statics marked #[no_mangle] should be exported"
1083 }
1084
1085 declare_lint! {
1086     NO_MANGLE_CONST_ITEMS,
1087     Deny,
1088     "const items will not have their symbols exported"
1089 }
1090
1091 declare_lint! {
1092     NO_MANGLE_GENERIC_ITEMS,
1093     Warn,
1094     "generic items must be mangled"
1095 }
1096
1097 #[derive(Copy, Clone)]
1098 pub struct InvalidNoMangleItems;
1099
1100 impl LintPass for InvalidNoMangleItems {
1101     fn get_lints(&self) -> LintArray {
1102         lint_array!(PRIVATE_NO_MANGLE_FNS,
1103                     PRIVATE_NO_MANGLE_STATICS,
1104                     NO_MANGLE_CONST_ITEMS,
1105                     NO_MANGLE_GENERIC_ITEMS)
1106     }
1107 }
1108
1109 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1110     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1111         match it.node {
1112             hir::ItemFn(.., ref generics, _) => {
1113                 if attr::contains_name(&it.attrs, "no_mangle") {
1114                     if !cx.access_levels.is_reachable(it.id) {
1115                         let msg = format!("function {} is marked #[no_mangle], but not exported",
1116                                           it.name);
1117                         cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1118                     }
1119                     if generics.is_parameterized() {
1120                         cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1121                                      it.span,
1122                                      "generic functions must be mangled");
1123                     }
1124                 }
1125             }
1126             hir::ItemStatic(..) => {
1127                 if attr::contains_name(&it.attrs, "no_mangle") &&
1128                    !cx.access_levels.is_reachable(it.id) {
1129                     let msg = format!("static {} is marked #[no_mangle], but not exported",
1130                                       it.name);
1131                     cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1132                 }
1133             }
1134             hir::ItemConst(..) => {
1135                 if attr::contains_name(&it.attrs, "no_mangle") {
1136                     // Const items do not refer to a particular location in memory, and therefore
1137                     // don't have anything to attach a symbol to
1138                     let msg = "const items should never be #[no_mangle], consider instead using \
1139                                `pub static`";
1140                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1141                 }
1142             }
1143             _ => {}
1144         }
1145     }
1146 }
1147
1148 #[derive(Clone, Copy)]
1149 pub struct MutableTransmutes;
1150
1151 declare_lint! {
1152     MUTABLE_TRANSMUTES,
1153     Deny,
1154     "mutating transmuted &mut T from &T may cause undefined behavior"
1155 }
1156
1157 impl LintPass for MutableTransmutes {
1158     fn get_lints(&self) -> LintArray {
1159         lint_array!(MUTABLE_TRANSMUTES)
1160     }
1161 }
1162
1163 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1164     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1165         use syntax::abi::Abi::RustIntrinsic;
1166
1167         let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1168                    consider instead using an UnsafeCell";
1169         match get_transmute_from_to(cx, expr) {
1170             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1171                 if to_mt.mutbl == hir::Mutability::MutMutable &&
1172                    from_mt.mutbl == hir::Mutability::MutImmutable {
1173                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1174                 }
1175             }
1176             _ => (),
1177         }
1178
1179         fn get_transmute_from_to<'a, 'tcx>
1180             (cx: &LateContext<'a, 'tcx>,
1181              expr: &hir::Expr)
1182              -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1183             let def = if let hir::ExprPath(ref qpath) = expr.node {
1184                 cx.tables.qpath_def(qpath, expr.id)
1185             } else {
1186                 return None;
1187             };
1188             if let Def::Fn(did) = def {
1189                 if !def_id_is_transmute(cx, did) {
1190                     return None;
1191                 }
1192                 let typ = cx.tables.node_id_to_type(expr.id);
1193                 match typ.sty {
1194                     ty::TyFnDef(.., bare_fn) if bare_fn.abi() == RustIntrinsic => {
1195                         let from = bare_fn.inputs().skip_binder()[0];
1196                         let to = *bare_fn.output().skip_binder();
1197                         return Some((&from.sty, &to.sty));
1198                     }
1199                     _ => (),
1200                 }
1201             }
1202             None
1203         }
1204
1205         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1206             match cx.tcx.type_of(def_id).sty {
1207                 ty::TyFnDef(.., bfty) if bfty.abi() == RustIntrinsic => (),
1208                 _ => return false,
1209             }
1210             cx.tcx.item_name(def_id) == "transmute"
1211         }
1212     }
1213 }
1214
1215 /// Forbids using the `#[feature(...)]` attribute
1216 #[derive(Copy, Clone)]
1217 pub struct UnstableFeatures;
1218
1219 declare_lint! {
1220     UNSTABLE_FEATURES,
1221     Allow,
1222     "enabling unstable features (deprecated. do not use)"
1223 }
1224
1225 impl LintPass for UnstableFeatures {
1226     fn get_lints(&self) -> LintArray {
1227         lint_array!(UNSTABLE_FEATURES)
1228     }
1229 }
1230
1231 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1232     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1233         if attr.check_name("feature") {
1234             if let Some(items) = attr.meta_item_list() {
1235                 for item in items {
1236                     ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1237                 }
1238             }
1239         }
1240     }
1241 }
1242
1243 /// Lint for unions that contain fields with possibly non-trivial destructors.
1244 pub struct UnionsWithDropFields;
1245
1246 declare_lint! {
1247     UNIONS_WITH_DROP_FIELDS,
1248     Warn,
1249     "use of unions that contain fields with possibly non-trivial drop code"
1250 }
1251
1252 impl LintPass for UnionsWithDropFields {
1253     fn get_lints(&self) -> LintArray {
1254         lint_array!(UNIONS_WITH_DROP_FIELDS)
1255     }
1256 }
1257
1258 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1259     fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1260         if let hir::ItemUnion(ref vdata, _) = item.node {
1261             let param_env = &ctx.tcx.parameter_environment(ctx.tcx.hir.local_def_id(item.id));
1262             for field in vdata.fields() {
1263                 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1264                 if field_ty.needs_drop(ctx.tcx, param_env) {
1265                     ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1266                                   field.span,
1267                                   "union contains a field with possibly non-trivial drop code, \
1268                                    drop code of union fields is ignored when dropping the union");
1269                     return;
1270                 }
1271             }
1272         }
1273     }
1274 }