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;
33 use middle::stability;
35 use rustc::ty::subst::Substs;
36 use rustc::ty::{self, Ty, TyCtxt};
37 use rustc::ty::adjustment;
38 use rustc::traits::{self, ProjectionMode};
39 use rustc::hir::map as hir_map;
40 use util::nodemap::{NodeSet};
41 use lint::{Level, LateContext, LintContext, LintArray, Lint};
42 use lint::{LintPass, LateLintPass};
44 use std::collections::HashSet;
47 use syntax::attr::{self, AttrMetaMethods};
48 use syntax::codemap::{self, Span};
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 LateLintPass 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, e.span,
79 "denote infinite loops with loop { ... }");
89 "use of owned (Box type) heap memory"
92 #[derive(Copy, Clone)]
93 pub struct BoxPointers;
96 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext<'a, 'tcx>,
97 span: Span, ty: Ty<'tcx>) {
98 for leaf_ty in ty.walk() {
99 if let ty::TyBox(_) = leaf_ty.sty {
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 LateLintPass for BoxPointers {
114 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
119 hir::ItemStruct(..) =>
120 self.check_heap_type(cx, it.span,
121 cx.tcx.node_id_to_type(it.id)),
125 // If it's a struct, we also have to check the fields' types
127 hir::ItemStruct(ref struct_def, _) => {
128 for struct_field in struct_def.fields() {
129 self.check_heap_type(cx, struct_field.span,
130 cx.tcx.node_id_to_type(struct_field.id));
137 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
138 let ty = cx.tcx.node_id_to_type(e.id);
139 self.check_heap_type(cx, e.span, ty);
144 NON_SHORTHAND_FIELD_PATTERNS,
146 "using `Struct { x: x }` instead of `Struct { x }`"
149 #[derive(Copy, Clone)]
150 pub struct NonShorthandFieldPatterns;
152 impl LintPass for NonShorthandFieldPatterns {
153 fn get_lints(&self) -> LintArray {
154 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
158 impl LateLintPass for NonShorthandFieldPatterns {
159 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
160 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
161 for fieldpat in field_pats {
162 if fieldpat.node.is_shorthand {
165 if let PatKind::Binding(_, ident, None) = fieldpat.node.pat.node {
166 if ident.node.unhygienize() == fieldpat.node.name {
167 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span,
168 &format!("the `{}:` in this pattern is redundant and can \
169 be removed", ident.node))
180 "usage of `unsafe` code"
183 #[derive(Copy, Clone)]
184 pub struct UnsafeCode;
186 impl LintPass for UnsafeCode {
187 fn get_lints(&self) -> LintArray {
188 lint_array!(UNSAFE_CODE)
192 impl LateLintPass for UnsafeCode {
193 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
194 if let hir::ExprBlock(ref blk) = e.node {
195 // Don't warn about generated blocks, that'll just pollute the output.
196 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
197 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
202 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
204 hir::ItemTrait(hir::Unsafety::Unsafe, _, _, _) =>
205 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait"),
207 hir::ItemImpl(hir::Unsafety::Unsafe, _, _, _, _, _) =>
208 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait"),
214 fn check_fn(&mut self, cx: &LateContext, fk: FnKind, _: &hir::FnDecl,
215 _: &hir::Block, span: Span, _: ast::NodeId) {
217 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, _, _, _, _) =>
218 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function"),
220 FnKind::Method(_, sig, _, _) => {
221 if sig.unsafety == hir::Unsafety::Unsafe {
222 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
230 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
231 if let hir::MethodTraitItem(ref sig, None) = trait_item.node {
232 if sig.unsafety == hir::Unsafety::Unsafe {
233 cx.span_lint(UNSAFE_CODE, trait_item.span,
234 "declaration of an `unsafe` method")
243 "detects missing documentation for public members"
246 pub struct MissingDoc {
247 /// Stack of IDs of struct definitions.
248 struct_def_stack: Vec<ast::NodeId>,
250 /// True if inside variant definition
253 /// Stack of whether #[doc(hidden)] is set
254 /// at each level which has lint attributes.
255 doc_hidden_stack: Vec<bool>,
257 /// Private traits or trait items that leaked through. Don't check their methods.
258 private_traits: HashSet<ast::NodeId>,
262 pub fn new() -> MissingDoc {
264 struct_def_stack: vec!(),
266 doc_hidden_stack: vec!(false),
267 private_traits: HashSet::new(),
271 fn doc_hidden(&self) -> bool {
272 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
275 fn check_missing_docs_attrs(&self,
277 id: Option<ast::NodeId>,
278 attrs: &[ast::Attribute],
280 desc: &'static str) {
281 // If we're building a test harness, then warning about
282 // documentation is probably not really relevant right now.
283 if cx.sess().opts.test {
287 // `#[doc(hidden)]` disables missing_docs check.
288 if self.doc_hidden() {
292 // Only check publicly-visible items, using the result from the privacy pass.
293 // It's an option so the crate root can also use this function (it doesn't
295 if let Some(id) = id {
296 if !cx.access_levels.is_exported(id) {
301 let has_doc = attrs.iter().any(|a| {
302 match a.node.value.node {
303 ast::MetaItemKind::NameValue(ref name, _) if *name == "doc" => true,
308 cx.span_lint(MISSING_DOCS, sp,
309 &format!("missing documentation for {}", desc));
314 impl LintPass for MissingDoc {
315 fn get_lints(&self) -> LintArray {
316 lint_array!(MISSING_DOCS)
320 impl LateLintPass for MissingDoc {
321 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
322 let doc_hidden = self.doc_hidden() || attrs.iter().any(|attr| {
323 attr.check_name("doc") && match attr.meta_item_list() {
325 Some(l) => attr::contains_name(&l[..], "hidden"),
328 self.doc_hidden_stack.push(doc_hidden);
331 fn exit_lint_attrs(&mut self, _: &LateContext, _: &[ast::Attribute]) {
332 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
335 fn check_struct_def(&mut self, _: &LateContext, _: &hir::VariantData,
336 _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
337 self.struct_def_stack.push(item_id);
340 fn check_struct_def_post(&mut self, _: &LateContext, _: &hir::VariantData,
341 _: ast::Name, _: &hir::Generics, item_id: ast::NodeId) {
342 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
343 assert!(popped == item_id);
346 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
347 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
350 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
351 let desc = match it.node {
352 hir::ItemFn(..) => "a function",
353 hir::ItemMod(..) => "a module",
354 hir::ItemEnum(..) => "an enum",
355 hir::ItemStruct(..) => "a struct",
356 hir::ItemTrait(_, _, _, ref items) => {
357 // Issue #11592, traits are always considered exported, even when private.
358 if it.vis == hir::Visibility::Inherited {
359 self.private_traits.insert(it.id);
361 self.private_traits.insert(itm.id);
367 hir::ItemTy(..) => "a type alias",
368 hir::ItemImpl(_, _, _, Some(ref trait_ref), _, ref impl_items) => {
369 // If the trait is private, add the impl items to private_traits so they don't get
370 // reported for missing docs.
371 let real_trait = cx.tcx.expect_def(trait_ref.ref_id).def_id();
372 if let Some(node_id) = cx.tcx.map.as_local_node_id(real_trait) {
373 match cx.tcx.map.find(node_id) {
374 Some(hir_map::NodeItem(item)) => if item.vis == hir::Visibility::Inherited {
375 for itm in impl_items {
376 self.private_traits.insert(itm.id);
384 hir::ItemConst(..) => "a constant",
385 hir::ItemStatic(..) => "a static",
389 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
392 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
393 if self.private_traits.contains(&trait_item.id) { return }
395 let desc = match trait_item.node {
396 hir::ConstTraitItem(..) => "an associated constant",
397 hir::MethodTraitItem(..) => "a trait method",
398 hir::TypeTraitItem(..) => "an associated type",
401 self.check_missing_docs_attrs(cx, Some(trait_item.id),
403 trait_item.span, desc);
406 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
407 // If the method is an impl for a trait, don't doc.
408 if method_context(cx, impl_item.id, impl_item.span) == MethodLateContext::TraitImpl {
412 let desc = match impl_item.node {
413 hir::ImplItemKind::Const(..) => "an associated constant",
414 hir::ImplItemKind::Method(..) => "a method",
415 hir::ImplItemKind::Type(_) => "an associated type",
417 self.check_missing_docs_attrs(cx, Some(impl_item.id),
419 impl_item.span, desc);
422 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
423 if !sf.is_positional() {
424 if sf.vis == hir::Public || self.in_variant {
425 let cur_struct_def = *self.struct_def_stack.last()
426 .expect("empty struct_def_stack");
427 self.check_missing_docs_attrs(cx, Some(cur_struct_def),
434 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
435 self.check_missing_docs_attrs(cx, Some(v.node.data.id()),
436 &v.node.attrs, v.span, "a variant");
437 assert!(!self.in_variant);
438 self.in_variant = true;
441 fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
442 assert!(self.in_variant);
443 self.in_variant = false;
448 pub MISSING_COPY_IMPLEMENTATIONS,
450 "detects potentially-forgotten implementations of `Copy`"
453 #[derive(Copy, Clone)]
454 pub struct MissingCopyImplementations;
456 impl LintPass for MissingCopyImplementations {
457 fn get_lints(&self) -> LintArray {
458 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
462 impl LateLintPass for MissingCopyImplementations {
463 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
464 if !cx.access_levels.is_reachable(item.id) {
467 let (def, ty) = match item.node {
468 hir::ItemStruct(_, ref ast_generics) => {
469 if ast_generics.is_parameterized() {
472 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
473 (def, cx.tcx.mk_struct(def,
474 cx.tcx.mk_substs(Substs::empty())))
476 hir::ItemEnum(_, ref ast_generics) => {
477 if ast_generics.is_parameterized() {
480 let def = cx.tcx.lookup_adt_def(cx.tcx.map.local_def_id(item.id));
481 (def, cx.tcx.mk_enum(def,
482 cx.tcx.mk_substs(Substs::empty())))
486 if def.has_dtor() { return; }
487 let parameter_environment = cx.tcx.empty_parameter_environment();
488 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
490 if !ty.moves_by_default(cx.tcx, ¶meter_environment, item.span) {
493 if parameter_environment.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
494 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
496 "type could implement `Copy`; consider adding `impl \
503 MISSING_DEBUG_IMPLEMENTATIONS,
505 "detects missing implementations of fmt::Debug"
508 pub struct MissingDebugImplementations {
509 impling_types: Option<NodeSet>,
512 impl MissingDebugImplementations {
513 pub fn new() -> MissingDebugImplementations {
514 MissingDebugImplementations {
520 impl LintPass for MissingDebugImplementations {
521 fn get_lints(&self) -> LintArray {
522 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
526 impl LateLintPass for MissingDebugImplementations {
527 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
528 if !cx.access_levels.is_reachable(item.id) {
533 hir::ItemStruct(..) | hir::ItemEnum(..) => {},
537 let debug = match cx.tcx.lang_items.debug_trait() {
538 Some(debug) => debug,
542 if self.impling_types.is_none() {
543 let debug_def = cx.tcx.lookup_trait_def(debug);
544 let mut impls = NodeSet();
545 debug_def.for_each_impl(cx.tcx, |d| {
546 if let Some(n) = cx.tcx.map.as_local_node_id(d) {
547 if let Some(ty_def) = cx.tcx.node_id_to_type(n).ty_to_def_id() {
548 if let Some(node_id) = cx.tcx.map.as_local_node_id(ty_def) {
549 impls.insert(node_id);
555 self.impling_types = Some(impls);
556 debug!("{:?}", self.impling_types);
559 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
560 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
562 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
563 or a manual implementation")
571 "detects use of deprecated items"
574 /// Checks for use of items with `#[deprecated]` or `#[rustc_deprecated]` attributes
575 #[derive(Copy, Clone)]
576 pub struct Deprecated;
579 fn lint(&self, cx: &LateContext, _id: DefId, span: Span,
580 stability: &Option<&attr::Stability>, deprecation: &Option<attr::Deprecation>) {
581 // Deprecated attributes apply in-crate and cross-crate.
582 if let Some(&attr::Stability{rustc_depr: Some(attr::RustcDeprecation{ref reason, ..}), ..})
584 output(cx, DEPRECATED, span, Some(&reason))
585 } else if let Some(attr::Deprecation{ref note, ..}) = *deprecation {
586 output(cx, DEPRECATED, span, note.as_ref().map(|x| &**x))
589 fn output(cx: &LateContext, lint: &'static Lint, span: Span, note: Option<&str>) {
590 let msg = if let Some(note) = note {
591 format!("use of deprecated item: {}", note)
593 format!("use of deprecated item")
596 cx.span_lint(lint, span, &msg);
601 impl LintPass for Deprecated {
602 fn get_lints(&self) -> LintArray {
603 lint_array!(DEPRECATED)
607 impl LateLintPass for Deprecated {
608 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
609 stability::check_item(cx.tcx, item, false,
610 &mut |id, sp, stab, depr|
611 self.lint(cx, id, sp, &stab, &depr));
614 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
615 stability::check_expr(cx.tcx, e,
616 &mut |id, sp, stab, depr|
617 self.lint(cx, id, sp, &stab, &depr));
620 fn check_path(&mut self, cx: &LateContext, path: &hir::Path, id: ast::NodeId) {
621 stability::check_path(cx.tcx, path, id,
622 &mut |id, sp, stab, depr|
623 self.lint(cx, id, sp, &stab, &depr));
626 fn check_path_list_item(&mut self, cx: &LateContext, item: &hir::PathListItem) {
627 stability::check_path_list_item(cx.tcx, item,
628 &mut |id, sp, stab, depr|
629 self.lint(cx, id, sp, &stab, &depr));
632 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
633 stability::check_pat(cx.tcx, pat,
634 &mut |id, sp, stab, depr|
635 self.lint(cx, id, sp, &stab, &depr));
640 pub UNCONDITIONAL_RECURSION,
642 "functions that cannot return without calling themselves"
645 #[derive(Copy, Clone)]
646 pub struct UnconditionalRecursion;
649 impl LintPass for UnconditionalRecursion {
650 fn get_lints(&self) -> LintArray {
651 lint_array![UNCONDITIONAL_RECURSION]
655 impl LateLintPass for UnconditionalRecursion {
656 fn check_fn(&mut self, cx: &LateContext, fn_kind: FnKind, _: &hir::FnDecl,
657 blk: &hir::Block, sp: Span, id: ast::NodeId) {
658 let method = match fn_kind {
659 FnKind::ItemFn(..) => None,
660 FnKind::Method(..) => {
661 cx.tcx.impl_or_trait_item(cx.tcx.map.local_def_id(id)).as_opt_method()
663 // closures can't recur, so they don't matter.
664 FnKind::Closure(_) => return
667 // Walk through this function (say `f`) looking to see if
668 // every possible path references itself, i.e. the function is
669 // called recursively unconditionally. This is done by trying
670 // to find a path from the entry node to the exit node that
671 // *doesn't* call `f` by traversing from the entry while
672 // pretending that calls of `f` are sinks (i.e. ignoring any
673 // exit edges from them).
675 // NB. this has an edge case with non-returning statements,
676 // like `loop {}` or `panic!()`: control flow never reaches
677 // the exit node through these, so one can have a function
678 // that never actually calls itselfs but is still picked up by
681 // fn f(cond: bool) {
682 // if !cond { panic!() } // could come from `assert!(cond)`
686 // In general, functions of that form may be able to call
687 // itself a finite number of times and then diverge. The lint
688 // considers this to be an error for two reasons, (a) it is
689 // easier to implement, and (b) it seems rare to actually want
690 // to have behaviour like the above, rather than
691 // e.g. accidentally recurring after an assert.
693 let cfg = cfg::CFG::new(cx.tcx, blk);
695 let mut work_queue = vec![cfg.entry];
696 let mut reached_exit_without_self_call = false;
697 let mut self_call_spans = vec![];
698 let mut visited = HashSet::new();
700 while let Some(idx) = work_queue.pop() {
703 reached_exit_without_self_call = true;
707 let cfg_id = idx.node_id();
708 if visited.contains(&cfg_id) {
712 visited.insert(cfg_id);
714 let node_id = cfg.graph.node_data(idx).id();
716 // is this a recursive call?
717 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
719 Some(ref method) => {
720 expr_refers_to_this_method(cx.tcx, method, node_id)
722 None => expr_refers_to_this_fn(cx.tcx, id, node_id)
728 self_call_spans.push(cx.tcx.map.span(node_id));
729 // this is a self call, so we shouldn't explore past
730 // this node in the CFG.
733 // add the successors of this node to explore the graph further.
734 for (_, edge) in cfg.graph.outgoing_edges(idx) {
735 let target_idx = edge.target();
736 let target_cfg_id = target_idx.node_id();
737 if !visited.contains(&target_cfg_id) {
738 work_queue.push(target_idx)
743 // Check the number of self calls because a function that
744 // doesn't return (e.g. calls a `-> !` function or `loop { /*
745 // no break */ }`) shouldn't be linted unless it actually
747 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
748 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION, sp,
749 "function cannot return without recurring");
751 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
752 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
753 // offer some help to the programmer.
754 for call in &self_call_spans {
755 db.span_note(*call, "recursive call site");
757 db.help("a `loop` may express intention \
758 better if this is on purpose");
766 // Functions for identifying if the given Expr NodeId `id`
767 // represents a call to the function `fn_id`/method `method`.
769 fn expr_refers_to_this_fn(tcx: TyCtxt,
771 id: ast::NodeId) -> bool {
772 match tcx.map.get(id) {
773 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
774 tcx.expect_def_or_none(callee.id).map_or(false, |def| {
775 def.def_id() == tcx.map.local_def_id(fn_id)
782 // Check if the expression `id` performs a call to `method`.
783 fn expr_refers_to_this_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
785 id: ast::NodeId) -> bool {
786 // Check for method calls and overloaded operators.
787 let opt_m = tcx.tables.borrow().method_map.get(&ty::MethodCall::expr(id)).cloned();
788 if let Some(m) = opt_m {
789 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
794 // Check for overloaded autoderef method calls.
795 let opt_adj = tcx.tables.borrow().adjustments.get(&id).cloned();
796 if let Some(adjustment::AdjustDerefRef(adj)) = opt_adj {
797 for i in 0..adj.autoderefs {
798 let method_call = ty::MethodCall::autoderef(id, i as u32);
799 if let Some(m) = tcx.tables.borrow().method_map
802 if method_call_refers_to_method(tcx, method, m.def_id, m.substs, id) {
809 // Check for calls to methods via explicit paths (e.g. `T::method()`).
810 match tcx.map.get(id) {
811 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
812 // The callee is an arbitrary expression,
813 // it doesn't necessarily have a definition.
814 match tcx.expect_def_or_none(callee.id) {
815 Some(Def::Method(def_id)) => {
816 let item_substs = tcx.node_id_item_substs(callee.id);
817 method_call_refers_to_method(
818 tcx, method, def_id, &item_substs.substs, id)
827 // Check if the method call to the method with the ID `callee_id`
828 // and instantiated with `callee_substs` refers to method `method`.
829 fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
832 callee_substs: &Substs<'tcx>,
833 expr_id: ast::NodeId) -> bool {
834 let callee_item = tcx.impl_or_trait_item(callee_id);
836 match callee_item.container() {
837 // This is an inherent method, so the `def_id` refers
838 // directly to the method definition.
839 ty::ImplContainer(_) => {
840 callee_id == method.def_id
843 // A trait method, from any number of possible sources.
844 // Attempt to select a concrete impl before checking.
845 ty::TraitContainer(trait_def_id) => {
846 let trait_ref = callee_substs.to_trait_ref(tcx, trait_def_id);
847 let trait_ref = ty::Binder(trait_ref);
848 let span = tcx.map.span(expr_id);
850 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
851 trait_ref.to_poly_trait_predicate());
853 // unwrap() is ok here b/c `method` is the method
854 // defined in this crate whose body we are
855 // checking, so it's always local
856 let node_id = tcx.map.as_local_node_id(method.def_id).unwrap();
858 let param_env = Some(ty::ParameterEnvironment::for_item(tcx, node_id));
859 tcx.infer_ctxt(None, param_env, ProjectionMode::AnyFinal).enter(|infcx| {
860 let mut selcx = traits::SelectionContext::new(&infcx);
861 match selcx.select(&obligation) {
862 // The method comes from a `T: Trait` bound.
863 // If `T` is `Self`, then this call is inside
864 // a default method definition.
865 Ok(Some(traits::VtableParam(_))) => {
866 let self_ty = callee_substs.self_ty();
867 let on_self = self_ty.map_or(false, |t| t.is_self());
868 // We can only be recurring in a default
869 // method if we're being called literally
870 // on the `Self` type.
871 on_self && callee_id == method.def_id
874 // The `impl` is known, so we check that with a
876 Ok(Some(traits::VtableImpl(vtable_impl))) => {
877 let container = ty::ImplContainer(vtable_impl.impl_def_id);
878 // It matches if it comes from the same impl,
879 // and has the same method name.
880 container == method.container
881 && callee_item.name() == method.name
884 // There's no way to know if this call is
885 // recursive, so we assume it's not.
898 "compiler plugin used as ordinary library in non-plugin crate"
901 #[derive(Copy, Clone)]
902 pub struct PluginAsLibrary;
904 impl LintPass for PluginAsLibrary {
905 fn get_lints(&self) -> LintArray {
906 lint_array![PLUGIN_AS_LIBRARY]
910 impl LateLintPass for PluginAsLibrary {
911 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
912 if cx.sess().plugin_registrar_fn.get().is_some() {
913 // We're compiling a plugin; it's fine to link other plugins.
918 hir::ItemExternCrate(..) => (),
922 let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
923 Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
925 // Probably means we aren't linking the crate for some reason.
927 // Not sure if / when this could happen.
933 cx.span_lint(PLUGIN_AS_LIBRARY, it.span,
934 "compiler plugin used as an ordinary library");
940 PRIVATE_NO_MANGLE_FNS,
942 "functions marked #[no_mangle] should be exported"
946 PRIVATE_NO_MANGLE_STATICS,
948 "statics marked #[no_mangle] should be exported"
952 NO_MANGLE_CONST_ITEMS,
954 "const items will not have their symbols exported"
958 NO_MANGLE_GENERIC_ITEMS,
960 "generic items must be mangled"
963 #[derive(Copy, Clone)]
964 pub struct InvalidNoMangleItems;
966 impl LintPass for InvalidNoMangleItems {
967 fn get_lints(&self) -> LintArray {
968 lint_array!(PRIVATE_NO_MANGLE_FNS,
969 PRIVATE_NO_MANGLE_STATICS,
970 NO_MANGLE_CONST_ITEMS,
971 NO_MANGLE_GENERIC_ITEMS)
975 impl LateLintPass for InvalidNoMangleItems {
976 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
978 hir::ItemFn(_, _, _, _, ref generics, _) => {
979 if attr::contains_name(&it.attrs, "no_mangle") {
980 if !cx.access_levels.is_reachable(it.id) {
981 let msg = format!("function {} is marked #[no_mangle], but not exported",
983 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
985 if generics.is_parameterized() {
986 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
988 "generic functions must be mangled");
992 hir::ItemStatic(..) => {
993 if attr::contains_name(&it.attrs, "no_mangle") &&
994 !cx.access_levels.is_reachable(it.id) {
995 let msg = format!("static {} is marked #[no_mangle], but not exported",
997 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1000 hir::ItemConst(..) => {
1001 if attr::contains_name(&it.attrs, "no_mangle") {
1002 // Const items do not refer to a particular location in memory, and therefore
1003 // don't have anything to attach a symbol to
1004 let msg = "const items should never be #[no_mangle], consider instead using \
1006 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1014 #[derive(Clone, Copy)]
1015 pub struct MutableTransmutes;
1020 "mutating transmuted &mut T from &T may cause undefined behavior"
1023 impl LintPass for MutableTransmutes {
1024 fn get_lints(&self) -> LintArray {
1025 lint_array!(MUTABLE_TRANSMUTES)
1029 impl LateLintPass for MutableTransmutes {
1030 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1031 use syntax::abi::Abi::RustIntrinsic;
1033 let msg = "mutating transmuted &mut T from &T may cause undefined behavior,\
1034 consider instead using an UnsafeCell";
1035 match get_transmute_from_to(cx, expr) {
1036 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1037 if to_mt.mutbl == hir::Mutability::MutMutable
1038 && from_mt.mutbl == hir::Mutability::MutImmutable {
1039 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1045 fn get_transmute_from_to<'a, 'tcx>(cx: &LateContext<'a, 'tcx>, expr: &hir::Expr)
1046 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1048 hir::ExprPath(..) => (),
1051 if let Def::Fn(did) = cx.tcx.expect_def(expr.id) {
1052 if !def_id_is_transmute(cx, did) {
1055 let typ = cx.tcx.node_id_to_type(expr.id);
1057 ty::TyFnDef(_, _, ref bare_fn) if bare_fn.abi == RustIntrinsic => {
1058 if let ty::FnConverging(to) = bare_fn.sig.0.output {
1059 let from = bare_fn.sig.0.inputs[0];
1060 return Some((&from.sty, &to.sty));
1069 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1070 match cx.tcx.lookup_item_type(def_id).ty.sty {
1071 ty::TyFnDef(_, _, ref bfty) if bfty.abi == RustIntrinsic => (),
1074 cx.tcx.item_name(def_id).as_str() == "transmute"
1079 /// Forbids using the `#[feature(...)]` attribute
1080 #[derive(Copy, Clone)]
1081 pub struct UnstableFeatures;
1086 "enabling unstable features (deprecated. do not use)"
1089 impl LintPass for UnstableFeatures {
1090 fn get_lints(&self) -> LintArray {
1091 lint_array!(UNSTABLE_FEATURES)
1095 impl LateLintPass for UnstableFeatures {
1096 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1097 if attr::contains_name(&[attr.node.value.clone()], "feature") {
1098 if let Some(items) = attr.node.value.meta_item_list() {
1100 ctx.span_lint(UNSTABLE_FEATURES, item.span, "unstable feature");
1107 /// Lints for attempts to impl Drop on types that have `#[repr(C)]`
1108 /// attribute (see issue #24585).
1109 #[derive(Copy, Clone)]
1110 pub struct DropWithReprExtern;
1113 DROP_WITH_REPR_EXTERN,
1115 "use of #[repr(C)] on a type that implements Drop"
1118 impl LintPass for DropWithReprExtern {
1119 fn get_lints(&self) -> LintArray {
1120 lint_array!(DROP_WITH_REPR_EXTERN)
1124 impl LateLintPass for DropWithReprExtern {
1125 fn check_crate(&mut self, ctx: &LateContext, _: &hir::Crate) {
1126 let drop_trait = match ctx.tcx.lang_items.drop_trait() {
1127 Some(id) => ctx.tcx.lookup_trait_def(id), None => { return }
1129 drop_trait.for_each_impl(ctx.tcx, |drop_impl_did| {
1130 if !drop_impl_did.is_local() {
1133 let dtor_self_type = ctx.tcx.lookup_item_type(drop_impl_did).ty;
1135 match dtor_self_type.sty {
1136 ty::TyEnum(self_type_def, _) |
1137 ty::TyStruct(self_type_def, _) => {
1138 let self_type_did = self_type_def.did;
1139 let hints = ctx.tcx.lookup_repr_hints(self_type_did);
1140 if hints.iter().any(|attr| *attr == attr::ReprExtern) &&
1141 self_type_def.dtor_kind().has_drop_flag() {
1142 let drop_impl_span = ctx.tcx.map.def_id_span(drop_impl_did,
1144 let self_defn_span = ctx.tcx.map.def_id_span(self_type_did,
1146 ctx.span_lint_note(DROP_WITH_REPR_EXTERN,
1148 "implementing Drop adds hidden state to types, \
1149 possibly conflicting with `#[repr(C)]`",
1151 "the `#[repr(C)]` attribute is attached here");