cgen: use alias next method if defined in for x in iterator { (#24905)

This commit is contained in:
Swastik Baranwal 2025-07-15 12:50:17 +05:30 committed by GitHub
parent 69a887f63b
commit 9b348b1b11
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 25 additions and 5 deletions

View file

@ -422,10 +422,21 @@ fn (mut g Gen) for_in_stmt(node_ ast.ForInStmt) {
g.writeln('${field_accessor}str[${i}];') g.writeln('${field_accessor}str[${i}];')
} }
} else if node.kind in [.struct, .interface] { } else if node.kind in [.struct, .interface] {
cond_type_sym := g.table.final_sym(node.cond_type) cond_type_sym := g.table.sym(node.cond_type)
next_fn := cond_type_sym.find_method_with_generic_parent('next') or { mut next_fn := ast.Fn{}
verror('`next` method not found') // use alias `next` method if exists else use parent type `next` method
return if cond_type_sym.kind == .alias {
next_fn = cond_type_sym.find_method_with_generic_parent('next') or {
g.table.final_sym(node.cond_type).find_method_with_generic_parent('next') or {
verror('`next` method not found')
return
}
}
} else {
next_fn = cond_type_sym.find_method_with_generic_parent('next') or {
verror('`next` method not found')
return
}
} }
ret_typ := next_fn.return_type ret_typ := next_fn.return_type
t_expr := g.new_tmp_var() t_expr := g.new_tmp_var()

View file

@ -35,10 +35,18 @@ fn iterator_as_concrete_type() LineIterator {
fn iterator_as_alias_concrete_type() AliasLineIterator { fn iterator_as_alias_concrete_type() AliasLineIterator {
return AliasLineIterator(LineIterator{ return AliasLineIterator(LineIterator{
lines: ['alias'] lines: ['alias', 'iterator', 'next']
}) })
} }
pub fn (mut line_iterator AliasLineIterator) next() ?string {
if line_iterator.idx >= line_iterator.lines.len {
return none
}
defer { line_iterator.idx += 2 }
return line_iterator.lines[line_iterator.idx]
}
fn test_main() { fn test_main() {
mut out := []string{} mut out := []string{}
for line in iterator_as_interface() { for line in iterator_as_interface() {
@ -78,4 +86,5 @@ fn test_main() {
} }
assert out[6] == 'LINE: alias' assert out[6] == 'LINE: alias'
assert out[7] == 'LINE: next'
} }