From f55646746c6bc423084d1e2bfcfb8199247cd359 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Fri, 24 Jan 2020 18:57:32 +0100 Subject: [PATCH] handle empty config structs --- vlib/compiler/expression.v | 2 +- vlib/compiler/gen_c.v | 9 +++++++++ vlib/compiler/tests/struct_test.v | 15 +++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/vlib/compiler/expression.v b/vlib/compiler/expression.v index f1a41db9d6..bdf423678d 100644 --- a/vlib/compiler/expression.v +++ b/vlib/compiler/expression.v @@ -903,7 +903,7 @@ fn (p mut Parser) factor() string { return p.map_init() } peek2 := p.tokens[p.token_idx + 1] - if p.peek() == .name && peek2.tok == .colon { + if p.peek() == .rcbr || (p.peek() == .name && peek2.tok == .colon) { if !p.expected_type.ends_with('Config') { p.error('short struct initialization syntax only works with structs that end with `Config`') } diff --git a/vlib/compiler/gen_c.v b/vlib/compiler/gen_c.v index 901e0d3698..ebe0a68c6a 100644 --- a/vlib/compiler/gen_c.v +++ b/vlib/compiler/gen_c.v @@ -493,10 +493,19 @@ fn (p mut Parser) gen_struct_init(typ string, t &Type) bool { if typ == 'tm' { p.cgen.lines[p.cgen.lines.len - 1] = '' } + mut is_config := false if p.tok != .lcbr { p.next() + } else { + is_config = true } p.check(.lcbr) + // Handle empty config ({}) + if is_config && p.tok == .rcbr { + p.check(.rcbr) + p.gen('($typ) {}') + return true + } ptr := typ.contains('*') // `user := User{foo:bar}` => `User user = (User){ .foo = bar}` if !ptr { diff --git a/vlib/compiler/tests/struct_test.v b/vlib/compiler/tests/struct_test.v index 1654a64094..879e8c2f86 100644 --- a/vlib/compiler/tests/struct_test.v +++ b/vlib/compiler/tests/struct_test.v @@ -194,3 +194,18 @@ fn test_fixed_field() { } */ + +struct Config { + n int + def int = 10 +} + +fn foo_config(c Config) { +} + +fn test_config() { + foo_config({n: 10, def: 20}) + foo_config({}) +} + +