1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

parser/vfmt: handle array len and default in array init

This commit is contained in:
Alexander Medvednikov 2020-05-13 16:11:52 +02:00
parent 478ebed069
commit 33a9822548
4 changed files with 33 additions and 2 deletions

View File

@ -654,9 +654,11 @@ pub:
has_val bool
mod string
len_expr Expr
cap_expr Expr
default_expr Expr
has_len bool
has_cap bool
cap_expr Expr
has_default bool
pub mut:
is_interface bool // array of interfaces e.g. `[]Animal` `[Dog{}, Cat{}]`
interface_types []table.Type // [Dog, Cat]

View File

@ -970,18 +970,41 @@ fn (mut f Fmt) array_init(it ast.ArrayInit) {
}
f.write('map[${mk}]${mv}')
f.write('{')
if it.has_len {
f.write('len: ')
f.expr(it.len_expr)
}
if it.has_cap {
f.write('cap: ')
f.expr(it.cap_expr)
}
if it.has_default {
f.write('default: ')
f.expr(it.default_expr)
}
f.write('}')
return
}
f.write(f.type_to_str(it.typ))
f.write('{')
// TODO copypasta
if it.has_len {
f.write('len: ')
f.expr(it.len_expr)
if it.has_cap || it.has_default {
f.write(', ')
}
}
if it.has_cap {
f.write('cap: ')
f.expr(it.cap_expr)
if it.has_default {
f.write(', ')
}
}
if it.has_default {
f.write('default: ')
f.expr(it.default_expr)
}
f.write('}')
return

View File

@ -9,5 +9,6 @@ fn main() {
make_flag('darwin', '-framework', 'Cocoa'),
make_flag('windows', '-l', 'gdi32')
]
x := []int{len: 10, cap: 100, default: 1}
_ := expected_flags
}

View File

@ -72,8 +72,10 @@ fn (mut p Parser) array_init() ast.ArrayInit {
}
mut has_len := false
mut has_cap := false
mut has_default := false
mut len_expr := ast.Expr{}
mut cap_expr := ast.Expr{}
mut default_expr := ast.Expr{}
if p.tok.kind == .lcbr && exprs.len == 0 {
// `[]int{ len: 10, cap: 100}` syntax
p.next()
@ -90,7 +92,8 @@ fn (mut p Parser) array_init() ast.ArrayInit {
cap_expr = p.expr(0)
}
'default' {
p.expr(0)
has_default = true
default_expr = p.expr(0)
}
else {
p.error('wrong field `$key`, expecting `len`, `cap`, or `default`')
@ -118,7 +121,9 @@ fn (mut p Parser) array_init() ast.ArrayInit {
has_len: has_len
len_expr: len_expr
has_cap: has_cap
has_default: has_default
cap_expr: cap_expr
default_expr: default_expr
}
}