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;
63 use syntax::ast_util::IdVisitingOperation;
64 use syntax::attr::{AttrMetaMethods, AttributeMethods};
66 use syntax::codemap::Span;
67 use syntax::parse::token::InternedString;
68 use syntax::parse::token;
69 use syntax::visit::Visitor;
70 use syntax::{ast, ast_util, visit};
72 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
76 UnnecessaryQualification,
82 NonUppercasePatternStatics,
100 UnnecessaryAllocation,
115 DeprecatedOwnedVector,
122 pub fn level_to_str(lv: level) -> &'static str {
131 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
133 allow, warn, deny, forbid
136 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
137 pub struct LintSpec {
143 pub type LintDict = HashMap<&'static str, LintSpec>;
152 static lint_table: &'static [(&'static str, LintSpec)] = &[
156 desc: "proper use of std::libc types in foreign modules",
163 desc: "imports that are never used",
167 ("unnecessary_qualification",
169 lint: UnnecessaryQualification,
170 desc: "detects unnecessarily qualified names",
177 desc: "suggest using `loop { }` instead of `while true { }`",
184 desc: "path statements with no effect",
188 ("unrecognized_lint",
190 lint: UnrecognizedLint,
191 desc: "unrecognized lint attribute",
195 ("non_camel_case_types",
197 lint: NonCamelCaseTypes,
198 desc: "types, variants and traits should have camel case names",
202 ("non_uppercase_statics",
204 lint: NonUppercaseStatics,
205 desc: "static constants should have uppercase identifiers",
209 ("non_uppercase_pattern_statics",
211 lint: NonUppercasePatternStatics,
212 desc: "static constants in match patterns should be all caps",
216 ("uppercase_variables",
218 lint: UppercaseVariables,
219 desc: "variable and structure field names should start with a lowercase character",
223 ("unnecessary_parens",
225 lint: UnnecessaryParens,
226 desc: "`if`, `match`, `while` and `return` do not need parentheses",
230 ("managed_heap_memory",
232 lint: ManagedHeapMemory,
233 desc: "use of managed (@ type) heap memory",
237 ("owned_heap_memory",
239 lint: OwnedHeapMemory,
240 desc: "use of owned (~ type) heap memory",
247 desc: "use of any (~ type or @ type) heap memory",
254 desc: "comparisons made useless by limits of the types involved",
261 desc: "literal out of range for its type",
269 desc: "unnecessary use of an `unsafe` block",
276 desc: "usage of an `unsafe` block",
282 lint: AttributeUsage,
283 desc: "detects bad use of attributes",
289 lint: UnusedVariable,
290 desc: "detect variables which are not used in any way",
296 lint: DeadAssignment,
297 desc: "detect assignments that will never be read",
301 ("unnecessary_typecast",
303 lint: UnnecessaryTypecast,
304 desc: "detects unnecessary type casts, that can be removed",
311 desc: "detect mut variables which don't need to be mutable",
315 ("unnecessary_allocation",
317 lint: UnnecessaryAllocation,
318 desc: "detects unnecessary allocations that can be eliminated",
325 desc: "detect piece of code that will never be used",
328 ("visible_private_types",
330 lint: VisiblePrivateTypes,
331 desc: "detect use of private types in exported type signatures",
338 desc: "detects missing documentation for public members",
344 lint: UnreachableCode,
345 desc: "detects unreachable code",
352 desc: "detects use of #[deprecated] items",
359 desc: "detects use of #[experimental] items",
366 desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
373 desc: "mass-change the level for lints which produce warnings",
379 lint: UnknownFeatures,
380 desc: "unknown features found in crate-level #[feature] directives",
384 ("unknown_crate_type",
386 lint: UnknownCrateType,
387 desc: "unknown crate type found in #[crate_type] directive",
394 desc: "unused result of a type flagged as #[must_use]",
401 desc: "unused result of an expression in a statement",
405 ("deprecated_owned_vector",
407 lint: DeprecatedOwnedVector,
408 desc: "use of a `~[T]` vector",
412 ("raw_pointer_deriving",
414 lint: RawPointerDeriving,
415 desc: "uses of #[deriving] with raw pointers are rarely correct",
421 Pass names should not contain a '-', as the compiler normalizes
422 '-' to '_' in command-line flags
424 pub fn get_lint_dict() -> LintDict {
425 let mut map = HashMap::new();
426 for &(k, v) in lint_table.iter() {
433 // All known lint modes (string versions)
435 // Current levels of each lint warning
436 cur: SmallIntMap<(level, LintSource)>,
437 // context we're checking in (used to access fields like sess)
439 // maps from an expression id that corresponds to a method call to the
440 // details of the method to be invoked
441 method_map: typeck::MethodMap,
442 // Items exported by the crate; used by the missing_doc lint.
443 exported_items: &'a privacy::ExportedItems,
444 // The id of the current `ast::StructDef` being walked.
445 cur_struct_def_id: ast::NodeId,
446 // Whether some ancestor of the current node was marked
450 // When recursing into an attributed node of the ast which modifies lint
451 // levels, this stack keeps track of the previous lint levels of whatever
453 lint_stack: Vec<(Lint, level, LintSource)> ,
455 // id of the last visited negated expression
456 negated_expr_id: ast::NodeId
459 impl<'a> Context<'a> {
460 fn get_level(&self, lint: Lint) -> level {
461 match self.cur.find(&(lint as uint)) {
462 Some(&(lvl, _)) => lvl,
467 fn get_source(&self, lint: Lint) -> LintSource {
468 match self.cur.find(&(lint as uint)) {
469 Some(&(_, src)) => src,
474 fn set_level(&mut self, lint: Lint, level: level, src: LintSource) {
476 self.cur.remove(&(lint as uint));
478 self.cur.insert(lint as uint, (level, src));
482 fn lint_to_str(&self, lint: Lint) -> &'static str {
483 for (k, v) in self.dict.iter() {
488 fail!("unregistered lint {:?}", lint);
491 fn span_lint(&self, lint: Lint, span: Span, msg: &str) {
492 let (level, src) = match self.cur.find(&(lint as uint)) {
494 Some(&(warn, src)) => (self.get_level(Warnings), src),
497 if level == allow { return }
500 let msg = match src {
502 format!("{}, \\#[{}({})] on by default", msg,
503 level_to_str(level), self.lint_to_str(lint))
506 format!("{} [-{} {}]", msg,
508 warn => 'W', deny => 'D', forbid => 'F',
510 }, self.lint_to_str(lint).replace("_", "-"))
518 warn => { self.tcx.sess.span_warn(span, msg); }
519 deny | forbid => { self.tcx.sess.span_err(span, msg); }
523 for &span in note.iter() {
524 self.tcx.sess.span_note(span, "lint level defined here");
529 * Merge the lints specified by any lint attributes into the
530 * current lint context, call the provided function, then reset the
531 * lints in effect to their previous state.
533 fn with_lint_attrs(&mut self,
534 attrs: &[ast::Attribute],
536 // Parse all of the lint attributes, and then add them all to the
537 // current dictionary of lint information. Along the way, keep a history
538 // of what we changed so we can roll everything back after invoking the
541 each_lint(&self.tcx.sess, attrs, |meta, level, lintname| {
542 match self.dict.find_equiv(&lintname) {
547 format!("unknown `{}` attribute: `{}`",
548 level_to_str(level), lintname));
551 let lint = lint.lint;
552 let now = self.get_level(lint);
553 if now == forbid && level != forbid {
554 self.tcx.sess.span_err(meta.span,
555 format!("{}({}) overruled by outer forbid({})",
557 lintname, lintname));
558 } else if now != level {
559 let src = self.get_source(lint);
560 self.lint_stack.push((lint, now, src));
562 self.set_level(lint, level, Node(meta.span));
569 let old_is_doc_hidden = self.is_doc_hidden;
571 self.is_doc_hidden ||
574 attr.name().equiv(&("doc")) &&
575 match attr.meta_item_list() {
578 attr::contains_name(l.as_slice(), "hidden")
586 self.is_doc_hidden = old_is_doc_hidden;
587 for _ in range(0, pushed) {
588 let (lint, lvl, src) = self.lint_stack.pop().unwrap();
589 self.set_level(lint, lvl, src);
593 fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
594 let mut v = ast_util::IdVisitor {
596 pass_through_items: false,
597 visited_outermost: false,
603 // Check that every lint from the list of attributes satisfies `f`.
604 // Return true if that's the case. Otherwise return false.
605 pub fn each_lint(sess: &session::Session,
606 attrs: &[ast::Attribute],
607 f: |@ast::MetaItem, level, InternedString| -> bool)
609 let xs = [allow, warn, deny, forbid];
610 for &level in xs.iter() {
611 let level_name = level_to_str(level);
612 for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
613 let meta = attr.node.value;
614 let metas = match meta.node {
615 ast::MetaList(_, ref metas) => metas,
617 sess.span_err(meta.span, "malformed lint attribute");
621 for meta in metas.iter() {
623 ast::MetaWord(ref lintname) => {
624 if !f(*meta, level, (*lintname).clone()) {
629 sess.span_err(meta.span, "malformed lint attribute");
638 // Check from a list of attributes if it contains the appropriate
639 // `#[level(lintname)]` attribute (e.g. `#[allow(dead_code)]).
640 pub fn contains_lint(attrs: &[ast::Attribute],
642 lintname: &'static str)
644 let level_name = level_to_str(level);
645 for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
646 if attr.meta_item_list().is_none() {
649 let list = attr.meta_item_list().unwrap();
650 for meta_item in list.iter() {
651 if meta_item.name().equiv(&lintname) {
659 fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
661 ast::ExprWhile(cond, _) => {
663 ast::ExprLit(lit) => {
665 ast::LitBool(true) => {
666 cx.span_lint(WhileTrue,
668 "denote infinite loops with loop \
680 impl<'a> AstConv for Context<'a>{
681 fn tcx<'a>(&'a self) -> &'a ty::ctxt { self.tcx }
683 fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
684 ty::lookup_item_type(self.tcx, id)
687 fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef {
688 ty::lookup_trait_def(self.tcx, id)
691 fn ty_infer(&self, _span: Span) -> ty::t {
692 infer::new_infer_ctxt(self.tcx).next_ty_var()
697 fn check_unused_casts(cx: &Context, e: &ast::Expr) {
698 return match e.node {
699 ast::ExprCast(expr, ty) => {
700 let t_t = ast_ty_to_ty(cx, &infer::new_infer_ctxt(cx.tcx), ty);
701 if ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty {
702 cx.span_lint(UnnecessaryTypecast, ty.span,
703 "unnecessary type cast");
710 fn check_type_limits(cx: &Context, e: &ast::Expr) {
711 return match e.node {
712 ast::ExprBinary(binop, l, r) => {
713 if is_comparison(binop) && !check_limits(cx.tcx, binop, l, r) {
714 cx.span_lint(TypeLimits, e.span,
715 "comparison is useless due to type limits");
718 ast::ExprLit(lit) => {
719 match ty::get(ty::expr_ty(cx.tcx, e)).sty {
721 let int_type = if t == ast::TyI {
722 cx.tcx.sess.targ_cfg.int_type
724 let (min, max) = int_ty_range(int_type);
725 let mut lit_val: i64 = match lit.node {
726 ast::LitInt(v, _) => v,
727 ast::LitUint(v, _) => v as i64,
728 ast::LitIntUnsuffixed(v) => v,
731 if cx.negated_expr_id == e.id {
734 if lit_val < min || lit_val > max {
735 cx.span_lint(TypeOverflow, e.span,
736 "literal out of range for its type");
740 let uint_type = if t == ast::TyU {
741 cx.tcx.sess.targ_cfg.uint_type
743 let (min, max) = uint_ty_range(uint_type);
744 let lit_val: u64 = match lit.node {
745 ast::LitInt(v, _) => v as u64,
746 ast::LitUint(v, _) => v,
747 ast::LitIntUnsuffixed(v) => v as u64,
750 if lit_val < min || lit_val > max {
751 cx.span_lint(TypeOverflow, e.span,
752 "literal out of range for its type");
762 fn is_valid<T:cmp::Ord>(binop: ast::BinOp, v: T,
763 min: T, max: T) -> bool {
765 ast::BiLt => v <= max,
766 ast::BiLe => v < max,
767 ast::BiGt => v >= min,
768 ast::BiGe => v > min,
769 ast::BiEq | ast::BiNe => v >= min && v <= max,
774 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
776 ast::BiLt => ast::BiGt,
777 ast::BiLe => ast::BiGe,
778 ast::BiGt => ast::BiLt,
779 ast::BiGe => ast::BiLe,
784 // for int & uint, be conservative with the warnings, so that the
785 // warnings are consistent between 32- and 64-bit platforms
786 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
788 ast::TyI => (i64::MIN, i64::MAX),
789 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
790 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
791 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
792 ast::TyI64 => (i64::MIN, i64::MAX)
796 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
798 ast::TyU => (u64::MIN, u64::MAX),
799 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
800 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
801 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
802 ast::TyU64 => (u64::MIN, u64::MAX)
806 fn check_limits(tcx: &ty::ctxt, binop: ast::BinOp,
807 l: &ast::Expr, r: &ast::Expr) -> bool {
808 let (lit, expr, swap) = match (&l.node, &r.node) {
809 (&ast::ExprLit(_), _) => (l, r, true),
810 (_, &ast::ExprLit(_)) => (r, l, false),
813 // Normalize the binop so that the literal is always on the RHS in
815 let norm_binop = if swap { rev_binop(binop) } else { binop };
816 match ty::get(ty::expr_ty(tcx, expr)).sty {
817 ty::ty_int(int_ty) => {
818 let (min, max) = int_ty_range(int_ty);
819 let lit_val: i64 = match lit.node {
820 ast::ExprLit(li) => match li.node {
821 ast::LitInt(v, _) => v,
822 ast::LitUint(v, _) => v as i64,
823 ast::LitIntUnsuffixed(v) => v,
828 is_valid(norm_binop, lit_val, min, max)
830 ty::ty_uint(uint_ty) => {
831 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
832 let lit_val: u64 = match lit.node {
833 ast::ExprLit(li) => match li.node {
834 ast::LitInt(v, _) => v as u64,
835 ast::LitUint(v, _) => v,
836 ast::LitIntUnsuffixed(v) => v as u64,
841 is_valid(norm_binop, lit_val, min, max)
847 fn is_comparison(binop: ast::BinOp) -> bool {
849 ast::BiEq | ast::BiLt | ast::BiLe |
850 ast::BiNe | ast::BiGe | ast::BiGt => true,
856 fn check_item_ctypes(cx: &Context, it: &ast::Item) {
857 fn check_ty(cx: &Context, ty: &ast::Ty) {
859 ast::TyPath(_, _, id) => {
860 match cx.tcx.def_map.borrow().get_copy(&id) {
861 ast::DefPrimTy(ast::TyInt(ast::TyI)) => {
862 cx.span_lint(CTypes, ty.span,
863 "found rust type `int` in foreign module, while \
864 libc::c_int or libc::c_long should be used");
866 ast::DefPrimTy(ast::TyUint(ast::TyU)) => {
867 cx.span_lint(CTypes, ty.span,
868 "found rust type `uint` in foreign module, while \
869 libc::c_uint or libc::c_ulong should be used");
871 ast::DefTy(def_id) => {
872 if !adt::is_ffi_safe(cx.tcx, def_id) {
873 cx.span_lint(CTypes, ty.span,
874 "found enum type without foreign-function-safe \
875 representation annotation in foreign module");
876 // hmm... this message could be more helpful
882 ast::TyPtr(ref mt) => { check_ty(cx, mt.ty) }
887 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
888 for input in decl.inputs.iter() {
889 check_ty(cx, input.ty);
891 check_ty(cx, decl.output)
895 ast::ItemForeignMod(ref nmod) if !nmod.abis.is_intrinsic() => {
896 for ni in nmod.items.iter() {
898 ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, decl),
899 ast::ForeignItemStatic(t, _) => check_ty(cx, t)
903 _ => {/* nothing to do */ }
907 fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
908 let xs = [ManagedHeapMemory, OwnedHeapMemory, HeapMemory];
909 for &lint in xs.iter() {
910 if cx.get_level(lint) == allow { continue }
914 ty::fold_ty(cx.tcx, ty, |t| {
915 match ty::get(t).sty {
919 ty::ty_uniq(_) | ty::ty_str(ty::vstore_uniq) |
920 ty::ty_vec(_, ty::vstore_uniq) |
921 ty::ty_trait(~ty::TyTrait { store: ty::UniqTraitStore, .. }) => {
924 ty::ty_closure(ref c) if c.sigil == ast::OwnedSigil => {
933 if n_uniq > 0 && lint != ManagedHeapMemory {
934 let s = ty_to_str(cx.tcx, ty);
935 let m = format!("type uses owned (~ type) pointers: {}", s);
936 cx.span_lint(lint, span, m);
939 if n_box > 0 && lint != OwnedHeapMemory {
940 let s = ty_to_str(cx.tcx, ty);
941 let m = format!("type uses managed (@ type) pointers: {}", s);
942 cx.span_lint(lint, span, m);
947 fn check_heap_item(cx: &Context, it: &ast::Item) {
952 ast::ItemStruct(..) => check_heap_type(cx, it.span,
953 ty::node_id_to_type(cx.tcx,
958 // If it's a struct, we also have to check the fields' types
960 ast::ItemStruct(struct_def, _) => {
961 for struct_field in struct_def.fields.iter() {
962 check_heap_type(cx, struct_field.span,
963 ty::node_id_to_type(cx.tcx,
964 struct_field.node.id));
971 struct RawPtrDerivingVisitor<'a> {
975 impl<'a> Visitor<()> for RawPtrDerivingVisitor<'a> {
976 fn visit_ty(&mut self, ty: &ast::Ty, _: ()) {
977 static MSG: &'static str = "use of `#[deriving]` with a raw pointer";
979 ast::TyPtr(..) => self.cx.span_lint(RawPointerDeriving, ty.span, MSG),
982 visit::walk_ty(self, ty, ());
984 // explicit override to a no-op to reduce code bloat
985 fn visit_expr(&mut self, _: &ast::Expr, _: ()) {}
986 fn visit_block(&mut self, _: &ast::Block, _: ()) {}
989 fn check_raw_ptr_deriving(cx: &Context, item: &ast::Item) {
990 if !attr::contains_name(item.attrs.as_slice(), "deriving") {
994 ast::ItemStruct(..) | ast::ItemEnum(..) => {
995 let mut visitor = RawPtrDerivingVisitor { cx: cx };
996 visit::walk_item(&mut visitor, item, ());
1002 static crate_attrs: &'static [&'static str] = &[
1003 "crate_type", "feature", "no_start", "no_main", "no_std", "crate_id",
1004 "desc", "comment", "license", "copyright", // not used in rustc now
1008 static obsolete_attrs: &'static [(&'static str, &'static str)] = &[
1009 ("abi", "Use `extern \"abi\" fn` instead"),
1010 ("auto_encode", "Use `#[deriving(Encodable)]` instead"),
1011 ("auto_decode", "Use `#[deriving(Decodable)]` instead"),
1012 ("fast_ffi", "Remove it"),
1013 ("fixed_stack_segment", "Remove it"),
1014 ("rust_stack", "Remove it"),
1017 static other_attrs: &'static [&'static str] = &[
1019 "address_insignificant", // can be crate-level too
1020 "thread_local", // for statics
1021 "allow", "deny", "forbid", "warn", // lint options
1022 "deprecated", "experimental", "unstable", "stable", "locked", "frozen", //item stability
1023 "cfg", "doc", "export_name", "link_section",
1024 "no_mangle", "static_assert", "unsafe_no_drop_flag", "packed",
1025 "simd", "repr", "deriving", "unsafe_destructor", "link", "phase",
1026 "macro_export", "must_use", "automatically_derived",
1029 "path", "link_name", "link_args", "macro_escape", "no_implicit_prelude",
1032 "test", "bench", "should_fail", "ignore", "inline", "lang", "main", "start",
1033 "no_split_stack", "cold", "macro_registrar", "linkage",
1035 // internal attribute: bypass privacy inside items
1036 "!resolve_unexported",
1039 fn check_crate_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
1041 for attr in attrs.iter() {
1042 let name = attr.node.value.name();
1043 let mut iter = crate_attrs.iter().chain(other_attrs.iter());
1044 if !iter.any(|other_attr| { name.equiv(other_attr) }) {
1045 cx.span_lint(AttributeUsage, attr.span, "unknown crate attribute");
1047 if name.equiv(& &"link") {
1048 cx.tcx.sess.span_err(attr.span,
1049 "obsolete crate `link` attribute");
1050 cx.tcx.sess.note("the link attribute has been superceded by the crate_id \
1051 attribute, which has the format `#[crate_id = \"name#version\"]`");
1056 fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
1057 // check if element has crate-level, obsolete, or any unknown attributes.
1059 for attr in attrs.iter() {
1060 let name = attr.node.value.name();
1061 for crate_attr in crate_attrs.iter() {
1062 if name.equiv(crate_attr) {
1063 let msg = match attr.node.style {
1064 ast::AttrOuter => "crate-level attribute should be an inner attribute: \
1065 add semicolon at end",
1066 ast::AttrInner => "crate-level attribute should be in the root module",
1068 cx.span_lint(AttributeUsage, attr.span, msg);
1073 for &(obs_attr, obs_alter) in obsolete_attrs.iter() {
1074 if name.equiv(&obs_attr) {
1075 cx.span_lint(AttributeUsage, attr.span,
1076 format!("obsolete attribute: {:s}", obs_alter));
1081 if !other_attrs.iter().any(|other_attr| { name.equiv(other_attr) }) {
1082 cx.span_lint(AttributeUsage, attr.span, "unknown attribute");
1087 fn check_heap_expr(cx: &Context, e: &ast::Expr) {
1088 let ty = ty::expr_ty(cx.tcx, e);
1089 check_heap_type(cx, e.span, ty);
1092 fn check_path_statement(cx: &Context, s: &ast::Stmt) {
1094 ast::StmtSemi(expr, _) => {
1096 ast::ExprPath(_) => {
1097 cx.span_lint(PathStatement,
1099 "path statement with no effect");
1108 fn check_unused_result(cx: &Context, s: &ast::Stmt) {
1109 let expr = match s.node {
1110 ast::StmtSemi(expr, _) => expr,
1113 let t = ty::expr_ty(cx.tcx, expr);
1114 match ty::get(t).sty {
1115 ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
1119 ast::ExprRet(..) => return,
1123 let t = ty::expr_ty(cx.tcx, expr);
1124 let mut warned = false;
1125 match ty::get(t).sty {
1126 ty::ty_struct(did, _) |
1127 ty::ty_enum(did, _) => {
1128 if ast_util::is_local(did) {
1129 match cx.tcx.map.get(did.node) {
1130 ast_map::NodeItem(it) => {
1131 if attr::contains_name(it.attrs.as_slice(),
1133 cx.span_lint(UnusedMustUse, s.span,
1134 "unused result which must be used");
1141 csearch::get_item_attrs(&cx.tcx.sess.cstore, did, |attrs| {
1142 if attr::contains_name(attrs.as_slice(), "must_use") {
1143 cx.span_lint(UnusedMustUse, s.span,
1144 "unused result which must be used");
1153 cx.span_lint(UnusedResult, s.span, "unused result");
1157 fn check_deprecated_owned_vector(cx: &Context, e: &ast::Expr) {
1158 let t = ty::expr_ty(cx.tcx, e);
1159 match ty::get(t).sty {
1160 ty::ty_vec(_, ty::vstore_uniq) => {
1161 cx.span_lint(DeprecatedOwnedVector, e.span,
1162 "use of deprecated `~[]` vector; replaced by `std::vec::Vec`")
1168 fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
1169 fn is_camel_case(ident: ast::Ident) -> bool {
1170 let ident = token::get_ident(ident);
1171 assert!(!ident.get().is_empty());
1172 let ident = ident.get().trim_chars(&'_');
1174 // start with a non-lowercase letter rather than non-uppercase
1175 // ones (some scripts don't have a concept of upper/lowercase)
1176 !ident.char_at(0).is_lowercase() && !ident.contains_char('_')
1179 fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1180 if !is_camel_case(ident) {
1182 NonCamelCaseTypes, span,
1183 format!("{} `{}` should have a camel case identifier",
1184 sort, token::get_ident(ident)));
1189 ast::ItemTy(..) | ast::ItemStruct(..) => {
1190 check_case(cx, "type", it.ident, it.span)
1192 ast::ItemTrait(..) => {
1193 check_case(cx, "trait", it.ident, it.span)
1195 ast::ItemEnum(ref enum_definition, _) => {
1196 check_case(cx, "type", it.ident, it.span);
1197 for variant in enum_definition.variants.iter() {
1198 check_case(cx, "variant", variant.node.name, variant.span);
1205 fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) {
1207 // only check static constants
1208 ast::ItemStatic(_, ast::MutImmutable, _) => {
1209 let s = token::get_ident(it.ident);
1210 // check for lowercase letters rather than non-uppercase
1211 // ones (some scripts don't have a concept of
1213 if s.get().chars().any(|c| c.is_lowercase()) {
1214 cx.span_lint(NonUppercaseStatics, it.span,
1215 "static constant should have an uppercase identifier");
1222 fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
1223 // Lint for constants that look like binding identifiers (#7526)
1224 match (&p.node, cx.tcx.def_map.borrow().find(&p.id)) {
1225 (&ast::PatIdent(_, ref path, _), Some(&ast::DefStatic(_, false))) => {
1226 // last identifier alone is right choice for this lint.
1227 let ident = path.segments.last().unwrap().identifier;
1228 let s = token::get_ident(ident);
1229 if s.get().chars().any(|c| c.is_lowercase()) {
1230 cx.span_lint(NonUppercasePatternStatics, path.span,
1231 "static constant in pattern should be all caps");
1238 fn check_pat_uppercase_variable(cx: &Context, p: &ast::Pat) {
1240 &ast::PatIdent(_, ref path, _) => {
1241 match cx.tcx.def_map.borrow().find(&p.id) {
1242 Some(&ast::DefLocal(_, _)) | Some(&ast::DefBinding(_, _)) |
1243 Some(&ast::DefArg(_, _)) => {
1244 // last identifier alone is right choice for this lint.
1245 let ident = path.segments.last().unwrap().identifier;
1246 let s = token::get_ident(ident);
1247 if s.get().char_at(0).is_uppercase() {
1251 "variable names should start with a lowercase character");
1261 fn check_struct_uppercase_variable(cx: &Context, s: &ast::StructDef) {
1262 for sf in s.fields.iter() {
1264 ast::StructField_ { kind: ast::NamedField(ident, _), .. } => {
1265 let s = token::get_ident(ident);
1266 if s.get().char_at(0).is_uppercase() {
1270 "structure field names should start with a lowercase character");
1278 fn check_unnecessary_parens_core(cx: &Context, value: &ast::Expr, msg: &str) {
1280 ast::ExprParen(_) => {
1281 cx.span_lint(UnnecessaryParens, value.span,
1282 format!("unnecessary parentheses around {}", msg))
1288 fn check_unnecessary_parens_expr(cx: &Context, e: &ast::Expr) {
1289 let (value, msg) = match e.node {
1290 ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
1291 ast::ExprWhile(cond, _) => (cond, "`while` condition"),
1292 ast::ExprMatch(head, _) => (head, "`match` head expression"),
1293 ast::ExprRet(Some(value)) => (value, "`return` value"),
1294 ast::ExprAssign(_, value) => (value, "assigned value"),
1295 ast::ExprAssignOp(_, _, value) => (value, "assigned value"),
1298 check_unnecessary_parens_core(cx, value, msg);
1301 fn check_unnecessary_parens_stmt(cx: &Context, s: &ast::Stmt) {
1302 let (value, msg) = match s.node {
1303 ast::StmtDecl(decl, _) => match decl.node {
1304 ast::DeclLocal(local) => match local.init {
1305 Some(value) => (value, "assigned value"),
1312 check_unnecessary_parens_core(cx, value, msg);
1315 fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
1317 // Don't warn about generated blocks, that'll just pollute the output.
1318 ast::ExprBlock(ref blk) => {
1319 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1320 !cx.tcx.used_unsafe.borrow().contains(&blk.id) {
1321 cx.span_lint(UnusedUnsafe, blk.span,
1322 "unnecessary `unsafe` block");
1329 fn check_unsafe_block(cx: &Context, e: &ast::Expr) {
1331 // Don't warn about generated blocks, that'll just pollute the output.
1332 ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1333 cx.span_lint(UnsafeBlock, blk.span, "usage of an `unsafe` block");
1339 fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
1341 ast::PatIdent(ast::BindByValue(ast::MutMutable),
1342 ref path, _) if pat_util::pat_is_binding(cx.tcx.def_map, p)=> {
1343 // `let mut _a = 1;` doesn't need a warning.
1344 let initial_underscore = if path.segments.len() == 1 {
1345 token::get_ident(path.segments
1347 .identifier).get().starts_with("_")
1349 cx.tcx.sess.span_bug(p.span,
1350 "mutable binding that doesn't consist \
1351 of exactly one segment")
1354 if !initial_underscore &&
1355 !cx.tcx.used_mut_nodes.borrow().contains(&p.id) {
1356 cx.span_lint(UnusedMut, p.span,
1357 "variable does not need to be mutable");
1369 fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
1370 // Warn if string and vector literals with sigils, or boxing expressions,
1371 // are immediately borrowed.
1372 let allocation = match e.node {
1373 ast::ExprVstore(e2, ast::ExprVstoreUniq) => {
1375 ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1378 ast::ExprVec(..) => VectorAllocation,
1382 ast::ExprUnary(ast::UnUniq, _) |
1383 ast::ExprUnary(ast::UnBox, _) => BoxAllocation,
1388 let report = |msg| {
1389 cx.span_lint(UnnecessaryAllocation, e.span, msg);
1392 match cx.tcx.adjustments.borrow().find_copy(&e.id) {
1393 Some(adjustment) => {
1395 ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1396 match (allocation, autoref) {
1397 (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1398 report("unnecessary allocation, the sigil can be \
1402 Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1403 report("unnecessary allocation, use & instead");
1406 Some(ty::AutoPtr(_, ast::MutMutable))) => {
1407 report("unnecessary allocation, use &mut \
1421 fn check_missing_doc_attrs(cx: &Context,
1422 id: Option<ast::NodeId>,
1423 attrs: &[ast::Attribute],
1425 desc: &'static str) {
1426 // If we're building a test harness, then warning about
1427 // documentation is probably not really relevant right now.
1428 if cx.tcx.sess.opts.test { return }
1430 // `#[doc(hidden)]` disables missing_doc check.
1431 if cx.is_doc_hidden { return }
1433 // Only check publicly-visible items, using the result from the privacy pass. It's an option so
1434 // the crate root can also use this function (it doesn't have a NodeId).
1436 Some(ref id) if !cx.exported_items.contains(id) => return,
1440 let has_doc = attrs.iter().any(|a| {
1441 match a.node.value.node {
1442 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1447 cx.span_lint(MissingDoc, sp,
1448 format!("missing documentation for {}", desc));
1452 fn check_missing_doc_item(cx: &Context, it: &ast::Item) {
1453 let desc = match it.node {
1454 ast::ItemFn(..) => "a function",
1455 ast::ItemMod(..) => "a module",
1456 ast::ItemEnum(..) => "an enum",
1457 ast::ItemStruct(..) => "a struct",
1458 ast::ItemTrait(..) => "a trait",
1461 check_missing_doc_attrs(cx,
1463 it.attrs.as_slice(),
1468 fn check_missing_doc_method(cx: &Context, m: &ast::Method) {
1469 let did = ast::DefId {
1470 krate: ast::LOCAL_CRATE,
1474 match cx.tcx.methods.borrow().find(&did).map(|method| *method) {
1475 None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
1477 match md.container {
1478 // Always check default methods defined on traits.
1479 ty::TraitContainer(..) => {}
1480 // For methods defined on impls, it depends on whether
1481 // it is an implementation for a trait or is a plain
1483 ty::ImplContainer(cid) => {
1484 match ty::impl_trait_ref(cx.tcx, cid) {
1485 Some(..) => return, // impl for trait: don't doc
1486 None => {} // plain impl: doc according to privacy
1492 check_missing_doc_attrs(cx,
1499 fn check_missing_doc_ty_method(cx: &Context, tm: &ast::TypeMethod) {
1500 check_missing_doc_attrs(cx,
1502 tm.attrs.as_slice(),
1507 fn check_missing_doc_struct_field(cx: &Context, sf: &ast::StructField) {
1508 match sf.node.kind {
1509 ast::NamedField(_, vis) if vis != ast::Private =>
1510 check_missing_doc_attrs(cx,
1511 Some(cx.cur_struct_def_id),
1512 sf.node.attrs.as_slice(),
1519 fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) {
1520 check_missing_doc_attrs(cx,
1522 v.node.attrs.as_slice(),
1527 /// Checks for use of items with #[deprecated], #[experimental] and
1528 /// #[unstable] (or none of them) attributes.
1529 fn check_stability(cx: &Context, e: &ast::Expr) {
1530 let id = match e.node {
1531 ast::ExprPath(..) | ast::ExprStruct(..) => {
1532 match cx.tcx.def_map.borrow().find(&e.id) {
1533 Some(&def) => ast_util::def_id_of_def(def),
1537 ast::ExprMethodCall(..) => {
1538 let method_call = typeck::MethodCall::expr(e.id);
1539 match cx.method_map.borrow().find(&method_call) {
1541 match method.origin {
1542 typeck::MethodStatic(def_id) => {
1543 // If this implements a trait method, get def_id
1544 // of the method inside trait definition.
1545 // Otherwise, use the current def_id (which refers
1546 // to the method inside impl).
1547 ty::trait_method_of_method(
1548 cx.tcx, def_id).unwrap_or(def_id)
1550 typeck::MethodParam(typeck::MethodParam {
1555 | typeck::MethodObject(typeck::MethodObject {
1559 }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1568 let stability = if ast_util::is_local(id) {
1570 let s = cx.tcx.map.with_attrs(id.node, |attrs| {
1572 attr::find_stability(a.iter().map(|a| a.meta()))
1578 // no possibility of having attributes
1579 // (e.g. it's a local variable), so just
1587 // run through all the attributes and take the first
1589 csearch::get_item_attrs(&cx.tcx.sess.cstore, id, |meta_items| {
1591 s = attr::find_stability(meta_items.move_iter())
1597 let (lint, label) = match stability {
1598 // no stability attributes == Unstable
1599 None => (Unstable, "unmarked"),
1600 Some(attr::Stability { level: attr::Unstable, .. }) =>
1601 (Unstable, "unstable"),
1602 Some(attr::Stability { level: attr::Experimental, .. }) =>
1603 (Experimental, "experimental"),
1604 Some(attr::Stability { level: attr::Deprecated, .. }) =>
1605 (Deprecated, "deprecated"),
1609 let msg = match stability {
1610 Some(attr::Stability { text: Some(ref s), .. }) => {
1611 format!("use of {} item: {}", label, *s)
1613 _ => format!("use of {} item", label)
1616 cx.span_lint(lint, e.span, msg);
1619 impl<'a> Visitor<()> for Context<'a> {
1620 fn visit_item(&mut self, it: &ast::Item, _: ()) {
1621 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
1622 check_item_ctypes(cx, it);
1623 check_item_non_camel_case_types(cx, it);
1624 check_item_non_uppercase_statics(cx, it);
1625 check_heap_item(cx, it);
1626 check_missing_doc_item(cx, it);
1627 check_attrs_usage(cx, it.attrs.as_slice());
1628 check_raw_ptr_deriving(cx, it);
1630 cx.visit_ids(|v| v.visit_item(it, ()));
1632 visit::walk_item(cx, it, ());
1636 fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
1637 self.with_lint_attrs(it.attrs.as_slice(), |cx| {
1638 check_attrs_usage(cx, it.attrs.as_slice());
1639 visit::walk_foreign_item(cx, it, ());
1643 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
1644 self.with_lint_attrs(i.attrs.as_slice(), |cx| {
1645 check_attrs_usage(cx, i.attrs.as_slice());
1646 visit::walk_view_item(cx, i, ());
1650 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
1651 check_pat_non_uppercase_statics(self, p);
1652 check_pat_uppercase_variable(self, p);
1653 check_unused_mut_pat(self, p);
1655 visit::walk_pat(self, p, ());
1658 fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
1660 ast::ExprUnary(ast::UnNeg, expr) => {
1661 // propagate negation, if the negation itself isn't negated
1662 if self.negated_expr_id != e.id {
1663 self.negated_expr_id = expr.id;
1666 ast::ExprParen(expr) => if self.negated_expr_id == e.id {
1667 self.negated_expr_id = expr.id
1672 check_while_true_expr(self, e);
1673 check_stability(self, e);
1674 check_unnecessary_parens_expr(self, e);
1675 check_unused_unsafe(self, e);
1676 check_unsafe_block(self, e);
1677 check_unnecessary_allocation(self, e);
1678 check_heap_expr(self, e);
1680 check_type_limits(self, e);
1681 check_unused_casts(self, e);
1682 check_deprecated_owned_vector(self, e);
1684 visit::walk_expr(self, e, ());
1687 fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
1688 check_path_statement(self, s);
1689 check_unused_result(self, s);
1690 check_unnecessary_parens_stmt(self, s);
1692 visit::walk_stmt(self, s, ());
1695 fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
1696 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
1697 let recurse = |this: &mut Context| {
1698 visit::walk_fn(this, fk, decl, body, span, id, ());
1702 visit::FkMethod(_, _, m) => {
1703 self.with_lint_attrs(m.attrs.as_slice(), |cx| {
1704 check_missing_doc_method(cx, m);
1705 check_attrs_usage(cx, m.attrs.as_slice());
1708 v.visit_fn(fk, decl, body, span, id, ());
1718 fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
1719 self.with_lint_attrs(t.attrs.as_slice(), |cx| {
1720 check_missing_doc_ty_method(cx, t);
1721 check_attrs_usage(cx, t.attrs.as_slice());
1723 visit::walk_ty_method(cx, t, ());
1727 fn visit_struct_def(&mut self,
1733 check_struct_uppercase_variable(self, s);
1735 let old_id = self.cur_struct_def_id;
1736 self.cur_struct_def_id = id;
1737 visit::walk_struct_def(self, s, i, g, id, ());
1738 self.cur_struct_def_id = old_id;
1741 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1742 self.with_lint_attrs(s.node.attrs.as_slice(), |cx| {
1743 check_missing_doc_struct_field(cx, s);
1744 check_attrs_usage(cx, s.node.attrs.as_slice());
1746 visit::walk_struct_field(cx, s, ());
1750 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1751 self.with_lint_attrs(v.node.attrs.as_slice(), |cx| {
1752 check_missing_doc_variant(cx, v);
1753 check_attrs_usage(cx, v.node.attrs.as_slice());
1755 visit::walk_variant(cx, v, g, ());
1759 // FIXME(#10894) should continue recursing
1760 fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
1763 impl<'a> IdVisitingOperation for Context<'a> {
1764 fn visit_id(&self, id: ast::NodeId) {
1765 match self.tcx.sess.lints.borrow_mut().pop(&id) {
1768 for (lint, span, msg) in l.move_iter() {
1769 self.span_lint(lint, span, msg)
1776 pub fn check_crate(tcx: &ty::ctxt,
1777 method_map: typeck::MethodMap,
1778 exported_items: &privacy::ExportedItems,
1779 krate: &ast::Crate) {
1780 let mut cx = Context {
1781 dict: @get_lint_dict(),
1782 cur: SmallIntMap::new(),
1784 method_map: method_map,
1785 exported_items: exported_items,
1786 cur_struct_def_id: -1,
1787 is_doc_hidden: false,
1788 lint_stack: Vec::new(),
1792 // Install default lint levels, followed by the command line levels, and
1793 // then actually visit the whole crate.
1794 for (_, spec) in cx.dict.iter() {
1795 cx.set_level(spec.lint, spec.default, Default);
1797 for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1798 cx.set_level(lint, level, CommandLine);
1800 cx.with_lint_attrs(krate.attrs.as_slice(), |cx| {
1801 cx.visit_id(ast::CRATE_NODE_ID);
1803 v.visited_outermost = true;
1804 visit::walk_crate(v, krate, ());
1807 check_crate_attrs_usage(cx, krate.attrs.as_slice());
1808 // since the root module isn't visited as an item (because it isn't an item), warn for it
1810 check_missing_doc_attrs(cx,
1812 krate.attrs.as_slice(),
1816 visit::walk_crate(cx, krate, ());
1819 // If we missed any lints added to the session, then there's a bug somewhere
1820 // in the iteration code.
1821 for (id, v) in tcx.sess.lints.borrow().iter() {
1822 for &(lint, span, ref msg) in v.iter() {
1823 tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}",
1824 lint, tcx.map.node_to_str(*id), *msg))
1828 tcx.sess.abort_if_errors();