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::{Level, LateContext, LintContext, LintArray};
40 use lint::{LintPass, LateLintPass, EarlyLintPass, EarlyContext};
42 use std::collections::HashSet;
46 use syntax::feature_gate::{AttributeGate, AttributeType, Stability, deprecated_attributes};
48 use syntax::symbol::keywords;
50 use rustc::hir::{self, PatKind};
51 use rustc::hir::intravisit::FnKind;
53 use bad_style::{MethodLateContext, method_context};
55 // hardwired lints from librustc
56 pub use lint::builtin::*;
61 "suggest using `loop { }` instead of `while true { }`"
64 #[derive(Copy, Clone)]
67 impl LintPass for WhileTrue {
68 fn get_lints(&self) -> LintArray {
69 lint_array!(WHILE_TRUE)
73 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WhileTrue {
74 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
75 if let hir::ExprWhile(ref cond, ..) = e.node {
76 if let hir::ExprLit(ref lit) = cond.node {
77 if let ast::LitKind::Bool(true) = lit.node {
78 cx.span_lint(WHILE_TRUE,
80 "denote infinite loops with loop { ... }");
90 "use of owned (Box type) heap memory"
93 #[derive(Copy, Clone)]
94 pub struct BoxPointers;
97 fn check_heap_type<'a, 'tcx>(&self, cx: &LateContext, span: Span, ty: Ty) {
98 for leaf_ty in ty.walk() {
100 let m = format!("type uses owned (Box type) pointers: {}", ty);
101 cx.span_lint(BOX_POINTERS, span, &m);
107 impl LintPass for BoxPointers {
108 fn get_lints(&self) -> LintArray {
109 lint_array!(BOX_POINTERS)
113 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
114 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
119 hir::ItemStruct(..) |
120 hir::ItemUnion(..) => {
121 let def_id = cx.tcx.hir.local_def_id(it.id);
122 self.check_heap_type(cx, it.span, cx.tcx.type_of(def_id))
127 // If it's a struct, we also have to check the fields' types
129 hir::ItemStruct(ref struct_def, _) |
130 hir::ItemUnion(ref struct_def, _) => {
131 for struct_field in struct_def.fields() {
132 let def_id = cx.tcx.hir.local_def_id(struct_field.id);
133 self.check_heap_type(cx, struct_field.span,
134 cx.tcx.type_of(def_id));
141 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
142 let ty = cx.tables.node_id_to_type(e.id);
143 self.check_heap_type(cx, e.span, ty);
148 NON_SHORTHAND_FIELD_PATTERNS,
150 "using `Struct { x: x }` instead of `Struct { x }`"
153 #[derive(Copy, Clone)]
154 pub struct NonShorthandFieldPatterns;
156 impl LintPass for NonShorthandFieldPatterns {
157 fn get_lints(&self) -> LintArray {
158 lint_array!(NON_SHORTHAND_FIELD_PATTERNS)
162 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
163 fn check_pat(&mut self, cx: &LateContext, pat: &hir::Pat) {
164 if let PatKind::Struct(_, ref field_pats, _) = pat.node {
165 for fieldpat in field_pats {
166 if fieldpat.node.is_shorthand {
169 if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
170 if ident.node == fieldpat.node.name {
171 cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
173 &format!("the `{}:` in this pattern is redundant and can \
186 "usage of `unsafe` code"
189 #[derive(Copy, Clone)]
190 pub struct UnsafeCode;
192 impl LintPass for UnsafeCode {
193 fn get_lints(&self) -> LintArray {
194 lint_array!(UNSAFE_CODE)
198 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnsafeCode {
199 fn check_expr(&mut self, cx: &LateContext, e: &hir::Expr) {
200 if let hir::ExprBlock(ref blk) = e.node {
201 // Don't warn about generated blocks, that'll just pollute the output.
202 if blk.rules == hir::UnsafeBlock(hir::UserProvided) {
203 cx.span_lint(UNSAFE_CODE, blk.span, "usage of an `unsafe` block");
208 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
210 hir::ItemTrait(hir::Unsafety::Unsafe, ..) => {
211 cx.span_lint(UNSAFE_CODE, it.span, "declaration of an `unsafe` trait")
214 hir::ItemImpl(hir::Unsafety::Unsafe, ..) => {
215 cx.span_lint(UNSAFE_CODE, it.span, "implementation of an `unsafe` trait")
222 fn check_fn(&mut self,
230 FnKind::ItemFn(_, _, hir::Unsafety::Unsafe, ..) => {
231 cx.span_lint(UNSAFE_CODE, span, "declaration of an `unsafe` function")
234 FnKind::Method(_, sig, ..) => {
235 if sig.unsafety == hir::Unsafety::Unsafe {
236 cx.span_lint(UNSAFE_CODE, span, "implementation of an `unsafe` method")
244 fn check_trait_item(&mut self, cx: &LateContext, item: &hir::TraitItem) {
245 if let hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Required(_)) = item.node {
246 if sig.unsafety == hir::Unsafety::Unsafe {
247 cx.span_lint(UNSAFE_CODE,
249 "declaration of an `unsafe` method")
258 "detects missing documentation for public members"
261 pub struct MissingDoc {
262 /// Stack of whether #[doc(hidden)] is set
263 /// at each level which has lint attributes.
264 doc_hidden_stack: Vec<bool>,
266 /// Private traits or trait items that leaked through. Don't check their methods.
267 private_traits: HashSet<ast::NodeId>,
271 pub fn new() -> MissingDoc {
273 doc_hidden_stack: vec![false],
274 private_traits: HashSet::new(),
278 fn doc_hidden(&self) -> bool {
279 *self.doc_hidden_stack.last().expect("empty doc_hidden_stack")
282 fn check_missing_docs_attrs(&self,
284 id: Option<ast::NodeId>,
285 attrs: &[ast::Attribute],
287 desc: &'static str) {
288 // If we're building a test harness, then warning about
289 // documentation is probably not really relevant right now.
290 if cx.sess().opts.test {
294 // `#[doc(hidden)]` disables missing_docs check.
295 if self.doc_hidden() {
299 // Only check publicly-visible items, using the result from the privacy pass.
300 // It's an option so the crate root can also use this function (it doesn't
302 if let Some(id) = id {
303 if !cx.access_levels.is_exported(id) {
308 let has_doc = attrs.iter().any(|a| a.is_value_str() && a.check_name("doc"));
310 cx.span_lint(MISSING_DOCS,
312 &format!("missing documentation for {}", desc));
317 impl LintPass for MissingDoc {
318 fn get_lints(&self) -> LintArray {
319 lint_array!(MISSING_DOCS)
323 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc {
324 fn enter_lint_attrs(&mut self, _: &LateContext, attrs: &[ast::Attribute]) {
325 let doc_hidden = self.doc_hidden() ||
326 attrs.iter().any(|attr| {
327 attr.check_name("doc") &&
328 match attr.meta_item_list() {
330 Some(l) => attr::list_contains_name(&l, "hidden"),
333 self.doc_hidden_stack.push(doc_hidden);
336 fn exit_lint_attrs(&mut self, _: &LateContext, _attrs: &[ast::Attribute]) {
337 self.doc_hidden_stack.pop().expect("empty doc_hidden_stack");
340 fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) {
341 self.check_missing_docs_attrs(cx, None, &krate.attrs, krate.span, "crate");
344 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
345 let desc = match it.node {
346 hir::ItemFn(..) => "a function",
347 hir::ItemMod(..) => "a module",
348 hir::ItemEnum(..) => "an enum",
349 hir::ItemStruct(..) => "a struct",
350 hir::ItemUnion(..) => "a union",
351 hir::ItemTrait(.., ref trait_item_refs) => {
352 // Issue #11592, traits are always considered exported, even when private.
353 if it.vis == hir::Visibility::Inherited {
354 self.private_traits.insert(it.id);
355 for trait_item_ref in trait_item_refs {
356 self.private_traits.insert(trait_item_ref.id.node_id);
362 hir::ItemTy(..) => "a type alias",
363 hir::ItemImpl(.., Some(ref trait_ref), _, ref impl_item_refs) => {
364 // If the trait is private, add the impl items to private_traits so they don't get
365 // reported for missing docs.
366 let real_trait = trait_ref.path.def.def_id();
367 if let Some(node_id) = cx.tcx.hir.as_local_node_id(real_trait) {
368 match cx.tcx.hir.find(node_id) {
369 Some(hir_map::NodeItem(item)) => {
370 if item.vis == hir::Visibility::Inherited {
371 for impl_item_ref in impl_item_refs {
372 self.private_traits.insert(impl_item_ref.id.node_id);
381 hir::ItemConst(..) => "a constant",
382 hir::ItemStatic(..) => "a static",
386 self.check_missing_docs_attrs(cx, Some(it.id), &it.attrs, it.span, desc);
389 fn check_trait_item(&mut self, cx: &LateContext, trait_item: &hir::TraitItem) {
390 if self.private_traits.contains(&trait_item.id) {
394 let desc = match trait_item.node {
395 hir::TraitItemKind::Const(..) => "an associated constant",
396 hir::TraitItemKind::Method(..) => "a trait method",
397 hir::TraitItemKind::Type(..) => "an associated type",
400 self.check_missing_docs_attrs(cx,
407 fn check_impl_item(&mut self, cx: &LateContext, impl_item: &hir::ImplItem) {
408 // If the method is an impl for a trait, don't doc.
409 if method_context(cx, impl_item.id) == MethodLateContext::TraitImpl {
413 let desc = match impl_item.node {
414 hir::ImplItemKind::Const(..) => "an associated constant",
415 hir::ImplItemKind::Method(..) => "a method",
416 hir::ImplItemKind::Type(_) => "an associated type",
418 self.check_missing_docs_attrs(cx,
425 fn check_struct_field(&mut self, cx: &LateContext, sf: &hir::StructField) {
426 if !sf.is_positional() {
427 self.check_missing_docs_attrs(cx,
435 fn check_variant(&mut self, cx: &LateContext, v: &hir::Variant, _: &hir::Generics) {
436 self.check_missing_docs_attrs(cx,
437 Some(v.node.data.id()),
445 pub MISSING_COPY_IMPLEMENTATIONS,
447 "detects potentially-forgotten implementations of `Copy`"
450 #[derive(Copy, Clone)]
451 pub struct MissingCopyImplementations;
453 impl LintPass for MissingCopyImplementations {
454 fn get_lints(&self) -> LintArray {
455 lint_array!(MISSING_COPY_IMPLEMENTATIONS)
459 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingCopyImplementations {
460 fn check_item(&mut self, cx: &LateContext, item: &hir::Item) {
461 if !cx.access_levels.is_reachable(item.id) {
464 let (def, ty) = match item.node {
465 hir::ItemStruct(_, ref ast_generics) => {
466 if ast_generics.is_parameterized() {
469 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
470 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
472 hir::ItemUnion(_, ref ast_generics) => {
473 if ast_generics.is_parameterized() {
476 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
477 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
479 hir::ItemEnum(_, ref ast_generics) => {
480 if ast_generics.is_parameterized() {
483 let def = cx.tcx.adt_def(cx.tcx.hir.local_def_id(item.id));
484 (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[])))
488 if def.has_dtor(cx.tcx) {
491 let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
492 if !ty.moves_by_default(cx.tcx, param_env, item.span) {
495 if param_env.can_type_implement_copy(cx.tcx, ty, item.span).is_ok() {
496 cx.span_lint(MISSING_COPY_IMPLEMENTATIONS,
498 "type could implement `Copy`; consider adding `impl \
505 MISSING_DEBUG_IMPLEMENTATIONS,
507 "detects missing implementations of fmt::Debug"
510 pub struct MissingDebugImplementations {
511 impling_types: Option<NodeSet>,
514 impl MissingDebugImplementations {
515 pub fn new() -> MissingDebugImplementations {
516 MissingDebugImplementations { impling_types: None }
520 impl LintPass for MissingDebugImplementations {
521 fn get_lints(&self) -> LintArray {
522 lint_array!(MISSING_DEBUG_IMPLEMENTATIONS)
526 impl<'a, 'tcx> LateLintPass<'a, 'tcx> 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(..) |
535 hir::ItemEnum(..) => {}
539 let debug = match cx.tcx.lang_items.debug_trait() {
540 Some(debug) => debug,
544 if self.impling_types.is_none() {
545 let debug_def = cx.tcx.trait_def(debug);
546 let mut impls = NodeSet();
547 debug_def.for_each_impl(cx.tcx, |d| {
548 if let Some(ty_def) = cx.tcx.type_of(d).ty_to_def_id() {
549 if let Some(node_id) = cx.tcx.hir.as_local_node_id(ty_def) {
550 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")
569 pub ANONYMOUS_PARAMETERS,
571 "detects anonymous parameters"
574 /// Checks for use of anonymous parameters (RFC 1685)
576 pub struct AnonymousParameters;
578 impl LintPass for AnonymousParameters {
579 fn get_lints(&self) -> LintArray {
580 lint_array!(ANONYMOUS_PARAMETERS)
584 impl EarlyLintPass for AnonymousParameters {
585 fn check_trait_item(&mut self, cx: &EarlyContext, it: &ast::TraitItem) {
587 ast::TraitItemKind::Method(ref sig, _) => {
588 for arg in sig.decl.inputs.iter() {
590 ast::PatKind::Ident(_, ident, None) => {
591 if ident.node.name == keywords::Invalid.name() {
592 cx.span_lint(ANONYMOUS_PARAMETERS,
594 "use of deprecated anonymous parameter");
609 "detects use of deprecated attributes"
612 /// Checks for use of attributes which have been deprecated.
614 pub struct DeprecatedAttr {
615 // This is not free to compute, so we want to keep it around, rather than
616 // compute it for every attribute.
617 depr_attrs: Vec<&'static (&'static str, AttributeType, AttributeGate)>,
620 impl DeprecatedAttr {
621 pub fn new() -> DeprecatedAttr {
623 depr_attrs: deprecated_attributes(),
628 impl LintPass for DeprecatedAttr {
629 fn get_lints(&self) -> LintArray {
630 lint_array!(DEPRECATED_ATTR)
634 impl EarlyLintPass for DeprecatedAttr {
635 fn check_attribute(&mut self, cx: &EarlyContext, attr: &ast::Attribute) {
636 let name = unwrap_or!(attr.name(), return);
637 for &&(n, _, ref g) in &self.depr_attrs {
639 if let &AttributeGate::Gated(Stability::Deprecated(link),
643 cx.span_lint(DEPRECATED,
645 &format!("use of deprecated attribute `{}`: {}. See {}",
646 name, reason, link));
655 pub ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
657 "floating-point literals cannot be used in patterns"
660 /// Checks for floating point literals in patterns.
662 pub struct IllegalFloatLiteralPattern;
664 impl LintPass for IllegalFloatLiteralPattern {
665 fn get_lints(&self) -> LintArray {
666 lint_array!(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN)
670 fn fl_lit_check_expr(cx: &EarlyContext, expr: &ast::Expr) {
671 use self::ast::{ExprKind, LitKind};
673 ExprKind::Lit(ref l) => {
675 LitKind::FloatUnsuffixed(..) |
676 LitKind::Float(..) => {
677 cx.span_lint(ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
679 "floating-point literals cannot be used in patterns");
684 // These may occur in patterns
685 // and can maybe contain float literals
686 ExprKind::Unary(_, ref f) => fl_lit_check_expr(cx, f),
687 // Other kinds of exprs can't occur in patterns so we don't have to check them
688 // (ast_validation will emit an error if they occur)
693 impl EarlyLintPass for IllegalFloatLiteralPattern {
694 fn check_pat(&mut self, cx: &EarlyContext, pat: &ast::Pat) {
695 use self::ast::PatKind;
698 // Wildcard patterns and paths are uninteresting for the lint
700 PatKind::Path(..) => (),
702 // The walk logic recurses inside these
704 PatKind::Struct(..) |
706 PatKind::TupleStruct(..) |
709 PatKind::Slice(..) => (),
711 // Extract the expressions and check them
712 PatKind::Lit(ref e) => fl_lit_check_expr(cx, e),
713 PatKind::Range(ref st, ref en, _) => {
714 fl_lit_check_expr(cx, st);
715 fl_lit_check_expr(cx, en);
718 PatKind::Mac(_) => bug!("lint must run post-expansion"),
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 let node_id = cfg.graph.node_data(idx).id();
807 // is this a recursive call?
808 let self_recursive = if node_id != ast::DUMMY_NODE_ID {
810 Some(ref method) => expr_refers_to_this_method(cx, method, node_id),
811 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.
822 // add the successors of this node to explore the graph further.
823 for (_, edge) in cfg.graph.outgoing_edges(idx) {
824 let target_idx = edge.target();
825 let target_cfg_id = target_idx.node_id();
826 if !visited.contains(&target_cfg_id) {
827 work_queue.push(target_idx)
832 // Check the number of self calls because a function that
833 // doesn't return (e.g. calls a `-> !` function or `loop { /*
834 // no break */ }`) shouldn't be linted unless it actually
836 if !reached_exit_without_self_call && !self_call_spans.is_empty() {
837 let mut db = cx.struct_span_lint(UNCONDITIONAL_RECURSION,
839 "function cannot return without recurring");
841 // FIXME #19668: these could be span_lint_note's instead of this manual guard.
842 if cx.current_level(UNCONDITIONAL_RECURSION) != Level::Allow {
843 // offer some help to the programmer.
844 for call in &self_call_spans {
845 db.span_note(*call, "recursive call site");
847 db.help("a `loop` may express intention \
848 better if this is on purpose");
856 // Functions for identifying if the given Expr NodeId `id`
857 // represents a call to the function `fn_id`/method `method`.
859 fn expr_refers_to_this_fn(cx: &LateContext, fn_id: ast::NodeId, id: ast::NodeId) -> bool {
860 match cx.tcx.hir.get(id) {
861 hir_map::NodeExpr(&hir::Expr { node: hir::ExprCall(ref callee, _), .. }) => {
862 let def = if let hir::ExprPath(ref qpath) = callee.node {
863 cx.tables.qpath_def(qpath, callee.id)
867 def.def_id() == cx.tcx.hir.local_def_id(fn_id)
873 // Check if the expression `id` performs a call to `method`.
874 fn expr_refers_to_this_method(cx: &LateContext,
875 method: &ty::AssociatedItem,
878 use rustc::ty::adjustment::*;
880 // Ignore non-expressions.
881 let expr = if let hir_map::NodeExpr(e) = cx.tcx.hir.get(id) {
887 // Check for overloaded autoderef method calls.
888 let mut source = cx.tables.expr_ty(expr);
889 for adjustment in cx.tables.expr_adjustments(expr) {
890 if let Adjust::Deref(Some(deref)) = adjustment.kind {
891 let (def_id, substs) = deref.method_call(cx.tcx, source);
892 if method_call_refers_to_method(cx, method, def_id, substs, id) {
896 source = adjustment.target;
899 // Check for method calls and overloaded operators.
900 if cx.tables.is_method_call(expr) {
901 let def_id = cx.tables.type_dependent_defs[&id].def_id();
902 let substs = cx.tables.node_substs(id);
903 if method_call_refers_to_method(cx, method, def_id, substs, id) {
908 // Check for calls to methods via explicit paths (e.g. `T::method()`).
910 hir::ExprCall(ref callee, _) => {
911 let def = if let hir::ExprPath(ref qpath) = callee.node {
912 cx.tables.qpath_def(qpath, callee.id)
917 Def::Method(def_id) => {
918 let substs = cx.tables.node_substs(callee.id);
919 method_call_refers_to_method(cx, method, def_id, substs, id)
928 // Check if the method call to the method with the ID `callee_id`
929 // and instantiated with `callee_substs` refers to method `method`.
930 fn method_call_refers_to_method<'a, 'tcx>(cx: &LateContext<'a, 'tcx>,
931 method: &ty::AssociatedItem,
933 callee_substs: &Substs<'tcx>,
934 expr_id: ast::NodeId)
937 let callee_item = tcx.associated_item(callee_id);
939 match callee_item.container {
940 // This is an inherent method, so the `def_id` refers
941 // directly to the method definition.
942 ty::ImplContainer(_) => callee_id == method.def_id,
944 // A trait method, from any number of possible sources.
945 // Attempt to select a concrete impl before checking.
946 ty::TraitContainer(trait_def_id) => {
947 let trait_ref = ty::TraitRef::from_method(tcx, trait_def_id, callee_substs);
948 let trait_ref = ty::Binder(trait_ref);
949 let span = tcx.hir.span(expr_id);
951 traits::Obligation::new(traits::ObligationCause::misc(span, expr_id),
953 trait_ref.to_poly_trait_predicate());
955 tcx.infer_ctxt().enter(|infcx| {
956 let mut selcx = traits::SelectionContext::new(&infcx);
957 match selcx.select(&obligation) {
958 // The method comes from a `T: Trait` bound.
959 // If `T` is `Self`, then this call is inside
960 // a default method definition.
961 Ok(Some(traits::VtableParam(_))) => {
962 let on_self = trait_ref.self_ty().is_self();
963 // We can only be recurring in a default
964 // method if we're being called literally
965 // on the `Self` type.
966 on_self && callee_id == method.def_id
969 // The `impl` is known, so we check that with a
971 Ok(Some(traits::VtableImpl(vtable_impl))) => {
972 let container = ty::ImplContainer(vtable_impl.impl_def_id);
973 // It matches if it comes from the same impl,
974 // and has the same method name.
975 container == method.container && callee_item.name == method.name
978 // There's no way to know if this call is
979 // recursive, so we assume it's not.
992 "compiler plugin used as ordinary library in non-plugin crate"
995 #[derive(Copy, Clone)]
996 pub struct PluginAsLibrary;
998 impl LintPass for PluginAsLibrary {
999 fn get_lints(&self) -> LintArray {
1000 lint_array![PLUGIN_AS_LIBRARY]
1004 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for PluginAsLibrary {
1005 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1006 if cx.sess().plugin_registrar_fn.get().is_some() {
1007 // We're compiling a plugin; it's fine to link other plugins.
1012 hir::ItemExternCrate(..) => (),
1016 let prfn = match cx.sess().cstore.extern_mod_stmt_cnum(it.id) {
1017 Some(cnum) => cx.sess().cstore.plugin_registrar_fn(cnum),
1019 // Probably means we aren't linking the crate for some reason.
1021 // Not sure if / when this could happen.
1027 cx.span_lint(PLUGIN_AS_LIBRARY,
1029 "compiler plugin used as an ordinary library");
1035 PRIVATE_NO_MANGLE_FNS,
1037 "functions marked #[no_mangle] should be exported"
1041 PRIVATE_NO_MANGLE_STATICS,
1043 "statics marked #[no_mangle] should be exported"
1047 NO_MANGLE_CONST_ITEMS,
1049 "const items will not have their symbols exported"
1053 NO_MANGLE_GENERIC_ITEMS,
1055 "generic items must be mangled"
1058 #[derive(Copy, Clone)]
1059 pub struct InvalidNoMangleItems;
1061 impl LintPass for InvalidNoMangleItems {
1062 fn get_lints(&self) -> LintArray {
1063 lint_array!(PRIVATE_NO_MANGLE_FNS,
1064 PRIVATE_NO_MANGLE_STATICS,
1065 NO_MANGLE_CONST_ITEMS,
1066 NO_MANGLE_GENERIC_ITEMS)
1070 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for InvalidNoMangleItems {
1071 fn check_item(&mut self, cx: &LateContext, it: &hir::Item) {
1073 hir::ItemFn(.., ref generics, _) => {
1074 if attr::contains_name(&it.attrs, "no_mangle") &&
1075 !attr::contains_name(&it.attrs, "linkage") {
1076 if !cx.access_levels.is_reachable(it.id) {
1077 let msg = format!("function {} is marked #[no_mangle], but not exported",
1079 cx.span_lint(PRIVATE_NO_MANGLE_FNS, it.span, &msg);
1081 if generics.is_type_parameterized() {
1082 cx.span_lint(NO_MANGLE_GENERIC_ITEMS,
1084 "functions generic over types must be mangled");
1088 hir::ItemStatic(..) => {
1089 if attr::contains_name(&it.attrs, "no_mangle") &&
1090 !cx.access_levels.is_reachable(it.id) {
1091 let msg = format!("static {} is marked #[no_mangle], but not exported",
1093 cx.span_lint(PRIVATE_NO_MANGLE_STATICS, it.span, &msg);
1096 hir::ItemConst(..) => {
1097 if attr::contains_name(&it.attrs, "no_mangle") {
1098 // Const items do not refer to a particular location in memory, and therefore
1099 // don't have anything to attach a symbol to
1100 let msg = "const items should never be #[no_mangle], consider instead using \
1102 cx.span_lint(NO_MANGLE_CONST_ITEMS, it.span, msg);
1110 #[derive(Clone, Copy)]
1111 pub struct MutableTransmutes;
1116 "mutating transmuted &mut T from &T may cause undefined behavior"
1119 impl LintPass for MutableTransmutes {
1120 fn get_lints(&self) -> LintArray {
1121 lint_array!(MUTABLE_TRANSMUTES)
1125 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MutableTransmutes {
1126 fn check_expr(&mut self, cx: &LateContext, expr: &hir::Expr) {
1127 use syntax::abi::Abi::RustIntrinsic;
1129 let msg = "mutating transmuted &mut T from &T may cause undefined behavior, \
1130 consider instead using an UnsafeCell";
1131 match get_transmute_from_to(cx, expr) {
1132 Some((&ty::TyRef(_, from_mt), &ty::TyRef(_, to_mt))) => {
1133 if to_mt.mutbl == hir::Mutability::MutMutable &&
1134 from_mt.mutbl == hir::Mutability::MutImmutable {
1135 cx.span_lint(MUTABLE_TRANSMUTES, expr.span, msg);
1141 fn get_transmute_from_to<'a, 'tcx>
1142 (cx: &LateContext<'a, 'tcx>,
1144 -> Option<(&'tcx ty::TypeVariants<'tcx>, &'tcx ty::TypeVariants<'tcx>)> {
1145 let def = if let hir::ExprPath(ref qpath) = expr.node {
1146 cx.tables.qpath_def(qpath, expr.id)
1150 if let Def::Fn(did) = def {
1151 if !def_id_is_transmute(cx, did) {
1154 let sig = cx.tables.node_id_to_type(expr.id).fn_sig(cx.tcx);
1155 let from = sig.inputs().skip_binder()[0];
1156 let to = *sig.output().skip_binder();
1157 return Some((&from.sty, &to.sty));
1162 fn def_id_is_transmute(cx: &LateContext, def_id: DefId) -> bool {
1163 cx.tcx.fn_sig(def_id).abi() == RustIntrinsic &&
1164 cx.tcx.item_name(def_id) == "transmute"
1169 /// Forbids using the `#[feature(...)]` attribute
1170 #[derive(Copy, Clone)]
1171 pub struct UnstableFeatures;
1176 "enabling unstable features (deprecated. do not use)"
1179 impl LintPass for UnstableFeatures {
1180 fn get_lints(&self) -> LintArray {
1181 lint_array!(UNSTABLE_FEATURES)
1185 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnstableFeatures {
1186 fn check_attribute(&mut self, ctx: &LateContext, attr: &ast::Attribute) {
1187 if attr.check_name("feature") {
1188 if let Some(items) = attr.meta_item_list() {
1190 ctx.span_lint(UNSTABLE_FEATURES, item.span(), "unstable feature");
1197 /// Lint for unions that contain fields with possibly non-trivial destructors.
1198 pub struct UnionsWithDropFields;
1201 UNIONS_WITH_DROP_FIELDS,
1203 "use of unions that contain fields with possibly non-trivial drop code"
1206 impl LintPass for UnionsWithDropFields {
1207 fn get_lints(&self) -> LintArray {
1208 lint_array!(UNIONS_WITH_DROP_FIELDS)
1212 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for UnionsWithDropFields {
1213 fn check_item(&mut self, ctx: &LateContext, item: &hir::Item) {
1214 if let hir::ItemUnion(ref vdata, _) = item.node {
1215 for field in vdata.fields() {
1216 let field_ty = ctx.tcx.type_of(ctx.tcx.hir.local_def_id(field.id));
1217 if field_ty.needs_drop(ctx.tcx, ctx.param_env) {
1218 ctx.span_lint(UNIONS_WITH_DROP_FIELDS,
1220 "union contains a field with possibly non-trivial drop code, \
1221 drop code of union fields is ignored when dropping the union");