From 393b46a6dd50f4d573961eb7abeed018da020aa3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20Kr=C3=BCger?= <45282134+UweKrueger@users.noreply.github.com> Date: Wed, 26 Aug 2020 06:41:51 +0200 Subject: [PATCH] channels: make `ch.len` and `ch.cap` available as properties (#6221) --- vlib/sync/channel_fill_test.v | 10 +++++----- vlib/v/checker/checker.v | 7 +++++-- vlib/v/gen/cgen.v | 8 +++++++- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/vlib/sync/channel_fill_test.v b/vlib/sync/channel_fill_test.v index 7252dfe0ab..cc68749810 100644 --- a/vlib/sync/channel_fill_test.v +++ b/vlib/sync/channel_fill_test.v @@ -5,18 +5,18 @@ const ( queue_fill = 763 ) -fn do_send(mut ch sync.Channel, fin sync.Semaphore) { +fn do_send(ch chan int, fin sync.Semaphore) { for i in 0 .. queue_fill { - ch.push(&i) + ch <- i } fin.post() } fn test_channel_len_cap() { - mut ch := sync.new_channel(queue_len) + ch := chan int{cap: queue_len} sem := sync.new_semaphore() - go do_send(mut ch, sem) + go do_send(ch, sem) sem.wait() assert ch.cap == queue_len - assert ch.len() == queue_fill + assert ch.len == queue_fill } diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index ff01021029..c97f29e3cd 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1470,8 +1470,8 @@ pub fn (mut c Checker) selector_expr(mut selector_expr ast.SelectorExpr) table.T sym := c.table.get_type_symbol(c.unwrap_generic(typ)) field_name := selector_expr.field_name // variadic - if typ.has_flag(.variadic) || sym.kind == .array_fixed { - if field_name == 'len' { + if typ.has_flag(.variadic) || sym.kind == .array_fixed || sym.kind == .chan { + if field_name == 'len' || (sym.kind == .chan && field_name == 'cap') { selector_expr.typ = table.int_type return table.int_type } @@ -3262,6 +3262,9 @@ pub fn (mut c Checker) chan_init(mut node ast.ChanInit) table.Type { if node.typ != 0 { info := c.table.get_type_symbol(node.typ).chan_info() node.elem_type = info.elem_type + if node.has_cap { + c.check_array_init_para_type('cap', node.cap_expr, node.pos) + } return node.typ } else { c.error('`chan` of unknown type', node.pos) diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index e3df4b88db..c95f303296 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -2107,8 +2107,14 @@ fn (mut g Gen) expr(node ast.Expr) { g.write('$info.size') return } + if sym.kind == .chan && node.field_name == 'len' { + g.write('sync__Channel_len(') + g.expr(node.expr) + g.write(')') + return + } g.expr(node.expr) - if node.expr_type.is_ptr() { + if node.expr_type.is_ptr() || sym.kind == .chan { g.write('->') } else { // g.write('. /*typ= $it.expr_type */') // ${g.typ(it.expr_type)} /')