]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/attrs.rs
Rollup merge of #89068 - bjorn3:restructure_rt2, r=joshtriplett
[rust.git] / src / tools / clippy / clippy_lints / src / attrs.rs
1 //! checks for attributes
2
3 use clippy_utils::diagnostics::{span_lint, span_lint_and_help, span_lint_and_sugg, span_lint_and_then};
4 use clippy_utils::match_panic_def_id;
5 use clippy_utils::source::{first_line_of_span, is_present_in_source, snippet_opt, without_block_comments};
6 use if_chain::if_chain;
7 use rustc_ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
8 use rustc_errors::Applicability;
9 use rustc_hir::{
10     Block, Expr, ExprKind, ImplItem, ImplItemKind, Item, ItemKind, StmtKind, TraitFn, TraitItem, TraitItemKind,
11 };
12 use rustc_lint::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
13 use rustc_middle::lint::in_external_macro;
14 use rustc_middle::ty;
15 use rustc_session::{declare_lint_pass, declare_tool_lint};
16 use rustc_span::source_map::Span;
17 use rustc_span::sym;
18 use rustc_span::symbol::{Symbol, SymbolStr};
19 use semver::Version;
20
21 static UNIX_SYSTEMS: &[&str] = &[
22     "android",
23     "dragonfly",
24     "emscripten",
25     "freebsd",
26     "fuchsia",
27     "haiku",
28     "illumos",
29     "ios",
30     "l4re",
31     "linux",
32     "macos",
33     "netbsd",
34     "openbsd",
35     "redox",
36     "solaris",
37     "vxworks",
38 ];
39
40 // NOTE: windows is excluded from the list because it's also a valid target family.
41 static NON_UNIX_SYSTEMS: &[&str] = &["hermit", "none", "wasi"];
42
43 declare_clippy_lint! {
44     /// ### What it does
45     /// Checks for items annotated with `#[inline(always)]`,
46     /// unless the annotated function is empty or simply panics.
47     ///
48     /// ### Why is this bad?
49     /// 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.
52     ///
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.
56     ///
57     /// ### Known problems
58     /// False positives, big time. This lint is meant to be
59     /// deactivated by everyone doing serious performance work. This means having
60     /// done the measurement.
61     ///
62     /// ### Example
63     /// ```ignore
64     /// #[inline(always)]
65     /// fn not_quite_hot_code(..) { ... }
66     /// ```
67     pub INLINE_ALWAYS,
68     pedantic,
69     "use of `#[inline(always)]`"
70 }
71
72 declare_clippy_lint! {
73     /// ### What it does
74     /// Checks for `extern crate` and `use` items annotated with
75     /// lint attributes.
76     ///
77     /// This lint permits `#[allow(unused_imports)]`, `#[allow(deprecated)]`,
78     /// `#[allow(unreachable_pub)]`, `#[allow(clippy::wildcard_imports)]` and
79     /// `#[allow(clippy::enum_glob_use)]` on `use` items and `#[allow(unused_imports)]` on
80     /// `extern crate` items with a `#[macro_use]` attribute.
81     ///
82     /// ### Why is this bad?
83     /// Lint attributes have no effect on crate imports. Most
84     /// likely a `!` was forgotten.
85     ///
86     /// ### Example
87     /// ```ignore
88     /// // Bad
89     /// #[deny(dead_code)]
90     /// extern crate foo;
91     /// #[forbid(dead_code)]
92     /// use foo::bar;
93     ///
94     /// // Ok
95     /// #[allow(unused_imports)]
96     /// use foo::baz;
97     /// #[allow(unused_imports)]
98     /// #[macro_use]
99     /// extern crate baz;
100     /// ```
101     pub USELESS_ATTRIBUTE,
102     correctness,
103     "use of lint attributes on `extern crate` items"
104 }
105
106 declare_clippy_lint! {
107     /// ### What it does
108     /// Checks for `#[deprecated]` annotations with a `since`
109     /// field that is not a valid semantic version.
110     ///
111     /// ### Why is this bad?
112     /// For checking the version of the deprecation, it must be
113     /// a valid semver. Failing that, the contained information is useless.
114     ///
115     /// ### Example
116     /// ```rust
117     /// #[deprecated(since = "forever")]
118     /// fn something_else() { /* ... */ }
119     /// ```
120     pub DEPRECATED_SEMVER,
121     correctness,
122     "use of `#[deprecated(since = \"x\")]` where x is not semver"
123 }
124
125 declare_clippy_lint! {
126     /// ### What it does
127     /// Checks for empty lines after outer attributes
128     ///
129     /// ### Why is this bad?
130     /// Most likely the attribute was meant to be an inner attribute using a '!'.
131     /// If it was meant to be an outer attribute, then the following item
132     /// should not be separated by empty lines.
133     ///
134     /// ### Known problems
135     /// Can cause false positives.
136     ///
137     /// From the clippy side it's difficult to detect empty lines between an attributes and the
138     /// following item because empty lines and comments are not part of the AST. The parsing
139     /// currently works for basic cases but is not perfect.
140     ///
141     /// ### Example
142     /// ```rust
143     /// // Good (as inner attribute)
144     /// #![allow(dead_code)]
145     ///
146     /// fn this_is_fine() { }
147     ///
148     /// // Bad
149     /// #[allow(dead_code)]
150     ///
151     /// fn not_quite_good_code() { }
152     ///
153     /// // Good (as outer attribute)
154     /// #[allow(dead_code)]
155     /// fn this_is_fine_too() { }
156     /// ```
157     pub EMPTY_LINE_AFTER_OUTER_ATTR,
158     nursery,
159     "empty line after outer attribute"
160 }
161
162 declare_clippy_lint! {
163     /// ### What it does
164     /// Checks for `warn`/`deny`/`forbid` attributes targeting the whole clippy::restriction category.
165     ///
166     /// ### Why is this bad?
167     /// Restriction lints sometimes are in contrast with other lints or even go against idiomatic rust.
168     /// These lints should only be enabled on a lint-by-lint basis and with careful consideration.
169     ///
170     /// ### Example
171     /// Bad:
172     /// ```rust
173     /// #![deny(clippy::restriction)]
174     /// ```
175     ///
176     /// Good:
177     /// ```rust
178     /// #![deny(clippy::as_conversions)]
179     /// ```
180     pub BLANKET_CLIPPY_RESTRICTION_LINTS,
181     suspicious,
182     "enabling the complete restriction group"
183 }
184
185 declare_clippy_lint! {
186     /// ### What it does
187     /// Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
188     /// with `#[rustfmt::skip]`.
189     ///
190     /// ### Why is this bad?
191     /// Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
192     /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
193     ///
194     /// ### Known problems
195     /// This lint doesn't detect crate level inner attributes, because they get
196     /// processed before the PreExpansionPass lints get executed. See
197     /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
198     ///
199     /// ### Example
200     /// Bad:
201     /// ```rust
202     /// #[cfg_attr(rustfmt, rustfmt_skip)]
203     /// fn main() { }
204     /// ```
205     ///
206     /// Good:
207     /// ```rust
208     /// #[rustfmt::skip]
209     /// fn main() { }
210     /// ```
211     pub DEPRECATED_CFG_ATTR,
212     complexity,
213     "usage of `cfg_attr(rustfmt)` instead of tool attributes"
214 }
215
216 declare_clippy_lint! {
217     /// ### What it does
218     /// Checks for cfg attributes having operating systems used in target family position.
219     ///
220     /// ### Why is this bad?
221     /// The configuration option will not be recognised and the related item will not be included
222     /// by the conditional compilation engine.
223     ///
224     /// ### Example
225     /// Bad:
226     /// ```rust
227     /// #[cfg(linux)]
228     /// fn conditional() { }
229     /// ```
230     ///
231     /// Good:
232     /// ```rust
233     /// #[cfg(target_os = "linux")]
234     /// fn conditional() { }
235     /// ```
236     ///
237     /// Or:
238     /// ```rust
239     /// #[cfg(unix)]
240     /// fn conditional() { }
241     /// ```
242     /// Check the [Rust Reference](https://doc.rust-lang.org/reference/conditional-compilation.html#target_os) for more details.
243     pub MISMATCHED_TARGET_OS,
244     correctness,
245     "usage of `cfg(operating_system)` instead of `cfg(target_os = \"operating_system\")`"
246 }
247
248 declare_lint_pass!(Attributes => [
249     INLINE_ALWAYS,
250     DEPRECATED_SEMVER,
251     USELESS_ATTRIBUTE,
252     BLANKET_CLIPPY_RESTRICTION_LINTS,
253 ]);
254
255 impl<'tcx> LateLintPass<'tcx> for Attributes {
256     fn check_attribute(&mut self, cx: &LateContext<'tcx>, attr: &'tcx Attribute) {
257         if let Some(items) = &attr.meta_item_list() {
258             if let Some(ident) = attr.ident() {
259                 if is_lint_level(ident.name) {
260                     check_clippy_lint_names(cx, ident.name, items);
261                 }
262                 if items.is_empty() || !attr.has_name(sym::deprecated) {
263                     return;
264                 }
265                 for item in items {
266                     if_chain! {
267                         if let NestedMetaItem::MetaItem(mi) = &item;
268                         if let MetaItemKind::NameValue(lit) = &mi.kind;
269                         if mi.has_name(sym::since);
270                         then {
271                             check_semver(cx, item.span(), lit);
272                         }
273                     }
274                 }
275             }
276         }
277     }
278
279     fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
280         let attrs = cx.tcx.hir().attrs(item.hir_id());
281         if is_relevant_item(cx, item) {
282             check_attrs(cx, item.span, item.ident.name, attrs);
283         }
284         match item.kind {
285             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
286                 let skip_unused_imports = attrs.iter().any(|attr| attr.has_name(sym::macro_use));
287
288                 for attr in attrs {
289                     if in_external_macro(cx.sess(), attr.span) {
290                         return;
291                     }
292                     if let Some(lint_list) = &attr.meta_item_list() {
293                         if attr.ident().map_or(false, |ident| is_lint_level(ident.name)) {
294                             // permit `unused_imports`, `deprecated`, `unreachable_pub`,
295                             // `clippy::wildcard_imports`, and `clippy::enum_glob_use` for `use` items
296                             // and `unused_imports` for `extern crate` items with `macro_use`
297                             for lint in lint_list {
298                                 match item.kind {
299                                     ItemKind::Use(..) => {
300                                         if is_word(lint, sym!(unused_imports))
301                                             || is_word(lint, sym::deprecated)
302                                             || is_word(lint, sym!(unreachable_pub))
303                                             || is_word(lint, sym!(unused))
304                                             || extract_clippy_lint(lint).map_or(false, |s| s == "wildcard_imports")
305                                             || extract_clippy_lint(lint).map_or(false, |s| s == "enum_glob_use")
306                                         {
307                                             return;
308                                         }
309                                     },
310                                     ItemKind::ExternCrate(..) => {
311                                         if is_word(lint, sym!(unused_imports)) && skip_unused_imports {
312                                             return;
313                                         }
314                                         if is_word(lint, sym!(unused_extern_crates)) {
315                                             return;
316                                         }
317                                     },
318                                     _ => {},
319                                 }
320                             }
321                             let line_span = first_line_of_span(cx, attr.span);
322
323                             if let Some(mut sugg) = snippet_opt(cx, line_span) {
324                                 if sugg.contains("#[") {
325                                     span_lint_and_then(
326                                         cx,
327                                         USELESS_ATTRIBUTE,
328                                         line_span,
329                                         "useless lint attribute",
330                                         |diag| {
331                                             sugg = sugg.replacen("#[", "#![", 1);
332                                             diag.span_suggestion(
333                                                 line_span,
334                                                 "if you just forgot a `!`, use",
335                                                 sugg,
336                                                 Applicability::MaybeIncorrect,
337                                             );
338                                         },
339                                     );
340                                 }
341                             }
342                         }
343                     }
344                 }
345             },
346             _ => {},
347         }
348     }
349
350     fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx ImplItem<'_>) {
351         if is_relevant_impl(cx, item) {
352             check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
353         }
354     }
355
356     fn check_trait_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx TraitItem<'_>) {
357         if is_relevant_trait(cx, item) {
358             check_attrs(cx, item.span, item.ident.name, cx.tcx.hir().attrs(item.hir_id()));
359         }
360     }
361 }
362
363 /// Returns the lint name if it is clippy lint.
364 fn extract_clippy_lint(lint: &NestedMetaItem) -> Option<SymbolStr> {
365     if_chain! {
366         if let Some(meta_item) = lint.meta_item();
367         if meta_item.path.segments.len() > 1;
368         if let tool_name = meta_item.path.segments[0].ident;
369         if tool_name.name == sym::clippy;
370         then {
371             let lint_name = meta_item.path.segments.last().unwrap().ident.name;
372             return Some(lint_name.as_str());
373         }
374     }
375     None
376 }
377
378 fn check_clippy_lint_names(cx: &LateContext<'_>, name: Symbol, items: &[NestedMetaItem]) {
379     for lint in items {
380         if let Some(lint_name) = extract_clippy_lint(lint) {
381             if lint_name == "restriction" && name != sym::allow {
382                 span_lint_and_help(
383                     cx,
384                     BLANKET_CLIPPY_RESTRICTION_LINTS,
385                     lint.span(),
386                     "restriction lints are not meant to be all enabled",
387                     None,
388                     "try enabling only the lints you really need",
389                 );
390             }
391         }
392     }
393 }
394
395 fn is_relevant_item(cx: &LateContext<'_>, item: &Item<'_>) -> bool {
396     if let ItemKind::Fn(_, _, eid) = item.kind {
397         is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
398     } else {
399         true
400     }
401 }
402
403 fn is_relevant_impl(cx: &LateContext<'_>, item: &ImplItem<'_>) -> bool {
404     match item.kind {
405         ImplItemKind::Fn(_, eid) => is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value),
406         _ => false,
407     }
408 }
409
410 fn is_relevant_trait(cx: &LateContext<'_>, item: &TraitItem<'_>) -> bool {
411     match item.kind {
412         TraitItemKind::Fn(_, TraitFn::Required(_)) => true,
413         TraitItemKind::Fn(_, TraitFn::Provided(eid)) => {
414             is_relevant_expr(cx, cx.tcx.typeck_body(eid), &cx.tcx.hir().body(eid).value)
415         },
416         _ => false,
417     }
418 }
419
420 fn is_relevant_block(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, block: &Block<'_>) -> bool {
421     block.stmts.first().map_or(
422         block
423             .expr
424             .as_ref()
425             .map_or(false, |e| is_relevant_expr(cx, typeck_results, e)),
426         |stmt| match &stmt.kind {
427             StmtKind::Local(_) => true,
428             StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, typeck_results, expr),
429             StmtKind::Item(_) => false,
430         },
431     )
432 }
433
434 fn is_relevant_expr(cx: &LateContext<'_>, typeck_results: &ty::TypeckResults<'_>, expr: &Expr<'_>) -> bool {
435     match &expr.kind {
436         ExprKind::Block(block, _) => is_relevant_block(cx, typeck_results, block),
437         ExprKind::Ret(Some(e)) => is_relevant_expr(cx, typeck_results, e),
438         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
439         ExprKind::Call(path_expr, _) => {
440             if let ExprKind::Path(qpath) = &path_expr.kind {
441                 typeck_results
442                     .qpath_res(qpath, path_expr.hir_id)
443                     .opt_def_id()
444                     .map_or(true, |fun_id| !match_panic_def_id(cx, fun_id))
445             } else {
446                 true
447             }
448         },
449         _ => true,
450     }
451 }
452
453 fn check_attrs(cx: &LateContext<'_>, span: Span, name: Symbol, attrs: &[Attribute]) {
454     if span.from_expansion() {
455         return;
456     }
457
458     for attr in attrs {
459         if let Some(values) = attr.meta_item_list() {
460             if values.len() != 1 || !attr.has_name(sym::inline) {
461                 continue;
462             }
463             if is_word(&values[0], sym::always) {
464                 span_lint(
465                     cx,
466                     INLINE_ALWAYS,
467                     attr.span,
468                     &format!(
469                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
470                         name
471                     ),
472                 );
473             }
474         }
475     }
476 }
477
478 fn check_semver(cx: &LateContext<'_>, span: Span, lit: &Lit) {
479     if let LitKind::Str(is, _) = lit.kind {
480         if Version::parse(&is.as_str()).is_ok() {
481             return;
482         }
483     }
484     span_lint(
485         cx,
486         DEPRECATED_SEMVER,
487         span,
488         "the since field must contain a semver-compliant version",
489     );
490 }
491
492 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
493     if let NestedMetaItem::MetaItem(mi) = &nmi {
494         mi.is_word() && mi.has_name(expected)
495     } else {
496         false
497     }
498 }
499
500 declare_lint_pass!(EarlyAttributes => [
501     DEPRECATED_CFG_ATTR,
502     MISMATCHED_TARGET_OS,
503     EMPTY_LINE_AFTER_OUTER_ATTR,
504 ]);
505
506 impl EarlyLintPass for EarlyAttributes {
507     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
508         check_empty_line_after_outer_attr(cx, item);
509     }
510
511     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
512         check_deprecated_cfg_attr(cx, attr);
513         check_mismatched_target_os(cx, attr);
514     }
515 }
516
517 fn check_empty_line_after_outer_attr(cx: &EarlyContext<'_>, item: &rustc_ast::Item) {
518     for attr in &item.attrs {
519         let attr_item = if let AttrKind::Normal(ref attr, _) = attr.kind {
520             attr
521         } else {
522             return;
523         };
524
525         if attr.style == AttrStyle::Outer {
526             if attr_item.args.inner_tokens().is_empty() || !is_present_in_source(cx, attr.span) {
527                 return;
528             }
529
530             let begin_of_attr_to_item = Span::new(attr.span.lo(), item.span.lo(), item.span.ctxt(), item.span.parent());
531             let end_of_attr_to_item = Span::new(attr.span.hi(), item.span.lo(), item.span.ctxt(), item.span.parent());
532
533             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
534                 let lines = snippet.split('\n').collect::<Vec<_>>();
535                 let lines = without_block_comments(lines);
536
537                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
538                     span_lint(
539                         cx,
540                         EMPTY_LINE_AFTER_OUTER_ATTR,
541                         begin_of_attr_to_item,
542                         "found an empty line after an outer attribute. \
543                         Perhaps you forgot to add a `!` to make it an inner attribute?",
544                     );
545                 }
546             }
547         }
548     }
549 }
550
551 fn check_deprecated_cfg_attr(cx: &EarlyContext<'_>, attr: &Attribute) {
552     if_chain! {
553         // check cfg_attr
554         if attr.has_name(sym::cfg_attr);
555         if let Some(items) = attr.meta_item_list();
556         if items.len() == 2;
557         // check for `rustfmt`
558         if let Some(feature_item) = items[0].meta_item();
559         if feature_item.has_name(sym::rustfmt);
560         // check for `rustfmt_skip` and `rustfmt::skip`
561         if let Some(skip_item) = &items[1].meta_item();
562         if skip_item.has_name(sym!(rustfmt_skip)) ||
563             skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym::skip;
564         // Only lint outer attributes, because custom inner attributes are unstable
565         // Tracking issue: https://github.com/rust-lang/rust/issues/54726
566         if attr.style == AttrStyle::Outer;
567         then {
568             span_lint_and_sugg(
569                 cx,
570                 DEPRECATED_CFG_ATTR,
571                 attr.span,
572                 "`cfg_attr` is deprecated for rustfmt and got replaced by tool attributes",
573                 "use",
574                 "#[rustfmt::skip]".to_string(),
575                 Applicability::MachineApplicable,
576             );
577         }
578     }
579 }
580
581 fn check_mismatched_target_os(cx: &EarlyContext<'_>, attr: &Attribute) {
582     fn find_os(name: &str) -> Option<&'static str> {
583         UNIX_SYSTEMS
584             .iter()
585             .chain(NON_UNIX_SYSTEMS.iter())
586             .find(|&&os| os == name)
587             .copied()
588     }
589
590     fn is_unix(name: &str) -> bool {
591         UNIX_SYSTEMS.iter().any(|&os| os == name)
592     }
593
594     fn find_mismatched_target_os(items: &[NestedMetaItem]) -> Vec<(&str, Span)> {
595         let mut mismatched = Vec::new();
596
597         for item in items {
598             if let NestedMetaItem::MetaItem(meta) = item {
599                 match &meta.kind {
600                     MetaItemKind::List(list) => {
601                         mismatched.extend(find_mismatched_target_os(list));
602                     },
603                     MetaItemKind::Word => {
604                         if_chain! {
605                             if let Some(ident) = meta.ident();
606                             if let Some(os) = find_os(&*ident.name.as_str());
607                             then {
608                                 mismatched.push((os, ident.span));
609                             }
610                         }
611                     },
612                     MetaItemKind::NameValue(..) => {},
613                 }
614             }
615         }
616
617         mismatched
618     }
619
620     if_chain! {
621         if attr.has_name(sym::cfg);
622         if let Some(list) = attr.meta_item_list();
623         let mismatched = find_mismatched_target_os(&list);
624         if !mismatched.is_empty();
625         then {
626             let mess = "operating system used in target family position";
627
628             span_lint_and_then(cx, MISMATCHED_TARGET_OS, attr.span, mess, |diag| {
629                 // Avoid showing the unix suggestion multiple times in case
630                 // we have more than one mismatch for unix-like systems
631                 let mut unix_suggested = false;
632
633                 for (os, span) in mismatched {
634                     let sugg = format!("target_os = \"{}\"", os);
635                     diag.span_suggestion(span, "try", sugg, Applicability::MaybeIncorrect);
636
637                     if !unix_suggested && is_unix(os) {
638                         diag.help("did you mean `unix`?");
639                         unix_suggested = true;
640                     }
641                 }
642             });
643         }
644     }
645 }
646
647 fn is_lint_level(symbol: Symbol) -> bool {
648     matches!(symbol, sym::allow | sym::warn | sym::deny | sym::forbid)
649 }