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 cx.span_lint(WHILE_TRUE,
81 "denote infinite loops with loop { ... }");
92 "use of owned (Box type) heap memory"
95 #[derive(Copy, Clone)]
96 pub struct BoxPointers;
99 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
100 for leaf_ty in ty.walk() {
101 if leaf_ty.is_box() {
102 let m = format!("type uses owned (Box type) pointers: {}", ty);
103 cx.span_lint(BOX_POINTERS, span, &m);
109 impl LintPass for BoxPointers {
110 fn get_lints(&self) -> LintArray {
111 lint_array!(BOX_POINTERS)
115 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
116 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
121 hir::ItemStruct(..) |
122 hir::ItemUnion(..) => {
123 let def_id = cx.tcx.hir.local_def_id(it.id);
124 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
129 // If it's a struct, we also have to check the fields' types
131 hir::ItemStruct(ref struct_def, _) |
132 hir::ItemUnion(ref struct_def, _) => {
133 for struct_field in struct_def.fields() {
134 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
135 self.check_heap_type(cx, struct_field.span,
136 cx.tcx.type_of(def_id));
143 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
144 let ty = cx.tables.node_id_to_type(e.hir_id);
145 self.check_heap_type(cx, e.span, ty);
150 NON_SHORTHAND_FIELD_PATTERNS,
152 "using `Struct { x: x }` instead of `Struct { x }`"
155 #[derive(Copy, Clone)]
156 pub struct NonShorthandFieldPatterns;
158 impl LintPass for NonShorthandFieldPatterns {
159 fn get_lints(&self) -> LintArray {
160 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
164 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
165 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
166 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
167 for fieldpat in field_pats {
168 if fieldpat.node.is_shorthand {
171 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
172 if ident.node == fieldpat.node.name {
173 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
175 &format!("the `{}:` in this pattern is redundant and can \
188 "usage of `unsafe` code"
191 #[derive(Copy, Clone)]
192 pub struct UnsafeCode;
194 impl LintPass for UnsafeCode {
195 fn get_lints(&self) -> LintArray {
196 lint_array!(UNSAFE_CODE)
201 fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
202 // This comes from a macro that has #[allow_internal_unsafe].
203 if span.allows_unsafe() {
207 cx.span_lint(UNSAFE_CODE, span, desc);
211 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
212 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
213 if let hir::ExprBlock(ref blk) = e.node {
214 // Don't warn about generated blocks, that'll just pollute the output.
215 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
216 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
221 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
223 hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
224 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
227 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
228 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
235 fn check_fn(&mut self,
243 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
244 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
247 FnKind::Method(_, sig, ..) => {
248 if sig.unsafety == hir::Unsafety::Unsafe {
249 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
257 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
258 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
259 if sig.unsafety == hir::Unsafety::Unsafe {
260 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
269 "detects missing documentation for public members"
272 pub struct MissingDoc {
273 /// Stack of whether #[doc(hidden)] is set
274 /// at each level which has lint attributes.
275 doc_hidden_stack: Vec<bool>,
277 /// Private traits or trait items that leaked through. Don't check their methods.
278 private_traits: HashSet<ast::NodeId>,
282 pub fn new() -> MissingDoc {
284 doc_hidden_stack: vec![false],
285 private_traits: HashSet::new(),
289 fn doc_hidden(&self) -> bool {
290 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
293 fn check_missing_docs_attrs(&self,
295 id: Option<ast::NodeId>,
296 attrs: &[ast::Attribute],
298 desc: &'static str) {
299 // If we're building a test harness, then warning about
300 // documentation is probably not really relevant right now.
301 if cx.sess().opts.test {
305 // `#[doc(hidden)]` disables missing_docs check.
306 if self.doc_hidden() {
310 // Only check publicly-visible items, using the result from the privacy pass.
311 // It's an option so the crate root can also use this function (it doesn't
313 if let Some(id) = id {
314 if !cx.access_levels.is_exported(id) {
319 let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
321 cx.span_lint(MISSING_DOCS,
323 &format!("missing documentation for {}", desc));
328 impl LintPass for MissingDoc {
329 fn get_lints(&self) -> LintArray {
330 lint_array!(MISSING_DOCS)
334 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
335 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
336 let doc_hidden = self.doc_hidden() ||
337 attrs.iter().any(|attr| {
338 attr.check_name("doc") &&
339 match attr.meta_item_list() {
341 Some(l) => attr::list_contains_name(&l, "hidden"),
344 self.doc_hidden_stack.push(doc_hidden);
347 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
348 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
351 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
352 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
355 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
356 let desc = match it.node {
357 hir::ItemFn(..) => "a function",
358 hir::ItemMod(..) => "a module",
359 hir::ItemEnum(..) => "an enum",
360 hir::ItemStruct(..) => "a struct",
361 hir::ItemUnion(..) => "a union",
362 hir::ItemTrait(.., ref trait_item_refs) => {
363 // Issue #11592, traits are always considered exported, even when private.
364 if it.vis == hir::Visibility::Inherited {
365 self.private_traits.insert(it.id);
366 for trait_item_ref in trait_item_refs {
367 self.private_traits.insert(trait_item_ref.id.node_id);
373 hir::ItemTy(..) => "a type alias",
374 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
375 // If the trait is private, add the impl items to private_traits so they don't get
376 // reported for missing docs.
377 let real_trait = trait_ref.path.def.def_id();
378 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
379 match cx.tcx.hir.find(node_id) {
380 Some(hir_map::NodeItem(item)) => {
381 if item.vis == hir::Visibility::Inherited {
382 for impl_item_ref in impl_item_refs {
383 self.private_traits.insert(impl_item_ref.id.node_id);
392 hir::ItemConst(..) => "a constant",
393 hir::ItemStatic(..) => "a static",
397 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
400 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
401 if self.private_traits.contains(&trait_item.id) {
405 let desc = match trait_item.node {
406 hir::TraitItemKind::Const(..) => "an associated constant",
407 hir::TraitItemKind::Method(..) => "a trait method",
408 hir::TraitItemKind::Type(..) => "an associated type",
411 self.check_missing_docs_attrs(cx,
418 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
419 // If the method is an impl for a trait, don't doc.
420 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
424 let desc = match impl_item.node {
425 hir::ImplItemKind::Const(..) => "an associated constant",
426 hir::ImplItemKind::Method(..) => "a method",
427 hir::ImplItemKind::Type(_) => "an associated type",
429 self.check_missing_docs_attrs(cx,
436 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
437 if !sf.is_positional() {
438 self.check_missing_docs_attrs(cx,
446 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
447 self.check_missing_docs_attrs(cx,
448 Some(v.node.data.id()),
456 pub MISSING_COPY_IMPLEMENTATIONS,
458 "detects potentially-forgotten implementations of `Copy`"
461 #[derive(Copy, Clone)]
462 pub struct MissingCopyImplementations;
464 impl LintPass for MissingCopyImplementations {
465 fn get_lints(&self) -> LintArray {
466 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
470 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
471 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
472 if !cx.access_levels.is_reachable(item.id) {
475 let (def, ty) = match item.node {
476 hir::ItemStruct(_, ref ast_generics) => {
477 if ast_generics.is_parameterized() {
480 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
481 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
483 hir::ItemUnion(_, ref ast_generics) => {
484 if ast_generics.is_parameterized() {
487 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
488 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
490 hir::ItemEnum(_, ref ast_generics) => {
491 if ast_generics.is_parameterized() {
494 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
495 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
499 if def.has_dtor(cx.tcx) {
502 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
503 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
506 if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
507 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
509 "type could implement `Copy`; consider adding `impl \
516 MISSING_DEBUG_IMPLEMENTATIONS,
518 "detects missing implementations of fmt::Debug"
521 pub struct MissingDebugImplementations {
522 impling_types: Option<NodeSet>,
525 impl MissingDebugImplementations {
526 pub fn new() -> MissingDebugImplementations {
527 MissingDebugImplementations { impling_types: None }
531 impl LintPass for MissingDebugImplementations {
532 fn get_lints(&self) -> LintArray {
533 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
537 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
538 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
539 if !cx.access_levels.is_reachable(item.id) {
544 hir::ItemStruct(..) |
546 hir::ItemEnum(..) => {}
550 let debug = match cx.tcx.lang_items().debug_trait() {
551 Some(debug) => debug,
555 if self.impling_types.is_none() {
556 let mut impls = NodeSet();
557 cx.tcx.for_each_impl(debug, |d| {
558 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
559 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
560 impls.insert(node_id);
565 self.impling_types = Some(impls);
566 debug!("{:?}", self.impling_types);
569 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
570 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
572 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
573 or a manual implementation")
579 pub ANONYMOUS_PARAMETERS,
581 "detects anonymous parameters"
584 /// Checks for use of anonymous parameters (RFC 1685)
586 pub struct AnonymousParameters;
588 impl LintPass for AnonymousParameters {
589 fn get_lints(&self) -> LintArray {
590 lint_array!(ANONYMOUS_PARAMETERS)
594 impl EarlyLintPass for AnonymousParameters {
595 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
597 ast::TraitItemKind::Method(ref sig, _) => {
598 for arg in sig.decl.inputs.iter() {
600 ast::PatKind::Ident(_, ident, None) => {
601 if ident.node.name == keywords::Invalid.name() {
602 cx.span_lint(ANONYMOUS_PARAMETERS,
604 "use of deprecated anonymous parameter");
619 "detects use of deprecated attributes"
622 /// Checks for use of attributes which have been deprecated.
624 pub struct DeprecatedAttr {
625 // This is not free to compute, so we want to keep it around, rather than
626 // compute it for every attribute.
627 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
630 impl DeprecatedAttr {
631 pub fn new() -> DeprecatedAttr {
633 depr_attrs: deprecated_attributes(),
638 impl LintPass for DeprecatedAttr {
639 fn get_lints(&self) -> LintArray {
640 lint_array!(DEPRECATED_ATTR)
644 impl EarlyLintPass for DeprecatedAttr {
645 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
646 let name = unwrap_or!(attr.name(), return);
647 for &&(n, _, ref g) in &self.depr_attrs {
649 if let &AttributeGate::Gated(Stability::Deprecated(link),
653 cx.span_lint(DEPRECATED,
655 &format!("use of deprecated attribute `{}`: {}. See {}",
656 name, reason, link));
665 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
667 "floating-point literals cannot be used in patterns"
670 /// Checks for floating point literals in patterns.
672 pub struct IllegalFloatLiteralPattern;
674 impl LintPass for IllegalFloatLiteralPattern {
675 fn get_lints(&self) -> LintArray {
676 lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
680 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
681 use self::ast::{ExprKind, LitKind};
683 ExprKind::Lit(ref l) => {
685 LitKind::FloatUnsuffixed(..) |
686 LitKind::Float(..) => {
687 cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
689 "floating-point literals cannot be used in patterns");
694 // These may occur in patterns
695 // and can maybe contain float literals
696 ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
697 // Other kinds of exprs can't occur in patterns so we don't have to check them
698 // (ast_validation will emit an error if they occur)
703 impl EarlyLintPass for IllegalFloatLiteralPattern {
704 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
705 use self::ast::PatKind;
708 // Wildcard patterns and paths are uninteresting for the lint
710 PatKind::Path(..) => (),
712 // The walk logic recurses inside these
714 PatKind::Struct(..) |
716 PatKind::TupleStruct(..) |
719 PatKind::Slice(..) => (),
721 // Extract the expressions and check them
722 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
723 PatKind::Range(ref st, ref en, _) => {
724 fl_lit_check_expr(cx, st);
725 fl_lit_check_expr(cx, en);
728 PatKind::Mac(_) => bug!("lint must run post-expansion"),
736 pub UNUSED_DOC_COMMENT,
738 "detects doc comments that aren't used by rustdoc"
741 #[derive(Copy, Clone)]
742 pub struct UnusedDocComment;
744 impl LintPass for UnusedDocComment {
745 fn get_lints(&self) -> LintArray {
746 lint_array![UNUSED_DOC_COMMENT]
750 impl UnusedDocComment {
751 fn warn_if_doc<'a, 'tcx,
752 I: Iterator<Item=&'a ast::Attribute>,
753 C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
754 if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
755 cx.struct_span_lint(UNUSED_DOC_COMMENT, attr.span, "doc comment not used by rustdoc")
761 impl EarlyLintPass for UnusedDocComment {
762 fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
763 self.warn_if_doc(decl.attrs.iter(), cx);
766 fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
767 self.warn_if_doc(arm.attrs.iter(), cx);
770 fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
771 self.warn_if_doc(expr.attrs.iter(), cx);
776 pub UNCONDITIONAL_RECURSION,
778 "functions that cannot return without calling themselves"
781 #[derive(Copy, Clone)]
782 pub struct UnconditionalRecursion;
785 impl LintPass for UnconditionalRecursion {
786 fn get_lints(&self) -> LintArray {
787 lint_array![UNCONDITIONAL_RECURSION]
791 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
792 fn check_fn(&mut self,
799 let method = match fn_kind {
800 FnKind::ItemFn(..) => None,
801 FnKind::Method(..) => {
802 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
804 // closures can't recur, so they don't matter.
805 FnKind::Closure(_) => return,
808 // Walk through this function (say `f`) looking to see if
809 // every possible path references itself, i.e. the function is
810 // called recursively unconditionally. This is done by trying
811 // to find a path from the entry node to the exit node that
812 // *doesn't* call `f` by traversing from the entry while
813 // pretending that calls of `f` are sinks (i.e. ignoring any
814 // exit edges from them).
816 // NB. this has an edge case with non-returning statements,
817 // like `loop {}` or `panic!()`: control flow never reaches
818 // the exit node through these, so one can have a function
819 // that never actually calls itselfs but is still picked up by
822 // fn f(cond: bool) {
823 // if !cond { panic!() } // could come from `assert!(cond)`
827 // In general, functions of that form may be able to call
828 // itself a finite number of times and then diverge. The lint
829 // considers this to be an error for two reasons, (a) it is
830 // easier to implement, and (b) it seems rare to actually want
831 // to have behaviour like the above, rather than
832 // e.g. accidentally recurring after an assert.
834 let cfg = cfg::CFG::new(cx.tcx, &body);
836 let mut work_queue = vec![cfg.entry];
837 let mut reached_exit_without_self_call = false;
838 let mut self_call_spans = vec![];
839 let mut visited = HashSet::new();
841 while let Some(idx) = work_queue.pop() {
844 reached_exit_without_self_call = true;
848 let cfg_id = idx.node_id();
849 if visited.contains(&cfg_id) {
853 visited.insert(cfg_id);
855 // is this a recursive call?
856 let local_id = cfg.graph.node_data(idx).id();
857 if local_id != hir::DUMMY_ITEM_LOCAL_ID {
858 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
859 owner: body.value.hir_id.owner,
862 let self_recursive = match method {
863 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
864 None => expr_refers_to_this_fn(cx, id, node_id),
867 self_call_spans.push(cx.tcx.hir.span(node_id));
868 // this is a self call, so we shouldn't explore past
869 // this node in the CFG.
874 // add the successors of this node to explore the graph further.
875 for (_, edge) in cfg.graph.outgoing_edges(idx) {
876 let target_idx = edge.target();
877 let target_cfg_id = target_idx.node_id();
878 if !visited.contains(&target_cfg_id) {
879 work_queue.push(target_idx)
884 // Check the number of self calls because a function that
885 // doesn't return (e.g. calls a `-> !` function or `loop { /*
886 // no break */ }`) shouldn't be linted unless it actually
888 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
889 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
891 "function cannot return without recurring");
892 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
893 // offer some help to the programmer.
894 for call in &self_call_spans {
895 db.span_note(*call, "recursive call site");
897 db.help("a `loop` may express intention \
898 better if this is on purpose");
905 // Functions for identifying if the given Expr NodeId `id`
906 // represents a call to the function `fn_id`/method `method`.
908 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
909 match cx.tcx.hir.get(id) {
910 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
911 let def = if let hir::ExprPath(ref qpath) = callee.node {
912 cx.tables.qpath_def(qpath, callee.hir_id)
917 Def::Local(..) | Def::Upvar(..) => false,
918 _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
925 // Check if the expression `id` performs a call to `method`.
926 fn expr_refers_to_this_method(cx: &LateContext,
927 method: &ty::AssociatedItem,
930 use rustc::ty::adjustment::*;
932 // Ignore non-expressions.
933 let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
939 // Check for overloaded autoderef method calls.
940 let mut source = cx.tables.expr_ty(expr);
941 for adjustment in cx.tables.expr_adjustments(expr) {
942 if let Adjust::Deref(Some(deref)) = adjustment.kind {
943 let (def_id, substs) = deref.method_call(cx.tcx, source);
944 if method_call_refers_to_method(cx, method, def_id, substs, id) {
948 source = adjustment.target;
951 // Check for method calls and overloaded operators.
952 if cx.tables.is_method_call(expr) {
953 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
954 let def_id = cx.tables.type_dependent_defs()[hir_id].def_id();
955 let substs = cx.tables.node_substs(hir_id);
956 if method_call_refers_to_method(cx, method, def_id, substs, id) {
961 // Check for calls to methods via explicit paths (e.g. `T::method()`).
963 hir::ExprCall(ref callee, _) => {
964 let def = if let hir::ExprPath(ref qpath) = callee.node {
965 cx.tables.qpath_def(qpath, callee.hir_id)
970 Def::Method(def_id) => {
971 let substs = cx.tables.node_substs(callee.hir_id);
972 method_call_refers_to_method(cx, method, def_id, substs, id)
981 // Check if the method call to the method with the ID `callee_id`
982 // and instantiated with `callee_substs` refers to method `method`.
983 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
984 method: &ty::AssociatedItem,
986 callee_substs: &Substs<'tcx>,
987 expr_id: ast::NodeId)
990 let callee_item = tcx.associated_item(callee_id);
992 match callee_item.container {
993 // This is an inherent method, so the `def_id` refers
994 // directly to the method definition.
995 ty::ImplContainer(_) => callee_id == method.def_id,
997 // A trait method, from any number of possible sources.
998 // Attempt to select a concrete impl before checking.
999 ty::TraitContainer(trait_def_id) => {
1000 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
1001 let trait_ref = ty::Binder(trait_ref);
1002 let span = tcx.hir.span(expr_id);
1004 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
1006 trait_ref.to_poly_trait_predicate());
1008 tcx.infer_ctxt().enter(|infcx| {
1009 let mut selcx = traits::SelectionContext::new(&infcx);
1010 match selcx.select(&obligation) {
1011 // The method comes from a `T: Trait` bound.
1012 // If `T` is `Self`, then this call is inside
1013 // a default method definition.
1014 Ok(Some(traits::VtableParam(_))) => {
1015 let on_self = trait_ref.self_ty().is_self();
1016 // We can only be recurring in a default
1017 // method if we're being called literally
1018 // on the `Self` type.
1019 on_self && callee_id == method.def_id
1022 // The `impl` is known, so we check that with a
1024 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1025 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1026 // It matches if it comes from the same impl,
1027 // and has the same method name.
1028 container == method.container && callee_item.name == method.name
1031 // There's no way to know if this call is
1032 // recursive, so we assume it's not.
1045 "compiler plugin used as ordinary library in non-plugin crate"
1048 #[derive(Copy, Clone)]
1049 pub struct PluginAsLibrary;
1051 impl LintPass for PluginAsLibrary {
1052 fn get_lints(&self) -> LintArray {
1053 lint_array![PLUGIN_AS_LIBRARY]
1057 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1058 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1059 if cx.sess().plugin_registrar_fn.get().is_some() {
1060 // We're compiling a plugin; it's fine to link other plugins.
1065 hir::ItemExternCrate(..) => (),
1069 let hir_id = cx.tcx.hir.node_to_hir_id(it.id);
1070 let prfn = match cx.tcx.extern_mod_stmt_cnum(hir_id) {
1071 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1073 // Probably means we aren't linking the crate for some reason.
1075 // Not sure if / when this could happen.
1081 cx.span_lint(PLUGIN_AS_LIBRARY,
1083 "compiler plugin used as an ordinary library");
1089 PRIVATE_NO_MANGLE_FNS,
1091 "functions marked #[no_mangle] should be exported"
1095 PRIVATE_NO_MANGLE_STATICS,
1097 "statics marked #[no_mangle] should be exported"
1101 NO_MANGLE_CONST_ITEMS,
1103 "const items will not have their symbols exported"
1107 NO_MANGLE_GENERIC_ITEMS,
1109 "generic items must be mangled"
1112 #[derive(Copy, Clone)]
1113 pub struct InvalidNoMangleItems;
1115 impl LintPass for InvalidNoMangleItems {
1116 fn get_lints(&self) -> LintArray {
1117 lint_array!(PRIVATE_NO_MANGLE_FNS,
1118 PRIVATE_NO_MANGLE_STATICS,
1119 NO_MANGLE_CONST_ITEMS,
1120 NO_MANGLE_GENERIC_ITEMS)
1124 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1125 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1127 hir::ItemFn(.., ref generics, _) => {
1128 if attr::contains_name(&it.attrs, "no_mangle") &&
1129 !attr::contains_name(&it.attrs, "linkage") {
1130 if !cx.access_levels.is_reachable(it.id) {
1131 let msg = format!("function {} is marked #[no_mangle], but not exported",
1133 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1135 if generics.is_type_parameterized() {
1136 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1138 "functions generic over types must be mangled");
1142 hir::ItemStatic(..) => {
1143 if attr::contains_name(&it.attrs, "no_mangle") &&
1144 !cx.access_levels.is_reachable(it.id) {
1145 let msg = format!("static {} is marked #[no_mangle], but not exported",
1147 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1150 hir::ItemConst(..) => {
1151 if attr::contains_name(&it.attrs, "no_mangle") {
1152 // Const items do not refer to a particular location in memory, and therefore
1153 // don't have anything to attach a symbol to
1154 let msg = "const items should never be #[no_mangle], consider instead using \
1156 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1164 #[derive(Clone, Copy)]
1165 pub struct MutableTransmutes;
1170 "mutating transmuted &mut T from &T may cause undefined behavior"
1173 impl LintPass for MutableTransmutes {
1174 fn get_lints(&self) -> LintArray {
1175 lint_array!(MUTABLE_TRANSMUTES)
1179 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1180 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1181 use syntax::abi::Abi::RustIntrinsic;
1183 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1184 consider instead using an UnsafeCell";
1185 match get_transmute_from_to(cx, expr) {
1186 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1187 if to_mt.mutbl == hir::Mutability::MutMutable &&
1188 from_mt.mutbl == hir::Mutability::MutImmutable {
1189 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1195 fn get_transmute_from_to<'a, 'tcx>
1196 (cx: &LateContext<'a, 'tcx>,
1198 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1199 let def = if let hir::ExprPath(ref qpath) = expr.node {
1200 cx.tables.qpath_def(qpath, expr.hir_id)
1204 if let Def::Fn(did) = def {
1205 if !def_id_is_transmute(cx, did) {
1208 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1209 let from = sig.inputs().skip_binder()[0];
1210 let to = *sig.output().skip_binder();
1211 return Some((&from.sty, &to.sty));
1216 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1217 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1218 cx.tcx.item_name(def_id) == "transmute"
1223 /// Forbids using the `#[feature(...)]` attribute
1224 #[derive(Copy, Clone)]
1225 pub struct UnstableFeatures;
1230 "enabling unstable features (deprecated. do not use)"
1233 impl LintPass for UnstableFeatures {
1234 fn get_lints(&self) -> LintArray {
1235 lint_array!(UNSTABLE_FEATURES)
1239 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1240 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1241 if attr.check_name("feature") {
1242 if let Some(items) = attr.meta_item_list() {
1244 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1251 /// Lint for unions that contain fields with possibly non-trivial destructors.
1252 pub struct UnionsWithDropFields;
1255 UNIONS_WITH_DROP_FIELDS,
1257 "use of unions that contain fields with possibly non-trivial drop code"
1260 impl LintPass for UnionsWithDropFields {
1261 fn get_lints(&self) -> LintArray {
1262 lint_array!(UNIONS_WITH_DROP_FIELDS)
1266 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1267 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1268 if let hir::ItemUnion(ref vdata, _) = item.node {
1269 for field in vdata.fields() {
1270 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1271 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1272 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1274 "union contains a field with possibly non-trivial drop code, \
1275 drop code of union fields is ignored when dropping the union");