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 rustc::hir::def::Def;
32 use rustc::hir::def_id::DefId;
34 use rustc::ty::subst::Substs;
35 use rustc::ty::{self, Ty};
36 use rustc::traits::{self, Reveal};
37 use rustc::hir::map as hir_map;
38 use util::nodemap::NodeSet;
39 use lint::{LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
42 use std::collections::HashSet;
46 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
47 use syntax_pos::{Span, SyntaxContext};
48 use syntax::symbol::keywords;
50 use rustc::hir::{self, PatKind};
51 use rustc::hir::intravisit::FnKind;
53 use bad_style::{MethodLateContext, method_context};
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
61 "suggest using `loop { }` instead of `while true { }`"
64 #[derive(Copy, Clone)]
67 impl LintPass for WhileTrue {
68 fn get_lints(&self) -> LintArray {
69 lint_array!(WHILE_TRUE)
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
74 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
75 if let hir::ExprWhile(ref cond, ..) = e.node {
76 if let hir::ExprLit(ref lit) = cond.node {
77 if let ast::LitKind::Bool(true) = lit.node {
78 if lit.span.ctxt() == SyntaxContext::empty() {
79 let msg = "denote infinite loops with `loop { ... }`";
80 let mut err = cx.struct_span_lint(WHILE_TRUE, e.span, msg);
81 let condition_span = cx.tcx.sess.codemap().def_span(e.span);
82 err.span_suggestion_short(condition_span,
96 "use of owned (Box type) heap memory"
99 #[derive(Copy, Clone)]
100 pub struct BoxPointers;
103 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
104 for leaf_ty in ty.walk() {
105 if leaf_ty.is_box() {
106 let m = format!("type uses owned (Box type) pointers: {}", ty);
107 cx.span_lint(BOX_POINTERS, span, &m);
113 impl LintPass for BoxPointers {
114 fn get_lints(&self) -> LintArray {
115 lint_array!(BOX_POINTERS)
119 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
120 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
125 hir::ItemStruct(..) |
126 hir::ItemUnion(..) => {
127 let def_id = cx.tcx.hir.local_def_id(it.id);
128 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
133 // If it's a struct, we also have to check the fields' types
135 hir::ItemStruct(ref struct_def, _) |
136 hir::ItemUnion(ref struct_def, _) => {
137 for struct_field in struct_def.fields() {
138 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
139 self.check_heap_type(cx, struct_field.span,
140 cx.tcx.type_of(def_id));
147 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
148 let ty = cx.tables.node_id_to_type(e.hir_id);
149 self.check_heap_type(cx, e.span, ty);
154 NON_SHORTHAND_FIELD_PATTERNS,
156 "using `Struct { x: x }` instead of `Struct { x }`"
159 #[derive(Copy, Clone)]
160 pub struct NonShorthandFieldPatterns;
162 impl LintPass for NonShorthandFieldPatterns {
163 fn get_lints(&self) -> LintArray {
164 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
168 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
169 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
170 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
171 for fieldpat in field_pats {
172 if fieldpat.node.is_shorthand {
175 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
176 if ident.node == fieldpat.node.name {
177 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
179 &format!("the `{}:` in this pattern is redundant and can \
192 "usage of `unsafe` code"
195 #[derive(Copy, Clone)]
196 pub struct UnsafeCode;
198 impl LintPass for UnsafeCode {
199 fn get_lints(&self) -> LintArray {
200 lint_array!(UNSAFE_CODE)
205 fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
206 // This comes from a macro that has #[allow_internal_unsafe].
207 if span.allows_unsafe() {
211 cx.span_lint(UNSAFE_CODE, span, desc);
215 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
216 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
217 if let hir::ExprBlock(ref blk) = e.node {
218 // Don't warn about generated blocks, that'll just pollute the output.
219 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
220 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
225 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
227 hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
228 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
231 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
232 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
239 fn check_fn(&mut self,
247 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
248 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
251 FnKind::Method(_, sig, ..) => {
252 if sig.unsafety == hir::Unsafety::Unsafe {
253 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
261 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
262 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
263 if sig.unsafety == hir::Unsafety::Unsafe {
264 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
273 "detects missing documentation for public members"
276 pub struct MissingDoc {
277 /// Stack of whether #[doc(hidden)] is set
278 /// at each level which has lint attributes.
279 doc_hidden_stack: Vec<bool>,
281 /// Private traits or trait items that leaked through. Don't check their methods.
282 private_traits: HashSet<ast::NodeId>,
286 pub fn new() -> MissingDoc {
288 doc_hidden_stack: vec![false],
289 private_traits: HashSet::new(),
293 fn doc_hidden(&self) -> bool {
294 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
297 fn check_missing_docs_attrs(&self,
299 id: Option<ast::NodeId>,
300 attrs: &[ast::Attribute],
302 desc: &'static str) {
303 // If we're building a test harness, then warning about
304 // documentation is probably not really relevant right now.
305 if cx.sess().opts.test {
309 // `#[doc(hidden)]` disables missing_docs check.
310 if self.doc_hidden() {
314 // Only check publicly-visible items, using the result from the privacy pass.
315 // It's an option so the crate root can also use this function (it doesn't
317 if let Some(id) = id {
318 if !cx.access_levels.is_exported(id) {
323 let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
325 cx.span_lint(MISSING_DOCS,
327 &format!("missing documentation for {}", desc));
332 impl LintPass for MissingDoc {
333 fn get_lints(&self) -> LintArray {
334 lint_array!(MISSING_DOCS)
338 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
339 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
340 let doc_hidden = self.doc_hidden() ||
341 attrs.iter().any(|attr| {
342 attr.check_name("doc") &&
343 match attr.meta_item_list() {
345 Some(l) => attr::list_contains_name(&l, "hidden"),
348 self.doc_hidden_stack.push(doc_hidden);
351 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
352 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
355 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
356 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
359 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
360 let desc = match it.node {
361 hir::ItemFn(..) => "a function",
362 hir::ItemMod(..) => "a module",
363 hir::ItemEnum(..) => "an enum",
364 hir::ItemStruct(..) => "a struct",
365 hir::ItemUnion(..) => "a union",
366 hir::ItemTrait(.., ref trait_item_refs) => {
367 // Issue #11592, traits are always considered exported, even when private.
368 if it.vis == hir::Visibility::Inherited {
369 self.private_traits.insert(it.id);
370 for trait_item_ref in trait_item_refs {
371 self.private_traits.insert(trait_item_ref.id.node_id);
377 hir::ItemTy(..) => "a type alias",
378 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
379 // If the trait is private, add the impl items to private_traits so they don't get
380 // reported for missing docs.
381 let real_trait = trait_ref.path.def.def_id();
382 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
383 match cx.tcx.hir.find(node_id) {
384 Some(hir_map::NodeItem(item)) => {
385 if item.vis == hir::Visibility::Inherited {
386 for impl_item_ref in impl_item_refs {
387 self.private_traits.insert(impl_item_ref.id.node_id);
396 hir::ItemConst(..) => "a constant",
397 hir::ItemStatic(..) => "a static",
401 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
404 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
405 if self.private_traits.contains(&trait_item.id) {
409 let desc = match trait_item.node {
410 hir::TraitItemKind::Const(..) => "an associated constant",
411 hir::TraitItemKind::Method(..) => "a trait method",
412 hir::TraitItemKind::Type(..) => "an associated type",
415 self.check_missing_docs_attrs(cx,
422 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
423 // If the method is an impl for a trait, don't doc.
424 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
428 let desc = match impl_item.node {
429 hir::ImplItemKind::Const(..) => "an associated constant",
430 hir::ImplItemKind::Method(..) => "a method",
431 hir::ImplItemKind::Type(_) => "an associated type",
433 self.check_missing_docs_attrs(cx,
440 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
441 if !sf.is_positional() {
442 self.check_missing_docs_attrs(cx,
450 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
451 self.check_missing_docs_attrs(cx,
452 Some(v.node.data.id()),
460 pub MISSING_COPY_IMPLEMENTATIONS,
462 "detects potentially-forgotten implementations of `Copy`"
465 #[derive(Copy, Clone)]
466 pub struct MissingCopyImplementations;
468 impl LintPass for MissingCopyImplementations {
469 fn get_lints(&self) -> LintArray {
470 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
474 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
475 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
476 if !cx.access_levels.is_reachable(item.id) {
479 let (def, ty) = match item.node {
480 hir::ItemStruct(_, ref ast_generics) => {
481 if ast_generics.is_parameterized() {
484 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
485 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
487 hir::ItemUnion(_, ref ast_generics) => {
488 if ast_generics.is_parameterized() {
491 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
492 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
494 hir::ItemEnum(_, ref ast_generics) => {
495 if ast_generics.is_parameterized() {
498 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
499 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
503 if def.has_dtor(cx.tcx) {
506 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
507 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
510 if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
511 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
513 "type could implement `Copy`; consider adding `impl \
520 MISSING_DEBUG_IMPLEMENTATIONS,
522 "detects missing implementations of fmt::Debug"
525 pub struct MissingDebugImplementations {
526 impling_types: Option<NodeSet>,
529 impl MissingDebugImplementations {
530 pub fn new() -> MissingDebugImplementations {
531 MissingDebugImplementations { impling_types: None }
535 impl LintPass for MissingDebugImplementations {
536 fn get_lints(&self) -> LintArray {
537 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
541 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
542 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
543 if !cx.access_levels.is_reachable(item.id) {
548 hir::ItemStruct(..) |
550 hir::ItemEnum(..) => {}
554 let debug = match cx.tcx.lang_items().debug_trait() {
555 Some(debug) => debug,
559 if self.impling_types.is_none() {
560 let mut impls = NodeSet();
561 cx.tcx.for_each_impl(debug, |d| {
562 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
563 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
564 impls.insert(node_id);
569 self.impling_types = Some(impls);
570 debug!("{:?}", self.impling_types);
573 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
574 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
576 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
577 or a manual implementation")
583 pub ANONYMOUS_PARAMETERS,
585 "detects anonymous parameters"
588 /// Checks for use of anonymous parameters (RFC 1685)
590 pub struct AnonymousParameters;
592 impl LintPass for AnonymousParameters {
593 fn get_lints(&self) -> LintArray {
594 lint_array!(ANONYMOUS_PARAMETERS)
598 impl EarlyLintPass for AnonymousParameters {
599 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
601 ast::TraitItemKind::Method(ref sig, _) => {
602 for arg in sig.decl.inputs.iter() {
604 ast::PatKind::Ident(_, ident, None) => {
605 if ident.node.name == keywords::Invalid.name() {
606 cx.span_lint(ANONYMOUS_PARAMETERS,
608 "use of deprecated anonymous parameter");
623 "detects use of deprecated attributes"
626 /// Checks for use of attributes which have been deprecated.
628 pub struct DeprecatedAttr {
629 // This is not free to compute, so we want to keep it around, rather than
630 // compute it for every attribute.
631 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
634 impl DeprecatedAttr {
635 pub fn new() -> DeprecatedAttr {
637 depr_attrs: deprecated_attributes(),
642 impl LintPass for DeprecatedAttr {
643 fn get_lints(&self) -> LintArray {
644 lint_array!(DEPRECATED_ATTR)
648 impl EarlyLintPass for DeprecatedAttr {
649 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
650 let name = unwrap_or!(attr.name(), return);
651 for &&(n, _, ref g) in &self.depr_attrs {
653 if let &AttributeGate::Gated(Stability::Deprecated(link),
657 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
659 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
660 err.span_suggestion_short(attr.span, "remove this attribute", "".to_owned());
670 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
672 "floating-point literals cannot be used in patterns"
675 /// Checks for floating point literals in patterns.
677 pub struct IllegalFloatLiteralPattern;
679 impl LintPass for IllegalFloatLiteralPattern {
680 fn get_lints(&self) -> LintArray {
681 lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
685 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
686 use self::ast::{ExprKind, LitKind};
688 ExprKind::Lit(ref l) => {
690 LitKind::FloatUnsuffixed(..) |
691 LitKind::Float(..) => {
692 cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
694 "floating-point literals cannot be used in patterns");
699 // These may occur in patterns
700 // and can maybe contain float literals
701 ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
702 // Other kinds of exprs can't occur in patterns so we don't have to check them
703 // (ast_validation will emit an error if they occur)
708 impl EarlyLintPass for IllegalFloatLiteralPattern {
709 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
710 use self::ast::PatKind;
713 // Wildcard patterns and paths are uninteresting for the lint
715 PatKind::Path(..) => (),
717 // The walk logic recurses inside these
719 PatKind::Struct(..) |
721 PatKind::TupleStruct(..) |
724 PatKind::Slice(..) => (),
726 // Extract the expressions and check them
727 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
728 PatKind::Range(ref st, ref en, _) => {
729 fl_lit_check_expr(cx, st);
730 fl_lit_check_expr(cx, en);
733 PatKind::Mac(_) => bug!("lint must run post-expansion"),
741 pub UNUSED_DOC_COMMENT,
743 "detects doc comments that aren't used by rustdoc"
746 #[derive(Copy, Clone)]
747 pub struct UnusedDocComment;
749 impl LintPass for UnusedDocComment {
750 fn get_lints(&self) -> LintArray {
751 lint_array![UNUSED_DOC_COMMENT]
755 impl UnusedDocComment {
756 fn warn_if_doc<'a, 'tcx,
757 I: Iterator<Item=&'a ast::Attribute>,
758 C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
759 if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
760 cx.struct_span_lint(UNUSED_DOC_COMMENT, attr.span, "doc comment not used by rustdoc")
766 impl EarlyLintPass for UnusedDocComment {
767 fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
768 self.warn_if_doc(decl.attrs.iter(), cx);
771 fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
772 self.warn_if_doc(arm.attrs.iter(), cx);
775 fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
776 self.warn_if_doc(expr.attrs.iter(), cx);
781 pub UNCONDITIONAL_RECURSION,
783 "functions that cannot return without calling themselves"
786 #[derive(Copy, Clone)]
787 pub struct UnconditionalRecursion;
790 impl LintPass for UnconditionalRecursion {
791 fn get_lints(&self) -> LintArray {
792 lint_array![UNCONDITIONAL_RECURSION]
796 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
797 fn check_fn(&mut self,
804 let method = match fn_kind {
805 FnKind::ItemFn(..) => None,
806 FnKind::Method(..) => {
807 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
809 // closures can't recur, so they don't matter.
810 FnKind::Closure(_) => return,
813 // Walk through this function (say `f`) looking to see if
814 // every possible path references itself, i.e. the function is
815 // called recursively unconditionally. This is done by trying
816 // to find a path from the entry node to the exit node that
817 // *doesn't* call `f` by traversing from the entry while
818 // pretending that calls of `f` are sinks (i.e. ignoring any
819 // exit edges from them).
821 // NB. this has an edge case with non-returning statements,
822 // like `loop {}` or `panic!()`: control flow never reaches
823 // the exit node through these, so one can have a function
824 // that never actually calls itselfs but is still picked up by
827 // fn f(cond: bool) {
828 // if !cond { panic!() } // could come from `assert!(cond)`
832 // In general, functions of that form may be able to call
833 // itself a finite number of times and then diverge. The lint
834 // considers this to be an error for two reasons, (a) it is
835 // easier to implement, and (b) it seems rare to actually want
836 // to have behaviour like the above, rather than
837 // e.g. accidentally recurring after an assert.
839 let cfg = cfg::CFG::new(cx.tcx, &body);
841 let mut work_queue = vec![cfg.entry];
842 let mut reached_exit_without_self_call = false;
843 let mut self_call_spans = vec![];
844 let mut visited = HashSet::new();
846 while let Some(idx) = work_queue.pop() {
849 reached_exit_without_self_call = true;
853 let cfg_id = idx.node_id();
854 if visited.contains(&cfg_id) {
858 visited.insert(cfg_id);
860 // is this a recursive call?
861 let local_id = cfg.graph.node_data(idx).id();
862 if local_id != hir::DUMMY_ITEM_LOCAL_ID {
863 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
864 owner: body.value.hir_id.owner,
867 let self_recursive = match method {
868 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
869 None => expr_refers_to_this_fn(cx, id, node_id),
872 self_call_spans.push(cx.tcx.hir.span(node_id));
873 // this is a self call, so we shouldn't explore past
874 // this node in the CFG.
879 // add the successors of this node to explore the graph further.
880 for (_, edge) in cfg.graph.outgoing_edges(idx) {
881 let target_idx = edge.target();
882 let target_cfg_id = target_idx.node_id();
883 if !visited.contains(&target_cfg_id) {
884 work_queue.push(target_idx)
889 // Check the number of self calls because a function that
890 // doesn't return (e.g. calls a `-> !` function or `loop { /*
891 // no break */ }`) shouldn't be linted unless it actually
893 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
894 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
896 "function cannot return without recurring");
897 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
898 // offer some help to the programmer.
899 for call in &self_call_spans {
900 db.span_note(*call, "recursive call site");
902 db.help("a `loop` may express intention \
903 better if this is on purpose");
910 // Functions for identifying if the given Expr NodeId `id`
911 // represents a call to the function `fn_id`/method `method`.
913 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
914 match cx.tcx.hir.get(id) {
915 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
916 let def = if let hir::ExprPath(ref qpath) = callee.node {
917 cx.tables.qpath_def(qpath, callee.hir_id)
922 Def::Local(..) | Def::Upvar(..) => false,
923 _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
930 // Check if the expression `id` performs a call to `method`.
931 fn expr_refers_to_this_method(cx: &LateContext,
932 method: &ty::AssociatedItem,
935 use rustc::ty::adjustment::*;
937 // Ignore non-expressions.
938 let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
944 // Check for overloaded autoderef method calls.
945 let mut source = cx.tables.expr_ty(expr);
946 for adjustment in cx.tables.expr_adjustments(expr) {
947 if let Adjust::Deref(Some(deref)) = adjustment.kind {
948 let (def_id, substs) = deref.method_call(cx.tcx, source);
949 if method_call_refers_to_method(cx, method, def_id, substs, id) {
953 source = adjustment.target;
956 // Check for method calls and overloaded operators.
957 if cx.tables.is_method_call(expr) {
958 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
959 let def_id = cx.tables.type_dependent_defs()[hir_id].def_id();
960 let substs = cx.tables.node_substs(hir_id);
961 if method_call_refers_to_method(cx, method, def_id, substs, id) {
966 // Check for calls to methods via explicit paths (e.g. `T::method()`).
968 hir::ExprCall(ref callee, _) => {
969 let def = if let hir::ExprPath(ref qpath) = callee.node {
970 cx.tables.qpath_def(qpath, callee.hir_id)
975 Def::Method(def_id) => {
976 let substs = cx.tables.node_substs(callee.hir_id);
977 method_call_refers_to_method(cx, method, def_id, substs, id)
986 // Check if the method call to the method with the ID `callee_id`
987 // and instantiated with `callee_substs` refers to method `method`.
988 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
989 method: &ty::AssociatedItem,
991 callee_substs: &Substs<'tcx>,
992 expr_id: ast::NodeId)
995 let callee_item = tcx.associated_item(callee_id);
997 match callee_item.container {
998 // This is an inherent method, so the `def_id` refers
999 // directly to the method definition.
1000 ty::ImplContainer(_) => callee_id == method.def_id,
1002 // A trait method, from any number of possible sources.
1003 // Attempt to select a concrete impl before checking.
1004 ty::TraitContainer(trait_def_id) => {
1005 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1006 let trait_ref = ty::Binder(trait_ref);
1007 let span = tcx.hir.span(expr_id);
1009 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1011 trait_ref.to_poly_trait_predicate());
1013 tcx.infer_ctxt().enter(|infcx| {
1014 let mut selcx = traits::SelectionContext::new(&infcx);
1015 match selcx.select(&obligation) {
1016 // The method comes from a `T: Trait` bound.
1017 // If `T` is `Self`, then this call is inside
1018 // a default method definition.
1019 Ok(Some(traits::VtableParam(_))) => {
1020 let on_self = trait_ref.self_ty().is_self();
1021 // We can only be recurring in a default
1022 // method if we're being called literally
1023 // on the `Self` type.
1024 on_self && callee_id == method.def_id
1027 // The `impl` is known, so we check that with a
1029 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1030 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1031 // It matches if it comes from the same impl,
1032 // and has the same method name.
1033 container == method.container && callee_item.name == method.name
1036 // There's no way to know if this call is
1037 // recursive, so we assume it's not.
1050 "compiler plugin used as ordinary library in non-plugin crate"
1053 #[derive(Copy, Clone)]
1054 pub struct PluginAsLibrary;
1056 impl LintPass for PluginAsLibrary {
1057 fn get_lints(&self) -> LintArray {
1058 lint_array![PLUGIN_AS_LIBRARY]
1062 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1063 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1064 if cx.sess().plugin_registrar_fn.get().is_some() {
1065 // We're compiling a plugin; it's fine to link other plugins.
1070 hir::ItemExternCrate(..) => (),
1074 let def_id = cx.tcx.hir.local_def_id(it.id);
1075 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1076 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1078 // Probably means we aren't linking the crate for some reason.
1080 // Not sure if / when this could happen.
1086 cx.span_lint(PLUGIN_AS_LIBRARY,
1088 "compiler plugin used as an ordinary library");
1094 PRIVATE_NO_MANGLE_FNS,
1096 "functions marked #[no_mangle] should be exported"
1100 PRIVATE_NO_MANGLE_STATICS,
1102 "statics marked #[no_mangle] should be exported"
1106 NO_MANGLE_CONST_ITEMS,
1108 "const items will not have their symbols exported"
1112 NO_MANGLE_GENERIC_ITEMS,
1114 "generic items must be mangled"
1117 #[derive(Copy, Clone)]
1118 pub struct InvalidNoMangleItems;
1120 impl LintPass for InvalidNoMangleItems {
1121 fn get_lints(&self) -> LintArray {
1122 lint_array!(PRIVATE_NO_MANGLE_FNS,
1123 PRIVATE_NO_MANGLE_STATICS,
1124 NO_MANGLE_CONST_ITEMS,
1125 NO_MANGLE_GENERIC_ITEMS)
1129 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1130 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1132 hir::ItemFn(.., ref generics, _) => {
1133 if attr::contains_name(&it.attrs, "no_mangle") &&
1134 !attr::contains_name(&it.attrs, "linkage") {
1135 if !cx.access_levels.is_reachable(it.id) {
1136 let msg = format!("function {} is marked #[no_mangle], but not exported",
1138 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1140 if generics.is_type_parameterized() {
1141 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1143 "functions generic over types must be mangled");
1147 hir::ItemStatic(..) => {
1148 if attr::contains_name(&it.attrs, "no_mangle") &&
1149 !cx.access_levels.is_reachable(it.id) {
1150 let msg = format!("static {} is marked #[no_mangle], but not exported",
1152 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1155 hir::ItemConst(..) => {
1156 if attr::contains_name(&it.attrs, "no_mangle") {
1157 // Const items do not refer to a particular location in memory, and therefore
1158 // don't have anything to attach a symbol to
1159 let msg = "const items should never be #[no_mangle], consider instead using \
1161 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1169 #[derive(Clone, Copy)]
1170 pub struct MutableTransmutes;
1175 "mutating transmuted &mut T from &T may cause undefined behavior"
1178 impl LintPass for MutableTransmutes {
1179 fn get_lints(&self) -> LintArray {
1180 lint_array!(MUTABLE_TRANSMUTES)
1184 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1185 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1186 use syntax::abi::Abi::RustIntrinsic;
1188 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1189 consider instead using an UnsafeCell";
1190 match get_transmute_from_to(cx, expr) {
1191 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1192 if to_mt.mutbl == hir::Mutability::MutMutable &&
1193 from_mt.mutbl == hir::Mutability::MutImmutable {
1194 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1200 fn get_transmute_from_to<'a, 'tcx>
1201 (cx: &LateContext<'a, 'tcx>,
1203 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1204 let def = if let hir::ExprPath(ref qpath) = expr.node {
1205 cx.tables.qpath_def(qpath, expr.hir_id)
1209 if let Def::Fn(did) = def {
1210 if !def_id_is_transmute(cx, did) {
1213 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1214 let from = sig.inputs().skip_binder()[0];
1215 let to = *sig.output().skip_binder();
1216 return Some((&from.sty, &to.sty));
1221 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1222 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1223 cx.tcx.item_name(def_id) == "transmute"
1228 /// Forbids using the `#[feature(...)]` attribute
1229 #[derive(Copy, Clone)]
1230 pub struct UnstableFeatures;
1235 "enabling unstable features (deprecated. do not use)"
1238 impl LintPass for UnstableFeatures {
1239 fn get_lints(&self) -> LintArray {
1240 lint_array!(UNSTABLE_FEATURES)
1244 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1245 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1246 if attr.check_name("feature") {
1247 if let Some(items) = attr.meta_item_list() {
1249 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1256 /// Lint for unions that contain fields with possibly non-trivial destructors.
1257 pub struct UnionsWithDropFields;
1260 UNIONS_WITH_DROP_FIELDS,
1262 "use of unions that contain fields with possibly non-trivial drop code"
1265 impl LintPass for UnionsWithDropFields {
1266 fn get_lints(&self) -> LintArray {
1267 lint_array!(UNIONS_WITH_DROP_FIELDS)
1271 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1272 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1273 if let hir::ItemUnion(ref vdata, _) = item.node {
1274 for field in vdata.fields() {
1275 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1276 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1277 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1279 "union contains a field with possibly non-trivial drop code, \
1280 drop code of union fields is ignored when dropping the union");