From 5bcc04e66a3f2697adc4da3e7d792e4ab6ea5f2c Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Thu, 4 May 2023 23:53:34 +0530 Subject: [PATCH] checker: disallow `_ = <- quit` (#18104) --- vlib/v/checker/checker.v | 6 +++ .../blank_ident_select_branch_send_err.out | 7 ++++ .../blank_ident_select_branch_send_err.vv | 39 +++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 vlib/v/checker/tests/blank_ident_select_branch_send_err.out create mode 100644 vlib/v/checker/tests/blank_ident_select_branch_send_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index a65b8a2257..2bbbbf3603 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -3609,6 +3609,12 @@ fn (mut c Checker) select_expr(mut node ast.SelectExpr) ast.Type { c.error('`<-` receive expression expected', branch.stmt.right[0].pos()) } } + if mut branch.stmt.left[0] is ast.Ident { + ident := branch.stmt.left[0] as ast.Ident + if ident.kind == .blank_ident && branch.stmt.op != .decl_assign { + c.error('cannot send on `_`, use `_ := <- quit` instead', branch.stmt.left[0].pos()) + } + } } else { if !branch.is_else { diff --git a/vlib/v/checker/tests/blank_ident_select_branch_send_err.out b/vlib/v/checker/tests/blank_ident_select_branch_send_err.out new file mode 100644 index 0000000000..b2cd5ffb70 --- /dev/null +++ b/vlib/v/checker/tests/blank_ident_select_branch_send_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/blank_ident_select_branch_send_err.vv:13:4: error: cannot send on `_`, use `_ := <- quit` instead + 11 | x, y = y, x + y + 12 | } + 13 | _ = <-quit { + | ^ + 14 | println('quit') + 15 | return diff --git a/vlib/v/checker/tests/blank_ident_select_branch_send_err.vv b/vlib/v/checker/tests/blank_ident_select_branch_send_err.vv new file mode 100644 index 0000000000..1977d09fda --- /dev/null +++ b/vlib/v/checker/tests/blank_ident_select_branch_send_err.vv @@ -0,0 +1,39 @@ +import time + +fn fibonacci(c chan int, quit chan int) { + println('fibonacci') + mut x, mut y := 0, 1 + + for { + select { + c <- x { + println('send') + x, y = y, x + y + } + _ = <-quit { + println('quit') + return + } + 2 * time.second { + println('timeout') + return + } + } + } +} + +fn main() { + ch := chan int{} + quit := chan int{} + + spawn fn [ch, quit] () { + for _ in 0 .. 5 { + println('pop') + println(<-ch) + } + println('quit') + quit <- 0 + }() + + fibonacci(ch, quit) +}