3 use syntax::ext::quote::rt::Span;
4 use utils::span_note_and_lint;
6 /// **What it does:** Checks for
7 /// - () being assigned to a variable
8 /// - () being passed to a function
10 /// **Why is this bad?** It is extremely unlikely that a user intended to
11 /// assign '()' to valiable. Instead,
12 /// Unit is what a block evaluates to when it returns nothing. This is
13 /// typically caused by a trailing
14 /// unintended semicolon.
16 /// **Known problems:** None.
19 /// * `let x = {"foo" ;}` when the user almost certainly intended `let x
24 "unintended assignment or use of a unit typed value"
27 #[derive(Copy, Clone)]
30 impl LintPass for UnitExpr {
31 fn get_lints(&self) -> LintArray {
32 lint_array!(UNIT_EXPR)
36 impl EarlyLintPass for UnitExpr {
37 fn check_expr(&mut self, cx: &EarlyContext, expr: &Expr) {
38 if let ExprKind::Assign(ref _left, ref right) = expr.node {
39 if let Some(span) = is_unit_expr(right) {
44 "This expression evaluates to the Unit type ()",
46 "Consider removing the trailing semicolon",
50 if let ExprKind::MethodCall(ref _left, ref args) = expr.node {
52 if let Some(span) = is_unit_expr(arg) {
57 "This expression evaluates to the Unit type ()",
59 "Consider removing the trailing semicolon",
64 if let ExprKind::Call(_, ref args) = expr.node {
66 if let Some(span) = is_unit_expr(arg) {
71 "This expression evaluates to the Unit type ()",
73 "Consider removing the trailing semicolon",
80 fn check_stmt(&mut self, cx: &EarlyContext, stmt: &Stmt) {
81 if let StmtKind::Local(ref local) = stmt.node {
82 if local.pat.node == PatKind::Wild {
85 if let Some(ref expr) = local.init {
86 if let Some(span) = is_unit_expr(expr) {
91 "This expression evaluates to the Unit type ()",
93 "Consider removing the trailing semicolon",
101 fn is_unit_expr(expr: &Expr) -> Option<Span> {
103 ExprKind::Block(ref block) => if check_last_stmt_in_block(block) {
104 Some(block.stmts[block.stmts.len() - 1].span)
108 ExprKind::If(_, ref then, ref else_) => {
109 let check_then = check_last_stmt_in_block(then);
110 if let Some(ref else_) = *else_ {
111 let check_else = is_unit_expr(else_);
112 if let Some(ref expr_else) = check_else {
113 return Some(*expr_else);
122 ExprKind::Match(ref _pattern, ref arms) => {
124 if let Some(expr) = is_unit_expr(&arm.body) {
134 fn check_last_stmt_in_block(block: &Block) -> bool {
135 let final_stmt = &block.stmts[block.stmts.len() - 1];
138 // Made a choice here to risk false positives on divergent macro invocations
140 match final_stmt.node {
141 StmtKind::Expr(_) => false,
142 StmtKind::Semi(ref expr) => match expr.node {
143 ExprKind::Break(_, _) | ExprKind::Continue(_) | ExprKind::Ret(_) => false,