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