1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: check unused last expression in if (fix #16084) (#16088)

This commit is contained in:
yuyi 2022-10-17 23:15:01 +08:00 committed by GitHub
parent 43b9a716c5
commit 556244576d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 41 additions and 3 deletions

View File

@ -55,9 +55,6 @@ fn open(f string) voidptr {
// locking it
fd := C.CreateFileW(f_wide, C.GENERIC_READ | C.GENERIC_WRITE, 0, 0, C.OPEN_ALWAYS,
C.FILE_ATTRIBUTE_NORMAL, 0)
if fd == C.INVALID_HANDLE_VALUE {
fd == -1
}
return fd
}

View File

@ -140,6 +140,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
c.stmts_ending_with_expression(branch.stmts)
} else {
c.stmts(branch.stmts)
c.check_non_expr_branch_last_stmt(branch.stmts)
}
} else if c.pref.output_cross_c {
mut is_freestanding_block := false
@ -156,6 +157,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
c.stmts_ending_with_expression(branch.stmts)
} else {
c.stmts(branch.stmts)
c.check_non_expr_branch_last_stmt(branch.stmts)
}
} else if !is_comptime_type_is_expr {
node.branches[i].stmts = []
@ -174,6 +176,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type {
c.stmts_ending_with_expression(branch.stmts)
} else {
c.stmts(branch.stmts)
c.check_non_expr_branch_last_stmt(branch.stmts)
}
c.smartcast_mut_pos = token.Pos{}
c.smartcast_cond_pos = token.Pos{}
@ -361,3 +364,16 @@ fn (mut c Checker) smartcast_if_conds(node ast.Expr, mut scope ast.Scope) {
c.smartcast_if_conds(node.expr, mut scope)
}
}
fn (mut c Checker) check_non_expr_branch_last_stmt(stmts []ast.Stmt) {
if stmts.len > 0 {
last_stmt := stmts.last()
if last_stmt is ast.ExprStmt {
if last_stmt.expr is ast.InfixExpr {
if last_stmt.expr.op !in [.left_shift, .right_shift, .unsigned_right_shift, .arrow] {
c.error('expression evaluated but not used', last_stmt.pos)
}
}
}
}
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/unused_last_expr_stmt_in_if.vv:16:5: error: expression evaluated but not used
14 | if a.mode == .zz {
15 | println('hello')
16 | a.mode == .yy
| ~~~~~~~~~~~
17 | }
18 | }

View File

@ -0,0 +1,18 @@
enum MyEnum {
xx
yy
zz
}
struct Abc {
mut:
mode MyEnum
}
fn main() {
a := Abc{}
if a.mode == .zz {
println('hello')
a.mode == .yy
}
}