1 //! checks for attributes
3 use crate::reexport::*;
5 in_macro_or_desugar, is_present_in_source, last_line_of_span, match_def_path, paths, snippet_opt, span_lint,
6 span_lint_and_sugg, span_lint_and_then, without_block_comments,
8 use if_chain::if_chain;
11 in_external_macro, CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray,
12 LintContext, LintPass,
15 use rustc::{declare_lint_pass, declare_tool_lint};
16 use rustc_errors::Applicability;
18 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
19 use syntax::source_map::Span;
20 use syntax_pos::symbol::Symbol;
22 declare_clippy_lint! {
23 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
24 /// unless the annotated function is empty or simply panics.
26 /// **Why is this bad?** While there are valid uses of this annotation (and once
27 /// you know when to use it, by all means `allow` this lint), it's a common
28 /// newbie-mistake to pepper one's code with it.
30 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
31 /// measure if that additional function call really affects your runtime profile
32 /// sufficiently to make up for the increase in compile time.
34 /// **Known problems:** False positives, big time. This lint is meant to be
35 /// deactivated by everyone doing serious performance work. This means having
36 /// done the measurement.
41 /// fn not_quite_hot_code(..) { ... }
45 "use of `#[inline(always)]`"
48 declare_clippy_lint! {
49 /// **What it does:** Checks for `extern crate` and `use` items annotated with
52 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
53 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
54 /// `#[macro_use]` attribute.
56 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
57 /// likely a `!` was forgotten.
59 /// **Known problems:** None.
64 /// #[deny(dead_code)]
66 /// #[forbid(dead_code)]
70 /// #[allow(unused_imports)]
72 /// #[allow(unused_imports)]
76 pub USELESS_ATTRIBUTE,
78 "use of lint attributes on `extern crate` items"
81 declare_clippy_lint! {
82 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
83 /// field that is not a valid semantic version.
85 /// **Why is this bad?** For checking the version of the deprecation, it must be
86 /// a valid semver. Failing that, the contained information is useless.
88 /// **Known problems:** None.
92 /// #[deprecated(since = "forever")]
93 /// fn something_else() { /* ... */ }
95 pub DEPRECATED_SEMVER,
97 "use of `#[deprecated(since = \"x\")]` where x is not semver"
100 declare_clippy_lint! {
101 /// **What it does:** Checks for empty lines after outer attributes
103 /// **Why is this bad?**
104 /// Most likely the attribute was meant to be an inner attribute using a '!'.
105 /// If it was meant to be an outer attribute, then the following item
106 /// should not be separated by empty lines.
108 /// **Known problems:** Can cause false positives.
110 /// From the clippy side it's difficult to detect empty lines between an attributes and the
111 /// following item because empty lines and comments are not part of the AST. The parsing
112 /// currently works for basic cases but is not perfect.
117 /// #[inline(always)]
119 /// fn not_quite_good_code(..) { ... }
121 /// // Good (as inner attribute)
122 /// #![inline(always)]
124 /// fn this_is_fine(..) { ... }
126 /// // Good (as outer attribute)
127 /// #[inline(always)]
128 /// fn this_is_fine_too(..) { ... }
130 pub EMPTY_LINE_AFTER_OUTER_ATTR,
132 "empty line after outer attribute"
135 declare_clippy_lint! {
136 /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
137 /// lints and if those lints exist in clippy. If there is a uppercase letter in the lint name
138 /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
141 /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
143 /// **Known problems:** None.
148 /// #![warn(if_not_els)]
149 /// #![deny(clippy::All)]
154 /// #![warn(if_not_else)]
155 /// #![deny(clippy::all)]
157 pub UNKNOWN_CLIPPY_LINTS,
159 "unknown_lints for scoped Clippy lints"
162 declare_clippy_lint! {
163 /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
164 /// with `#[rustfmt::skip]`.
166 /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
167 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
169 /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
170 /// processed before the PreExpansionPass lints get executed. See
171 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
177 /// #[cfg_attr(rustfmt, rustfmt_skip)]
186 pub DEPRECATED_CFG_ATTR,
188 "usage of `cfg_attr(rustfmt)` instead of `tool_attributes`"
191 declare_lint_pass!(Attributes => [
195 EMPTY_LINE_AFTER_OUTER_ATTR,
196 UNKNOWN_CLIPPY_LINTS,
199 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes {
200 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
201 if let Some(items) = &attr.meta_item_list() {
202 if let Some(ident) = attr.ident() {
203 match &*ident.as_str() {
204 "allow" | "warn" | "deny" | "forbid" => {
205 check_clippy_lint_names(cx, items);
209 if items.is_empty() || !attr.check_name(sym!(deprecated)) {
214 if let NestedMetaItem::MetaItem(mi) = &item;
215 if let MetaItemKind::NameValue(lit) = &mi.node;
216 if mi.check_name(sym!(since));
218 check_semver(cx, item.span(), lit);
226 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
227 if is_relevant_item(cx, item) {
228 check_attrs(cx, item.span, item.ident.name, &item.attrs)
231 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
232 let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use)));
234 for attr in &item.attrs {
235 if in_external_macro(cx.sess(), attr.span) {
238 if let Some(lint_list) = &attr.meta_item_list() {
239 if let Some(ident) = attr.ident() {
240 match &*ident.as_str() {
241 "allow" | "warn" | "deny" | "forbid" => {
242 // whitelist `unused_imports` and `deprecated` for `use` items
243 // and `unused_imports` for `extern crate` items with `macro_use`
244 for lint in lint_list {
246 ItemKind::Use(..) => {
247 if is_word(lint, sym!(unused_imports))
248 || is_word(lint, sym!(deprecated))
253 ItemKind::ExternCrate(..) => {
254 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
257 if is_word(lint, sym!(unused_extern_crates)) {
264 let line_span = last_line_of_span(cx, attr.span);
266 if let Some(mut sugg) = snippet_opt(cx, line_span) {
267 if sugg.contains("#[") {
272 "useless lint attribute",
274 sugg = sugg.replacen("#[", "#![", 1);
277 "if you just forgot a `!`, use",
279 Applicability::MachineApplicable,
296 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
297 if is_relevant_impl(cx, item) {
298 check_attrs(cx, item.span, item.ident.name, &item.attrs)
302 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
303 if is_relevant_trait(cx, item) {
304 check_attrs(cx, item.span, item.ident.name, &item.attrs)
309 #[allow(clippy::single_match_else)]
310 fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) {
311 let lint_store = cx.lints();
314 if let Some(meta_item) = lint.meta_item();
315 if meta_item.path.segments.len() > 1;
316 if let tool_name = meta_item.path.segments[0].ident;
317 if tool_name.as_str() == "clippy";
318 let name = meta_item.path.segments.last().unwrap().ident.name;
319 if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(
321 Some(tool_name.as_str()),
326 UNKNOWN_CLIPPY_LINTS,
328 &format!("unknown clippy lint: clippy::{}", name),
330 if name.as_str().chars().any(char::is_uppercase) {
331 let name_lower = name.as_str().to_lowercase();
332 match lint_store.check_lint_name(
334 Some(tool_name.as_str())
336 // FIXME: can we suggest similar lint names here?
337 // https://github.com/rust-lang/rust/pull/56992
338 CheckLintNameResult::NoLint(None) => (),
342 "lowercase the lint name",
344 Applicability::MaybeIncorrect,
356 fn is_relevant_item(cx: &LateContext<'_, '_>, item: &Item) -> bool {
357 if let ItemKind::Fn(_, _, _, eid) = item.node {
358 is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
364 fn is_relevant_impl(cx: &LateContext<'_, '_>, item: &ImplItem) -> bool {
366 ImplItemKind::Method(_, eid) => is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value),
371 fn is_relevant_trait(cx: &LateContext<'_, '_>, item: &TraitItem) -> bool {
373 TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
374 TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
375 is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
381 fn is_relevant_block(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, block: &Block) -> bool {
382 if let Some(stmt) = block.stmts.first() {
384 StmtKind::Local(_) => true,
385 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, tables, expr),
389 block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e))
393 fn is_relevant_expr(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr) -> bool {
395 ExprKind::Block(block, _) => is_relevant_block(cx, tables, block),
396 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, tables, e),
397 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
398 ExprKind::Call(path_expr, _) => {
399 if let ExprKind::Path(qpath) = &path_expr.node {
400 if let Some(fun_id) = tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
401 !match_def_path(cx, fun_id, &paths::BEGIN_PANIC)
413 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
414 if in_macro_or_desugar(span) {
419 if attr.is_sugared_doc {
422 if attr.style == AttrStyle::Outer {
423 if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
427 let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
428 let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
430 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
431 let lines = snippet.split('\n').collect::<Vec<_>>();
432 let lines = without_block_comments(lines);
434 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
437 EMPTY_LINE_AFTER_OUTER_ATTR,
438 begin_of_attr_to_item,
439 "Found an empty line after an outer attribute. \
440 Perhaps you forgot to add a '!' to make it an inner attribute?",
446 if let Some(values) = attr.meta_item_list() {
447 if values.len() != 1 || !attr.check_name(sym!(inline)) {
450 if is_word(&values[0], sym!(always)) {
456 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
465 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
466 if let LitKind::Str(is, _) = lit.node {
467 if Version::parse(&is.as_str()).is_ok() {
475 "the since field must contain a semver-compliant version",
479 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
480 if let NestedMetaItem::MetaItem(mi) = &nmi {
481 mi.is_word() && mi.check_name(expected)
487 declare_lint_pass!(DeprecatedCfgAttribute => [DEPRECATED_CFG_ATTR]);
489 impl EarlyLintPass for DeprecatedCfgAttribute {
490 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
493 if attr.check_name(sym!(cfg_attr));
494 if let Some(items) = attr.meta_item_list();
496 // check for `rustfmt`
497 if let Some(feature_item) = items[0].meta_item();
498 if feature_item.check_name(sym!(rustfmt));
499 // check for `rustfmt_skip` and `rustfmt::skip`
500 if let Some(skip_item) = &items[1].meta_item();
501 if skip_item.check_name(sym!(rustfmt_skip)) ||
502 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
503 // Only lint outer attributes, because custom inner attributes are unstable
504 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
505 if let AttrStyle::Outer = attr.style;
511 "`cfg_attr` is deprecated for rustfmt and got replaced by tool_attributes",
513 "#[rustfmt::skip]".to_string(),
514 Applicability::MachineApplicable,