From 5cd2dffafb9ef4d6214de9d59ead14d30bef1335 Mon Sep 17 00:00:00 2001 From: Lukas Neubert Date: Mon, 21 Dec 2020 21:05:50 +0100 Subject: [PATCH] checker: error, when same type is used multiple times in a sum type (#7432) --- vlib/v/checker/checker.v | 7 ++++++- vlib/v/checker/tests/sum_type_multiple_type_define.out | 5 +++++ vlib/v/checker/tests/sum_type_multiple_type_define.vv | 3 +++ 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 vlib/v/checker/tests/sum_type_multiple_type_define.out create mode 100644 vlib/v/checker/tests/sum_type_multiple_type_define.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 34864061b4..ff7bf3c5f2 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -338,16 +338,21 @@ pub fn (mut c Checker) type_decl(node ast.TypeDecl) { } ast.SumTypeDecl { c.check_valid_pascal_case(node.name, 'sum type', node.pos) + mut names_used := []string{} for variant in node.variants { if variant.typ.is_ptr() { c.error('sum type cannot hold a reference type', variant.pos) } mut sym := c.table.get_type_symbol(variant.typ) - if sym.kind == .placeholder { + if sym.name in names_used { + c.error('sum type $node.name cannot hold the type `$sym.name` more than once', + variant.pos) + } else if sym.kind == .placeholder { c.error("type `$sym.name` doesn't exist", node.pos) } else if sym.kind == .interface_ { c.error('sum type cannot hold an interface', node.pos) } + names_used << sym.name } } } diff --git a/vlib/v/checker/tests/sum_type_multiple_type_define.out b/vlib/v/checker/tests/sum_type_multiple_type_define.out new file mode 100644 index 0000000000..7052f3ba53 --- /dev/null +++ b/vlib/v/checker/tests/sum_type_multiple_type_define.out @@ -0,0 +1,5 @@ +vlib/v/checker/tests/sum_type_multiple_type_define.vv:3:22: error: sum type FooType cannot hold the type `Foo` more than once + 1 | struct Foo {} + 2 | + 3 | type FooType = Foo | Foo + | ~~~ diff --git a/vlib/v/checker/tests/sum_type_multiple_type_define.vv b/vlib/v/checker/tests/sum_type_multiple_type_define.vv new file mode 100644 index 0000000000..7ec43d012c --- /dev/null +++ b/vlib/v/checker/tests/sum_type_multiple_type_define.vv @@ -0,0 +1,3 @@ +struct Foo {} + +type FooType = Foo | Foo