Skip to content

Commit

Permalink
сgen: print generic structs (#6967)
Browse files Browse the repository at this point in the history
  • Loading branch information
danieldaeschle committed Nov 26, 2020
1 parent 6563535 commit d71d9ad
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
6 changes: 6 additions & 0 deletions vlib/v/gen/auto_str_methods.v
Expand Up @@ -367,6 +367,12 @@ fn (mut g Gen) gen_str_for_struct(info table.Struct, styp string, str_fn_name st
g.type_definitions.writeln('string indent_${str_fn_name}($styp x, int indent_count); // auto')
g.auto_str_funcs.writeln('string indent_${str_fn_name}($styp x, int indent_count) {')
mut clean_struct_v_type_name := styp.replace('__', '.')
if clean_struct_v_type_name.contains('_T_') {
// TODO: this is a bit hacky. styp shouldn't be even parsed with _T_
// use something different than g.typ for styp
clean_struct_v_type_name = clean_struct_v_type_name.replace('_T_', '<').replace('_', ', ') +
'>'
}
if styp.ends_with('*') {
deref_typ := styp.replace('*', '')
g.auto_str_funcs.writeln('\t$deref_typ *it = x;')
Expand Down
7 changes: 3 additions & 4 deletions vlib/v/gen/cgen.v
Expand Up @@ -500,11 +500,10 @@ static inline $opt_el_type __Option_${styp}_popval($styp ch) {
fn (g &Gen) cc_type2(t table.Type) string {
sym := g.table.get_type_symbol(g.unwrap_generic(t))
mut styp := util.no_dots(sym.name)
if sym.kind == .struct_ {
info := sym.info as table.Struct
if info.generic_types.len > 0 {
if mut sym.info is table.Struct {
if sym.info.generic_types.len > 0 {
mut sgtyps := '_T'
for gt in info.generic_types {
for gt in sym.info.generic_types {
gts := g.table.get_type_symbol(if gt.has_flag(.generic) { g.unwrap_generic(gt) } else { gt })
sgtyps += '_$gts.name'
}
Expand Down
21 changes: 21 additions & 0 deletions vlib/v/tests/str_gen_test.v
Expand Up @@ -269,3 +269,24 @@ fn test_alias_struct() {
assert t.str() == 'TestAlias($ts)'
assert '$t' == 'TestAlias(TestStruct{\n x: 0\n})'
}

struct GenericStruct<T> {
x T
}

fn test_generic_struct() {
x := GenericStruct<TestStruct>{}
assert '$x' == 'GenericStruct<TestStruct>{\n x: TestStruct{\n x: 0\n }\n}'
assert x.str() == 'GenericStruct<TestStruct>{\n x: TestStruct{\n x: 0\n }\n}'
}

struct MultiGenericStruct<T, X> {
t T
x X
}

fn test_multi_generic_struct() {
x := MultiGenericStruct<TestStruct, TestStruct>{}
assert '$x' == 'MultiGenericStruct<TestStruct, TestStruct>{\n t: TestStruct{\n x: 0\n }\n x: TestStruct{\n x: 0\n }\n}'
assert x.str() == 'MultiGenericStruct<TestStruct, TestStruct>{\n t: TestStruct{\n x: 0\n }\n x: TestStruct{\n x: 0\n }\n}'
}

0 comments on commit d71d9ad

Please sign in to comment.