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