From 3eeef6203e82357206320937767b2426617c55cd Mon Sep 17 00:00:00 2001 From: yuyi Date: Sat, 9 May 2020 22:55:38 +0800 Subject: [PATCH] checker: check for map_init key duplicate --- vlib/v/checker/checker.v | 7 +++++++ vlib/v/checker/tests/map_init_key_duplicate_err.out | 7 +++++++ vlib/v/checker/tests/map_init_key_duplicate_err.vv | 8 ++++++++ 3 files changed, 22 insertions(+) create mode 100644 vlib/v/checker/tests/map_init_key_duplicate_err.out create mode 100644 vlib/v/checker/tests/map_init_key_duplicate_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 8926193377..aec91a1fec 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -2139,6 +2139,13 @@ pub fn (mut c Checker) map_init(node mut ast.MapInit) table.Type { key0_type := c.expr(node.keys[0]) val0_type := c.expr(node.vals[0]) for i, key in node.keys { + key_i := key as ast.StringLiteral + for j in 0..i { + key_j := node.keys[j] as ast.StringLiteral + if key_i.val == key_j.val { + c.error('duplicate key "$key_i.val" in map literal', key.position()) + } + } if i == 0 { continue } diff --git a/vlib/v/checker/tests/map_init_key_duplicate_err.out b/vlib/v/checker/tests/map_init_key_duplicate_err.out new file mode 100644 index 0000000000..01b7bd570e --- /dev/null +++ b/vlib/v/checker/tests/map_init_key_duplicate_err.out @@ -0,0 +1,7 @@ +vlib/v/checker/tests/map_init_key_duplicate_err.v:5:3: error: duplicate key "foo" in map literal + 3 | 'foo': 'bar' + 4 | 'abc': 'abc' + 5 | 'foo': 'bar' + | ~~~~~ + 6 | } + 7 | println(a) diff --git a/vlib/v/checker/tests/map_init_key_duplicate_err.vv b/vlib/v/checker/tests/map_init_key_duplicate_err.vv new file mode 100644 index 0000000000..497c61a46b --- /dev/null +++ b/vlib/v/checker/tests/map_init_key_duplicate_err.vv @@ -0,0 +1,8 @@ +fn main() { + a := { + 'foo': 'bar' + 'abc': 'abc' + 'foo': 'bar' + } + println(a) +}