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, TyCtxt};
36 use rustc::traits::{self, Reveal};
37 use rustc::hir::map as hir_map;
38 use util::nodemap::NodeSet;
39 use lint::{Level, LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
42 use std::collections::HashSet;
46 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
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 cx.span_lint(WHILE_TRUE,
80 "denote infinite loops with loop { ... }");
90 "use of owned (Box type) heap memory"
93 #[derive(Copy, Clone)]
94 pub struct BoxPointers;
97 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
98 for leaf_ty in ty.walk() {
100 let m = format!("type uses owned (Box type) pointers: {}", ty);
101 cx.span_lint(BOX_POINTERS, span, &m);
107 impl LintPass for BoxPointers {
108 fn get_lints(&self) -> LintArray {
109 lint_array!(BOX_POINTERS)
113 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
114 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
119 hir::ItemStruct(..) |
120 hir::ItemUnion(..) => {
121 let def_id = cx.tcx.hir.local_def_id(it.id);
122 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
127 // If it's a struct, we also have to check the fields' types
129 hir::ItemStruct(ref struct_def, _) |
130 hir::ItemUnion(ref struct_def, _) => {
131 for struct_field in struct_def.fields() {
132 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
133 self.check_heap_type(cx, struct_field.span,
134 cx.tcx.type_of(def_id));
141 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
142 let ty = cx.tables.node_id_to_type(e.id);
143 self.check_heap_type(cx, e.span, ty);
148 NON_SHORTHAND_FIELD_PATTERNS,
150 "using `Struct { x: x }` instead of `Struct { x }`"
153 #[derive(Copy, Clone)]
154 pub struct NonShorthandFieldPatterns;
156 impl LintPass for NonShorthandFieldPatterns {
157 fn get_lints(&self) -> LintArray {
158 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
162 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
163 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
164 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
165 for fieldpat in field_pats {
166 if fieldpat.node.is_shorthand {
169 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
170 if ident.node == fieldpat.node.name {
171 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
173 &format!("the `{}:` in this pattern is redundant and can \
186 "usage of `unsafe` code"
189 #[derive(Copy, Clone)]
190 pub struct UnsafeCode;
192 impl LintPass for UnsafeCode {
193 fn get_lints(&self) -> LintArray {
194 lint_array!(UNSAFE_CODE)
198 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
199 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
200 if let hir::ExprBlock(ref blk) = e.node {
201 // Don't warn about generated blocks, that'll just pollute the output.
202 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
203 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
208 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
210 hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
211 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait")
214 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
215 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait")
222 fn check_fn(&mut self,
230 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
231 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function")
234 FnKind::Method(_, sig, ..) => {
235 if sig.unsafety == hir::Unsafety::Unsafe {
236 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
244 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
245 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
246 if sig.unsafety == hir::Unsafety::Unsafe {
247 cx.span_lint(UNSAFE_CODE,
249 "declaration of an `unsafe` method")
258 "detects missing documentation for public members"
261 pub struct MissingDoc {
262 /// Stack of IDs of struct definitions.
263 struct_def_stack: Vec<ast::NodeId>,
265 /// True if inside variant definition
268 /// Stack of whether #[doc(hidden)] is set
269 /// at each level which has lint attributes.
270 doc_hidden_stack: Vec<bool>,
272 /// Private traits or trait items that leaked through. Don't check their methods.
273 private_traits: HashSet<ast::NodeId>,
277 pub fn new() -> MissingDoc {
279 struct_def_stack: vec![],
281 doc_hidden_stack: vec![false],
282 private_traits: HashSet::new(),
286 fn doc_hidden(&self) -> bool {
287 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
290 fn check_missing_docs_attrs(&self,
292 id: Option<ast::NodeId>,
293 attrs: &[ast::Attribute],
295 desc: &'static str) {
296 // If we're building a test harness, then warning about
297 // documentation is probably not really relevant right now.
298 if cx.sess().opts.test {
302 // `#[doc(hidden)]` disables missing_docs check.
303 if self.doc_hidden() {
307 // Only check publicly-visible items, using the result from the privacy pass.
308 // It's an option so the crate root can also use this function (it doesn't
310 if let Some(id) = id {
311 if !cx.access_levels.is_exported(id) {
316 let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
318 cx.span_lint(MISSING_DOCS,
320 &format!("missing documentation for {}", desc));
325 impl LintPass for MissingDoc {
326 fn get_lints(&self) -> LintArray {
327 lint_array!(MISSING_DOCS)
331 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
332 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
333 let doc_hidden = self.doc_hidden() ||
334 attrs.iter().any(|attr| {
335 attr.check_name("doc") &&
336 match attr.meta_item_list() {
338 Some(l) => attr::list_contains_name(&l, "hidden"),
341 self.doc_hidden_stack.push(doc_hidden);
344 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
345 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
348 fn check_struct_def(&mut self,
350 _: &hir::VariantData,
353 item_id: ast::NodeId) {
354 self.struct_def_stack.push(item_id);
357 fn check_struct_def_post(&mut self,
359 _: &hir::VariantData,
362 item_id: ast::NodeId) {
363 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
364 assert!(popped == item_id);
367 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
368 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
371 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
372 let desc = match it.node {
373 hir::ItemFn(..) => "a function",
374 hir::ItemMod(..) => "a module",
375 hir::ItemEnum(..) => "an enum",
376 hir::ItemStruct(..) => "a struct",
377 hir::ItemUnion(..) => "a union",
378 hir::ItemTrait(.., ref trait_item_refs) => {
379 // Issue #11592, traits are always considered exported, even when private.
380 if it.vis == hir::Visibility::Inherited {
381 self.private_traits.insert(it.id);
382 for trait_item_ref in trait_item_refs {
383 self.private_traits.insert(trait_item_ref.id.node_id);
389 hir::ItemTy(..) => "a type alias",
390 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
391 // If the trait is private, add the impl items to private_traits so they don't get
392 // reported for missing docs.
393 let real_trait = trait_ref.path.def.def_id();
394 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
395 match cx.tcx.hir.find(node_id) {
396 Some(hir_map::NodeItem(item)) => {
397 if item.vis == hir::Visibility::Inherited {
398 for impl_item_ref in impl_item_refs {
399 self.private_traits.insert(impl_item_ref.id.node_id);
408 hir::ItemConst(..) => "a constant",
409 hir::ItemStatic(..) => "a static",
413 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
416 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
417 if self.private_traits.contains(&trait_item.id) {
421 let desc = match trait_item.node {
422 hir::TraitItemKind::Const(..) => "an associated constant",
423 hir::TraitItemKind::Method(..) => "a trait method",
424 hir::TraitItemKind::Type(..) => "an associated type",
427 self.check_missing_docs_attrs(cx,
434 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
435 // If the method is an impl for a trait, don't doc.
436 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
440 let desc = match impl_item.node {
441 hir::ImplItemKind::Const(..) => "an associated constant",
442 hir::ImplItemKind::Method(..) => "a method",
443 hir::ImplItemKind::Type(_) => "an associated type",
445 self.check_missing_docs_attrs(cx,
452 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
453 if !sf.is_positional() {
454 if sf.vis == hir::Public || self.in_variant {
455 let cur_struct_def = *self.struct_def_stack
457 .expect("empty struct_def_stack");
458 self.check_missing_docs_attrs(cx,
459 Some(cur_struct_def),
467 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
468 self.check_missing_docs_attrs(cx,
469 Some(v.node.data.id()),
473 assert!(!self.in_variant);
474 self.in_variant = true;
477 fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
478 assert!(self.in_variant);
479 self.in_variant = false;
484 pub MISSING_COPY_IMPLEMENTATIONS,
486 "detects potentially-forgotten implementations of `Copy`"
489 #[derive(Copy, Clone)]
490 pub struct MissingCopyImplementations;
492 impl LintPass for MissingCopyImplementations {
493 fn get_lints(&self) -> LintArray {
494 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
498 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
499 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
500 if !cx.access_levels.is_reachable(item.id) {
503 let (def, ty) = match item.node {
504 hir::ItemStruct(_, ref ast_generics) => {
505 if ast_generics.is_parameterized() {
508 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
509 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
511 hir::ItemUnion(_, ref ast_generics) => {
512 if ast_generics.is_parameterized() {
515 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
516 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
518 hir::ItemEnum(_, ref ast_generics) => {
519 if ast_generics.is_parameterized() {
522 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
523 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
527 if def.has_dtor(cx.tcx) {
530 let param_env = ty::ParamEnv::empty();
531 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
534 if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
535 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
537 "type could implement `Copy`; consider adding `impl \
544 MISSING_DEBUG_IMPLEMENTATIONS,
546 "detects missing implementations of fmt::Debug"
549 pub struct MissingDebugImplementations {
550 impling_types: Option<NodeSet>,
553 impl MissingDebugImplementations {
554 pub fn new() -> MissingDebugImplementations {
555 MissingDebugImplementations { impling_types: None }
559 impl LintPass for MissingDebugImplementations {
560 fn get_lints(&self) -> LintArray {
561 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
565 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
566 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
567 if !cx.access_levels.is_reachable(item.id) {
572 hir::ItemStruct(..) |
574 hir::ItemEnum(..) => {}
578 let debug = match cx.tcx.lang_items.debug_trait() {
579 Some(debug) => debug,
583 if self.impling_types.is_none() {
584 let debug_def = cx.tcx.trait_def(debug);
585 let mut impls = NodeSet();
586 debug_def.for_each_impl(cx.tcx, |d| {
587 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
588 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
589 impls.insert(node_id);
594 self.impling_types = Some(impls);
595 debug!("{:?}", self.impling_types);
598 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
599 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
601 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
602 or a manual implementation")
608 pub ANONYMOUS_PARAMETERS,
610 "detects anonymous parameters"
613 /// Checks for use of anonymous parameters (RFC 1685)
615 pub struct AnonymousParameters;
617 impl LintPass for AnonymousParameters {
618 fn get_lints(&self) -> LintArray {
619 lint_array!(ANONYMOUS_PARAMETERS)
623 impl EarlyLintPass for AnonymousParameters {
624 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
626 ast::TraitItemKind::Method(ref sig, _) => {
627 for arg in sig.decl.inputs.iter() {
629 ast::PatKind::Ident(_, ident, None) => {
630 if ident.node.name == keywords::Invalid.name() {
631 cx.span_lint(ANONYMOUS_PARAMETERS,
633 "use of deprecated anonymous parameter");
648 "detects use of deprecated attributes"
651 /// Checks for use of attributes which have been deprecated.
653 pub struct DeprecatedAttr {
654 // This is not free to compute, so we want to keep it around, rather than
655 // compute it for every attribute.
656 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
659 impl DeprecatedAttr {
660 pub fn new() -> DeprecatedAttr {
662 depr_attrs: deprecated_attributes(),
667 impl LintPass for DeprecatedAttr {
668 fn get_lints(&self) -> LintArray {
669 lint_array!(DEPRECATED_ATTR)
673 impl EarlyLintPass for DeprecatedAttr {
674 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
675 let name = unwrap_or!(attr.name(), return);
676 for &&(n, _, ref g) in &self.depr_attrs {
678 if let &AttributeGate::Gated(Stability::Deprecated(link),
682 cx.span_lint(DEPRECATED,
684 &format!("use of deprecated attribute `{}`: {}. See {}",
685 name, reason, link));
694 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
696 "floating-point literals cannot be used in patterns"
699 /// Checks for floating point literals in patterns.
701 pub struct IllegalFloatLiteralPattern;
703 impl LintPass for IllegalFloatLiteralPattern {
704 fn get_lints(&self) -> LintArray {
705 lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
709 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
710 use self::ast::{ExprKind, LitKind};
712 ExprKind::Lit(ref l) => {
714 LitKind::FloatUnsuffixed(..) |
715 LitKind::Float(..) => {
716 cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
718 "floating-point literals cannot be used in patterns");
723 // These may occur in patterns
724 // and can maybe contain float literals
725 ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
726 // These may occur in patterns
727 // and can't contain float literals
728 ExprKind::Path(..) => (),
729 // If something unhandled is encountered, we need to expand the
730 // search or ignore more ExprKinds.
731 _ => span_bug!(expr.span, "Unhandled expression {:?} in float lit pattern lint",
736 impl EarlyLintPass for IllegalFloatLiteralPattern {
737 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
738 use self::ast::PatKind;
741 // Wildcard patterns and paths are uninteresting for the lint
743 PatKind::Path(..) => (),
745 // The walk logic recurses inside these
747 PatKind::Struct(..) |
749 PatKind::TupleStruct(..) |
752 PatKind::Slice(..) => (),
754 // Extract the expressions and check them
755 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
756 PatKind::Range(ref st, ref en, _) => {
757 fl_lit_check_expr(cx, st);
758 fl_lit_check_expr(cx, en);
761 PatKind::Mac(_) => bug!("lint must run post-expansion"),
769 pub UNCONDITIONAL_RECURSION,
771 "functions that cannot return without calling themselves"
774 #[derive(Copy, Clone)]
775 pub struct UnconditionalRecursion;
778 impl LintPass for UnconditionalRecursion {
779 fn get_lints(&self) -> LintArray {
780 lint_array![UNCONDITIONAL_RECURSION]
784 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
785 fn check_fn(&mut self,
792 let method = match fn_kind {
793 FnKind::ItemFn(..) => None,
794 FnKind::Method(..) => {
795 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
797 // closures can't recur, so they don't matter.
798 FnKind::Closure(_) => return,
801 // Walk through this function (say `f`) looking to see if
802 // every possible path references itself, i.e. the function is
803 // called recursively unconditionally. This is done by trying
804 // to find a path from the entry node to the exit node that
805 // *doesn't* call `f` by traversing from the entry while
806 // pretending that calls of `f` are sinks (i.e. ignoring any
807 // exit edges from them).
809 // NB. this has an edge case with non-returning statements,
810 // like `loop {}` or `panic!()`: control flow never reaches
811 // the exit node through these, so one can have a function
812 // that never actually calls itselfs but is still picked up by
815 // fn f(cond: bool) {
816 // if !cond { panic!() } // could come from `assert!(cond)`
820 // In general, functions of that form may be able to call
821 // itself a finite number of times and then diverge. The lint
822 // considers this to be an error for two reasons, (a) it is
823 // easier to implement, and (b) it seems rare to actually want
824 // to have behaviour like the above, rather than
825 // e.g. accidentally recurring after an assert.
827 let cfg = cfg::CFG::new(cx.tcx, &body);
829 let mut work_queue = vec![cfg.entry];
830 let mut reached_exit_without_self_call = false;
831 let mut self_call_spans = vec![];
832 let mut visited = HashSet::new();
834 while let Some(idx) = work_queue.pop() {
837 reached_exit_without_self_call = true;
841 let cfg_id = idx.node_id();
842 if visited.contains(&cfg_id) {
846 visited.insert(cfg_id);
848 let node_id = cfg.graph.node_data(idx).id();
850 // is this a recursive call?
851 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
853 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
854 None => expr_refers_to_this_fn(cx, id, node_id),
860 self_call_spans.push(cx.tcx.hir.span(node_id));
861 // this is a self call, so we shouldn't explore past
862 // this node in the CFG.
865 // add the successors of this node to explore the graph further.
866 for (_, edge) in cfg.graph.outgoing_edges(idx) {
867 let target_idx = edge.target();
868 let target_cfg_id = target_idx.node_id();
869 if !visited.contains(&target_cfg_id) {
870 work_queue.push(target_idx)
875 // Check the number of self calls because a function that
876 // doesn't return (e.g. calls a `-> !` function or `loop { /*
877 // no break */ }`) shouldn't be linted unless it actually
879 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
880 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
882 "function cannot return without recurring");
884 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
885 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
886 // offer some help to the programmer.
887 for call in &self_call_spans {
888 db.span_note(*call, "recursive call site");
890 db.help("a `loop` may express intention \
891 better if this is on purpose");
899 // Functions for identifying if the given Expr NodeId `id`
900 // represents a call to the function `fn_id`/method `method`.
902 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
903 match cx.tcx.hir.get(id) {
904 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
905 let def = if let hir::ExprPath(ref qpath) = callee.node {
906 cx.tables.qpath_def(qpath, callee.id)
910 def.def_id() == cx.tcx.hir.local_def_id(fn_id)
916 // Check if the expression `id` performs a call to `method`.
917 fn expr_refers_to_this_method(cx: &LateContext,
918 method: &ty::AssociatedItem,
921 use rustc::ty::adjustment::*;
923 // Check for method calls and overloaded operators.
924 let opt_m = cx.tables.method_map.get(&ty::MethodCall::expr(id)).cloned();
925 if let Some(m) = opt_m {
926 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
931 // Check for overloaded autoderef method calls.
932 let opt_adj = cx.tables.adjustments.get(&id).cloned();
933 if let Some(Adjustment { kind: Adjust::DerefRef { autoderefs, .. }, .. }) = opt_adj {
934 for i in 0..autoderefs {
935 let method_call = ty::MethodCall::autoderef(id, i as u32);
936 if let Some(m) = cx.tables.method_map.get(&method_call).cloned() {
937 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
944 // Check for calls to methods via explicit paths (e.g. `T::method()`).
945 match cx.tcx.hir.get(id) {
946 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
947 let def = if let hir::ExprPath(ref qpath) = callee.node {
948 cx.tables.qpath_def(qpath, callee.id)
953 Def::Method(def_id) => {
954 let substs = cx.tables.node_id_item_substs(callee.id)
955 .unwrap_or_else(|| cx.tcx.intern_substs(&[]));
956 method_call_refers_to_method(
957 cx.tcx, method, def_id, substs, id)
966 // Check if the method call to the method with the ID `callee_id`
967 // and instantiated with `callee_substs` refers to method `method`.
968 fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
969 method: &ty::AssociatedItem,
971 callee_substs: &Substs<'tcx>,
972 expr_id: ast::NodeId)
974 let callee_item = tcx.associated_item(callee_id);
976 match callee_item.container {
977 // This is an inherent method, so the `def_id` refers
978 // directly to the method definition.
979 ty::ImplContainer(_) => callee_id == method.def_id,
981 // A trait method, from any number of possible sources.
982 // Attempt to select a concrete impl before checking.
983 ty::TraitContainer(trait_def_id) => {
984 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
985 let trait_ref = ty::Binder(trait_ref);
986 let span = tcx.hir.span(expr_id);
988 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
989 trait_ref.to_poly_trait_predicate());
991 let param_env = tcx.param_env(method.def_id);
992 tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
993 let mut selcx = traits::SelectionContext::new(&infcx);
994 match selcx.select(&obligation) {
995 // The method comes from a `T: Trait` bound.
996 // If `T` is `Self`, then this call is inside
997 // a default method definition.
998 Ok(Some(traits::VtableParam(_))) => {
999 let on_self = trait_ref.self_ty().is_self();
1000 // We can only be recurring in a default
1001 // method if we're being called literally
1002 // on the `Self` type.
1003 on_self && callee_id == method.def_id
1006 // The `impl` is known, so we check that with a
1008 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1009 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1010 // It matches if it comes from the same impl,
1011 // and has the same method name.
1012 container == method.container && callee_item.name == method.name
1015 // There's no way to know if this call is
1016 // recursive, so we assume it's not.
1029 "compiler plugin used as ordinary library in non-plugin crate"
1032 #[derive(Copy, Clone)]
1033 pub struct PluginAsLibrary;
1035 impl LintPass for PluginAsLibrary {
1036 fn get_lints(&self) -> LintArray {
1037 lint_array![PLUGIN_AS_LIBRARY]
1041 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1042 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1043 if cx.sess().plugin_registrar_fn.get().is_some() {
1044 // We're compiling a plugin; it's fine to link other plugins.
1049 hir::ItemExternCrate(..) => (),
1053 let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
1054 Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
1056 // Probably means we aren't linking the crate for some reason.
1058 // Not sure if / when this could happen.
1064 cx.span_lint(PLUGIN_AS_LIBRARY,
1066 "compiler plugin used as an ordinary library");
1072 PRIVATE_NO_MANGLE_FNS,
1074 "functions marked #[no_mangle] should be exported"
1078 PRIVATE_NO_MANGLE_STATICS,
1080 "statics marked #[no_mangle] should be exported"
1084 NO_MANGLE_CONST_ITEMS,
1086 "const items will not have their symbols exported"
1090 NO_MANGLE_GENERIC_ITEMS,
1092 "generic items must be mangled"
1095 #[derive(Copy, Clone)]
1096 pub struct InvalidNoMangleItems;
1098 impl LintPass for InvalidNoMangleItems {
1099 fn get_lints(&self) -> LintArray {
1100 lint_array!(PRIVATE_NO_MANGLE_FNS,
1101 PRIVATE_NO_MANGLE_STATICS,
1102 NO_MANGLE_CONST_ITEMS,
1103 NO_MANGLE_GENERIC_ITEMS)
1107 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1108 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1110 hir::ItemFn(.., ref generics, _) => {
1111 if attr::contains_name(&it.attrs, "no_mangle") {
1112 if !cx.access_levels.is_reachable(it.id) {
1113 let msg = format!("function {} is marked #[no_mangle], but not exported",
1115 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1117 if generics.is_parameterized() {
1118 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1120 "generic functions must be mangled");
1124 hir::ItemStatic(..) => {
1125 if attr::contains_name(&it.attrs, "no_mangle") &&
1126 !cx.access_levels.is_reachable(it.id) {
1127 let msg = format!("static {} is marked #[no_mangle], but not exported",
1129 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1132 hir::ItemConst(..) => {
1133 if attr::contains_name(&it.attrs, "no_mangle") {
1134 // Const items do not refer to a particular location in memory, and therefore
1135 // don't have anything to attach a symbol to
1136 let msg = "const items should never be #[no_mangle], consider instead using \
1138 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1146 #[derive(Clone, Copy)]
1147 pub struct MutableTransmutes;
1152 "mutating transmuted &mut T from &T may cause undefined behavior"
1155 impl LintPass for MutableTransmutes {
1156 fn get_lints(&self) -> LintArray {
1157 lint_array!(MUTABLE_TRANSMUTES)
1161 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1162 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1163 use syntax::abi::Abi::RustIntrinsic;
1165 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1166 consider instead using an UnsafeCell";
1167 match get_transmute_from_to(cx, expr) {
1168 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1169 if to_mt.mutbl == hir::Mutability::MutMutable &&
1170 from_mt.mutbl == hir::Mutability::MutImmutable {
1171 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1177 fn get_transmute_from_to<'a, 'tcx>
1178 (cx: &LateContext<'a, 'tcx>,
1180 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1181 let def = if let hir::ExprPath(ref qpath) = expr.node {
1182 cx.tables.qpath_def(qpath, expr.id)
1186 if let Def::Fn(did) = def {
1187 if !def_id_is_transmute(cx, did) {
1190 let typ = cx.tables.node_id_to_type(expr.id);
1192 ty::TyFnDef(.., bare_fn) if bare_fn.abi() == RustIntrinsic => {
1193 let from = bare_fn.inputs().skip_binder()[0];
1194 let to = *bare_fn.output().skip_binder();
1195 return Some((&from.sty, &to.sty));
1203 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1204 match cx.tcx.type_of(def_id).sty {
1205 ty::TyFnDef(.., bfty) if bfty.abi() == RustIntrinsic => (),
1208 cx.tcx.item_name(def_id) == "transmute"
1213 /// Forbids using the `#[feature(...)]` attribute
1214 #[derive(Copy, Clone)]
1215 pub struct UnstableFeatures;
1220 "enabling unstable features (deprecated. do not use)"
1223 impl LintPass for UnstableFeatures {
1224 fn get_lints(&self) -> LintArray {
1225 lint_array!(UNSTABLE_FEATURES)
1229 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1230 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1231 if attr.check_name("feature") {
1232 if let Some(items) = attr.meta_item_list() {
1234 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1241 /// Lint for unions that contain fields with possibly non-trivial destructors.
1242 pub struct UnionsWithDropFields;
1245 UNIONS_WITH_DROP_FIELDS,
1247 "use of unions that contain fields with possibly non-trivial drop code"
1250 impl LintPass for UnionsWithDropFields {
1251 fn get_lints(&self) -> LintArray {
1252 lint_array!(UNIONS_WITH_DROP_FIELDS)
1256 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1257 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1258 if let hir::ItemUnion(ref vdata, _) = item.node {
1259 let item_def_id = ctx.tcx.hir.local_def_id(item.id);
1260 let param_env = ctx.tcx.param_env(item_def_id);
1261 for field in vdata.fields() {
1262 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1263 if field_ty.needs_drop(ctx.tcx, param_env) {
1264 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1266 "union contains a field with possibly non-trivial drop code, \
1267 drop code of union fields is ignored when dropping the union");