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::VariantData,
431 _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
432 self.struct_def_stack.push(item_id);
435 fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::VariantData,
436 _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
437 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
438 assert!(popped == item_id);
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.data.id()),
531 &v.node.attrs, v.span, "a variant");
532 assert!(!self.in_variant);
533 self.in_variant = true;
536 fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
537 assert!(self.in_variant);
538 self.in_variant = false;
543 pub MISSING_COPY_IMPLEMENTATIONS,
545 "detects potentially-forgotten implementations of `Copy`"
548 #[derive(Copy, Clone)]
549 pub struct MissingCopyImplementations;
551 impl LintPass for MissingCopyImplementations {
552 fn get_lints(&self) -> LintArray {
553 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
557 impl LateLintPass for MissingCopyImplementations {
558 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
559 if !cx.exported_items.contains(&item.id) {
562 let (def, ty) = match item.node {
563 hir::ItemStruct(_, ref ast_generics) => {
564 if ast_generics.is_parameterized() {
567 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
568 (def, cx.tcx.mk_struct(def,
569 cx.tcx.mk_substs(Substs::empty())))
571 hir::ItemEnum(_, ref ast_generics) => {
572 if ast_generics.is_parameterized() {
575 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
576 (def, cx.tcx.mk_enum(def,
577 cx.tcx.mk_substs(Substs::empty())))
581 if def.has_dtor() { return; }
582 let parameter_environment = cx.tcx.empty_parameter_environment();
583 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
585 if !ty.moves_by_default(¶meter_environment, item.span) {
588 if parameter_environment.can_type_implement_copy(ty, item.span).is_ok() {
589 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
591 "type could implement `Copy`; consider adding `impl \
598 MISSING_DEBUG_IMPLEMENTATIONS,
600 "detects missing implementations of fmt::Debug"
603 pub struct MissingDebugImplementations {
604 impling_types: Option<NodeSet>,
607 impl MissingDebugImplementations {
608 pub fn new() -> MissingDebugImplementations {
609 MissingDebugImplementations {
615 impl LintPass for MissingDebugImplementations {
616 fn get_lints(&self) -> LintArray {
617 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
621 impl LateLintPass for MissingDebugImplementations {
622 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
623 if !cx.exported_items.contains(&item.id) {
628 hir::ItemStruct(..) | hir::ItemEnum(..) => {},
632 let debug = match cx.tcx.lang_items.debug_trait() {
633 Some(debug) => debug,
637 if self.impling_types.is_none() {
638 let debug_def = cx.tcx.lookup_trait_def(debug);
639 let mut impls = NodeSet();
640 debug_def.for_each_impl(cx.tcx, |d| {
641 if let Some(n) = cx.tcx.map.as_local_node_id(d) {
642 if let Some(ty_def) = cx.tcx.node_id_to_type(n).ty_to_def_id() {
643 if let Some(node_id) = cx.tcx.map.as_local_node_id(ty_def) {
644 impls.insert(node_id);
650 self.impling_types = Some(impls);
651 debug!("{:?}", self.impling_types);
654 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
655 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
657 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
658 or a manual implementation")
666 "detects use of #[deprecated] items"
669 /// Checks for use of items with `#[deprecated]` attributes
670 #[derive(Copy, Clone)]
671 pub struct Stability;
674 fn lint(&self, cx: &LateContext, _id: DefId,
675 span: Span, stability: &Option<&attr::Stability>) {
676 // Deprecated attributes apply in-crate and cross-crate.
677 let (lint, label) = match *stability {
678 Some(&attr::Stability { deprecated_since: Some(_), .. }) =>
679 (DEPRECATED, "deprecated"),
683 output(cx, span, stability, lint, label);
685 fn output(cx: &LateContext, span: Span, stability: &Option<&attr::Stability>,
686 lint: &'static Lint, label: &'static str) {
687 let msg = match *stability {
688 Some(&attr::Stability { reason: Some(ref s), .. }) => {
689 format!("use of {} item: {}", label, *s)
691 _ => format!("use of {} item", label)
694 cx.span_lint(lint, span, &msg[..]);
699 fn hir_to_ast_stability(stab: &attr::Stability) -> attr::Stability {
701 level: match stab.level {
702 attr::Unstable => attr::Unstable,
703 attr::Stable => attr::Stable,
705 feature: stab.feature.clone(),
706 since: stab.since.clone(),
707 deprecated_since: stab.deprecated_since.clone(),
708 reason: stab.reason.clone(),
713 impl LintPass for Stability {
714 fn get_lints(&self) -> LintArray {
715 lint_array!(DEPRECATED)
719 impl LateLintPass for Stability {
720 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
721 stability::check_item(cx.tcx, item, false,
723 self.lint(cx, id, sp,
724 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
727 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
728 stability::check_expr(cx.tcx, e,
730 self.lint(cx, id, sp,
731 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
734 fn check_path(&mut self, cx: &LateContext, path: &hir::Path, id: ast::NodeId) {
735 stability::check_path(cx.tcx, path, id,
737 self.lint(cx, id, sp,
738 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
741 fn check_path_list_item(&mut self, cx: &LateContext, item: &hir::PathListItem) {
742 stability::check_path_list_item(cx.tcx, item,
744 self.lint(cx, id, sp,
745 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
748 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
749 stability::check_pat(cx.tcx, pat,
751 self.lint(cx, id, sp,
752 &stab.map(|s| hir_to_ast_stability(s)).as_ref()));
757 pub UNCONDITIONAL_RECURSION,
759 "functions that cannot return without calling themselves"
762 #[derive(Copy, Clone)]
763 pub struct UnconditionalRecursion;
766 impl LintPass for UnconditionalRecursion {
767 fn get_lints(&self) -> LintArray {
768 lint_array![UNCONDITIONAL_RECURSION]
772 impl LateLintPass for UnconditionalRecursion {
773 fn check_fn(&mut self, cx: &LateContext, fn_kind: FnKind, _: &hir::FnDecl,
774 blk: &hir::Block, sp: Span, id: ast::NodeId) {
775 let method = match fn_kind {
776 FnKind::ItemFn(..) => None,
777 FnKind::Method(..) => {
778 cx.tcx.impl_or_trait_item(cx.tcx.map.local_def_id(id)).as_opt_method()
780 // closures can't recur, so they don't matter.
781 FnKind::Closure => return
784 // Walk through this function (say `f`) looking to see if
785 // every possible path references itself, i.e. the function is
786 // called recursively unconditionally. This is done by trying
787 // to find a path from the entry node to the exit node that
788 // *doesn't* call `f` by traversing from the entry while
789 // pretending that calls of `f` are sinks (i.e. ignoring any
790 // exit edges from them).
792 // NB. this has an edge case with non-returning statements,
793 // like `loop {}` or `panic!()`: control flow never reaches
794 // the exit node through these, so one can have a function
795 // that never actually calls itselfs but is still picked up by
798 // fn f(cond: bool) {
799 // if !cond { panic!() } // could come from `assert!(cond)`
803 // In general, functions of that form may be able to call
804 // itself a finite number of times and then diverge. The lint
805 // considers this to be an error for two reasons, (a) it is
806 // easier to implement, and (b) it seems rare to actually want
807 // to have behaviour like the above, rather than
808 // e.g. accidentally recurring after an assert.
810 let cfg = cfg::CFG::new(cx.tcx, blk);
812 let mut work_queue = vec![cfg.entry];
813 let mut reached_exit_without_self_call = false;
814 let mut self_call_spans = vec![];
815 let mut visited = HashSet::new();
817 while let Some(idx) = work_queue.pop() {
820 reached_exit_without_self_call = true;
824 let cfg_id = idx.node_id();
825 if visited.contains(&cfg_id) {
829 visited.insert(cfg_id);
831 let node_id = cfg.graph.node_data(idx).id();
833 // is this a recursive call?
834 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
836 Some(ref method) => {
837 expr_refers_to_this_method(cx.tcx, method, node_id)
839 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
845 self_call_spans.push(cx.tcx.map.span(node_id));
846 // this is a self call, so we shouldn't explore past
847 // this node in the CFG.
850 // add the successors of this node to explore the graph further.
851 for (_, edge) in cfg.graph.outgoing_edges(idx) {
852 let target_idx = edge.target();
853 let target_cfg_id = target_idx.node_id();
854 if !visited.contains(&target_cfg_id) {
855 work_queue.push(target_idx)
860 // Check the number of self calls because a function that
861 // doesn't return (e.g. calls a `-> !` function or `loop { /*
862 // no break */ }`) shouldn't be linted unless it actually
864 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
865 cx.span_lint(UNCONDITIONAL_RECURSION, sp,
866 "function cannot return without recurring");
868 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
869 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
870 let sess = cx.sess();
871 // offer some help to the programmer.
872 for call in &self_call_spans {
873 sess.span_note(*call, "recursive call site")
875 sess.fileline_help(sp, "a `loop` may express intention \
876 better if this is on purpose")
883 // Functions for identifying if the given Expr NodeId `id`
884 // represents a call to the function `fn_id`/method `method`.
886 fn expr_refers_to_this_fn(tcx: &ty::ctxt,
888 id: ast::NodeId) -> bool {
889 match tcx.map.get(id) {
890 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
895 |def| def.def_id() == tcx.map.local_def_id(fn_id))
901 // Check if the expression `id` performs a call to `method`.
902 fn expr_refers_to_this_method(tcx: &ty::ctxt,
904 id: ast::NodeId) -> bool {
905 // Check for method calls and overloaded operators.
906 let opt_m = tcx.tables.borrow().method_map.get(&ty::MethodCall::expr(id)).cloned();
907 if let Some(m) = opt_m {
908 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
913 // Check for overloaded autoderef method calls.
914 let opt_adj = tcx.tables.borrow().adjustments.get(&id).cloned();
915 if let Some(adjustment::AdjustDerefRef(adj)) = opt_adj {
916 for i in 0..adj.autoderefs {
917 let method_call = ty::MethodCall::autoderef(id, i as u32);
918 if let Some(m) = tcx.tables.borrow().method_map
921 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
928 // Check for calls to methods via explicit paths (e.g. `T::method()`).
929 match tcx.map.get(id) {
930 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
931 match tcx.def_map.borrow().get(&callee.id).map(|d| d.full_def()) {
932 Some(def::DefMethod(def_id)) => {
934 tcx.tables.borrow().item_substs
937 .unwrap_or_else(|| ty::ItemSubsts::empty());
938 method_call_refers_to_method(
939 tcx, method, def_id, &item_substs.substs, id)
948 // Check if the method call to the method with the ID `callee_id`
949 // and instantiated with `callee_substs` refers to method `method`.
950 fn method_call_refers_to_method<'tcx>(tcx: &ty::ctxt<'tcx>,
953 callee_substs: &Substs<'tcx>,
954 expr_id: ast::NodeId) -> bool {
955 let callee_item = tcx.impl_or_trait_item(callee_id);
957 match callee_item.container() {
958 // This is an inherent method, so the `def_id` refers
959 // directly to the method definition.
960 ty::ImplContainer(_) => {
961 callee_id == method.def_id
964 // A trait method, from any number of possible sources.
965 // Attempt to select a concrete impl before checking.
966 ty::TraitContainer(trait_def_id) => {
967 let trait_substs = callee_substs.clone().method_to_trait();
968 let trait_substs = tcx.mk_substs(trait_substs);
969 let trait_ref = ty::TraitRef::new(trait_def_id, trait_substs);
970 let trait_ref = ty::Binder(trait_ref);
971 let span = tcx.map.span(expr_id);
973 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
974 trait_ref.to_poly_trait_predicate());
976 // unwrap() is ok here b/c `method` is the method
977 // defined in this crate whose body we are
978 // checking, so it's always local
979 let node_id = tcx.map.as_local_node_id(method.def_id).unwrap();
981 let param_env = ty::ParameterEnvironment::for_item(tcx, node_id);
982 let infcx = infer::new_infer_ctxt(tcx, &tcx.tables, Some(param_env), false);
983 let mut selcx = traits::SelectionContext::new(&infcx);
984 match selcx.select(&obligation) {
985 // The method comes from a `T: Trait` bound.
986 // If `T` is `Self`, then this call is inside
987 // a default method definition.
988 Ok(Some(traits::VtableParam(_))) => {
989 let self_ty = callee_substs.self_ty();
990 let on_self = self_ty.map_or(false, |t| t.is_self());
991 // We can only be recurring in a default
992 // method if we're being called literally
993 // on the `Self` type.
994 on_self && callee_id == method.def_id
997 // The `impl` is known, so we check that with a
999 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1000 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1001 // It matches if it comes from the same impl,
1002 // and has the same method name.
1003 container == method.container
1004 && callee_item.name() == method.name
1007 // There's no way to know if this call is
1008 // recursive, so we assume it's not.
1020 "compiler plugin used as ordinary library in non-plugin crate"
1023 #[derive(Copy, Clone)]
1024 pub struct PluginAsLibrary;
1026 impl LintPass for PluginAsLibrary {
1027 fn get_lints(&self) -> LintArray {
1028 lint_array![PLUGIN_AS_LIBRARY]
1032 impl LateLintPass for PluginAsLibrary {
1033 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1034 if cx.sess().plugin_registrar_fn.get().is_some() {
1035 // We're compiling a plugin; it's fine to link other plugins.
1040 hir::ItemExternCrate(..) => (),
1044 let md = match cx.sess().cstore.find_extern_mod_stmt_cnum(it.id) {
1045 Some(cnum) => cx.sess().cstore.get_crate_data(cnum),
1047 // Probably means we aren't linking the crate for some reason.
1049 // Not sure if / when this could happen.
1054 if decoder::get_plugin_registrar_fn(md.data()).is_some() {
1055 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
1056 "compiler plugin used as an ordinary library");
1062 PRIVATE_NO_MANGLE_FNS,
1064 "functions marked #[no_mangle] should be exported"
1068 PRIVATE_NO_MANGLE_STATICS,
1070 "statics marked #[no_mangle] should be exported"
1074 NO_MANGLE_CONST_ITEMS,
1076 "const items will not have their symbols exported"
1079 #[derive(Copy, Clone)]
1080 pub struct InvalidNoMangleItems;
1082 impl LintPass for InvalidNoMangleItems {
1083 fn get_lints(&self) -> LintArray {
1084 lint_array!(PRIVATE_NO_MANGLE_FNS,
1085 PRIVATE_NO_MANGLE_STATICS,
1086 NO_MANGLE_CONST_ITEMS)
1090 impl LateLintPass for InvalidNoMangleItems {
1091 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1093 hir::ItemFn(..) => {
1094 if attr::contains_name(&it.attrs, "no_mangle") &&
1095 !cx.exported_items.contains(&it.id) {
1096 let msg = format!("function {} is marked #[no_mangle], but not exported",
1098 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1101 hir::ItemStatic(..) => {
1102 if attr::contains_name(&it.attrs, "no_mangle") &&
1103 !cx.exported_items.contains(&it.id) {
1104 let msg = format!("static {} is marked #[no_mangle], but not exported",
1106 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1109 hir::ItemConst(..) => {
1110 if attr::contains_name(&it.attrs, "no_mangle") {
1111 // Const items do not refer to a particular location in memory, and therefore
1112 // don't have anything to attach a symbol to
1113 let msg = "const items should never be #[no_mangle], consider instead using \
1115 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1123 #[derive(Clone, Copy)]
1124 pub struct MutableTransmutes;
1129 "mutating transmuted &mut T from &T may cause undefined behavior"
1132 impl LintPass for MutableTransmutes {
1133 fn get_lints(&self) -> LintArray {
1134 lint_array!(MUTABLE_TRANSMUTES)
1138 impl LateLintPass for MutableTransmutes {
1139 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1140 use syntax::abi::RustIntrinsic;
1142 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
1143 consider instead using an UnsafeCell";
1144 match get_transmute_from_to(cx, expr) {
1145 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1146 if to_mt.mutbl == hir::Mutability::MutMutable
1147 && from_mt.mutbl == hir::Mutability::MutImmutable {
1148 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1154 fn get_transmute_from_to<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr)
1155 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1157 hir::ExprPath(..) => (),
1160 if let def::DefFn(did, _) = cx.tcx.resolve_expr(expr) {
1161 if !def_id_is_transmute(cx, did) {
1164 let typ = cx.tcx.node_id_to_type(expr.id);
1166 ty::TyBareFn(_, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
1167 if let ty::FnConverging(to) = bare_fn.sig.0.output {
1168 let from = bare_fn.sig.0.inputs[0];
1169 return Some((&from.sty, &to.sty));
1178 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1179 match cx.tcx.lookup_item_type(def_id).ty.sty {
1180 ty::TyBareFn(_, ref bfty) if bfty.abi == RustIntrinsic => (),
1183 cx.tcx.with_path(def_id, |path| match path.last() {
1184 Some(ref last) => last.name().as_str() == "transmute",
1191 /// Forbids using the `#[feature(...)]` attribute
1192 #[derive(Copy, Clone)]
1193 pub struct UnstableFeatures;
1198 "enabling unstable features (deprecated. do not use)"
1201 impl LintPass for UnstableFeatures {
1202 fn get_lints(&self) -> LintArray {
1203 lint_array!(UNSTABLE_FEATURES)
1207 impl LateLintPass for UnstableFeatures {
1208 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1209 if attr::contains_name(&[attr.node.value.clone()], "feature") {
1210 if let Some(items) = attr.node.value.meta_item_list() {
1212 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
1219 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
1220 /// attribute (see issue #24585).
1221 #[derive(Copy, Clone)]
1222 pub struct DropWithReprExtern;
1225 DROP_WITH_REPR_EXTERN,
1227 "use of #[repr(C)] on a type that implements Drop"
1230 impl LintPass for DropWithReprExtern {
1231 fn get_lints(&self) -> LintArray {
1232 lint_array!(DROP_WITH_REPR_EXTERN)
1236 impl LateLintPass for DropWithReprExtern {
1237 fn check_crate(&mut self, ctx: &LateContext, _: &hir::Crate) {
1238 let drop_trait = match ctx.tcx.lang_items.drop_trait() {
1239 Some(id) => ctx.tcx.lookup_trait_def(id), None => { return }
1241 drop_trait.for_each_impl(ctx.tcx, |drop_impl_did| {
1242 if !drop_impl_did.is_local() {
1245 let dtor_self_type = ctx.tcx.lookup_item_type(drop_impl_did).ty;
1247 match dtor_self_type.sty {
1248 ty::TyEnum(self_type_def, _) |
1249 ty::TyStruct(self_type_def, _) => {
1250 let self_type_did = self_type_def.did;
1251 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
1252 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
1253 self_type_def.dtor_kind().has_drop_flag() {
1254 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
1256 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
1258 ctx.span_lint(DROP_WITH_REPR_EXTERN,
1260 "implementing Drop adds hidden state to types, \
1261 possibly conflicting with `#[repr(C)]`");
1262 // FIXME #19668: could be span_lint_note instead of manual guard.
1263 if ctx.current_level(DROP_WITH_REPR_EXTERN) != Level::Allow {
1264 ctx.sess().span_note(self_defn_span,
1265 "the `#[repr(C)]` attribute is attached here");