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