v.parser: add check for existing type on sum type declaration (#11054)

pull/11062/head
Daniel Däschle 2021-08-04 17:14:16 +02:00 committed by GitHub
parent 310b51c883
commit f59119485a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 15 additions and 5 deletions

View File

@ -3123,6 +3123,7 @@ fn (mut p Parser) type_decl() ast.TypeDecl {
p.check(.key_type) p.check(.key_type)
end_pos := p.tok.position() end_pos := p.tok.position()
decl_pos := start_pos.extend(end_pos) decl_pos := start_pos.extend(end_pos)
name_pos := p.tok.position()
name := p.check_name() name := p.check_name()
if name.len == 1 && name[0].is_capital() { if name.len == 1 && name[0].is_capital() {
p.error_with_pos('single letter capital names are reserved for generic template types.', p.error_with_pos('single letter capital names are reserved for generic template types.',
@ -3197,6 +3198,11 @@ fn (mut p Parser) type_decl() ast.TypeDecl {
} }
is_public: is_pub is_public: is_pub
}) })
if typ == -1 {
p.error_with_pos('cannot register sum type `$name`, another type with this name exists',
name_pos)
return ast.SumTypeDecl{}
}
comments = p.eat_comments(same_line: true) comments = p.eat_comments(same_line: true)
return ast.SumTypeDecl{ return ast.SumTypeDecl{
name: name name: name
@ -3233,7 +3239,7 @@ fn (mut p Parser) type_decl() ast.TypeDecl {
type_end_pos := p.prev_tok.position() type_end_pos := p.prev_tok.position()
if idx == -1 { if idx == -1 {
p.error_with_pos('cannot register alias `$name`, another type with this name exists', p.error_with_pos('cannot register alias `$name`, another type with this name exists',
decl_pos.extend(type_alias_pos)) name_pos)
return ast.AliasTypeDecl{} return ast.AliasTypeDecl{}
} }
if idx == pidx { if idx == pidx {

View File

@ -0,0 +1,3 @@
vlib/v/parser/tests/sum_type_exists_err.vv:1:6: error: cannot register sum type `Option`, another type with this name exists
1 | type Option = string | int
| ~~~~~~

View File

@ -0,0 +1 @@
type Option = string | int

View File

@ -1,7 +1,7 @@
vlib/v/parser/tests/type_alias_existing_type_err.vv:3:1: error: cannot register alias `Foo`, another type with this name exists vlib/v/parser/tests/type_alias_existing_type_err.vv:3:6: error: cannot register alias `Foo`, another type with this name exists
1 | struct Foo{} 1 | struct Foo{}
2 | 2 |
3 | type Foo = Foo 3 | type Foo = Foo
| ~~~~~~~~~~~~~~ | ~~~
4 | 4 |
5 | fn main() { 5 | fn main() {