parser, checker: fix generic fn that returns a generic struct (#9469)

pull/9475/head
yuyi 2021-03-26 14:32:11 +08:00 committed by GitHub
parent d8108a58d8
commit 478bb9ce8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 68 additions and 2 deletions

View File

@ -1944,9 +1944,39 @@ pub fn (mut c Checker) call_fn(mut call_expr ast.CallExpr) table.Type {
if rts.info.generic_types.len > 0 {
gts := c.table.get_type_symbol(call_expr.generic_types[0])
nrt := '$rts.name<$gts.name>'
c_nrt := '${rts.name}_T_$gts.name'
idx := c.table.type_idxs[nrt]
c.ensure_type_exists(idx, call_expr.pos) or {}
call_expr.return_type = table.new_type(idx).derive(f.return_type)
if idx != 0 {
c.ensure_type_exists(idx, call_expr.pos) or {}
call_expr.return_type = table.new_type(idx).derive(f.return_type)
} else {
mut fields := rts.info.fields.clone()
if rts.info.generic_types.len == generic_types.len {
for i, _ in fields {
mut field := fields[i]
if field.typ.has_flag(.generic) {
for j, gp in rts.info.generic_types {
if gp == field.typ {
field.typ = generic_types[j].derive(field.typ).clear_flag(.generic)
break
}
}
}
fields[i] = field
}
mut info := rts.info
info.generic_types = []
info.fields = fields
stru_idx := c.table.register_type_symbol(table.TypeSymbol{
kind: .struct_
name: nrt
cname: util.no_dots(c_nrt)
mod: c.mod
info: info
})
call_expr.return_type = table.new_type(stru_idx)
}
}
}
}
} else {

View File

@ -502,6 +502,11 @@ pub fn (mut p Parser) parse_generic_struct_inst_type(name string) table.Type {
}
})
return table.new_type(idx)
} else {
idx := p.table.find_type_idx(name)
if idx != 0 {
return table.new_type(idx).set_flag(.generic)
}
}
return p.parse_enum_or_struct_type(name, .v)
}

View File

@ -0,0 +1,31 @@
pub struct Optional<T> {
mut:
value T
some bool
}
pub fn new_some<T>(value T) Optional<T> {
return {value: value, some: true}
}
pub fn some<T>(opt Optional<T>) bool {
return opt.some
}
pub fn get<T>(opt Optional<T>) T {
return opt.value
}
pub fn set<T>(mut opt Optional<T>, value T) {
opt.value = value
opt.some = true
}
fn test_generics_return_generics_struct() {
mut o := new_some<int>(23)
println(some<int>(o))
assert some<int>(o) == true
set<int>(mut o, 42)
println(get<int>(o))
assert get<int>(o) == 42
}