channels: make `ch.len` and `ch.cap` available as properties (#6221)

pull/6228/head
Uwe Krüger 2020-08-26 06:41:51 +02:00 committed by GitHub
parent 7879510ef5
commit 393b46a6dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 17 additions and 8 deletions

View File

@ -5,18 +5,18 @@ const (
queue_fill = 763 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 { for i in 0 .. queue_fill {
ch.push(&i) ch <- i
} }
fin.post() fin.post()
} }
fn test_channel_len_cap() { fn test_channel_len_cap() {
mut ch := sync.new_channel<int>(queue_len) ch := chan int{cap: queue_len}
sem := sync.new_semaphore() sem := sync.new_semaphore()
go do_send(mut ch, sem) go do_send(ch, sem)
sem.wait() sem.wait()
assert ch.cap == queue_len assert ch.cap == queue_len
assert ch.len() == queue_fill assert ch.len == queue_fill
} }

View File

@ -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)) sym := c.table.get_type_symbol(c.unwrap_generic(typ))
field_name := selector_expr.field_name field_name := selector_expr.field_name
// variadic // variadic
if typ.has_flag(.variadic) || sym.kind == .array_fixed { if typ.has_flag(.variadic) || sym.kind == .array_fixed || sym.kind == .chan {
if field_name == 'len' { if field_name == 'len' || (sym.kind == .chan && field_name == 'cap') {
selector_expr.typ = table.int_type selector_expr.typ = table.int_type
return 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 { if node.typ != 0 {
info := c.table.get_type_symbol(node.typ).chan_info() info := c.table.get_type_symbol(node.typ).chan_info()
node.elem_type = info.elem_type 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 return node.typ
} else { } else {
c.error('`chan` of unknown type', node.pos) c.error('`chan` of unknown type', node.pos)

View File

@ -2107,8 +2107,14 @@ fn (mut g Gen) expr(node ast.Expr) {
g.write('$info.size') g.write('$info.size')
return return
} }
if sym.kind == .chan && node.field_name == 'len' {
g.write('sync__Channel_len(')
g.expr(node.expr) g.expr(node.expr)
if node.expr_type.is_ptr() { g.write(')')
return
}
g.expr(node.expr)
if node.expr_type.is_ptr() || sym.kind == .chan {
g.write('->') g.write('->')
} else { } else {
// g.write('. /*typ= $it.expr_type */') // ${g.typ(it.expr_type)} /') // g.write('. /*typ= $it.expr_type */') // ${g.typ(it.expr_type)} /')