From 03b7c76b38f680acf6821a1d56ddbca0b23cc787 Mon Sep 17 00:00:00 2001 From: yuyi Date: Tue, 26 Jul 2022 14:38:50 +0800 Subject: [PATCH] cgen: optimize auto_str_methods of [str:skip] fields (#15227) --- vlib/v/gen/c/auto_str_methods.v | 23 +++++++++---------- .../inout/printing_struct_with_skip_fields.vv | 4 ++-- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/vlib/v/gen/c/auto_str_methods.v b/vlib/v/gen/c/auto_str_methods.v index 2278c29ee0..f28076955c 100644 --- a/vlib/v/gen/c/auto_str_methods.v +++ b/vlib/v/gen/c/auto_str_methods.v @@ -843,25 +843,23 @@ fn (mut g Gen) gen_str_for_struct(info ast.Struct, styp string, str_fn_name stri fn_builder.writeln('\treturn res;') fn_builder.writeln('}') } - // find skip fields - mut skip_field_count := 0 - for field in info.fields { + // find `[str: skip]` fields + mut field_skips := []int{} + for i, field in info.fields { if attr := field.attrs.find_first('str') { if attr.arg == 'skip' { - skip_field_count++ + field_skips << i } } } - fn_body.writeln('\tstring res = str_intp( ${(info.fields.len - skip_field_count) * 4 + 3}, _MOV((StrIntpData[]){') + fn_body.writeln('\tstring res = str_intp( ${(info.fields.len - field_skips.len) * 4 + 3}, _MOV((StrIntpData[]){') fn_body.writeln('\t\t{_SLIT("$clean_struct_v_type_name{\\n"), 0, {.d_c=0}},') + mut is_first := true for i, field in info.fields { // Skip `str:skip` fields - if attr := field.attrs.find_first('str') { - if attr.arg == 'skip' { - continue - } + if i in field_skips { + continue } - ftyp_noshared := if field.typ.has_flag(.shared_f) { field.typ.deref().clear_flag(.shared_f) } else { @@ -885,9 +883,10 @@ fn (mut g Gen) gen_str_for_struct(info ast.Struct, styp string, str_fn_name stri prefix = 'C' } - // first fields doesn't need \n - if i == 0 { + if is_first { + // first field doesn't need \n fn_body.write_string('\t\t{_SLIT0, $c.si_s_code, {.d_s=indents}}, {_SLIT(" $field.name: $ptr_amp$prefix"), 0, {.d_c=0}}, ') + is_first = false } else { fn_body.write_string('\t\t{_SLIT("\\n"), $c.si_s_code, {.d_s=indents}}, {_SLIT(" $field.name: $ptr_amp$prefix"), 0, {.d_c=0}}, ') } diff --git a/vlib/v/tests/inout/printing_struct_with_skip_fields.vv b/vlib/v/tests/inout/printing_struct_with_skip_fields.vv index 097458e88c..f285067907 100644 --- a/vlib/v/tests/inout/printing_struct_with_skip_fields.vv +++ b/vlib/v/tests/inout/printing_struct_with_skip_fields.vv @@ -1,9 +1,9 @@ struct Foo { - name string age int [str: skip] + name string } fn main() { - x := Foo{'Peter', 25} + x := Foo{25, 'Peter'} println(x) }