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::{declare_lint, lint_array};
11 use if_chain::if_chain;
12 use rustc::ty::{self, TyCtxt};
14 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
15 use syntax::codemap::Span;
17 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
18 /// unless the annotated function is empty or simply panics.
20 /// **Why is this bad?** While there are valid uses of this annotation (and once
21 /// you know when to use it, by all means `allow` this lint), it's a common
22 /// newbie-mistake to pepper one's code with it.
24 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
25 /// measure if that additional function call really affects your runtime profile
26 /// sufficiently to make up for the increase in compile time.
28 /// **Known problems:** False positives, big time. This lint is meant to be
29 /// deactivated by everyone doing serious performance work. This means having
30 /// done the measurement.
35 /// fn not_quite_hot_code(..) { ... }
37 declare_clippy_lint! {
40 "use of `#[inline(always)]`"
43 /// **What it does:** Checks for `extern crate` and `use` items annotated with
46 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
47 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
48 /// `#[macro_use]` attribute.
50 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
51 /// likely a `!` was forgotten.
53 /// **Known problems:** None.
58 /// #[deny(dead_code)]
60 /// #[forbid(dead_code)]
64 /// #[allow(unused_imports)]
66 /// #[allow(unused_imports)]
70 declare_clippy_lint! {
71 pub USELESS_ATTRIBUTE,
73 "use of lint attributes on `extern crate` items"
76 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
77 /// field that is not a valid semantic version.
79 /// **Why is this bad?** For checking the version of the deprecation, it must be
80 /// a valid semver. Failing that, the contained information is useless.
82 /// **Known problems:** None.
86 /// #[deprecated(since = "forever")]
87 /// fn something_else(..) { ... }
89 declare_clippy_lint! {
90 pub DEPRECATED_SEMVER,
92 "use of `#[deprecated(since = \"x\")]` where x is not semver"
95 /// **What it does:** Checks for empty lines after outer attributes
97 /// **Why is this bad?**
98 /// Most likely the attribute was meant to be an inner attribute using a '!'.
99 /// If it was meant to be an outer attribute, then the following item
100 /// should not be separated by empty lines.
102 /// **Known problems:** Can cause false positives.
104 /// From the clippy side it's difficult to detect empty lines between an attributes and the
105 /// following item because empty lines and comments are not part of the AST. The parsing
106 /// currently works for basic cases but is not perfect.
111 /// #[inline(always)]
113 /// fn not_quite_good_code(..) { ... }
115 /// // Good (as inner attribute)
116 /// #![inline(always)]
118 /// fn this_is_fine(..) { ... }
120 /// // Good (as outer attribute)
121 /// #[inline(always)]
122 /// fn this_is_fine_too(..) { ... }
124 declare_clippy_lint! {
125 pub EMPTY_LINE_AFTER_OUTER_ATTR,
127 "empty line after outer attribute"
130 #[derive(Copy, Clone)]
133 impl LintPass for AttrPass {
134 fn get_lints(&self) -> LintArray {
139 EMPTY_LINE_AFTER_OUTER_ATTR
144 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
145 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
146 if let Some(ref items) = attr.meta_item_list() {
147 if items.is_empty() || attr.name() != "deprecated" {
152 if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
153 if let MetaItemKind::NameValue(ref lit) = mi.node;
154 if mi.name() == "since";
156 check_semver(cx, item.span, lit);
163 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
164 if is_relevant_item(cx.tcx, item) {
165 check_attrs(cx, item.span, item.name, &item.attrs)
168 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
169 let skip_unused_imports = item.attrs.iter().any(|attr| attr.name() == "macro_use");
171 for attr in &item.attrs {
172 if let Some(ref lint_list) = attr.meta_item_list() {
173 match &*attr.name().as_str() {
174 "allow" | "warn" | "deny" | "forbid" => {
175 // whitelist `unused_imports` and `deprecated` for `use` items
176 // and `unused_imports` for `extern crate` items with `macro_use`
177 for lint in lint_list {
179 ItemKind::Use(..) => if is_word(lint, "unused_imports")
180 || is_word(lint, "deprecated") {
183 ItemKind::ExternCrate(..) => if is_word(lint, "unused_imports")
184 && skip_unused_imports {
190 let line_span = last_line_of_span(cx, attr.span);
192 if let Some(mut sugg) = snippet_opt(cx, line_span) {
193 if sugg.contains("#[") {
198 "useless lint attribute",
200 sugg = sugg.replacen("#[", "#![", 1);
201 db.span_suggestion(line_span, "if you just forgot a `!`, use", sugg);
216 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
217 if is_relevant_impl(cx.tcx, item) {
218 check_attrs(cx, item.span, item.ident.name, &item.attrs)
222 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
223 if is_relevant_trait(cx.tcx, item) {
224 check_attrs(cx, item.span, item.ident.name, &item.attrs)
229 fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
230 if let ItemKind::Fn(_, _, _, eid) = item.node {
231 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
237 fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
239 ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
244 fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
246 TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
247 TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
248 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
254 fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
255 if let Some(stmt) = block.stmts.first() {
257 StmtKind::Decl(_, _) => true,
258 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
261 block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
265 fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
267 ExprKind::Block(ref block, _) => is_relevant_block(tcx, tables, block),
268 ExprKind::Ret(Some(ref e)) => is_relevant_expr(tcx, tables, e),
269 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
270 ExprKind::Call(ref path_expr, _) => if let ExprKind::Path(ref qpath) = path_expr.node {
271 if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
272 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
283 fn check_attrs(cx: &LateContext, span: Span, name: Name, attrs: &[Attribute]) {
289 if attr.is_sugared_doc {
292 if attr.style == AttrStyle::Outer {
293 if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
297 let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
298 let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
300 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
301 let lines = snippet.split('\n').collect::<Vec<_>>();
302 let lines = without_block_comments(lines);
304 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
307 EMPTY_LINE_AFTER_OUTER_ATTR,
308 begin_of_attr_to_item,
309 "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
315 if let Some(ref values) = attr.meta_item_list() {
316 if values.len() != 1 || attr.name() != "inline" {
319 if is_word(&values[0], "always") {
325 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
334 fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
335 if let LitKind::Str(ref is, _) = lit.node {
336 if Version::parse(&is.as_str()).is_ok() {
344 "the since field must contain a semver-compliant version",
348 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
349 if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
350 mi.is_word() && mi.name() == expected
356 // If the snippet is empty, it's an attribute that was inserted during macro
357 // expansion and we want to ignore those, because they could come from external
358 // sources that the user has no control over.
359 // For some reason these attributes don't have any expansion info on them, so
360 // we have to check it this way until there is a better way.
361 fn is_present_in_source(cx: &LateContext, span: Span) -> bool {
362 if let Some(snippet) = snippet_opt(cx, span) {
363 if snippet.is_empty() {