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 EMPTY_LINE_AFTER_OUTER_ATTR,
252 UNKNOWN_CLIPPY_LINTS,
255 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes {
256 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
257 if let Some(items) = &attr.meta_item_list() {
258 if let Some(ident) = attr.ident() {
259 match &*ident.as_str() {
260 "allow" | "warn" | "deny" | "forbid" => {
261 check_clippy_lint_names(cx, items);
265 if items.is_empty() || !attr.check_name(sym!(deprecated)) {
270 if let NestedMetaItem::MetaItem(mi) = &item;
271 if let MetaItemKind::NameValue(lit) = &mi.kind;
272 if mi.check_name(sym!(since));
274 check_semver(cx, item.span(), lit);
282 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item<'_>) {
283 if is_relevant_item(cx, item) {
284 check_attrs(cx, item.span, item.ident.name, &item.attrs)
287 ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
288 let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use)));
290 for attr in item.attrs {
291 if in_external_macro(cx.sess(), attr.span) {
294 if let Some(lint_list) = &attr.meta_item_list() {
295 if let Some(ident) = attr.ident() {
296 match &*ident.as_str() {
297 "allow" | "warn" | "deny" | "forbid" => {
298 // whitelist `unused_imports`, `deprecated` and `unreachable_pub` for `use` items
299 // and `unused_imports` for `extern crate` items with `macro_use`
300 for lint in lint_list {
302 ItemKind::Use(..) => {
303 if is_word(lint, sym!(unused_imports))
304 || is_word(lint, sym!(deprecated))
305 || is_word(lint, sym!(unreachable_pub))
306 || is_word(lint, sym!(unused))
311 ItemKind::ExternCrate(..) => {
312 if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
315 if is_word(lint, sym!(unused_extern_crates)) {
322 let line_span = first_line_of_span(cx, attr.span);
324 if let Some(mut sugg) = snippet_opt(cx, line_span) {
325 if sugg.contains("#[") {
330 "useless lint attribute",
332 sugg = sugg.replacen("#[", "#![", 1);
333 diag.span_suggestion(
335 "if you just forgot a `!`, use",
337 Applicability::MaybeIncorrect,
354 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem<'_>) {
355 if is_relevant_impl(cx, item) {
356 check_attrs(cx, item.span, item.ident.name, &item.attrs)
360 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem<'_>) {
361 if is_relevant_trait(cx, item) {
362 check_attrs(cx, item.span, item.ident.name, &item.attrs)
367 #[allow(clippy::single_match_else)]
368 fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) {
369 let lint_store = cx.lints();
372 if let Some(meta_item) = lint.meta_item();
373 if meta_item.path.segments.len() > 1;
374 if let tool_name = meta_item.path.segments[0].ident;
375 if tool_name.as_str() == "clippy";
376 let name = meta_item.path.segments.last().unwrap().ident.name;
377 if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(
379 Some(tool_name.name),
384 UNKNOWN_CLIPPY_LINTS,
386 &format!("unknown clippy lint: clippy::{}", name),
388 let name_lower = name.as_str().to_lowercase();
389 let symbols = lint_store.get_lints().iter().map(
390 |l| Symbol::intern(&l.name_lower())
391 ).collect::<Vec<_>>();
392 let sugg = find_best_match_for_name(
394 &format!("clippy::{}", name_lower),
397 if name.as_str().chars().any(char::is_uppercase)
398 && lint_store.find_lints(&format!("clippy::{}", name_lower)).is_ok() {
399 diag.span_suggestion(
401 "lowercase the lint name",
402 format!("clippy::{}", name_lower),
403 Applicability::MachineApplicable,
405 } else if let Some(sugg) = sugg {
406 diag.span_suggestion(
410 Applicability::MachineApplicable,
420 fn is_relevant_item(cx: &LateContext<'_, '_>, item: &Item<'_>) -> bool {
421 if let ItemKind::Fn(_, _, eid) = item.kind {
422 is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
428 fn is_relevant_impl(cx: &LateContext<'_, '_>, item: &ImplItem<'_>) -> bool {
430 ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value),
435 fn is_relevant_trait(cx: &LateContext<'_, '_>, item: &TraitItem<'_>) -> bool {
437 TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
438 TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
439 is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
445 fn is_relevant_block(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, block: &Block<'_>) -> bool {
446 if let Some(stmt) = block.stmts.first() {
448 StmtKind::Local(_) => true,
449 StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, tables, expr),
453 block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e))
457 fn is_relevant_expr(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr<'_>) -> bool {
459 ExprKind::Block(block, _) => is_relevant_block(cx, tables, block),
460 ExprKind::Ret(Some(e)) => is_relevant_expr(cx, tables, e),
461 ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
462 ExprKind::Call(path_expr, _) => {
463 if let ExprKind::Path(qpath) = &path_expr.kind {
464 if let Some(fun_id) = tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
465 !match_def_path(cx, fun_id, &paths::BEGIN_PANIC)
477 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
478 if span.from_expansion() {
483 let attr_item = if let AttrKind::Normal(ref attr) = attr.kind {
489 if attr.style == AttrStyle::Outer {
490 if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
494 let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
495 let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
497 if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
498 let lines = snippet.split('\n').collect::<Vec<_>>();
499 let lines = without_block_comments(lines);
501 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
504 EMPTY_LINE_AFTER_OUTER_ATTR,
505 begin_of_attr_to_item,
506 "Found an empty line after an outer attribute. \
507 Perhaps you forgot to add a `!` to make it an inner attribute?",
513 if let Some(values) = attr.meta_item_list() {
514 if values.len() != 1 || !attr.check_name(sym!(inline)) {
517 if is_word(&values[0], sym!(always)) {
523 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
532 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
533 if let LitKind::Str(is, _) = lit.kind {
534 if Version::parse(&is.as_str()).is_ok() {
542 "the since field must contain a semver-compliant version",
546 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
547 if let NestedMetaItem::MetaItem(mi) = &nmi {
548 mi.is_word() && mi.check_name(expected)
554 declare_lint_pass!(EarlyAttributes => [DEPRECATED_CFG_ATTR, MISMATCHED_TARGET_OS]);
556 impl EarlyLintPass for EarlyAttributes {
557 fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
558 check_deprecated_cfg_attr(cx, attr);
559 check_mismatched_target_os(cx, attr);
563 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
566 if attr.check_name(sym!(cfg_attr));
567 if let Some(items) = attr.meta_item_list();
569 // check for `rustfmt`
570 if let Some(feature_item) = items[0].meta_item();
571 if feature_item.check_name(sym!(rustfmt));
572 // check for `rustfmt_skip` and `rustfmt::skip`
573 if let Some(skip_item) = &items[1].meta_item();
574 if skip_item.check_name(sym!(rustfmt_skip)) ||
575 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
576 // Only lint outer attributes, because custom inner attributes are unstable
577 // Tracking issue: https://github.com/rust-lang/rust/issues/54726
578 if let AttrStyle::Outer = attr.style;
584 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
586 "#[rustfmt::skip]".to_string(),
587 Applicability::MachineApplicable,
593 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
594 fn find_os(name: &str) -> Option<&'static str> {
597 .chain(NON_UNIX_SYSTEMS.iter())
598 .find(|&&os| os == name)
602 fn is_unix(name: &str) -> bool {
603 UNIX_SYSTEMS.iter().any(|&os| os == name)
606 fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
607 let mut mismatched = Vec::new();
610 if let NestedMetaItem::MetaItem(meta) = item {
612 MetaItemKind::List(list) => {
613 mismatched.extend(find_mismatched_target_os(&list));
615 MetaItemKind::Word => {
617 if let Some(ident) = meta.ident();
618 if let Some(os) = find_os(&*ident.name.as_str());
620 mismatched.push((os, ident.span));
633 if attr.check_name(sym!(cfg));
634 if let Some(list) = attr.meta_item_list();
635 let mismatched = find_mismatched_target_os(&list);
636 if !mismatched.is_empty();
638 let mess = "operating system used in target family position";
640 span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, &mess, |diag| {
641 // Avoid showing the unix suggestion multiple times in case
642 // we have more than one mismatch for unix-like systems
643 let mut unix_suggested = false;
645 for (os, span) in mismatched {
646 let sugg = format!("target_os = \"{}\"", os);
647 diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
649 if !unix_suggested && is_unix(os) {
650 diag.help("Did you mean `unix`?");
651 unix_suggested = true;