From a4ab7b14c1deff981efa3e7d4d1f4f3468af2ff2 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sun, 24 Nov 2019 15:56:14 +0300 Subject: [PATCH] wrap up struct default vals + tests --- vlib/compiler/struct.v | 19 ++++++++++++++++--- vlib/compiler/table.v | 3 +++ vlib/compiler/tests/struct_test.v | 16 ++++++++++++++++ 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/vlib/compiler/struct.v b/vlib/compiler/struct.v index 4c1afd14a2..436197383c 100644 --- a/vlib/compiler/struct.v +++ b/vlib/compiler/struct.v @@ -214,7 +214,10 @@ fn (p mut Parser) struct_decl() { if def_val_type != field_type { p.error('expected `$field_type` but got `$def_val_type`') } - p.table.add_default_val(i, typ.name, expr) + //println('pass=$p.pass $typ.name ADDING field=$field_name "$def_val_type" "$expr"') + if !p.first_pass() { + p.table.add_default_val(i, typ.name, expr) + } } // [ATTR] mut attr := '' @@ -303,7 +306,11 @@ fn (p mut Parser) struct_init(typ string) string { } // Zero values: init all fields (ints to 0, strings to '' etc) for i, field in t.fields { - sanitized_name := if typ != 'Option' { p.table.var_cgen_name( field.name ) } else { field.name } + sanitized_name := if typ != 'Option' { + p.table.var_cgen_name( field.name ) + } else { + field.name + } // println('### field.name') // Skip if this field has already been assigned to if sanitized_name in inited_fields { @@ -324,7 +331,13 @@ fn (p mut Parser) struct_init(typ string) string { did_gen_something = true continue } - def_val := type_default(field_typ) + // Did the user provide a default value for this struct field? + // Use it. Otherwise zero it. + def_val := if t.default_vals.len > i && t.default_vals[i] != '' { + t.default_vals[i] + } else { + type_default(field_typ) + } if def_val != '' && def_val != '{0}' { p.gen_struct_field_init(sanitized_name) p.gen(def_val) diff --git a/vlib/compiler/table.v b/vlib/compiler/table.v index 5d41bc146d..405bad8070 100644 --- a/vlib/compiler/table.v +++ b/vlib/compiler/table.v @@ -444,6 +444,9 @@ fn (table mut Table) add_field(type_name, field_name, field_type string, is_mut fn (table mut Table) add_default_val(idx int, type_name, val_expr string) { mut t := table.typesmap[type_name] + if t.default_vals.len == 0 { + t.default_vals = [''].repeat(t.fields.len) + } t.default_vals[idx] = val_expr table.typesmap[type_name] = t } diff --git a/vlib/compiler/tests/struct_test.v b/vlib/compiler/tests/struct_test.v index 75a9cf7e59..07021b0df1 100644 --- a/vlib/compiler/tests/struct_test.v +++ b/vlib/compiler/tests/struct_test.v @@ -118,3 +118,19 @@ fn test_mutable_fields() { u.name = 'Peter' assert u.name == 'Peter' } + + +struct Def { + a int + b int = 7 +} + +fn test_default_vals() { + d := Def{} + assert d.a == 0 + assert d.b == 7 + d2 := Def{10, 20} + assert d2.a == 10 + assert d2.b == 20 +} +