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.
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.
11 //! Lints in the Rust compiler.
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
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).
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
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};
42 use std::collections::HashSet;
45 use syntax::attr::{self, AttrMetaMethods};
46 use syntax::codemap::{self, Span};
49 use rustc_front::visit::{self, FnKind, Visitor};
51 use bad_style::{MethodLateContext, method_context};
53 // hardwired lints from librustc
54 pub use lint::builtin::*;
59 "suggest using `loop { }` instead of `while true { }`"
62 #[derive(Copy, Clone)]
65 impl LintPass for WhileTrue {
66 fn get_lints(&self) -> LintArray {
67 lint_array!(WHILE_TRUE)
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 { ... }");
87 "use of owned (Box type) heap memory"
90 #[derive(Copy, Clone)]
91 pub struct 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);
105 impl LintPass for BoxPointers {
106 fn get_lints(&self) -> LintArray {
107 lint_array!(BOX_POINTERS)
111 impl LateLintPass for BoxPointers {
112 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
117 hir::ItemStruct(..) =>
118 self.check_heap_type(cx, it.span,
119 cx.tcx.node_id_to_type(it.id)),
123 // If it's a struct, we also have to check the fields' types
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));
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);
144 "uses of #[derive] with raw pointers are rarely correct"
147 struct RawPtrDeriveVisitor<'a, 'tcx: 'a> {
148 cx: &'a LateContext<'a, 'tcx>
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);
157 visit::walk_ty(self, ty);
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) {}
164 pub struct RawPointerDerive {
165 checked_raw_pointers: NodeSet,
168 impl RawPointerDerive {
169 pub fn new() -> RawPointerDerive {
171 checked_raw_pointers: NodeSet(),
176 impl LintPass for RawPointerDerive {
177 fn get_lints(&self) -> LintArray {
178 lint_array!(RAW_POINTER_DERIVE)
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") {
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() {
197 match cx.tcx.node_id_to_type(item.id).sty {
198 ty::TyEnum(def, _) => def.did,
199 ty::TyStruct(def, _) => def.did,
205 let node_id = if let Some(node_id) = cx.tcx.map.as_local_node_id(did) {
210 let item = match cx.tcx.map.find(node_id) {
211 Some(hir_map::NodeItem(item)) => item,
214 if !self.checked_raw_pointers.insert(item.id) {
218 hir::ItemStruct(..) | hir::ItemEnum(..) => {
219 let mut visitor = RawPtrDeriveVisitor { cx: cx };
220 visit::walk_item(&mut visitor, &item);
228 NON_SHORTHAND_FIELD_PATTERNS,
230 "using `Struct { x: x }` instead of `Struct { x }`"
233 #[derive(Copy, Clone)]
234 pub struct NonShorthandFieldPatterns;
236 impl LintPass for NonShorthandFieldPatterns {
237 fn get_lints(&self) -> LintArray {
238 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
242 impl LateLintPass for NonShorthandFieldPatterns {
243 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
244 let def_map = cx.tcx.def_map.borrow();
245 if let hir::PatStruct(_, ref v, _) = pat.node {
246 let field_pats = v.iter().filter(|fieldpat| {
247 if fieldpat.node.is_shorthand {
250 let def = def_map.get(&fieldpat.node.pat.id).map(|d| d.full_def());
251 if let Some(def_id) = cx.tcx.map.opt_local_def_id(fieldpat.node.pat.id) {
252 def == Some(def::DefLocal(def_id, fieldpat.node.pat.id))
257 for fieldpat in field_pats {
258 if let hir::PatIdent(_, ident, None) = fieldpat.node.pat.node {
259 if ident.node.name == fieldpat.node.name {
260 // FIXME: should this comparison really be done on the name?
261 // doing it on the ident will fail during compilation of libcore
262 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
263 &format!("the `{}:` in this pattern is redundant and can \
264 be removed", ident.node))
275 "usage of `unsafe` code"
278 #[derive(Copy, Clone)]
279 pub struct UnsafeCode;
281 impl LintPass for UnsafeCode {
282 fn get_lints(&self) -> LintArray {
283 lint_array!(UNSAFE_CODE)
287 impl LateLintPass for UnsafeCode {
288 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
289 if let hir::ExprBlock(ref blk) = e.node {
290 // Don't warn about generated blocks, that'll just pollute the output.
291 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
292 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
297 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
299 hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
300 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
302 hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
303 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
309 fn check_fn(&mut self, cx: &LateContext, fk: FnKind, _: &hir::FnDecl,
310 _: &hir::Block, span: Span, _: ast::NodeId) {
312 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _) =>
313 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
315 FnKind::Method(_, sig, _) => {
316 if sig.unsafety == hir::Unsafety::Unsafe {
317 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
325 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
326 if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
327 if sig.unsafety == hir::Unsafety::Unsafe {
328 cx.span_lint(UNSAFE_CODE, trait_item.span,
329 "declaration of an `unsafe` method")
338 "detects missing documentation for public members"
341 pub struct MissingDoc {
342 /// Stack of IDs of struct definitions.
343 struct_def_stack: Vec<ast::NodeId>,
345 /// True if inside variant definition
348 /// Stack of whether #[doc(hidden)] is set
349 /// at each level which has lint attributes.
350 doc_hidden_stack: Vec<bool>,
352 /// Private traits or trait items that leaked through. Don't check their methods.
353 private_traits: HashSet<ast::NodeId>,
357 pub fn new() -> MissingDoc {
359 struct_def_stack: vec!(),
361 doc_hidden_stack: vec!(false),
362 private_traits: HashSet::new(),
366 fn doc_hidden(&self) -> bool {
367 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
370 fn check_missing_docs_attrs(&self,
372 id: Option<ast::NodeId>,
373 attrs: &[ast::Attribute],
375 desc: &'static str) {
376 // If we're building a test harness, then warning about
377 // documentation is probably not really relevant right now.
378 if cx.sess().opts.test {
382 // `#[doc(hidden)]` disables missing_docs check.
383 if self.doc_hidden() {
387 // Only check publicly-visible items, using the result from the privacy pass.
388 // It's an option so the crate root can also use this function (it doesn't
390 if let Some(ref id) = id {
391 if !cx.exported_items.contains(id) {
396 let has_doc = attrs.iter().any(|a| {
397 match a.node.value.node {
398 ast::MetaNameValue(ref name, _) if *name == "doc" => true,
403 cx.span_lint(MISSING_DOCS, sp,
404 &format!("missing documentation for {}", desc));
409 impl LintPass for MissingDoc {
410 fn get_lints(&self) -> LintArray {
411 lint_array!(MISSING_DOCS)
415 impl LateLintPass for MissingDoc {
416 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
417 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
418 attr.check_name("doc") && match attr.meta_item_list() {
420 Some(l) => attr::contains_name(&l[..], "hidden"),
423 self.doc_hidden_stack.push(doc_hidden);
426 fn exit_lint_attrs(&mut self, _: &LateContext, _: &[ast::Attribute]) {
427 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
430 fn check_struct_def(&mut self, _: &LateContext, _: &hir::StructDef,
431 _: ast::Name, _: &hir::Generics, id: ast::NodeId) {
432 self.struct_def_stack.push(id);
435 fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::StructDef,
436 _: ast::Name, _: &hir::Generics, id: ast::NodeId) {
437 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
438 assert!(popped == id);
441 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
442 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
445 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
446 let desc = match it.node {
447 hir::ItemFn(..) => "a function",
448 hir::ItemMod(..) => "a module",
449 hir::ItemEnum(..) => "an enum",
450 hir::ItemStruct(..) => "a struct",
451 hir::ItemTrait(_, _, _, ref items) => {
452 // Issue #11592, traits are always considered exported, even when private.
453 if it.vis == hir::Visibility::Inherited {
454 self.private_traits.insert(it.id);
456 self.private_traits.insert(itm.id);
462 hir::ItemTy(..) => "a type alias",
463 hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
464 // If the trait is private, add the impl items to private_traits so they don't get
465 // reported for missing docs.
466 let real_trait = cx.tcx.trait_ref_to_def_id(trait_ref);
467 if let Some(node_id) = cx.tcx.map.as_local_node_id(real_trait) {
468 match cx.tcx.map.find(node_id) {
469 Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
470 for itm in impl_items {
471 self.private_traits.insert(itm.id);
479 hir::ItemConst(..) => "a constant",
480 hir::ItemStatic(..) => "a static",
484 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
487 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
488 if self.private_traits.contains(&trait_item.id) { return }
490 let desc = match trait_item.node {
491 hir::ConstTraitItem(..) => "an associated constant",
492 hir::MethodTraitItem(..) => "a trait method",
493 hir::TypeTraitItem(..) => "an associated type",
496 self.check_missing_docs_attrs(cx, Some(trait_item.id),
498 trait_item.span, desc);
501 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
502 // If the method is an impl for a trait, don't doc.
503 if method_context(cx, impl_item.id, impl_item.span) == MethodLateContext::TraitImpl {
507 let desc = match impl_item.node {
508 hir::ConstImplItem(..) => "an associated constant",
509 hir::MethodImplItem(..) => "a method",
510 hir::TypeImplItem(_) => "an associated type",
512 self.check_missing_docs_attrs(cx, Some(impl_item.id),
514 impl_item.span, desc);
517 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
518 if let hir::NamedField(_, vis) = sf.node.kind {
519 if vis == hir::Public || self.in_variant {
520 let cur_struct_def = *self.struct_def_stack.last()
521 .expect("empty struct_def_stack");
522 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
523 &sf.node.attrs, sf.span,
529 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
530 self.check_missing_docs_attrs(cx, Some(v.node.id), &v.node.attrs, v.span, "a variant");
531 assert!(!self.in_variant);
532 self.in_variant = true;
535 fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
536 assert!(self.in_variant);
537 self.in_variant = false;
542 pub MISSING_COPY_IMPLEMENTATIONS,
544 "detects potentially-forgotten implementations of `Copy`"
547 #[derive(Copy, Clone)]
548 pub struct MissingCopyImplementations;
550 impl LintPass for MissingCopyImplementations {
551 fn get_lints(&self) -> LintArray {
552 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
556 impl LateLintPass for MissingCopyImplementations {
557 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
558 if !cx.exported_items.contains(&item.id) {
561 let (def, ty) = match item.node {
562 hir::ItemStruct(_, ref ast_generics) => {
563 if ast_generics.is_parameterized() {
566 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
567 (def, cx.tcx.mk_struct(def,
568 cx.tcx.mk_substs(Substs::empty())))
570 hir::ItemEnum(_, ref ast_generics) => {
571 if ast_generics.is_parameterized() {
574 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
575 (def, cx.tcx.mk_enum(def,
576 cx.tcx.mk_substs(Substs::empty())))
580 if def.has_dtor() { return; }
581 let parameter_environment = cx.tcx.empty_parameter_environment();
582 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
584 if !ty.moves_by_default(¶meter_environment, item.span) {
587 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
588 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
590 "type could implement `Copy`; consider adding `impl \
597 MISSING_DEBUG_IMPLEMENTATIONS,
599 "detects missing implementations of fmt::Debug"
602 pub struct MissingDebugImplementations {
603 impling_types: Option<NodeSet>,
606 impl MissingDebugImplementations {
607 pub fn new() -> MissingDebugImplementations {
608 MissingDebugImplementations {
614 impl LintPass for MissingDebugImplementations {
615 fn get_lints(&self) -> LintArray {
616 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
620 impl LateLintPass for MissingDebugImplementations {
621 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
622 if !cx.exported_items.contains(&item.id) {
627 hir::ItemStruct(..) | hir::ItemEnum(..) => {},
631 let debug = match cx.tcx.lang_items.debug_trait() {
632 Some(debug) => debug,
636 if self.impling_types.is_none() {
637 let debug_def = cx.tcx.lookup_trait_def(debug);
638 let mut impls = NodeSet();
639 debug_def.for_each_impl(cx.tcx, |d| {
640 if let Some(n) = cx.tcx.map.as_local_node_id(d) {
641 if let Some(ty_def) = cx.tcx.node_id_to_type(n).ty_to_def_id() {
642 if let Some(node_id) = cx.tcx.map.as_local_node_id(ty_def) {
643 impls.insert(node_id);
649 self.impling_types = Some(impls);
650 debug!("{:?}", self.impling_types);
653 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
654 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
656 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
657 or a manual implementation")
665 "detects use of #[deprecated] items"
668 /// Checks for use of items with `#[deprecated]` attributes
669 #[derive(Copy, Clone)]
670 pub struct Stability;
673 fn lint(&self, cx: &LateContext, _id: DefId,
674 span: Span, stability: &Option<&attr::Stability>) {
675 // Deprecated attributes apply in-crate and cross-crate.
676 let (lint, label) = match *stability {
677 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
678 (DEPRECATED, "deprecated"),
682 output(cx, span, stability, lint, label);
684 fn output(cx: &LateContext, span: Span, stability: &Option<&attr::Stability>,
685 lint: &'static Lint, label: &'static str) {
686 let msg = match *stability {
687 Some(&attr::Stability { reason: Some(ref s), .. }) => {
688 format!("use of {} item: {}", label, *s)
690 _ => format!("use of {} item", label)
693 cx.span_lint(lint, span, &msg[..]);
698 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
700 level: match stab.level {
701 attr::Unstable => attr::Unstable,
702 attr::Stable => attr::Stable,
704 feature: stab.feature.clone(),
705 since: stab.since.clone(),
706 deprecated_since: stab.deprecated_since.clone(),
707 reason: stab.reason.clone(),
712 impl LintPass for Stability {
713 fn get_lints(&self) -> LintArray {
714 lint_array!(DEPRECATED)
718 impl LateLintPass for Stability {
719 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
720 stability::check_item(cx.tcx, item, false,
722 self.lint(cx, id, sp,
723 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
726 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
727 stability::check_expr(cx.tcx, e,
729 self.lint(cx, id, sp,
730 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
733 fn check_path(&mut self, cx: &LateContext, path: &hir::Path, id: ast::NodeId) {
734 stability::check_path(cx.tcx, path, id,
736 self.lint(cx, id, sp,
737 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
740 fn check_path_list_item(&mut self, cx: &LateContext, item: &hir::PathListItem) {
741 stability::check_path_list_item(cx.tcx, item,
743 self.lint(cx, id, sp,
744 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
747 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
748 stability::check_pat(cx.tcx, pat,
750 self.lint(cx, id, sp,
751 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
756 pub UNCONDITIONAL_RECURSION,
758 "functions that cannot return without calling themselves"
761 #[derive(Copy, Clone)]
762 pub struct UnconditionalRecursion;
765 impl LintPass for UnconditionalRecursion {
766 fn get_lints(&self) -> LintArray {
767 lint_array![UNCONDITIONAL_RECURSION]
771 impl LateLintPass for UnconditionalRecursion {
772 fn check_fn(&mut self, cx: &LateContext, fn_kind: FnKind, _: &hir::FnDecl,
773 blk: &hir::Block, sp: Span, id: ast::NodeId) {
774 let method = match fn_kind {
775 FnKind::ItemFn(..) => None,
776 FnKind::Method(..) => {
777 cx.tcx.impl_or_trait_item(cx.tcx.map.local_def_id(id)).as_opt_method()
779 // closures can't recur, so they don't matter.
780 FnKind::Closure => return
783 // Walk through this function (say `f`) looking to see if
784 // every possible path references itself, i.e. the function is
785 // called recursively unconditionally. This is done by trying
786 // to find a path from the entry node to the exit node that
787 // *doesn't* call `f` by traversing from the entry while
788 // pretending that calls of `f` are sinks (i.e. ignoring any
789 // exit edges from them).
791 // NB. this has an edge case with non-returning statements,
792 // like `loop {}` or `panic!()`: control flow never reaches
793 // the exit node through these, so one can have a function
794 // that never actually calls itselfs but is still picked up by
797 // fn f(cond: bool) {
798 // if !cond { panic!() } // could come from `assert!(cond)`
802 // In general, functions of that form may be able to call
803 // itself a finite number of times and then diverge. The lint
804 // considers this to be an error for two reasons, (a) it is
805 // easier to implement, and (b) it seems rare to actually want
806 // to have behaviour like the above, rather than
807 // e.g. accidentally recurring after an assert.
809 let cfg = cfg::CFG::new(cx.tcx, blk);
811 let mut work_queue = vec![cfg.entry];
812 let mut reached_exit_without_self_call = false;
813 let mut self_call_spans = vec![];
814 let mut visited = HashSet::new();
816 while let Some(idx) = work_queue.pop() {
819 reached_exit_without_self_call = true;
823 let cfg_id = idx.node_id();
824 if visited.contains(&cfg_id) {
828 visited.insert(cfg_id);
830 let node_id = cfg.graph.node_data(idx).id();
832 // is this a recursive call?
833 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
835 Some(ref method) => {
836 expr_refers_to_this_method(cx.tcx, method, node_id)
838 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
844 self_call_spans.push(cx.tcx.map.span(node_id));
845 // this is a self call, so we shouldn't explore past
846 // this node in the CFG.
849 // add the successors of this node to explore the graph further.
850 for (_, edge) in cfg.graph.outgoing_edges(idx) {
851 let target_idx = edge.target();
852 let target_cfg_id = target_idx.node_id();
853 if !visited.contains(&target_cfg_id) {
854 work_queue.push(target_idx)
859 // Check the number of self calls because a function that
860 // doesn't return (e.g. calls a `-> !` function or `loop { /*
861 // no break */ }`) shouldn't be linted unless it actually
863 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
864 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
865 "function cannot return without recurring");
867 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
868 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
869 let sess = cx.sess();
870 // offer some help to the programmer.
871 for call in &self_call_spans {
872 sess.span_note(*call, "recursive call site")
874 sess.fileline_help(sp, "a `loop` may express intention \
875 better if this is on purpose")
882 // Functions for identifying if the given Expr NodeId `id`
883 // represents a call to the function `fn_id`/method `method`.
885 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
887 id: ast::NodeId) -> bool {
888 match tcx.map.get(id) {
889 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
894 |def| def.def_id() == tcx.map.local_def_id(fn_id))
900 // Check if the expression `id` performs a call to `method`.
901 fn expr_refers_to_this_method(tcx: &ty::ctxt,
903 id: ast::NodeId) -> bool {
904 let tables = tcx.tables.borrow();
906 // Check for method calls and overloaded operators.
907 if let Some(m) = tables.method_map.get(&ty::MethodCall::expr(id)) {
908 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
913 // Check for overloaded autoderef method calls.
914 if let Some(&adjustment::AdjustDerefRef(ref adj)) = tables.adjustments.get(&id) {
915 for i in 0..adj.autoderefs {
916 let method_call = ty::MethodCall::autoderef(id, i as u32);
917 if let Some(m) = tables.method_map.get(&method_call) {
918 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
925 // Check for calls to methods via explicit paths (e.g. `T::method()`).
926 match tcx.map.get(id) {
927 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
928 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
929 Some(def::DefMethod(def_id)) => {
930 let no_substs = &ty::ItemSubsts::empty();
931 let ts = tables.item_substs.get(&callee.id).unwrap_or(no_substs);
932 method_call_refers_to_method(tcx, method, def_id, &ts.substs, id)
941 // Check if the method call to the method with the ID `callee_id`
942 // and instantiated with `callee_substs` refers to method `method`.
943 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
946 callee_substs: &Substs<'tcx>,
947 expr_id: ast::NodeId) -> bool {
948 let callee_item = tcx.impl_or_trait_item(callee_id);
950 match callee_item.container() {
951 // This is an inherent method, so the `def_id` refers
952 // directly to the method definition.
953 ty::ImplContainer(_) => {
954 callee_id == method.def_id
957 // A trait method, from any number of possible sources.
958 // Attempt to select a concrete impl before checking.
959 ty::TraitContainer(trait_def_id) => {
960 let trait_substs = callee_substs.clone().method_to_trait();
961 let trait_substs = tcx.mk_substs(trait_substs);
962 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
963 let trait_ref = ty::Binder(trait_ref);
964 let span = tcx.map.span(expr_id);
966 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
967 trait_ref.to_poly_trait_predicate());
969 // unwrap() is ok here b/c `method` is the method
970 // defined in this crate whose body we are
971 // checking, so it's always local
972 let node_id = tcx.map.as_local_node_id(method.def_id).unwrap();
974 let param_env = ty::ParameterEnvironment::for_item(tcx, node_id);
975 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
976 let mut selcx = traits::SelectionContext::new(&infcx);
977 match selcx.select(&obligation) {
978 // The method comes from a `T: Trait` bound.
979 // If `T` is `Self`, then this call is inside
980 // a default method definition.
981 Ok(Some(traits::VtableParam(_))) => {
982 let self_ty = callee_substs.self_ty();
983 let on_self = self_ty.map_or(false, |t| t.is_self());
984 // We can only be recurring in a default
985 // method if we're being called literally
986 // on the `Self` type.
987 on_self && callee_id == method.def_id
990 // The `impl` is known, so we check that with a
992 Ok(Some(traits::VtableImpl(vtable_impl))) => {
993 let container = ty::ImplContainer(vtable_impl.impl_def_id);
994 // It matches if it comes from the same impl,
995 // and has the same method name.
996 container == method.container
997 && callee_item.name() == method.name
1000 // There's no way to know if this call is
1001 // recursive, so we assume it's not.
1013 "compiler plugin used as ordinary library in non-plugin crate"
1016 #[derive(Copy, Clone)]
1017 pub struct PluginAsLibrary;
1019 impl LintPass for PluginAsLibrary {
1020 fn get_lints(&self) -> LintArray {
1021 lint_array![PLUGIN_AS_LIBRARY]
1025 impl LateLintPass for PluginAsLibrary {
1026 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1027 if cx.sess().plugin_registrar_fn.get().is_some() {
1028 // We're compiling a plugin; it's fine to link other plugins.
1033 hir::ItemExternCrate(..) => (),
1037 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
1038 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
1040 // Probably means we aren't linking the crate for some reason.
1042 // Not sure if / when this could happen.
1047 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
1048 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
1049 "compiler plugin used as an ordinary library");
1055 PRIVATE_NO_MANGLE_FNS,
1057 "functions marked #[no_mangle] should be exported"
1061 PRIVATE_NO_MANGLE_STATICS,
1063 "statics marked #[no_mangle] should be exported"
1067 NO_MANGLE_CONST_ITEMS,
1069 "const items will not have their symbols exported"
1072 #[derive(Copy, Clone)]
1073 pub struct InvalidNoMangleItems;
1075 impl LintPass for InvalidNoMangleItems {
1076 fn get_lints(&self) -> LintArray {
1077 lint_array!(PRIVATE_NO_MANGLE_FNS,
1078 PRIVATE_NO_MANGLE_STATICS,
1079 NO_MANGLE_CONST_ITEMS)
1083 impl LateLintPass for InvalidNoMangleItems {
1084 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1086 hir::ItemFn(..) => {
1087 if attr::contains_name(&it.attrs, "no_mangle") &&
1088 !cx.exported_items.contains(&it.id) {
1089 let msg = format!("function {} is marked #[no_mangle], but not exported",
1091 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1094 hir::ItemStatic(..) => {
1095 if attr::contains_name(&it.attrs, "no_mangle") &&
1096 !cx.exported_items.contains(&it.id) {
1097 let msg = format!("static {} is marked #[no_mangle], but not exported",
1099 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1102 hir::ItemConst(..) => {
1103 if attr::contains_name(&it.attrs, "no_mangle") {
1104 // Const items do not refer to a particular location in memory, and therefore
1105 // don't have anything to attach a symbol to
1106 let msg = "const items should never be #[no_mangle], consider instead using \
1108 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1116 #[derive(Clone, Copy)]
1117 pub struct MutableTransmutes;
1122 "mutating transmuted &mut T from &T may cause undefined behavior"
1125 impl LintPass for MutableTransmutes {
1126 fn get_lints(&self) -> LintArray {
1127 lint_array!(MUTABLE_TRANSMUTES)
1131 impl LateLintPass for MutableTransmutes {
1132 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1133 use syntax::abi::RustIntrinsic;
1135 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
1136 consider instead using an UnsafeCell";
1137 match get_transmute_from_to(cx, expr) {
1138 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1139 if to_mt.mutbl == hir::Mutability::MutMutable
1140 && from_mt.mutbl == hir::Mutability::MutImmutable {
1141 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1147 fn get_transmute_from_to<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr)
1148 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1150 hir::ExprPath(..) => (),
1153 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
1154 if !def_id_is_transmute(cx, did) {
1157 let typ = cx.tcx.node_id_to_type(expr.id);
1159 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
1160 if let ty::FnConverging(to) = bare_fn.sig.0.output {
1161 let from = bare_fn.sig.0.inputs[0];
1162 return Some((&from.sty, &to.sty));
1171 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1172 match cx.tcx.lookup_item_type(def_id).ty.sty {
1173 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
1176 cx.tcx.with_path(def_id, |path| match path.last() {
1177 Some(ref last) => last.name().as_str() == "transmute",
1184 /// Forbids using the `#[feature(...)]` attribute
1185 #[derive(Copy, Clone)]
1186 pub struct UnstableFeatures;
1191 "enabling unstable features (deprecated. do not use)"
1194 impl LintPass for UnstableFeatures {
1195 fn get_lints(&self) -> LintArray {
1196 lint_array!(UNSTABLE_FEATURES)
1200 impl LateLintPass for UnstableFeatures {
1201 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1202 if attr::contains_name(&[attr.node.value.clone()], "feature") {
1203 if let Some(items) = attr.node.value.meta_item_list() {
1205 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
1212 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
1213 /// attribute (see issue #24585).
1214 #[derive(Copy, Clone)]
1215 pub struct DropWithReprExtern;
1218 DROP_WITH_REPR_EXTERN,
1220 "use of #[repr(C)] on a type that implements Drop"
1223 impl LintPass for DropWithReprExtern {
1224 fn get_lints(&self) -> LintArray {
1225 lint_array!(DROP_WITH_REPR_EXTERN)
1229 impl LateLintPass for DropWithReprExtern {
1230 fn check_crate(&mut self, ctx: &LateContext, _: &hir::Crate) {
1231 let drop_trait = match ctx.tcx.lang_items.drop_trait() {
1232 Some(id) => ctx.tcx.lookup_trait_def(id), None => { return }
1234 drop_trait.for_each_impl(ctx.tcx, |drop_impl_did| {
1235 if !drop_impl_did.is_local() {
1238 let dtor_self_type = ctx.tcx.lookup_item_type(drop_impl_did).ty;
1240 match dtor_self_type.sty {
1241 ty::TyEnum(self_type_def, _) |
1242 ty::TyStruct(self_type_def, _) => {
1243 let self_type_did = self_type_def.did;
1244 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
1245 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
1246 self_type_def.dtor_kind().has_drop_flag() {
1247 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
1249 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
1251 ctx.span_lint(DROP_WITH_REPR_EXTERN,
1253 "implementing Drop adds hidden state to types, \
1254 possibly conflicting with `#[repr(C)]`");
1255 // FIXME #19668: could be span_lint_note instead of manual guard.
1256 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
1257 ctx.sess().span_note(self_defn_span,
1258 "the `#[repr(C)]` attribute is attached here");