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.
37 use metadata::csearch;
38 use middle::dead::DEAD_CODE_LINT_STR;
41 use middle::trans::adt; // for `adt::is_ffi_safe`
43 use middle::typeck::astconv::{ast_ty_to_ty, AstConv};
44 use middle::typeck::infer;
46 use std::to_str::ToStr;
47 use util::ppaux::{ty_to_str};
50 use std::hashmap::HashMap;
59 use extra::smallintmap::SmallIntMap;
61 use syntax::ast_util::IdVisitingOperation;
62 use syntax::attr::{AttrMetaMethods, AttributeMethods};
64 use syntax::codemap::Span;
65 use syntax::parse::token::InternedString;
66 use syntax::parse::token;
67 use syntax::visit::Visitor;
68 use syntax::{ast, ast_util, visit};
70 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
74 UnnecessaryQualification,
80 NonUppercasePatternStatics,
89 DefaultTypeParamUsage,
98 UnnecessaryAllocation,
115 pub fn level_to_str(lv: level) -> &'static str {
124 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
126 allow, warn, deny, forbid
129 #[deriving(Clone, Eq, Ord, TotalEq, TotalOrd)]
130 pub struct LintSpec {
136 pub type LintDict = HashMap<&'static str, LintSpec>;
145 static lint_table: &'static [(&'static str, LintSpec)] = &[
149 desc: "proper use of std::libc types in foreign modules",
156 desc: "imports that are never used",
160 ("unnecessary_qualification",
162 lint: UnnecessaryQualification,
163 desc: "detects unnecessarily qualified names",
170 desc: "suggest using `loop { }` instead of `while true { }`",
177 desc: "path statements with no effect",
181 ("unrecognized_lint",
183 lint: UnrecognizedLint,
184 desc: "unrecognized lint attribute",
188 ("non_camel_case_types",
190 lint: NonCamelCaseTypes,
191 desc: "types, variants and traits should have camel case names",
195 ("non_uppercase_statics",
197 lint: NonUppercaseStatics,
198 desc: "static constants should have uppercase identifiers",
202 ("non_uppercase_pattern_statics",
204 lint: NonUppercasePatternStatics,
205 desc: "static constants in match patterns should be all caps",
209 ("unnecessary_parens",
211 lint: UnnecessaryParens,
212 desc: "`if`, `match`, `while` and `return` do not need parentheses",
216 ("managed_heap_memory",
218 lint: ManagedHeapMemory,
219 desc: "use of managed (@ type) heap memory",
223 ("owned_heap_memory",
225 lint: OwnedHeapMemory,
226 desc: "use of owned (~ type) heap memory",
233 desc: "use of any (~ type or @ type) heap memory",
240 desc: "comparisons made useless by limits of the types involved",
247 desc: "literal out of range for its type",
255 desc: "unnecessary use of an `unsafe` block",
262 desc: "usage of an `unsafe` block",
268 lint: AttributeUsage,
269 desc: "detects bad use of attributes",
275 lint: UnusedVariable,
276 desc: "detect variables which are not used in any way",
282 lint: DeadAssignment,
283 desc: "detect assignments that will never be read",
287 ("unnecessary_typecast",
289 lint: UnnecessaryTypecast,
290 desc: "detects unnecessary type casts, that can be removed",
297 desc: "detect mut variables which don't need to be mutable",
301 ("unnecessary_allocation",
303 lint: UnnecessaryAllocation,
304 desc: "detects unnecessary allocations that can be eliminated",
311 desc: "detect piece of code that will never be used",
318 desc: "detects missing documentation for public members",
324 lint: UnreachableCode,
325 desc: "detects unreachable code",
332 desc: "detects use of #[deprecated] items",
339 desc: "detects use of #[experimental] items",
346 desc: "detects use of #[unstable] items (incl. items with no stability attribute)",
353 desc: "mass-change the level for lints which produce warnings",
359 lint: UnknownFeatures,
360 desc: "unknown features found in crate-level #[feature] directives",
364 ("unknown_crate_type",
366 lint: UnknownCrateType,
367 desc: "unknown crate type found in #[crate_type] directive",
374 desc: "unused result of a type flagged as #[must_use]",
381 desc: "unused result of an expression in a statement",
385 ("default_type_param_usage",
387 lint: DefaultTypeParamUsage,
388 desc: "prevents explicitly setting a type parameter with a default",
394 Pass names should not contain a '-', as the compiler normalizes
395 '-' to '_' in command-line flags
397 pub fn get_lint_dict() -> LintDict {
398 let mut map = HashMap::new();
399 for &(k, v) in lint_table.iter() {
406 // All known lint modes (string versions)
408 // Current levels of each lint warning
409 cur: SmallIntMap<(level, LintSource)>,
410 // context we're checking in (used to access fields like sess)
412 // maps from an expression id that corresponds to a method call to the
413 // details of the method to be invoked
414 method_map: typeck::method_map,
415 // Items exported by the crate; used by the missing_doc lint.
416 exported_items: &'a privacy::ExportedItems,
417 // The id of the current `ast::StructDef` being walked.
418 cur_struct_def_id: ast::NodeId,
419 // Whether some ancestor of the current node was marked
423 // When recursing into an attributed node of the ast which modifies lint
424 // levels, this stack keeps track of the previous lint levels of whatever
426 lint_stack: ~[(Lint, level, LintSource)],
428 // id of the last visited negated expression
429 negated_expr_id: ast::NodeId
432 impl<'a> Context<'a> {
433 fn get_level(&self, lint: Lint) -> level {
434 match self.cur.find(&(lint as uint)) {
435 Some(&(lvl, _)) => lvl,
440 fn get_source(&self, lint: Lint) -> LintSource {
441 match self.cur.find(&(lint as uint)) {
442 Some(&(_, src)) => src,
447 fn set_level(&mut self, lint: Lint, level: level, src: LintSource) {
449 self.cur.remove(&(lint as uint));
451 self.cur.insert(lint as uint, (level, src));
455 fn lint_to_str(&self, lint: Lint) -> &'static str {
456 for (k, v) in self.dict.iter() {
461 fail!("unregistered lint {:?}", lint);
464 fn span_lint(&self, lint: Lint, span: Span, msg: &str) {
465 let (level, src) = match self.cur.find(&(lint as uint)) {
467 Some(&(warn, src)) => (self.get_level(Warnings), src),
470 if level == allow { return }
473 let msg = match src {
475 format!("{}, \\#[{}({})] on by default", msg,
476 level_to_str(level), self.lint_to_str(lint))
479 format!("{} [-{} {}]", msg,
481 warn => 'W', deny => 'D', forbid => 'F',
483 }, self.lint_to_str(lint).replace("_", "-"))
491 warn => { self.tcx.sess.span_warn(span, msg); }
492 deny | forbid => { self.tcx.sess.span_err(span, msg); }
496 for &span in note.iter() {
497 self.tcx.sess.span_note(span, "lint level defined here");
502 * Merge the lints specified by any lint attributes into the
503 * current lint context, call the provided function, then reset the
504 * lints in effect to their previous state.
506 fn with_lint_attrs(&mut self,
507 attrs: &[ast::Attribute],
509 // Parse all of the lint attributes, and then add them all to the
510 // current dictionary of lint information. Along the way, keep a history
511 // of what we changed so we can roll everything back after invoking the
514 each_lint(self.tcx.sess, attrs, |meta, level, lintname| {
515 match self.dict.find_equiv(&lintname) {
520 format!("unknown `{}` attribute: `{}`",
521 level_to_str(level), lintname));
524 let lint = lint.lint;
525 let now = self.get_level(lint);
526 if now == forbid && level != forbid {
527 self.tcx.sess.span_err(meta.span,
528 format!("{}({}) overruled by outer forbid({})",
530 lintname, lintname));
531 } else if now != level {
532 let src = self.get_source(lint);
533 self.lint_stack.push((lint, now, src));
535 self.set_level(lint, level, Node(meta.span));
542 let old_is_doc_hidden = self.is_doc_hidden;
544 self.is_doc_hidden ||
547 attr.name().equiv(&("doc")) &&
548 match attr.meta_item_list() {
550 Some(l) => attr::contains_name(l, "hidden")
557 self.is_doc_hidden = old_is_doc_hidden;
558 for _ in range(0, pushed) {
559 let (lint, lvl, src) = self.lint_stack.pop().unwrap();
560 self.set_level(lint, lvl, src);
564 fn visit_ids(&self, f: |&mut ast_util::IdVisitor<Context>|) {
565 let mut v = ast_util::IdVisitor {
567 pass_through_items: false,
568 visited_outermost: false,
574 // Check that every lint from the list of attributes satisfies `f`.
575 // Return true if that's the case. Otherwise return false.
576 pub fn each_lint(sess: session::Session,
577 attrs: &[ast::Attribute],
578 f: |@ast::MetaItem, level, InternedString| -> bool)
580 let xs = [allow, warn, deny, forbid];
581 for &level in xs.iter() {
582 let level_name = level_to_str(level);
583 for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
584 let meta = attr.node.value;
585 let metas = match meta.node {
586 ast::MetaList(_, ref metas) => metas,
588 sess.span_err(meta.span, "malformed lint attribute");
592 for meta in metas.iter() {
594 ast::MetaWord(ref lintname) => {
595 if !f(*meta, level, (*lintname).clone()) {
600 sess.span_err(meta.span, "malformed lint attribute");
609 // Check from a list of attributes if it contains the appropriate
610 // `#[level(lintname)]` attribute (e.g. `#[allow(dead_code)]).
611 pub fn contains_lint(attrs: &[ast::Attribute],
613 lintname: &'static str)
615 let level_name = level_to_str(level);
616 for attr in attrs.iter().filter(|m| m.name().equiv(&level_name)) {
617 if attr.meta_item_list().is_none() {
620 let list = attr.meta_item_list().unwrap();
621 for meta_item in list.iter() {
622 if meta_item.name().equiv(&lintname) {
630 fn check_while_true_expr(cx: &Context, e: &ast::Expr) {
632 ast::ExprWhile(cond, _) => {
634 ast::ExprLit(lit) => {
636 ast::LitBool(true) => {
637 cx.span_lint(WhileTrue,
639 "denote infinite loops with loop \
651 impl<'a> AstConv for Context<'a>{
652 fn tcx(&self) -> ty::ctxt { self.tcx }
654 fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
655 ty::lookup_item_type(self.tcx, id)
658 fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef {
659 ty::lookup_trait_def(self.tcx, id)
662 fn ty_infer(&self, _span: Span) -> ty::t {
663 let infcx: @infer::InferCtxt = infer::new_infer_ctxt(self.tcx);
669 fn check_unused_casts(cx: &Context, e: &ast::Expr) {
670 return match e.node {
671 ast::ExprCast(expr, ty) => {
672 let infcx: @infer::InferCtxt = infer::new_infer_ctxt(cx.tcx);
673 let t_t = ast_ty_to_ty(cx, &infcx, ty);
674 if ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty {
675 cx.span_lint(UnnecessaryTypecast, ty.span,
676 "unnecessary type cast");
683 fn check_type_limits(cx: &Context, e: &ast::Expr) {
684 return match e.node {
685 ast::ExprBinary(_, binop, l, r) => {
686 if is_comparison(binop) && !check_limits(cx.tcx, binop, l, r) {
687 cx.span_lint(TypeLimits, e.span,
688 "comparison is useless due to type limits");
691 ast::ExprLit(lit) => {
692 match ty::get(ty::expr_ty(cx.tcx, e)).sty {
694 let int_type = if t == ast::TyI {
695 cx.tcx.sess.targ_cfg.int_type
697 let (min, max) = int_ty_range(int_type);
698 let mut lit_val: i64 = match lit.node {
699 ast::LitInt(v, _) => v,
700 ast::LitUint(v, _) => v as i64,
701 ast::LitIntUnsuffixed(v) => v,
704 if cx.negated_expr_id == e.id {
707 if lit_val < min || lit_val > max {
708 cx.span_lint(TypeOverflow, e.span,
709 "literal out of range for its type");
713 let uint_type = if t == ast::TyU {
714 cx.tcx.sess.targ_cfg.uint_type
716 let (min, max) = uint_ty_range(uint_type);
717 let lit_val: u64 = match lit.node {
718 ast::LitInt(v, _) => v as u64,
719 ast::LitUint(v, _) => v,
720 ast::LitIntUnsuffixed(v) => v as u64,
723 if lit_val < min || lit_val > max {
724 cx.span_lint(TypeOverflow, e.span,
725 "literal out of range for its type");
735 fn is_valid<T:cmp::Ord>(binop: ast::BinOp, v: T,
736 min: T, max: T) -> bool {
738 ast::BiLt => v <= max,
739 ast::BiLe => v < max,
740 ast::BiGt => v >= min,
741 ast::BiGe => v > min,
742 ast::BiEq | ast::BiNe => v >= min && v <= max,
747 fn rev_binop(binop: ast::BinOp) -> ast::BinOp {
749 ast::BiLt => ast::BiGt,
750 ast::BiLe => ast::BiGe,
751 ast::BiGt => ast::BiLt,
752 ast::BiGe => ast::BiLe,
757 // for int & uint, be conservative with the warnings, so that the
758 // warnings are consistent between 32- and 64-bit platforms
759 fn int_ty_range(int_ty: ast::IntTy) -> (i64, i64) {
761 ast::TyI => (i64::MIN, i64::MAX),
762 ast::TyI8 => (i8::MIN as i64, i8::MAX as i64),
763 ast::TyI16 => (i16::MIN as i64, i16::MAX as i64),
764 ast::TyI32 => (i32::MIN as i64, i32::MAX as i64),
765 ast::TyI64 => (i64::MIN, i64::MAX)
769 fn uint_ty_range(uint_ty: ast::UintTy) -> (u64, u64) {
771 ast::TyU => (u64::MIN, u64::MAX),
772 ast::TyU8 => (u8::MIN as u64, u8::MAX as u64),
773 ast::TyU16 => (u16::MIN as u64, u16::MAX as u64),
774 ast::TyU32 => (u32::MIN as u64, u32::MAX as u64),
775 ast::TyU64 => (u64::MIN, u64::MAX)
779 fn check_limits(tcx: ty::ctxt, binop: ast::BinOp,
780 l: &ast::Expr, r: &ast::Expr) -> bool {
781 let (lit, expr, swap) = match (&l.node, &r.node) {
782 (&ast::ExprLit(_), _) => (l, r, true),
783 (_, &ast::ExprLit(_)) => (r, l, false),
786 // Normalize the binop so that the literal is always on the RHS in
788 let norm_binop = if swap { rev_binop(binop) } else { binop };
789 match ty::get(ty::expr_ty(tcx, expr)).sty {
790 ty::ty_int(int_ty) => {
791 let (min, max) = int_ty_range(int_ty);
792 let lit_val: i64 = match lit.node {
793 ast::ExprLit(li) => match li.node {
794 ast::LitInt(v, _) => v,
795 ast::LitUint(v, _) => v as i64,
796 ast::LitIntUnsuffixed(v) => v,
801 is_valid(norm_binop, lit_val, min, max)
803 ty::ty_uint(uint_ty) => {
804 let (min, max): (u64, u64) = uint_ty_range(uint_ty);
805 let lit_val: u64 = match lit.node {
806 ast::ExprLit(li) => match li.node {
807 ast::LitInt(v, _) => v as u64,
808 ast::LitUint(v, _) => v,
809 ast::LitIntUnsuffixed(v) => v as u64,
814 is_valid(norm_binop, lit_val, min, max)
820 fn is_comparison(binop: ast::BinOp) -> bool {
822 ast::BiEq | ast::BiLt | ast::BiLe |
823 ast::BiNe | ast::BiGe | ast::BiGt => true,
829 fn check_item_ctypes(cx: &Context, it: &ast::Item) {
830 fn check_ty(cx: &Context, ty: &ast::Ty) {
832 ast::TyPath(_, _, id) => {
833 let def_map = cx.tcx.def_map.borrow();
834 match def_map.get().get_copy(&id) {
835 ast::DefPrimTy(ast::TyInt(ast::TyI)) => {
836 cx.span_lint(CTypes, ty.span,
837 "found rust type `int` in foreign module, while \
838 libc::c_int or libc::c_long should be used");
840 ast::DefPrimTy(ast::TyUint(ast::TyU)) => {
841 cx.span_lint(CTypes, ty.span,
842 "found rust type `uint` in foreign module, while \
843 libc::c_uint or libc::c_ulong should be used");
845 ast::DefTy(def_id) => {
846 if !adt::is_ffi_safe(cx.tcx, def_id) {
847 cx.span_lint(CTypes, ty.span,
848 "found enum type without foreign-function-safe \
849 representation annotation in foreign module");
850 // hmm... this message could be more helpful
856 ast::TyPtr(ref mt) => { check_ty(cx, mt.ty) }
861 fn check_foreign_fn(cx: &Context, decl: &ast::FnDecl) {
862 for input in decl.inputs.iter() {
863 check_ty(cx, input.ty);
865 check_ty(cx, decl.output)
869 ast::ItemForeignMod(ref nmod) if !nmod.abis.is_intrinsic() => {
870 for ni in nmod.items.iter() {
872 ast::ForeignItemFn(decl, _) => check_foreign_fn(cx, decl),
873 ast::ForeignItemStatic(t, _) => check_ty(cx, t)
877 _ => {/* nothing to do */ }
881 fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
882 let xs = [ManagedHeapMemory, OwnedHeapMemory, HeapMemory];
883 for &lint in xs.iter() {
884 if cx.get_level(lint) == allow { continue }
888 ty::fold_ty(cx.tcx, ty, |t| {
889 match ty::get(t).sty {
891 ty::ty_vec(_, ty::vstore_box) |
892 ty::ty_trait(_, _, ty::BoxTraitStore, _, _) => {
895 ty::ty_uniq(_) | ty::ty_str(ty::vstore_uniq) |
896 ty::ty_vec(_, ty::vstore_uniq) |
897 ty::ty_trait(_, _, ty::UniqTraitStore, _, _) => {
900 ty::ty_closure(ref c) if c.sigil == ast::OwnedSigil => {
909 if n_uniq > 0 && lint != ManagedHeapMemory {
910 let s = ty_to_str(cx.tcx, ty);
911 let m = format!("type uses owned (~ type) pointers: {}", s);
912 cx.span_lint(lint, span, m);
915 if n_box > 0 && lint != OwnedHeapMemory {
916 let s = ty_to_str(cx.tcx, ty);
917 let m = format!("type uses managed (@ type) pointers: {}", s);
918 cx.span_lint(lint, span, m);
923 fn check_heap_item(cx: &Context, it: &ast::Item) {
928 ast::ItemStruct(..) => check_heap_type(cx, it.span,
929 ty::node_id_to_type(cx.tcx,
934 // If it's a struct, we also have to check the fields' types
936 ast::ItemStruct(struct_def, _) => {
937 for struct_field in struct_def.fields.iter() {
938 check_heap_type(cx, struct_field.span,
939 ty::node_id_to_type(cx.tcx,
940 struct_field.node.id));
947 static crate_attrs: &'static [&'static str] = &[
948 "crate_type", "feature", "no_uv", "no_main", "no_std", "crate_id",
949 "desc", "comment", "license", "copyright", // not used in rustc now
953 static obsolete_attrs: &'static [(&'static str, &'static str)] = &[
954 ("abi", "Use `extern \"abi\" fn` instead"),
955 ("auto_encode", "Use `#[deriving(Encodable)]` instead"),
956 ("auto_decode", "Use `#[deriving(Decodable)]` instead"),
957 ("fast_ffi", "Remove it"),
958 ("fixed_stack_segment", "Remove it"),
959 ("rust_stack", "Remove it"),
962 static other_attrs: &'static [&'static str] = &[
964 "address_insignificant", // can be crate-level too
965 "thread_local", // for statics
966 "allow", "deny", "forbid", "warn", // lint options
967 "deprecated", "experimental", "unstable", "stable", "locked", "frozen", //item stability
968 "crate_map", "cfg", "doc", "export_name", "link_section",
969 "no_mangle", "static_assert", "unsafe_no_drop_flag", "packed",
970 "simd", "repr", "deriving", "unsafe_destructor", "link", "phase",
971 "macro_export", "must_use",
974 "path", "link_name", "link_args", "nolink", "macro_escape", "no_implicit_prelude",
977 "test", "bench", "should_fail", "ignore", "inline", "lang", "main", "start",
978 "no_split_stack", "cold", "macro_registrar",
980 // internal attribute: bypass privacy inside items
981 "!resolve_unexported",
984 fn check_crate_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
986 for attr in attrs.iter() {
987 let name = attr.node.value.name();
988 let mut iter = crate_attrs.iter().chain(other_attrs.iter());
989 if !iter.any(|other_attr| { name.equiv(other_attr) }) {
990 cx.span_lint(AttributeUsage, attr.span, "unknown crate attribute");
992 if name.equiv(& &"link") {
993 cx.tcx.sess.span_err(attr.span,
994 "obsolete crate `link` attribute");
995 cx.tcx.sess.note("the link attribute has been superceded by the crate_id \
996 attribute, which has the format `#[crate_id = \"name#version\"]`");
1001 fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
1002 // check if element has crate-level, obsolete, or any unknown attributes.
1004 for attr in attrs.iter() {
1005 let name = attr.node.value.name();
1006 for crate_attr in crate_attrs.iter() {
1007 if name.equiv(crate_attr) {
1008 let msg = match attr.node.style {
1009 ast::AttrOuter => "crate-level attribute should be an inner attribute: \
1010 add semicolon at end",
1011 ast::AttrInner => "crate-level attribute should be in the root module",
1013 cx.span_lint(AttributeUsage, attr.span, msg);
1018 for &(obs_attr, obs_alter) in obsolete_attrs.iter() {
1019 if name.equiv(&obs_attr) {
1020 cx.span_lint(AttributeUsage, attr.span,
1021 format!("obsolete attribute: {:s}", obs_alter));
1026 if !other_attrs.iter().any(|other_attr| { name.equiv(other_attr) }) {
1027 cx.span_lint(AttributeUsage, attr.span, "unknown attribute");
1032 fn check_heap_expr(cx: &Context, e: &ast::Expr) {
1033 let ty = ty::expr_ty(cx.tcx, e);
1034 check_heap_type(cx, e.span, ty);
1037 fn check_path_statement(cx: &Context, s: &ast::Stmt) {
1039 ast::StmtSemi(expr, _) => {
1041 ast::ExprPath(_) => {
1042 cx.span_lint(PathStatement,
1044 "path statement with no effect");
1053 fn check_unused_result(cx: &Context, s: &ast::Stmt) {
1054 let expr = match s.node {
1055 ast::StmtSemi(expr, _) => expr,
1058 let t = ty::expr_ty(cx.tcx, expr);
1059 match ty::get(t).sty {
1060 ty::ty_nil | ty::ty_bot | ty::ty_bool => return,
1064 ast::ExprRet(..) => return,
1068 let t = ty::expr_ty(cx.tcx, expr);
1069 let mut warned = false;
1070 match ty::get(t).sty {
1071 ty::ty_struct(did, _) |
1072 ty::ty_enum(did, _) => {
1073 if ast_util::is_local(did) {
1074 match cx.tcx.items.get(did.node) {
1075 ast_map::NodeItem(it, _) => {
1076 if attr::contains_name(it.attrs, "must_use") {
1077 cx.span_lint(UnusedMustUse, s.span,
1078 "unused result which must be used");
1085 csearch::get_item_attrs(cx.tcx.sess.cstore, did, |attrs| {
1086 if attr::contains_name(attrs, "must_use") {
1087 cx.span_lint(UnusedMustUse, s.span,
1088 "unused result which must be used");
1097 cx.span_lint(UnusedResult, s.span, "unused result");
1101 fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
1102 fn is_camel_case(cx: ty::ctxt, ident: ast::Ident) -> bool {
1103 let ident = cx.sess.str_of(ident);
1104 assert!(!ident.is_empty());
1105 let ident = ident.trim_chars(&'_');
1107 // start with a non-lowercase letter rather than non-uppercase
1108 // ones (some scripts don't have a concept of upper/lowercase)
1109 !ident.char_at(0).is_lowercase() &&
1110 !ident.contains_char('_')
1113 fn check_case(cx: &Context, sort: &str, ident: ast::Ident, span: Span) {
1114 if !is_camel_case(cx.tcx, ident) {
1116 NonCamelCaseTypes, span,
1117 format!("{} `{}` should have a camel case identifier",
1118 sort, cx.tcx.sess.str_of(ident)));
1123 ast::ItemTy(..) | ast::ItemStruct(..) => {
1124 check_case(cx, "type", it.ident, it.span)
1126 ast::ItemTrait(..) => {
1127 check_case(cx, "trait", it.ident, it.span)
1129 ast::ItemEnum(ref enum_definition, _) => {
1130 check_case(cx, "type", it.ident, it.span);
1131 for variant in enum_definition.variants.iter() {
1132 check_case(cx, "variant", variant.node.name, variant.span);
1139 fn check_item_non_uppercase_statics(cx: &Context, it: &ast::Item) {
1141 // only check static constants
1142 ast::ItemStatic(_, ast::MutImmutable, _) => {
1143 let s = cx.tcx.sess.str_of(it.ident);
1144 // check for lowercase letters rather than non-uppercase
1145 // ones (some scripts don't have a concept of
1147 if s.chars().any(|c| c.is_lowercase()) {
1148 cx.span_lint(NonUppercaseStatics, it.span,
1149 "static constant should have an uppercase identifier");
1156 fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
1157 // Lint for constants that look like binding identifiers (#7526)
1158 let def_map = cx.tcx.def_map.borrow();
1159 match (&p.node, def_map.get().find(&p.id)) {
1160 (&ast::PatIdent(_, ref path, _), Some(&ast::DefStatic(_, false))) => {
1161 // last identifier alone is right choice for this lint.
1162 let ident = path.segments.last().unwrap().identifier;
1163 let s = cx.tcx.sess.str_of(ident);
1164 if s.chars().any(|c| c.is_lowercase()) {
1165 cx.span_lint(NonUppercasePatternStatics, path.span,
1166 "static constant in pattern should be all caps");
1173 fn check_unnecessary_parens(cx: &Context, e: &ast::Expr) {
1174 let (value, msg) = match e.node {
1175 ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
1176 ast::ExprWhile(cond, _) => (cond, "`while` condition"),
1177 ast::ExprMatch(head, _) => (head, "`match` head expression"),
1178 ast::ExprRet(Some(value)) => (value, "`return` value"),
1183 ast::ExprParen(_) => {
1184 cx.span_lint(UnnecessaryParens, value.span,
1185 format!("unnecessary parentheses around {}", msg))
1191 fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
1193 // Don't warn about generated blocks, that'll just pollute the output.
1194 ast::ExprBlock(ref blk) => {
1195 let used_unsafe = cx.tcx.used_unsafe.borrow();
1196 if blk.rules == ast::UnsafeBlock(ast::UserProvided) &&
1197 !used_unsafe.get().contains(&blk.id) {
1198 cx.span_lint(UnusedUnsafe, blk.span,
1199 "unnecessary `unsafe` block");
1206 fn check_unsafe_block(cx: &Context, e: &ast::Expr) {
1208 // Don't warn about generated blocks, that'll just pollute the output.
1209 ast::ExprBlock(ref blk) if blk.rules == ast::UnsafeBlock(ast::UserProvided) => {
1210 cx.span_lint(UnsafeBlock, blk.span, "usage of an `unsafe` block");
1216 fn check_unused_mut_pat(cx: &Context, p: &ast::Pat) {
1218 ast::PatIdent(ast::BindByValue(ast::MutMutable),
1219 ref path, _) if pat_util::pat_is_binding(cx.tcx.def_map, p)=> {
1220 // `let mut _a = 1;` doesn't need a warning.
1221 let initial_underscore = match path.segments {
1222 [ast::PathSegment { identifier: id, .. }] => {
1223 cx.tcx.sess.str_of(id).starts_with("_")
1226 cx.tcx.sess.span_bug(p.span,
1227 "mutable binding that doesn't \
1228 consist of exactly one segment");
1232 let used_mut_nodes = cx.tcx.used_mut_nodes.borrow();
1233 if !initial_underscore && !used_mut_nodes.get().contains(&p.id) {
1234 cx.span_lint(UnusedMut, p.span,
1235 "variable does not need to be mutable");
1247 fn check_unnecessary_allocation(cx: &Context, e: &ast::Expr) {
1248 // Warn if string and vector literals with sigils, or boxing expressions,
1249 // are immediately borrowed.
1250 let allocation = match e.node {
1251 ast::ExprVstore(e2, ast::ExprVstoreUniq) |
1252 ast::ExprVstore(e2, ast::ExprVstoreBox) => {
1254 ast::ExprLit(lit) if ast_util::lit_is_str(lit) => {
1257 ast::ExprVec(..) => VectorAllocation,
1261 ast::ExprUnary(_, ast::UnUniq, _) |
1262 ast::ExprUnary(_, ast::UnBox, _) => BoxAllocation,
1267 let report = |msg| {
1268 cx.span_lint(UnnecessaryAllocation, e.span, msg);
1272 let adjustments = cx.tcx.adjustments.borrow();
1273 adjustments.get().find_copy(&e.id)
1276 Some(adjustment) => {
1278 ty::AutoDerefRef(ty::AutoDerefRef { autoref, .. }) => {
1279 match (allocation, autoref) {
1280 (VectorAllocation, Some(ty::AutoBorrowVec(..))) => {
1281 report("unnecessary allocation, the sigil can be \
1285 Some(ty::AutoPtr(_, ast::MutImmutable))) => {
1286 report("unnecessary allocation, use & instead");
1289 Some(ty::AutoPtr(_, ast::MutMutable))) => {
1290 report("unnecessary allocation, use &mut \
1304 fn check_missing_doc_attrs(cx: &Context,
1305 id: Option<ast::NodeId>,
1306 attrs: &[ast::Attribute],
1308 desc: &'static str) {
1309 // If we're building a test harness, then warning about
1310 // documentation is probably not really relevant right now.
1311 if cx.tcx.sess.opts.test { return }
1313 // `#[doc(hidden)]` disables missing_doc check.
1314 if cx.is_doc_hidden { return }
1316 // Only check publicly-visible items, using the result from the privacy pass. It's an option so
1317 // the crate root can also use this function (it doesn't have a NodeId).
1319 Some(ref id) if !cx.exported_items.contains(id) => return,
1323 let has_doc = attrs.iter().any(|a| {
1324 match a.node.value.node {
1325 ast::MetaNameValue(ref name, _) if name.equiv(&("doc")) => true,
1330 cx.span_lint(MissingDoc, sp,
1331 format!("missing documentation for {}", desc));
1335 fn check_missing_doc_item(cx: &Context, it: &ast::Item) {
1336 let desc = match it.node {
1337 ast::ItemFn(..) => "a function",
1338 ast::ItemMod(..) => "a module",
1339 ast::ItemEnum(..) => "an enum",
1340 ast::ItemStruct(..) => "a struct",
1341 ast::ItemTrait(..) => "a trait",
1344 check_missing_doc_attrs(cx, Some(it.id), it.attrs, it.span, desc);
1347 fn check_missing_doc_method(cx: &Context, m: &ast::Method) {
1348 let did = ast::DefId {
1349 crate: ast::LOCAL_CRATE,
1355 let methods = cx.tcx.methods.borrow();
1356 method_opt = methods.get().find(&did).map(|method| *method);
1360 None => cx.tcx.sess.span_bug(m.span, "missing method descriptor?!"),
1362 match md.container {
1363 // Always check default methods defined on traits.
1364 ty::TraitContainer(..) => {}
1365 // For methods defined on impls, it depends on whether
1366 // it is an implementation for a trait or is a plain
1368 ty::ImplContainer(cid) => {
1369 match ty::impl_trait_ref(cx.tcx, cid) {
1370 Some(..) => return, // impl for trait: don't doc
1371 None => {} // plain impl: doc according to privacy
1377 check_missing_doc_attrs(cx, Some(m.id), m.attrs, m.span, "a method");
1380 fn check_missing_doc_ty_method(cx: &Context, tm: &ast::TypeMethod) {
1381 check_missing_doc_attrs(cx, Some(tm.id), tm.attrs, tm.span, "a type method");
1384 fn check_missing_doc_struct_field(cx: &Context, sf: &ast::StructField) {
1385 match sf.node.kind {
1386 ast::NamedField(_, vis) if vis != ast::Private =>
1387 check_missing_doc_attrs(cx, Some(cx.cur_struct_def_id), sf.node.attrs,
1388 sf.span, "a struct field"),
1393 fn check_missing_doc_variant(cx: &Context, v: &ast::Variant) {
1394 check_missing_doc_attrs(cx, Some(v.node.id), v.node.attrs, v.span, "a variant");
1397 /// Checks for use of items with #[deprecated], #[experimental] and
1398 /// #[unstable] (or none of them) attributes.
1399 fn check_stability(cx: &Context, e: &ast::Expr) {
1400 let id = match e.node {
1401 ast::ExprPath(..) | ast::ExprStruct(..) => {
1402 let def_map = cx.tcx.def_map.borrow();
1403 match def_map.get().find(&e.id) {
1404 Some(&def) => ast_util::def_id_of_def(def),
1408 ast::ExprMethodCall(..) => {
1409 let method_map = cx.method_map.borrow();
1410 match method_map.get().find(&e.id) {
1411 Some(&typeck::method_map_entry { origin, .. }) => {
1413 typeck::method_static(def_id) => {
1414 // If this implements a trait method, get def_id
1415 // of the method inside trait definition.
1416 // Otherwise, use the current def_id (which refers
1417 // to the method inside impl).
1418 ty::trait_method_of_method(
1419 cx.tcx, def_id).unwrap_or(def_id)
1421 typeck::method_param(typeck::method_param {
1426 | typeck::method_object(typeck::method_object {
1430 }) => ty::trait_method(cx.tcx, trait_id, index).def_id
1439 let stability = if ast_util::is_local(id) {
1441 match cx.tcx.items.find(id.node) {
1443 let s = ast_node.with_attrs(|attrs| {
1445 attr::find_stability(a.iter().map(|a| a.meta()))
1451 // no possibility of having attributes
1452 // (e.g. it's a local variable), so just
1457 _ => cx.tcx.sess.span_bug(e.span,
1458 format!("handle_def: {:?} not found", id))
1464 // run through all the attributes and take the first
1466 csearch::get_item_attrs(cx.tcx.cstore, id, |meta_items| {
1468 s = attr::find_stability(meta_items.move_iter())
1474 let (lint, label) = match stability {
1475 // no stability attributes == Unstable
1476 None => (Unstable, "unmarked"),
1477 Some(attr::Stability { level: attr::Unstable, .. }) =>
1478 (Unstable, "unstable"),
1479 Some(attr::Stability { level: attr::Experimental, .. }) =>
1480 (Experimental, "experimental"),
1481 Some(attr::Stability { level: attr::Deprecated, .. }) =>
1482 (Deprecated, "deprecated"),
1486 let msg = match stability {
1487 Some(attr::Stability { text: Some(ref s), .. }) => {
1488 format!("use of {} item: {}", label, *s)
1490 _ => format!("use of {} item", label)
1493 cx.span_lint(lint, e.span, msg);
1496 impl<'a> Visitor<()> for Context<'a> {
1497 fn visit_item(&mut self, it: &ast::Item, _: ()) {
1498 self.with_lint_attrs(it.attrs, |cx| {
1499 check_item_ctypes(cx, it);
1500 check_item_non_camel_case_types(cx, it);
1501 check_item_non_uppercase_statics(cx, it);
1502 check_heap_item(cx, it);
1503 check_missing_doc_item(cx, it);
1504 check_attrs_usage(cx, it.attrs);
1506 cx.visit_ids(|v| v.visit_item(it, ()));
1508 visit::walk_item(cx, it, ());
1512 fn visit_foreign_item(&mut self, it: &ast::ForeignItem, _: ()) {
1513 self.with_lint_attrs(it.attrs, |cx| {
1514 check_attrs_usage(cx, it.attrs);
1515 visit::walk_foreign_item(cx, it, ());
1519 fn visit_view_item(&mut self, i: &ast::ViewItem, _: ()) {
1520 self.with_lint_attrs(i.attrs, |cx| {
1521 check_attrs_usage(cx, i.attrs);
1522 visit::walk_view_item(cx, i, ());
1526 fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
1527 check_pat_non_uppercase_statics(self, p);
1528 check_unused_mut_pat(self, p);
1530 visit::walk_pat(self, p, ());
1533 fn visit_expr(&mut self, e: &ast::Expr, _: ()) {
1535 ast::ExprUnary(_, ast::UnNeg, expr) => {
1536 // propagate negation, if the negation itself isn't negated
1537 if self.negated_expr_id != e.id {
1538 self.negated_expr_id = expr.id;
1541 ast::ExprParen(expr) => if self.negated_expr_id == e.id {
1542 self.negated_expr_id = expr.id
1547 check_while_true_expr(self, e);
1548 check_stability(self, e);
1549 check_unnecessary_parens(self, e);
1550 check_unused_unsafe(self, e);
1551 check_unsafe_block(self, e);
1552 check_unnecessary_allocation(self, e);
1553 check_heap_expr(self, e);
1555 check_type_limits(self, e);
1556 check_unused_casts(self, e);
1558 visit::walk_expr(self, e, ());
1561 fn visit_stmt(&mut self, s: &ast::Stmt, _: ()) {
1562 check_path_statement(self, s);
1563 check_unused_result(self, s);
1565 visit::walk_stmt(self, s, ());
1568 fn visit_fn(&mut self, fk: &visit::FnKind, decl: &ast::FnDecl,
1569 body: &ast::Block, span: Span, id: ast::NodeId, _: ()) {
1570 let recurse = |this: &mut Context| {
1571 visit::walk_fn(this, fk, decl, body, span, id, ());
1575 visit::FkMethod(_, _, m) => {
1576 self.with_lint_attrs(m.attrs, |cx| {
1577 check_missing_doc_method(cx, m);
1578 check_attrs_usage(cx, m.attrs);
1581 v.visit_fn(fk, decl, body, span, id, ());
1591 fn visit_ty_method(&mut self, t: &ast::TypeMethod, _: ()) {
1592 self.with_lint_attrs(t.attrs, |cx| {
1593 check_missing_doc_ty_method(cx, t);
1594 check_attrs_usage(cx, t.attrs);
1596 visit::walk_ty_method(cx, t, ());
1600 fn visit_struct_def(&mut self,
1606 let old_id = self.cur_struct_def_id;
1607 self.cur_struct_def_id = id;
1608 visit::walk_struct_def(self, s, i, g, id, ());
1609 self.cur_struct_def_id = old_id;
1612 fn visit_struct_field(&mut self, s: &ast::StructField, _: ()) {
1613 self.with_lint_attrs(s.node.attrs, |cx| {
1614 check_missing_doc_struct_field(cx, s);
1615 check_attrs_usage(cx, s.node.attrs);
1617 visit::walk_struct_field(cx, s, ());
1621 fn visit_variant(&mut self, v: &ast::Variant, g: &ast::Generics, _: ()) {
1622 self.with_lint_attrs(v.node.attrs, |cx| {
1623 check_missing_doc_variant(cx, v);
1624 check_attrs_usage(cx, v.node.attrs);
1626 visit::walk_variant(cx, v, g, ());
1630 // FIXME(#10894) should continue recursing
1631 fn visit_ty(&mut self, _t: &ast::Ty, _: ()) {}
1634 impl<'a> IdVisitingOperation for Context<'a> {
1635 fn visit_id(&self, id: ast::NodeId) {
1636 let mut lints = self.tcx.sess.lints.borrow_mut();
1637 match lints.get().pop(&id) {
1640 for (lint, span, msg) in l.move_iter() {
1641 self.span_lint(lint, span, msg)
1648 pub fn check_crate(tcx: ty::ctxt,
1649 method_map: typeck::method_map,
1650 exported_items: &privacy::ExportedItems,
1651 crate: &ast::Crate) {
1652 let mut cx = Context {
1653 dict: @get_lint_dict(),
1654 cur: SmallIntMap::new(),
1656 method_map: method_map,
1657 exported_items: exported_items,
1658 cur_struct_def_id: -1,
1659 is_doc_hidden: false,
1664 // Install default lint levels, followed by the command line levels, and
1665 // then actually visit the whole crate.
1666 for (_, spec) in cx.dict.iter() {
1667 cx.set_level(spec.lint, spec.default, Default);
1669 for &(lint, level) in tcx.sess.opts.lint_opts.iter() {
1670 cx.set_level(lint, level, CommandLine);
1672 cx.with_lint_attrs(crate.attrs, |cx| {
1673 cx.visit_id(ast::CRATE_NODE_ID);
1675 v.visited_outermost = true;
1676 visit::walk_crate(v, crate, ());
1679 check_crate_attrs_usage(cx, crate.attrs);
1680 // since the root module isn't visited as an item (because it isn't an item), warn for it
1682 check_missing_doc_attrs(cx, None, crate.attrs, crate.span, "crate");
1684 visit::walk_crate(cx, crate, ());
1687 // If we missed any lints added to the session, then there's a bug somewhere
1688 // in the iteration code.
1689 let lints = tcx.sess.lints.borrow();
1690 for (id, v) in lints.get().iter() {
1691 for &(lint, span, ref msg) in v.iter() {
1692 tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}",
1694 ast_map::node_id_to_str(tcx.items,
1696 token::get_ident_interner()),
1701 tcx.sess.abort_if_errors();