]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/missing_inline.rs
Merge pull request #3269 from rust-lang-nursery/relicense
[rust.git] / clippy_lints / src / missing_inline.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10
11 //   Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
12 //   file at the top-level directory of this distribution and at
13 //   http://rust-lang.org/COPYRIGHT.
14 //
15 //   Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
16 //   http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
17 //   <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
18 //   option. This file may not be copied, modified, or distributed
19 //   except according to those terms.
20 //
21
22 use crate::rustc::hir;
23 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
24 use crate::rustc::{declare_tool_lint, lint_array};
25 use crate::syntax::ast;
26 use crate::syntax::source_map::Span;
27 use crate::utils::span_lint;
28
29 /// **What it does:** it lints if an exported function, method, trait method with default impl,
30 /// or trait method impl is not `#[inline]`.
31 ///
32 /// **Why is this bad?** In general, it is not. Functions can be inlined across
33 /// crates when that's profitable as long as any form of LTO is used. When LTO is disabled,
34 /// functions that are not `#[inline]` cannot be inlined across crates. Certain types of crates
35 /// might intend for most of the methods in their public API to be able to be inlined across
36 /// crates even when LTO is disabled. For these types of crates, enabling this lint might make sense.
37 /// It allows the crate to require all exported methods to be `#[inline]` by default, and then opt
38 /// out for specific methods where this might not make sense.
39 ///
40 /// **Known problems:** None.
41 ///
42 /// **Example:**
43 /// ```rust
44 /// pub fn foo() {} // missing #[inline]
45 /// fn ok() {} // ok
46 /// #[inline] pub fn bar() {} // ok
47 /// #[inline(always)] pub fn baz() {} // ok
48 ///
49 /// pub trait Bar {
50 ///   fn bar(); // ok
51 ///   fn def_bar() {} // missing #[inline]
52 /// }
53 ///
54 /// struct Baz;
55 /// impl Baz {
56 ///    fn priv() {} // ok
57 /// }
58 ///
59 /// impl Bar for Baz {
60 ///   fn bar() {} // ok - Baz is not exported
61 /// }
62 ///
63 /// pub struct PubBaz;
64 /// impl PubBaz {
65 ///    fn priv() {} // ok
66 ///    pub not_ptriv() {} // missing #[inline]
67 /// }
68 ///
69 /// impl Bar for PubBaz {
70 ///    fn bar() {} // missing #[inline]
71 ///    fn def_bar() {} // missing #[inline]
72 /// }
73 /// ```
74 declare_clippy_lint! {
75     pub MISSING_INLINE_IN_PUBLIC_ITEMS,
76     restriction,
77     "detects missing #[inline] attribute for public callables (functions, trait methods, methods...)"
78 }
79
80 pub struct MissingInline;
81
82 fn check_missing_inline_attrs(cx: &LateContext<'_, '_>,
83                               attrs: &[ast::Attribute], sp: Span, desc: &'static str) {
84     let has_inline = attrs
85         .iter()
86         .any(|a| a.name() == "inline" );
87     if !has_inline {
88         span_lint(
89             cx,
90             MISSING_INLINE_IN_PUBLIC_ITEMS,
91             sp,
92             &format!("missing `#[inline]` for {}", desc),
93         );
94     }
95 }
96
97 fn is_executable<'a, 'tcx>(cx: &LateContext<'a, 'tcx>) -> bool {
98     use crate::rustc::session::config::CrateType;
99
100     cx.tcx.sess.crate_types.get().iter().any(|t: &CrateType| {
101         match t {
102             CrateType::Executable => true,
103             _ => false,
104         }
105     })
106 }
107
108 impl LintPass for MissingInline {
109     fn get_lints(&self) -> LintArray {
110         lint_array![MISSING_INLINE_IN_PUBLIC_ITEMS]
111     }
112 }
113
114 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingInline {
115     fn check_item(&mut self, cx: &LateContext<'a, 'tcx>, it: &'tcx hir::Item) {
116         if is_executable(cx) {
117             return;
118         }
119
120         if !cx.access_levels.is_exported(it.id) {
121             return;
122         }
123         match it.node {
124             hir::ItemKind::Fn(..) => {
125                 let desc = "a function";
126                 check_missing_inline_attrs(cx, &it.attrs, it.span, desc);
127             },
128             hir::ItemKind::Trait(ref _is_auto, ref _unsafe, ref _generics,
129                            ref _bounds, ref trait_items)  => {
130                 // note: we need to check if the trait is exported so we can't use
131                 // `LateLintPass::check_trait_item` here.
132                 for tit in trait_items {
133                     let tit_ = cx.tcx.hir.trait_item(tit.id);
134                     match tit_.node {
135                         hir::TraitItemKind::Const(..) |
136                         hir::TraitItemKind::Type(..) => {},
137                         hir::TraitItemKind::Method(..) => {
138                             if tit.defaultness.has_value() {
139                                 // trait method with default body needs inline in case
140                                 // an impl is not provided
141                                 let desc = "a default trait method";
142                                 let item = cx.tcx.hir.expect_trait_item(tit.id.node_id);
143                                 check_missing_inline_attrs(cx, &item.attrs,
144                                                                 item.span, desc);
145                             }
146                         },
147                     }
148                 }
149             }
150             hir::ItemKind::Const(..) |
151             hir::ItemKind::Enum(..) |
152             hir::ItemKind::Mod(..) |
153             hir::ItemKind::Static(..) |
154             hir::ItemKind::Struct(..) |
155             hir::ItemKind::TraitAlias(..) |
156             hir::ItemKind::GlobalAsm(..) |
157             hir::ItemKind::Ty(..) |
158             hir::ItemKind::Union(..) |
159             hir::ItemKind::Existential(..) |
160             hir::ItemKind::ExternCrate(..) |
161             hir::ItemKind::ForeignMod(..) |
162             hir::ItemKind::Impl(..) |
163             hir::ItemKind::Use(..) => {},
164         };
165     }
166
167     fn check_impl_item(&mut self, cx: &LateContext<'a, 'tcx>, impl_item: &'tcx hir::ImplItem) {
168         use crate::rustc::ty::{TraitContainer, ImplContainer};
169         if is_executable(cx) {
170             return;
171         }
172
173         // If the item being implemented is not exported, then we don't need #[inline]
174         if !cx.access_levels.is_exported(impl_item.id) {
175             return;
176         }
177
178         let desc = match impl_item.node {
179             hir::ImplItemKind::Method(..) => "a method",
180             hir::ImplItemKind::Const(..) |
181             hir::ImplItemKind::Type(_) |
182             hir::ImplItemKind::Existential(_) => return,
183         };
184
185         let def_id = cx.tcx.hir.local_def_id(impl_item.id);
186         let trait_def_id = match cx.tcx.associated_item(def_id).container {
187             TraitContainer(cid) => Some(cid),
188             ImplContainer(cid) => cx.tcx.impl_trait_ref(cid).map(|t| t.def_id),
189         };
190
191         if let Some(trait_def_id) = trait_def_id {
192             if let Some(n) = cx.tcx.hir.as_local_node_id(trait_def_id) {
193                 if !cx.access_levels.is_exported(n) {
194                     // If a trait is being implemented for an item, and the
195                     // trait is not exported, we don't need #[inline]
196                     return;
197                 }
198             }
199         }
200
201         check_missing_inline_attrs(cx, &impl_item.attrs, impl_item.span, desc);
202     }
203 }