1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

compiler: add very simple nameof token to get type name as string

This commit is contained in:
Nicolas Sauzede 2020-02-05 06:12:33 +01:00 committed by GitHub
parent c595c9eee1
commit 9d4c943d64
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 27 additions and 0 deletions

View File

@ -813,6 +813,15 @@ fn (p mut Parser) factor() string {
// p.fgen('$sizeof_typ)') // p.fgen('$sizeof_typ)')
return 'int' return 'int'
} }
.key_nameof {
p.next()
p.check(.lpar)
mut nameof_typ := p.get_type()
p.check(.rpar)
p.gen('tos3("$nameof_typ")')
// return 'byteptr'
return 'string'
}
.key_offsetof { .key_offsetof {
p.next() p.next()
p.check(.lpar) p.check(.lpar)

View File

@ -0,0 +1,16 @@
fn simple<T>(p T) string {
tname := nameof(T)
println("Hello generic, I'm an [$tname]")
return tname
}
struct FunkyStruct{ }
fn test_nameof_on_various_types_in_generic() {
assert simple(42) == "int"
assert simple(3.14) == "f32"
assert simple("FuBar") == "string"
assert simple(FunkyStruct{}) == "FunkyStruct"
assert simple(test_nameof_on_various_types_in_generic) == "fn ()"
}

View File

@ -110,6 +110,7 @@ enum TokenKind {
key_select key_select
key_sizeof key_sizeof
key_offsetof key_offsetof
key_nameof
key_struct key_struct
key_switch key_switch
key_true key_true
@ -240,6 +241,7 @@ fn build_token_str() []string {
s[TokenKind.key_select] = 'select' s[TokenKind.key_select] = 'select'
s[TokenKind.key_none] = 'none' s[TokenKind.key_none] = 'none'
s[TokenKind.key_offsetof] = '__offsetof' s[TokenKind.key_offsetof] = '__offsetof'
s[TokenKind.key_nameof] = 'nameof'
return s return s
} }