]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/clippy_lints/src/attrs.rs
New upstream version 1.25.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / attrs.rs
CommitLineData
ea8adc8c
XL
1//! checks for attributes
2
3use reexport::*;
4use rustc::lint::*;
5use rustc::hir::*;
6use rustc::ty::{self, TyCtxt};
7use semver::Version;
2c00a5a8 8use syntax::ast::{Attribute, AttrStyle, Lit, LitKind, MetaItemKind, NestedMetaItem, NestedMetaItemKind};
ea8adc8c 9use syntax::codemap::Span;
abe05a73 10use utils::{in_macro, match_def_path, opt_def_id, paths, snippet_opt, span_lint, span_lint_and_then};
ea8adc8c
XL
11
12/// **What it does:** Checks for items annotated with `#[inline(always)]`,
13/// unless the annotated function is empty or simply panics.
14///
15/// **Why is this bad?** While there are valid uses of this annotation (and once
16/// you know when to use it, by all means `allow` this lint), it's a common
17/// newbie-mistake to pepper one's code with it.
18///
19/// As a rule of thumb, before slapping `#[inline(always)]` on a function,
20/// measure if that additional function call really affects your runtime profile
21/// sufficiently to make up for the increase in compile time.
22///
23/// **Known problems:** False positives, big time. This lint is meant to be
24/// deactivated by everyone doing serious performance work. This means having
25/// done the measurement.
26///
27/// **Example:**
28/// ```rust
29/// #[inline(always)]
30/// fn not_quite_hot_code(..) { ... }
31/// ```
32declare_lint! {
33 pub INLINE_ALWAYS,
34 Warn,
35 "use of `#[inline(always)]`"
36}
37
38/// **What it does:** Checks for `extern crate` and `use` items annotated with
39/// lint attributes
40///
41/// **Why is this bad?** Lint attributes have no effect on crate imports. Most
42/// likely a `!` was
43/// forgotten
44///
45/// **Known problems:** Technically one might allow `unused_import` on a `use`
46/// item,
47/// but it's easier to remove the unused item.
48///
49/// **Example:**
50/// ```rust
51/// #[deny(dead_code)]
52/// extern crate foo;
53/// #[allow(unused_import)]
54/// use foo::bar;
55/// ```
56declare_lint! {
57 pub USELESS_ATTRIBUTE,
58 Warn,
59 "use of lint attributes on `extern crate` items"
60}
61
62/// **What it does:** Checks for `#[deprecated]` annotations with a `since`
63/// field that is not a valid semantic version.
64///
65/// **Why is this bad?** For checking the version of the deprecation, it must be
66/// a valid semver. Failing that, the contained information is useless.
67///
68/// **Known problems:** None.
69///
70/// **Example:**
71/// ```rust
72/// #[deprecated(since = "forever")]
73/// fn something_else(..) { ... }
74/// ```
75declare_lint! {
76 pub DEPRECATED_SEMVER,
77 Warn,
78 "use of `#[deprecated(since = \"x\")]` where x is not semver"
79}
80
2c00a5a8
XL
81/// **What it does:** Checks for empty lines after outer attributes
82///
83/// **Why is this bad?**
84/// Most likely the attribute was meant to be an inner attribute using a '!'.
85/// If it was meant to be an outer attribute, then the following item
86/// should not be separated by empty lines.
87///
88/// **Known problems:** None
89///
90/// **Example:**
91/// ```rust
92/// // Bad
93/// #[inline(always)]
94///
95/// fn not_quite_good_code(..) { ... }
96///
97/// // Good (as inner attribute)
98/// #![inline(always)]
99///
100/// fn this_is_fine(..) { ... }
101///
102/// // Good (as outer attribute)
103/// #[inline(always)]
104/// fn this_is_fine_too(..) { ... }
105/// ```
106declare_lint! {
107 pub EMPTY_LINE_AFTER_OUTER_ATTR,
108 Warn,
109 "empty line after outer attribute"
110}
111
ea8adc8c
XL
112#[derive(Copy, Clone)]
113pub struct AttrPass;
114
115impl LintPass for AttrPass {
116 fn get_lints(&self) -> LintArray {
2c00a5a8 117 lint_array!(INLINE_ALWAYS, DEPRECATED_SEMVER, USELESS_ATTRIBUTE, EMPTY_LINE_AFTER_OUTER_ATTR)
ea8adc8c
XL
118 }
119}
120
121impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AttrPass {
122 fn check_attribute(&mut self, cx: &LateContext<'a, 'tcx>, attr: &'tcx Attribute) {
123 if let Some(ref items) = attr.meta_item_list() {
124 if items.is_empty() || attr.name().map_or(true, |n| n != "deprecated") {
125 return;
126 }
127 for item in items {
abe05a73
XL
128 if_chain! {
129 if let NestedMetaItemKind::MetaItem(ref mi) = item.node;
130 if let MetaItemKind::NameValue(ref lit) = mi.node;
131 if mi.name() == "since";
132 then {
133 check_semver(cx, item.span, lit);
134 }
135 }
ea8adc8c
XL
136 }
137 }
138 }
139
140 fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx Item) {
141 if is_relevant_item(cx.tcx, item) {
142 check_attrs(cx, item.span, &item.name, &item.attrs)
143 }
144 match item.node {
abe05a73 145 ItemExternCrate(_) | ItemUse(_, _) => {
ea8adc8c
XL
146 for attr in &item.attrs {
147 if let Some(ref lint_list) = attr.meta_item_list() {
148 if let Some(name) = attr.name() {
149 match &*name.as_str() {
150 "allow" | "warn" | "deny" | "forbid" => {
151 // whitelist `unused_imports` and `deprecated`
152 for lint in lint_list {
153 if is_word(lint, "unused_imports") || is_word(lint, "deprecated") {
154 if let ItemUse(_, _) = item.node {
155 return;
156 }
157 }
158 }
159 if let Some(mut sugg) = snippet_opt(cx, attr.span) {
160 if sugg.len() > 1 {
161 span_lint_and_then(
162 cx,
163 USELESS_ATTRIBUTE,
164 attr.span,
165 "useless lint attribute",
166 |db| {
167 sugg.insert(1, '!');
168 db.span_suggestion(
169 attr.span,
170 "if you just forgot a `!`, use",
171 sugg,
172 );
173 },
174 );
175 }
176 }
177 },
178 _ => {},
179 }
180 }
181 }
182 }
183 },
184 _ => {},
185 }
186 }
187
188 fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx ImplItem) {
189 if is_relevant_impl(cx.tcx, item) {
190 check_attrs(cx, item.span, &item.name, &item.attrs)
191 }
192 }
193
194 fn check_trait_item(&mut self, cx: &LateContext<'a, 'tcx>, item: &'tcx TraitItem) {
195 if is_relevant_trait(cx.tcx, item) {
196 check_attrs(cx, item.span, &item.name, &item.attrs)
197 }
198 }
199}
200
201fn is_relevant_item(tcx: TyCtxt, item: &Item) -> bool {
202 if let ItemFn(_, _, _, _, _, eid) = item.node {
203 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
204 } else {
2c00a5a8 205 true
ea8adc8c
XL
206 }
207}
208
209fn is_relevant_impl(tcx: TyCtxt, item: &ImplItem) -> bool {
210 match item.node {
211 ImplItemKind::Method(_, eid) => is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value),
212 _ => false,
213 }
214}
215
216fn is_relevant_trait(tcx: TyCtxt, item: &TraitItem) -> bool {
217 match item.node {
218 TraitItemKind::Method(_, TraitMethod::Required(_)) => true,
219 TraitItemKind::Method(_, TraitMethod::Provided(eid)) => {
220 is_relevant_expr(tcx, tcx.body_tables(eid), &tcx.hir.body(eid).value)
221 },
222 _ => false,
223 }
224}
225
226fn is_relevant_block(tcx: TyCtxt, tables: &ty::TypeckTables, block: &Block) -> bool {
227 if let Some(stmt) = block.stmts.first() {
228 match stmt.node {
229 StmtDecl(_, _) => true,
abe05a73 230 StmtExpr(ref expr, _) | StmtSemi(ref expr, _) => is_relevant_expr(tcx, tables, expr),
ea8adc8c
XL
231 }
232 } else {
abe05a73
XL
233 block
234 .expr
235 .as_ref()
236 .map_or(false, |e| is_relevant_expr(tcx, tables, e))
ea8adc8c
XL
237 }
238}
239
240fn is_relevant_expr(tcx: TyCtxt, tables: &ty::TypeckTables, expr: &Expr) -> bool {
241 match expr.node {
242 ExprBlock(ref block) => is_relevant_block(tcx, tables, block),
243 ExprRet(Some(ref e)) => is_relevant_expr(tcx, tables, e),
abe05a73
XL
244 ExprRet(None) | ExprBreak(_, None) => false,
245 ExprCall(ref path_expr, _) => if let ExprPath(ref qpath) = path_expr.node {
246 if let Some(fun_id) = opt_def_id(tables.qpath_def(qpath, path_expr.hir_id)) {
ea8adc8c
XL
247 !match_def_path(tcx, fun_id, &paths::BEGIN_PANIC)
248 } else {
249 true
250 }
abe05a73
XL
251 } else {
252 true
ea8adc8c
XL
253 },
254 _ => true,
255 }
256}
257
258fn check_attrs(cx: &LateContext, span: Span, name: &Name, attrs: &[Attribute]) {
259 if in_macro(span) {
260 return;
261 }
262
263 for attr in attrs {
2c00a5a8
XL
264 if attr.is_sugared_doc {
265 return;
266 }
267 if attr.style == AttrStyle::Outer {
268 if !is_present_in_source(cx, attr.span) {
269 return;
270 }
271
272 let attr_to_item_span = Span::new(attr.span.lo(), span.lo(), span.ctxt());
273
274 if let Some(snippet) = snippet_opt(cx, attr_to_item_span) {
275 let lines = snippet.split('\n').collect::<Vec<_>>();
276 if lines.iter().filter(|l| l.trim().is_empty()).count() > 1 {
277 span_lint(
278 cx,
279 EMPTY_LINE_AFTER_OUTER_ATTR,
280 attr_to_item_span,
281 "Found an empty line after an outer attribute. Perhaps you forgot to add a '!' to make it an inner attribute?"
282 );
283
284 }
285 }
286 }
287
ea8adc8c
XL
288 if let Some(ref values) = attr.meta_item_list() {
289 if values.len() != 1 || attr.name().map_or(true, |n| n != "inline") {
290 continue;
291 }
292 if is_word(&values[0], "always") {
293 span_lint(
294 cx,
295 INLINE_ALWAYS,
296 attr.span,
297 &format!(
298 "you have declared `#[inline(always)]` on `{}`. This is usually a bad idea",
299 name
300 ),
301 );
302 }
303 }
304 }
305}
306
307fn check_semver(cx: &LateContext, span: Span, lit: &Lit) {
308 if let LitKind::Str(ref is, _) = lit.node {
309 if Version::parse(&is.as_str()).is_ok() {
310 return;
311 }
312 }
313 span_lint(
314 cx,
315 DEPRECATED_SEMVER,
316 span,
317 "the since field must contain a semver-compliant version",
318 );
319}
320
321fn is_word(nmi: &NestedMetaItem, expected: &str) -> bool {
322 if let NestedMetaItemKind::MetaItem(ref mi) = nmi.node {
323 mi.is_word() && mi.name() == expected
324 } else {
325 false
326 }
327}
2c00a5a8
XL
328
329// If the snippet is empty, it's an attribute that was inserted during macro
330// expansion and we want to ignore those, because they could come from external
331// sources that the user has no control over.
332// For some reason these attributes don't have any expansion info on them, so
333// we have to check it this way until there is a better way.
334fn is_present_in_source(cx: &LateContext, span: Span) -> bool {
335 if let Some(snippet) = snippet_opt(cx, span) {
336 if snippet.is_empty() {
337 return false;
338 }
339 }
340 true
341}