robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
2.1 KiB55 linesraw
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)
12  return hashy.hashy_hash(name, keys, function(idx)
13    return name .. '_table[' .. idx .. '].str'
14  end)
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)
29  write(('%sKeySetLink %s_table[] = {'):format(p.static and 'static const ' or '', p.name))
30  for _, key in ipairs(p.order) do
31    local e = p.entry[key]
32    write(
33      ('  { "%s", offsetof(%s, %s), %s, %d, %s },'):format(
34        key,
35        p.struct,
36        e.field,
37        e.type,
38        e.opt_index,
39        e.is_hlgroup and 'true' or 'false'
40      )
41    )
42  end
43  write('  { NULL, 0, kObjectTypeNil, -1, false },')
44  write('};')
45  write('')
46  local inl = p.static and 'static inline ' or ''
47  write(inl .. p.hashfun)
48  write(inl .. ('const KeySetLink *%s(const char *str, size_t len)'):format(p.get_field))
49  write('{')
50  write(('  int hash = %s_hash(str, len);'):format(p.name))
51  write(('  return hash == -1 ? NULL : &%s_table[hash];'):format(p.name))
52  write('}')
53end
54
55return M