|
| 1 | +use clippy_utils::diagnostics::span_lint_and_then; |
| 2 | +use clippy_utils::source::{HasSession, snippet}; |
| 3 | +use rustc_ast::NodeId; |
| 4 | +use rustc_ast::ast::{Fn, FnRetTy, GenericParam, GenericParamKind}; |
| 5 | +use rustc_ast::visit::{FnCtxt, FnKind}; |
| 6 | +use rustc_errors::Applicability; |
| 7 | +use rustc_lint::{EarlyContext, EarlyLintPass}; |
| 8 | +use rustc_session::declare_lint_pass; |
| 9 | +use rustc_span::Span; |
| 10 | + |
| 11 | +declare_clippy_lint! { |
| 12 | + /// ### What it does |
| 13 | + /// Enforce that `where` bounds are used for all trait bounds. |
| 14 | + /// |
| 15 | + /// ### Why restrict this? |
| 16 | + /// Enforce a single style throughout a codebase. |
| 17 | + /// Avoid uncertainty about whether a bound should be inline |
| 18 | + /// or out-of-line (i.e. a where bound). |
| 19 | + /// Avoid complex inline bounds, which could make a function declaration more difficult to read. |
| 20 | + /// |
| 21 | + /// ### Known limitations |
| 22 | + /// Only lints functions and method declararions. Bounds on structs, enums, |
| 23 | + /// and impl blocks are not yet covered. |
| 24 | + /// |
| 25 | + /// ### Example |
| 26 | + /// ```no_run |
| 27 | + /// fn foo<T: Clone>() {} |
| 28 | + /// ``` |
| 29 | + /// |
| 30 | + /// Use instead: |
| 31 | + /// ```no_run |
| 32 | + /// fn foo<T>() where T: Clone {} |
| 33 | + /// ``` |
| 34 | + #[clippy::version = "1.97.0"] |
| 35 | + pub INLINE_TRAIT_BOUNDS, |
| 36 | + restriction, |
| 37 | + "enforce that `where` bounds are used for all trait bounds" |
| 38 | +} |
| 39 | + |
| 40 | +declare_lint_pass!(InlineTraitBounds => [INLINE_TRAIT_BOUNDS]); |
| 41 | + |
| 42 | +impl EarlyLintPass for InlineTraitBounds { |
| 43 | + fn check_fn(&mut self, cx: &EarlyContext<'_>, kind: FnKind<'_>, _: Span, _: NodeId) { |
| 44 | + let FnKind::Fn(ctxt, _vis, f) = kind else { |
| 45 | + return; |
| 46 | + }; |
| 47 | + |
| 48 | + // Skip foreign functions (extern "C" etc.) |
| 49 | + if !matches!(ctxt, FnCtxt::Free | FnCtxt::Assoc(..)) { |
| 50 | + return; |
| 51 | + } |
| 52 | + |
| 53 | + if f.sig.span.in_external_macro(cx.sess().source_map()) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + lint_fn(cx, f); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +fn lint_fn(cx: &EarlyContext<'_>, f: &Fn) { |
| 62 | + let generics = &f.generics; |
| 63 | + let offenders: Vec<&GenericParam> = generics |
| 64 | + .params |
| 65 | + .iter() |
| 66 | + .filter(|param| { |
| 67 | + !param.bounds.is_empty() && matches!(param.kind, GenericParamKind::Lifetime | GenericParamKind::Type { .. }) |
| 68 | + }) |
| 69 | + .collect(); |
| 70 | + if offenders.is_empty() { |
| 71 | + return; |
| 72 | + } |
| 73 | + |
| 74 | + let predicates = offenders |
| 75 | + .iter() |
| 76 | + .map(|param| build_predicate_text(cx, param)) |
| 77 | + .collect::<Vec<_>>(); |
| 78 | + |
| 79 | + let mut edits = Vec::new(); |
| 80 | + |
| 81 | + for param in offenders { |
| 82 | + if let Some(colon) = param.colon_span { |
| 83 | + let remove_span = colon.to(param.bounds.last().unwrap().span()); |
| 84 | + |
| 85 | + edits.push((remove_span, String::new())); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + let predicate_text = predicates.join(", "); |
| 90 | + |
| 91 | + let where_clause = &generics.where_clause; |
| 92 | + if where_clause.has_where_token { |
| 93 | + let (insert_at, suffix) = if let Some(last_pred) = where_clause.predicates.last() { |
| 94 | + // existing `where` with predicates: append after last predicate |
| 95 | + (last_pred.span.shrink_to_hi(), format!(", {predicate_text}")) |
| 96 | + } else { |
| 97 | + // `where` token present but empty predicate list |
| 98 | + (where_clause.span.shrink_to_hi(), format!(" {predicate_text}")) |
| 99 | + }; |
| 100 | + |
| 101 | + edits.push((insert_at, suffix)); |
| 102 | + } else { |
| 103 | + let insert_at = match &f.sig.decl.output { |
| 104 | + FnRetTy::Default(span) => span.shrink_to_lo(), |
| 105 | + FnRetTy::Ty(ty) => ty.span.shrink_to_hi(), |
| 106 | + }; |
| 107 | + edits.push((insert_at, format!(" where {predicate_text}"))); |
| 108 | + } |
| 109 | + |
| 110 | + span_lint_and_then( |
| 111 | + cx, |
| 112 | + INLINE_TRAIT_BOUNDS, |
| 113 | + generics.span, |
| 114 | + "inline trait bounds used", |
| 115 | + |diag| { |
| 116 | + diag.multipart_suggestion( |
| 117 | + "move bounds to a `where` clause", |
| 118 | + edits, |
| 119 | + Applicability::MachineApplicable, |
| 120 | + ); |
| 121 | + }, |
| 122 | + ); |
| 123 | +} |
| 124 | + |
| 125 | +fn build_predicate_text(cx: &EarlyContext<'_>, param: &GenericParam) -> String { |
| 126 | + // bounds is guaranteed non-empty by the filter in `lint_fn` |
| 127 | + let first = param.bounds.first().unwrap(); |
| 128 | + let last = param.bounds.last().unwrap(); |
| 129 | + |
| 130 | + let bounds_span = first.span().to(last.span()); |
| 131 | + |
| 132 | + let lhs = snippet(cx, param.ident.span, ".."); |
| 133 | + |
| 134 | + let rhs = snippet(cx, bounds_span, ".."); |
| 135 | + |
| 136 | + format!("{lhs}: {rhs}") |
| 137 | +} |
0 commit comments