1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::source::{trim_span, walk_span_to_context};
3 use clippy_utils::{meets_msrv, msrvs};
4 use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits};
5 use rustc_errors::Applicability;
6 use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
7 use rustc_semver::RustcVersion;
8 use rustc_session::{declare_tool_lint, impl_lint_pass};
11 declare_clippy_lint! {
13 /// Checks for ranges which almost include the entire range of letters from 'a' to 'z', but
14 /// don't because they're a half open range.
16 /// ### Why is this bad?
17 /// This (`'a'..'z'`) is almost certainly a typo meant to include all letters.
25 /// let _ = 'a'..='z';
27 #[clippy::version = "1.63.0"]
28 pub ALMOST_COMPLETE_LETTER_RANGE,
30 "almost complete letter range"
32 impl_lint_pass!(AlmostCompleteLetterRange => [ALMOST_COMPLETE_LETTER_RANGE]);
34 pub struct AlmostCompleteLetterRange {
35 msrv: Option<RustcVersion>,
37 impl AlmostCompleteLetterRange {
38 pub fn new(msrv: Option<RustcVersion>) -> Self {
42 impl EarlyLintPass for AlmostCompleteLetterRange {
43 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
44 if let ExprKind::Range(Some(start), Some(end), RangeLimits::HalfOpen) = &e.kind {
45 let ctxt = e.span.ctxt();
46 let sugg = if let Some(start) = walk_span_to_context(start.span, ctxt)
47 && let Some(end) = walk_span_to_context(end.span, ctxt)
48 && meets_msrv(self.msrv, msrvs::RANGE_INCLUSIVE)
50 Some((trim_span(cx.sess().source_map(), start.between(end)), "..="))
54 check_range(cx, e.span, start, end, sugg);
58 fn check_pat(&mut self, cx: &EarlyContext<'_>, p: &Pat) {
59 if let PatKind::Range(Some(start), Some(end), kind) = &p.kind
60 && matches!(kind.node, RangeEnd::Excluded)
62 let sugg = if meets_msrv(self.msrv, msrvs::RANGE_INCLUSIVE) {
67 check_range(cx, p.span, start, end, Some((kind.span, sugg)));
71 extract_msrv_attr!(EarlyContext);
74 fn check_range(cx: &EarlyContext<'_>, span: Span, start: &Expr, end: &Expr, sugg: Option<(Span, &str)>) {
75 if let ExprKind::Lit(start_lit) = &start.peel_parens().kind
76 && let ExprKind::Lit(end_lit) = &end.peel_parens().kind
78 (&start_lit.kind, &end_lit.kind),
79 (LitKind::Byte(b'a') | LitKind::Char('a'), LitKind::Byte(b'z') | LitKind::Char('z'))
80 | (LitKind::Byte(b'A') | LitKind::Char('A'), LitKind::Byte(b'Z') | LitKind::Char('Z'))
85 ALMOST_COMPLETE_LETTER_RANGE,
87 "almost complete ascii letter range",
89 if let Some((span, sugg)) = sugg {
92 "use an inclusive range",
94 Applicability::MaybeIncorrect,