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