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