]> git.lizzy.rs Git - rust.git/blob - src/librustc_lint/builtin.rs
Rollup merge of #29028 - Seeker14491:patch-1, r=Manishearth
[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::VariantData,
431                         _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
432         self.struct_def_stack.push(item_id);
433     }
434
435     fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::VariantData,
436                              _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
437         let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
438         assert!(popped == item_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.data.id()),
531                                       &v.node.attrs, v.span, "a variant");
532         assert!(!self.in_variant);
533         self.in_variant = true;
534     }
535
536     fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
537         assert!(self.in_variant);
538         self.in_variant = false;
539     }
540 }
541
542 declare_lint! {
543     pub MISSING_COPY_IMPLEMENTATIONS,
544     Allow,
545     "detects potentially-forgotten implementations of `Copy`"
546 }
547
548 #[derive(Copy, Clone)]
549 pub struct MissingCopyImplementations;
550
551 impl LintPass for MissingCopyImplementations {
552     fn get_lints(&self) -> LintArray {
553         lint_array!(MISSING_COPY_IMPLEMENTATIONS)
554     }
555 }
556
557 impl LateLintPass for MissingCopyImplementations {
558     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
559         if !cx.exported_items.contains(&item.id) {
560             return;
561         }
562         let (def, ty) = match item.node {
563             hir::ItemStruct(_, ref ast_generics) => {
564                 if ast_generics.is_parameterized() {
565                     return;
566                 }
567                 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
568                 (def, cx.tcx.mk_struct(def,
569                                        cx.tcx.mk_substs(Substs::empty())))
570             }
571             hir::ItemEnum(_, ref ast_generics) => {
572                 if ast_generics.is_parameterized() {
573                     return;
574                 }
575                 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
576                 (def, cx.tcx.mk_enum(def,
577                                      cx.tcx.mk_substs(Substs::empty())))
578             }
579             _ => return,
580         };
581         if def.has_dtor() { return; }
582         let parameter_environment = cx.tcx.empty_parameter_environment();
583         // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
584         // method
585         if !ty.moves_by_default(&parameter_environment, item.span) {
586             return;
587         }
588         if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
589             cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
590                          item.span,
591                          "type could implement `Copy`; consider adding `impl \
592                           Copy`")
593         }
594     }
595 }
596
597 declare_lint! {
598     MISSING_DEBUG_IMPLEMENTATIONS,
599     Allow,
600     "detects missing implementations of fmt::Debug"
601 }
602
603 pub struct MissingDebugImplementations {
604     impling_types: Option<NodeSet>,
605 }
606
607 impl MissingDebugImplementations {
608     pub fn new() -> MissingDebugImplementations {
609         MissingDebugImplementations {
610             impling_types: None,
611         }
612     }
613 }
614
615 impl LintPass for MissingDebugImplementations {
616     fn get_lints(&self) -> LintArray {
617         lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
618     }
619 }
620
621 impl LateLintPass for MissingDebugImplementations {
622     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
623         if !cx.exported_items.contains(&item.id) {
624             return;
625         }
626
627         match item.node {
628             hir::ItemStruct(..) | hir::ItemEnum(..) => {},
629             _ => return,
630         }
631
632         let debug = match cx.tcx.lang_items.debug_trait() {
633             Some(debug) => debug,
634             None => return,
635         };
636
637         if self.impling_types.is_none() {
638             let debug_def = cx.tcx.lookup_trait_def(debug);
639             let mut impls = NodeSet();
640             debug_def.for_each_impl(cx.tcx, |d| {
641                 if let Some(n) = cx.tcx.map.as_local_node_id(d) {
642                     if let Some(ty_def) = cx.tcx.node_id_to_type(n).ty_to_def_id() {
643                         if let Some(node_id) = cx.tcx.map.as_local_node_id(ty_def) {
644                             impls.insert(node_id);
645                         }
646                     }
647                 }
648             });
649
650             self.impling_types = Some(impls);
651             debug!("{:?}", self.impling_types);
652         }
653
654         if !self.impling_types.as_ref().unwrap().contains(&item.id) {
655             cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
656                          item.span,
657                          "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
658                           or a manual implementation")
659         }
660     }
661 }
662
663 declare_lint! {
664     DEPRECATED,
665     Warn,
666     "detects use of #[deprecated] items"
667 }
668
669 /// Checks for use of items with `#[deprecated]` attributes
670 #[derive(Copy, Clone)]
671 pub struct Stability;
672
673 impl Stability {
674     fn lint(&self, cx: &LateContext, _id: DefId,
675             span: Span, stability: &Option<&attr::Stability>) {
676         // Deprecated attributes apply in-crate and cross-crate.
677         let (lint, label) = match *stability {
678             Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
679                 (DEPRECATED, "deprecated"),
680             _ => return
681         };
682
683         output(cx, span, stability, lint, label);
684
685         fn output(cx: &LateContext, span: Span, stability: &Option<&attr::Stability>,
686                   lint: &'static Lint, label: &'static str) {
687             let msg = match *stability {
688                 Some(&attr::Stability { reason: Some(ref s), .. }) => {
689                     format!("use of {} item: {}", label, *s)
690                 }
691                 _ => format!("use of {} item", label)
692             };
693
694             cx.span_lint(lint, span, &msg[..]);
695         }
696     }
697 }
698
699 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
700     attr::Stability {
701         level: match stab.level {
702             attr::Unstable => attr::Unstable,
703             attr::Stable => attr::Stable,
704         },
705         feature: stab.feature.clone(),
706         since: stab.since.clone(),
707         deprecated_since: stab.deprecated_since.clone(),
708         reason: stab.reason.clone(),
709         issue: stab.issue,
710     }
711 }
712
713 impl LintPass for Stability {
714     fn get_lints(&self) -> LintArray {
715         lint_array!(DEPRECATED)
716     }
717 }
718
719 impl LateLintPass for Stability {
720     fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
721         stability::check_item(cx.tcx, item, false,
722                               &mut |id, sp, stab|
723                                 self.lint(cx, id, sp,
724                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
725     }
726
727     fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
728         stability::check_expr(cx.tcx, e,
729                               &mut |id, sp, stab|
730                                 self.lint(cx, id, sp,
731                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
732     }
733
734     fn check_path(&mut self, cx: &LateContext, path: &hir::Path, id: ast::NodeId) {
735         stability::check_path(cx.tcx, path, id,
736                               &mut |id, sp, stab|
737                                 self.lint(cx, id, sp,
738                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
739     }
740
741     fn check_path_list_item(&mut self, cx: &LateContext, item: &hir::PathListItem) {
742         stability::check_path_list_item(cx.tcx, item,
743                                          &mut |id, sp, stab|
744                                            self.lint(cx, id, sp,
745                                                 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
746     }
747
748     fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
749         stability::check_pat(cx.tcx, pat,
750                              &mut |id, sp, stab|
751                                 self.lint(cx, id, sp,
752                                           &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
753     }
754 }
755
756 declare_lint! {
757     pub UNCONDITIONAL_RECURSION,
758     Warn,
759     "functions that cannot return without calling themselves"
760 }
761
762 #[derive(Copy, Clone)]
763 pub struct UnconditionalRecursion;
764
765
766 impl LintPass for UnconditionalRecursion {
767     fn get_lints(&self) -> LintArray {
768         lint_array![UNCONDITIONAL_RECURSION]
769     }
770 }
771
772 impl LateLintPass for UnconditionalRecursion {
773     fn check_fn(&mut self, cx: &LateContext, fn_kind: FnKind, _: &hir::FnDecl,
774                 blk: &hir::Block, sp: Span, id: ast::NodeId) {
775         let method = match fn_kind {
776             FnKind::ItemFn(..) => None,
777             FnKind::Method(..) => {
778                 cx.tcx.impl_or_trait_item(cx.tcx.map.local_def_id(id)).as_opt_method()
779             }
780             // closures can't recur, so they don't matter.
781             FnKind::Closure => return
782         };
783
784         // Walk through this function (say `f`) looking to see if
785         // every possible path references itself, i.e. the function is
786         // called recursively unconditionally. This is done by trying
787         // to find a path from the entry node to the exit node that
788         // *doesn't* call `f` by traversing from the entry while
789         // pretending that calls of `f` are sinks (i.e. ignoring any
790         // exit edges from them).
791         //
792         // NB. this has an edge case with non-returning statements,
793         // like `loop {}` or `panic!()`: control flow never reaches
794         // the exit node through these, so one can have a function
795         // that never actually calls itselfs but is still picked up by
796         // this lint:
797         //
798         //     fn f(cond: bool) {
799         //         if !cond { panic!() } // could come from `assert!(cond)`
800         //         f(false)
801         //     }
802         //
803         // In general, functions of that form may be able to call
804         // itself a finite number of times and then diverge. The lint
805         // considers this to be an error for two reasons, (a) it is
806         // easier to implement, and (b) it seems rare to actually want
807         // to have behaviour like the above, rather than
808         // e.g. accidentally recurring after an assert.
809
810         let cfg = cfg::CFG::new(cx.tcx, blk);
811
812         let mut work_queue = vec![cfg.entry];
813         let mut reached_exit_without_self_call = false;
814         let mut self_call_spans = vec![];
815         let mut visited = HashSet::new();
816
817         while let Some(idx) = work_queue.pop() {
818             if idx == cfg.exit {
819                 // found a path!
820                 reached_exit_without_self_call = true;
821                 break;
822             }
823
824             let cfg_id = idx.node_id();
825             if visited.contains(&cfg_id) {
826                 // already done
827                 continue;
828             }
829             visited.insert(cfg_id);
830
831             let node_id = cfg.graph.node_data(idx).id();
832
833             // is this a recursive call?
834             let self_recursive = if node_id != ast::DUMMY_NODE_ID {
835                 match method {
836                     Some(ref method) => {
837                         expr_refers_to_this_method(cx.tcx, method, node_id)
838                     }
839                     None => expr_refers_to_this_fn(cx.tcx, id, node_id)
840                 }
841             } else {
842                 false
843             };
844             if self_recursive {
845                 self_call_spans.push(cx.tcx.map.span(node_id));
846                 // this is a self call, so we shouldn't explore past
847                 // this node in the CFG.
848                 continue;
849             }
850             // add the successors of this node to explore the graph further.
851             for (_, edge) in cfg.graph.outgoing_edges(idx) {
852                 let target_idx = edge.target();
853                 let target_cfg_id = target_idx.node_id();
854                 if !visited.contains(&target_cfg_id) {
855                     work_queue.push(target_idx)
856                 }
857             }
858         }
859
860         // Check the number of self calls because a function that
861         // doesn't return (e.g. calls a `-> !` function or `loop { /*
862         // no break */ }`) shouldn't be linted unless it actually
863         // recurs.
864         if !reached_exit_without_self_call && !self_call_spans.is_empty() {
865             cx.span_lint(UNCONDITIONAL_RECURSION, sp,
866                          "function cannot return without recurring");
867
868             // FIXME #19668: these could be span_lint_note's instead of this manual guard.
869             if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
870                 let sess = cx.sess();
871                 // offer some help to the programmer.
872                 for call in &self_call_spans {
873                     sess.span_note(*call, "recursive call site")
874                 }
875                 sess.fileline_help(sp, "a `loop` may express intention \
876                                         better if this is on purpose")
877             }
878         }
879
880         // all done
881         return;
882
883         // Functions for identifying if the given Expr NodeId `id`
884         // represents a call to the function `fn_id`/method `method`.
885
886         fn expr_refers_to_this_fn(tcx: &ty::ctxt,
887                                   fn_id: ast::NodeId,
888                                   id: ast::NodeId) -> bool {
889             match tcx.map.get(id) {
890                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
891                     tcx.def_map
892                        .borrow()
893                        .get(&callee.id)
894                        .map_or(false,
895                                |def| def.def_id() == tcx.map.local_def_id(fn_id))
896                 }
897                 _ => false
898             }
899         }
900
901         // Check if the expression `id` performs a call to `method`.
902         fn expr_refers_to_this_method(tcx: &ty::ctxt,
903                                       method: &ty::Method,
904                                       id: ast::NodeId) -> bool {
905             // Check for method calls and overloaded operators.
906             let opt_m = tcx.tables.borrow().method_map.get(&ty::MethodCall::expr(id)).cloned();
907             if let Some(m) = opt_m {
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             let opt_adj = tcx.tables.borrow().adjustments.get(&id).cloned();
915             if let Some(adjustment::AdjustDerefRef(adj)) = opt_adj {
916                 for i in 0..adj.autoderefs {
917                     let method_call = ty::MethodCall::autoderef(id, i as u32);
918                     if let Some(m) = tcx.tables.borrow().method_map
919                                                         .get(&method_call)
920                                                         .cloned() {
921                         if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
922                             return true;
923                         }
924                     }
925                 }
926             }
927
928             // Check for calls to methods via explicit paths (e.g. `T::method()`).
929             match tcx.map.get(id) {
930                 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
931                     match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
932                         Some(def::DefMethod(def_id)) => {
933                             let item_substs =
934                                 tcx.tables.borrow().item_substs
935                                                    .get(&callee.id)
936                                                    .cloned()
937                                                    .unwrap_or_else(|| ty::ItemSubsts::empty());
938                             method_call_refers_to_method(
939                                 tcx, method, def_id, &item_substs.substs, id)
940                         }
941                         _ => false
942                     }
943                 }
944                 _ => false
945             }
946         }
947
948         // Check if the method call to the method with the ID `callee_id`
949         // and instantiated with `callee_substs` refers to method `method`.
950         fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
951                                               method: &ty::Method,
952                                               callee_id: DefId,
953                                               callee_substs: &Substs<'tcx>,
954                                               expr_id: ast::NodeId) -> bool {
955             let callee_item = tcx.impl_or_trait_item(callee_id);
956
957             match callee_item.container() {
958                 // This is an inherent method, so the `def_id` refers
959                 // directly to the method definition.
960                 ty::ImplContainer(_) => {
961                     callee_id == method.def_id
962                 }
963
964                 // A trait method, from any number of possible sources.
965                 // Attempt to select a concrete impl before checking.
966                 ty::TraitContainer(trait_def_id) => {
967                     let trait_substs = callee_substs.clone().method_to_trait();
968                     let trait_substs = tcx.mk_substs(trait_substs);
969                     let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
970                     let trait_ref = ty::Binder(trait_ref);
971                     let span = tcx.map.span(expr_id);
972                     let obligation =
973                         traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
974                                                 trait_ref.to_poly_trait_predicate());
975
976                     // unwrap() is ok here b/c `method` is the method
977                     // defined in this crate whose body we are
978                     // checking, so it's always local
979                     let node_id = tcx.map.as_local_node_id(method.def_id).unwrap();
980
981                     let param_env = ty::ParameterEnvironment::for_item(tcx, node_id);
982                     let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
983                     let mut selcx = traits::SelectionContext::new(&infcx);
984                     match selcx.select(&obligation) {
985                         // The method comes from a `T: Trait` bound.
986                         // If `T` is `Self`, then this call is inside
987                         // a default method definition.
988                         Ok(Some(traits::VtableParam(_))) => {
989                             let self_ty = callee_substs.self_ty();
990                             let on_self = self_ty.map_or(false, |t| t.is_self());
991                             // We can only be recurring in a default
992                             // method if we're being called literally
993                             // on the `Self` type.
994                             on_self && callee_id == method.def_id
995                         }
996
997                         // The `impl` is known, so we check that with a
998                         // special case:
999                         Ok(Some(traits::VtableImpl(vtable_impl))) => {
1000                             let container = ty::ImplContainer(vtable_impl.impl_def_id);
1001                             // It matches if it comes from the same impl,
1002                             // and has the same method name.
1003                             container == method.container
1004                                 && callee_item.name() == method.name
1005                         }
1006
1007                         // There's no way to know if this call is
1008                         // recursive, so we assume it's not.
1009                         _ => return false
1010                     }
1011                 }
1012             }
1013         }
1014     }
1015 }
1016
1017 declare_lint! {
1018     PLUGIN_AS_LIBRARY,
1019     Warn,
1020     "compiler plugin used as ordinary library in non-plugin crate"
1021 }
1022
1023 #[derive(Copy, Clone)]
1024 pub struct PluginAsLibrary;
1025
1026 impl LintPass for PluginAsLibrary {
1027     fn get_lints(&self) -> LintArray {
1028         lint_array![PLUGIN_AS_LIBRARY]
1029     }
1030 }
1031
1032 impl LateLintPass for PluginAsLibrary {
1033     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1034         if cx.sess().plugin_registrar_fn.get().is_some() {
1035             // We're compiling a plugin; it's fine to link other plugins.
1036             return;
1037         }
1038
1039         match it.node {
1040             hir::ItemExternCrate(..) => (),
1041             _ => return,
1042         };
1043
1044         let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
1045             Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
1046             None => {
1047                 // Probably means we aren't linking the crate for some reason.
1048                 //
1049                 // Not sure if / when this could happen.
1050                 return;
1051             }
1052         };
1053
1054         if decoder::get_plugin_registrar_fn(md.data()).is_some() {
1055             cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
1056                          "compiler plugin used as an ordinary library");
1057         }
1058     }
1059 }
1060
1061 declare_lint! {
1062     PRIVATE_NO_MANGLE_FNS,
1063     Warn,
1064     "functions marked #[no_mangle] should be exported"
1065 }
1066
1067 declare_lint! {
1068     PRIVATE_NO_MANGLE_STATICS,
1069     Warn,
1070     "statics marked #[no_mangle] should be exported"
1071 }
1072
1073 declare_lint! {
1074     NO_MANGLE_CONST_ITEMS,
1075     Deny,
1076     "const items will not have their symbols exported"
1077 }
1078
1079 #[derive(Copy, Clone)]
1080 pub struct InvalidNoMangleItems;
1081
1082 impl LintPass for InvalidNoMangleItems {
1083     fn get_lints(&self) -> LintArray {
1084         lint_array!(PRIVATE_NO_MANGLE_FNS,
1085                     PRIVATE_NO_MANGLE_STATICS,
1086                     NO_MANGLE_CONST_ITEMS)
1087     }
1088 }
1089
1090 impl LateLintPass for InvalidNoMangleItems {
1091     fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1092         match it.node {
1093             hir::ItemFn(..) => {
1094                 if attr::contains_name(&it.attrs, "no_mangle") &&
1095                        !cx.exported_items.contains(&it.id) {
1096                     let msg = format!("function {} is marked #[no_mangle], but not exported",
1097                                       it.name);
1098                     cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1099                 }
1100             },
1101             hir::ItemStatic(..) => {
1102                 if attr::contains_name(&it.attrs, "no_mangle") &&
1103                        !cx.exported_items.contains(&it.id) {
1104                     let msg = format!("static {} is marked #[no_mangle], but not exported",
1105                                       it.name);
1106                     cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1107                 }
1108             },
1109             hir::ItemConst(..) => {
1110                 if attr::contains_name(&it.attrs, "no_mangle") {
1111                     // Const items do not refer to a particular location in memory, and therefore
1112                     // don't have anything to attach a symbol to
1113                     let msg = "const items should never be #[no_mangle], consider instead using \
1114                                `pub static`";
1115                     cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1116                 }
1117             }
1118             _ => {},
1119         }
1120     }
1121 }
1122
1123 #[derive(Clone, Copy)]
1124 pub struct MutableTransmutes;
1125
1126 declare_lint! {
1127     MUTABLE_TRANSMUTES,
1128     Deny,
1129     "mutating transmuted &mut T from &T may cause undefined behavior"
1130 }
1131
1132 impl LintPass for MutableTransmutes {
1133     fn get_lints(&self) -> LintArray {
1134         lint_array!(MUTABLE_TRANSMUTES)
1135     }
1136 }
1137
1138 impl LateLintPass for MutableTransmutes {
1139     fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1140         use syntax::abi::RustIntrinsic;
1141
1142         let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
1143                    consider instead using an UnsafeCell";
1144         match get_transmute_from_to(cx, expr) {
1145             Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1146                 if to_mt.mutbl == hir::Mutability::MutMutable
1147                     && from_mt.mutbl == hir::Mutability::MutImmutable {
1148                     cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1149                 }
1150             }
1151             _ => ()
1152         }
1153
1154         fn get_transmute_from_to<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr)
1155             -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1156             match expr.node {
1157                 hir::ExprPath(..) => (),
1158                 _ => return None
1159             }
1160             if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
1161                 if !def_id_is_transmute(cx, did) {
1162                     return None;
1163                 }
1164                 let typ = cx.tcx.node_id_to_type(expr.id);
1165                 match typ.sty {
1166                     ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
1167                         if let ty::FnConverging(to) = bare_fn.sig.0.output {
1168                             let from = bare_fn.sig.0.inputs[0];
1169                             return Some((&from.sty, &to.sty));
1170                         }
1171                     },
1172                     _ => ()
1173                 }
1174             }
1175             None
1176         }
1177
1178         fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1179             match cx.tcx.lookup_item_type(def_id).ty.sty {
1180                 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
1181                 _ => return false
1182             }
1183             cx.tcx.with_path(def_id, |path| match path.last() {
1184                 Some(ref last) => last.name().as_str() == "transmute",
1185                 _ => false
1186             })
1187         }
1188     }
1189 }
1190
1191 /// Forbids using the `#[feature(...)]` attribute
1192 #[derive(Copy, Clone)]
1193 pub struct UnstableFeatures;
1194
1195 declare_lint! {
1196     UNSTABLE_FEATURES,
1197     Allow,
1198     "enabling unstable features (deprecated. do not use)"
1199 }
1200
1201 impl LintPass for UnstableFeatures {
1202     fn get_lints(&self) -> LintArray {
1203         lint_array!(UNSTABLE_FEATURES)
1204     }
1205 }
1206
1207 impl LateLintPass for UnstableFeatures {
1208     fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1209         if attr::contains_name(&[attr.node.value.clone()], "feature") {
1210             if let Some(items) = attr.node.value.meta_item_list() {
1211                 for item in items {
1212                     ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
1213                 }
1214             }
1215         }
1216     }
1217 }
1218
1219 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
1220 /// attribute (see issue #24585).
1221 #[derive(Copy, Clone)]
1222 pub struct DropWithReprExtern;
1223
1224 declare_lint! {
1225     DROP_WITH_REPR_EXTERN,
1226     Warn,
1227     "use of #[repr(C)] on a type that implements Drop"
1228 }
1229
1230 impl LintPass for DropWithReprExtern {
1231     fn get_lints(&self) -> LintArray {
1232         lint_array!(DROP_WITH_REPR_EXTERN)
1233     }
1234 }
1235
1236 impl LateLintPass for DropWithReprExtern {
1237     fn check_crate(&mut self, ctx: &LateContext, _: &hir::Crate) {
1238         let drop_trait = match ctx.tcx.lang_items.drop_trait() {
1239             Some(id) => ctx.tcx.lookup_trait_def(id), None => { return }
1240         };
1241         drop_trait.for_each_impl(ctx.tcx, |drop_impl_did| {
1242             if !drop_impl_did.is_local() {
1243                 return;
1244             }
1245             let dtor_self_type = ctx.tcx.lookup_item_type(drop_impl_did).ty;
1246
1247             match dtor_self_type.sty {
1248                 ty::TyEnum(self_type_def, _) |
1249                 ty::TyStruct(self_type_def, _) => {
1250                     let self_type_did = self_type_def.did;
1251                     let hints = ctx.tcx.lookup_repr_hints(self_type_did);
1252                     if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
1253                         self_type_def.dtor_kind().has_drop_flag() {
1254                         let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
1255                                                                      codemap::DUMMY_SP);
1256                         let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
1257                                                                      codemap::DUMMY_SP);
1258                         ctx.span_lint(DROP_WITH_REPR_EXTERN,
1259                                       drop_impl_span,
1260                                       "implementing Drop adds hidden state to types, \
1261                                        possibly conflicting with `#[repr(C)]`");
1262                         // FIXME #19668: could be span_lint_note instead of manual guard.
1263                         if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
1264                             ctx.sess().span_note(self_defn_span,
1265                                                "the `#[repr(C)]` attribute is attached here");
1266                         }
1267                     }
1268                 }
1269                 _ => {}
1270             }
1271         })
1272     }
1273 }