robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
398f2c108d
master
1---@diagnostic disable: no-unknown 2if arg [ 1 ] == '--help' then 3( 'Usage:' ) 4( ' ' .. arg [ 0 ] .. ' [-c] target source varname [source varname]...' ) 5( '' ) 6( 'Generates C file with big uint8_t blob.' ) 7( 'Blob will be stored in a static const array named varname.' ) 8os . 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 22local opt =string . match ( arg [ 1 ], '^-(%w)' ) 23if not opt then 24break 25end 26 27options [ opt ] =true 28table . 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 42local source_file =arg [ argi ] 43local modname =arg [ argi + 1 ] 44if modnames [ modname ] then 45error ( string . format ( 'modname %q is already specified for file %q' , modname , modnames [ modname ])) 46end 47modnames [ modname ] =source_file 48 49local varname =string . gsub ( modname , '%.' , '_dot_' ) .. '_module' 50target : write (( 'static const uint8_t %s[] = {\n' ): format ( varname )) 51 52local source =io . open ( source_file , 'r' ) 53or error ( string . format ( "source_file %q doesn't exist" , source_file )) 54local output =source : read ( '*a' ) 55source : close () 56if options . c then 57local prefix =ignorelist [ modname ] and '' or '@' 58local relpath =modname : gsub ( '%.' , '/' ) 59output =string . dump ( assert (( loadstring or load )( output , prefix .. relpath )), false ) 60end 61 62local num_bytes =0 63local MAX_NUM_BYTES =15 -- 78 / 5: maximum number of bytes on one line 64target : write ( ' ' ) 65 66local increase_num_bytes 67increase_num_bytes =function () 68num_bytes =num_bytes + 1 69if num_bytes == MAX_NUM_BYTES then 70num_bytes =0 71target : write ( '\n ' ) 72end 73end 74 75for i =1 , string . len ( output ) do 76local byte =output : byte ( i ) 77target : write ( string . format ( ' %3u,' , byte )) 78increase_num_bytes () 79end 80 81target : write ( ' 0};\n' ) 82if modname ~= '_' then 83table . insert ( 84index_items , 85' { "' .. modname .. '", ' .. varname .. ', sizeof ' .. varname .. ' },\n\n' 86) 87end 88end 89 90target : write ( 'static ModuleDef builtin_modules[] = {\n' ) 91target : write ( table . concat ( index_items )) 92target : write ( '};\n' ) 93 94target : close ()