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

pull/4884/head
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 has_val bool
mod string mod string
len_expr Expr len_expr Expr
cap_expr Expr
default_expr Expr
has_len bool has_len bool
has_cap bool has_cap bool
cap_expr Expr has_default bool
pub mut: pub mut:
is_interface bool // array of interfaces e.g. `[]Animal` `[Dog{}, Cat{}]` is_interface bool // array of interfaces e.g. `[]Animal` `[Dog{}, Cat{}]`
interface_types []table.Type // [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('map[${mk}]${mv}')
f.write('{') f.write('{')
if it.has_len {
f.write('len: ')
f.expr(it.len_expr)
}
if it.has_cap { if it.has_cap {
f.write('cap: ') f.write('cap: ')
f.expr(it.cap_expr) f.expr(it.cap_expr)
} }
if it.has_default {
f.write('default: ')
f.expr(it.default_expr)
}
f.write('}') f.write('}')
return return
} }
f.write(f.type_to_str(it.typ)) f.write(f.type_to_str(it.typ))
f.write('{') 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 { if it.has_cap {
f.write('cap: ') f.write('cap: ')
f.expr(it.cap_expr) 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('}') f.write('}')
return return

View File

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

View File

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