]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Merge remote-tracking branch 'origin/rust-1.34.1' into HEAD
[rust.git] / clippy_lints / src / attrs.rs
1 //! checks for attributes
2
3 use crate::reexport::*;
4 use crate::utils::sym;
5 use crate::utils::{
6     in_macro_or_desugar, is_present_in_source, last_line_of_span, match_def_path, paths, snippet_opt, span_lint,
7     span_lint_and_sugg, span_lint_and_then, without_block_comments,
8 };
9 use if_chain::if_chain;
10 use rustc::hir::*;
11 use rustc::lint::{
12     in_external_macro, CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray,
13     LintContext, LintPass,
14 };
15 use rustc::ty;
16 use rustc::{declare_lint_pass, declare_tool_lint};
17 use rustc_errors::Applicability;
18 use semver::Version;
19 use syntax::ast::{AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
20 use syntax::source_map::Span;
21 use syntax::symbol::Symbol;
22
23 declare_clippy_lint! {
24     /// **What it does:** Checks for items annotated with `#[inline(always)]`,
25     /// unless the annotated function is empty or simply panics.
26     ///
27     /// **Why is this bad?** While there are valid uses of this annotation (and once
28     /// you know when to use it, by all means `allow` this lint), it's a common
29     /// newbie-mistake to pepper one's code with it.
30     ///
31     /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
32     /// measure if that additional function call really affects your runtime profile
33     /// sufficiently to make up for the increase in compile time.
34     ///
35     /// **Known problems:** False positives, big time. This lint is meant to be
36     /// deactivated by everyone doing serious performance work. This means having
37     /// done the measurement.
38     ///
39     /// **Example:**
40     /// ```ignore
41     /// #[inline(always)]
42     /// fn not_quite_hot_code(..) { ... }
43     /// ```
44     pub INLINE_ALWAYS,
45     pedantic,
46     "use of `#[inline(always)]`"
47 }
48
49 declare_clippy_lint! {
50     /// **What it does:** Checks for `extern crate` and `use` items annotated with
51     /// lint attributes.
52     ///
53     /// This lint whitelists `#[allow(unused_imports)]` and `#[allow(deprecated)]` on
54     /// `use` items and `#[allow(unused_imports)]` on `extern crate` items with a
55     /// `#[macro_use]` attribute.
56     ///
57     /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
58     /// likely a `!` was forgotten.
59     ///
60     /// **Known problems:** None.
61     ///
62     /// **Example:**
63     /// ```ignore
64     /// // Bad
65     /// #[deny(dead_code)]
66     /// extern crate foo;
67     /// #[forbid(dead_code)]
68     /// use foo::bar;
69     ///
70     /// // Ok
71     /// #[allow(unused_imports)]
72     /// use foo::baz;
73     /// #[allow(unused_imports)]
74     /// #[macro_use]
75     /// extern crate baz;
76     /// ```
77     pub USELESS_ATTRIBUTE,
78     correctness,
79     "use of lint attributes on `extern crate` items"
80 }
81
82 declare_clippy_lint! {
83     /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
84     /// field that is not a valid semantic version.
85     ///
86     /// **Why is this bad?** For checking the version of the deprecation, it must be
87     /// a valid semver. Failing that, the contained information is useless.
88     ///
89     /// **Known problems:** None.
90     ///
91     /// **Example:**
92     /// ```rust
93     /// #[deprecated(since = "forever")]
94     /// fn something_else() { /* ... */ }
95     /// ```
96     pub DEPRECATED_SEMVER,
97     correctness,
98     "use of `#[deprecated(since = \"x\")]` where x is not semver"
99 }
100
101 declare_clippy_lint! {
102     /// **What it does:** Checks for empty lines after outer attributes
103     ///
104     /// **Why is this bad?**
105     /// Most likely the attribute was meant to be an inner attribute using a '!'.
106     /// If it was meant to be an outer attribute, then the following item
107     /// should not be separated by empty lines.
108     ///
109     /// **Known problems:** Can cause false positives.
110     ///
111     /// From the clippy side it's difficult to detect empty lines between an attributes and the
112     /// following item because empty lines and comments are not part of the AST. The parsing
113     /// currently works for basic cases but is not perfect.
114     ///
115     /// **Example:**
116     /// ```rust
117     /// // Bad
118     /// #[inline(always)]
119     ///
120     /// fn not_quite_good_code(..) { ... }
121     ///
122     /// // Good (as inner attribute)
123     /// #![inline(always)]
124     ///
125     /// fn this_is_fine(..) { ... }
126     ///
127     /// // Good (as outer attribute)
128     /// #[inline(always)]
129     /// fn this_is_fine_too(..) { ... }
130     /// ```
131     pub EMPTY_LINE_AFTER_OUTER_ATTR,
132     nursery,
133     "empty line after outer attribute"
134 }
135
136 declare_clippy_lint! {
137     /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
138     /// lints and if those lints exist in clippy. If there is a uppercase letter in the lint name
139     /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
140     /// the lint name.
141     ///
142     /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
143     ///
144     /// **Known problems:** None.
145     ///
146     /// **Example:**
147     /// Bad:
148     /// ```rust
149     /// #![warn(if_not_els)]
150     /// #![deny(clippy::All)]
151     /// ```
152     ///
153     /// Good:
154     /// ```rust
155     /// #![warn(if_not_else)]
156     /// #![deny(clippy::all)]
157     /// ```
158     pub UNKNOWN_CLIPPY_LINTS,
159     style,
160     "unknown_lints for scoped Clippy lints"
161 }
162
163 declare_clippy_lint! {
164     /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
165     /// with `#[rustfmt::skip]`.
166     ///
167     /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
168     /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
169     ///
170     /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
171     /// processed before the PreExpansionPass lints get executed. See
172     /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
173     ///
174     /// **Example:**
175     ///
176     /// Bad:
177     /// ```rust
178     /// #[cfg_attr(rustfmt, rustfmt_skip)]
179     /// fn main() { }
180     /// ```
181     ///
182     /// Good:
183     /// ```rust
184     /// #[rustfmt::skip]
185     /// fn main() { }
186     /// ```
187     pub DEPRECATED_CFG_ATTR,
188     complexity,
189     "usage of `cfg_attr(rustfmt)` instead of `tool_attributes`"
190 }
191
192 declare_lint_pass!(Attributes => [
193     INLINE_ALWAYS,
194     DEPRECATED_SEMVER,
195     USELESS_ATTRIBUTE,
196     EMPTY_LINE_AFTER_OUTER_ATTR,
197     UNKNOWN_CLIPPY_LINTS,
198 ]);
199
200 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes {
201     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
202         if let Some(items) = &attr.meta_item_list() {
203             if let Some(ident) = attr.ident() {
204                 match &*ident.as_str() {
205                     "allow" | "warn" | "deny" | "forbid" => {
206                         check_clippy_lint_names(cx, items);
207                     },
208                     _ => {},
209                 }
210                 if items.is_empty() || !attr.check_name(*sym::deprecated) {
211                     return;
212                 }
213                 for item in items {
214                     if_chain! {
215                         if let NestedMetaItem::MetaItem(mi) = &item;
216                         if let MetaItemKind::NameValue(lit) = &mi.node;
217                         if mi.check_name(*sym::since);
218                         then {
219                             check_semver(cx, item.span(), lit);
220                         }
221                     }
222                 }
223             }
224         }
225     }
226
227     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
228         if is_relevant_item(cx, item) {
229             check_attrs(cx, item.span, item.ident.name, &item.attrs)
230         }
231         match item.node {
232             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
233                 let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(*sym::macro_use));
234
235                 for attr in &item.attrs {
236                     if in_external_macro(cx.sess(), attr.span) {
237                         return;
238                     }
239                     if let Some(lint_list) = &attr.meta_item_list() {
240                         if let Some(ident) = attr.ident() {
241                             match &*ident.as_str() {
242                                 "allow" | "warn" | "deny" | "forbid" => {
243                                     // whitelist `unused_imports` and `deprecated` for `use` items
244                                     // and `unused_imports` for `extern crate` items with `macro_use`
245                                     for lint in lint_list {
246                                         match item.node {
247                                             ItemKind::Use(..) => {
248                                                 if is_word(lint, *sym::unused_imports)
249                                                     || is_word(lint, *sym::deprecated)
250                                                 {
251                                                     return;
252                                                 }
253                                             },
254                                             ItemKind::ExternCrate(..) => {
255                                                 if is_word(lint, *sym::unused_imports) && skip_unused_imports {
256                                                     return;
257                                                 }
258                                                 if is_word(lint, *sym::unused_extern_crates) {
259                                                     return;
260                                                 }
261                                             },
262                                             _ => {},
263                                         }
264                                     }
265                                     let line_span = last_line_of_span(cx, attr.span);
266
267                                     if let Some(mut sugg) = snippet_opt(cx, line_span) {
268                                         if sugg.contains("#[") {
269                                             span_lint_and_then(
270                                                 cx,
271                                                 USELESS_ATTRIBUTE,
272                                                 line_span,
273                                                 "useless lint attribute",
274                                                 |db| {
275                                                     sugg = sugg.replacen("#[", "#![", 1);
276                                                     db.span_suggestion(
277                                                         line_span,
278                                                         "if you just forgot a `!`, use",
279                                                         sugg,
280                                                         Applicability::MachineApplicable,
281                                                     );
282                                                 },
283                                             );
284                                         }
285                                     }
286                                 },
287                                 _ => {},
288                             }
289                         }
290                     }
291                 }
292             },
293             _ => {},
294         }
295     }
296
297     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
298         if is_relevant_impl(cx, item) {
299             check_attrs(cx, item.span, item.ident.name, &item.attrs)
300         }
301     }
302
303     fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
304         if is_relevant_trait(cx, item) {
305             check_attrs(cx, item.span, item.ident.name, &item.attrs)
306         }
307     }
308 }
309
310 #[allow(clippy::single_match_else)]
311 fn check_clippy_lint_names(cx: &LateContext<'_, '_>, items: &[NestedMetaItem]) {
312     let lint_store = cx.lints();
313     for lint in items {
314         if_chain! {
315             if let Some(meta_item) = lint.meta_item();
316             if meta_item.path.segments.len() > 1;
317             if let tool_name = meta_item.path.segments[0].ident;
318             if tool_name.as_str() == "clippy";
319             let name = meta_item.path.segments.last().unwrap().ident.name;
320             if let CheckLintNameResult::Tool(Err((None, _))) = lint_store.check_lint_name(
321                 &name.as_str(),
322                 Some(tool_name.as_str()),
323             );
324             then {
325                 span_lint_and_then(
326                     cx,
327                     UNKNOWN_CLIPPY_LINTS,
328                     lint.span(),
329                     &format!("unknown clippy lint: clippy::{}", name),
330                     |db| {
331                         if name.as_str().chars().any(char::is_uppercase) {
332                             let name_lower = name.as_str().to_lowercase();
333                             match lint_store.check_lint_name(
334                                 &name_lower,
335                                 Some(tool_name.as_str())
336                             ) {
337                                 // FIXME: can we suggest similar lint names here?
338                                 // https://github.com/rust-lang/rust/pull/56992
339                                 CheckLintNameResult::NoLint(None) => (),
340                                 _ => {
341                                     db.span_suggestion(
342                                         lint.span(),
343                                         "lowercase the lint name",
344                                         name_lower,
345                                         Applicability::MaybeIncorrect,
346                                     );
347                                 }
348                             }
349                         }
350                     }
351                 );
352             }
353         };
354     }
355 }
356
357 fn is_relevant_item(cx: &LateContext<'_, '_>, item: &Item) -> bool {
358     if let ItemKind::Fn(_, _, _, eid) = item.node {
359         is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
360     } else {
361         true
362     }
363 }
364
365 fn is_relevant_impl(cx: &LateContext<'_, '_>, item: &ImplItem) -> bool {
366     match item.node {
367         ImplItemKind::Method(_, eid) => is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value),
368         _ => false,
369     }
370 }
371
372 fn is_relevant_trait(cx: &LateContext<'_, '_>, item: &TraitItem) -> bool {
373     match item.node {
374         TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
375         TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
376             is_relevant_expr(cx, cx.tcx.body_tables(eid), &cx.tcx.hir().body(eid).value)
377         },
378         _ => false,
379     }
380 }
381
382 fn is_relevant_block(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, block: &Block) -> bool {
383     if let Some(stmt) = block.stmts.first() {
384         match &stmt.node {
385             StmtKind::Local(_) => true,
386             StmtKind::Expr(expr) | StmtKind::Semi(expr) => is_relevant_expr(cx, tables, expr),
387             _ => false,
388         }
389     } else {
390         block.expr.as_ref().map_or(false, |e| is_relevant_expr(cx, tables, e))
391     }
392 }
393
394 fn is_relevant_expr(cx: &LateContext<'_, '_>, tables: &ty::TypeckTables<'_>, expr: &Expr) -> bool {
395     match &expr.node {
396         ExprKind::Block(block, _) => is_relevant_block(cx, tables, block),
397         ExprKind::Ret(Some(e)) => is_relevant_expr(cx, tables, e),
398         ExprKind::Ret(None) | ExprKind::Break(_, None) => false,
399         ExprKind::Call(path_expr, _) => {
400             if let ExprKind::Path(qpath) = &path_expr.node {
401                 if let Some(fun_id) = tables.qpath_res(qpath, path_expr.hir_id).opt_def_id() {
402                     !match_def_path(cx, fun_id, &*paths::BEGIN_PANIC)
403                 } else {
404                     true
405                 }
406             } else {
407                 true
408             }
409         },
410         _ => true,
411     }
412 }
413
414 fn check_attrs(cx: &LateContext<'_, '_>, span: Span, name: Name, attrs: &[Attribute]) {
415     if in_macro_or_desugar(span) {
416         return;
417     }
418
419     for attr in attrs {
420         if attr.is_sugared_doc {
421             return;
422         }
423         if attr.style == AttrStyle::Outer {
424             if attr.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
425                 return;
426             }
427
428             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
429             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
430
431             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
432                 let lines = snippet.split('\n').collect::<Vec<_>>();
433                 let lines = without_block_comments(lines);
434
435                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
436                     span_lint(
437                         cx,
438                         EMPTY_LINE_AFTER_OUTER_ATTR,
439                         begin_of_attr_to_item,
440                         "Found an empty line after an outer attribute. \
441                          Perhaps you forgot to add a '!' to make it an inner attribute?",
442                     );
443                 }
444             }
445         }
446
447         if let Some(values) = attr.meta_item_list() {
448             if values.len() != 1 || !attr.check_name(*sym::inline) {
449                 continue;
450             }
451             if is_word(&values[0], *sym::always) {
452                 span_lint(
453                     cx,
454                     INLINE_ALWAYS,
455                     attr.span,
456                     &format!(
457                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
458                         name
459                     ),
460                 );
461             }
462         }
463     }
464 }
465
466 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
467     if let LitKind::Str(is, _) = lit.node {
468         if Version::parse(&is.as_str()).is_ok() {
469             return;
470         }
471     }
472     span_lint(
473         cx,
474         DEPRECATED_SEMVER,
475         span,
476         "the since field must contain a semver-compliant version",
477     );
478 }
479
480 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
481     if let NestedMetaItem::MetaItem(mi) = &nmi {
482         mi.is_word() && mi.check_name(expected)
483     } else {
484         false
485     }
486 }
487
488 declare_lint_pass!(DeprecatedCfgAttribute => [DEPRECATED_CFG_ATTR]);
489
490 impl EarlyLintPass for DeprecatedCfgAttribute {
491     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
492         if_chain! {
493             // check cfg_attr
494             if attr.check_name(*sym::cfg_attr);
495             if let Some(items) = attr.meta_item_list();
496             if items.len() == 2;
497             // check for `rustfmt`
498             if let Some(feature_item) = items[0].meta_item();
499             if feature_item.check_name(*sym::rustfmt);
500             // check for `rustfmt_skip` and `rustfmt::skip`
501             if let Some(skip_item) = &items[1].meta_item();
502             if skip_item.check_name(*sym::rustfmt_skip) ||
503                 skip_item.path.segments.last().expect("empty path in attribute").ident.name == *sym::skip;
504             // Only lint outer attributes, because custom inner attributes are unstable
505             // Tracking issue: https://github.com/rust-lang/rust/issues/54726
506             if let AttrStyle::Outer = attr.style;
507             then {
508                 span_lint_and_sugg(
509                     cx,
510                     DEPRECATED_CFG_ATTR,
511                     attr.span,
512                     "`cfg_attr` is deprecated for rustfmt and got replaced by tool_attributes",
513                     "use",
514                     "#[rustfmt::skip]".to_string(),
515                     Applicability::MachineApplicable,
516                 );
517             }
518         }
519     }
520 }