robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1-- Shared codegen for a `KeySetLink` perfect-hash table and its `get_field()` lookup. 2local hashy =require ( 'gen.hashy' ) 3 4local M ={} 5 6--- Perfect-hash `keys`, using the shared `<name>_table[idx].str` probe convention. 7--- @param name string 8--- @param keys string[] 9--- @return string[] order keys in perfect-hash order 10--- @return string hashfun source of the `<name>_hash()` function 11function M . hash ( name , keys ) 12return hashy . hashy_hash ( name , keys , function ( idx ) 13return name .. '_table[' .. idx .. '].str' 14end ) 15end 16 17--- @class gen.keyset.entry 18--- @field field string C struct field name, for offsetof() 19--- @field type string ObjectType/UnpackType enum, e.g. 'kObjectTypeInteger' 20--- @field opt_index integer index used by HAS_KEY (or -1 when the keyset has no optional keys) 21--- @field is_hlgroup boolean 22 23--- Emit `<name>_table[]` (a `KeySetLink[]` in perfect-hash `order`) followed by `<get_field>()`. 24--- @param write fun(s: string) writer that appends a newline 25--- @param p { name: string, get_field: string, struct: string, order: string[], hashfun: string, entry: table<string, gen.keyset.entry>, static: boolean } 26--- `static` emits a `static const` table + `static inline` funcs (a self-contained header, e.g. the 27--- option keysets); otherwise external linkage (the API keydicts, declared in a separate header). 28function M . emit ( write , p ) 29write (( '%sKeySetLink %s_table[] = {' ): format ( p . static and 'static const ' or '' , p . name )) 30for _ , key in ipairs ( p . order ) do 31local e =p . entry [ key ] 32write ( 33( ' { "%s", offsetof(%s, %s), %s, %d, %s },' ): format ( 34key , 35p . struct , 36e . field , 37e . type , 38e . opt_index , 39e . is_hlgroup and 'true' or 'false' 40) 41) 42end 43write ( ' { NULL, 0, kObjectTypeNil, -1, false },' ) 44write ( '};' ) 45write ( '' ) 46local inl =p . static and 'static inline ' or '' 47write ( inl .. p . hashfun ) 48write ( inl .. ( 'const KeySetLink *%s(const char *str, size_t len)' ): format ( p . get_field )) 49write ( '{' ) 50write (( ' int hash = %s_hash(str, len);' ): format ( p . name )) 51write (( ' return hash == -1 ? NULL : &%s_table[hash];' ): format ( p . name )) 52write ( '}' ) 53end 54 55return M