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