1 use clippy_utils::diagnostics::{multispan_sugg_with_applicability, span_lint_and_then};
2 use rustc_errors::Applicability;
3 use rustc_hir::{Block, Expr, ExprKind, Stmt, StmtKind};
4 use rustc_lint::{LateContext, LateLintPass, LintContext};
5 use rustc_session::{declare_lint_pass, declare_tool_lint};
11 /// Suggests moving the semicolon after a block to the inside of the block, after its last
14 /// ### Why is this bad?
16 /// For consistency it's best to have the semicolon inside/outside the block. Either way is fine
17 /// and this lint suggests inside the block.
18 /// Take a look at `semicolon_outside_block` for the other alternative.
33 #[clippy::version = "1.66.0"]
34 pub SEMICOLON_INSIDE_BLOCK,
36 "add a semicolon inside the block"
38 declare_clippy_lint! {
41 /// Suggests moving the semicolon from a block's final expression outside of the block.
43 /// ### Why is this bad?
45 /// For consistency it's best to have the semicolon inside/outside the block. Either way is fine
46 /// and this lint suggests outside the block.
47 /// Take a look at `semicolon_inside_block` for the other alternative.
62 #[clippy::version = "1.66.0"]
63 pub SEMICOLON_OUTSIDE_BLOCK,
65 "add a semicolon outside the block"
67 declare_lint_pass!(SemicolonBlock => [SEMICOLON_INSIDE_BLOCK, SEMICOLON_OUTSIDE_BLOCK]);
69 impl LateLintPass<'_> for SemicolonBlock {
70 fn check_stmt(&mut self, cx: &LateContext<'_>, stmt: &Stmt<'_>) {
73 kind: ExprKind::Block(block, _),
75 }) if !block.span.from_expansion() => {
80 } = block else { return };
82 kind: StmtKind::Semi(expr),
85 } = stmt else { return };
86 semicolon_outside_block(cx, block, expr, span);
89 kind: ExprKind::Block(block @ Block { expr: Some(tail), .. }, _),
91 }) if !block.span.from_expansion() => semicolon_inside_block(cx, block, tail, stmt.span),
97 fn semicolon_inside_block(cx: &LateContext<'_>, block: &Block<'_>, tail: &Expr<'_>, semi_span: Span) {
98 let insert_span = tail.span.source_callsite().shrink_to_hi();
99 let remove_span = semi_span.with_lo(block.span.hi());
103 SEMICOLON_INSIDE_BLOCK,
105 "consider moving the `;` inside the block for consistent formatting",
107 multispan_sugg_with_applicability(
110 Applicability::MachineApplicable,
111 [(remove_span, String::new()), (insert_span, ";".to_owned())],
117 fn semicolon_outside_block(cx: &LateContext<'_>, block: &Block<'_>, tail_stmt_expr: &Expr<'_>, semi_span: Span) {
118 let insert_span = block.span.with_lo(block.span.hi());
119 // account for macro calls
120 let semi_span = cx.sess().source_map().stmt_span(semi_span, block.span);
121 let remove_span = semi_span.with_lo(tail_stmt_expr.span.source_callsite().hi());
125 SEMICOLON_OUTSIDE_BLOCK,
127 "consider moving the `;` outside the block for consistent formatting",
129 multispan_sugg_with_applicability(
132 Applicability::MachineApplicable,
133 [(remove_span, String::new()), (insert_span, ";".to_owned())],