From e4f15605c07b90ff07343902c46f20a804996e89 Mon Sep 17 00:00:00 2001 From: zakuro Date: Sun, 14 Feb 2021 15:33:24 +0900 Subject: [PATCH] checker: reject void type condition (#8737) --- vlib/builtin/cfns.c.v | 2 +- vlib/v/checker/checker.v | 5 +---- vlib/v/checker/tests/if_non_bool_cond.out | 20 ++++++++++++++++++++ vlib/v/checker/tests/if_non_bool_cond.vv | 13 +++++++++++++ 4 files changed, 35 insertions(+), 5 deletions(-) create mode 100644 vlib/v/checker/tests/if_non_bool_cond.out create mode 100644 vlib/v/checker/tests/if_non_bool_cond.vv diff --git a/vlib/builtin/cfns.c.v b/vlib/builtin/cfns.c.v index 75fdbb8bac..655c1f6843 100644 --- a/vlib/builtin/cfns.c.v +++ b/vlib/builtin/cfns.c.v @@ -213,7 +213,7 @@ fn C.RemoveDirectory() int fn C.GetStdHandle(u32) voidptr // fn C.SetConsoleMode() -fn C.SetConsoleMode(voidptr, u32) +fn C.SetConsoleMode(voidptr, u32) int // fn C.GetConsoleMode() int fn C.GetConsoleMode(voidptr, &u32) int diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index e9a3ea6c81..f1be4029d1 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -4755,10 +4755,7 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) table.Type { // check condition type is boolean c.expected_type = table.bool_type cond_typ := c.expr(branch.cond) - if cond_typ.idx() !in [table.bool_type_idx, table.void_type_idx] - && !c.pref.translated { - // void types are skipped, because they mean the var was initialized incorrectly - // (via missing function etc) + if cond_typ.idx() != table.bool_type_idx && !c.pref.translated { typ_sym := c.table.get_type_symbol(cond_typ) c.error('non-bool type `$typ_sym.name` used as if condition', branch.pos) } diff --git a/vlib/v/checker/tests/if_non_bool_cond.out b/vlib/v/checker/tests/if_non_bool_cond.out new file mode 100644 index 0000000000..ecb8ff6dcd --- /dev/null +++ b/vlib/v/checker/tests/if_non_bool_cond.out @@ -0,0 +1,20 @@ +vlib/v/checker/tests/if_non_bool_cond.vv:2:2: error: non-bool type `string` used as if condition + 1 | fn main() { + 2 | if '10' { + | ~~~~~~~ + 3 | println('10') + 4 | } +vlib/v/checker/tests/if_non_bool_cond.vv:6:2: error: non-bool type `int literal` used as if condition + 4 | } + 5 | + 6 | if 5 { + | ~~~~ + 7 | println(5) + 8 | } +vlib/v/checker/tests/if_non_bool_cond.vv:10:2: error: non-bool type `void` used as if condition + 8 | } + 9 | + 10 | if println('v') { + | ~~~~~~~~~~~~~~~ + 11 | println('println') + 12 | } diff --git a/vlib/v/checker/tests/if_non_bool_cond.vv b/vlib/v/checker/tests/if_non_bool_cond.vv new file mode 100644 index 0000000000..626aafe9a9 --- /dev/null +++ b/vlib/v/checker/tests/if_non_bool_cond.vv @@ -0,0 +1,13 @@ +fn main() { + if '10' { + println('10') + } + + if 5 { + println(5) + } + + if println('v') { + println('println') + } +}