robin/laufey

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

robinmerge: 1dc9728daa1d8a2702

master
24.9 KiB827 linesraw
1---@diagnostic disable: no-unknown
2local options_input_file = arg[7]
3
4--- @module 'nvim.options'
5local options = loadfile(options_input_file)()
6local options_meta = options.options
7local cstr = options.cstr
8local valid_scopes = options.valid_scopes
9local schema_values = options.schema_values
10-- Limit for a free-string (`str`) dict value; opt_strings_check() rejects anything longer.
11local keyset_str_max = 256
12
13-- Object type of a `dict` key's value, for the generated KeySetLink table. String-ish kinds
14-- (enum/str) are stored inline as fixed `char[]` (keyset_charsize); opt_fill() copies to them.
15local keyset_ctype = {
16  num = 'kObjectTypeInteger',
17  snum = 'kObjectTypeInteger',
18  enum = 'kObjectTypeString',
19  str = 'kObjectTypeString',
20}
21-- C field type for `dict` key kinds (except enum/str, which use a fixed-size `char[]`).
22local keyset_ftype = {
23  num = 'Integer',
24  snum = 'Integer',
25}
26
27--- Fixed `char[]` size for a string-ish dict key, to avoid allocations. An `enum` fits its longest
28--- value, a `str` is limited to `keyset_str_max`. Returns nil for non-string kinds (num/snum/flag).
29--- @param item vim.option_schema.dictkey
30--- @return integer?
31local function keyset_charsize(item)
32  local kind = type(item) == 'string' and 'flag' or item[2]
33  if kind == 'enum' then
34    local n = 0
35    for _, val in ipairs(item[3].values) do
36      n = math.max(n, #val)
37    end
38    return n + 1
39  elseif kind == 'str' then
40    return keyset_str_max
41  end
42  return nil
43end
44
45--- @param o vim.option_meta
46--- @return string
47local function get_values_var(o)
48  return ('opt_%s_values'):format(o.abbreviation or o.full_name)
49end
50
51--- True if an option is a dict option: a `dict` schema (typed key:value map, e.g. 'diffopt'), as
52--- opposed to a flag/enum/char category. Dict options are stored as their (canonical) ":set"
53--- string; the `dict` schema generates the keyset machinery used to validate and reify it on demand.
54--- @param o vim.option_meta
55--- @return boolean
56local function is_dict_option(o)
57  return o.schema ~= nil and o.schema.dict ~= nil
58end
59
60--- @param s string
61--- @return string
62local function lowercase_to_titlecase(s)
63  return table.concat(vim.tbl_map(function(word) --- @param word string
64    return word:sub(1, 1):upper() .. word:sub(2)
65  end, vim.split(s, '[-_]')))
66end
67
68--- @param scope string
69--- @param option_name string
70--- @return string
71local function get_scope_option(scope, option_name)
72  return ('k%sOpt%s'):format(lowercase_to_titlecase(scope), lowercase_to_titlecase(option_name))
73end
74
75local redraw_flags = {
76  ui_option = 'kOptFlagUIOption',
77  tabline = 'kOptFlagRedrTabl',
78  statuslines = 'kOptFlagRedrStat',
79  current_window = 'kOptFlagRedrWin',
80  current_buffer = 'kOptFlagRedrBuf',
81  all_windows = 'kOptFlagRedrAll',
82  curswant = 'kOptFlagCurswant',
83  highlight_only = 'kOptFlagHLOnly',
84}
85
86local list_flags = {
87  comma = 'kOptFlagComma',
88  onecomma = 'kOptFlagOneComma',
89  commacolon = 'kOptFlagComma|kOptFlagColon',
90  onecommacolon = 'kOptFlagOneComma|kOptFlagColon',
91  flags = 'kOptFlagFlagList',
92  flagscomma = 'kOptFlagComma|kOptFlagFlagList',
93}
94
95--- @param o vim.option_meta
96--- @return string
97local function get_flags(o)
98  --- @type string[]
99  local flags = { '0' }
100
101  --- @param f string
102  local function add_flag(f)
103    table.insert(flags, f)
104  end
105
106  if o.list then
107    add_flag(list_flags[o.list])
108  end
109
110  for _, r_flag in ipairs(o.redraw or {}) do
111    add_flag(redraw_flags[r_flag])
112  end
113
114  if o.expand then
115    add_flag('kOptFlagExpand')
116    if o.expand == 'nodefault' then
117      add_flag('kOptFlagNoDefExp')
118    end
119  end
120
121  -- Callback option: `type='func'` (funcref/lambda/Lua fn) or `type='expr'` (Vimscript expr).
122  if o.type == 'func' then
123    add_flag('kOptFlagFunc')
124  elseif o.type == 'expr' then
125    add_flag('kOptFlagExpr')
126  end
127
128  for _, flag_desc in ipairs({
129    { 'deny_duplicates', 'NoDup' },
130    { 'gettext' },
131    { 'modelineexpr', 'MLE' },
132    { 'no_mkrc', 'NoMkrc' },
133    { 'nodefault', 'NoDefault' },
134    { 'noglob', 'NoGlob' },
135    { 'normal_dname_chars', 'NDname' },
136    { 'normal_fname_chars', 'NFname' },
137    { 'pri_mkrc', 'PriMkrc' },
138    { 'secure' },
139  }) do
140    local key_name, flag_suffix = flag_desc[1], flag_desc[2]
141    if o[key_name] then
142      local def_name = 'kOptFlag' .. (flag_suffix or lowercase_to_titlecase(key_name))
143      add_flag(def_name)
144    end
145  end
146
147  return table.concat(flags, '|')
148end
149
150--- @param opt_type vim.option_type
151--- @return string
152local function opt_type_enum(opt_type)
153  return ('kObjectType%s'):format(({
154    boolean = 'Boolean',
155    number = 'Integer',
156    string = 'String',
157    func = 'String',
158    expr = 'String',
159  })[opt_type])
160end
161
162--- @param scope vim.option_scope
163--- @return string
164local function opt_scope_enum(scope)
165  return ('kOptScope%s'):format(lowercase_to_titlecase(scope))
166end
167
168--- @param o vim.option_meta
169--- @return string
170local function get_scope_flags(o)
171  local scope_flags = '0'
172
173  for _, scope in ipairs(o.scope) do
174    scope_flags = ('%s | (1 << %s)'):format(scope_flags, opt_scope_enum(scope))
175  end
176
177  return scope_flags
178end
179
180--- @param o vim.option_meta
181--- @return string
182local function get_scope_idx(o)
183  --- @type string[]
184  local strs = {}
185
186  for _, scope in pairs(valid_scopes) do
187    local has_scope = vim.tbl_contains(o.scope, scope)
188    strs[#strs + 1] = ('      [%s] = %s'):format(
189      opt_scope_enum(scope),
190      get_scope_option(scope, has_scope and o.full_name or 'Invalid')
191    )
192  end
193
194  return ('{\n%s\n    }'):format(table.concat(strs, ',\n'))
195end
196
197--- @param s string
198--- @return string
199local function static_cstr_as_string(s)
200  return ('{ .data = %s, .size = sizeof(%s) - 1 }'):format(s, s)
201end
202
203--- @param v vim.option_value|function
204--- @return string
205local function get_opt_val(v)
206  --- @type vim.option_type
207  local v_type
208
209  if type(v) == 'function' then
210    v, v_type = v() --[[ @as string, vim.option_type ]]
211
212    if v_type == 'string' then
213      v = static_cstr_as_string(v)
214    end
215  else
216    v_type = type(v) --[[ @as vim.option_type ]]
217
218    if v_type == 'boolean' then
219      v = v and 'true' or 'false'
220    elseif v_type == 'number' then
221      v = ('%iL'):format(v)
222    elseif v_type == 'string' then
223      --- @cast v string
224      v = static_cstr_as_string(cstr(v))
225    end
226  end
227
228  -- def_val is stored as an API Object.
229  local obj_type = ({ boolean = 'Boolean', number = 'Integer', string = 'String' })[v_type]
230  local obj_field = ({ boolean = 'boolean', number = 'integer', string = 'string' })[v_type]
231  return ('{ .type = kObjectType%s, .data.%s = %s }'):format(obj_type, obj_field, v)
232end
233
234--- @param d vim.option_value|function
235--- @param n string
236--- @return string
237local function get_defaults(d, n)
238  if d == nil then
239    error("option '" .. n .. "' should have a default value")
240  end
241  return get_opt_val(d)
242end
243
244--- @param i integer
245--- @param o vim.option_meta
246--- @param write fun(...: string)
247local function dump_option(i, o, write)
248  write('  [', ('%u'):format(i - 1) .. ']={')
249  write('    .fullname=', cstr(o.full_name))
250  if o.abbreviation then
251    write('    .shortname=', cstr(o.abbreviation))
252  end
253  write('    .type=', opt_type_enum(o.type))
254  write('    .flags=', get_flags(o))
255  write('    .scope_flags=', get_scope_flags(o))
256  write('    .scope_idx=', get_scope_idx(o))
257  -- `chars` (dispatch tables) and `flagchars` don't generate completion values (they self-expand).
258  local values = o.schema and schema_values(o.schema) or {}
259  write('    .values=', (#values > 0 and get_values_var(o) or 'NULL'))
260  write('    .values_len=', (#values > 0 and #values or '0'))
261  -- A `dict` schema also emits an OptSchemaItem[]; expose it so the structured value conversion can
262  -- read typed sub-values.
263  write(
264    '    .schema=',
265    (is_dict_option(o) and ('opt_%s_schema'):format(o.abbreviation or o.full_name) or 'NULL')
266  )
267  write('    .flags_var=', (o.flags_varname and ('&%s'):format(o.flags_varname) or 'NULL'))
268  if o.enable_if then
269    write(('#if defined(%s)'):format(o.enable_if))
270  end
271
272  local is_window_local = #o.scope == 1 and o.scope[1] == 'win'
273
274  if is_window_local then
275    write('    .var=NULL')
276  elseif o.varname then
277    write('    .var=&', o.varname)
278  elseif o.immutable then
279    -- Immutable options can directly point to the default value.
280    write(('    .var=&options[%u].def_val.data'):format(i - 1))
281  else
282    error('Option must be immutable or have a variable.')
283  end
284
285  write('    .immutable=', (o.immutable and 'true' or 'false'))
286  write('    .opt_validate_cb=', o.validation_cb or 'NULL')
287  write('    .opt_did_set_cb=', o.cb or 'NULL')
288  write('    .opt_expand_cb=', o.expand_cb or 'NULL')
289
290  if o.enable_if then
291    write('#else')
292    -- Hidden option directly points to default value.
293    write(('    .var=&options[%u].def_val.data'):format(i - 1))
294    -- Option is always immutable on the false branch of `enable_if`.
295    write('    .immutable=true')
296    write('#endif')
297  end
298
299  if not o.defaults then
300    write('    .def_val={ .type = kObjectTypeNil }')
301  elseif o.defaults.condition then
302    write(('#if defined(%s)'):format(o.defaults.condition))
303    write('    .def_val=', get_defaults(o.defaults.if_true, o.full_name))
304    -- Check against nil: `if_false=false` is a valid default and must still emit the `#else`.
305    if o.defaults.if_false ~= nil then
306      write('#else')
307      write('    .def_val=', get_defaults(o.defaults.if_false, o.full_name))
308    end
309    write('#endif')
310  else
311    write('    .def_val=', get_defaults(o.defaults.if_true, o.full_name))
312  end
313
314  write('  },')
315end
316
317--- Emit an option's flag-set enum from its `flagchars` or `flags` schema:
318---   * `flagchars` (e.g. 'formatoptions'): a name->char map -> `enum { kFoWrap = 't', … }`
319---   * `flags` (e.g. 'foldopen', 'virtualedit'): an ordered list of names (bit = 2^i) or of
320---     {name, bit} pairs -> `typedef enum { kOptFdoFlagHor = 0x…, … } OptFdoFlags;`. A pair's
321---     optional 3rd element overrides the C constant's token (e.g. 'NONE' -> `NoneU`).
322--- @param o vim.option_meta
323--- @return string
324local function gen_token_enum(o)
325  local out = {} --- @type string[]
326  local function add(s)
327    table.insert(out, s)
328  end
329  local opt_name = lowercase_to_titlecase(o.abbreviation or o.full_name)
330
331  if o.schema.flagchars then
332    -- Char flags complete as raw chars, so order is irrelevant; sort by name for a stable enum.
333    local names = vim.tbl_keys(o.schema.flagchars) --[[ @as string[] ]]
334    table.sort(names)
335    add('')
336    add('enum {')
337    for _, name in ipairs(names) do
338      add(
339        ("  k%s%s = '%s',"):format(
340          opt_name,
341          lowercase_to_titlecase(name),
342          (o.schema.flagchars[name]:gsub("[\\']", '\\%0'))
343        )
344      )
345    end
346    add('};')
347    return table.concat(out, '\n')
348  end
349
350  -- Bitmask flags: collect (C-token, bit) and emit in bit order.
351  local flags = {} --- @type {name:string,bit:integer}[]
352  for i, entry in ipairs(o.schema.flags) do
353    if type(entry) == 'string' then
354      flags[#flags + 1] = { name = entry, bit = math.pow(2, i - 1) }
355    else
356      local e = entry --[[ @as {[1]:string, [2]:integer, [3]:string?} ]]
357      flags[#flags + 1] = { name = e[3] or e[1], bit = e[2] }
358    end
359  end
360  table.sort(flags, function(a, b)
361    return a.bit < b.bit
362  end)
363
364  add('')
365  add('typedef enum {')
366  for _, f in ipairs(flags) do
367    -- A "key:" token (e.g. 'messagesopt' "wait:") names its flag without the trailing colon.
368    add(
369      ('  kOpt%sFlag%s = 0x%02x,'):format(
370        opt_name,
371        lowercase_to_titlecase((f.name:gsub(':$', ''))),
372        f.bit
373      )
374    )
375  end
376  add(('} Opt%sFlags;'):format(opt_name))
377  return table.concat(out, '\n')
378end
379
380--- @param output_file string
381--- @return table<string,string> options_index Map of option name to option index
382local function gen_enums(output_file)
383  --- Options for each scope.
384  --- @type table<string, vim.option_meta[]>
385  local scope_options = {}
386  for _, scope in ipairs(valid_scopes) do
387    scope_options[scope] = {}
388  end
389
390  local fd = assert(io.open(output_file, 'w'))
391
392  --- @param s string
393  local function write(s)
394    fd:write(s)
395    fd:write('\n')
396  end
397
398  -- Generate options enum file
399  write('// IWYU pragma: private, include "nvim/option_defs.h"')
400  write('')
401
402  --- Map of option name to option index
403  --- @type table<string, string>
404  local option_index = {}
405
406  -- Generate option index enum and populate the `option_index` and `scope_option` dicts.
407  write('typedef enum {')
408  write('  kOptInvalid = -1,')
409
410  for i, o in ipairs(options_meta) do
411    local enum_val_name = 'kOpt' .. lowercase_to_titlecase(o.full_name)
412    write(('  %s = %u,'):format(enum_val_name, i - 1))
413
414    option_index[o.full_name] = enum_val_name
415
416    if o.abbreviation then
417      option_index[o.abbreviation] = enum_val_name
418    end
419
420    local alias = o.alias or {} --[[@as string[] ]]
421    for _, v in ipairs(alias) do
422      option_index[v] = enum_val_name
423    end
424
425    for _, scope in ipairs(o.scope) do
426      table.insert(scope_options[scope], o)
427    end
428  end
429
430  write('  // Option count')
431  write('#define kOptCount ' .. tostring(#options_meta))
432  write('} OptIndex;')
433
434  -- Generate option index enum for each scope
435  for _, scope in ipairs(valid_scopes) do
436    write('')
437
438    local scope_name = lowercase_to_titlecase(scope)
439    write('typedef enum {')
440    write(('  %s = -1,'):format(get_scope_option(scope, 'Invalid')))
441
442    for idx, option in ipairs(scope_options[scope]) do
443      write(('  %s = %u,'):format(get_scope_option(scope, option.full_name), idx - 1))
444    end
445
446    write(('  // %s option count'):format(scope_name))
447    write(('#define %s %d'):format(get_scope_option(scope, 'Count'), #scope_options[scope]))
448    write(('} %sOptIndex;'):format(scope_name))
449  end
450
451  -- Generate reverse lookup from option scope index to option index for each scope.
452  for _, scope in ipairs(valid_scopes) do
453    write('')
454    write(('EXTERN const OptIndex %s_opt_idx[] INIT( = {'):format(scope))
455    for _, option in ipairs(scope_options[scope]) do
456      local idx = option_index[option.full_name]
457      write(('  [%s] = %s,'):format(get_scope_option(scope, option.full_name), idx))
458    end
459    write('});')
460  end
461
462  fd:close()
463
464  return option_index
465end
466
467--- @param output_file string
468--- @param option_index table<string,string>
469local function gen_map(output_file, option_index)
470  -- Generate option index map.
471  local hashy = require('gen.hashy')
472
473  local neworder, hashfun = hashy.hashy_hash(
474    'find_option',
475    vim.tbl_keys(option_index),
476    function(idx)
477      return ('option_hash_elems[%s].name'):format(idx)
478    end
479  )
480
481  local fd = assert(io.open(output_file, 'w'))
482
483  --- @param s string
484  local function write(s)
485    fd:write(s)
486    fd:write('\n')
487  end
488
489  write('static const struct { const char *name; OptIndex opt_idx; } option_hash_elems[] = {')
490
491  for _, name in ipairs(neworder) do
492    assert(option_index[name] ~= nil)
493    write(('  { .name = "%s", .opt_idx = %s },'):format(name, option_index[name]))
494  end
495
496  write('};')
497  write('')
498  write('static ' .. hashfun)
499
500  fd:close()
501end
502
503-- Maps a `dict` key's value-kind to its OptSchemaKind enum. Enum keys carry a values array instead.
504local schema_kinds = {
505  num = 'kOptSchemaNum',
506  snum = 'kOptSchemaSNum',
507  str = 'kOptSchemaStr',
508}
509
510--- Emit the OptSchemaItem[] that opt_strings_check() validates against, from a `dict` schema.
511--- @param prefix string  e.g. "opt_dip"
512--- @param schema vim.option_schema
513--- @return string
514local function gen_opt_schema(prefix, schema)
515  local out = {} --- @type string[]
516  local function add(s)
517    table.insert(out, s)
518  end
519
520  add('')
521  add(('EXTERN const OptSchemaItem %s_schema[] INIT( = {'):format(prefix))
522  for _, item in ipairs(schema.dict) do
523    if type(item) == 'string' then
524      add(('  { "%s", kOptSchemaFlag, NULL },'):format(item))
525    elseif item[2] == 'enum' then
526      add(('  { "%s", kOptSchemaEnum, %s_%s_values },'):format(item[1], prefix, item[1]))
527    else
528      local kind = schema_kinds[item[2]] or error(('%s: bad kind %q'):format(prefix, item[2]))
529      add(('  { "%s", %s, NULL },'):format(item[1], kind))
530    end
531  end
532  add('  { NULL, kOptSchemaFlag, NULL },')
533  add('});')
534
535  return table.concat(out, '\n')
536end
537
538--- Emit the completion values arrays (`opt_<name>_values`, plus `opt_<name>_<key>_values` for each
539--- `dict` enum key). Enum/set/flag tokens complete as-is; `dict` keys complete as "key:".
540--- @param prefix string  e.g. "opt_dip"
541--- @param schema vim.option_schema
542--- @return string
543local function gen_schema_values(prefix, schema)
544  local out = {} --- @type string[]
545  local function add(s)
546    table.insert(out, s)
547  end
548
549  local values = schema_values(schema)
550  add('')
551  add(('EXTERN const char *(%s_values[%s]) INIT( = {'):format(prefix, #values + 1))
552  for _, v in ipairs(values) do
553    add(('  "%s",'):format(v))
554  end
555  add('  NULL')
556  add('});')
557
558  for _, item in ipairs(schema.dict or {}) do
559    if type(item) == 'table' and item[2] == 'enum' then
560      local vals = item[3].values --[[ @as string[] ]]
561      add('')
562      add(('EXTERN const char *(%s_%s_values[%s]) INIT( = {'):format(prefix, item[1], #vals + 1))
563      for _, v in ipairs(vals) do
564        add(('  "%s",'):format(v))
565      end
566      add('  NULL')
567      add('});')
568    end
569  end
570
571  return table.concat(out, '\n')
572end
573
574local c_keywords = { inline = true, default = true, auto = true, register = true }
575
576--- Sanitize a schema key into a C struct field name. C keywords get a trailing '_'.
577--- @param name string
578--- @return string
579local function c_field_name(name)
580  local f = (name:gsub('%-', '_'))
581  return c_keywords[f] and (f .. '_') or f
582end
583
584--- @param output_file string
585local function gen_vars(output_file)
586  local fd = assert(io.open(output_file, 'w'))
587
588  --- @param s string
589  local function write(s)
590    fd:write(s)
591    fd:write('\n')
592  end
593
594  write('// IWYU pragma: private, include "nvim/option_vars.h"')
595
596  -- Generate enums for option flags.
597  for _, o in ipairs(options_meta) do
598    if o.schema and (o.schema.flags or o.schema.flagchars) then
599      write(gen_token_enum(o))
600    end
601  end
602
603  -- Generate valid values (for completion) and, for `dict` schemas, the validation schema.
604  for _, option in ipairs(options_meta) do
605    local values_var = ('opt_%s'):format(option.abbreviation or option.full_name)
606    -- `chars` dispatch tables (gen_chartab) and `flagchars` (gen_token_enum) have no completion
607    -- values; every other schema does.
608    if option.schema and #schema_values(option.schema) > 0 then
609      write(gen_schema_values(values_var, option.schema))
610      if is_dict_option(option) then
611        write(gen_opt_schema(values_var, option.schema))
612      end
613    end
614  end
615
616  fd:close()
617end
618
619--- Emit the chars_tab[] dispatch tables (fcs_tab/lcs_tab) from options with a `char`/`chars`
620--- schema.
621---
622---     #include "options_chartab.generated.h"
623---
624--- @param output_file string
625local function gen_chartab(output_file)
626  local fd = assert(io.open(output_file, 'w'))
627  --- @param s string
628  local function write(s)
629    fd:write(s)
630    fd:write('\n')
631  end
632
633  write('// IWYU pragma: private, include "nvim/optionstr.c"')
634  for _, o in ipairs(options_meta) do
635    if o.schema and o.schema.chars then
636      local abbr = o.abbreviation or o.full_name
637      write('')
638      write(('static const struct chars_tab %s_tab[] = {'):format(abbr))
639      for _, item in ipairs(o.schema.chars) do
640        --- @cast item vim.option_schema.char
641        local name = item[1]
642        local opts = item[3] or {}
643        -- opts.field == false means no storage (NULL cp), e.g. 'multispace'; nil defaults to name.
644        local cp = 'NULL'
645        if opts.field ~= false then
646          cp = ('&%s_chars.%s'):format(abbr, opts.field or name)
647        end
648        local def = opts.def and ('"%s"'):format(opts.def) or 'NULL'
649        local fallback = opts.fallback and ('"%s"'):format(opts.fallback) or 'NULL'
650        write(('  CHARSTAB_ENTRY(%s, "%s", %s, %s),'):format(cp, name, def, fallback))
651      end
652      write('};')
653    end
654  end
655
656  fd:close()
657end
658
659--- Emit an option keyset: a `KeyDict_…` struct + `KeySetLink` + perfect-hash get_field, generated
660--- from a `dict` schema. Consumed by `api_dict_to_keydict()`.
661--- @param output_file string
662local function gen_keysets(output_file)
663  local keyset = require('gen.keyset')
664  local fd = assert(io.open(output_file, 'w'))
665  local function write(s)
666    fd:write(s)
667    fd:write('\n')
668  end
669
670  write('#pragma once')
671  write('')
672  write('#include <stddef.h>')
673  write('')
674  write('#include "nvim/api/private/defs.h"')
675  write('#include "nvim/option_defs.h"')
676
677  local struct_opts = {} --- @type {enum:string,abbr:string,kd:string}[]
678
679  for _, o in ipairs(options_meta) do
680    -- A `dict` schema reifies to a keyset; generate it here.
681    if is_dict_option(o) then
682      -- Mirrors the API's KeyDict codegen with an "Opt" prefix: struct OptKeyDict_<abbr>, and
683      -- <abbr> as the keyset name for the table/hash/HAS_KEY (e.g. HAS_KEY(v, dip, filler)).
684      local abbr = o.abbreviation or o.full_name
685      local kd = 'OptKeyDict_' .. abbr
686      struct_opts[#struct_opts + 1] =
687        { enum = 'kOpt' .. lowercase_to_titlecase(o.full_name), abbr = abbr, kd = kd }
688      local keys = {} --- @type string[]
689      local info = {} --- @type table<string,{field:string,ctype:string}>
690      for _, item in ipairs(o.schema.dict) do
691        local key = type(item) == 'string' and item or item[1]
692        local kind = type(item) == 'string' and 'flag' or item[2]
693        keys[#keys + 1] = key
694        info[key] = {
695          field = c_field_name(key),
696          ctype = keyset_ctype[kind] or 'kObjectTypeBoolean',
697        }
698      end
699
700      -- The schema array (validation grammar) lives in option_vars.generated.h; forward-declare it
701      -- so this header stays self-contained.
702      write('')
703      write(('extern const OptSchemaItem opt_%s_schema[];'):format(abbr))
704      write('')
705      write(("/// '%s'"):format(o.full_name))
706      write(('typedef struct %s {'):format(kd))
707      write(('  OptionalKeys is_set__%s_;'):format(abbr))
708      for _, item in ipairs(o.schema.dict) do
709        local key = type(item) == 'string' and item or item[1]
710        local kind = type(item) == 'string' and 'flag' or item[2]
711        local charsize = keyset_charsize(item)
712        if charsize then
713          write(('  char %s[%d];'):format(c_field_name(key), charsize))
714        else
715          write(('  %s %s;'):format(keyset_ftype[kind] or 'Boolean', c_field_name(key)))
716        end
717      end
718      write(('} %s;'):format(kd))
719      write('')
720
721      local order, hashfun = keyset.hash(abbr, keys)
722      local entry = {} --- @type table<string, gen.keyset.entry>
723      for i, key in ipairs(order) do
724        write(('#define KEYSET_OPTIDX_%s__%s %d'):format(abbr, c_field_name(key), i))
725        entry[key] =
726          { field = info[key].field, type = info[key].ctype, opt_index = i, is_hlgroup = false }
727      end
728      -- `static` (inline): diff.c includes this header for the struct type alone, so a plain `static`
729      -- table/hash/get_field would warn as unused.
730      keyset.emit(write, {
731        name = abbr,
732        get_field = kd .. '_get_field',
733        struct = kd,
734        order = order,
735        hashfun = hashfun,
736        entry = entry,
737        static = true,
738      })
739    end
740  end
741
742  -- Union of all keyset types, for opt_keyset()'s shared storage.
743  write('')
744  write('typedef union {')
745  for _, s in ipairs(struct_opts) do
746    write(('  %s %s;'):format(s.kd, s.abbr))
747  end
748  write('} OptKeyDict;')
749
750  -- Dispatch from option index to its dict schema (opt_dict_schema); NULL for non-dict options.
751  write('')
752  write('static inline const OptDictSchema *opt_dict_schema(OptIndex opt_idx)')
753  write('{')
754  write('  switch (opt_idx) {')
755  for _, s in ipairs(struct_opts) do
756    write(('  case %s: {'):format(s.enum))
757    write(
758      ('    static const OptDictSchema info = { %s_get_field, opt_%s_schema,'):format(s.kd, s.abbr)
759    )
760    write(('                                        sizeof(%s) };'):format(s.kd))
761    write('    return &info;')
762    write('  }')
763  end
764  write('  default:')
765  write('    return NULL;')
766  write('  }')
767  write('}')
768
769  fd:close()
770end
771
772--- @param output_file string
773local function gen_options(output_file)
774  local fd = assert(io.open(output_file, 'w'))
775
776  --- @param ... string
777  local function write(...)
778    local s = table.concat({ ... }, '')
779    fd:write(s)
780    if s:match('^    %.') then
781      fd:write(',')
782    end
783    fd:write('\n')
784  end
785
786  -- Generate options[] array.
787  write([[
788  #include "nvim/ex_docmd.h"
789  #include "nvim/ex_getln.h"
790  #include "nvim/insexpand.h"
791  #include "nvim/mapping.h"
792  #include "nvim/ops.h"
793  #include "nvim/option.h"
794  #include "nvim/optionstr.h"
795  #include "nvim/quickfix.h"
796  #include "nvim/runtime.h"
797  #include "nvim/tag.h"
798  #include "nvim/window.h"
799
800  static vimoption_T options[] = {]])
801
802  for i, o in ipairs(options_meta) do
803    dump_option(i, o, write)
804  end
805
806  write('};')
807
808  fd:close()
809end
810
811local function main()
812  local options_file = arg[1]
813  local options_enum_file = arg[2]
814  local options_map_file = arg[3]
815  local option_vars_file = arg[4]
816  local options_chartab_file = arg[5]
817  local options_keysets_file = arg[6]
818
819  local option_index = gen_enums(options_enum_file)
820  gen_map(options_map_file, option_index)
821  gen_vars(option_vars_file)
822  gen_chartab(options_chartab_file)
823  gen_keysets(options_keysets_file)
824  gen_options(options_file)
825end
826
827main()