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