1 use clippy_utils::diagnostics::{span_lint_and_help, span_lint_and_note};
2 use clippy_utils::differing_macro_contexts;
3 use clippy_utils::source::snippet_opt;
4 use if_chain::if_chain;
5 use rustc_ast::ast::{BinOpKind, Block, Expr, ExprKind, StmtKind, UnOp};
6 use rustc_lint::{EarlyContext, EarlyLintPass};
7 use rustc_middle::lint::in_external_macro;
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9 use rustc_span::source_map::Span;
11 declare_clippy_lint! {
13 /// Checks for use of the non-existent `=*`, `=!` and `=-`
16 /// ### Why is this bad?
17 /// This is either a typo of `*=`, `!=` or `-=` or
22 /// a =- 42; // confusing, should it be `a -= 42` or `a = -42`?
24 #[clippy::version = "pre 1.29.0"]
25 pub SUSPICIOUS_ASSIGNMENT_FORMATTING,
27 "suspicious formatting of `*=`, `-=` or `!=`"
30 declare_clippy_lint! {
32 /// Checks the formatting of a unary operator on the right hand side
33 /// of a binary operator. It lints if there is no space between the binary and unary operators,
34 /// but there is a space between the unary and its operand.
36 /// ### Why is this bad?
37 /// This is either a typo in the binary operator or confusing.
41 /// if foo <- 30 { // this should be `foo < -30` but looks like a different operator
44 /// if foo &&! bar { // this should be `foo && !bar` but looks like a different operator
47 #[clippy::version = "1.40.0"]
48 pub SUSPICIOUS_UNARY_OP_FORMATTING,
50 "suspicious formatting of unary `-` or `!` on the RHS of a BinOp"
53 declare_clippy_lint! {
55 /// Checks for formatting of `else`. It lints if the `else`
56 /// is followed immediately by a newline or the `else` seems to be missing.
58 /// ### Why is this bad?
59 /// This is probably some refactoring remnant, even if the
60 /// code is correct, it might look confusing.
65 /// } { // looks like an `else` is missing here
69 /// } if bar { // looks like an `else` is missing here
75 /// { // this is the `else` block of the previous `if`, but should it be?
81 /// if bar { // this is the `else` block of the previous `if`, but should it be?
84 #[clippy::version = "pre 1.29.0"]
85 pub SUSPICIOUS_ELSE_FORMATTING,
87 "suspicious formatting of `else`"
90 declare_clippy_lint! {
92 /// Checks for possible missing comma in an array. It lints if
93 /// an array element is a binary operator expression and it lies on two lines.
95 /// ### Why is this bad?
96 /// This could lead to unexpected results.
101 /// -1, -2, -3 // <= no comma here
105 #[clippy::version = "pre 1.29.0"]
106 pub POSSIBLE_MISSING_COMMA,
108 "possible missing comma in array"
111 declare_lint_pass!(Formatting => [
112 SUSPICIOUS_ASSIGNMENT_FORMATTING,
113 SUSPICIOUS_UNARY_OP_FORMATTING,
114 SUSPICIOUS_ELSE_FORMATTING,
115 POSSIBLE_MISSING_COMMA
118 impl EarlyLintPass for Formatting {
119 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
120 for w in block.stmts.windows(2) {
121 if let (StmtKind::Expr(first), StmtKind::Expr(second) | StmtKind::Semi(second)) = (&w[0].kind, &w[1].kind) {
122 check_missing_else(cx, first, second);
127 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
128 check_assign(cx, expr);
129 check_unop(cx, expr);
130 check_else(cx, expr);
131 check_array(cx, expr);
135 /// Implementation of the `SUSPICIOUS_ASSIGNMENT_FORMATTING` lint.
136 fn check_assign(cx: &EarlyContext<'_>, expr: &Expr) {
137 if let ExprKind::Assign(ref lhs, ref rhs, _) = expr.kind {
138 if !differing_macro_contexts(lhs.span, rhs.span) && !lhs.span.from_expansion() {
139 let eq_span = lhs.span.between(rhs.span);
140 if let ExprKind::Unary(op, ref sub_rhs) = rhs.kind {
141 if let Some(eq_snippet) = snippet_opt(cx, eq_span) {
142 let op = UnOp::to_string(op);
143 let eqop_span = lhs.span.between(sub_rhs.span);
144 if eq_snippet.ends_with('=') {
147 SUSPICIOUS_ASSIGNMENT_FORMATTING,
150 "this looks like you are trying to use `.. {op}= ..`, but you \
151 really are doing `.. = ({op} ..)`",
155 &format!("to remove this lint, use either `{op}=` or `= {op}`", op = op),
164 /// Implementation of the `SUSPICIOUS_UNARY_OP_FORMATTING` lint.
165 fn check_unop(cx: &EarlyContext<'_>, expr: &Expr) {
167 if let ExprKind::Binary(ref binop, ref lhs, ref rhs) = expr.kind;
168 if !differing_macro_contexts(lhs.span, rhs.span) && !lhs.span.from_expansion();
169 // span between BinOp LHS and RHS
170 let binop_span = lhs.span.between(rhs.span);
172 if let ExprKind::Unary(op, ref un_rhs) = rhs.kind;
173 // from UnOp operator to UnOp operand
174 let unop_operand_span = rhs.span.until(un_rhs.span);
175 if let Some(binop_snippet) = snippet_opt(cx, binop_span);
176 if let Some(unop_operand_snippet) = snippet_opt(cx, unop_operand_span);
177 let binop_str = BinOpKind::to_string(&binop.node);
178 // no space after BinOp operator and space after UnOp operator
179 if binop_snippet.ends_with(binop_str) && unop_operand_snippet.ends_with(' ');
181 let unop_str = UnOp::to_string(op);
182 let eqop_span = lhs.span.between(un_rhs.span);
185 SUSPICIOUS_UNARY_OP_FORMATTING,
188 "by not having a space between `{binop}` and `{unop}` it looks like \
189 `{binop}{unop}` is a single operator",
195 "put a space between `{binop}` and `{unop}` and remove the space after `{unop}`",
204 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for weird `else`.
205 fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
207 if let ExprKind::If(_, then, Some(else_)) = &expr.kind;
208 if is_block(else_) || is_if(else_);
209 if !differing_macro_contexts(then.span, else_.span);
210 if !then.span.from_expansion() && !in_external_macro(cx.sess, expr.span);
212 // workaround for rust-lang/rust#43081
213 if expr.span.lo().0 != 0 && expr.span.hi().0 != 0;
215 // this will be a span from the closing ‘}’ of the “then” block (excluding) to
216 // the “if” of the “else if” block (excluding)
217 let else_span = then.span.between(else_.span);
219 // the snippet should look like " else \n " with maybe comments anywhere
220 // it’s bad when there is a ‘\n’ after the “else”
221 if let Some(else_snippet) = snippet_opt(cx, else_span);
222 if let Some((pre_else, post_else)) = else_snippet.split_once("else");
223 if let Some((_, post_else_post_eol)) = post_else.split_once('\n');
226 // Allow allman style braces `} \n else \n {`
229 if let Some((_, pre_else_post_eol)) = pre_else.split_once('\n');
230 // Exactly one eol before and after the else
231 if !pre_else_post_eol.contains('\n');
232 if !post_else_post_eol.contains('\n');
238 let else_desc = if is_if(else_) { "if" } else { "{..}" };
241 SUSPICIOUS_ELSE_FORMATTING,
243 &format!("this is an `else {}` but the formatting might hide it", else_desc),
246 "to remove this lint, remove the `else` or remove the new line between \
256 fn has_unary_equivalent(bin_op: BinOpKind) -> bool {
258 bin_op == BinOpKind::And || bin_op == BinOpKind::Mul || bin_op == BinOpKind::Sub
261 fn indentation(cx: &EarlyContext<'_>, span: Span) -> usize {
262 cx.sess.source_map().lookup_char_pos(span.lo()).col.0
265 /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array
266 fn check_array(cx: &EarlyContext<'_>, expr: &Expr) {
267 if let ExprKind::Array(ref array) = expr.kind {
268 for element in array {
270 if let ExprKind::Binary(ref op, ref lhs, _) = element.kind;
271 if has_unary_equivalent(op.node) && !differing_macro_contexts(lhs.span, op.span);
272 let space_span = lhs.span.between(op.span);
273 if let Some(space_snippet) = snippet_opt(cx, space_span);
274 let lint_span = lhs.span.with_lo(lhs.span.hi());
275 if space_snippet.contains('\n');
276 if indentation(cx, op.span) <= indentation(cx, lhs.span);
280 POSSIBLE_MISSING_COMMA,
282 "possibly missing a comma here",
284 "to remove this lint, add a comma or write the expr in a single line",
292 fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) {
294 if !differing_macro_contexts(first.span, second.span);
295 if !first.span.from_expansion();
296 if let ExprKind::If(cond_expr, ..) = &first.kind;
297 if is_block(second) || is_if(second);
299 // Proc-macros can give weird spans. Make sure this is actually an `if`.
300 if let Some(if_snip) = snippet_opt(cx, first.span.until(cond_expr.span));
301 if if_snip.starts_with("if");
303 // If there is a line break between the two expressions, don't lint.
304 // If there is a non-whitespace character, this span came from a proc-macro.
305 let else_span = first.span.between(second.span);
306 if let Some(else_snippet) = snippet_opt(cx, else_span);
307 if !else_snippet.chars().any(|c| c == '\n' || !c.is_whitespace());
309 let (looks_like, next_thing) = if is_if(second) {
310 ("an `else if`", "the second `if`")
312 ("an `else {..}`", "the next block")
317 SUSPICIOUS_ELSE_FORMATTING,
319 &format!("this looks like {} but the `else` is missing", looks_like),
322 "to remove this lint, add the missing `else` or add a new line before {}",
330 fn is_block(expr: &Expr) -> bool {
331 matches!(expr.kind, ExprKind::Block(..))
334 /// Check if the expression is an `if` or `if let`
335 fn is_if(expr: &Expr) -> bool {
336 matches!(expr.kind, ExprKind::If(..))