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,
8 use crate::rustc::hir::*;
9 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
10 use crate::rustc::{declare_tool_lint, lint_array};
11 use if_chain::if_chain;
12 use crate::rustc::ty::{self, TyCtxt};
14 use crate::syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
15 use crate::syntax::source_map::Span;
16 use crate::rustc_errors::Applicability;
18 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
19 /// unless the annotated function is empty or simply panics.
21 /// **Why is this bad?** While there are valid uses of this annotation (and once
22 /// you know when to use it, by all means `allow` this lint), it's a common
23 /// newbie-mistake to pepper one's code with it.
25 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
26 /// measure if that additional function call really affects your runtime profile
27 /// sufficiently to make up for the increase in compile time.
29 /// **Known problems:** False positives, big time. This lint is meant to be
30 /// deactivated by everyone doing serious performance work. This means having
31 /// done the measurement.
36 /// fn not_quite_hot_code(..) { ... }
38 declare_clippy_lint! {
41 "use of `#[inline(always)]`"
44 /// **What it does:** Checks for `extern crate` and `use` items annotated with
47 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
48 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
49 /// `#[macro_use]` attribute.
51 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
52 /// likely a `!` was forgotten.
54 /// **Known problems:** None.
59 /// #[deny(dead_code)]
61 /// #[forbid(dead_code)]
65 /// #[allow(unused_imports)]
67 /// #[allow(unused_imports)]
71 declare_clippy_lint! {
72 pub USELESS_ATTRIBUTE,
74 "use of lint attributes on `extern crate` items"
77 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
78 /// field that is not a valid semantic version.
80 /// **Why is this bad?** For checking the version of the deprecation, it must be
81 /// a valid semver. Failing that, the contained information is useless.
83 /// **Known problems:** None.
87 /// #[deprecated(since = "forever")]
88 /// fn something_else(..) { ... }
90 declare_clippy_lint! {
91 pub DEPRECATED_SEMVER,
93 "use of `#[deprecated(since = \"x\")]` where x is not semver"
96 /// **What it does:** Checks for empty lines after outer attributes
98 /// **Why is this bad?**
99 /// Most likely the attribute was meant to be an inner attribute using a '!'.
100 /// If it was meant to be an outer attribute, then the following item
101 /// should not be separated by empty lines.
103 /// **Known problems:** Can cause false positives.
105 /// From the clippy side it's difficult to detect empty lines between an attributes and the
106 /// following item because empty lines and comments are not part of the AST. The parsing
107 /// currently works for basic cases but is not perfect.
112 /// #[inline(always)]
114 /// fn not_quite_good_code(..) { ... }
116 /// // Good (as inner attribute)
117 /// #![inline(always)]
119 /// fn this_is_fine(..) { ... }
121 /// // Good (as outer attribute)
122 /// #[inline(always)]
123 /// fn this_is_fine_too(..) { ... }
125 declare_clippy_lint! {
126 pub EMPTY_LINE_AFTER_OUTER_ATTR,
128 "empty line after outer attribute"
131 #[derive(Copy, Clone)]
134 impl LintPass for AttrPass {
135 fn get_lints(&self) -> LintArray {
140 EMPTY_LINE_AFTER_OUTER_ATTR
145 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
146 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
147 if let Some(ref items) = attr.meta_item_list() {
148 if items.is_empty() || attr.name() != "deprecated" {
153 if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
154 if let MetaItemKind::NameValue(ref lit) = mi.node;
155 if mi.name() == "since";
157 check_semver(cx, item.span, lit);
164 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
165 if is_relevant_item(cx.tcx, item) {
166 check_attrs(cx, item.span, item.name, &item.attrs)
169 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
170 let skip_unused_imports = item.attrs.iter().any(|attr| attr.name() == "macro_use");
172 for attr in &item.attrs {
173 if let Some(ref lint_list) = attr.meta_item_list() {
174 match &*attr.name().as_str() {
175 "allow" | "warn" | "deny" | "forbid" => {
176 // whitelist `unused_imports` and `deprecated` for `use` items
177 // and `unused_imports` for `extern crate` items with `macro_use`
178 for lint in lint_list {
180 ItemKind::Use(..) => if is_word(lint, "unused_imports")
181 || is_word(lint, "deprecated") {
184 ItemKind::ExternCrate(..) => {
185 if is_word(lint, "unused_imports")
186 && skip_unused_imports {
189 if is_word(lint, "unused_extern_crates") {
196 let line_span = last_line_of_span(cx, attr.span);
198 if let Some(mut sugg) = snippet_opt(cx, line_span) {
199 if sugg.contains("#[") {
204 "useless lint attribute",
206 sugg = sugg.replacen("#[", "#![", 1);
207 db.span_suggestion_with_applicability(
209 "if you just forgot a `!`, use",
211 Applicability::Unspecified,
227 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
228 if is_relevant_impl(cx.tcx, item) {
229 check_attrs(cx, item.span, item.ident.name, &item.attrs)
233 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
234 if is_relevant_trait(cx.tcx, item) {
235 check_attrs(cx, item.span, item.ident.name, &item.attrs)
240 fn is_relevant_item(tcx: TyCtxt<'_, '_, '_>, item: &Item) -> bool {
241 if let ItemKind::Fn(_, _, _, eid) = item.node {
242 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
248 fn is_relevant_impl(tcx: TyCtxt<'_, '_, '_>, item: &ImplItem) -> bool {
250 ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
255 fn is_relevant_trait(tcx: TyCtxt<'_, '_, '_>, item: &TraitItem) -> bool {
257 TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
258 TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
259 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
265 fn is_relevant_block(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>, block: &Block) -> bool {
266 if let Some(stmt) = block.stmts.first() {
268 StmtKind::Decl(_, _) => true,
269 StmtKind::Expr(ref expr, _) | StmtKind::Semi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
272 block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
276 fn is_relevant_expr(tcx: TyCtxt<'_, '_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr) -> bool {
278 ExprKind::Block(ref block, _) => is_relevant_block(tcx, tables, block),
279 ExprKind::Ret(Some(ref e)) => is_relevant_expr(tcx, tables, e),
280 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
281 ExprKind::Call(ref path_expr, _) => if let ExprKind::Path(ref qpath) = path_expr.node {
282 if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
283 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
294 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
300 if attr.is_sugared_doc {
303 if attr.style == AttrStyle::Outer {
304 if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
308 let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
309 let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
311 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
312 let lines = snippet.split('\n').collect::<Vec<_>>();
313 let lines = without_block_comments(lines);
315 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
318 EMPTY_LINE_AFTER_OUTER_ATTR,
319 begin_of_attr_to_item,
320 "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
326 if let Some(ref values) = attr.meta_item_list() {
327 if values.len() != 1 || attr.name() != "inline" {
330 if is_word(&values[0], "always") {
336 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
345 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
346 if let LitKind::Str(ref is, _) = lit.node {
347 if Version::parse(&is.as_str()).is_ok() {
355 "the since field must contain a semver-compliant version",
359 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
360 if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
361 mi.is_word() && mi.name() == expected
367 // If the snippet is empty, it's an attribute that was inserted during macro
368 // expansion and we want to ignore those, because they could come from external
369 // sources that the user has no control over.
370 // For some reason these attributes don't have any expansion info on them, so
371 // we have to check it this way until there is a better way.
372 fn is_present_in_source(cx: &LateContext<'_, '_>, span: Span) -> bool {
373 if let Some(snippet) = snippet_opt(cx, span) {
374 if snippet.is_empty() {