From 35cbca96e1bef5d296bb74d30c99e9755528d1b5 Mon Sep 17 00:00:00 2001 From: spaceface777 Date: Mon, 31 Aug 2020 23:15:40 +0200 Subject: [PATCH] checker: implement `[required]` struct field attribute (#6276) --- examples/2048/main.v | 2 +- examples/sokol/particles/main.v | 2 +- vlib/v/checker/checker.v | 14 ++++++++++++++ vlib/v/checker/tests/struct_required_field.out | 7 +++++++ vlib/v/checker/tests/struct_required_field.vv | 16 ++++++++++++++++ 5 files changed, 39 insertions(+), 2 deletions(-) create mode 100644 vlib/v/checker/tests/struct_required_field.out create mode 100644 vlib/v/checker/tests/struct_required_field.vv diff --git a/examples/2048/main.v b/examples/2048/main.v index df9cc75098..90565f4d2f 100644 --- a/examples/2048/main.v +++ b/examples/2048/main.v @@ -180,7 +180,7 @@ fn (t TileLine) to_left() TileLine { fn (b Board) to_left() Board { mut res := b for y := 0; y < 4; y++ { - mut hline := TileLine{y} + mut hline := TileLine{ypos: y} for x := 0; x < 4; x++ { hline.field[x] = b.field[y][x] } diff --git a/examples/sokol/particles/main.v b/examples/sokol/particles/main.v index a308c6e3af..b86d5ac169 100644 --- a/examples/sokol/particles/main.v +++ b/examples/sokol/particles/main.v @@ -36,7 +36,7 @@ mut: fn (mut a App) init() { a.frame = 0 a.last = time.ticks() - a.ps = particle.System{a.width, a.height} + a.ps = particle.System{width: a.width, height: a.height} a.ps.init(particle.SystemConfig{ pool: 20000 }) diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 281dee302e..f2d0ddad80 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -480,6 +480,20 @@ pub fn (mut c Checker) struct_init(mut struct_init ast.StructInit) table.Type { c.warn('reference field `${type_sym.source_name}.$field.name` must be initialized', struct_init.pos) } + // Check for `[required]` struct attr + if field.attrs.contains('required') && !struct_init.is_short { + mut found := false + for init_field in struct_init.fields { + if field.name == init_field.name { + found = true + break + } + } + if !found { + c.error('field `${type_sym.source_name}.$field.name` is required', + struct_init.pos) + } + } } } else {} diff --git a/vlib/v/checker/tests/struct_required_field.out b/vlib/v/checker/tests/struct_required_field.out new file mode 100644 index 0000000000..6294ee4b61 --- /dev/null +++ b/vlib/v/checker/tests/struct_required_field.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/struct_required_field.vv:12:6: error: field `Abc.f3` is required + 10 | f3: 789 + 11 | } + 12 | _ = Abc{ + | ~~~~ + 13 | f1: 123 + 14 | f2: 789 diff --git a/vlib/v/checker/tests/struct_required_field.vv b/vlib/v/checker/tests/struct_required_field.vv new file mode 100644 index 0000000000..85b2a4d8f7 --- /dev/null +++ b/vlib/v/checker/tests/struct_required_field.vv @@ -0,0 +1,16 @@ +struct Abc { + f1 int [required] + f2 int + f3 int [required] +} + +fn main() { + _ = Abc{ + f1: 123 + f3: 789 + } + _ = Abc{ + f1: 123 + f2: 789 + } +}