]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_lints/src/semicolon_if_nothing_returned.rs
Merge commit '3ae8faff4d46ad92f194c2a4b941c3152a701b31' into clippyup
[rust.git] / src / tools / clippy / clippy_lints / src / semicolon_if_nothing_returned.rs
1 use clippy_utils::diagnostics::span_lint_and_sugg;
2 use clippy_utils::source::snippet_with_macro_callsite;
3 use clippy_utils::{in_macro, sugg};
4 use if_chain::if_chain;
5 use rustc_errors::Applicability;
6 use rustc_hir::{Block, ExprKind};
7 use rustc_lint::{LateContext, LateLintPass};
8 use rustc_session::{declare_lint_pass, declare_tool_lint};
9
10 declare_clippy_lint! {
11     /// **What it does:** Looks for blocks of expressions and fires if the last expression returns
12     /// `()` but is not followed by a semicolon.
13     ///
14     /// **Why is this bad?** The semicolon might be optional but when extending the block with new
15     /// code, it doesn't require a change in previous last line.
16     ///
17     /// **Known problems:** None.
18     ///
19     /// **Example:**
20     ///
21     /// ```rust
22     /// fn main() {
23     ///     println!("Hello world")
24     /// }
25     /// ```
26     /// Use instead:
27     /// ```rust
28     /// fn main() {
29     ///     println!("Hello world");
30     /// }
31     /// ```
32     pub SEMICOLON_IF_NOTHING_RETURNED,
33     pedantic,
34     "add a semicolon if nothing is returned"
35 }
36
37 declare_lint_pass!(SemicolonIfNothingReturned => [SEMICOLON_IF_NOTHING_RETURNED]);
38
39 impl LateLintPass<'_> for SemicolonIfNothingReturned {
40     fn check_block(&mut self, cx: &LateContext<'tcx>, block: &'tcx Block<'tcx>) {
41         if_chain! {
42             if !in_macro(block.span);
43             if let Some(expr) = block.expr;
44             let t_expr = cx.typeck_results().expr_ty(expr);
45             if t_expr.is_unit();
46             if let snippet = snippet_with_macro_callsite(cx, expr.span, "}");
47             if !snippet.ends_with('}');
48             then {
49                 // filter out the desugared `for` loop
50                 if let ExprKind::DropTemps(..) = &expr.kind {
51                     return;
52                 }
53
54                 let sugg = sugg::Sugg::hir_with_macro_callsite(cx, expr, "..");
55                 let suggestion = format!("{0};", sugg);
56                 span_lint_and_sugg(
57                     cx,
58                     SEMICOLON_IF_NOTHING_RETURNED,
59                     expr.span.source_callsite(),
60                     "consider adding a `;` to the last statement for consistent formatting",
61                     "add a `;` here",
62                     suggestion,
63                     Applicability::MaybeIncorrect,
64                 );
65             }
66         }
67     }
68 }