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

compiler: __offsetof keyword for C offsetof() macro

This commit is contained in:
Emily Hudson 2019-12-21 21:46:09 +00:00 committed by Alexander Medvednikov
parent 31b7991a93
commit 8512c9fc9d
4 changed files with 23 additions and 2 deletions

View File

@ -400,4 +400,3 @@ fn C.WaitForSingleObject(voidptr, int) int
fn C.ReleaseMutex(voidptr) bool fn C.ReleaseMutex(voidptr) bool

View File

@ -20,6 +20,10 @@ const (
#define TCCSKIP(x) #define TCCSKIP(x)
#endif #endif
// for __offset_of
#define __offsetof(s,memb) \\
((size_t)((char *)&((s *)0)->memb - (char *)0))
#define OPTION_CAST(x) (x) #define OPTION_CAST(x) (x)
' '
c_headers = ' c_headers = '

View File

@ -227,6 +227,7 @@ fn (p mut Parser) name_expr() string {
p.string_expr() p.string_expr()
return 'charptr' return 'charptr'
} }
// known_type := p.table.known_type(name) // known_type := p.table.known_type(name)
orig_name := name orig_name := name
is_c := name == 'C' && p.peek() == .dot is_c := name == 'C' && p.peek() == .dot
@ -718,6 +719,21 @@ fn (p mut Parser) factor() string {
// p.fgen('$sizeof_typ)') // p.fgen('$sizeof_typ)')
return 'int' return 'int'
} }
.key_offsetof {
p.next()
p.check(.lpar)
offsetof_typ := p.get_type()
p.check(.comma)
member := p.check_name()
p.check(.rpar)
p.gen('__offsetof($offsetof_typ, $member)')
return 'int'
}
.amp, .dot, .mul { .amp, .dot, .mul {
// (dot is for enum vals: `.green`) // (dot is for enum vals: `.green`)
return p.name_expr() return p.name_expr()

View File

@ -108,6 +108,7 @@ enum TokenKind {
key_return key_return
key_select key_select
key_sizeof key_sizeof
key_offsetof
key_struct key_struct
key_switch key_switch
key_true key_true
@ -237,11 +238,12 @@ fn build_token_str() []string {
s[TokenKind.key_match] = 'match' s[TokenKind.key_match] = 'match'
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'
return s return s
} }
const ( const (
NrTokens = 140 NrTokens = 141
TokenStr = build_token_str() TokenStr = build_token_str()
KEYWORDS = build_keys() KEYWORDS = build_keys()
) )