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};
49 use rustc::hir::{self, PatKind};
50 use rustc::hir::intravisit::FnKind;
52 use bad_style::{MethodLateContext, method_context};
54 // hardwired lints from librustc
55 pub use lint::builtin::*;
60 "suggest using `loop { }` instead of `while true { }`"
63 #[derive(Copy, Clone)]
66 impl LintPass for WhileTrue {
67 fn get_lints(&self) -> LintArray {
68 lint_array!(WHILE_TRUE)
72 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
73 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
74 if let hir::ExprWhile(ref cond, ..) = e.node {
75 if let hir::ExprLit(ref lit) = cond.node {
76 if let ast::LitKind::Bool(true) = lit.node {
77 cx.span_lint(WHILE_TRUE,
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, span: Span, ty: Ty) {
97 for leaf_ty in ty.walk() {
99 let m = format!("type uses owned (Box type) pointers: {}", ty);
100 cx.span_lint(BOX_POINTERS, span, &m);
106 impl LintPass for BoxPointers {
107 fn get_lints(&self) -> LintArray {
108 lint_array!(BOX_POINTERS)
112 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
113 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
118 hir::ItemStruct(..) |
119 hir::ItemUnion(..) => {
120 let def_id = cx.tcx.hir.local_def_id(it.id);
121 self.check_heap_type(cx, it.span, cx.tcx.item_type(def_id))
126 // If it's a struct, we also have to check the fields' types
128 hir::ItemStruct(ref struct_def, _) |
129 hir::ItemUnion(ref struct_def, _) => {
130 for struct_field in struct_def.fields() {
131 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
132 self.check_heap_type(cx, struct_field.span,
133 cx.tcx.item_type(def_id));
140 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
141 let ty = cx.tables.node_id_to_type(e.id);
142 self.check_heap_type(cx, e.span, ty);
147 NON_SHORTHAND_FIELD_PATTERNS,
149 "using `Struct { x: x }` instead of `Struct { x }`"
152 #[derive(Copy, Clone)]
153 pub struct NonShorthandFieldPatterns;
155 impl LintPass for NonShorthandFieldPatterns {
156 fn get_lints(&self) -> LintArray {
157 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
161 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
162 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
163 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
164 for fieldpat in field_pats {
165 if fieldpat.node.is_shorthand {
168 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
169 if ident.node == fieldpat.node.name {
170 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
172 &format!("the `{}:` in this pattern is redundant and can \
185 "usage of `unsafe` code"
188 #[derive(Copy, Clone)]
189 pub struct UnsafeCode;
191 impl LintPass for UnsafeCode {
192 fn get_lints(&self) -> LintArray {
193 lint_array!(UNSAFE_CODE)
197 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
198 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
199 if let hir::ExprBlock(ref blk) = e.node {
200 // Don't warn about generated blocks, that'll just pollute the output.
201 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
202 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
207 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
209 hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
210 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait")
213 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
214 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait")
221 fn check_fn(&mut self,
229 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
230 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function")
233 FnKind::Method(_, sig, ..) => {
234 if sig.unsafety == hir::Unsafety::Unsafe {
235 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
243 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
244 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
245 if sig.unsafety == hir::Unsafety::Unsafe {
246 cx.span_lint(UNSAFE_CODE,
248 "declaration of an `unsafe` method")
257 "detects missing documentation for public members"
260 pub struct MissingDoc {
261 /// Stack of IDs of struct definitions.
262 struct_def_stack: Vec<ast::NodeId>,
264 /// True if inside variant definition
267 /// Stack of whether #[doc(hidden)] is set
268 /// at each level which has lint attributes.
269 doc_hidden_stack: Vec<bool>,
271 /// Private traits or trait items that leaked through. Don't check their methods.
272 private_traits: HashSet<ast::NodeId>,
276 pub fn new() -> MissingDoc {
278 struct_def_stack: vec![],
280 doc_hidden_stack: vec![false],
281 private_traits: HashSet::new(),
285 fn doc_hidden(&self) -> bool {
286 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
289 fn check_missing_docs_attrs(&self,
291 id: Option<ast::NodeId>,
292 attrs: &[ast::Attribute],
294 desc: &'static str) {
295 // If we're building a test harness, then warning about
296 // documentation is probably not really relevant right now.
297 if cx.sess().opts.test {
301 // `#[doc(hidden)]` disables missing_docs check.
302 if self.doc_hidden() {
306 // Only check publicly-visible items, using the result from the privacy pass.
307 // It's an option so the crate root can also use this function (it doesn't
309 if let Some(id) = id {
310 if !cx.access_levels.is_exported(id) {
315 let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
317 cx.span_lint(MISSING_DOCS,
319 &format!("missing documentation for {}", desc));
324 impl LintPass for MissingDoc {
325 fn get_lints(&self) -> LintArray {
326 lint_array!(MISSING_DOCS)
330 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
331 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
332 let doc_hidden = self.doc_hidden() ||
333 attrs.iter().any(|attr| {
334 attr.check_name("doc") &&
335 match attr.meta_item_list() {
337 Some(l) => attr::list_contains_name(&l, "hidden"),
340 self.doc_hidden_stack.push(doc_hidden);
343 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
344 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
347 fn check_struct_def(&mut self,
349 _: &hir::VariantData,
352 item_id: ast::NodeId) {
353 self.struct_def_stack.push(item_id);
356 fn check_struct_def_post(&mut self,
358 _: &hir::VariantData,
361 item_id: ast::NodeId) {
362 let popped = self.struct_def_stack.pop().expect("empty struct_def_stack");
363 assert!(popped == item_id);
366 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
367 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
370 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
371 let desc = match it.node {
372 hir::ItemFn(..) => "a function",
373 hir::ItemMod(..) => "a module",
374 hir::ItemEnum(..) => "an enum",
375 hir::ItemStruct(..) => "a struct",
376 hir::ItemUnion(..) => "a union",
377 hir::ItemTrait(.., ref trait_item_refs) => {
378 // Issue #11592, traits are always considered exported, even when private.
379 if it.vis == hir::Visibility::Inherited {
380 self.private_traits.insert(it.id);
381 for trait_item_ref in trait_item_refs {
382 self.private_traits.insert(trait_item_ref.id.node_id);
388 hir::ItemTy(..) => "a type alias",
389 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
390 // If the trait is private, add the impl items to private_traits so they don't get
391 // reported for missing docs.
392 let real_trait = trait_ref.path.def.def_id();
393 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
394 match cx.tcx.hir.find(node_id) {
395 Some(hir_map::NodeItem(item)) => {
396 if item.vis == hir::Visibility::Inherited {
397 for impl_item_ref in impl_item_refs {
398 self.private_traits.insert(impl_item_ref.id.node_id);
407 hir::ItemConst(..) => "a constant",
408 hir::ItemStatic(..) => "a static",
412 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
415 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
416 if self.private_traits.contains(&trait_item.id) {
420 let desc = match trait_item.node {
421 hir::TraitItemKind::Const(..) => "an associated constant",
422 hir::TraitItemKind::Method(..) => "a trait method",
423 hir::TraitItemKind::Type(..) => "an associated type",
426 self.check_missing_docs_attrs(cx,
433 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
434 // If the method is an impl for a trait, don't doc.
435 if method_context(cx, impl_item.id, impl_item.span) == MethodLateContext::TraitImpl {
439 let desc = match impl_item.node {
440 hir::ImplItemKind::Const(..) => "an associated constant",
441 hir::ImplItemKind::Method(..) => "a method",
442 hir::ImplItemKind::Type(_) => "an associated type",
444 self.check_missing_docs_attrs(cx,
451 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
452 if !sf.is_positional() {
453 if sf.vis == hir::Public || self.in_variant {
454 let cur_struct_def = *self.struct_def_stack
456 .expect("empty struct_def_stack");
457 self.check_missing_docs_attrs(cx,
458 Some(cur_struct_def),
466 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
467 self.check_missing_docs_attrs(cx,
468 Some(v.node.data.id()),
472 assert!(!self.in_variant);
473 self.in_variant = true;
476 fn check_variant_post(&mut self, _: &LateContext, _: &hir::Variant, _: &hir::Generics) {
477 assert!(self.in_variant);
478 self.in_variant = false;
483 pub MISSING_COPY_IMPLEMENTATIONS,
485 "detects potentially-forgotten implementations of `Copy`"
488 #[derive(Copy, Clone)]
489 pub struct MissingCopyImplementations;
491 impl LintPass for MissingCopyImplementations {
492 fn get_lints(&self) -> LintArray {
493 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
497 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
498 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
499 if !cx.access_levels.is_reachable(item.id) {
502 let (def, ty) = match item.node {
503 hir::ItemStruct(_, ref ast_generics) => {
504 if ast_generics.is_parameterized() {
507 let def = cx.tcx.lookup_adt_def(cx.tcx.hir.local_def_id(item.id));
508 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
510 hir::ItemUnion(_, ref ast_generics) => {
511 if ast_generics.is_parameterized() {
514 let def = cx.tcx.lookup_adt_def(cx.tcx.hir.local_def_id(item.id));
515 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
517 hir::ItemEnum(_, ref ast_generics) => {
518 if ast_generics.is_parameterized() {
521 let def = cx.tcx.lookup_adt_def(cx.tcx.hir.local_def_id(item.id));
522 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
526 if def.has_dtor(cx.tcx) {
529 let parameter_environment = cx.tcx.empty_parameter_environment();
530 // FIXME (@jroesch) should probably inver this so that the parameter env still impls this
532 if !ty.moves_by_default(cx.tcx, ¶meter_environment, item.span) {
535 if parameter_environment.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
536 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
538 "type could implement `Copy`; consider adding `impl \
545 MISSING_DEBUG_IMPLEMENTATIONS,
547 "detects missing implementations of fmt::Debug"
550 pub struct MissingDebugImplementations {
551 impling_types: Option<NodeSet>,
554 impl MissingDebugImplementations {
555 pub fn new() -> MissingDebugImplementations {
556 MissingDebugImplementations { impling_types: None }
560 impl LintPass for MissingDebugImplementations {
561 fn get_lints(&self) -> LintArray {
562 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
566 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDebugImplementations {
567 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
568 if !cx.access_levels.is_reachable(item.id) {
573 hir::ItemStruct(..) |
575 hir::ItemEnum(..) => {}
579 let debug = match cx.tcx.lang_items.debug_trait() {
580 Some(debug) => debug,
584 if self.impling_types.is_none() {
585 let debug_def = cx.tcx.lookup_trait_def(debug);
586 let mut impls = NodeSet();
587 debug_def.for_each_impl(cx.tcx, |d| {
588 if let Some(ty_def) = cx.tcx.item_type(d).ty_to_def_id() {
589 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
590 impls.insert(node_id);
595 self.impling_types = Some(impls);
596 debug!("{:?}", self.impling_types);
599 if !self.impling_types.as_ref().unwrap().contains(&item.id) {
600 cx.span_lint(MISSING_DEBUG_IMPLEMENTATIONS,
602 "type does not implement `fmt::Debug`; consider adding #[derive(Debug)] \
603 or a manual implementation")
611 "detects use of deprecated attributes"
614 /// Checks for use of attributes which have been deprecated.
616 pub struct DeprecatedAttr {
617 // This is not free to compute, so we want to keep it around, rather than
618 // compute it for every attribute.
619 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
622 impl DeprecatedAttr {
623 pub fn new() -> DeprecatedAttr {
625 depr_attrs: deprecated_attributes(),
630 impl LintPass for DeprecatedAttr {
631 fn get_lints(&self) -> LintArray {
632 lint_array!(DEPRECATED_ATTR)
636 impl EarlyLintPass for DeprecatedAttr {
637 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
638 let name = unwrap_or!(attr.name(), return);
639 for &&(n, _, ref g) in &self.depr_attrs {
641 if let &AttributeGate::Gated(Stability::Deprecated(link),
645 cx.span_lint(DEPRECATED,
647 &format!("use of deprecated attribute `{}`: {}. See {}",
648 name, reason, link));
657 pub UNCONDITIONAL_RECURSION,
659 "functions that cannot return without calling themselves"
662 #[derive(Copy, Clone)]
663 pub struct UnconditionalRecursion;
666 impl LintPass for UnconditionalRecursion {
667 fn get_lints(&self) -> LintArray {
668 lint_array![UNCONDITIONAL_RECURSION]
672 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnconditionalRecursion {
673 fn check_fn(&mut self,
680 let method = match fn_kind {
681 FnKind::ItemFn(..) => None,
682 FnKind::Method(..) => {
683 Some(cx.tcx.associated_item(cx.tcx.hir.local_def_id(id)))
685 // closures can't recur, so they don't matter.
686 FnKind::Closure(_) => return,
689 // Walk through this function (say `f`) looking to see if
690 // every possible path references itself, i.e. the function is
691 // called recursively unconditionally. This is done by trying
692 // to find a path from the entry node to the exit node that
693 // *doesn't* call `f` by traversing from the entry while
694 // pretending that calls of `f` are sinks (i.e. ignoring any
695 // exit edges from them).
697 // NB. this has an edge case with non-returning statements,
698 // like `loop {}` or `panic!()`: control flow never reaches
699 // the exit node through these, so one can have a function
700 // that never actually calls itselfs but is still picked up by
703 // fn f(cond: bool) {
704 // if !cond { panic!() } // could come from `assert!(cond)`
708 // In general, functions of that form may be able to call
709 // itself a finite number of times and then diverge. The lint
710 // considers this to be an error for two reasons, (a) it is
711 // easier to implement, and (b) it seems rare to actually want
712 // to have behaviour like the above, rather than
713 // e.g. accidentally recurring after an assert.
715 let cfg = cfg::CFG::new(cx.tcx, &body);
717 let mut work_queue = vec![cfg.entry];
718 let mut reached_exit_without_self_call = false;
719 let mut self_call_spans = vec![];
720 let mut visited = HashSet::new();
722 while let Some(idx) = work_queue.pop() {
725 reached_exit_without_self_call = true;
729 let cfg_id = idx.node_id();
730 if visited.contains(&cfg_id) {
734 visited.insert(cfg_id);
736 let node_id = cfg.graph.node_data(idx).id();
738 // is this a recursive call?
739 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
741 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
742 None => expr_refers_to_this_fn(cx, id, node_id),
748 self_call_spans.push(cx.tcx.hir.span(node_id));
749 // this is a self call, so we shouldn't explore past
750 // this node in the CFG.
753 // add the successors of this node to explore the graph further.
754 for (_, edge) in cfg.graph.outgoing_edges(idx) {
755 let target_idx = edge.target();
756 let target_cfg_id = target_idx.node_id();
757 if !visited.contains(&target_cfg_id) {
758 work_queue.push(target_idx)
763 // Check the number of self calls because a function that
764 // doesn't return (e.g. calls a `-> !` function or `loop { /*
765 // no break */ }`) shouldn't be linted unless it actually
767 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
768 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
770 "function cannot return without recurring");
772 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
773 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
774 // offer some help to the programmer.
775 for call in &self_call_spans {
776 db.span_note(*call, "recursive call site");
778 db.help("a `loop` may express intention \
779 better if this is on purpose");
787 // Functions for identifying if the given Expr NodeId `id`
788 // represents a call to the function `fn_id`/method `method`.
790 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
791 match cx.tcx.hir.get(id) {
792 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
793 let def = if let hir::ExprPath(ref qpath) = callee.node {
794 cx.tables.qpath_def(qpath, callee.id)
798 def.def_id() == cx.tcx.hir.local_def_id(fn_id)
804 // Check if the expression `id` performs a call to `method`.
805 fn expr_refers_to_this_method(cx: &LateContext,
806 method: &ty::AssociatedItem,
809 use rustc::ty::adjustment::*;
811 // Check for method calls and overloaded operators.
812 let opt_m = cx.tables.method_map.get(&ty::MethodCall::expr(id)).cloned();
813 if let Some(m) = opt_m {
814 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
819 // Check for overloaded autoderef method calls.
820 let opt_adj = cx.tables.adjustments.get(&id).cloned();
821 if let Some(Adjustment { kind: Adjust::DerefRef { autoderefs, .. }, .. }) = opt_adj {
822 for i in 0..autoderefs {
823 let method_call = ty::MethodCall::autoderef(id, i as u32);
824 if let Some(m) = cx.tables.method_map.get(&method_call).cloned() {
825 if method_call_refers_to_method(cx.tcx, method, m.def_id, m.substs, id) {
832 // Check for calls to methods via explicit paths (e.g. `T::method()`).
833 match cx.tcx.hir.get(id) {
834 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
835 let def = if let hir::ExprPath(ref qpath) = callee.node {
836 cx.tables.qpath_def(qpath, callee.id)
841 Def::Method(def_id) => {
842 let substs = cx.tables.node_id_item_substs(callee.id)
843 .unwrap_or_else(|| cx.tcx.intern_substs(&[]));
844 method_call_refers_to_method(
845 cx.tcx, method, def_id, substs, id)
854 // Check if the method call to the method with the ID `callee_id`
855 // and instantiated with `callee_substs` refers to method `method`.
856 fn method_call_refers_to_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
857 method: &ty::AssociatedItem,
859 callee_substs: &Substs<'tcx>,
860 expr_id: ast::NodeId)
862 let callee_item = tcx.associated_item(callee_id);
864 match callee_item.container {
865 // This is an inherent method, so the `def_id` refers
866 // directly to the method definition.
867 ty::ImplContainer(_) => callee_id == method.def_id,
869 // A trait method, from any number of possible sources.
870 // Attempt to select a concrete impl before checking.
871 ty::TraitContainer(trait_def_id) => {
872 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
873 let trait_ref = ty::Binder(trait_ref);
874 let span = tcx.hir.span(expr_id);
876 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
877 trait_ref.to_poly_trait_predicate());
879 // unwrap() is ok here b/c `method` is the method
880 // defined in this crate whose body we are
881 // checking, so it's always local
882 let node_id = tcx.hir.as_local_node_id(method.def_id).unwrap();
884 let param_env = ty::ParameterEnvironment::for_item(tcx, node_id);
885 tcx.infer_ctxt(param_env, Reveal::UserFacing).enter(|infcx| {
886 let mut selcx = traits::SelectionContext::new(&infcx);
887 match selcx.select(&obligation) {
888 // The method comes from a `T: Trait` bound.
889 // If `T` is `Self`, then this call is inside
890 // a default method definition.
891 Ok(Some(traits::VtableParam(_))) => {
892 let on_self = trait_ref.self_ty().is_self();
893 // We can only be recurring in a default
894 // method if we're being called literally
895 // on the `Self` type.
896 on_self && callee_id == method.def_id
899 // The `impl` is known, so we check that with a
901 Ok(Some(traits::VtableImpl(vtable_impl))) => {
902 let container = ty::ImplContainer(vtable_impl.impl_def_id);
903 // It matches if it comes from the same impl,
904 // and has the same method name.
905 container == method.container && callee_item.name == method.name
908 // There's no way to know if this call is
909 // recursive, so we assume it's not.
922 "compiler plugin used as ordinary library in non-plugin crate"
925 #[derive(Copy, Clone)]
926 pub struct PluginAsLibrary;
928 impl LintPass for PluginAsLibrary {
929 fn get_lints(&self) -> LintArray {
930 lint_array![PLUGIN_AS_LIBRARY]
934 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
935 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
936 if cx.sess().plugin_registrar_fn.get().is_some() {
937 // We're compiling a plugin; it's fine to link other plugins.
942 hir::ItemExternCrate(..) => (),
946 let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
947 Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
949 // Probably means we aren't linking the crate for some reason.
951 // Not sure if / when this could happen.
957 cx.span_lint(PLUGIN_AS_LIBRARY,
959 "compiler plugin used as an ordinary library");
965 PRIVATE_NO_MANGLE_FNS,
967 "functions marked #[no_mangle] should be exported"
971 PRIVATE_NO_MANGLE_STATICS,
973 "statics marked #[no_mangle] should be exported"
977 NO_MANGLE_CONST_ITEMS,
979 "const items will not have their symbols exported"
983 NO_MANGLE_GENERIC_ITEMS,
985 "generic items must be mangled"
988 #[derive(Copy, Clone)]
989 pub struct InvalidNoMangleItems;
991 impl LintPass for InvalidNoMangleItems {
992 fn get_lints(&self) -> LintArray {
993 lint_array!(PRIVATE_NO_MANGLE_FNS,
994 PRIVATE_NO_MANGLE_STATICS,
995 NO_MANGLE_CONST_ITEMS,
996 NO_MANGLE_GENERIC_ITEMS)
1000 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1001 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1003 hir::ItemFn(.., ref generics, _) => {
1004 if attr::contains_name(&it.attrs, "no_mangle") {
1005 if !cx.access_levels.is_reachable(it.id) {
1006 let msg = format!("function {} is marked #[no_mangle], but not exported",
1008 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1010 if generics.is_parameterized() {
1011 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1013 "generic functions must be mangled");
1017 hir::ItemStatic(..) => {
1018 if attr::contains_name(&it.attrs, "no_mangle") &&
1019 !cx.access_levels.is_reachable(it.id) {
1020 let msg = format!("static {} is marked #[no_mangle], but not exported",
1022 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1025 hir::ItemConst(..) => {
1026 if attr::contains_name(&it.attrs, "no_mangle") {
1027 // Const items do not refer to a particular location in memory, and therefore
1028 // don't have anything to attach a symbol to
1029 let msg = "const items should never be #[no_mangle], consider instead using \
1031 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1039 #[derive(Clone, Copy)]
1040 pub struct MutableTransmutes;
1045 "mutating transmuted &mut T from &T may cause undefined behavior"
1048 impl LintPass for MutableTransmutes {
1049 fn get_lints(&self) -> LintArray {
1050 lint_array!(MUTABLE_TRANSMUTES)
1054 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1055 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1056 use syntax::abi::Abi::RustIntrinsic;
1058 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1059 consider instead using an UnsafeCell";
1060 match get_transmute_from_to(cx, expr) {
1061 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1062 if to_mt.mutbl == hir::Mutability::MutMutable &&
1063 from_mt.mutbl == hir::Mutability::MutImmutable {
1064 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1070 fn get_transmute_from_to<'a, 'tcx>
1071 (cx: &LateContext<'a, 'tcx>,
1073 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1074 let def = if let hir::ExprPath(ref qpath) = expr.node {
1075 cx.tables.qpath_def(qpath, expr.id)
1079 if let Def::Fn(did) = def {
1080 if !def_id_is_transmute(cx, did) {
1083 let typ = cx.tables.node_id_to_type(expr.id);
1085 ty::TyFnDef(.., bare_fn) if bare_fn.abi() == RustIntrinsic => {
1086 let from = bare_fn.inputs().skip_binder()[0];
1087 let to = *bare_fn.output().skip_binder();
1088 return Some((&from.sty, &to.sty));
1096 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1097 match cx.tcx.item_type(def_id).sty {
1098 ty::TyFnDef(.., bfty) if bfty.abi() == RustIntrinsic => (),
1101 cx.tcx.item_name(def_id) == "transmute"
1106 /// Forbids using the `#[feature(...)]` attribute
1107 #[derive(Copy, Clone)]
1108 pub struct UnstableFeatures;
1113 "enabling unstable features (deprecated. do not use)"
1116 impl LintPass for UnstableFeatures {
1117 fn get_lints(&self) -> LintArray {
1118 lint_array!(UNSTABLE_FEATURES)
1122 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1123 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1124 if attr.check_name("feature") {
1125 if let Some(items) = attr.meta_item_list() {
1127 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1134 /// Lint for unions that contain fields with possibly non-trivial destructors.
1135 pub struct UnionsWithDropFields;
1138 UNIONS_WITH_DROP_FIELDS,
1140 "use of unions that contain fields with possibly non-trivial drop code"
1143 impl LintPass for UnionsWithDropFields {
1144 fn get_lints(&self) -> LintArray {
1145 lint_array!(UNIONS_WITH_DROP_FIELDS)
1149 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1150 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1151 if let hir::ItemUnion(ref vdata, _) = item.node {
1152 let param_env = &ty::ParameterEnvironment::for_item(ctx.tcx, item.id);
1153 for field in vdata.fields() {
1154 let field_ty = ctx.tcx.item_type(ctx.tcx.hir.local_def_id(field.id));
1155 if ctx.tcx.type_needs_drop_given_env(field_ty, param_env) {
1156 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1158 "union contains a field with possibly non-trivial drop code, \
1159 drop code of union fields is ignored when dropping the union");