From 52f908839e5fec7edc2ed4a123b60f0434112878 Mon Sep 17 00:00:00 2001 From: Swastik Baranwal Date: Wed, 16 Dec 2020 01:19:04 +0530 Subject: [PATCH] parser: add error for self aliasing (#7347) --- vlib/v/parser/parser.v | 7 ++++++- vlib/v/parser/tests/type_alias_same_type_err.out | 7 +++++++ vlib/v/parser/tests/type_alias_same_type_err.vv | 7 +++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 vlib/v/parser/tests/type_alias_same_type_err.out create mode 100644 vlib/v/parser/tests/type_alias_same_type_err.vv diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 8377367472..95dc05625d 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -2015,6 +2015,7 @@ fn (mut p Parser) type_decl() ast.TypeDecl { } } first_type := p.parse_type() // need to parse the first type before we can check if it's `type A = X | Y` + type_alias_pos := p.tok.position() if p.tok.kind == .pipe { mut type_end_pos := p.prev_tok.position() type_pos = type_pos.extend(type_end_pos) @@ -2061,7 +2062,7 @@ fn (mut p Parser) type_decl() ast.TypeDecl { comments: comments } } - // type MyType int + // type MyType = int parent_type := first_type parent_name := p.table.get_type_symbol(parent_type).name pid := parent_type.idx() @@ -2087,6 +2088,10 @@ fn (mut p Parser) type_decl() ast.TypeDecl { is_public: is_pub }) comments = p.eat_line_end_comments() + if prepend_mod_name == parent_name { + p.error_with_pos('a type alias can not refer to itself: $name', decl_pos.extend(type_alias_pos)) + return ast.AliasTypeDecl{} + } return ast.AliasTypeDecl{ name: name is_pub: is_pub diff --git a/vlib/v/parser/tests/type_alias_same_type_err.out b/vlib/v/parser/tests/type_alias_same_type_err.out new file mode 100644 index 0000000000..1cdf5f45a0 --- /dev/null +++ b/vlib/v/parser/tests/type_alias_same_type_err.out @@ -0,0 +1,7 @@ +vlib/v/parser/tests/type_alias_same_type_err.vv:3:1: error: a type alias can not refer to itself: Foo + 1 | struct Foo{} + 2 | + 3 | type Foo = Foo + | ~~~~~~~~~~~~~~ + 4 | + 5 | fn main() { diff --git a/vlib/v/parser/tests/type_alias_same_type_err.vv b/vlib/v/parser/tests/type_alias_same_type_err.vv new file mode 100644 index 0000000000..c1aeeed296 --- /dev/null +++ b/vlib/v/parser/tests/type_alias_same_type_err.vv @@ -0,0 +1,7 @@ +struct Foo{} + +type Foo = Foo + +fn main() { + +}