cgen: generate typeof for functions

pull/4455/head
Enzo Baldisserri 2020-04-16 21:04:27 +02:00 committed by GitHub
parent dee64347e0
commit 051cc732bb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 36 additions and 6 deletions

View File

@ -32,7 +32,6 @@ const (
'vlib/v/tests/string_interpolation_struct_test.v',
'vlib/v/tests/string_interpolation_variadic_test.v',
'vlib/v/tests/type_test.v',
'vlib/v/tests/typeof_test.v',
'vlib/v/tests/valgrind/valgrind_test.v', // ubuntu-musl only
'vlib/v/tests/pointers_str_test.v',
'vlib/net/http/cookie_test.v',

View File

@ -1103,8 +1103,23 @@ fn (var g Gen) typeof_expr(node ast.TypeOf) {
g.write(').typ ))')
} else if sym.kind == .array_fixed {
fixed_info := sym.info as table.ArrayFixed
elem_sym := g.table.get_type_symbol(fixed_info.elem_type)
g.write('tos3("[$fixed_info.size]${elem_sym.name}")')
typ_name := g.table.get_type_name(fixed_info.elem_type)
g.write('tos3("[$fixed_info.size]${typ_name}")')
} else if sym.kind == .function {
info := sym.info as table.FnType
fn_info := info.func
mut repr := 'fn ('
for i, arg in fn_info.args {
if i > 0 {
repr += ', '
}
repr += g.table.get_type_name(arg.typ)
}
repr += ')'
if fn_info.return_type != table.void_type {
repr += ' ${g.table.get_type_name(fn_info.return_type)}'
}
g.write('tos3("$repr")')
} else {
g.write('tos3("${sym.name}")')
}

View File

@ -204,6 +204,13 @@ pub fn (t &Table) get_type_symbol(typ Type) &TypeSymbol {
panic('get_type_symbol: invalid type (typ=$typ idx=${idx}). This should never happen')
}
[inline]
pub fn (t &Table) get_type_name(typ Type) string {
typ_sym := t.get_type_symbol(typ)
return typ_sym.name
}
// this will override or register builtin type
// allows prexisitng types added in register_builtins
// to be overriden with their real type info

View File

@ -17,8 +17,12 @@ type AnotherSumType = XxYyZz | int
type SuperSumType = MySumType | AnotherSumType | string
fn test_typeof_for_builtin_int_types() {
assert typeof(i8(1)) == 'i8'
assert typeof(i16(1)) == 'i16'
assert typeof(1) == 'int'
assert typeof(i64(1)) == 'i64'
assert typeof(byte(1)) == 'byte'
assert typeof(u16(1)) == 'u16'
assert typeof(u32(1)) == 'u32'
assert typeof(u64(1)) == 'u64'
}

View File

@ -73,15 +73,20 @@ fn test_typeof_on_sumtypes_of_structs() {
assert typeof(d) == 'UnaryExpr'
}
type MyFn fn(int) int
type MyFn2 fn()
fn myfn(i int) int {
return i
}
fn myfn2() {}
fn myfn3(i int, s string) byte {
return byte(0)
}
fn myfn4() i8 {
return -1
}
fn test_typeof_on_fn() {
assert typeof(myfn) == 'fn (int) int'
assert typeof(myfn2) == 'fn ()'
assert typeof(myfn3) == 'fn (int, string) byte'
assert typeof(myfn4) == 'fn () i8'
}