1 //! checks for attributes
3 use crate::reexport::*;
5 in_macro, last_line_of_span, match_def_path, paths, snippet_opt, span_lint, span_lint_and_sugg, span_lint_and_then,
6 without_block_comments,
8 use if_chain::if_chain;
11 CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintContext, LintPass,
13 use rustc::ty::{self, TyCtxt};
14 use rustc::{declare_tool_lint, lint_array};
15 use rustc_errors::Applicability;
17 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
18 use syntax::source_map::Span;
20 declare_clippy_lint! {
21 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
22 /// unless the annotated function is empty or simply panics.
24 /// **Why is this bad?** While there are valid uses of this annotation (and once
25 /// you know when to use it, by all means `allow` this lint), it's a common
26 /// newbie-mistake to pepper one's code with it.
28 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
29 /// measure if that additional function call really affects your runtime profile
30 /// sufficiently to make up for the increase in compile time.
32 /// **Known problems:** False positives, big time. This lint is meant to be
33 /// deactivated by everyone doing serious performance work. This means having
34 /// done the measurement.
39 /// fn not_quite_hot_code(..) { ... }
43 "use of `#[inline(always)]`"
46 declare_clippy_lint! {
47 /// **What it does:** Checks for `extern crate` and `use` items annotated with
50 /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
51 /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
52 /// `#[macro_use]` attribute.
54 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
55 /// likely a `!` was forgotten.
57 /// **Known problems:** None.
62 /// #[deny(dead_code)]
64 /// #[forbid(dead_code)]
68 /// #[allow(unused_imports)]
70 /// #[allow(unused_imports)]
74 pub USELESS_ATTRIBUTE,
76 "use of lint attributes on `extern crate` items"
79 declare_clippy_lint! {
80 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
81 /// field that is not a valid semantic version.
83 /// **Why is this bad?** For checking the version of the deprecation, it must be
84 /// a valid semver. Failing that, the contained information is useless.
86 /// **Known problems:** None.
90 /// #[deprecated(since = "forever")]
91 /// fn something_else() { /* ... */ }
93 pub DEPRECATED_SEMVER,
95 "use of `#[deprecated(since = \"x\")]` where x is not semver"
98 declare_clippy_lint! {
99 /// **What it does:** Checks for empty lines after outer attributes
101 /// **Why is this bad?**
102 /// Most likely the attribute was meant to be an inner attribute using a '!'.
103 /// If it was meant to be an outer attribute, then the following item
104 /// should not be separated by empty lines.
106 /// **Known problems:** Can cause false positives.
108 /// From the clippy side it's difficult to detect empty lines between an attributes and the
109 /// following item because empty lines and comments are not part of the AST. The parsing
110 /// currently works for basic cases but is not perfect.
115 /// #[inline(always)]
117 /// fn not_quite_good_code(..) { ... }
119 /// // Good (as inner attribute)
120 /// #![inline(always)]
122 /// fn this_is_fine(..) { ... }
124 /// // Good (as outer attribute)
125 /// #[inline(always)]
126 /// fn this_is_fine_too(..) { ... }
128 pub EMPTY_LINE_AFTER_OUTER_ATTR,
130 "empty line after outer attribute"
133 declare_clippy_lint! {
134 /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
135 /// lints and if those lints exist in clippy. If there is a uppercase letter in the lint name
136 /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
139 /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
141 /// **Known problems:** None.
146 /// #![warn(if_not_els)]
147 /// #![deny(clippy::All)]
152 /// #![warn(if_not_else)]
153 /// #![deny(clippy::all)]
155 pub UNKNOWN_CLIPPY_LINTS,
157 "unknown_lints for scoped Clippy lints"
160 declare_clippy_lint! {
161 /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
162 /// with `#[rustfmt::skip]`.
164 /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
165 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
167 /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
168 /// processed before the PreExpansionPass lints get executed. See
169 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
175 /// #[cfg_attr(rustfmt, rustfmt_skip)]
184 pub DEPRECATED_CFG_ATTR,
186 "usage of `cfg_attr(rustfmt)` instead of `tool_attributes`"
189 #[derive(Copy, Clone)]
192 impl LintPass for AttrPass {
193 fn get_lints(&self) -> LintArray {
198 EMPTY_LINE_AFTER_OUTER_ATTR,
199 UNKNOWN_CLIPPY_LINTS,
203 fn name(&self) -> &'static str {
208 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
209 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
210 if let Some(items) = &attr.meta_item_list() {
211 if let Some(ident) = attr.ident_str() {
213 "allow" | "warn" | "deny" | "forbid" => {
214 check_clippy_lint_names(cx, items);
218 if items.is_empty() || attr.name() != "deprecated" {
223 if let NestedMetaItem::MetaItem(mi) = &item;
224 if let MetaItemKind::NameValue(lit) = &mi.node;
225 if mi.name() == "since";
227 check_semver(cx, item.span, lit);
235 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
236 if is_relevant_item(cx.tcx, item) {
237 check_attrs(cx, item.span, item.ident.name, &item.attrs)
240 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
241 let skip_unused_imports = item.attrs.iter().any(|attr| attr.name() == "macro_use");
243 for attr in &item.attrs {
244 if let Some(lint_list) = &attr.meta_item_list() {
245 if let Some(ident) = attr.ident_str() {
247 "allow" | "warn" | "deny" | "forbid" => {
248 // whitelist `unused_imports` and `deprecated` for `use` items
249 // and `unused_imports` for `extern crate` items with `macro_use`
250 for lint in lint_list {
252 ItemKind::Use(..) => {
253 if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
257 ItemKind::ExternCrate(..) => {
258 if is_word(lint, "unused_imports") && skip_unused_imports {
261 if is_word(lint, "unused_extern_crates") {
268 let line_span = last_line_of_span(cx, attr.span);
270 if let Some(mut sugg) = snippet_opt(cx, line_span) {
271 if sugg.contains("#[") {
276 "useless lint attribute",
278 sugg = sugg.replacen("#[", "#![", 1);
281 "if you just forgot a `!`, use",
283 Applicability::MachineApplicable,
300 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
301 if is_relevant_impl(cx.tcx, item) {
302 check_attrs(cx, item.span, item.ident.name, &item.attrs)
306 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
307 if is_relevant_trait(cx.tcx, item) {
308 check_attrs(cx, item.span, item.ident.name, &item.attrs)
313 #[allow(clippy::single_match_else)]
314 fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) {
315 let lint_store = cx.lints();
318 if let Some(word) = lint.word();
319 if let Some(tool_name) = word.is_scoped();
320 if tool_name.as_str() == "clippy";
321 let name = word.name();
322 if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(
324 Some(tool_name.as_str()),
329 UNKNOWN_CLIPPY_LINTS,
331 &format!("unknown clippy lint: clippy::{}", name),
333 if name.as_str().chars().any(char::is_uppercase) {
334 let name_lower = name.as_str().to_lowercase();
335 match lint_store.check_lint_name(
337 Some(tool_name.as_str())
339 // FIXME: can we suggest similar lint names here?
340 // https://github.com/rust-lang/rust/pull/56992
341 CheckLintNameResult::NoLint(None) => (),
345 "lowercase the lint name",
347 Applicability::MaybeIncorrect,
359 fn is_relevant_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &Item) -> bool {
360 if let ItemKind::Fn(_, _, _, eid) = item.node {
361 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir().body(eid).value)
367 fn is_relevant_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &ImplItem) -> bool {
369 ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir().body(eid).value),
374 fn is_relevant_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, item: &TraitItem) -> bool {
376 TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
377 TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
378 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir().body(eid).value)
384 fn is_relevant_block<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, tables: &ty::TypeckTables<'_>, block: &Block) -> bool {
385 if let Some(stmt) = block.stmts.first() {
387 StmtKind::Local(_) => true,
388 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(tcx, tables, expr),
392 block.expr.as_ref().map_or(false, |e| is_relevant_expr(tcx, tables, e))
396 fn is_relevant_expr<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, tables: &ty::TypeckTables<'_>, expr: &Expr) -> bool {
398 ExprKind::Block(block, _) => is_relevant_block(tcx, tables, block),
399 ExprKind::Ret(Some(e)) => is_relevant_expr(tcx, tables, e),
400 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
401 ExprKind::Call(path_expr, _) => {
402 if let ExprKind::Path(qpath) = &path_expr.node {
403 if let Some(fun_id) = tables.qpath_def(qpath, path_expr.hir_id).opt_def_id() {
404 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
416 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
422 if attr.is_sugared_doc {
425 if attr.style == AttrStyle::Outer {
426 if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
430 let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
431 let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
433 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
434 let lines = snippet.split('\n').collect::<Vec<_>>();
435 let lines = without_block_comments(lines);
437 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
440 EMPTY_LINE_AFTER_OUTER_ATTR,
441 begin_of_attr_to_item,
442 "Found an empty line after an outer attribute. \
443 Perhaps you forgot to add a '!' to make it an inner attribute?",
449 if let Some(values) = attr.meta_item_list() {
450 if values.len() != 1 || attr.name() != "inline" {
453 if is_word(&values[0], "always") {
459 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
468 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
469 if let LitKind::Str(is, _) = lit.node {
470 if Version::parse(&is.as_str()).is_ok() {
478 "the since field must contain a semver-compliant version",
482 fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
483 if let NestedMetaItem::MetaItem(mi) = &nmi {
484 mi.is_word() && mi.name() == expected
490 // If the snippet is empty, it's an attribute that was inserted during macro
491 // expansion and we want to ignore those, because they could come from external
492 // sources that the user has no control over.
493 // For some reason these attributes don't have any expansion info on them, so
494 // we have to check it this way until there is a better way.
495 fn is_present_in_source(cx: &LateContext<'_, '_>, span: Span) -> bool {
496 if let Some(snippet) = snippet_opt(cx, span) {
497 if snippet.is_empty() {
504 #[derive(Copy, Clone)]
505 pub struct CfgAttrPass;
507 impl LintPass for CfgAttrPass {
508 fn get_lints(&self) -> LintArray {
509 lint_array!(DEPRECATED_CFG_ATTR,)
512 fn name(&self) -> &'static str {
513 "DeprecatedCfgAttribute"
517 impl EarlyLintPass for CfgAttrPass {
518 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
521 if attr.name() == "cfg_attr";
522 if let Some(items) = attr.meta_item_list();
524 // check for `rustfmt`
525 if let Some(feature_item) = items[0].meta_item();
526 if feature_item.name() == "rustfmt";
527 // check for `rustfmt_skip` and `rustfmt::skip`
528 if let Some(skip_item) = &items[1].meta_item();
529 if skip_item.name() == "rustfmt_skip" || skip_item.name() == "skip";
530 // Only lint outer attributes, because custom inner attributes are unstable
531 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
532 if let AttrStyle::Outer = attr.style;
538 "`cfg_attr` is deprecated for rustfmt and got replaced by tool_attributes",
540 "#[rustfmt::skip]".to_string(),
541 Applicability::MachineApplicable,