]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/attrs.rs
Run update_lints
[rust.git] / clippy_lints / src / attrs.rs
1 //! checks for attributes
2
3 use crate::reexport::*;
4 use crate::utils::{
5     is_present_in_source, last_line_of_span, match_def_path, paths, snippet_opt, span_lint, span_lint_and_sugg,
6     span_lint_and_then, without_block_comments,
7 };
8 use if_chain::if_chain;
9 use rustc::hir::*;
10 use rustc::lint::{
11     in_external_macro, CheckLintNameResult, EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray,
12     LintContext, LintPass,
13 };
14 use rustc::ty;
15 use rustc::{declare_lint_pass, declare_tool_lint};
16 use rustc_errors::Applicability;
17 use semver::Version;
18 use syntax::ast::{AttrKind, AttrStyle, Attribute, Lit, LitKind, MetaItemKind, NestedMetaItem};
19 use syntax::source_map::Span;
20 use syntax_pos::symbol::Symbol;
21
22 declare_clippy_lint! {
23     /// **What it does:** Checks for items annotated with `#[inline(always)]`,
24     /// unless the annotated function is empty or simply panics.
25     ///
26     /// **Why is this bad?** While there are valid uses of this annotation (and once
27     /// you know when to use it, by all means `allow` this lint), it's a common
28     /// newbie-mistake to pepper one's code with it.
29     ///
30     /// As a rule of thumb, before slapping `#[inline(always)]` on a function,
31     /// measure if that additional function call really affects your runtime profile
32     /// sufficiently to make up for the increase in compile time.
33     ///
34     /// **Known problems:** False positives, big time. This lint is meant to be
35     /// deactivated by everyone doing serious performance work. This means having
36     /// done the measurement.
37     ///
38     /// **Example:**
39     /// ```ignore
40     /// #[inline(always)]
41     /// fn not_quite_hot_code(..) { ... }
42     /// ```
43     pub INLINE_ALWAYS,
44     pedantic,
45     "use of `#[inline(always)]`"
46 }
47
48 declare_clippy_lint! {
49     /// **What it does:** Checks for `extern crate` and `use` items annotated with
50     /// lint attributes.
51     ///
52     /// This lint whitelists `#[allow(unused_imports)]`, `#[allow(deprecated)]` and
53     /// `#[allow(unreachable_pub)]` on `use` items and `#[allow(unused_imports)]` on
54     /// `extern crate` items with a `#[macro_use]` attribute.
55     ///
56     /// **Why is this bad?** Lint attributes have no effect on crate imports. Most
57     /// likely a `!` was forgotten.
58     ///
59     /// **Known problems:** None.
60     ///
61     /// **Example:**
62     /// ```ignore
63     /// // Bad
64     /// #[deny(dead_code)]
65     /// extern crate foo;
66     /// #[forbid(dead_code)]
67     /// use foo::bar;
68     ///
69     /// // Ok
70     /// #[allow(unused_imports)]
71     /// use foo::baz;
72     /// #[allow(unused_imports)]
73     /// #[macro_use]
74     /// extern crate baz;
75     /// ```
76     pub USELESS_ATTRIBUTE,
77     correctness,
78     "use of lint attributes on `extern crate` items"
79 }
80
81 declare_clippy_lint! {
82     /// **What it does:** Checks for `#[deprecated]` annotations with a `since`
83     /// field that is not a valid semantic version.
84     ///
85     /// **Why is this bad?** For checking the version of the deprecation, it must be
86     /// a valid semver. Failing that, the contained information is useless.
87     ///
88     /// **Known problems:** None.
89     ///
90     /// **Example:**
91     /// ```rust
92     /// #[deprecated(since = "forever")]
93     /// fn something_else() { /* ... */ }
94     /// ```
95     pub DEPRECATED_SEMVER,
96     correctness,
97     "use of `#[deprecated(since = \"x\")]` where x is not semver"
98 }
99
100 declare_clippy_lint! {
101     /// **What it does:** Checks for empty lines after outer attributes
102     ///
103     /// **Why is this bad?**
104     /// Most likely the attribute was meant to be an inner attribute using a '!'.
105     /// If it was meant to be an outer attribute, then the following item
106     /// should not be separated by empty lines.
107     ///
108     /// **Known problems:** Can cause false positives.
109     ///
110     /// From the clippy side it's difficult to detect empty lines between an attributes and the
111     /// following item because empty lines and comments are not part of the AST. The parsing
112     /// currently works for basic cases but is not perfect.
113     ///
114     /// **Example:**
115     /// ```rust
116     /// // Good (as inner attribute)
117     /// #![inline(always)]
118     ///
119     /// fn this_is_fine() { }
120     ///
121     /// // Bad
122     /// #[inline(always)]
123     ///
124     /// fn not_quite_good_code() { }
125     ///
126     /// // Good (as outer attribute)
127     /// #[inline(always)]
128     /// fn this_is_fine_too() { }
129     /// ```
130     pub EMPTY_LINE_AFTER_OUTER_ATTR,
131     nursery,
132     "empty line after outer attribute"
133 }
134
135 declare_clippy_lint! {
136     /// **What it does:** Checks for `allow`/`warn`/`deny`/`forbid` attributes with scoped clippy
137     /// lints and if those lints exist in clippy. If there is an uppercase letter in the lint name
138     /// (not the tool name) and a lowercase version of this lint exists, it will suggest to lowercase
139     /// the lint name.
140     ///
141     /// **Why is this bad?** A lint attribute with a mistyped lint name won't have an effect.
142     ///
143     /// **Known problems:** None.
144     ///
145     /// **Example:**
146     /// Bad:
147     /// ```rust
148     /// #![warn(if_not_els)]
149     /// #![deny(clippy::All)]
150     /// ```
151     ///
152     /// Good:
153     /// ```rust
154     /// #![warn(if_not_else)]
155     /// #![deny(clippy::all)]
156     /// ```
157     pub UNKNOWN_CLIPPY_LINTS,
158     style,
159     "unknown_lints for scoped Clippy lints"
160 }
161
162 declare_clippy_lint! {
163     /// **What it does:** Checks for `#[cfg_attr(rustfmt, rustfmt_skip)]` and suggests to replace it
164     /// with `#[rustfmt::skip]`.
165     ///
166     /// **Why is this bad?** Since tool_attributes ([rust-lang/rust#44690](https://github.com/rust-lang/rust/issues/44690))
167     /// are stable now, they should be used instead of the old `cfg_attr(rustfmt)` attributes.
168     ///
169     /// **Known problems:** This lint doesn't detect crate level inner attributes, because they get
170     /// processed before the PreExpansionPass lints get executed. See
171     /// [#3123](https://github.com/rust-lang/rust-clippy/pull/3123#issuecomment-422321765)
172     ///
173     /// **Example:**
174     ///
175     /// Bad:
176     /// ```rust
177     /// #[cfg_attr(rustfmt, rustfmt_skip)]
178     /// fn main() { }
179     /// ```
180     ///
181     /// Good:
182     /// ```rust
183     /// #[rustfmt::skip]
184     /// fn main() { }
185     /// ```
186     pub DEPRECATED_CFG_ATTR,
187     complexity,
188     "usage of `cfg_attr(rustfmt)` instead of `tool_attributes`"
189 }
190
191 declare_lint_pass!(Attributes => [
192     INLINE_ALWAYS,
193     DEPRECATED_SEMVER,
194     USELESS_ATTRIBUTE,
195     EMPTY_LINE_AFTER_OUTER_ATTR,
196     UNKNOWN_CLIPPY_LINTS,
197 ]);
198
199 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Attributes {
200     fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
201         if let Some(items) = &attr.meta_item_list() {
202             if let Some(ident) = attr.ident() {
203                 match &*ident.as_str() {
204                     "allow" | "warn" | "deny" | "forbid" => {
205                         check_clippy_lint_names(cx, items);
206                     },
207                     _ => {},
208                 }
209                 if items.is_empty() || !attr.check_name(sym!(deprecated)) {
210                     return;
211                 }
212                 for item in items {
213                     if_chain! {
214                         if let NestedMetaItem::MetaItem(mi) = &item;
215                         if let MetaItemKind::NameValue(lit) = &mi.kind;
216                         if mi.check_name(sym!(since));
217                         then {
218                             check_semver(cx, item.span(), lit);
219                         }
220                     }
221                 }
222             }
223         }
224     }
225
226     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
227         if is_relevant_item(cx, item) {
228             check_attrs(cx, item.span, item.ident.name, &item.attrs)
229         }
230         match item.kind {
231             ItemKind::ExternCrate(..) | ItemKind::Use(..) => {
232                 let skip_unused_imports = item.attrs.iter().any(|attr| attr.check_name(sym!(macro_use)));
233
234                 for attr in &item.attrs {
235                     if in_external_macro(cx.sess(), attr.span) {
236                         return;
237                     }
238                     if let Some(lint_list) = &attr.meta_item_list() {
239                         if let Some(ident) = attr.ident() {
240                             match &*ident.as_str() {
241                                 "allow" | "warn" | "deny" | "forbid" => {
242                                     // whitelist `unused_imports`, `deprecated` and `unreachable_pub` for `use` items
243                                     // and `unused_imports` for `extern crate` items with `macro_use`
244                                     for lint in lint_list {
245                                         match item.kind {
246                                             ItemKind::Use(..) => {
247                                                 if is_word(lint, sym!(unused_imports))
248                                                     || is_word(lint, sym!(deprecated))
249                                                     || is_word(lint, sym!(unreachable_pub))
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::MaybeIncorrect,
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.name),
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.name)
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.kind {
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.kind {
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.kind {
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.kind {
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.kind {
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.kind {
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 span.from_expansion() {
416         return;
417     }
418
419     for attr in attrs {
420         let attr_item = if let AttrKind::Normal(ref attr) = attr.kind {
421             attr
422         } else {
423             continue;
424         };
425
426         if attr.style == AttrStyle::Outer {
427             if attr_item.tokens.is_empty() || !is_present_in_source(cx, attr.span) {
428                 return;
429             }
430
431             let begin_of_attr_to_item = Span::new(attr.span.lo(), span.lo(), span.ctxt());
432             let end_of_attr_to_item = Span::new(attr.span.hi(), span.lo(), span.ctxt());
433
434             if let Some(snippet) = snippet_opt(cx, end_of_attr_to_item) {
435                 let lines = snippet.split('\n').collect::<Vec<_>>();
436                 let lines = without_block_comments(lines);
437
438                 if lines.iter().filter(|l| l.trim().is_empty()).count() > 2 {
439                     span_lint(
440                         cx,
441                         EMPTY_LINE_AFTER_OUTER_ATTR,
442                         begin_of_attr_to_item,
443                         "Found an empty line after an outer attribute. \
444                          Perhaps you forgot to add a '!' to make it an inner attribute?",
445                     );
446                 }
447             }
448         }
449
450         if let Some(values) = attr.meta_item_list() {
451             if values.len() != 1 || !attr.check_name(sym!(inline)) {
452                 continue;
453             }
454             if is_word(&values[0], sym!(always)) {
455                 span_lint(
456                     cx,
457                     INLINE_ALWAYS,
458                     attr.span,
459                     &format!(
460                         "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
461                         name
462                     ),
463                 );
464             }
465         }
466     }
467 }
468
469 fn check_semver(cx: &LateContext<'_, '_>, span: Span, lit: &Lit) {
470     if let LitKind::Str(is, _) = lit.kind {
471         if Version::parse(&is.as_str()).is_ok() {
472             return;
473         }
474     }
475     span_lint(
476         cx,
477         DEPRECATED_SEMVER,
478         span,
479         "the since field must contain a semver-compliant version",
480     );
481 }
482
483 fn is_word(nmi: &NestedMetaItem, expected: Symbol) -> bool {
484     if let NestedMetaItem::MetaItem(mi) = &nmi {
485         mi.is_word() && mi.check_name(expected)
486     } else {
487         false
488     }
489 }
490
491 declare_lint_pass!(DeprecatedCfgAttribute => [DEPRECATED_CFG_ATTR]);
492
493 impl EarlyLintPass for DeprecatedCfgAttribute {
494     fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &Attribute) {
495         if_chain! {
496             // check cfg_attr
497             if attr.check_name(sym!(cfg_attr));
498             if let Some(items) = attr.meta_item_list();
499             if items.len() == 2;
500             // check for `rustfmt`
501             if let Some(feature_item) = items[0].meta_item();
502             if feature_item.check_name(sym!(rustfmt));
503             // check for `rustfmt_skip` and `rustfmt::skip`
504             if let Some(skip_item) = &items[1].meta_item();
505             if skip_item.check_name(sym!(rustfmt_skip)) ||
506                 skip_item.path.segments.last().expect("empty path in attribute").ident.name == sym!(skip);
507             // Only lint outer attributes, because custom inner attributes are unstable
508             // Tracking issue: https://github.com/rust-lang/rust/issues/54726
509             if let AttrStyle::Outer = attr.style;
510             then {
511                 span_lint_and_sugg(
512                     cx,
513                     DEPRECATED_CFG_ATTR,
514                     attr.span,
515                     "`cfg_attr` is deprecated for rustfmt and got replaced by tool_attributes",
516                     "use",
517                     "#[rustfmt::skip]".to_string(),
518                     Applicability::MachineApplicable,
519                 );
520             }
521         }
522     }
523 }