checker: disallow using a preexisting const name in a for loop, as either a key or value ident (#22108)

This commit is contained in:
Swastik Baranwal 2024-08-24 04:46:28 +05:30 committed by GitHub
parent 19c567047e
commit 4b799fd81d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 37 additions and 4 deletions

View File

@ -8,8 +8,8 @@ fn poly_n_eval(c []f64, n int, x f64) f64 {
}
len := int(min(c.len, n))
mut ans := c[len - 1]
for e in c[..len - 1] {
ans = e + x * ans
for e_ in c[..len - 1] {
ans = e_ + x * ans
}
return ans
}
@ -20,8 +20,8 @@ fn poly_n_1_eval(c []f64, n int, x f64) f64 {
}
len := int(min(c.len, n)) - 1
mut ans := c[len - 1]
for e in c[..len - 1] {
ans = e + x * ans
for e_ in c[..len - 1] {
ans = e_ + x * ans
}
return ans
}

View File

@ -1277,6 +1277,7 @@ pub:
is_range bool
pos token.Pos
kv_pos token.Pos
vv_pos token.Pos
comments []Comment
val_is_mut bool // `for mut val in vals {` means that modifying `val` will modify the array
// and the array cannot be indexed inside the loop

View File

@ -44,6 +44,14 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) {
c.error('invalid use of reserved type `${node.val_var}` as value name', node.pos)
}
}
if _ := c.file.global_scope.find_const('${c.mod}.${node.key_var}') {
c.error('duplicate of a const name `${c.mod}.${node.key_var}`', node.kv_pos)
}
if _ := c.file.global_scope.find_const('${c.mod}.${node.val_var}') {
c.error('duplicate of a const name `${c.mod}.${node.val_var}`', node.vv_pos)
}
if node.is_range {
typ_idx := typ.idx()
high_type := c.expr(mut node.high)

View File

@ -0,0 +1,14 @@
vlib/v/checker/tests/const_name_for_loop_duplicate_name_err.vv:5:6: error: duplicate of a const name `item`
3 |
4 | fn main() {
5 | for item, i in ['abc', 'def'] {
| ~~~~
6 | println(item)
7 | println(i)
vlib/v/checker/tests/const_name_for_loop_duplicate_name_err.vv:5:12: error: duplicate of a const name `i`
3 |
4 | fn main() {
5 | for item, i in ['abc', 'def'] {
| ^
6 | println(item)
7 | println(i)

View File

@ -0,0 +1,9 @@
const item = 24
const i = 23
fn main() {
for item, i in ['abc', 'def'] {
println(item)
println(i)
}
}

View File

@ -205,6 +205,7 @@ fn (mut p Parser) for_stmt() ast.Stmt {
is_range: is_range
pos: pos
kv_pos: key_var_pos
vv_pos: val_var_pos
comments: comments
val_is_mut: val_is_mut
scope: p.scope