]> git.proxmox.com Git - rustc.git/blob - src/tools/clippy/clippy_lints/src/missing_const_for_fn.rs
New upstream version 1.66.0+dfsg1
[rustc.git] / src / tools / clippy / clippy_lints / src / missing_const_for_fn.rs
1 use clippy_utils::diagnostics::span_lint;
2 use clippy_utils::qualify_min_const_fn::is_min_const_fn;
3 use clippy_utils::ty::has_drop;
4 use clippy_utils::{
5 fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, meets_msrv, msrvs, trait_ref_of_method,
6 };
7 use rustc_hir as hir;
8 use rustc_hir::def_id::CRATE_DEF_ID;
9 use rustc_hir::intravisit::FnKind;
10 use rustc_hir::{Body, Constness, FnDecl, GenericParamKind, HirId};
11 use rustc_hir_analysis::hir_ty_to_ty;
12 use rustc_lint::{LateContext, LateLintPass};
13 use rustc_middle::lint::in_external_macro;
14 use rustc_semver::RustcVersion;
15 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_span::Span;
17
18 declare_clippy_lint! {
19 /// ### What it does
20 /// Suggests the use of `const` in functions and methods where possible.
21 ///
22 /// ### Why is this bad?
23 /// Not having the function const prevents callers of the function from being const as well.
24 ///
25 /// ### Known problems
26 /// Const functions are currently still being worked on, with some features only being available
27 /// on nightly. This lint does not consider all edge cases currently and the suggestions may be
28 /// incorrect if you are using this lint on stable.
29 ///
30 /// Also, the lint only runs one pass over the code. Consider these two non-const functions:
31 ///
32 /// ```rust
33 /// fn a() -> i32 {
34 /// 0
35 /// }
36 /// fn b() -> i32 {
37 /// a()
38 /// }
39 /// ```
40 ///
41 /// When running Clippy, the lint will only suggest to make `a` const, because `b` at this time
42 /// can't be const as it calls a non-const function. Making `a` const and running Clippy again,
43 /// will suggest to make `b` const, too.
44 ///
45 /// ### Example
46 /// ```rust
47 /// # struct Foo {
48 /// # random_number: usize,
49 /// # }
50 /// # impl Foo {
51 /// fn new() -> Self {
52 /// Self { random_number: 42 }
53 /// }
54 /// # }
55 /// ```
56 ///
57 /// Could be a const fn:
58 ///
59 /// ```rust
60 /// # struct Foo {
61 /// # random_number: usize,
62 /// # }
63 /// # impl Foo {
64 /// const fn new() -> Self {
65 /// Self { random_number: 42 }
66 /// }
67 /// # }
68 /// ```
69 #[clippy::version = "1.34.0"]
70 pub MISSING_CONST_FOR_FN,
71 nursery,
72 "Lint functions definitions that could be made `const fn`"
73 }
74
75 impl_lint_pass!(MissingConstForFn => [MISSING_CONST_FOR_FN]);
76
77 pub struct MissingConstForFn {
78 msrv: Option<RustcVersion>,
79 }
80
81 impl MissingConstForFn {
82 #[must_use]
83 pub fn new(msrv: Option<RustcVersion>) -> Self {
84 Self { msrv }
85 }
86 }
87
88 impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
89 fn check_fn(
90 &mut self,
91 cx: &LateContext<'tcx>,
92 kind: FnKind<'tcx>,
93 _: &FnDecl<'_>,
94 body: &Body<'tcx>,
95 span: Span,
96 hir_id: HirId,
97 ) {
98 if !meets_msrv(self.msrv, msrvs::CONST_IF_MATCH) {
99 return;
100 }
101
102 let def_id = cx.tcx.hir().local_def_id(hir_id);
103
104 if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) {
105 return;
106 }
107
108 // Building MIR for `fn`s with unsatisfiable preds results in ICE.
109 if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
110 return;
111 }
112
113 // Perform some preliminary checks that rule out constness on the Clippy side. This way we
114 // can skip the actual const check and return early.
115 match kind {
116 FnKind::ItemFn(_, generics, header, ..) => {
117 let has_const_generic_params = generics
118 .params
119 .iter()
120 .any(|param| matches!(param.kind, GenericParamKind::Const { .. }));
121
122 if already_const(header) || has_const_generic_params {
123 return;
124 }
125 },
126 FnKind::Method(_, sig, ..) => {
127 if trait_ref_of_method(cx, def_id).is_some()
128 || already_const(sig.header)
129 || method_accepts_droppable(cx, sig.decl.inputs)
130 {
131 return;
132 }
133 },
134 FnKind::Closure => return,
135 }
136
137 // Const fns are not allowed as methods in a trait.
138 {
139 let parent = cx.tcx.hir().get_parent_item(hir_id).def_id;
140 if parent != CRATE_DEF_ID {
141 if let hir::Node::Item(item) = cx.tcx.hir().get_by_def_id(parent) {
142 if let hir::ItemKind::Trait(..) = &item.kind {
143 return;
144 }
145 }
146 }
147 }
148
149 if is_from_proc_macro(cx, &(&kind, body, hir_id, span)) {
150 return;
151 }
152
153 let mir = cx.tcx.optimized_mir(def_id);
154
155 if let Err((span, err)) = is_min_const_fn(cx.tcx, mir, self.msrv) {
156 if cx.tcx.is_const_fn_raw(def_id.to_def_id()) {
157 cx.tcx.sess.span_err(span, err.as_ref());
158 }
159 } else {
160 span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a `const fn`");
161 }
162 }
163 extract_msrv_attr!(LateContext);
164 }
165
166 /// Returns true if any of the method parameters is a type that implements `Drop`. The method
167 /// can't be made const then, because `drop` can't be const-evaluated.
168 fn method_accepts_droppable(cx: &LateContext<'_>, param_tys: &[hir::Ty<'_>]) -> bool {
169 // If any of the params are droppable, return true
170 param_tys.iter().any(|hir_ty| {
171 let ty_ty = hir_ty_to_ty(cx.tcx, hir_ty);
172 has_drop(cx, ty_ty)
173 })
174 }
175
176 // We don't have to lint on something that's already `const`
177 #[must_use]
178 fn already_const(header: hir::FnHeader) -> bool {
179 header.constness == Constness::Const
180 }