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