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;
5 fn_has_unsatisfiable_preds, is_entrypoint_fn, is_from_proc_macro, meets_msrv, msrvs, trait_ref_of_method,
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_lint::{LateContext, LateLintPass};
12 use rustc_middle::lint::in_external_macro;
13 use rustc_semver::RustcVersion;
14 use rustc_session::{declare_tool_lint, impl_lint_pass};
16 use rustc_typeck::hir_ty_to_ty;
18 declare_clippy_lint! {
20 /// Suggests the use of `const` in functions and methods where possible.
22 /// ### Why is this bad?
23 /// Not having the function const prevents callers of the function from being const as well.
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.
30 /// Also, the lint only runs one pass over the code. Consider these two non-const functions:
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.
48 /// # random_number: usize,
51 /// fn new() -> Self {
52 /// Self { random_number: 42 }
57 /// Could be a const fn:
61 /// # random_number: usize,
64 /// const fn new() -> Self {
65 /// Self { random_number: 42 }
69 #[clippy::version = "1.34.0"]
70 pub MISSING_CONST_FOR_FN,
72 "Lint functions definitions that could be made `const fn`"
75 impl_lint_pass!(MissingConstForFn => [MISSING_CONST_FOR_FN]);
77 pub struct MissingConstForFn {
78 msrv: Option<RustcVersion>,
81 impl MissingConstForFn {
83 pub fn new(msrv: Option<RustcVersion>) -> Self {
88 impl<'tcx> LateLintPass<'tcx> for MissingConstForFn {
91 cx: &LateContext<'tcx>,
98 if !meets_msrv(self.msrv, msrvs::CONST_IF_MATCH) {
102 let def_id = cx.tcx.hir().local_def_id(hir_id);
104 if in_external_macro(cx.tcx.sess, span) || is_entrypoint_fn(cx, def_id.to_def_id()) {
108 // Building MIR for `fn`s with unsatisfiable preds results in ICE.
109 if fn_has_unsatisfiable_preds(cx, def_id.to_def_id()) {
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.
116 FnKind::ItemFn(_, generics, header, ..) => {
117 let has_const_generic_params = generics
120 .any(|param| matches!(param.kind, GenericParamKind::Const { .. }));
122 if already_const(header) || has_const_generic_params {
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)
134 FnKind::Closure => return,
137 // Const fns are not allowed as methods in a trait.
139 let parent = cx.tcx.hir().get_parent_item(hir_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 {
149 if is_from_proc_macro(cx, &(&kind, body, hir_id, span)) {
153 let mir = cx.tcx.optimized_mir(def_id);
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());
160 span_lint(cx, MISSING_CONST_FOR_FN, span, "this could be a `const fn`");
163 extract_msrv_attr!(LateContext);
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);
176 // We don't have to lint on something that's already `const`
178 fn already_const(header: hir::FnHeader) -> bool {
179 header.constness == Constness::Const