From 9f532f1ba9b967f9b8c526736ee99853a98732cf Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Tue, 13 Feb 2024 22:48:34 +0530 Subject: [PATCH] checker: disallow sum type holding alias ptrs (#20786) --- vlib/v/checker/checker.v | 9 +++++++-- vlib/v/checker/tests/sum_type_holding_alias_ptr_err.out | 9 +++++++++ vlib/v/checker/tests/sum_type_holding_alias_ptr_err.vv | 6 ++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 vlib/v/checker/tests/sum_type_holding_alias_ptr_err.out create mode 100644 vlib/v/checker/tests/sum_type_holding_alias_ptr_err.vv diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 2d4ef02d0..1230b6141 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -627,10 +627,15 @@ fn (mut c Checker) sum_type_decl(node ast.SumTypeDecl) { for variant in node.variants { c.ensure_type_exists(variant.typ, variant.pos) sym := c.table.sym(variant.typ) - if variant.typ.is_ptr() { + if variant.typ.is_ptr() || (sym.info is ast.Alias && sym.info.parent_type.is_ptr()) { variant_name := sym.name.all_after_last('.') lb, rb := if sym.kind == .struct_ { '{', '}' } else { '(', ')' } - c.add_error_detail('declare the sum type with non-reference types: `${node.name} = ${variant_name} | ...` + msg := if sym.info is ast.Alias && sym.info.parent_type.is_ptr() { + 'alias as non-reference type' + } else { + 'the sum type with non-reference types' + } + c.add_error_detail('declare ${msg}: `${node.name} = ${variant_name} | ...` and use a reference to the sum type instead: `var := &${node.name}(${variant_name}${lb}val${rb})`') c.error('sum type cannot hold a reference type', variant.pos) } diff --git a/vlib/v/checker/tests/sum_type_holding_alias_ptr_err.out b/vlib/v/checker/tests/sum_type_holding_alias_ptr_err.out new file mode 100644 index 000000000..dce526dd6 --- /dev/null +++ b/vlib/v/checker/tests/sum_type_holding_alias_ptr_err.out @@ -0,0 +1,9 @@ +vlib/v/checker/tests/sum_type_holding_alias_ptr_err.vv:3:12: error: sum type cannot hold a reference type + 1 | type Alias1 = &int + 2 | type Alias2 = &string + 3 | type Qwe = Alias1 | Alias2 + | ~~~~~~ + 4 | + 5 | fn main() { +Details: declare alias as non-reference type: `Qwe = Alias1 | ...` +and use a reference to the sum type instead: `var := &Qwe(Alias1(val))` diff --git a/vlib/v/checker/tests/sum_type_holding_alias_ptr_err.vv b/vlib/v/checker/tests/sum_type_holding_alias_ptr_err.vv new file mode 100644 index 000000000..c37d19859 --- /dev/null +++ b/vlib/v/checker/tests/sum_type_holding_alias_ptr_err.vv @@ -0,0 +1,6 @@ +type Alias1 = &int +type Alias2 = &string +type Qwe = Alias1 | Alias2 + +fn main() { +} -- 2.39.5