|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::path_res; |
| 3 | +use rustc_ast::ast::LitKind; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::def::Res; |
| 6 | +use rustc_hir::intravisit::{FnKind, Visitor}; |
| 7 | +use rustc_hir::{Body, Expr, ExprKind, FnDecl, FnRetTy, Lit, MutTy, Mutability, PrimTy, Ty, TyKind, intravisit}; |
| 8 | +use rustc_lint::{LateContext, LateLintPass}; |
| 9 | +use rustc_session::declare_lint_pass; |
| 10 | +use rustc_span::Span; |
| 11 | +use rustc_span::def_id::LocalDefId; |
| 12 | + |
| 13 | +declare_clippy_lint! { |
| 14 | + /// ### What it does |
| 15 | + /// |
| 16 | + /// Detects functions that are written to return `&str` that could return `&'static str` but instead return a `&'a str`. |
| 17 | + /// |
| 18 | + /// ### Why is this bad? |
| 19 | + /// |
| 20 | + /// This leaves the caller unable to use the `&str` as `&'static str`, causing unneccessary allocations or confusion. |
| 21 | + /// This is also most likely what you meant to write. |
| 22 | + /// |
| 23 | + /// ### Example |
| 24 | + /// ```no_run |
| 25 | + /// # struct MyType; |
| 26 | + /// impl MyType { |
| 27 | + /// fn returns_literal(&self) -> &str { |
| 28 | + /// "Literal" |
| 29 | + /// } |
| 30 | + /// } |
| 31 | + /// ``` |
| 32 | + /// Use instead: |
| 33 | + /// ```no_run |
| 34 | + /// # struct MyType; |
| 35 | + /// impl MyType { |
| 36 | + /// fn returns_literal(&self) -> &'static str { |
| 37 | + /// "Literal" |
| 38 | + /// } |
| 39 | + /// } |
| 40 | + /// ``` |
| 41 | + /// Or, in case you may return a non-literal `str` in future: |
| 42 | + /// ```no_run |
| 43 | + /// # struct MyType; |
| 44 | + /// impl MyType { |
| 45 | + /// fn returns_literal<'a>(&'a self) -> &'a str { |
| 46 | + /// "Literal" |
| 47 | + /// } |
| 48 | + /// } |
| 49 | + /// ``` |
| 50 | + #[clippy::version = "1.83.0"] |
| 51 | + pub UNNECESSARY_LITERAL_BOUND, |
| 52 | + pedantic, |
| 53 | + "detects &str that could be &'static str in function return types" |
| 54 | +} |
| 55 | + |
| 56 | +declare_lint_pass!(UnnecessaryLiteralBound => [UNNECESSARY_LITERAL_BOUND]); |
| 57 | + |
| 58 | +fn extract_anonymous_ref<'tcx>(hir_ty: &Ty<'tcx>) -> Option<&'tcx Ty<'tcx>> { |
| 59 | + let TyKind::Ref(lifetime, MutTy { ty, mutbl }) = hir_ty.kind else { |
| 60 | + return None; |
| 61 | + }; |
| 62 | + |
| 63 | + if !lifetime.is_anonymous() || !matches!(mutbl, Mutability::Not) { |
| 64 | + return None; |
| 65 | + } |
| 66 | + |
| 67 | + Some(ty) |
| 68 | +} |
| 69 | + |
| 70 | +fn is_str_literal(expr: &Expr<'_>) -> bool { |
| 71 | + matches!( |
| 72 | + expr.kind, |
| 73 | + ExprKind::Lit(Lit { |
| 74 | + node: LitKind::Str(..), |
| 75 | + .. |
| 76 | + }), |
| 77 | + ) |
| 78 | +} |
| 79 | + |
| 80 | +struct FindNonLiteralReturn; |
| 81 | + |
| 82 | +impl<'hir> Visitor<'hir> for FindNonLiteralReturn { |
| 83 | + type Result = std::ops::ControlFlow<()>; |
| 84 | + type NestedFilter = intravisit::nested_filter::None; |
| 85 | + |
| 86 | + fn visit_expr(&mut self, expr: &'hir Expr<'hir>) -> Self::Result { |
| 87 | + if let ExprKind::Ret(Some(ret_val_expr)) = expr.kind |
| 88 | + && !is_str_literal(ret_val_expr) |
| 89 | + { |
| 90 | + Self::Result::Break(()) |
| 91 | + } else { |
| 92 | + intravisit::walk_expr(self, expr) |
| 93 | + } |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +fn check_implicit_returns_static_str(body: &Body<'_>) -> bool { |
| 98 | + // TODO: Improve this to the same complexity as the Visitor to catch more implicit return cases. |
| 99 | + if let ExprKind::Block(block, _) = body.value.kind |
| 100 | + && let Some(implicit_ret) = block.expr |
| 101 | + { |
| 102 | + return is_str_literal(implicit_ret); |
| 103 | + } |
| 104 | + |
| 105 | + false |
| 106 | +} |
| 107 | + |
| 108 | +fn check_explicit_returns_static_str(expr: &Expr<'_>) -> bool { |
| 109 | + let mut visitor = FindNonLiteralReturn; |
| 110 | + visitor.visit_expr(expr).is_continue() |
| 111 | +} |
| 112 | + |
| 113 | +impl<'tcx> LateLintPass<'tcx> for UnnecessaryLiteralBound { |
| 114 | + fn check_fn( |
| 115 | + &mut self, |
| 116 | + cx: &LateContext<'tcx>, |
| 117 | + kind: FnKind<'tcx>, |
| 118 | + decl: &'tcx FnDecl<'_>, |
| 119 | + body: &'tcx Body<'_>, |
| 120 | + span: Span, |
| 121 | + _: LocalDefId, |
| 122 | + ) { |
| 123 | + if span.from_expansion() { |
| 124 | + return; |
| 125 | + } |
| 126 | + |
| 127 | + // Checking closures would be a little silly |
| 128 | + if matches!(kind, FnKind::Closure) { |
| 129 | + return; |
| 130 | + } |
| 131 | + |
| 132 | + // Check for `-> &str` |
| 133 | + let FnRetTy::Return(ret_hir_ty) = decl.output else { |
| 134 | + return; |
| 135 | + }; |
| 136 | + |
| 137 | + let Some(inner_hir_ty) = extract_anonymous_ref(ret_hir_ty) else { |
| 138 | + return; |
| 139 | + }; |
| 140 | + |
| 141 | + if path_res(cx, inner_hir_ty) != Res::PrimTy(PrimTy::Str) { |
| 142 | + return; |
| 143 | + } |
| 144 | + |
| 145 | + // Check for all return statements returning literals |
| 146 | + if check_explicit_returns_static_str(body.value) && check_implicit_returns_static_str(body) { |
| 147 | + span_lint_and_sugg( |
| 148 | + cx, |
| 149 | + UNNECESSARY_LITERAL_BOUND, |
| 150 | + ret_hir_ty.span, |
| 151 | + "returning a `str` unnecessarily tied to the lifetime of arguments", |
| 152 | + "try", |
| 153 | + "&'static str".into(), // how ironic, a lint about `&'static str` requiring a `String` alloc... |
| 154 | + Applicability::MachineApplicable, |
| 155 | + ); |
| 156 | + } |
| 157 | + } |
| 158 | +} |
0 commit comments