1 // Copyright 2012-2014 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 //! A 'lint' check is a kind of miscellaneous constraint that a user _might_
12 //! want to enforce, but might reasonably want to permit as well, on a
13 //! module-by-module basis. They contrast with static constraints enforced by
14 //! other phases of the compiler, which are generally required to hold in order
15 //! to compile the program at all.
17 //! The lint checking is all consolidated into one pass which runs just before
18 //! translation to LLVM bytecode. Throughout compilation, lint warnings can be
19 //! added via the `add_lint` method on the Session structure. This requires a
20 //! span and an id of the node that the lint is being added to. The lint isn't
21 //! actually emitted at that time because it is unknown what the actual lint
22 //! level at that location is.
24 //! To actually emit lint warnings/errors, a separate pass is used just before
25 //! translation. A context keeps track of the current state of all lint levels.
26 //! Upon entering a node of the ast which can modify the lint settings, the
27 //! previous lint state is pushed onto a stack and the ast is then recursed
28 //! upon. As the ast is traversed, this keeps track of the current lint level
29 //! for all lint attributes.
31 //! To add a new lint warning, all you need to do is to either invoke `add_lint`
32 //! on the session at the appropriate time, or write a few linting functions and
33 //! modify the Context visitor appropriately. If you're adding lints from the
34 //! Context itself, span_lint should be used instead of add_lint.
36 #![allow(non_camel_case_types)]
39 use metadata::csearch;
40 use middle::dead::DEAD_CODE_LINT_STR;
43 use middle::trans::adt; // for `adt::is_ffi_safe`
45 use middle::typeck::astconv::{ast_ty_to_ty, AstConv};
46 use middle::typeck::infer;
48 use util::ppaux::{ty_to_str};
51 use collections::HashMap;
56 use std::to_str::ToStr;
61 use collections::SmallIntMap;
64 use syntax::ast_util::IdVisitingOperation;
65 use syntax::attr::{AttrMetaMethods, AttributeMethods};
67 use syntax::codemap::Span;
68 use syntax::parse::token::InternedString;
69 use syntax::parse::token;
70 use syntax::visit::Visitor;
71 use syntax::{ast, ast_util, visit};
73 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
77 UnnecessaryQualification,
83 NonUppercasePatternStatics,
101 UnnecessaryAllocation,
116 DeprecatedOwnedVector,
123 pub fn level_to_str(lv: level) -> &'static str {
132 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
134 allow, warn, deny, forbid
137 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
138 pub struct LintSpec {
141 pub desc: &'static str,
144 pub type LintDict = HashMap<&'static str, LintSpec>;
153 static lint_table: &'static [(&'static str, LintSpec)] = &[
157 desc: "proper use of libc types in foreign modules",
164 desc: "imports that are never used",
168 ("unnecessary_qualification",
170 lint: UnnecessaryQualification,
171 desc: "detects unnecessarily qualified names",
178 desc: "suggest using `loop { }` instead of `while true { }`",
185 desc: "path statements with no effect",
189 ("unrecognized_lint",
191 lint: UnrecognizedLint,
192 desc: "unrecognized lint attribute",
196 ("non_camel_case_types",
198 lint: NonCamelCaseTypes,
199 desc: "types, variants and traits should have camel case names",
203 ("non_uppercase_statics",
205 lint: NonUppercaseStatics,
206 desc: "static constants should have uppercase identifiers",
210 ("non_uppercase_pattern_statics",
212 lint: NonUppercasePatternStatics,
213 desc: "static constants in match patterns should be all caps",
217 ("uppercase_variables",
219 lint: UppercaseVariables,
220 desc: "variable and structure field names should start with a lowercase character",
224 ("unnecessary_parens",
226 lint: UnnecessaryParens,
227 desc: "`if`, `match`, `while` and `return` do not need parentheses",
231 ("managed_heap_memory",
233 lint: ManagedHeapMemory,
234 desc: "use of managed (@ type) heap memory",
238 ("owned_heap_memory",
240 lint: OwnedHeapMemory,
241 desc: "use of owned (~ type) heap memory",
248 desc: "use of any (~ type or @ type) heap memory",
255 desc: "comparisons made useless by limits of the types involved",
262 desc: "literal out of range for its type",
270 desc: "unnecessary use of an `unsafe` block",
277 desc: "usage of an `unsafe` block",
283 lint: AttributeUsage,
284 desc: "detects bad use of attributes",
290 lint: UnusedVariable,
291 desc: "detect variables which are not used in any way",
297 lint: DeadAssignment,
298 desc: "detect assignments that will never be read",
302 ("unnecessary_typecast",
304 lint: UnnecessaryTypecast,
305 desc: "detects unnecessary type casts, that can be removed",
312 desc: "detect mut variables which don't need to be mutable",
316 ("unnecessary_allocation",
318 lint: UnnecessaryAllocation,
319 desc: "detects unnecessary allocations that can be eliminated",
326 desc: "detect piece of code that will never be used",
329 ("visible_private_types",
331 lint: VisiblePrivateTypes,
332 desc: "detect use of private types in exported type signatures",
339 desc: "detects missing documentation for public members",
345 lint: UnreachableCode,
346 desc: "detects unreachable code",
353 desc: "detects use of #[deprecated] items",
360 desc: "detects use of #[experimental] items",
367 desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
374 desc: "mass-change the level for lints which produce warnings",
380 lint: UnknownFeatures,
381 desc: "unknown features found in crate-level #[feature] directives",
385 ("unknown_crate_type",
387 lint: UnknownCrateType,
388 desc: "unknown crate type found in #[crate_type] directive",
395 desc: "unused result of a type flagged as #[must_use]",
402 desc: "unused result of an expression in a statement",
406 ("deprecated_owned_vector",
408 lint: DeprecatedOwnedVector,
409 desc: "use of a `~[T]` vector",
413 ("raw_pointer_deriving",
415 lint: RawPointerDeriving,
416 desc: "uses of #[deriving] with raw pointers are rarely correct",
422 Pass names should not contain a '-', as the compiler normalizes
423 '-' to '_' in command-line flags
425 pub fn get_lint_dict() -> LintDict {
426 let mut map = HashMap::new();
427 for &(k, v) in lint_table.iter() {
434 // All known lint modes (string versions)
436 // Current levels of each lint warning
437 cur: SmallIntMap<(level, LintSource)>,
438 // context we're checking in (used to access fields like sess)
440 // maps from an expression id that corresponds to a method call to the
441 // details of the method to be invoked
442 method_map: typeck::MethodMap,
443 // Items exported by the crate; used by the missing_doc lint.
444 exported_items: &'a privacy::ExportedItems,
445 // The id of the current `ast::StructDef` being walked.
446 cur_struct_def_id: ast::NodeId,
447 // Whether some ancestor of the current node was marked
451 // When recursing into an attributed node of the ast which modifies lint
452 // levels, this stack keeps track of the previous lint levels of whatever
454 lint_stack: Vec<(Lint, level, LintSource)> ,
456 // id of the last visited negated expression
457 negated_expr_id: ast::NodeId
460 impl<'a> Context<'a> {
461 fn get_level(&self, lint: Lint) -> level {
462 match self.cur.find(&(lint as uint)) {
463 Some(&(lvl, _)) => lvl,
468 fn get_source(&self, lint: Lint) -> LintSource {
469 match self.cur.find(&(lint as uint)) {
470 Some(&(_, src)) => src,
475 fn set_level(&mut self, lint: Lint, level: level, src: LintSource) {
477 self.cur.remove(&(lint as uint));
479 self.cur.insert(lint as uint, (level, src));
483 fn lint_to_str(&self, lint: Lint) -> &'static str {
484 for (k, v) in self.dict.iter() {
489 fail!("unregistered lint {:?}", lint);
492 fn span_lint(&self, lint: Lint, span: Span, msg: &str) {
493 let (level, src) = match self.cur.find(&(lint as uint)) {
495 Some(&(warn, src)) => (self.get_level(Warnings), src),
498 if level == allow { return }
501 let msg = match src {
503 format!("{}, \\#[{}({})] on by default", msg,
504 level_to_str(level), self.lint_to_str(lint))
507 format!("{} [-{} {}]", msg,
509 warn => 'W', deny => 'D', forbid => 'F',
511 }, self.lint_to_str(lint).replace("_", "-"))
519 warn => { self.tcx.sess.span_warn(span, msg); }
520 deny | forbid => { self.tcx.sess.span_err(span, msg); }
524 for &span in note.iter() {
525 self.tcx.sess.span_note(span, "lint level defined here");
530 * Merge the lints specified by any lint attributes into the
531 * current lint context, call the provided function, then reset the
532 * lints in effect to their previous state.
534 fn with_lint_attrs(&mut self,
535 attrs: &[ast::Attribute],
537 // Parse all of the lint attributes, and then add them all to the
538 // current dictionary of lint information. Along the way, keep a history
539 // of what we changed so we can roll everything back after invoking the
542 each_lint(&self.tcx.sess, attrs, |meta, level, lintname| {
543 match self.dict.find_equiv(&lintname) {
548 format!("unknown `{}` attribute: `{}`",
549 level_to_str(level), lintname));
552 let lint = lint.lint;
553 let now = self.get_level(lint);
554 if now == forbid && level != forbid {
555 self.tcx.sess.span_err(meta.span,
556 format!("{}({}) overruled by outer forbid({})",
558 lintname, lintname));
559 } else if now != level {
560 let src = self.get_source(lint);
561 self.lint_stack.push((lint, now, src));
563 self.set_level(lint, level, Node(meta.span));
570 let old_is_doc_hidden = self.is_doc_hidden;
572 self.is_doc_hidden ||
575 attr.name().equiv(&("doc")) &&
576 match attr.meta_item_list() {
579 attr::contains_name(l.as_slice(), "hidden")
587 self.is_doc_hidden = old_is_doc_hidden;
588 for _ in range(0, pushed) {
589 let (lint, lvl, src) = self.lint_stack.pop().unwrap();
590 self.set_level(lint, lvl, src);
594 fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
595 let mut v = ast_util::IdVisitor {
597 pass_through_items: false,
598 visited_outermost: false,
604 // Check that every lint from the list of attributes satisfies `f`.
605 // Return true if that's the case. Otherwise return false.
606 pub fn each_lint(sess: &session::Session,
607 attrs: &[ast::Attribute],
608 f: |@ast::MetaItem, level, InternedString| -> bool)
610 let xs = [allow, warn, deny, forbid];
611 for &level in xs.iter() {
612 let level_name = level_to_str(level);
613 for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
614 let meta = attr.node.value;
615 let metas = match meta.node {
616 ast::MetaList(_, ref metas) => metas,
618 sess.span_err(meta.span, "malformed lint attribute");
622 for meta in metas.iter() {
624 ast::MetaWord(ref lintname) => {
625 if !f(*meta, level, (*lintname).clone()) {
630 sess.span_err(meta.span, "malformed lint attribute");
639 // Check from a list of attributes if it contains the appropriate
640 // `#[level(lintname)]` attribute (e.g. `#[allow(dead_code)]).
641 pub fn contains_lint(attrs: &[ast::Attribute],
643 lintname: &'static str)
645 let level_name = level_to_str(level);
646 for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
647 if attr.meta_item_list().is_none() {
650 let list = attr.meta_item_list().unwrap();
651 for meta_item in list.iter() {
652 if meta_item.name().equiv(&lintname) {
660 fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
662 ast::ExprWhile(cond, _) => {
664 ast::ExprLit(lit) => {
666 ast::LitBool(true) => {
667 cx.span_lint(WhileTrue,
669 "denote infinite loops with loop \
681 impl<'a> AstConv for Context<'a>{
682 fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
684 fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
685 ty::lookup_item_type(self.tcx, id)
688 fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef {
689 ty::lookup_trait_def(self.tcx, id)
692 fn ty_infer(&self, _span: Span) -> ty::t {
693 infer::new_infer_ctxt(self.tcx).next_ty_var()
698 fn check_unused_casts(cx: &Context, e: &ast::Expr) {
699 return match e.node {
700 ast::ExprCast(expr, ty) => {
701 let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), ty);
702 if ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty {
703 cx.span_lint(UnnecessaryTypecast, ty.span,
704 "unnecessary type cast");
711 fn check_type_limits(cx: &Context, e: &ast::Expr) {
712 return match e.node {
713 ast::ExprBinary(binop, l, r) => {
714 if is_comparison(binop) && !check_limits(cx.tcx, binop, l, r) {
715 cx.span_lint(TypeLimits, e.span,
716 "comparison is useless due to type limits");
719 ast::ExprLit(lit) => {
720 match ty::get(ty::expr_ty(cx.tcx, e)).sty {
722 let int_type = if t == ast::TyI {
723 cx.tcx.sess.targ_cfg.int_type
725 let (min, max) = int_ty_range(int_type);
726 let mut lit_val: i64 = match lit.node {
727 ast::LitInt(v, _) => v,
728 ast::LitUint(v, _) => v as i64,
729 ast::LitIntUnsuffixed(v) => v,
732 if cx.negated_expr_id == e.id {
735 if lit_val < min || lit_val > max {
736 cx.span_lint(TypeOverflow, e.span,
737 "literal out of range for its type");
741 let uint_type = if t == ast::TyU {
742 cx.tcx.sess.targ_cfg.uint_type
744 let (min, max) = uint_ty_range(uint_type);
745 let lit_val: u64 = match lit.node {
746 ast::LitInt(v, _) => v as u64,
747 ast::LitUint(v, _) => v,
748 ast::LitIntUnsuffixed(v) => v as u64,
751 if lit_val < min || lit_val > max {
752 cx.span_lint(TypeOverflow, e.span,
753 "literal out of range for its type");
763 fn is_valid<T:cmp::Ord>(binop: ast::BinOp, v: T,
764 min: T, max: T) -> bool {
766 ast::BiLt => v <= max,
767 ast::BiLe => v < max,
768 ast::BiGt => v >= min,
769 ast::BiGe => v > min,
770 ast::BiEq | ast::BiNe => v >= min && v <= max,
775 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
777 ast::BiLt => ast::BiGt,
778 ast::BiLe => ast::BiGe,
779 ast::BiGt => ast::BiLt,
780 ast::BiGe => ast::BiLe,
785 // for int & uint, be conservative with the warnings, so that the
786 // warnings are consistent between 32- and 64-bit platforms
787 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
789 ast::TyI => (i64::MIN, i64::MAX),
790 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
791 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
792 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
793 ast::TyI64 => (i64::MIN, i64::MAX)
797 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
799 ast::TyU => (u64::MIN, u64::MAX),
800 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
801 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
802 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
803 ast::TyU64 => (u64::MIN, u64::MAX)
807 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
808 l: &ast::Expr, r: &ast::Expr) -> bool {
809 let (lit, expr, swap) = match (&l.node, &r.node) {
810 (&ast::ExprLit(_), _) => (l, r, true),
811 (_, &ast::ExprLit(_)) => (r, l, false),
814 // Normalize the binop so that the literal is always on the RHS in
816 let norm_binop = if swap { rev_binop(binop) } else { binop };
817 match ty::get(ty::expr_ty(tcx, expr)).sty {
818 ty::ty_int(int_ty) => {
819 let (min, max) = int_ty_range(int_ty);
820 let lit_val: i64 = match lit.node {
821 ast::ExprLit(li) => match li.node {
822 ast::LitInt(v, _) => v,
823 ast::LitUint(v, _) => v as i64,
824 ast::LitIntUnsuffixed(v) => v,
829 is_valid(norm_binop, lit_val, min, max)
831 ty::ty_uint(uint_ty) => {
832 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
833 let lit_val: u64 = match lit.node {
834 ast::ExprLit(li) => match li.node {
835 ast::LitInt(v, _) => v as u64,
836 ast::LitUint(v, _) => v,
837 ast::LitIntUnsuffixed(v) => v as u64,
842 is_valid(norm_binop, lit_val, min, max)
848 fn is_comparison(binop: ast::BinOp) -> bool {
850 ast::BiEq | ast::BiLt | ast::BiLe |
851 ast::BiNe | ast::BiGe | ast::BiGt => true,
857 fn check_item_ctypes(cx: &Context, it: &ast::Item) {
858 fn check_ty(cx: &Context, ty: &ast::Ty) {
860 ast::TyPath(_, _, id) => {
861 match cx.tcx.def_map.borrow().get_copy(&id) {
862 ast::DefPrimTy(ast::TyInt(ast::TyI)) => {
863 cx.span_lint(CTypes, ty.span,
864 "found rust type `int` in foreign module, while \
865 libc::c_int or libc::c_long should be used");
867 ast::DefPrimTy(ast::TyUint(ast::TyU)) => {
868 cx.span_lint(CTypes, ty.span,
869 "found rust type `uint` in foreign module, while \
870 libc::c_uint or libc::c_ulong should be used");
872 ast::DefTy(def_id) => {
873 if !adt::is_ffi_safe(cx.tcx, def_id) {
874 cx.span_lint(CTypes, ty.span,
875 "found enum type without foreign-function-safe \
876 representation annotation in foreign module");
877 // hmm... this message could be more helpful
883 ast::TyPtr(ref mt) => { check_ty(cx, mt.ty) }
888 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
889 for input in decl.inputs.iter() {
890 check_ty(cx, input.ty);
892 check_ty(cx, decl.output)
896 ast::ItemForeignMod(ref nmod) if nmod.abi != abi::RustIntrinsic => {
897 for ni in nmod.items.iter() {
899 ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, decl),
900 ast::ForeignItemStatic(t, _) => check_ty(cx, t)
904 _ => {/* nothing to do */ }
908 fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
909 let xs = [ManagedHeapMemory, OwnedHeapMemory, HeapMemory];
910 for &lint in xs.iter() {
911 if cx.get_level(lint) == allow { continue }
915 ty::fold_ty(cx.tcx, ty, |t| {
916 match ty::get(t).sty {
920 ty::ty_uniq(_) | ty::ty_str(ty::VstoreUniq) |
921 ty::ty_vec(_, ty::VstoreUniq) |
922 ty::ty_trait(~ty::TyTrait { store: ty::UniqTraitStore, .. }) => {
925 ty::ty_closure(ref c) if c.sigil == ast::OwnedSigil => {
934 if n_uniq > 0 && lint != ManagedHeapMemory {
935 let s = ty_to_str(cx.tcx, ty);
936 let m = format!("type uses owned (~ type) pointers: {}", s);
937 cx.span_lint(lint, span, m);
940 if n_box > 0 && lint != OwnedHeapMemory {
941 let s = ty_to_str(cx.tcx, ty);
942 let m = format!("type uses managed (@ type) pointers: {}", s);
943 cx.span_lint(lint, span, m);
948 fn check_heap_item(cx: &Context, it: &ast::Item) {
953 ast::ItemStruct(..) => check_heap_type(cx, it.span,
954 ty::node_id_to_type(cx.tcx,
959 // If it's a struct, we also have to check the fields' types
961 ast::ItemStruct(struct_def, _) => {
962 for struct_field in struct_def.fields.iter() {
963 check_heap_type(cx, struct_field.span,
964 ty::node_id_to_type(cx.tcx,
965 struct_field.node.id));
972 struct RawPtrDerivingVisitor<'a> {
976 impl<'a> Visitor<()> for RawPtrDerivingVisitor<'a> {
977 fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
978 static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
980 ast::TyPtr(..) => self.cx.span_lint(RawPointerDeriving, ty.span, MSG),
983 visit::walk_ty(self, ty, ());
985 // explicit override to a no-op to reduce code bloat
986 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
987 fn visit_block(&mut self, _: &ast::Block, _: ()) {}
990 fn check_raw_ptr_deriving(cx: &Context, item: &ast::Item) {
991 if !attr::contains_name(item.attrs.as_slice(), "deriving") {
995 ast::ItemStruct(..) | ast::ItemEnum(..) => {
996 let mut visitor = RawPtrDerivingVisitor { cx: cx };
997 visit::walk_item(&mut visitor, item, ());
1003 static crate_attrs: &'static [&'static str] = &[
1004 "crate_type", "feature", "no_start", "no_main", "no_std", "crate_id",
1005 "desc", "comment", "license", "copyright", // not used in rustc now
1009 static obsolete_attrs: &'static [(&'static str, &'static str)] = &[
1010 ("abi", "Use `extern \"abi\" fn` instead"),
1011 ("auto_encode", "Use `#[deriving(Encodable)]` instead"),
1012 ("auto_decode", "Use `#[deriving(Decodable)]` instead"),
1013 ("fast_ffi", "Remove it"),
1014 ("fixed_stack_segment", "Remove it"),
1015 ("rust_stack", "Remove it"),
1018 static other_attrs: &'static [&'static str] = &[
1020 "address_insignificant", // can be crate-level too
1021 "thread_local", // for statics
1022 "allow", "deny", "forbid", "warn", // lint options
1023 "deprecated", "experimental", "unstable", "stable", "locked", "frozen", //item stability
1024 "cfg", "doc", "export_name", "link_section",
1025 "no_mangle", "static_assert", "unsafe_no_drop_flag", "packed",
1026 "simd", "repr", "deriving", "unsafe_destructor", "link", "phase",
1027 "macro_export", "must_use", "automatically_derived",
1030 "path", "link_name", "link_args", "macro_escape", "no_implicit_prelude",
1033 "test", "bench", "should_fail", "ignore", "inline", "lang", "main", "start",
1034 "no_split_stack", "cold", "macro_registrar", "linkage",
1036 // internal attribute: bypass privacy inside items
1037 "!resolve_unexported",
1040 fn check_crate_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
1042 for attr in attrs.iter() {
1043 let name = attr.node.value.name();
1044 let mut iter = crate_attrs.iter().chain(other_attrs.iter());
1045 if !iter.any(|other_attr| { name.equiv(other_attr) }) {
1046 cx.span_lint(AttributeUsage, attr.span, "unknown crate attribute");
1048 if name.equiv(& &"link") {
1049 cx.tcx.sess.span_err(attr.span,
1050 "obsolete crate `link` attribute");
1051 cx.tcx.sess.note("the link attribute has been superceded by the crate_id \
1052 attribute, which has the format `#[crate_id = \"name#version\"]`");
1057 fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
1058 // check if element has crate-level, obsolete, or any unknown attributes.
1060 for attr in attrs.iter() {
1061 let name = attr.node.value.name();
1062 for crate_attr in crate_attrs.iter() {
1063 if name.equiv(crate_attr) {
1064 let msg = match attr.node.style {
1065 ast::AttrOuter => "crate-level attribute should be an inner attribute: \
1066 add an exclamation mark: #![foo]",
1067 ast::AttrInner => "crate-level attribute should be in the root module",
1069 cx.span_lint(AttributeUsage, attr.span, msg);
1074 for &(obs_attr, obs_alter) in obsolete_attrs.iter() {
1075 if name.equiv(&obs_attr) {
1076 cx.span_lint(AttributeUsage, attr.span,
1077 format!("obsolete attribute: {:s}", obs_alter));
1082 if !other_attrs.iter().any(|other_attr| { name.equiv(other_attr) }) {
1083 cx.span_lint(AttributeUsage, attr.span, "unknown attribute");
1088 fn check_heap_expr(cx: &Context, e: &ast::Expr) {
1089 let ty = ty::expr_ty(cx.tcx, e);
1090 check_heap_type(cx, e.span, ty);
1093 fn check_path_statement(cx: &Context, s: &ast::Stmt) {
1095 ast::StmtSemi(expr, _) => {
1097 ast::ExprPath(_) => {
1098 cx.span_lint(PathStatement,
1100 "path statement with no effect");
1109 fn check_unused_result(cx: &Context, s: &ast::Stmt) {
1110 let expr = match s.node {
1111 ast::StmtSemi(expr, _) => expr,
1114 let t = ty::expr_ty(cx.tcx, expr);
1115 match ty::get(t).sty {
1116 ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
1120 ast::ExprRet(..) => return,
1124 let t = ty::expr_ty(cx.tcx, expr);
1125 let mut warned = false;
1126 match ty::get(t).sty {
1127 ty::ty_struct(did, _) |
1128 ty::ty_enum(did, _) => {
1129 if ast_util::is_local(did) {
1130 match cx.tcx.map.get(did.node) {
1131 ast_map::NodeItem(it) => {
1132 if attr::contains_name(it.attrs.as_slice(),
1134 cx.span_lint(UnusedMustUse, s.span,
1135 "unused result which must be used");
1142 csearch::get_item_attrs(&cx.tcx.sess.cstore, did, |attrs| {
1143 if attr::contains_name(attrs.as_slice(), "must_use") {
1144 cx.span_lint(UnusedMustUse, s.span,
1145 "unused result which must be used");
1154 cx.span_lint(UnusedResult, s.span, "unused result");
1158 fn check_deprecated_owned_vector(cx: &Context, e: &ast::Expr) {
1159 let t = ty::expr_ty(cx.tcx, e);
1160 match ty::get(t).sty {
1161 ty::ty_vec(_, ty::VstoreUniq) => {
1162 cx.span_lint(DeprecatedOwnedVector, e.span,
1163 "use of deprecated `~[]` vector; replaced by `std::vec::Vec`")
1169 fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
1170 fn is_camel_case(ident: ast::Ident) -> bool {
1171 let ident = token::get_ident(ident);
1172 assert!(!ident.get().is_empty());
1173 let ident = ident.get().trim_chars(&'_');
1175 // start with a non-lowercase letter rather than non-uppercase
1176 // ones (some scripts don't have a concept of upper/lowercase)
1177 !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
1180 fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1181 if !is_camel_case(ident) {
1183 NonCamelCaseTypes, span,
1184 format!("{} `{}` should have a camel case identifier",
1185 sort, token::get_ident(ident)));
1190 ast::ItemTy(..) | ast::ItemStruct(..) => {
1191 check_case(cx, "type", it.ident, it.span)
1193 ast::ItemTrait(..) => {
1194 check_case(cx, "trait", it.ident, it.span)
1196 ast::ItemEnum(ref enum_definition, _) => {
1197 check_case(cx, "type", it.ident, it.span);
1198 for variant in enum_definition.variants.iter() {
1199 check_case(cx, "variant", variant.node.name, variant.span);
1206 fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) {
1208 // only check static constants
1209 ast::ItemStatic(_, ast::MutImmutable, _) => {
1210 let s = token::get_ident(it.ident);
1211 // check for lowercase letters rather than non-uppercase
1212 // ones (some scripts don't have a concept of
1214 if s.get().chars().any(|c| c.is_lowercase()) {
1215 cx.span_lint(NonUppercaseStatics, it.span,
1216 "static constant should have an uppercase identifier");
1223 fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
1224 // Lint for constants that look like binding identifiers (#7526)
1225 match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
1226 (&ast::PatIdent(_, ref path, _), Some(&ast::DefStatic(_, false))) => {
1227 // last identifier alone is right choice for this lint.
1228 let ident = path.segments.last().unwrap().identifier;
1229 let s = token::get_ident(ident);
1230 if s.get().chars().any(|c| c.is_lowercase()) {
1231 cx.span_lint(NonUppercasePatternStatics, path.span,
1232 "static constant in pattern should be all caps");
1239 fn check_pat_uppercase_variable(cx: &Context, p: &ast::Pat) {
1241 &ast::PatIdent(_, ref path, _) => {
1242 match cx.tcx.def_map.borrow().find(&p.id) {
1243 Some(&ast::DefLocal(_, _)) | Some(&ast::DefBinding(_, _)) |
1244 Some(&ast::DefArg(_, _)) => {
1245 // last identifier alone is right choice for this lint.
1246 let ident = path.segments.last().unwrap().identifier;
1247 let s = token::get_ident(ident);
1248 if s.get().char_at(0).is_uppercase() {
1252 "variable names should start with a lowercase character");
1262 fn check_struct_uppercase_variable(cx: &Context, s: &ast::StructDef) {
1263 for sf in s.fields.iter() {
1265 ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
1266 let s = token::get_ident(ident);
1267 if s.get().char_at(0).is_uppercase() {
1271 "structure field names should start with a lowercase character");
1279 fn check_unnecessary_parens_core(cx: &Context, value: &ast::Expr, msg: &str) {
1281 ast::ExprParen(_) => {
1282 cx.span_lint(UnnecessaryParens, value.span,
1283 format!("unnecessary parentheses around {}", msg))
1289 fn check_unnecessary_parens_expr(cx: &Context, e: &ast::Expr) {
1290 let (value, msg) = match e.node {
1291 ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
1292 ast::ExprWhile(cond, _) => (cond, "`while` condition"),
1293 ast::ExprMatch(head, _) => (head, "`match` head expression"),
1294 ast::ExprRet(Some(value)) => (value, "`return` value"),
1295 ast::ExprAssign(_, value) => (value, "assigned value"),
1296 ast::ExprAssignOp(_, _, value) => (value, "assigned value"),
1299 check_unnecessary_parens_core(cx, value, msg);
1302 fn check_unnecessary_parens_stmt(cx: &Context, s: &ast::Stmt) {
1303 let (value, msg) = match s.node {
1304 ast::StmtDecl(decl, _) => match decl.node {
1305 ast::DeclLocal(local) => match local.init {
1306 Some(value) => (value, "assigned value"),
1313 check_unnecessary_parens_core(cx, value, msg);
1316 fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
1318 // Don't warn about generated blocks, that'll just pollute the output.
1319 ast::ExprBlock(ref blk) => {
1320 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1321 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1322 cx.span_lint(UnusedUnsafe, blk.span,
1323 "unnecessary `unsafe` block");
1330 fn check_unsafe_block(cx: &Context, e: &ast::Expr) {
1332 // Don't warn about generated blocks, that'll just pollute the output.
1333 ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1334 cx.span_lint(UnsafeBlock, blk.span, "usage of an `unsafe` block");
1340 fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
1342 ast::PatIdent(ast::BindByValue(ast::MutMutable),
1343 ref path, _) if pat_util::pat_is_binding(cx.tcx.def_map, p)=> {
1344 // `let mut _a = 1;` doesn't need a warning.
1345 let initial_underscore = if path.segments.len() == 1 {
1346 token::get_ident(path.segments
1348 .identifier).get().starts_with("_")
1350 cx.tcx.sess.span_bug(p.span,
1351 "mutable binding that doesn't consist \
1352 of exactly one segment")
1355 if !initial_underscore &&
1356 !cx.tcx.used_mut_nodes.borrow().contains(&p.id) {
1357 cx.span_lint(UnusedMut, p.span,
1358 "variable does not need to be mutable");
1370 fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
1371 // Warn if string and vector literals with sigils, or boxing expressions,
1372 // are immediately borrowed.
1373 let allocation = match e.node {
1374 ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
1376 ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1379 ast::ExprVec(..) => VectorAllocation,
1383 ast::ExprUnary(ast::UnUniq, _) |
1384 ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
1389 let report = |msg| {
1390 cx.span_lint(UnnecessaryAllocation, e.span, msg);
1393 match cx.tcx.adjustments.borrow().find_copy(&e.id) {
1394 Some(adjustment) => {
1396 ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1397 match (allocation, autoref) {
1398 (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1399 report("unnecessary allocation, the sigil can be \
1403 Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1404 report("unnecessary allocation, use & instead");
1407 Some(ty::AutoPtr(_, ast::MutMutable))) => {
1408 report("unnecessary allocation, use &mut \
1422 fn check_missing_doc_attrs(cx: &Context,
1423 id: Option<ast::NodeId>,
1424 attrs: &[ast::Attribute],
1426 desc: &'static str) {
1427 // If we're building a test harness, then warning about
1428 // documentation is probably not really relevant right now.
1429 if cx.tcx.sess.opts.test { return }
1431 // `#[doc(hidden)]` disables missing_doc check.
1432 if cx.is_doc_hidden { return }
1434 // Only check publicly-visible items, using the result from the privacy pass. It's an option so
1435 // the crate root can also use this function (it doesn't have a NodeId).
1437 Some(ref id) if !cx.exported_items.contains(id) => return,
1441 let has_doc = attrs.iter().any(|a| {
1442 match a.node.value.node {
1443 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1448 cx.span_lint(MissingDoc, sp,
1449 format!("missing documentation for {}", desc));
1453 fn check_missing_doc_item(cx: &Context, it: &ast::Item) {
1454 let desc = match it.node {
1455 ast::ItemFn(..) => "a function",
1456 ast::ItemMod(..) => "a module",
1457 ast::ItemEnum(..) => "an enum",
1458 ast::ItemStruct(..) => "a struct",
1459 ast::ItemTrait(..) => "a trait",
1462 check_missing_doc_attrs(cx,
1464 it.attrs.as_slice(),
1469 fn check_missing_doc_method(cx: &Context, m: &ast::Method) {
1470 let did = ast::DefId {
1471 krate: ast::LOCAL_CRATE,
1475 match cx.tcx.methods.borrow().find(&did).map(|method| *method) {
1476 None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
1478 match md.container {
1479 // Always check default methods defined on traits.
1480 ty::TraitContainer(..) => {}
1481 // For methods defined on impls, it depends on whether
1482 // it is an implementation for a trait or is a plain
1484 ty::ImplContainer(cid) => {
1485 match ty::impl_trait_ref(cx.tcx, cid) {
1486 Some(..) => return, // impl for trait: don't doc
1487 None => {} // plain impl: doc according to privacy
1493 check_missing_doc_attrs(cx,
1500 fn check_missing_doc_ty_method(cx: &Context, tm: &ast::TypeMethod) {
1501 check_missing_doc_attrs(cx,
1503 tm.attrs.as_slice(),
1508 fn check_missing_doc_struct_field(cx: &Context, sf: &ast::StructField) {
1509 match sf.node.kind {
1510 ast::NamedField(_, vis) if vis == ast::Public =>
1511 check_missing_doc_attrs(cx,
1512 Some(cx.cur_struct_def_id),
1513 sf.node.attrs.as_slice(),
1520 fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) {
1521 check_missing_doc_attrs(cx,
1523 v.node.attrs.as_slice(),
1528 /// Checks for use of items with #[deprecated], #[experimental] and
1529 /// #[unstable] (or none of them) attributes.
1530 fn check_stability(cx: &Context, e: &ast::Expr) {
1531 let id = match e.node {
1532 ast::ExprPath(..) | ast::ExprStruct(..) => {
1533 match cx.tcx.def_map.borrow().find(&e.id) {
1534 Some(&def) => ast_util::def_id_of_def(def),
1538 ast::ExprMethodCall(..) => {
1539 let method_call = typeck::MethodCall::expr(e.id);
1540 match cx.method_map.borrow().find(&method_call) {
1542 match method.origin {
1543 typeck::MethodStatic(def_id) => {
1544 // If this implements a trait method, get def_id
1545 // of the method inside trait definition.
1546 // Otherwise, use the current def_id (which refers
1547 // to the method inside impl).
1548 ty::trait_method_of_method(
1549 cx.tcx, def_id).unwrap_or(def_id)
1551 typeck::MethodParam(typeck::MethodParam {
1556 | typeck::MethodObject(typeck::MethodObject {
1560 }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1569 let stability = if ast_util::is_local(id) {
1571 let s = cx.tcx.map.with_attrs(id.node, |attrs| {
1573 attr::find_stability(a.iter().map(|a| a.meta()))
1579 // no possibility of having attributes
1580 // (e.g. it's a local variable), so just
1588 // run through all the attributes and take the first
1590 csearch::get_item_attrs(&cx.tcx.sess.cstore, id, |meta_items| {
1592 s = attr::find_stability(meta_items.move_iter())
1598 let (lint, label) = match stability {
1599 // no stability attributes == Unstable
1600 None => (Unstable, "unmarked"),
1601 Some(attr::Stability { level: attr::Unstable, .. }) =>
1602 (Unstable, "unstable"),
1603 Some(attr::Stability { level: attr::Experimental, .. }) =>
1604 (Experimental, "experimental"),
1605 Some(attr::Stability { level: attr::Deprecated, .. }) =>
1606 (Deprecated, "deprecated"),
1610 let msg = match stability {
1611 Some(attr::Stability { text: Some(ref s), .. }) => {
1612 format!("use of {} item: {}", label, *s)
1614 _ => format!("use of {} item", label)
1617 cx.span_lint(lint, e.span, msg);
1620 impl<'a> Visitor<()> for Context<'a> {
1621 fn visit_item(&mut self, it: &ast::Item, _: ()) {
1622 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
1623 check_item_ctypes(cx, it);
1624 check_item_non_camel_case_types(cx, it);
1625 check_item_non_uppercase_statics(cx, it);
1626 check_heap_item(cx, it);
1627 check_missing_doc_item(cx, it);
1628 check_attrs_usage(cx, it.attrs.as_slice());
1629 check_raw_ptr_deriving(cx, it);
1631 cx.visit_ids(|v| v.visit_item(it, ()));
1633 visit::walk_item(cx, it, ());
1637 fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
1638 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
1639 check_attrs_usage(cx, it.attrs.as_slice());
1640 visit::walk_foreign_item(cx, it, ());
1644 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
1645 self.with_lint_attrs(i.attrs.as_slice(), |cx| {
1646 check_attrs_usage(cx, i.attrs.as_slice());
1647 visit::walk_view_item(cx, i, ());
1651 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
1652 check_pat_non_uppercase_statics(self, p);
1653 check_pat_uppercase_variable(self, p);
1654 check_unused_mut_pat(self, p);
1656 visit::walk_pat(self, p, ());
1659 fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
1661 ast::ExprUnary(ast::UnNeg, expr) => {
1662 // propagate negation, if the negation itself isn't negated
1663 if self.negated_expr_id != e.id {
1664 self.negated_expr_id = expr.id;
1667 ast::ExprParen(expr) => if self.negated_expr_id == e.id {
1668 self.negated_expr_id = expr.id
1673 check_while_true_expr(self, e);
1674 check_stability(self, e);
1675 check_unnecessary_parens_expr(self, e);
1676 check_unused_unsafe(self, e);
1677 check_unsafe_block(self, e);
1678 check_unnecessary_allocation(self, e);
1679 check_heap_expr(self, e);
1681 check_type_limits(self, e);
1682 check_unused_casts(self, e);
1683 check_deprecated_owned_vector(self, e);
1685 visit::walk_expr(self, e, ());
1688 fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
1689 check_path_statement(self, s);
1690 check_unused_result(self, s);
1691 check_unnecessary_parens_stmt(self, s);
1693 visit::walk_stmt(self, s, ());
1696 fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
1697 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
1698 let recurse = |this: &mut Context| {
1699 visit::walk_fn(this, fk, decl, body, span, id, ());
1703 visit::FkMethod(_, _, m) => {
1704 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
1705 check_missing_doc_method(cx, m);
1706 check_attrs_usage(cx, m.attrs.as_slice());
1709 v.visit_fn(fk, decl, body, span, id, ());
1719 fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
1720 self.with_lint_attrs(t.attrs.as_slice(), |cx| {
1721 check_missing_doc_ty_method(cx, t);
1722 check_attrs_usage(cx, t.attrs.as_slice());
1724 visit::walk_ty_method(cx, t, ());
1728 fn visit_struct_def(&mut self,
1734 check_struct_uppercase_variable(self, s);
1736 let old_id = self.cur_struct_def_id;
1737 self.cur_struct_def_id = id;
1738 visit::walk_struct_def(self, s, i, g, id, ());
1739 self.cur_struct_def_id = old_id;
1742 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1743 self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
1744 check_missing_doc_struct_field(cx, s);
1745 check_attrs_usage(cx, s.node.attrs.as_slice());
1747 visit::walk_struct_field(cx, s, ());
1751 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1752 self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
1753 check_missing_doc_variant(cx, v);
1754 check_attrs_usage(cx, v.node.attrs.as_slice());
1756 visit::walk_variant(cx, v, g, ());
1760 // FIXME(#10894) should continue recursing
1761 fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
1764 impl<'a> IdVisitingOperation for Context<'a> {
1765 fn visit_id(&self, id: ast::NodeId) {
1766 match self.tcx.sess.lints.borrow_mut().pop(&id) {
1769 for (lint, span, msg) in l.move_iter() {
1770 self.span_lint(lint, span, msg)
1777 pub fn check_crate(tcx: &ty::ctxt,
1778 method_map: typeck::MethodMap,
1779 exported_items: &privacy::ExportedItems,
1780 krate: &ast::Crate) {
1781 let mut cx = Context {
1782 dict: @get_lint_dict(),
1783 cur: SmallIntMap::new(),
1785 method_map: method_map,
1786 exported_items: exported_items,
1787 cur_struct_def_id: -1,
1788 is_doc_hidden: false,
1789 lint_stack: Vec::new(),
1793 // Install default lint levels, followed by the command line levels, and
1794 // then actually visit the whole crate.
1795 for (_, spec) in cx.dict.iter() {
1796 cx.set_level(spec.lint, spec.default, Default);
1798 for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1799 cx.set_level(lint, level, CommandLine);
1801 cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
1802 cx.visit_id(ast::CRATE_NODE_ID);
1804 v.visited_outermost = true;
1805 visit::walk_crate(v, krate, ());
1808 check_crate_attrs_usage(cx, krate.attrs.as_slice());
1809 // since the root module isn't visited as an item (because it isn't an item), warn for it
1811 check_missing_doc_attrs(cx,
1813 krate.attrs.as_slice(),
1817 visit::walk_crate(cx, krate, ());
1820 // If we missed any lints added to the session, then there's a bug somewhere
1821 // in the iteration code.
1822 for (id, v) in tcx.sess.lints.borrow().iter() {
1823 for &(lint, span, ref msg) in v.iter() {
1824 tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}",
1825 lint, tcx.map.node_to_str(*id), *msg))
1829 tcx.sess.abort_if_errors();