Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

checker: check if next() method infers generic type correctly #23932

Merged
merged 4 commits into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions vlib/v/checker/for.v
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,13 @@ fn (mut c Checker) for_in_stmt(mut node ast.ForInStmt) {
node.cond_type = typ
node.kind = sym.kind
node.val_type = val_type
if node.val_type.has_flag(.generic) {
if c.table.sym(c.unwrap_generic(node.val_type)).kind == .any {
c.add_error_detail('type parameters defined by `next()` method should be bounded by method owner type')
c.error('cannot infer from generic type `${c.table.get_type_name(c.unwrap_generic(node.val_type))}`',
node.vv_pos)
}
}
node.scope.update_var_type(node.val_var, val_type)

if is_comptime {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
vlib/v/checker/tests/struct_iter_generic_invalid_infer_err.vv:25:6: error: cannot infer from generic type `K`
23 | }
24 |
25 | for squared in iter {
| ~~~~~~~
26 | println(squared)
27 | }
Details: type parameters defined by `next()` method should be bounded by method owner type
28 changes: 28 additions & 0 deletions vlib/v/checker/tests/struct_iter_generic_invalid_infer_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module main

struct SquareIterator {
arr []int
mut:
idx int
}

fn (mut iter SquareIterator) next[K]() ?K {
if iter.idx >= iter.arr.len {
return none
}
defer {
iter.idx++
}
return iter.arr[iter.idx] * iter.arr[iter.idx]
}

fn main() {
nums := [1, 2, 3, 4, 5]
iter := SquareIterator{
arr: nums
}

for squared in iter {
println(squared)
}
}
Loading