1 //! checks for attributes
3 use crate::reexport::Name;
5 first_line_of_span, is_present_in_source, match_def_path, paths, snippet_opt, span_lint, span_lint_and_sugg,
6 span_lint_and_then, without_block_comments,
8 use if_chain::if_chain;
9 use rustc_ast::ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
10 use rustc_ast::util::lev_distance::find_best_match_for_name;
11 use rustc_errors::Applicability;
13 Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
15 use rustc_lint::{CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
16 use rustc_middle::lint::in_external_macro;
18 use rustc_session::{declare_lint_pass, declare_tool_lint};
19 use rustc_span::source_map::Span;
20 use rustc_span::symbol::Symbol;
23 static UNIX_SYSTEMS: &[&str] = &[
42 // NOTE: windows is excluded from the list because it's also a valid target family.
43 static NON_UNIX_SYSTEMS: &[&str] = &["cloudabi", "hermit", "none", "wasi"];
45 declare_clippy_lint! {
46 /// **What it does:** Checks for items annotated with `#[inline(always)]`,
47 /// unless the annotated function is empty or simply panics.
49 /// **Why is this bad?** While there are valid uses of this annotation (and once
50 /// you know when to use it, by all means `allow` this lint), it's a common
51 /// newbie-mistake to pepper one's code with it.
53 /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
54 /// measure if that additional function call really affects your runtime profile
55 /// sufficiently to make up for the increase in compile time.
57 /// **Known problems:** False positives, big time. This lint is meant to be
58 /// deactivated by everyone doing serious performance work. This means having
59 /// done the measurement.
64 /// fn not_quite_hot_code(..) { ... }
68 "use of `#[inline(always)]`"
71 declare_clippy_lint! {
72 /// **What it does:** Checks for `extern crate` and `use` items annotated with
75 /// This lint whitelists `#[allow(unused_imports)]`, `#[allow(deprecated)]` and
76 /// `#[allow(unreachable_pub)]` on `use` items and `#[allow(unused_imports)]` on
77 /// `extern crate` items with a `#[macro_use]` attribute.
79 /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
80 /// likely a `!` was forgotten.
82 /// **Known problems:** None.
87 /// #[deny(dead_code)]
89 /// #[forbid(dead_code)]
93 /// #[allow(unused_imports)]
95 /// #[allow(unused_imports)]
99 pub USELESS_ATTRIBUTE,
101 "use of lint attributes on `extern crate` items"
104 declare_clippy_lint! {
105 /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
106 /// field that is not a valid semantic version.
108 /// **Why is this bad?** For checking the version of the deprecation, it must be
109 /// a valid semver. Failing that, the contained information is useless.
111 /// **Known problems:** None.
115 /// #[deprecated(since = "forever")]
116 /// fn something_else() { /* ... */ }
118 pub DEPRECATED_SEMVER,
120 "use of `#[deprecated(since = \"x\")]` where x is not semver"
123 declare_clippy_lint! {
124 /// **What it does:** Checks for empty lines after outer attributes
126 /// **Why is this bad?**
127 /// Most likely the attribute was meant to be an inner attribute using a '!'.
128 /// If it was meant to be an outer attribute, then the following item
129 /// should not be separated by empty lines.
131 /// **Known problems:** Can cause false positives.
133 /// From the clippy side it's difficult to detect empty lines between an attributes and the
134 /// following item because empty lines and comments are not part of the AST. The parsing
135 /// currently works for basic cases but is not perfect.
139 /// // Good (as inner attribute)
140 /// #![inline(always)]
142 /// fn this_is_fine() { }
145 /// #[inline(always)]
147 /// fn not_quite_good_code() { }
149 /// // Good (as outer attribute)
150 /// #[inline(always)]
151 /// fn this_is_fine_too() { }
153 pub EMPTY_LINE_AFTER_OUTER_ATTR,
155 "empty line after outer attribute"
158 declare_clippy_lint! {
159 /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
160 /// lints and if those lints exist in clippy. If there is an uppercase letter in the lint name
161 /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
164 /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
166 /// **Known problems:** None.
171 /// #![warn(if_not_els)]
172 /// #![deny(clippy::All)]
177 /// #![warn(if_not_else)]
178 /// #![deny(clippy::all)]
180 pub UNKNOWN_CLIPPY_LINTS,
182 "unknown_lints for scoped Clippy lints"
185 declare_clippy_lint! {
186 /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
187 /// with `#[rustfmt::skip]`.
189 /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
190 /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
192 /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
193 /// processed before the PreExpansionPass lints get executed. See
194 /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
200 /// #[cfg_attr(rustfmt, rustfmt_skip)]
209 pub DEPRECATED_CFG_ATTR,
211 "usage of `cfg_attr(rustfmt)` instead of tool attributes"
214 declare_clippy_lint! {
215 /// **What it does:** Checks for cfg attributes having operating systems used in target family position.
217 /// **Why is this bad?** The configuration option will not be recognised and the related item will not be included
218 /// by the conditional compilation engine.
220 /// **Known problems:** None.
227 /// fn conditional() { }
232 /// #[cfg(target_os = "linux")]
233 /// fn conditional() { }
239 /// fn conditional() { }
241 /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
242 pub MISMATCHED_TARGET_OS,
244 "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
247 declare_lint_pass!(Attributes => [
251 UNKNOWN_CLIPPY_LINTS,
254 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes {
255 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
256 if let Some(items) = &attr.meta_item_list() {
257 if let Some(ident) = attr.ident() {
258 match &*ident.as_str() {
259 "allow" | "warn" | "deny" | "forbid" => {
260 check_clippy_lint_names(cx, items);
264 if items.is_empty() || !attr.check_name(sym!(deprecated)) {
269 if let NestedMetaItem::MetaItem(mi) = &item;
270 if let MetaItemKind::NameValue(lit) = &mi.kind;
271 if mi.check_name(sym!(since));
273 check_semver(cx, item.span(), lit);
281 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
282 if is_relevant_item(cx, item) {
283 check_attrs(cx, item.span, item.ident.name, &item.attrs)
286 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
287 let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use)));
289 for attr in item.attrs {
290 if in_external_macro(cx.sess(), attr.span) {
293 if let Some(lint_list) = &attr.meta_item_list() {
294 if let Some(ident) = attr.ident() {
295 match &*ident.as_str() {
296 "allow" | "warn" | "deny" | "forbid" => {
297 // whitelist `unused_imports`, `deprecated` and `unreachable_pub` for `use` items
298 // and `unused_imports` for `extern crate` items with `macro_use`
299 for lint in lint_list {
301 ItemKind::Use(..) => {
302 if is_word(lint, sym!(unused_imports))
303 || is_word(lint, sym!(deprecated))
304 || is_word(lint, sym!(unreachable_pub))
305 || is_word(lint, sym!(unused))
310 ItemKind::ExternCrate(..) => {
311 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
314 if is_word(lint, sym!(unused_extern_crates)) {
321 let line_span = first_line_of_span(cx, attr.span);
323 if let Some(mut sugg) = snippet_opt(cx, line_span) {
324 if sugg.contains("#[") {
329 "useless lint attribute",
331 sugg = sugg.replacen("#[", "#![", 1);
332 diag.span_suggestion(
334 "if you just forgot a `!`, use",
336 Applicability::MaybeIncorrect,
353 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
354 if is_relevant_impl(cx, item) {
355 check_attrs(cx, item.span, item.ident.name, &item.attrs)
359 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
360 if is_relevant_trait(cx, item) {
361 check_attrs(cx, item.span, item.ident.name, &item.attrs)
366 #[allow(clippy::single_match_else)]
367 fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) {
368 let lint_store = cx.lints();
371 if let Some(meta_item) = lint.meta_item();
372 if meta_item.path.segments.len() > 1;
373 if let tool_name = meta_item.path.segments[0].ident;
374 if tool_name.as_str() == "clippy";
375 let name = meta_item.path.segments.last().unwrap().ident.name;
376 if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(
378 Some(tool_name.name),
383 UNKNOWN_CLIPPY_LINTS,
385 &format!("unknown clippy lint: clippy::{}", name),
387 let name_lower = name.as_str().to_lowercase();
388 let symbols = lint_store.get_lints().iter().map(
389 |l| Symbol::intern(&l.name_lower())
390 ).collect::<Vec<_>>();
391 let sugg = find_best_match_for_name(
393 &format!("clippy::{}", name_lower),
396 if name.as_str().chars().any(char::is_uppercase)
397 && lint_store.find_lints(&format!("clippy::{}", name_lower)).is_ok() {
398 diag.span_suggestion(
400 "lowercase the lint name",
401 format!("clippy::{}", name_lower),
402 Applicability::MachineApplicable,
404 } else if let Some(sugg) = sugg {
405 diag.span_suggestion(
409 Applicability::MachineApplicable,
419 fn is_relevant_item(cx: &LateContext<'_, '_>, item: &Item<'_>) -> bool {
420 if let ItemKind::Fn(_, _, eid) = item.kind {
421 is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
427 fn is_relevant_impl(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) -> bool {
429 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value),
434 fn is_relevant_trait(cx: &LateContext<'_, '_>, item: &TraitItem<'_>) -> bool {
436 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
437 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
438 is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
444 fn is_relevant_block(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, block: &Block<'_>) -> bool {
445 if let Some(stmt) = block.stmts.first() {
447 StmtKind::Local(_) => true,
448 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, tables, expr),
452 block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e))
456 fn is_relevant_expr(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr<'_>) -> bool {
458 ExprKind::Block(block, _) => is_relevant_block(cx, tables, block),
459 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, tables, e),
460 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
461 ExprKind::Call(path_expr, _) => {
462 if let ExprKind::Path(qpath) = &path_expr.kind {
463 if let Some(fun_id) = tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
464 !match_def_path(cx, fun_id, &paths::BEGIN_PANIC)
476 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
477 if span.from_expansion() {
482 if let Some(values) = attr.meta_item_list() {
483 if values.len() != 1 || !attr.check_name(sym!(inline)) {
486 if is_word(&values[0], sym!(always)) {
492 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
501 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
502 if let LitKind::Str(is, _) = lit.kind {
503 if Version::parse(&is.as_str()).is_ok() {
511 "the since field must contain a semver-compliant version",
515 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
516 if let NestedMetaItem::MetaItem(mi) = &nmi {
517 mi.is_word() && mi.check_name(expected)
523 declare_lint_pass!(EarlyAttributes => [
525 MISMATCHED_TARGET_OS,
526 EMPTY_LINE_AFTER_OUTER_ATTR,
529 impl EarlyLintPass for EarlyAttributes {
530 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::ast::Item) {
531 check_empty_line_after_outer_attr(cx, item);
534 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
535 check_deprecated_cfg_attr(cx, attr);
536 check_mismatched_target_os(cx, attr);
540 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::ast::Item) {
541 for attr in &item.attrs {
542 let attr_item = if let AttrKind::Normal(ref attr) = attr.kind {
548 if attr.style == AttrStyle::Outer {
549 if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
553 let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt());
554 let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt());
556 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
557 let lines = snippet.split('\n').collect::<Vec<_>>();
558 let lines = without_block_comments(lines);
560 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
563 EMPTY_LINE_AFTER_OUTER_ATTR,
564 begin_of_attr_to_item,
565 "Found an empty line after an outer attribute. \
566 Perhaps you forgot to add a `!` to make it an inner attribute?",
574 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
577 if attr.check_name(sym!(cfg_attr));
578 if let Some(items) = attr.meta_item_list();
580 // check for `rustfmt`
581 if let Some(feature_item) = items[0].meta_item();
582 if feature_item.check_name(sym!(rustfmt));
583 // check for `rustfmt_skip` and `rustfmt::skip`
584 if let Some(skip_item) = &items[1].meta_item();
585 if skip_item.check_name(sym!(rustfmt_skip)) ||
586 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
587 // Only lint outer attributes, because custom inner attributes are unstable
588 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
589 if let AttrStyle::Outer = attr.style;
595 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
597 "#[rustfmt::skip]".to_string(),
598 Applicability::MachineApplicable,
604 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
605 fn find_os(name: &str) -> Option<&'static str> {
608 .chain(NON_UNIX_SYSTEMS.iter())
609 .find(|&&os| os == name)
613 fn is_unix(name: &str) -> bool {
614 UNIX_SYSTEMS.iter().any(|&os| os == name)
617 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
618 let mut mismatched = Vec::new();
621 if let NestedMetaItem::MetaItem(meta) = item {
623 MetaItemKind::List(list) => {
624 mismatched.extend(find_mismatched_target_os(&list));
626 MetaItemKind::Word => {
628 if let Some(ident) = meta.ident();
629 if let Some(os) = find_os(&*ident.name.as_str());
631 mismatched.push((os, ident.span));
644 if attr.check_name(sym!(cfg));
645 if let Some(list) = attr.meta_item_list();
646 let mismatched = find_mismatched_target_os(&list);
647 if !mismatched.is_empty();
649 let mess = "operating system used in target family position";
651 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, &mess, |diag| {
652 // Avoid showing the unix suggestion multiple times in case
653 // we have more than one mismatch for unix-like systems
654 let mut unix_suggested = false;
656 for (os, span) in mismatched {
657 let sugg = format!("target_os = \"{}\"", os);
658 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
660 if !unix_suggested && is_unix(os) {
661 diag.help("Did you mean `unix`?");
662 unix_suggested = true;