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