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::{BytePos, Span, SyntaxContext};
48 use syntax::symbol::keywords;
50 use rustc::hir::{self, PatKind};
51 use rustc::hir::intravisit::FnKind;
53 use bad_style::{MethodLateContext, method_context};
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
61 "suggest using `loop { }` instead of `while true { }`"
64 #[derive(Copy, Clone)]
67 impl LintPass for WhileTrue {
68 fn get_lints(&self) -> LintArray {
69 lint_array!(WHILE_TRUE)
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
74 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
75 if let hir::ExprWhile(ref cond, ..) = e.node {
76 if let hir::ExprLit(ref lit) = cond.node {
77 if let ast::LitKind::Bool(true) = lit.node {
78 if lit.span.ctxt() == SyntaxContext::empty() {
79 let msg = "denote infinite loops with `loop { ... }`";
80 let condition_span = cx.tcx.sess.codemap().def_span(e.span);
81 let mut err = cx.struct_span_lint(WHILE_TRUE, condition_span, msg);
82 err.span_suggestion_short(condition_span, "use `loop`", "loop".to_owned());
94 "use of owned (Box type) heap memory"
97 #[derive(Copy, Clone)]
98 pub struct BoxPointers;
101 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
102 for leaf_ty in ty.walk() {
103 if leaf_ty.is_box() {
104 let m = format!("type uses owned (Box type) pointers: {}", ty);
105 cx.span_lint(BOX_POINTERS, span, &m);
111 impl LintPass for BoxPointers {
112 fn get_lints(&self) -> LintArray {
113 lint_array!(BOX_POINTERS)
117 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
118 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
123 hir::ItemStruct(..) |
124 hir::ItemUnion(..) => {
125 let def_id = cx.tcx.hir.local_def_id(it.id);
126 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
131 // If it's a struct, we also have to check the fields' types
133 hir::ItemStruct(ref struct_def, _) |
134 hir::ItemUnion(ref struct_def, _) => {
135 for struct_field in struct_def.fields() {
136 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
137 self.check_heap_type(cx, struct_field.span,
138 cx.tcx.type_of(def_id));
145 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
146 let ty = cx.tables.node_id_to_type(e.hir_id);
147 self.check_heap_type(cx, e.span, ty);
152 NON_SHORTHAND_FIELD_PATTERNS,
154 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
157 #[derive(Copy, Clone)]
158 pub struct NonShorthandFieldPatterns;
160 impl LintPass for NonShorthandFieldPatterns {
161 fn get_lints(&self) -> LintArray {
162 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
166 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
167 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
168 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
169 for fieldpat in field_pats {
170 if fieldpat.node.is_shorthand {
173 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
174 if ident.node == fieldpat.node.name {
175 let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
177 &format!("the `{}:` in this pattern is redundant",
179 let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':');
180 err.span_suggestion_short(subspan,
182 format!("{}", ident.node));
194 "usage of `unsafe` code"
197 #[derive(Copy, Clone)]
198 pub struct UnsafeCode;
200 impl LintPass for UnsafeCode {
201 fn get_lints(&self) -> LintArray {
202 lint_array!(UNSAFE_CODE)
207 fn report_unsafe(&self, cx: &LateContext, span: Span, desc: &'static str) {
208 // This comes from a macro that has #[allow_internal_unsafe].
209 if span.allows_unsafe() {
213 cx.span_lint(UNSAFE_CODE, span, desc);
217 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
218 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
219 if let hir::ExprBlock(ref blk) = e.node {
220 // Don't warn about generated blocks, that'll just pollute the output.
221 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
222 self.report_unsafe(cx, blk.span, "usage of an `unsafe` block");
227 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
229 hir::ItemTrait(_, hir::Unsafety::Unsafe, ..) => {
230 self.report_unsafe(cx, it.span, "declaration of an `unsafe` trait")
233 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
234 self.report_unsafe(cx, it.span, "implementation of an `unsafe` trait")
241 fn check_fn(&mut self,
249 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
250 self.report_unsafe(cx, span, "declaration of an `unsafe` function")
253 FnKind::Method(_, sig, ..) => {
254 if sig.unsafety == hir::Unsafety::Unsafe {
255 self.report_unsafe(cx, span, "implementation of an `unsafe` method")
263 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
264 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
265 if sig.unsafety == hir::Unsafety::Unsafe {
266 self.report_unsafe(cx, item.span, "declaration of an `unsafe` method")
275 "detects missing documentation for public members"
278 pub struct MissingDoc {
279 /// Stack of whether #[doc(hidden)] is set
280 /// at each level which has lint attributes.
281 doc_hidden_stack: Vec<bool>,
283 /// Private traits or trait items that leaked through. Don't check their methods.
284 private_traits: HashSet<ast::NodeId>,
288 pub fn new() -> MissingDoc {
290 doc_hidden_stack: vec![false],
291 private_traits: HashSet::new(),
295 fn doc_hidden(&self) -> bool {
296 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
299 fn check_missing_docs_attrs(&self,
301 id: Option<ast::NodeId>,
302 attrs: &[ast::Attribute],
304 desc: &'static str) {
305 // If we're building a test harness, then warning about
306 // documentation is probably not really relevant right now.
307 if cx.sess().opts.test {
311 // `#[doc(hidden)]` disables missing_docs check.
312 if self.doc_hidden() {
316 // Only check publicly-visible items, using the result from the privacy pass.
317 // It's an option so the crate root can also use this function (it doesn't
319 if let Some(id) = id {
320 if !cx.access_levels.is_exported(id) {
325 fn has_doc(attr: &ast::Attribute) -> bool {
326 if !attr.check_name("doc") {
330 if attr.is_value_str() {
334 if let Some(list) = attr.meta_item_list() {
336 if meta.check_name("include") {
345 let has_doc = attrs.iter().any(|a| has_doc(a));
347 cx.span_lint(MISSING_DOCS,
348 cx.tcx.sess.codemap().def_span(sp),
349 &format!("missing documentation for {}", desc));
354 impl LintPass for MissingDoc {
355 fn get_lints(&self) -> LintArray {
356 lint_array!(MISSING_DOCS)
360 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
361 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
362 let doc_hidden = self.doc_hidden() ||
363 attrs.iter().any(|attr| {
364 attr.check_name("doc") &&
365 match attr.meta_item_list() {
367 Some(l) => attr::list_contains_name(&l, "hidden"),
370 self.doc_hidden_stack.push(doc_hidden);
373 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
374 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
377 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
378 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
381 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
382 let desc = match it.node {
383 hir::ItemFn(..) => "a function",
384 hir::ItemMod(..) => "a module",
385 hir::ItemEnum(..) => "an enum",
386 hir::ItemStruct(..) => "a struct",
387 hir::ItemUnion(..) => "a union",
388 hir::ItemTrait(.., ref trait_item_refs) => {
389 // Issue #11592, traits are always considered exported, even when private.
390 if it.vis == hir::Visibility::Inherited {
391 self.private_traits.insert(it.id);
392 for trait_item_ref in trait_item_refs {
393 self.private_traits.insert(trait_item_ref.id.node_id);
399 hir::ItemTy(..) => "a type alias",
400 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
401 // If the trait is private, add the impl items to private_traits so they don't get
402 // reported for missing docs.
403 let real_trait = trait_ref.path.def.def_id();
404 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
405 match cx.tcx.hir.find(node_id) {
406 Some(hir_map::NodeItem(item)) => {
407 if item.vis == hir::Visibility::Inherited {
408 for impl_item_ref in impl_item_refs {
409 self.private_traits.insert(impl_item_ref.id.node_id);
418 hir::ItemConst(..) => "a constant",
419 hir::ItemStatic(..) => "a static",
423 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
426 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
427 if self.private_traits.contains(&trait_item.id) {
431 let desc = match trait_item.node {
432 hir::TraitItemKind::Const(..) => "an associated constant",
433 hir::TraitItemKind::Method(..) => "a trait method",
434 hir::TraitItemKind::Type(..) => "an associated type",
437 self.check_missing_docs_attrs(cx,
444 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
445 // If the method is an impl for a trait, don't doc.
446 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
450 let desc = match impl_item.node {
451 hir::ImplItemKind::Const(..) => "an associated constant",
452 hir::ImplItemKind::Method(..) => "a method",
453 hir::ImplItemKind::Type(_) => "an associated type",
455 self.check_missing_docs_attrs(cx,
462 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
463 if !sf.is_positional() {
464 self.check_missing_docs_attrs(cx,
472 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
473 self.check_missing_docs_attrs(cx,
474 Some(v.node.data.id()),
482 pub MISSING_COPY_IMPLEMENTATIONS,
484 "detects potentially-forgotten implementations of `Copy`"
487 #[derive(Copy, Clone)]
488 pub struct MissingCopyImplementations;
490 impl LintPass for MissingCopyImplementations {
491 fn get_lints(&self) -> LintArray {
492 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
496 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
497 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
498 if !cx.access_levels.is_reachable(item.id) {
501 let (def, ty) = match item.node {
502 hir::ItemStruct(_, ref ast_generics) => {
503 if !ast_generics.params.is_empty() {
506 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
507 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
509 hir::ItemUnion(_, ref ast_generics) => {
510 if !ast_generics.params.is_empty() {
513 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
514 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
516 hir::ItemEnum(_, ref ast_generics) => {
517 if !ast_generics.params.is_empty() {
520 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
521 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
525 if def.has_dtor(cx.tcx) {
528 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
529 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
532 if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
533 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
535 "type could implement `Copy`; consider adding `impl \
542 MISSING_DEBUG_IMPLEMENTATIONS,
544 "detects missing implementations of fmt::Debug"
547 pub struct MissingDebugImplementations {
548 impling_types: Option<NodeSet>,
551 impl MissingDebugImplementations {
552 pub fn new() -> MissingDebugImplementations {
553 MissingDebugImplementations { impling_types: None }
557 impl LintPass for MissingDebugImplementations {
558 fn get_lints(&self) -> LintArray {
559 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
563 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
564 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
565 if !cx.access_levels.is_reachable(item.id) {
570 hir::ItemStruct(..) |
572 hir::ItemEnum(..) => {}
576 let debug = match cx.tcx.lang_items().debug_trait() {
577 Some(debug) => debug,
581 if self.impling_types.is_none() {
582 let mut impls = NodeSet();
583 cx.tcx.for_each_impl(debug, |d| {
584 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
585 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
586 impls.insert(node_id);
591 self.impling_types = Some(impls);
592 debug!("{:?}", self.impling_types);
595 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
596 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
598 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
599 or a manual implementation")
605 pub ANONYMOUS_PARAMETERS,
607 "detects anonymous parameters"
610 /// Checks for use of anonymous parameters (RFC 1685)
612 pub struct AnonymousParameters;
614 impl LintPass for AnonymousParameters {
615 fn get_lints(&self) -> LintArray {
616 lint_array!(ANONYMOUS_PARAMETERS)
620 impl EarlyLintPass for AnonymousParameters {
621 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
623 ast::TraitItemKind::Method(ref sig, _) => {
624 for arg in sig.decl.inputs.iter() {
626 ast::PatKind::Ident(_, ident, None) => {
627 if ident.node.name == keywords::Invalid.name() {
628 cx.span_lint(ANONYMOUS_PARAMETERS,
630 "use of deprecated anonymous parameter");
642 /// Checks for use of attributes which have been deprecated.
644 pub struct DeprecatedAttr {
645 // This is not free to compute, so we want to keep it around, rather than
646 // compute it for every attribute.
647 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
650 impl DeprecatedAttr {
651 pub fn new() -> DeprecatedAttr {
653 depr_attrs: deprecated_attributes(),
658 impl LintPass for DeprecatedAttr {
659 fn get_lints(&self) -> LintArray {
664 impl EarlyLintPass for DeprecatedAttr {
665 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
666 let name = unwrap_or!(attr.name(), return);
667 for &&(n, _, ref g) in &self.depr_attrs {
669 if let &AttributeGate::Gated(Stability::Deprecated(link),
673 let msg = format!("use of deprecated attribute `{}`: {}. See {}",
675 let mut err = cx.struct_span_lint(DEPRECATED, attr.span, &msg);
676 err.span_suggestion_short(attr.span, "remove this attribute", "".to_owned());
686 pub UNUSED_DOC_COMMENT,
688 "detects doc comments that aren't used by rustdoc"
691 #[derive(Copy, Clone)]
692 pub struct UnusedDocComment;
694 impl LintPass for UnusedDocComment {
695 fn get_lints(&self) -> LintArray {
696 lint_array![UNUSED_DOC_COMMENT]
700 impl UnusedDocComment {
701 fn warn_if_doc<'a, 'tcx,
702 I: Iterator<Item=&'a ast::Attribute>,
703 C: LintContext<'tcx>>(&self, mut attrs: I, cx: &C) {
704 if let Some(attr) = attrs.find(|a| a.is_value_str() && a.check_name("doc")) {
705 cx.struct_span_lint(UNUSED_DOC_COMMENT, attr.span, "doc comment not used by rustdoc")
711 impl EarlyLintPass for UnusedDocComment {
712 fn check_local(&mut self, cx: &EarlyContext, decl: &ast::Local) {
713 self.warn_if_doc(decl.attrs.iter(), cx);
716 fn check_arm(&mut self, cx: &EarlyContext, arm: &ast::Arm) {
717 self.warn_if_doc(arm.attrs.iter(), cx);
720 fn check_expr(&mut self, cx: &EarlyContext, expr: &ast::Expr) {
721 self.warn_if_doc(expr.attrs.iter(), cx);
726 pub UNCONDITIONAL_RECURSION,
728 "functions that cannot return without calling themselves"
731 #[derive(Copy, Clone)]
732 pub struct UnconditionalRecursion;
735 impl LintPass for UnconditionalRecursion {
736 fn get_lints(&self) -> LintArray {
737 lint_array![UNCONDITIONAL_RECURSION]
741 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
742 fn check_fn(&mut self,
749 let method = match fn_kind {
750 FnKind::ItemFn(..) => None,
751 FnKind::Method(..) => {
752 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
754 // closures can't recur, so they don't matter.
755 FnKind::Closure(_) => return,
758 // Walk through this function (say `f`) looking to see if
759 // every possible path references itself, i.e. the function is
760 // called recursively unconditionally. This is done by trying
761 // to find a path from the entry node to the exit node that
762 // *doesn't* call `f` by traversing from the entry while
763 // pretending that calls of `f` are sinks (i.e. ignoring any
764 // exit edges from them).
766 // NB. this has an edge case with non-returning statements,
767 // like `loop {}` or `panic!()`: control flow never reaches
768 // the exit node through these, so one can have a function
769 // that never actually calls itselfs but is still picked up by
772 // fn f(cond: bool) {
773 // if !cond { panic!() } // could come from `assert!(cond)`
777 // In general, functions of that form may be able to call
778 // itself a finite number of times and then diverge. The lint
779 // considers this to be an error for two reasons, (a) it is
780 // easier to implement, and (b) it seems rare to actually want
781 // to have behaviour like the above, rather than
782 // e.g. accidentally recurring after an assert.
784 let cfg = cfg::CFG::new(cx.tcx, &body);
786 let mut work_queue = vec![cfg.entry];
787 let mut reached_exit_without_self_call = false;
788 let mut self_call_spans = vec![];
789 let mut visited = HashSet::new();
791 while let Some(idx) = work_queue.pop() {
794 reached_exit_without_self_call = true;
798 let cfg_id = idx.node_id();
799 if visited.contains(&cfg_id) {
803 visited.insert(cfg_id);
805 // is this a recursive call?
806 let local_id = cfg.graph.node_data(idx).id();
807 if local_id != hir::DUMMY_ITEM_LOCAL_ID {
808 let node_id = cx.tcx.hir.hir_to_node_id(hir::HirId {
809 owner: body.value.hir_id.owner,
812 let self_recursive = match method {
813 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
814 None => expr_refers_to_this_fn(cx, id, node_id),
817 self_call_spans.push(cx.tcx.hir.span(node_id));
818 // this is a self call, so we shouldn't explore past
819 // this node in the CFG.
824 // add the successors of this node to explore the graph further.
825 for (_, edge) in cfg.graph.outgoing_edges(idx) {
826 let target_idx = edge.target();
827 let target_cfg_id = target_idx.node_id();
828 if !visited.contains(&target_cfg_id) {
829 work_queue.push(target_idx)
834 // Check the number of self calls because a function that
835 // doesn't return (e.g. calls a `-> !` function or `loop { /*
836 // no break */ }`) shouldn't be linted unless it actually
838 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
839 let sp = cx.tcx.sess.codemap().def_span(sp);
840 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
842 "function cannot return without recurring");
843 db.span_label(sp, "cannot return without recurring");
844 // offer some help to the programmer.
845 for call in &self_call_spans {
846 db.span_label(*call, "recursive call site");
848 db.help("a `loop` may express intention better if this is on purpose");
855 // Functions for identifying if the given Expr NodeId `id`
856 // represents a call to the function `fn_id`/method `method`.
858 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
859 match cx.tcx.hir.get(id) {
860 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
861 let def = if let hir::ExprPath(ref qpath) = callee.node {
862 cx.tables.qpath_def(qpath, callee.hir_id)
867 Def::Local(..) | Def::Upvar(..) => false,
868 _ => def.def_id() == cx.tcx.hir.local_def_id(fn_id)
875 // Check if the expression `id` performs a call to `method`.
876 fn expr_refers_to_this_method(cx: &LateContext,
877 method: &ty::AssociatedItem,
880 use rustc::ty::adjustment::*;
882 // Ignore non-expressions.
883 let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
889 // Check for overloaded autoderef method calls.
890 let mut source = cx.tables.expr_ty(expr);
891 for adjustment in cx.tables.expr_adjustments(expr) {
892 if let Adjust::Deref(Some(deref)) = adjustment.kind {
893 let (def_id, substs) = deref.method_call(cx.tcx, source);
894 if method_call_refers_to_method(cx, method, def_id, substs, id) {
898 source = adjustment.target;
901 // Check for method calls and overloaded operators.
902 if cx.tables.is_method_call(expr) {
903 let hir_id = cx.tcx.hir.definitions().node_to_hir_id(id);
904 let def_id = cx.tables.type_dependent_defs()[hir_id].def_id();
905 let substs = cx.tables.node_substs(hir_id);
906 if method_call_refers_to_method(cx, method, def_id, substs, id) {
911 // Check for calls to methods via explicit paths (e.g. `T::method()`).
913 hir::ExprCall(ref callee, _) => {
914 let def = if let hir::ExprPath(ref qpath) = callee.node {
915 cx.tables.qpath_def(qpath, callee.hir_id)
920 Def::Method(def_id) => {
921 let substs = cx.tables.node_substs(callee.hir_id);
922 method_call_refers_to_method(cx, method, def_id, substs, id)
931 // Check if the method call to the method with the ID `callee_id`
932 // and instantiated with `callee_substs` refers to method `method`.
933 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
934 method: &ty::AssociatedItem,
936 callee_substs: &Substs<'tcx>,
937 expr_id: ast::NodeId)
940 let callee_item = tcx.associated_item(callee_id);
942 match callee_item.container {
943 // This is an inherent method, so the `def_id` refers
944 // directly to the method definition.
945 ty::ImplContainer(_) => callee_id == method.def_id,
947 // A trait method, from any number of possible sources.
948 // Attempt to select a concrete impl before checking.
949 ty::TraitContainer(trait_def_id) => {
950 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
951 let trait_ref = ty::Binder(trait_ref);
952 let span = tcx.hir.span(expr_id);
954 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
956 trait_ref.to_poly_trait_predicate());
958 tcx.infer_ctxt().enter(|infcx| {
959 let mut selcx = traits::SelectionContext::new(&infcx);
960 match selcx.select(&obligation) {
961 // The method comes from a `T: Trait` bound.
962 // If `T` is `Self`, then this call is inside
963 // a default method definition.
964 Ok(Some(traits::VtableParam(_))) => {
965 let on_self = trait_ref.self_ty().is_self();
966 // We can only be recurring in a default
967 // method if we're being called literally
968 // on the `Self` type.
969 on_self && callee_id == method.def_id
972 // The `impl` is known, so we check that with a
974 Ok(Some(traits::VtableImpl(vtable_impl))) => {
975 let container = ty::ImplContainer(vtable_impl.impl_def_id);
976 // It matches if it comes from the same impl,
977 // and has the same method name.
978 container == method.container && callee_item.name == method.name
981 // There's no way to know if this call is
982 // recursive, so we assume it's not.
995 "compiler plugin used as ordinary library in non-plugin crate"
998 #[derive(Copy, Clone)]
999 pub struct PluginAsLibrary;
1001 impl LintPass for PluginAsLibrary {
1002 fn get_lints(&self) -> LintArray {
1003 lint_array![PLUGIN_AS_LIBRARY]
1007 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1008 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1009 if cx.sess().plugin_registrar_fn.get().is_some() {
1010 // We're compiling a plugin; it's fine to link other plugins.
1015 hir::ItemExternCrate(..) => (),
1019 let def_id = cx.tcx.hir.local_def_id(it.id);
1020 let prfn = match cx.tcx.extern_mod_stmt_cnum(def_id) {
1021 Some(cnum) => cx.tcx.plugin_registrar_fn(cnum),
1023 // Probably means we aren't linking the crate for some reason.
1025 // Not sure if / when this could happen.
1031 cx.span_lint(PLUGIN_AS_LIBRARY,
1033 "compiler plugin used as an ordinary library");
1039 PRIVATE_NO_MANGLE_FNS,
1041 "functions marked #[no_mangle] should be exported"
1045 PRIVATE_NO_MANGLE_STATICS,
1047 "statics marked #[no_mangle] should be exported"
1051 NO_MANGLE_CONST_ITEMS,
1053 "const items will not have their symbols exported"
1057 NO_MANGLE_GENERIC_ITEMS,
1059 "generic items must be mangled"
1062 #[derive(Copy, Clone)]
1063 pub struct InvalidNoMangleItems;
1065 impl LintPass for InvalidNoMangleItems {
1066 fn get_lints(&self) -> LintArray {
1067 lint_array!(PRIVATE_NO_MANGLE_FNS,
1068 PRIVATE_NO_MANGLE_STATICS,
1069 NO_MANGLE_CONST_ITEMS,
1070 NO_MANGLE_GENERIC_ITEMS)
1074 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1075 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1077 hir::ItemFn(.., ref generics, _) => {
1078 if let Some(no_mangle_attr) = attr::find_by_name(&it.attrs, "no_mangle") {
1079 if attr::contains_name(&it.attrs, "linkage") {
1082 if !cx.access_levels.is_reachable(it.id) {
1083 let msg = "function is marked #[no_mangle], but not exported";
1084 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_FNS, it.span, msg);
1085 let insertion_span = it.span.with_hi(it.span.lo());
1086 if it.vis == hir::Visibility::Inherited {
1087 err.span_suggestion(insertion_span,
1088 "try making it public",
1093 if generics.is_type_parameterized() {
1094 let mut err = cx.struct_span_lint(NO_MANGLE_GENERIC_ITEMS,
1096 "functions generic over \
1097 types must be mangled");
1098 err.span_suggestion_short(no_mangle_attr.span,
1099 "remove this attribute",
1105 hir::ItemStatic(..) => {
1106 if attr::contains_name(&it.attrs, "no_mangle") &&
1107 !cx.access_levels.is_reachable(it.id) {
1108 let msg = "static is marked #[no_mangle], but not exported";
1109 let mut err = cx.struct_span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, msg);
1110 let insertion_span = it.span.with_hi(it.span.lo());
1111 if it.vis == hir::Visibility::Inherited {
1112 err.span_suggestion(insertion_span,
1113 "try making it public",
1119 hir::ItemConst(..) => {
1120 if attr::contains_name(&it.attrs, "no_mangle") {
1121 // Const items do not refer to a particular location in memory, and therefore
1122 // don't have anything to attach a symbol to
1123 let msg = "const items should never be #[no_mangle]";
1124 let mut err = cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1126 // account for "pub const" (#45562)
1127 let start = cx.tcx.sess.codemap().span_to_snippet(it.span)
1128 .map(|snippet| snippet.find("const").unwrap_or(0))
1129 .unwrap_or(0) as u32;
1130 // `const` is 5 chars
1131 let const_span = it.span.with_hi(BytePos(it.span.lo().0 + start + 5));
1132 err.span_suggestion(const_span,
1133 "try a static value",
1134 "pub static".to_owned());
1143 #[derive(Clone, Copy)]
1144 pub struct MutableTransmutes;
1149 "mutating transmuted &mut T from &T may cause undefined behavior"
1152 impl LintPass for MutableTransmutes {
1153 fn get_lints(&self) -> LintArray {
1154 lint_array!(MUTABLE_TRANSMUTES)
1158 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1159 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1160 use syntax::abi::Abi::RustIntrinsic;
1162 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1163 consider instead using an UnsafeCell";
1164 match get_transmute_from_to(cx, expr) {
1165 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1166 if to_mt.mutbl == hir::Mutability::MutMutable &&
1167 from_mt.mutbl == hir::Mutability::MutImmutable {
1168 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1174 fn get_transmute_from_to<'a, 'tcx>
1175 (cx: &LateContext<'a, 'tcx>,
1177 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1178 let def = if let hir::ExprPath(ref qpath) = expr.node {
1179 cx.tables.qpath_def(qpath, expr.hir_id)
1183 if let Def::Fn(did) = def {
1184 if !def_id_is_transmute(cx, did) {
1187 let sig = cx.tables.node_id_to_type(expr.hir_id).fn_sig(cx.tcx);
1188 let from = sig.inputs().skip_binder()[0];
1189 let to = *sig.output().skip_binder();
1190 return Some((&from.sty, &to.sty));
1195 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1196 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1197 cx.tcx.item_name(def_id) == "transmute"
1202 /// Forbids using the `#[feature(...)]` attribute
1203 #[derive(Copy, Clone)]
1204 pub struct UnstableFeatures;
1209 "enabling unstable features (deprecated. do not use)"
1212 impl LintPass for UnstableFeatures {
1213 fn get_lints(&self) -> LintArray {
1214 lint_array!(UNSTABLE_FEATURES)
1218 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1219 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1220 if attr.check_name("feature") {
1221 if let Some(items) = attr.meta_item_list() {
1223 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1230 /// Lint for unions that contain fields with possibly non-trivial destructors.
1231 pub struct UnionsWithDropFields;
1234 UNIONS_WITH_DROP_FIELDS,
1236 "use of unions that contain fields with possibly non-trivial drop code"
1239 impl LintPass for UnionsWithDropFields {
1240 fn get_lints(&self) -> LintArray {
1241 lint_array!(UNIONS_WITH_DROP_FIELDS)
1245 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1246 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1247 if let hir::ItemUnion(ref vdata, _) = item.node {
1248 for field in vdata.fields() {
1249 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1250 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1251 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1253 "union contains a field with possibly non-trivial drop code, \
1254 drop code of union fields is ignored when dropping the union");
1262 /// Lint for items marked `pub` that aren't reachable from other crates
1263 pub struct UnreachablePub;
1266 pub UNREACHABLE_PUB,
1268 "`pub` items not reachable from crate root"
1271 impl LintPass for UnreachablePub {
1272 fn get_lints(&self) -> LintArray {
1273 lint_array!(UNREACHABLE_PUB)
1277 impl UnreachablePub {
1278 fn perform_lint(&self, cx: &LateContext, what: &str, id: ast::NodeId,
1279 vis: &hir::Visibility, span: Span, exportable: bool) {
1280 if !cx.access_levels.is_reachable(id) && *vis == hir::Visibility::Public {
1281 let def_span = cx.tcx.sess.codemap().def_span(span);
1282 let mut err = cx.struct_span_lint(UNREACHABLE_PUB, def_span,
1283 &format!("unreachable `pub` {}", what));
1284 // visibility is token at start of declaration (can be macro
1285 // variable rather than literal `pub`)
1286 let pub_span = cx.tcx.sess.codemap().span_until_char(def_span, ' ');
1287 let replacement = if cx.tcx.features().crate_visibility_modifier {
1292 err.span_suggestion(pub_span, "consider restricting its visibility", replacement);
1294 err.help("or consider exporting it for use by other crates");
1301 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnreachablePub {
1302 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
1303 self.perform_lint(cx, "item", item.id, &item.vis, item.span, true);
1306 fn check_foreign_item(&mut self, cx: &LateContext, foreign_item: &hir::ForeignItem) {
1307 self.perform_lint(cx, "item", foreign_item.id, &foreign_item.vis, foreign_item.span, true);
1310 fn check_struct_field(&mut self, cx: &LateContext, field: &hir::StructField) {
1311 self.perform_lint(cx, "field", field.id, &field.vis, field.span, false);
1314 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
1315 self.perform_lint(cx, "item", impl_item.id, &impl_item.vis, impl_item.span, false);
1319 /// Lint for trait and lifetime bounds that are (accidentally) accepted by the parser, but
1322 pub struct IgnoredGenericBounds;
1325 IGNORED_GENERIC_BOUNDS,
1327 "these generic bounds are ignored"
1330 impl LintPass for IgnoredGenericBounds {
1331 fn get_lints(&self) -> LintArray {
1332 lint_array!(IGNORED_GENERIC_BOUNDS)
1336 impl EarlyLintPass for IgnoredGenericBounds {
1337 fn check_item(&mut self, cx: &EarlyContext, item: &ast::Item) {
1338 let type_alias_generics = match item.node {
1339 ast::ItemKind::Ty(_, ref generics) => generics,
1342 // There must not be a where clause
1343 if !type_alias_generics.where_clause.predicates.is_empty() {
1344 let spans : Vec<_> = type_alias_generics.where_clause.predicates.iter()
1345 .map(|pred| pred.span()).collect();
1346 cx.span_lint(IGNORED_GENERIC_BOUNDS, spans,
1347 "where clauses are ignored in type aliases");
1349 // The parameters must not have bounds
1350 for param in type_alias_generics.params.iter() {
1351 let spans : Vec<_> = match param {
1352 &ast::GenericParam::Lifetime(ref l) => l.bounds.iter().map(|b| b.span).collect(),
1353 &ast::GenericParam::Type(ref ty) => ty.bounds.iter().map(|b| b.span()).collect(),
1355 if !spans.is_empty() {
1357 IGNORED_GENERIC_BOUNDS,
1359 "bounds on generic parameters are ignored in type aliases",