Skip to content

Commit

Permalink
fmt: fix anonymous struct in parameter with invalid type name. fix #1…
Browse files Browse the repository at this point in the history
  • Loading branch information
shove70 committed Sep 9, 2022
1 parent 6db5781 commit ca36284
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 18 deletions.
47 changes: 31 additions & 16 deletions vlib/v/ast/str.v
Expand Up @@ -137,26 +137,41 @@ fn stringify_fn_after_name(node &FnDecl, mut f strings.Builder, t &Table, cur_mo
f.write_string(arg.typ.share().str() + ' ')
}
f.write_string(arg.name)
mut s := t.type_to_str(arg.typ.clear_flag(.shared_f))
if arg.is_mut {
arg_sym := t.sym(arg.typ)
if s.starts_with('&') && ((!arg_sym.is_number() && arg_sym.kind != .bool)
|| node.language != .v) {
s = s[1..]
arg_sym := t.sym(arg.typ)
if arg_sym.kind == .struct_ && (arg_sym.info as Struct).is_anon {
f.write_string(' struct {')
struct_ := arg_sym.info as Struct
for field in struct_.fields {
f.write_string(' $field.name ${t.type_to_str(field.typ)}')
if field.has_default_expr {
f.write_string(' = $field.default_expr')
}
}
}
s = util.no_cur_mod(s, cur_mod)
for mod, alias in m2a {
s = s.replace(mod, alias)
}
if should_add_type {
if !is_type_only {
if struct_.fields.len > 0 {
f.write_string(' ')
}
if node.is_variadic && is_last_arg {
f.write_string('...')
f.write_string('}')
} else {
mut s := t.type_to_str(arg.typ.clear_flag(.shared_f))
if arg.is_mut {
if s.starts_with('&') && ((!arg_sym.is_number() && arg_sym.kind != .bool)
|| node.language != .v) {
s = s[1..]
}
}
s = util.no_cur_mod(s, cur_mod)
for mod, alias in m2a {
s = s.replace(mod, alias)
}
if should_add_type {
if !is_type_only {
f.write_string(' ')
}
if node.is_variadic && is_last_arg {
f.write_string('...')
}
f.write_string(s)
}
f.write_string(s)
}
if !is_last_arg {
f.write_string(', ')
Expand Down
4 changes: 2 additions & 2 deletions vlib/v/fmt/struct.v
Expand Up @@ -253,7 +253,7 @@ pub fn (mut f Fmt) struct_init(node ast.StructInit) {
if node.pos.line_nr < node.pos.last_line || node.pre_comments.len > 0 {
single_line_fields = false
}
if !use_short_args {
if !use_short_args || node.is_anon {
f.write('$name{')
f.mark_import_as_used(name)
if single_line_fields {
Expand Down Expand Up @@ -315,7 +315,7 @@ pub fn (mut f Fmt) struct_init(node ast.StructInit) {
if !single_line_fields {
f.indent--
}
if !use_short_args {
if !use_short_args || node.is_anon {
if single_line_fields {
f.write(' ')
}
Expand Down
9 changes: 9 additions & 0 deletions vlib/v/fmt/tests/anon_struct_as_param_expected.vv
@@ -0,0 +1,9 @@
fn func(arg struct { foo string = 'bar' }) {
println(arg.foo)
}

fn main() {
func(struct {
foo: 'foo'
})
}
8 changes: 8 additions & 0 deletions vlib/v/fmt/tests/anon_struct_as_param_input.vv
@@ -0,0 +1,8 @@
fn func(arg struct{foo string='bar'}) {
println(arg.foo)
}

fn main() {
func(struct {foo: 'foo'
})
}

0 comments on commit ca36284

Please sign in to comment.