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 pub SUSPICIOUS_ASSIGNMENT_FORMATTING,
26 "suspicious formatting of `*=`, `-=` or `!=`"
29 declare_clippy_lint! {
31 /// Checks the formatting of a unary operator on the right hand side
32 /// of a binary operator. It lints if there is no space between the binary and unary operators,
33 /// but there is a space between the unary and its operand.
35 /// ### Why is this bad?
36 /// This is either a typo in the binary operator or confusing.
40 /// if foo <- 30 { // this should be `foo < -30` but looks like a different operator
43 /// if foo &&! bar { // this should be `foo && !bar` but looks like a different operator
46 pub SUSPICIOUS_UNARY_OP_FORMATTING,
48 "suspicious formatting of unary `-` or `!` on the RHS of a BinOp"
51 declare_clippy_lint! {
53 /// Checks for formatting of `else`. It lints if the `else`
54 /// is followed immediately by a newline or the `else` seems to be missing.
56 /// ### Why is this bad?
57 /// This is probably some refactoring remnant, even if the
58 /// code is correct, it might look confusing.
63 /// } { // looks like an `else` is missing here
67 /// } if bar { // looks like an `else` is missing here
73 /// { // this is the `else` block of the previous `if`, but should it be?
79 /// if bar { // this is the `else` block of the previous `if`, but should it be?
82 pub SUSPICIOUS_ELSE_FORMATTING,
84 "suspicious formatting of `else`"
87 declare_clippy_lint! {
89 /// Checks for possible missing comma in an array. It lints if
90 /// an array element is a binary operator expression and it lies on two lines.
92 /// ### Why is this bad?
93 /// This could lead to unexpected results.
98 /// -1, -2, -3 // <= no comma here
102 pub POSSIBLE_MISSING_COMMA,
104 "possible missing comma in array"
107 declare_lint_pass!(Formatting => [
108 SUSPICIOUS_ASSIGNMENT_FORMATTING,
109 SUSPICIOUS_UNARY_OP_FORMATTING,
110 SUSPICIOUS_ELSE_FORMATTING,
111 POSSIBLE_MISSING_COMMA
114 impl EarlyLintPass for Formatting {
115 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &Block) {
116 for w in block.stmts.windows(2) {
117 if let (StmtKind::Expr(first), StmtKind::Expr(second) | StmtKind::Semi(second)) = (&w[0].kind, &w[1].kind) {
118 check_missing_else(cx, first, second);
123 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &Expr) {
124 check_assign(cx, expr);
125 check_unop(cx, expr);
126 check_else(cx, expr);
127 check_array(cx, expr);
131 /// Implementation of the `SUSPICIOUS_ASSIGNMENT_FORMATTING` lint.
132 fn check_assign(cx: &EarlyContext<'_>, expr: &Expr) {
133 if let ExprKind::Assign(ref lhs, ref rhs, _) = expr.kind {
134 if !differing_macro_contexts(lhs.span, rhs.span) && !lhs.span.from_expansion() {
135 let eq_span = lhs.span.between(rhs.span);
136 if let ExprKind::Unary(op, ref sub_rhs) = rhs.kind {
137 if let Some(eq_snippet) = snippet_opt(cx, eq_span) {
138 let op = UnOp::to_string(op);
139 let eqop_span = lhs.span.between(sub_rhs.span);
140 if eq_snippet.ends_with('=') {
143 SUSPICIOUS_ASSIGNMENT_FORMATTING,
146 "this looks like you are trying to use `.. {op}= ..`, but you \
147 really are doing `.. = ({op} ..)`",
151 &format!("to remove this lint, use either `{op}=` or `= {op}`", op = op),
160 /// Implementation of the `SUSPICIOUS_UNARY_OP_FORMATTING` lint.
161 fn check_unop(cx: &EarlyContext<'_>, expr: &Expr) {
163 if let ExprKind::Binary(ref binop, ref lhs, ref rhs) = expr.kind;
164 if !differing_macro_contexts(lhs.span, rhs.span) && !lhs.span.from_expansion();
165 // span between BinOp LHS and RHS
166 let binop_span = lhs.span.between(rhs.span);
168 if let ExprKind::Unary(op, ref un_rhs) = rhs.kind;
169 // from UnOp operator to UnOp operand
170 let unop_operand_span = rhs.span.until(un_rhs.span);
171 if let Some(binop_snippet) = snippet_opt(cx, binop_span);
172 if let Some(unop_operand_snippet) = snippet_opt(cx, unop_operand_span);
173 let binop_str = BinOpKind::to_string(&binop.node);
174 // no space after BinOp operator and space after UnOp operator
175 if binop_snippet.ends_with(binop_str) && unop_operand_snippet.ends_with(' ');
177 let unop_str = UnOp::to_string(op);
178 let eqop_span = lhs.span.between(un_rhs.span);
181 SUSPICIOUS_UNARY_OP_FORMATTING,
184 "by not having a space between `{binop}` and `{unop}` it looks like \
185 `{binop}{unop}` is a single operator",
191 "put a space between `{binop}` and `{unop}` and remove the space after `{unop}`",
200 /// Implementation of the `SUSPICIOUS_ELSE_FORMATTING` lint for weird `else`.
201 fn check_else(cx: &EarlyContext<'_>, expr: &Expr) {
203 if let ExprKind::If(_, then, Some(else_)) = &expr.kind;
204 if is_block(else_) || is_if(else_);
205 if !differing_macro_contexts(then.span, else_.span);
206 if !then.span.from_expansion() && !in_external_macro(cx.sess, expr.span);
208 // workaround for rust-lang/rust#43081
209 if expr.span.lo().0 != 0 && expr.span.hi().0 != 0;
211 // this will be a span from the closing ‘}’ of the “then” block (excluding) to
212 // the “if” of the “else if” block (excluding)
213 let else_span = then.span.between(else_.span);
215 // the snippet should look like " else \n " with maybe comments anywhere
216 // it’s bad when there is a ‘\n’ after the “else”
217 if let Some(else_snippet) = snippet_opt(cx, else_span);
218 if let Some((pre_else, post_else)) = else_snippet.split_once("else");
219 if let Some((_, post_else_post_eol)) = post_else.split_once('\n');
222 // Allow allman style braces `} \n else \n {`
225 if let Some((_, pre_else_post_eol)) = pre_else.split_once('\n');
226 // Exactly one eol before and after the else
227 if !pre_else_post_eol.contains('\n');
228 if !post_else_post_eol.contains('\n');
234 let else_desc = if is_if(else_) { "if" } else { "{..}" };
237 SUSPICIOUS_ELSE_FORMATTING,
239 &format!("this is an `else {}` but the formatting might hide it", else_desc),
242 "to remove this lint, remove the `else` or remove the new line between \
252 fn has_unary_equivalent(bin_op: BinOpKind) -> bool {
254 bin_op == BinOpKind::And || bin_op == BinOpKind::Mul || bin_op == BinOpKind::Sub
257 fn indentation(cx: &EarlyContext<'_>, span: Span) -> usize {
258 cx.sess.source_map().lookup_char_pos(span.lo()).col.0
261 /// Implementation of the `POSSIBLE_MISSING_COMMA` lint for array
262 fn check_array(cx: &EarlyContext<'_>, expr: &Expr) {
263 if let ExprKind::Array(ref array) = expr.kind {
264 for element in array {
266 if let ExprKind::Binary(ref op, ref lhs, _) = element.kind;
267 if has_unary_equivalent(op.node) && !differing_macro_contexts(lhs.span, op.span);
268 let space_span = lhs.span.between(op.span);
269 if let Some(space_snippet) = snippet_opt(cx, space_span);
270 let lint_span = lhs.span.with_lo(lhs.span.hi());
271 if space_snippet.contains('\n');
272 if indentation(cx, op.span) <= indentation(cx, lhs.span);
276 POSSIBLE_MISSING_COMMA,
278 "possibly missing a comma here",
280 "to remove this lint, add a comma or write the expr in a single line",
288 fn check_missing_else(cx: &EarlyContext<'_>, first: &Expr, second: &Expr) {
289 if !differing_macro_contexts(first.span, second.span)
290 && !first.span.from_expansion()
292 && (is_block(second) || is_if(second))
294 // where the else would be
295 let else_span = first.span.between(second.span);
297 if let Some(else_snippet) = snippet_opt(cx, else_span) {
298 if !else_snippet.contains('\n') {
299 let (looks_like, next_thing) = if is_if(second) {
300 ("an `else if`", "the second `if`")
302 ("an `else {..}`", "the next block")
307 SUSPICIOUS_ELSE_FORMATTING,
309 &format!("this looks like {} but the `else` is missing", looks_like),
312 "to remove this lint, add the missing `else` or add a new line before {}",
321 fn is_block(expr: &Expr) -> bool {
322 matches!(expr.kind, ExprKind::Block(..))
325 /// Check if the expression is an `if` or `if let`
326 fn is_if(expr: &Expr) -> bool {
327 matches!(expr.kind, ExprKind::If(..))