1 //! checks for attributes
3 use crate::reexport::*;
5 in_macro, last_line_of_span, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then,
6 without_block_comments,
10 use rustc::ty::{self, TyCtxt};
12 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
13 use syntax::codemap::Span;
15 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
16 /// unless the annotated function is empty or simply panics.
18 /// **Why is this bad?** While there are valid uses of this annotation (and once
19 /// you know when to use it, by all means `allow` this lint), it's a common
20 /// newbie-mistake to pepper one's code with it.
22 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
23 /// measure if that additional function call really affects your runtime profile
24 /// sufficiently to make up for the increase in compile time.
26 /// **Known problems:** False positives, big time. This lint is meant to be
27 /// deactivated by everyone doing serious performance work. This means having
28 /// done the measurement.
33 /// fn not_quite_hot_code(..) { ... }
35 declare_clippy_lint! {
38 "use of `#[inline(always)]`"
41 /// **What it does:** Checks for `extern crate` and `use` items annotated with
44 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
45 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
46 /// `#[macro_use]` attribute.
48 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
49 /// likely a `!` was forgotten.
51 /// **Known problems:** None.
56 /// #[deny(dead_code)]
58 /// #[forbid(dead_code)]
62 /// #[allow(unused_imports)]
64 /// #[allow(unused_imports)]
68 declare_clippy_lint! {
69 pub USELESS_ATTRIBUTE,
71 "use of lint attributes on `extern crate` items"
74 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
75 /// field that is not a valid semantic version.
77 /// **Why is this bad?** For checking the version of the deprecation, it must be
78 /// a valid semver. Failing that, the contained information is useless.
80 /// **Known problems:** None.
84 /// #[deprecated(since = "forever")]
85 /// fn something_else(..) { ... }
87 declare_clippy_lint! {
88 pub DEPRECATED_SEMVER,
90 "use of `#[deprecated(since = \"x\")]` where x is not semver"
93 /// **What it does:** Checks for empty lines after outer attributes
95 /// **Why is this bad?**
96 /// Most likely the attribute was meant to be an inner attribute using a '!'.
97 /// If it was meant to be an outer attribute, then the following item
98 /// should not be separated by empty lines.
100 /// **Known problems:** Can cause false positives.
102 /// From the clippy side it's difficult to detect empty lines between an attributes and the
103 /// following item because empty lines and comments are not part of the AST. The parsing
104 /// currently works for basic cases but is not perfect.
109 /// #[inline(always)]
111 /// fn not_quite_good_code(..) { ... }
113 /// // Good (as inner attribute)
114 /// #![inline(always)]
116 /// fn this_is_fine(..) { ... }
118 /// // Good (as outer attribute)
119 /// #[inline(always)]
120 /// fn this_is_fine_too(..) { ... }
122 declare_clippy_lint! {
123 pub EMPTY_LINE_AFTER_OUTER_ATTR,
125 "empty line after outer attribute"
128 #[derive(Copy, Clone)]
131 impl LintPass for AttrPass {
132 fn get_lints(&self) -> LintArray {
137 EMPTY_LINE_AFTER_OUTER_ATTR
142 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
143 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
144 if let Some(ref items) = attr.meta_item_list() {
145 if items.is_empty() || attr.name() != "deprecated" {
150 if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
151 if let MetaItemKind::NameValue(ref lit) = mi.node;
152 if mi.name() == "since";
154 check_semver(cx, item.span, lit);
161 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
162 if is_relevant_item(cx.tcx, item) {
163 check_attrs(cx, item.span, item.name, &item.attrs)
166 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
167 let skip_unused_imports = item.attrs.iter().any(|attr| attr.name() == "macro_use");
169 for attr in &item.attrs {
170 if let Some(ref lint_list) = attr.meta_item_list() {
171 match &*attr.name().as_str() {
172 "allow" | "warn" | "deny" | "forbid" => {
173 // whitelist `unused_imports` and `deprecated` for `use` items
174 // and `unused_imports` for `extern crate` items with `macro_use`
175 for lint in lint_list {
177 ItemKind::Use(..) => if is_word(lint, "unused_imports")
178 || is_word(lint, "deprecated") {
181 ItemKind::ExternCrate(..) => if is_word(lint, "unused_imports")
182 && skip_unused_imports {
188 let line_span = last_line_of_span(cx, attr.span);
190 if let Some(mut sugg) = snippet_opt(cx, line_span) {
191 if sugg.contains("#[") {
196 "useless lint attribute",
198 sugg = sugg.replacen("#[", "#![", 1);
199 db.span_suggestion(line_span, "if you just forgot a `!`, use", sugg);
214 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
215 if is_relevant_impl(cx.tcx, item) {
216 check_attrs(cx, item.span, item.ident.name, &item.attrs)
220 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
221 if is_relevant_trait(cx.tcx, item) {
222 check_attrs(cx, item.span, item.ident.name, &item.attrs)
227 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
228 if let ItemKind::Fn(_, _, _, eid) = item.node {
229 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
235 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
237 ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
242 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
244 TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
245 TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
246 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
252 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
253 if let Some(stmt) = block.stmts.first() {
255 StmtKind::Decl(_, _) => true,
256 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
259 block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
263 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
265 ExprKind::Block(ref block, _) => is_relevant_block(tcx, tables, block),
266 ExprKind::Ret(Some(ref e)) => is_relevant_expr(tcx, tables, e),
267 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
268 ExprKind::Call(ref path_expr, _) => if let ExprKind::Path(ref qpath) = path_expr.node {
269 if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
270 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
281 fn check_attrs(cx: &LateContext, span: Span, name: Name, attrs: &[Attribute]) {
287 if attr.is_sugared_doc {
290 if attr.style == AttrStyle::Outer {
291 if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
295 let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
296 let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
298 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
299 let lines = snippet.split('\n').collect::<Vec<_>>();
300 let lines = without_block_comments(lines);
302 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
305 EMPTY_LINE_AFTER_OUTER_ATTR,
306 begin_of_attr_to_item,
307 "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
313 if let Some(ref values) = attr.meta_item_list() {
314 if values.len() != 1 || attr.name() != "inline" {
317 if is_word(&values[0], "always") {
323 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
332 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
333 if let LitKind::Str(ref is, _) = lit.node {
334 if Version::parse(&is.as_str()).is_ok() {
342 "the since field must contain a semver-compliant version",
346 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
347 if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
348 mi.is_word() && mi.name() == expected
354 // If the snippet is empty, it's an attribute that was inserted during macro
355 // expansion and we want to ignore those, because they could come from external
356 // sources that the user has no control over.
357 // For some reason these attributes don't have any expansion info on them, so
358 // we have to check it this way until there is a better way.
359 fn is_present_in_source(cx: &LateContext, span: Span) -> bool {
360 if let Some(snippet) = snippet_opt(cx, span) {
361 if snippet.is_empty() {