From 0b843b801f030f8727c73c4d7b318525c3383f95 Mon Sep 17 00:00:00 2001 From: ChAoS_UnItY Date: Sat, 27 Aug 2022 14:00:14 +0800 Subject: [PATCH] checker: fix returning expression with void type (fix #15543) (#15554) --- vlib/builtin/cfns.c.v | 2 +- vlib/v/checker/if.v | 8 ++++++++ vlib/v/checker/tests/if_match_result.out | 15 +++++++++++---- vlib/v/checker/tests/if_match_result.vv | 4 ++-- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/vlib/builtin/cfns.c.v b/vlib/builtin/cfns.c.v index 50b37f08a..f287f4d71 100644 --- a/vlib/builtin/cfns.c.v +++ b/vlib/builtin/cfns.c.v @@ -321,7 +321,7 @@ fn C.WriteConsole() voidptr fn C.WriteFile() voidptr -fn C._wchdir(dirname &u16) +fn C._wchdir(dirname &u16) int fn C._wgetcwd(buffer &u16, maxlen int) int diff --git a/vlib/v/checker/if.v b/vlib/v/checker/if.v index f3287636b..af9a11da5 100644 --- a/vlib/v/checker/if.v +++ b/vlib/v/checker/if.v @@ -194,6 +194,14 @@ pub fn (mut c Checker) if_expr(mut node ast.IfExpr) ast.Type { node.typ = c.expected_type } } + if last_expr.typ == ast.void_type && !is_noreturn_callexpr(last_expr.expr) + && !c.skip_flags { + // cannot return void type and use it as expr in any circumstances + // (e.g. argument expression, variable declaration / assignment) + c.error('the final expression in `if` or `match`, must have a value of a non-void type', + last_expr.pos) + continue + } if !c.check_types(last_expr.typ, node.typ) { if node.typ == ast.void_type { // first branch of if expression diff --git a/vlib/v/checker/tests/if_match_result.out b/vlib/v/checker/tests/if_match_result.out index 53a154ea2..00c41ad1e 100644 --- a/vlib/v/checker/tests/if_match_result.out +++ b/vlib/v/checker/tests/if_match_result.out @@ -19,14 +19,21 @@ vlib/v/checker/tests/if_match_result.vv:7:3: error: `if` expression requires an 8 | } 9 | vlib/v/checker/tests/if_match_result.vv:11:3: error: assignment mismatch: 1 variable(s) 0 value(s) - 9 | + 9 | 10 | // void results 11 | _ = match 4 { | ^ - 12 | 1 {println('')} - 13 | else {exit(0)} + 12 | 1 { println('') } + 13 | else { exit(0) } +vlib/v/checker/tests/if_match_result.vv:16:2: error: the final expression in `if` or `match`, must have a value of a non-void type + 14 | } + 15 | _ = if true { + 16 | println('') + | ~~~~~~~~~~~ + 17 | } else { + 18 | exit(0) vlib/v/checker/tests/if_match_result.vv:15:3: error: assignment mismatch: 1 variable(s) 0 value(s) - 13 | else {exit(0)} + 13 | else { exit(0) } 14 | } 15 | _ = if true { | ^ diff --git a/vlib/v/checker/tests/if_match_result.vv b/vlib/v/checker/tests/if_match_result.vv index ad85b13bc..58cbda59c 100644 --- a/vlib/v/checker/tests/if_match_result.vv +++ b/vlib/v/checker/tests/if_match_result.vv @@ -9,8 +9,8 @@ _ = if true { // void results _ = match 4 { - 1 {println('')} - else {exit(0)} + 1 { println('') } + else { exit(0) } } _ = if true { println('') -- 2.30.2