1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: check duplicate consts

This commit is contained in:
yuyi 2020-04-30 18:17:31 +08:00 committed by GitHub
parent 4d415e56d6
commit 81ed6ad2a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 33 additions and 2 deletions

View File

@ -29,6 +29,7 @@ mut:
fn_return_type table.Type // current function's return type
const_decl string
const_deps []string
const_names []string
pref &pref.Preferences // Preferences shared from V struct
in_for_count int // if checker is currently in an for loop
// checked_ident string // to avoid infinit checker loops
@ -1271,6 +1272,10 @@ fn (mut c Checker) stmt(node ast.Stmt) {
mut field_names := []string{}
mut field_order := []int{}
for i, field in it.fields {
if field.name in c.const_names {
c.error('field name `$field.name` duplicate', field.pos)
}
c.const_names << field.name
field_names << field.name
field_order << i
}
@ -1873,7 +1878,7 @@ pub fn (mut c Checker) if_expr(node mut ast.IfExpr) table.Type {
t := c.expr(it.expr)
if is_ternary && t != first_typ {
c.error('mismatched types `${c.table.type_to_str(first_typ)}` and `${c.table.type_to_str(t)}`', node.pos)
}
}
node.typ = t
return t
}

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/const_field_name_duplicate_err.v:3:2: error: field name `aaa` duplicate
1| const (
2| aaa = 1
3| aaa = 2
~~~
4| )
5| fn main() {

View File

@ -0,0 +1,7 @@
const (
aaa = 1
aaa = 2
)
fn main() {
println(aaa)
}

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/multi_const_field_name_duplicate_err.v:2:8: error: field name `aaa` duplicate
1| const (aaa = 1)
2| const (aaa = 2)
~~~
3| fn main() {
4| println(aaa)

View File

@ -0,0 +1,5 @@
const (aaa = 1)
const (aaa = 2)
fn main() {
println(aaa)
}

View File

@ -1002,6 +1002,7 @@ fn (mut p Parser) const_decl() ast.ConstDecl {
if p.tok.kind == .comment {
p.comment()
}
pos := p.tok.position()
name := p.prepend_mod(p.check_name())
// name := p.check_name()
// println('!!const: $name')
@ -1010,7 +1011,7 @@ fn (mut p Parser) const_decl() ast.ConstDecl {
field := ast.ConstField{
name: name
expr: expr
pos: p.tok.position()
pos: pos
}
fields << field
p.global_scope.register(field.name, field)