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 parameter_environment = cx.tcx.empty_parameter_environment();
531 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
533 if !ty.moves_by_default(cx.tcx, ¶meter_environment, item.span) {
536 if parameter_environment.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
537 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
539 "type could implement `Copy`; consider adding `impl \
546 MISSING_DEBUG_IMPLEMENTATIONS,
548 "detects missing implementations of fmt::Debug"
551 pub struct MissingDebugImplementations {
552 impling_types: Option<NodeSet>,
555 impl MissingDebugImplementations {
556 pub fn new() -> MissingDebugImplementations {
557 MissingDebugImplementations { impling_types: None }
561 impl LintPass for MissingDebugImplementations {
562 fn get_lints(&self) -> LintArray {
563 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
567 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
568 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
569 if !cx.access_levels.is_reachable(item.id) {
574 hir::ItemStruct(..) |
576 hir::ItemEnum(..) => {}
580 let debug = match cx.tcx.lang_items.debug_trait() {
581 Some(debug) => debug,
585 if self.impling_types.is_none() {
586 let debug_def = cx.tcx.trait_def(debug);
587 let mut impls = NodeSet();
588 debug_def.for_each_impl(cx.tcx, |d| {
589 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
590 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
591 impls.insert(node_id);
596 self.impling_types = Some(impls);
597 debug!("{:?}", self.impling_types);
600 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
601 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
603 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
604 or a manual implementation")
610 pub ANONYMOUS_PARAMETERS,
612 "detects anonymous parameters"
615 /// Checks for use of anonymous parameters (RFC 1685)
617 pub struct AnonymousParameters;
619 impl LintPass for AnonymousParameters {
620 fn get_lints(&self) -> LintArray {
621 lint_array!(ANONYMOUS_PARAMETERS)
625 impl EarlyLintPass for AnonymousParameters {
626 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
628 ast::TraitItemKind::Method(ref sig, _) => {
629 for arg in sig.decl.inputs.iter() {
631 ast::PatKind::Ident(_, ident, None) => {
632 if ident.node.name == keywords::Invalid.name() {
633 cx.span_lint(ANONYMOUS_PARAMETERS,
635 "use of deprecated anonymous parameter");
650 "detects use of deprecated attributes"
653 /// Checks for use of attributes which have been deprecated.
655 pub struct DeprecatedAttr {
656 // This is not free to compute, so we want to keep it around, rather than
657 // compute it for every attribute.
658 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
661 impl DeprecatedAttr {
662 pub fn new() -> DeprecatedAttr {
664 depr_attrs: deprecated_attributes(),
669 impl LintPass for DeprecatedAttr {
670 fn get_lints(&self) -> LintArray {
671 lint_array!(DEPRECATED_ATTR)
675 impl EarlyLintPass for DeprecatedAttr {
676 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
677 let name = unwrap_or!(attr.name(), return);
678 for &&(n, _, ref g) in &self.depr_attrs {
680 if let &AttributeGate::Gated(Stability::Deprecated(link),
684 cx.span_lint(DEPRECATED,
686 &format!("use of deprecated attribute `{}`: {}. See {}",
687 name, reason, link));
696 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
698 "floating-point literals cannot be used in patterns"
701 /// Checks for floating point literals in patterns.
703 pub struct IllegalFloatLiteralPattern;
705 impl LintPass for IllegalFloatLiteralPattern {
706 fn get_lints(&self) -> LintArray {
707 lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
711 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
712 use self::ast::{ExprKind, LitKind};
714 ExprKind::Lit(ref l) => {
716 LitKind::FloatUnsuffixed(..) |
717 LitKind::Float(..) => {
718 cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
720 "floating-point literals cannot be used in patterns");
725 // These may occur in patterns
726 // and can maybe contain float literals
727 ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
728 // These may occur in patterns
729 // and can't contain float literals
730 ExprKind::Path(..) => (),
731 // If something unhandled is encountered, we need to expand the
732 // search or ignore more ExprKinds.
733 _ => span_bug!(expr.span, "Unhandled expression {:?} in float lit pattern lint",
738 impl EarlyLintPass for IllegalFloatLiteralPattern {
739 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
740 use self::ast::PatKind;
743 // Wildcard patterns and paths are uninteresting for the lint
745 PatKind::Path(..) => (),
747 // The walk logic recurses inside these
749 PatKind::Struct(..) |
751 PatKind::TupleStruct(..) |
754 PatKind::Slice(..) => (),
756 // Extract the expressions and check them
757 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
758 PatKind::Range(ref st, ref en, _) => {
759 fl_lit_check_expr(cx, st);
760 fl_lit_check_expr(cx, en);
763 PatKind::Mac(_) => bug!("lint must run post-expansion"),
771 pub UNCONDITIONAL_RECURSION,
773 "functions that cannot return without calling themselves"
776 #[derive(Copy, Clone)]
777 pub struct UnconditionalRecursion;
780 impl LintPass for UnconditionalRecursion {
781 fn get_lints(&self) -> LintArray {
782 lint_array![UNCONDITIONAL_RECURSION]
786 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
787 fn check_fn(&mut self,
794 let method = match fn_kind {
795 FnKind::ItemFn(..) => None,
796 FnKind::Method(..) => {
797 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
799 // closures can't recur, so they don't matter.
800 FnKind::Closure(_) => return,
803 // Walk through this function (say `f`) looking to see if
804 // every possible path references itself, i.e. the function is
805 // called recursively unconditionally. This is done by trying
806 // to find a path from the entry node to the exit node that
807 // *doesn't* call `f` by traversing from the entry while
808 // pretending that calls of `f` are sinks (i.e. ignoring any
809 // exit edges from them).
811 // NB. this has an edge case with non-returning statements,
812 // like `loop {}` or `panic!()`: control flow never reaches
813 // the exit node through these, so one can have a function
814 // that never actually calls itselfs but is still picked up by
817 // fn f(cond: bool) {
818 // if !cond { panic!() } // could come from `assert!(cond)`
822 // In general, functions of that form may be able to call
823 // itself a finite number of times and then diverge. The lint
824 // considers this to be an error for two reasons, (a) it is
825 // easier to implement, and (b) it seems rare to actually want
826 // to have behaviour like the above, rather than
827 // e.g. accidentally recurring after an assert.
829 let cfg = cfg::CFG::new(cx.tcx, &body);
831 let mut work_queue = vec![cfg.entry];
832 let mut reached_exit_without_self_call = false;
833 let mut self_call_spans = vec![];
834 let mut visited = HashSet::new();
836 while let Some(idx) = work_queue.pop() {
839 reached_exit_without_self_call = true;
843 let cfg_id = idx.node_id();
844 if visited.contains(&cfg_id) {
848 visited.insert(cfg_id);
850 let node_id = cfg.graph.node_data(idx).id();
852 // is this a recursive call?
853 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
855 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
856 None => expr_refers_to_this_fn(cx, id, node_id),
862 self_call_spans.push(cx.tcx.hir.span(node_id));
863 // this is a self call, so we shouldn't explore past
864 // this node in the CFG.
867 // add the successors of this node to explore the graph further.
868 for (_, edge) in cfg.graph.outgoing_edges(idx) {
869 let target_idx = edge.target();
870 let target_cfg_id = target_idx.node_id();
871 if !visited.contains(&target_cfg_id) {
872 work_queue.push(target_idx)
877 // Check the number of self calls because a function that
878 // doesn't return (e.g. calls a `-> !` function or `loop { /*
879 // no break */ }`) shouldn't be linted unless it actually
881 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
882 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
884 "function cannot return without recurring");
886 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
887 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
888 // offer some help to the programmer.
889 for call in &self_call_spans {
890 db.span_note(*call, "recursive call site");
892 db.help("a `loop` may express intention \
893 better if this is on purpose");
901 // Functions for identifying if the given Expr NodeId `id`
902 // represents a call to the function `fn_id`/method `method`.
904 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
905 match cx.tcx.hir.get(id) {
906 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
907 let def = if let hir::ExprPath(ref qpath) = callee.node {
908 cx.tables.qpath_def(qpath, callee.id)
912 def.def_id() == cx.tcx.hir.local_def_id(fn_id)
918 // Check if the expression `id` performs a call to `method`.
919 fn expr_refers_to_this_method(cx: &LateContext,
920 method: &ty::AssociatedItem,
923 use rustc::ty::adjustment::*;
925 // Check for method calls and overloaded operators.
926 let opt_m = cx.tables.method_map.get(&ty::MethodCall::expr(id)).cloned();
927 if let Some(m) = opt_m {
928 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
933 // Check for overloaded autoderef method calls.
934 let opt_adj = cx.tables.adjustments.get(&id).cloned();
935 if let Some(Adjustment { kind: Adjust::DerefRef { autoderefs, .. }, .. }) = opt_adj {
936 for i in 0..autoderefs {
937 let method_call = ty::MethodCall::autoderef(id, i as u32);
938 if let Some(m) = cx.tables.method_map.get(&method_call).cloned() {
939 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
946 // Check for calls to methods via explicit paths (e.g. `T::method()`).
947 match cx.tcx.hir.get(id) {
948 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
949 let def = if let hir::ExprPath(ref qpath) = callee.node {
950 cx.tables.qpath_def(qpath, callee.id)
955 Def::Method(def_id) => {
956 let substs = cx.tables.node_id_item_substs(callee.id)
957 .unwrap_or_else(|| cx.tcx.intern_substs(&[]));
958 method_call_refers_to_method(
959 cx.tcx, method, def_id, substs, id)
968 // Check if the method call to the method with the ID `callee_id`
969 // and instantiated with `callee_substs` refers to method `method`.
970 fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
971 method: &ty::AssociatedItem,
973 callee_substs: &Substs<'tcx>,
974 expr_id: ast::NodeId)
976 let callee_item = tcx.associated_item(callee_id);
978 match callee_item.container {
979 // This is an inherent method, so the `def_id` refers
980 // directly to the method definition.
981 ty::ImplContainer(_) => callee_id == method.def_id,
983 // A trait method, from any number of possible sources.
984 // Attempt to select a concrete impl before checking.
985 ty::TraitContainer(trait_def_id) => {
986 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
987 let trait_ref = ty::Binder(trait_ref);
988 let span = tcx.hir.span(expr_id);
990 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
991 trait_ref.to_poly_trait_predicate());
993 // unwrap() is ok here b/c `method` is the method
994 // defined in this crate whose body we are
995 // checking, so it's always local
996 let node_id = tcx.hir.as_local_node_id(method.def_id).unwrap();
998 let param_env = ty::ParameterEnvironment::for_item(tcx, node_id);
999 tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
1000 let mut selcx = traits::SelectionContext::new(&infcx);
1001 match selcx.select(&obligation) {
1002 // The method comes from a `T: Trait` bound.
1003 // If `T` is `Self`, then this call is inside
1004 // a default method definition.
1005 Ok(Some(traits::VtableParam(_))) => {
1006 let on_self = trait_ref.self_ty().is_self();
1007 // We can only be recurring in a default
1008 // method if we're being called literally
1009 // on the `Self` type.
1010 on_self && callee_id == method.def_id
1013 // The `impl` is known, so we check that with a
1015 Ok(Some(traits::VtableImpl(vtable_impl))) => {
1016 let container = ty::ImplContainer(vtable_impl.impl_def_id);
1017 // It matches if it comes from the same impl,
1018 // and has the same method name.
1019 container == method.container && callee_item.name == method.name
1022 // There's no way to know if this call is
1023 // recursive, so we assume it's not.
1036 "compiler plugin used as ordinary library in non-plugin crate"
1039 #[derive(Copy, Clone)]
1040 pub struct PluginAsLibrary;
1042 impl LintPass for PluginAsLibrary {
1043 fn get_lints(&self) -> LintArray {
1044 lint_array![PLUGIN_AS_LIBRARY]
1048 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1049 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1050 if cx.sess().plugin_registrar_fn.get().is_some() {
1051 // We're compiling a plugin; it's fine to link other plugins.
1056 hir::ItemExternCrate(..) => (),
1060 let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
1061 Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
1063 // Probably means we aren't linking the crate for some reason.
1065 // Not sure if / when this could happen.
1071 cx.span_lint(PLUGIN_AS_LIBRARY,
1073 "compiler plugin used as an ordinary library");
1079 PRIVATE_NO_MANGLE_FNS,
1081 "functions marked #[no_mangle] should be exported"
1085 PRIVATE_NO_MANGLE_STATICS,
1087 "statics marked #[no_mangle] should be exported"
1091 NO_MANGLE_CONST_ITEMS,
1093 "const items will not have their symbols exported"
1097 NO_MANGLE_GENERIC_ITEMS,
1099 "generic items must be mangled"
1102 #[derive(Copy, Clone)]
1103 pub struct InvalidNoMangleItems;
1105 impl LintPass for InvalidNoMangleItems {
1106 fn get_lints(&self) -> LintArray {
1107 lint_array!(PRIVATE_NO_MANGLE_FNS,
1108 PRIVATE_NO_MANGLE_STATICS,
1109 NO_MANGLE_CONST_ITEMS,
1110 NO_MANGLE_GENERIC_ITEMS)
1114 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1115 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1117 hir::ItemFn(.., ref generics, _) => {
1118 if attr::contains_name(&it.attrs, "no_mangle") {
1119 if !cx.access_levels.is_reachable(it.id) {
1120 let msg = format!("function {} is marked #[no_mangle], but not exported",
1122 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1124 if generics.is_parameterized() {
1125 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1127 "generic functions must be mangled");
1131 hir::ItemStatic(..) => {
1132 if attr::contains_name(&it.attrs, "no_mangle") &&
1133 !cx.access_levels.is_reachable(it.id) {
1134 let msg = format!("static {} is marked #[no_mangle], but not exported",
1136 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1139 hir::ItemConst(..) => {
1140 if attr::contains_name(&it.attrs, "no_mangle") {
1141 // Const items do not refer to a particular location in memory, and therefore
1142 // don't have anything to attach a symbol to
1143 let msg = "const items should never be #[no_mangle], consider instead using \
1145 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1153 #[derive(Clone, Copy)]
1154 pub struct MutableTransmutes;
1159 "mutating transmuted &mut T from &T may cause undefined behavior"
1162 impl LintPass for MutableTransmutes {
1163 fn get_lints(&self) -> LintArray {
1164 lint_array!(MUTABLE_TRANSMUTES)
1168 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1169 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1170 use syntax::abi::Abi::RustIntrinsic;
1172 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1173 consider instead using an UnsafeCell";
1174 match get_transmute_from_to(cx, expr) {
1175 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1176 if to_mt.mutbl == hir::Mutability::MutMutable &&
1177 from_mt.mutbl == hir::Mutability::MutImmutable {
1178 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1184 fn get_transmute_from_to<'a, 'tcx>
1185 (cx: &LateContext<'a, 'tcx>,
1187 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1188 let def = if let hir::ExprPath(ref qpath) = expr.node {
1189 cx.tables.qpath_def(qpath, expr.id)
1193 if let Def::Fn(did) = def {
1194 if !def_id_is_transmute(cx, did) {
1197 let typ = cx.tables.node_id_to_type(expr.id);
1199 ty::TyFnDef(.., bare_fn) if bare_fn.abi() == RustIntrinsic => {
1200 let from = bare_fn.inputs().skip_binder()[0];
1201 let to = *bare_fn.output().skip_binder();
1202 return Some((&from.sty, &to.sty));
1210 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1211 match cx.tcx.type_of(def_id).sty {
1212 ty::TyFnDef(.., bfty) if bfty.abi() == RustIntrinsic => (),
1215 cx.tcx.item_name(def_id) == "transmute"
1220 /// Forbids using the `#[feature(...)]` attribute
1221 #[derive(Copy, Clone)]
1222 pub struct UnstableFeatures;
1227 "enabling unstable features (deprecated. do not use)"
1230 impl LintPass for UnstableFeatures {
1231 fn get_lints(&self) -> LintArray {
1232 lint_array!(UNSTABLE_FEATURES)
1236 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1237 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1238 if attr.check_name("feature") {
1239 if let Some(items) = attr.meta_item_list() {
1241 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1248 /// Lint for unions that contain fields with possibly non-trivial destructors.
1249 pub struct UnionsWithDropFields;
1252 UNIONS_WITH_DROP_FIELDS,
1254 "use of unions that contain fields with possibly non-trivial drop code"
1257 impl LintPass for UnionsWithDropFields {
1258 fn get_lints(&self) -> LintArray {
1259 lint_array!(UNIONS_WITH_DROP_FIELDS)
1263 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1264 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1265 if let hir::ItemUnion(ref vdata, _) = item.node {
1266 let param_env = &ty::ParameterEnvironment::for_item(ctx.tcx, item.id);
1267 for field in vdata.fields() {
1268 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1269 if field_ty.needs_drop(ctx.tcx, param_env) {
1270 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1272 "union contains a field with possibly non-trivial drop code, \
1273 drop code of union fields is ignored when dropping the union");