checker: check error in for_c_stmt with optional call (#14190)

yuyi 2022-04-28 13:43:16 +08:00 committed by Jef Roosens
parent f9bd107a84
commit bf75a873b5
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
3 changed files with 48 additions and 0 deletions

View File

@ -13,6 +13,16 @@ fn (mut c Checker) for_c_stmt(node ast.ForCStmt) {
} }
c.expr(node.cond) c.expr(node.cond)
if node.has_inc { if node.has_inc {
if node.inc is ast.AssignStmt {
for right in node.inc.right {
if right is ast.CallExpr {
if right.or_block.stmts.len > 0 {
c.error('optionals are not allowed in `for statement increment` (yet)',
right.pos)
}
}
}
}
c.stmt(node.inc) c.stmt(node.inc)
} }
c.check_loop_label(node.label, node.pos) c.check_loop_label(node.label, node.pos)

View File

@ -0,0 +1,7 @@
vlib/v/checker/tests/for_c_stmt_with_optional_call.vv:15:31: error: optionals are not allowed in `for statement increment` (yet)
13 | for t := 0; t < tests; t++ {
14 | mut v := []bool{len: nmax, init: false}
15 | for x := 0; !v[x]; x = rand.intn(n) or { 0 } {
| ~~~~~~~
16 | v[x] = true
17 | sum++

View File

@ -0,0 +1,31 @@
import rand
import math { abs }
const nmax = 20
fn ana(n int) f64 {
return 1.0 // haven't started
}
fn avg(n int) f64 {
tests := 1e4
mut sum := 0
for t := 0; t < tests; t++ {
mut v := []bool{len: nmax, init: false}
for x := 0; !v[x]; x = rand.intn(n) or { 0 } {
v[x] = true
sum++
}
}
return f64(sum) / tests
}
fn main() {
println(' N average analytical (error)')
println('=== ========= ============ =========')
for n in 1 .. nmax + 1 {
a := avg(n)
b := ana(n)
println('${n:3} ${a:9.4f} ${b:12.4f} (${(abs(a - b) / b * 100):6.2f}%)')
}
}