robin/laufey

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

phaniumfix(lua): don't strip debuginfo in precompile module #39191398f2c108d

master
2.4 KiB94 linesraw
1---@diagnostic disable: no-unknown
2if arg[1] == '--help' then
3  print('Usage:')
4  print('  ' .. arg[0] .. ' [-c] target source varname [source varname]...')
5  print('')
6  print('Generates C file with big uint8_t blob.')
7  print('Blob will be stored in a static const array named varname.')
8  os.exit()
9end
10
11-- Recognized options:
12--   -c   compile Lua bytecode
13local options = {}
14
15local ignorelist = {
16  ['vim._core.editor'] = true,
17  ['vim._core.options'] = true,
18  ['vim.keymap'] = true,
19}
20
21while true do
22  local opt = string.match(arg[1], '^-(%w)')
23  if not opt then
24    break
25  end
26
27  options[opt] = true
28  table.remove(arg, 1)
29end
30
31assert(#arg >= 3 and (#arg - 1) % 2 == 0)
32
33local target_file = arg[1] or error('Need a target file')
34local target = assert(io.open(target_file, 'w'))
35
36target:write('#include <stdint.h>\n\n')
37
38local index_items = {}
39
40local modnames = {}
41for argi = 2, #arg, 2 do
42  local source_file = arg[argi]
43  local modname = arg[argi + 1]
44  if modnames[modname] then
45    error(string.format('modname %q is already specified for file %q', modname, modnames[modname]))
46  end
47  modnames[modname] = source_file
48
49  local varname = string.gsub(modname, '%.', '_dot_') .. '_module'
50  target:write(('static const uint8_t %s[] = {\n'):format(varname))
51
52  local source = io.open(source_file, 'r')
53    or error(string.format("source_file %q doesn't exist", source_file))
54  local output = source:read('*a')
55  source:close()
56  if options.c then
57    local prefix = ignorelist[modname] and '' or '@'
58    local relpath = modname:gsub('%.', '/')
59    output = string.dump(assert((loadstring or load)(output, prefix .. relpath)), false)
60  end
61
62  local num_bytes = 0
63  local MAX_NUM_BYTES = 15 -- 78 / 5: maximum number of bytes on one line
64  target:write(' ')
65
66  local increase_num_bytes
67  increase_num_bytes = function()
68    num_bytes = num_bytes + 1
69    if num_bytes == MAX_NUM_BYTES then
70      num_bytes = 0
71      target:write('\n ')
72    end
73  end
74
75  for i = 1, string.len(output) do
76    local byte = output:byte(i)
77    target:write(string.format(' %3u,', byte))
78    increase_num_bytes()
79  end
80
81  target:write('  0};\n')
82  if modname ~= '_' then
83    table.insert(
84      index_items,
85      '  { "' .. modname .. '", ' .. varname .. ', sizeof ' .. varname .. ' },\n\n'
86    )
87  end
88end
89
90target:write('static ModuleDef builtin_modules[] = {\n')
91target:write(table.concat(index_items))
92target:write('};\n')
93
94target:close()