From 3f1c6019bb80382b07b876014c7f5257e10e0a0e Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 16 Sep 2023 12:37:57 +0800 Subject: [PATCH] ast, fmt: fix formatting type decl with anon struct (#19356) --- vlib/v/ast/ast.v | 10 +++++----- vlib/v/fmt/fmt.v | 11 +++++++++++ .../fmt/tests/type_decl_with_anon_struct_keep.vv | 15 +++++++++++++++ 3 files changed, 31 insertions(+), 5 deletions(-) create mode 100644 vlib/v/fmt/tests/type_decl_with_anon_struct_keep.vv diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 2fddcef480d21e..b9d36b557bce12 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -379,11 +379,11 @@ pub: generic_types []Type is_pub bool // _pos fields for vfmt - mut_pos int // mut: - pub_pos int // pub: - pub_mut_pos int // pub mut: - global_pos int // __global: - module_pos int // module: + mut_pos int = -1 // mut: + pub_pos int = -1 // pub: + pub_mut_pos int = -1 // pub mut: + global_pos int = -1 // __global: + module_pos int = -1 // module: language Language is_union bool attrs []Attr diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 4b15f48fa3270d..549e006a7d12ae 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -1502,6 +1502,17 @@ pub fn (mut f Fmt) alias_type_decl(node ast.AliasTypeDecl) { if node.is_pub { f.write('pub ') } + // aliases of anon struct: `type foo = struct {}` + sym := f.table.sym(node.parent_type) + if sym.info is ast.Struct { + if sym.info.is_anon { + f.write('type ${node.name} = ') + f.write_anon_struct_field_decl(node.parent_type, ast.StructDecl{ fields: sym.info.fields }) + f.comments(node.comments, has_nl: false) + f.mark_types_import_as_used(node.parent_type) + return + } + } ptype := f.table.type_to_str_using_aliases(node.parent_type, f.mod2alias) f.write('type ${node.name} = ${ptype}') diff --git a/vlib/v/fmt/tests/type_decl_with_anon_struct_keep.vv b/vlib/v/fmt/tests/type_decl_with_anon_struct_keep.vv new file mode 100644 index 00000000000000..f77285bb160338 --- /dev/null +++ b/vlib/v/fmt/tests/type_decl_with_anon_struct_keep.vv @@ -0,0 +1,15 @@ +pub type Unit1 = struct {} + +pub type Unit2 = struct { + name string + age int + } + +pub const unit1 = Unit1{} + +pub const unit2 = Unit2{'bob', 22} + +fn main() { + println(unit1) + println(unit2) +}