|
| 1 | +use rustc_ast::token::LitKind; |
| 2 | +use rustc_ast::{Expr, ExprKind, MethodCall, UnOp}; |
| 3 | +use rustc_session::{declare_lint, declare_lint_pass}; |
| 4 | + |
| 5 | +use crate::lints::{ |
| 6 | + AmbiguousNegativeLiteralsCurrentBehaviorSuggestion, AmbiguousNegativeLiteralsDiag, |
| 7 | + AmbiguousNegativeLiteralsNegativeLiteralSuggestion, |
| 8 | +}; |
| 9 | +use crate::{EarlyContext, EarlyLintPass, LintContext}; |
| 10 | + |
| 11 | +declare_lint! { |
| 12 | + /// The `ambiguous_negative_literals` lint checks for cases that are |
| 13 | + /// confusing between a negative literal and a negation that's not part |
| 14 | + /// of the literal. |
| 15 | + /// |
| 16 | + /// ### Example |
| 17 | + /// |
| 18 | + /// ```rust,compile_fail |
| 19 | + /// # #![allow(unused)] |
| 20 | + /// -1i32.abs(); // equals -1, while `(-1i32).abs()` equals 1 |
| 21 | + /// ``` |
| 22 | + /// |
| 23 | + /// {{produces}} |
| 24 | + /// |
| 25 | + /// ### Explanation |
| 26 | + /// |
| 27 | + /// Method calls take precedence over unary precedence. Setting the |
| 28 | + /// precedence explicitly makes the code clearer and avoid potential bugs. |
| 29 | + pub AMBIGUOUS_NEGATIVE_LITERALS, |
| 30 | + Deny, |
| 31 | + "ambiguous negative literals operations", |
| 32 | + report_in_external_macro |
| 33 | +} |
| 34 | + |
| 35 | +declare_lint_pass!(Precedence => [AMBIGUOUS_NEGATIVE_LITERALS]); |
| 36 | + |
| 37 | +impl EarlyLintPass for Precedence { |
| 38 | + fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) { |
| 39 | + let ExprKind::Unary(UnOp::Neg, operand) = &expr.kind else { |
| 40 | + return; |
| 41 | + }; |
| 42 | + |
| 43 | + let mut arg = operand; |
| 44 | + let mut at_least_one = false; |
| 45 | + while let ExprKind::MethodCall(box MethodCall { receiver, .. }) = &arg.kind { |
| 46 | + at_least_one = true; |
| 47 | + arg = receiver; |
| 48 | + } |
| 49 | + |
| 50 | + if at_least_one |
| 51 | + && let ExprKind::Lit(lit) = &arg.kind |
| 52 | + && let LitKind::Integer | LitKind::Float = &lit.kind |
| 53 | + { |
| 54 | + cx.emit_span_lint( |
| 55 | + AMBIGUOUS_NEGATIVE_LITERALS, |
| 56 | + expr.span, |
| 57 | + AmbiguousNegativeLiteralsDiag { |
| 58 | + negative_literal: AmbiguousNegativeLiteralsNegativeLiteralSuggestion { |
| 59 | + start_span: expr.span.shrink_to_lo(), |
| 60 | + end_span: arg.span.shrink_to_hi(), |
| 61 | + }, |
| 62 | + current_behavior: AmbiguousNegativeLiteralsCurrentBehaviorSuggestion { |
| 63 | + start_span: operand.span.shrink_to_lo(), |
| 64 | + end_span: operand.span.shrink_to_hi(), |
| 65 | + }, |
| 66 | + }, |
| 67 | + ); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments