1#!/usr/bin/env lua 2--[[ minified code follows, see --help text for source location! ]] 3local require=function(modname)if package.loaded[modname]==nil then 4if type(package.preload[modname])~="function"then 5io.stderr:write("module '" .. modname .. "' not found:\n no valid field package.preload['" .. modname .. "']\n") 6return nil 7end 8package.loaded[modname]=package.preload[modname](modname,"package.preload")end 9return package.loaded[modname]end 10package.preload['luke._base']=function() 11local _ENV=require'std.normalize'{}local function fatal(...)local msg=(...)if select('#',...)>1 then 12msg=format(...)end 13stderr:write('luke: fatal: '..msg..'\n')exit(1)end 14return{diagnose=function(predicate,...)if not predicate then 15fatal(...)end 16end,fatal=fatal,} 17end 18package.preload['luke.cli']=function() 19local _ENV=require'std.normalize'{'luke._base','luke.lukefile','luke.platforms','std.functional',}local function version()print[[ 20luke (Luke) 0.2.3 21Written by Gary V. Vaughan <gary@gnu.org>, 2014 22 23Copyright (C) 2022, Gary V. Vaughan 24Luke comes with ABSOLUTELY NO WARRANTY. 25You may redistribute copies of Luke under the terms of the MIT license; 26it may be used for any purpose at absolutely no cost, without permission. 27See <https://mit-license.org> for details. 28]]exit(0)end 29local function help()print[[ 30Usage: luke [OPTION]... [VAR=VALUE]... [TARGET] 31 32Use the source, Luke! 33 34 --help print this help, then exit 35 --version print version number, then exit 36 --file=FILE use FILE instead of lukefile 37 --value=NAME print the value of variable NAME 38 --quiet without any output 39 --verbose provide more progress output 40 41Each TARGET can be one of the module table keys from lukefile, or: 42 43 all build all targets in lukefile 44 install copy all built targets to $PREFIX 45 46If no TARGET is given, 'all' is implied. 47 48Report bugs to https://github.com/gvvaughan/luke/issues.]]exit(0)end 49local function opterr(...)local msg=(...)if select('#',...)>1 then 50msg=format(...)end 51msg=gsub(msg,'%.$','')stderr:write('luke: error: '..msg..'.\n')stderr:write("luke: try '"..arg[0].." --help' for help.\n")exit(2)end 52local function display(...)return stdout:write(concat{...})end 53local function dump(...)local s=concat(map(list(...),str))if len(s)>0 then 54gsub(concat(map(list(...),str)),'\n*$','\n'):gsub('(.-)\n',function(line)stderr:write(' DEBUG: '..line..'\n')end)end 55end 56local function interpolate_to_substitute(s)return(gsub(s,'%$([%w_]+)','@%1@'))end 57return{parse_arguments=function(args)local r={clidefs={},valreqs={},fname='lukefile',install={},log=nop,targets={},verbose=nop,write=display,}map(args,function(opt)case(opt,{['--debug']=function()r.log=dump 58end,['%-%-file=(.+)']=function(optarg)r.fname=optarg 59end,['%-%-value=(.+)']=function(optarg)r.valreqs[#r.valreqs+1]=optarg 60end,['--quiet']=function()r.write=nop 61end,['--verbose']=function()r.verbose=display 62end,['--help']=help,['--version']=version,['([^-][^=]-)=(.+)']=function(name,value)r.clidefs[name]=value 63end,function(opt)if match(opt,'^-')~=nil then 64opterr("unrecognized option '%s'",opt)end 65append(r.targets,opt)end,})end)return r 66end,validate_arguments=function(parsed)local luke,err=loadluke(parsed.fname)diagnose(luke~=nil,'bad %s: %s',parsed.fname,err)if isempty(luke.modules or{})then 67fatal("no modules table in '%s', nothing to build",parsed.fname)end 68local targets=call(function()if isempty(parsed.targets)or contains(parsed.targets,'all')then 69return except(flatten(parsed.targets,keys(luke.modules)),'all')end 70local r=filter(parsed.targets,function(target)if target~='install'and luke.modules[target]==nil then 71fatal("no rule to make target '%s'",target)end 72return true 73end)assert(len(r)>0,"no build targets specified")return r 74end)local install 75local build=pluck(targets,luke.modules)if contains(targets,'install')then 76install=build or luke.modules 77end 78luke.modules=build 79if isempty(luke.modules)then 80luke.external_dependencies=nil 81end 82luke.substitute=merge(luke.substitute or{},{package=interpolate_to_substitute(luke.package),version=interpolate_to_substitute(luke.version),})luke.variables=merge(luke.variables or{},collect_variables(luke),{LUA_DIR='/usr',LUA_BINDIR='$LUA_DIR/bin',LUA_INCDIR='$LUA_DIR/include/lua$LUAVERSION',LUA_LIBDIR='$LUA_DIR/lib',objdir=platforms[1],package=luke.package,version=luke.version,})return{clidefs=parsed.clidefs,install=install,log=parsed.log,luke=luke,valreqs=parsed.valreqs,verbose=parsed.verbose,write=parsed.write,}end,} 83end 84package.preload['luke.compile']=function() 85local _ENV=require'std.normalize'{'luke._base','luke.environment','std.functional','type.context-manager','type.path',SHELLMETACHARS='[%s%$"]',}local function spawn(env,...)local command=interpolate(env,concat({...},' '))return with(TmpFile(),TmpFile(),function(out,err)local pipe=concat{command,' >',out.filename,' 2>',err.filename,'; printf $?'}return tonumber(slurp(Pipe(pipe))),slurp(File(err.filename)),slurp(File(out.filename))end)end 86local function run(L,env,command)L.write(interpolate(env,concat(command,' ')),'\n')local status,err,out=spawn(env,unpack(command))if status~=0 then 87if L.write==nop then 88stdout:write(concat(command,' ')..'\n')end 89stderr:write(err..'\n')end 90return status,out,err 91end 92local function defines(env,deftables)return zip_with(merge({},unpack(deftables)),function(name,value)local fmt=cond({[int(value)==1]='-D%s'},{[match(value,SHELLMETACHARS)~=nil]="-D%s='%s'"},{[true]='-D%s=%s'})return format(fmt,name,value)end)end 93local function incdirs(...)return map(flatten(...),function(v)return'-I'..v 94end)end 95local function libdirs(...)return map(flatten(...),function(v)return'-L'..v 96end)end 97local function c_module_path(objdir,name)return format('%s/%s.$LIB_EXTENSION',objdir,gsub(name,'%.','/'))end 98local function c_source(module,objdir)local path=gsub(module,'%.','/')local src=c_module_path(objdir,path)return src,(gsub('$INST_LIBDIR/'..path,'/[^/]+$',''))end 99local function lua_source(module,src)local abspath='$INST_LUADIR/'..gsub(module,'%.','/')if match(src,'/init%.lua$')then 100abspath=abspath..'/init'end 101abspath=abspath..'.lua'return src,(gsub(abspath,'/[^/]+%.lua$',''))end 102local function module_to_path(module,sources,objdir)return dropuntil(sources,function(source)return case(source,{['.*%.[ch]']=bind(c_source,{module,objdir}),['(.*%.[ch])%.in']=bind(c_source,{module,objdir}),['.*%.lua']=bind(lua_source,{module}),['(.*%.lua)%.in']=bind(lua_source,{module}),function(src)fatal("unsupported source type '%s'",src)end,})end)end 103return{build_c_module=function(L,env,luke,name)local rules=luke.modules[name]local c_module=c_module_path(luke.variables.objdir,name)local command={'$MAKEDIRS',dirname(c_module)}local status,err,out=spawn(env,unpack(command))if status~=0 then 104stdout:write(concat(command,' ')..'\n')stderr:write(err..'\n')exit(status)end 105return run(L,env,flatten('$CC $CFLAGS $LIBFLAG $PKGFLAGS $CPPFLAGS',defines(env,except(list(rules.defines,luke.defines),nil)),incdirs(rules.incdirs,luke.incdirs),rules.sources,'-o',c_module,'$LDFLAGS',libdirs(rules.libdirs,luke.libdirs),'$LIBS',rules.libraries,luke.libraries))end,c_modules=function(modules)return filter(keys(modules),function(name)return dropuntil(modules[name].sources,bind(match,{[2]='%.[ch]$'}))end)end,incdirs=incdirs,install_modules=function(L,env,luke,modules)return reduce(keys(modules),0,function(status,name)if status==0 then 106local src,dir=module_to_path(name,modules[name].sources,luke.variables.objdir)if not exists(interpolate(env,dir))then 107status=run(L,env,{'$MAKEDIRS',dir})end 108if status==0 then 109status=run(L,env,{'$INSTALL',src,dir..'/'})end 110end 111return status 112end)end,libdirs=libdirs,run_command=run,spawn=spawn,} 113end 114package.preload['luke.configure']=function() 115local _ENV=require'std.normalize'{'luke._base','luke.compile','luke.environment','std.functional','type.context-manager','type.dict',CCPROGS={'cc','gcc','clang'},}local function logspawn(L,env,...)local status,err=spawn(env,...)if status~=0 and err~=''then 116L.log(err)end 117return status 118end 119local function checking(L,...)L.verbose('checking ',concat({...},' '),'... ')end 120local function found_library(L,x)if x==nil or x==''then 121L.verbose'none required'elseif isempty(x)then 122L.verbose'not supported'else 123L.verbose(x)end 124L.verbose'\n'return x 125end 126local function found_prog(L,x)L.verbose(x and'yes\n'or'no\n')return x 127end 128local function found_result(L,x)L.verbose(x==0 and'yes\n'or'no\n')return x~=0 and 0 or 1 129end 130local function bindirs(...)return map(flatten(...),function(v)return v..':'end)end 131local function compile_command(L,env,config,filename)local command=flatten('$CC','-c','$CFLAGS',incdirs(config.incdir),'$CPPFLAGS',filename)L.log(interpolate(env,concat(command,' ')))return unpack(command)end 132local function link_command(L,env,config,a_out,source,lib)local command=flatten('$CC','$CFLAGS',incdirs(config.incdir),'$CPPFLAGS','-o',a_out,source,libdirs(config.libdir),'$LDFLAGS',lib,'$libs',CONFIGENV.libs)L.log(interpolate(env,concat(command,' ')))return unpack(command)end 133local function check_executable_in_path(L,env,config,prog)local PATH=concat(bindirs(config.bindir))..getenv('PATH')local found=dropuntil(gmatch(PATH,'[^:]+'),function(path)local progpath=path..'/'..prog 134return with(File(progpath,'r'),function(h)return h and isfile(h.context)and progpath or nil 135end)end)L.log(found and'found '..found or prog..' not found')return found~=nil 136end 137local function check_header_compile(L,env,config,header,extra_hdrs)return with(CTest(),function(conftest)conftest:write(format('%s\n#include "%s"\n',extra_hdrs,header))return logspawn(L,env,compile_command(L,env,config,conftest.filename))end)end 138local function check_struct_member_compile(L,env,config,structname,member,extra_hdrs)return with(CTest(),function(conftest)conftest:write(format([[ 139%s 140int main () { 141static %s aggr; 142if (sizeof aggr.%s) 143 return 0; 144return 0; 145} 146]],extra_hdrs,structname,member))return logspawn(L,env,compile_command(L,env,config,conftest.filename))end)end 147local function try_link(L,env,config,lib,symbol)return with(CTest(),TmpFile(),function(conftest,a_out)conftest:write(format([[ 148/* Override any GCC internal prototype to avoid an error. 149 Use char because int might match the return type of a GCC 150 builtin and then its argument prototype would still apply. */ 151char %s (); 152int main () { 153return %s (); 154} 155]],symbol,symbol))return logspawn(L,env,link_command(L,env,config,a_out.filename,conftest.filename,lib))end)end 156local function try_compile(L,env,config,headers)return with(CTest(),TmpFile(),function(conftest,a_out)conftest:write(format([[ 157%s 158#if !defined %s || %s == -1 159choke me 160#endif 161int 162main() 163{ 164return 0; 165} 166]],headers,config.ifdef,config.ifdef))return logspawn(L,env,link_command(L,env,config,a_out.filename,conftest.filename))end)end 167local function check_func_decl(L,env,config,fname,extra_hdrs)return with(CTest(),function(conftest)conftest:write(format([[ 168%s 169int 170main() 171{ 172#ifndef %s 173(void) %s; 174#endif 175return 0; 176} 177]],extra_hdrs,fname,fname))return logspawn(L,env,compile_command(L,env,config,conftest.filename))end)end 178local function check_func_link(L,env,config,fname)return with(CTest(),TmpFile(),function(conftest,a_out)conftest:write(format([[ 179/* Define to an innocous variant, in case <limits.h> declares it. 180 For example, HP-UX 11i <limits,h> declares gettimeofday. */ 181#define %s innocuous_%s 182 183/* System header to define __stub macros and hopefully few prototypes, 184 which can conflict with declaration below. 185 Prefer <limits.h> to <assert.h> if __STDC__ is defined, since 186 <limits.h> exists even on freestanding compilers. */ 187 188#ifdef __STDC__ 189# include <limits.h> 190#else 191# include <assert.h> 192#endif 193 194#undef %s 195 196/* Override any GCC internal prototype to avoid an error. 197 Use char because int might match the return type of a GCC 198 builtin and then its argument prototype would still apply. */ 199char %s (); 200 201/* The GNU C library defines this for functions which it implements 202 to always fail with ENOSYS. Some functions are actually named 203 something starting with __ and the normal name is an alias. */ 204#if defined __stub_%s || defined __stub__%s 205choke me 206#endif 207 208int main () { 209return %s (); 210} 211]],fname,fname,fname,fname,fname,fname,fname))return logspawn(L,env,link_command(L,env,config,a_out.filename,conftest.filename))end)end 212local function add_external_deps(env,config,prefix)if prefix~=nil then 213for k,v in next,{bindir='$%s_BINDIR',incdir='$%s_INCDIR',libdir='$%s_LIBDIR'}do 214local envvar=interpolate(env,format(v,prefix))if envvar~=''then 215config[k]=envvar 216end 217end 218end 219end 220local function format_includes(includes)return map(includes or{},function(include)return format('#include "%s"',include)end)end 221local configure=setmetatable(OrderedDict({checkprog=function(L,env,config)return dropuntil(config.progs,function(prog)checking(L,'for',prog)if found_prog(L,check_executable_in_path(L,env,config,prog))then 222return prog 223end 224end)or fatal('cannot find '..config.checkprog)end},{checkheader=function(L,env,config)checking(L,'for',config.checkheader)local extra_hdrs=concat(format_includes(config.includes),'\n')return found_result(L,check_header_compile(L,env,config,config.checkheader,extra_hdrs))end},{checkdecl=function(L,env,config)checking(L,'whether',config.checkdecl,'is declared')local extra_hdrs=concat(format_includes(config.includes),'\n')return found_result(L,check_func_decl(L,env,config,config.checkdecl,extra_hdrs))end},{checksymbol=function(L,env,config)checking(L,'for library containing',config.checksymbol)if config.ifdef~=nil then 225local headers=concat(format_includes(config.includes),'\n')if try_compile(L,env,config,headers)~=0 then 226return found_library(L,{})end 227end 228local libraries,symbol=config.libraries,config.checksymbol 229local trylibs=reduce(libraries,{''},function(r,lib)append(r,'-l'..lib)end)return dropuntil(trylibs,function(lib)if try_link(L,env,config,lib,symbol)==0 then 230if lib~=''then 231if CONFIGENV.libs~=''then 232CONFIGENV.libs=' '..CONFIGENV.libs 233end 234CONFIGENV.libs=lib..CONFIGENV.libs 235end 236return found_library(L,lib)end 237end)or call(function()L.verbose'\n'fatal("required symbol '%s' not found in any of libc, lib%s",symbol,concat(libraries,', lib'))end)end},{checkfunc=function(L,env,config)checking(L,'for',config.checkfunc)return found_result(L,check_func_link(L,env,config,config.checkfunc))end},{checkmember=function(L,env,config)checking(L,'for',config.checkmember)local extra_hdrs=concat(format_includes(config.includes),'\n')local i=find(config.checkmember,'%.')local structname=sub(config.checkmember,1,i-1)local member=sub(config.checkmember,i+1)return found_result(L,check_struct_member_compile(L,env,config,structname,member,extra_hdrs))end}),{__call=function(self,L,env,config,prefix)return case(type(config),{['number']=function()return str(config)end,['string']=function()return config 238end,['table']=function()return dropuntil(self,function(fname)if config[fname]~=nil then 239add_external_deps(env,config,prefix)return apply(self[fname],list(L,env,config))end 240end)or fatal("unable to configure with keys '%s'",concat(keys(config),"', '"))end,function(type)fatal("unsupported configure type '%s'",type)end,})end,})return{config_compiler=function(L,env)local CC=env.CC 241if CC==nil then 242CC=configure(L,env,{checkprog='C compiler',progs=CCPROGS})env=makeenv(env,{CC=CC})end 243checking(L,interpolate(env,'whether $CC works'))local cm=CTest()local works,err=with(cm,function(conftest)conftest:write('typedef int x;\n')return spawn(env,'$compile',conftest.filename)end)if works~=0 then 244L.verbose'no\n'L.log(interpolate(env,'$compile '..cm.filename))if err and err~=''then 245L.log(err)end 246fatal('could not find a working C compiler')end 247found_prog(L,CC)return env 248end,config_ldoc=function(L,env)local LDOC=env.LDOC 249if LDOC==nil then 250LDOC=configure(L,env,{checkprog='LDocs generator',progs={'ldoc','true'}})env=makeenv(env,{LDOC=LDOC})end 251return env 252end,configure=configure,} 253end 254package.preload['luke.environment']=function() 255local _ENV=require'std.normalize'{'luke.platforms','std.functional',LUAVERSION=string.gsub(_VERSION,'[^0-9%.]+',''),}local env_mt={__index=function(self,varname)return dropuntil(self,function(env)local value=env[varname]if value~=nil then 256self[varname]=value 257return value 258end 259end)end,}local function interpolate_with(pattern,env,s)local r=''while r~=s do 260r=s 261s=gsub(r,pattern,function(varname)return env[varname]or''end)end 262return r 263end 264local function isenv(t)return getmetatable(t)==env_mt 265end 266return{CONFIGENV={compile='$CC -c $CFLAGS $CPPFLAGS',libs='',link='$CC $CFLAGS $CPPFLAGS $LDFLAGS',},DEFAULTENV=filter_platforms{LUAVERSION=LUAVERSION,PREFIX='/usr/local',INST_LIBDIR='$PREFIX/lib/lua/$LUAVERSION',INST_LUADIR='$PREFIX/share/lua/$LUAVERSION',LIB_EXTENSION='so',OBJ_EXTENSION='o',INSTALL='cp',MAKEDIRS='mkdir -p',CFLAGS='-O2',platforms={macosx={LIBFLAG='-fPIC -bundle -undefined dynamic_lookup -all_load',},LIBFLAG='-shared -fPIC',},},SHELLENV=setmetatable({},{__index=function(_,v)return getenv(v)end,}),expand=bind(interpolate_with,{'@([^@]+)@'}),interpolate=bind(interpolate_with,{'%$([%w_]+)'}),makeenv=function(...)local env=reduce(except(list(...),nil),function(r,t)if isenv(t)then 267map(t,bind(append,{r}))else 268append(r,t)end 269end)return setmetatable(env,env_mt)end,} 270end 271package.preload['luke']=function() 272local _ENV=require'std.normalize'{'luke.cli','luke.compile','luke.configure','luke.environment','luke.lukefile','std.functional',}local function run_ldocs(L,env,ldocs)return run_command(L,env,flatten{'$LDOC -c',ldocs.sources,'.'})end 273local function build_modules(L,env)local conf=makeenv(CONFIGENV,env)if not isempty(L.luke.ldocs or{})then 274conf=config_ldoc(L,conf)env=makeenv(env,{LDOC=conf.LDOC})end 275local c=c_modules(L.luke.modules)if not isempty(c)then 276conf=config_compiler(L,conf)env=makeenv(env,{CC=conf.CC})end 277L.luke=run_configs(L,conf,L.luke)local substitute=makeenv(L.clidefs,L.luke.substitute,SHELLENV)L.luke=run_templates(L,substitute,L.luke)local status=dropuntil(c,isnonzero,function(name)return build_c_module(L,env,L.luke,name)end)or 0 278if status==0 and not isempty(L.luke.ldocs or{})then 279status=run_ldocs(L,env,L.luke.ldocs)end 280return status 281end 282return{main=function(args)local L=validate_arguments(parse_arguments(args))local env=makeenv(L.clidefs,L.luke.variables,DEFAULTENV,SHELLENV)local status=0 283if not isempty(L.valreqs)then 284map(L.valreqs,function(name)print(interpolate(env,concat{name,"='$",name,"'"}))end)exit(0)end 285if status==0 and not isempty(L.luke.modules or{})then 286status=build_modules(L,env)end 287if status==0 then 288status=install_modules(L,env,L.luke,L.install)end 289return status 290end,} 291end 292package.preload['luke.lukefile']=function() 293local _ENV=require'std.normalize'{'luke._base','luke.configure','luke.environment','luke.platforms','std.functional','type.context-manager',}local function has_anykey(t,keylist)return any(map(keylist,function(k)return t[k]~=nil 294end))end 295local function isconfig(x)return istable(x)and has_anykey(x,configure)end 296local function collect_configs(luke,modulename,configs)configs=configs or{}for k,v in next,luke do 297if isconfig(v)then 298append(configs,{t=luke,k=k,module=modulename})elseif istable(v)then 299if k=='modules'or k=='external_dependencies'then 300for name,rules in next,v do 301collect_configs(rules,name,configs)end 302else 303collect_configs(v,modulename,configs)end 304end 305end 306return configs 307end 308local function deepcopy(t)return mapvalues(t,function(v)return case(type(v),{['table']=function()return deepcopy(v)end,v,})end)end 309local weighting=setmetatable(copy(configure),{__call=function(self,config)local t=config.t[config.k]for i=1,len(self)do 310if t[self[i]]~=nil then 311return i 312end 313end 314end})local function config_cmp(a,b)return weighting(a)<weighting(b)end 315local function fill_templates(env,src,dest)with(File(dest,'w'),function(cm)for line in lines(src)do 316cm:write(expand(env,line)..'\n')end 317end)return dest 318end 319local function rewrite_template_files(L,env,source)return case(source,{['(.+)%.in']=function(r)L.write('creating '..r..'\n')return fill_templates(env,r..'.in',r)end,source,})end 320local function collect_variables(luke,variables)for k,v in next,luke do 321if k=='external_dependencies'then 322map(keys(v),function(name)local rootdir=concat{'$',name,'_DIR'}variables[name..'_DIR']='/usr'variables[name..'_BINDIR']=rootdir..'/bin'variables[name..'_INCDIR']=rootdir..'/include'variables[name..'_LIBDIR']=rootdir..'/lib'end)elseif istable(v)then 323collect_variables(v,variables)end 324end 325return variables 326end 327local function normalize_configs(config)return cond({[not istable(config)]=config,},{[not isconfig(config)]=function()return mapvalues(config,normalize_configs)end,},{[true]=function()local keymap={include='includes',prog='progs',library='libraries',}return foldkeys(keymap,config,function(a,b)local r=istable(a)and copy(a)or{a}b=istable(b)and b or{b}return reduce(b,r,function(v)append(r,v)end)end)end,})end 328local function normalize_rules(rules)return case(type(rules),{['nil']=nop,['string']=function()return{sources={rules}}end,['table']=function()if len(rules)>0 then 329return{sources=rules}elseif isstring(rules.sources)then 330return merge({sources={rules.sources}},normalize_configs(rules))end 331return normalize_configs(rules)end,function(v)fatal("unsupported rule type '%s'",v)end,})end 332local function unwrap_external_dependencies(luke)if istable(luke.external_dependencies)then 333for prefix,config in next,luke.external_dependencies do 334if istable(config)and next(config)and config.library~=''then 335luke.incdirs=append(luke.incdirs or{},format('$%s_INCDIR',prefix))luke.libdirs=append(luke.libdirs or{},format('$%s_LIBDIR',prefix))luke.libraries=append(luke.libraries or{},config.library)end 336end 337luke.external_dependencies=nil 338end 339return luke 340end 341return{loadluke=function(filename)local content,err=slurp(File(filename))if content==nil then 342return nil,err 343end 344local r={}local chunk,err=loadstring(content,filename,r)if chunk==nil then 345return nil,"Error loading file: "..err 346end 347local ok,err=pcall(chunk)if not ok then 348return nil,"Error running file: "..err 349end 350r=filter_platforms(r)r.external_dependencies=normalize_configs(r.external_dependencies)r.ldocs=normalize_rules(r.ldocs)r.modules=mapvalues(r.modules,normalize_rules)return r 351end,collect_variables=function(luke)return collect_variables(luke,{})end,run_configs=function(L,env,luke)local r=deepcopy(luke)local all_configs=collect_configs(r)sort(all_configs,config_cmp)map(all_configs,function(config)config.t[config.k]=configure(L,env,config.t[config.k],config.module)end)return unwrap_external_dependencies(r)end,run_templates=function(L,env,luke)local r=copy(luke)local rewrite=bind(rewrite_template_files,{L,env})r.modules=mapvalues(r.modules,function(rules)rules.sources=map(rules.sources,rewrite)end)if r.ldocs then 352r.ldocs.sources=map(r.ldocs.sources,rewrite)end 353return r 354end,} 355end 356package.preload['luke.platforms']=function() 357local _ENV=require'std.normalize'{'std.functional',}local CANON={['AIX']=list('aix','unix'),['FreeBSD']=list('freebsd','bsd','unix'),['OpenBSD']=list('openbsd','bsd','unix'),['NetBSD']=list('netbsd','bsd','unix'),['Darwin']=list('macosx','bsd','unix'),['Linux']=list('linux','unix'),['SunOS']=list('solaris','unix'),['^CYGWIN']=list('cygwin','unix'),['^MSYS']=list('msys','cygwin','unix'),['^Windows']=list('win32','windows'),['^MINGW']=list('mingw32','win32','windows'),['^procnto']=list('qnx'),['QNX']=list('qnx'),['Haiku']=list('haiku','unix'),}local ALLPLATFORMS=reduce(values(CANON),function(acc,platforms)map(platforms,function(v)acc[v]=true 358end)end)local function match_uname(canon,uname,x)return match(uname,x)and canon[x]end 359local function toplatforms(canon,uname)local literalkeys,patternkeys=partition(keys(canon),function(k)return sub(k,1,1)~='^'end)return(pluck(literalkeys,canon)or{})[uname]or dropuntil(map(patternkeys,bind(match_uname,{canon,uname})))or list('unix')end 360local supported=toplatforms(CANON,popen('uname -s'):read'*l')local function isplatform(x)return ALLPLATFORMS[x]~=nil 361end 362local function filter_platforms(t,using,predicate)local r,supported,isplatform={},using or supported,predicate or isplatform 363for k,v in next,t do 364if k=='platforms'then 365local matches=filter(supported,bind(get,{v}))local default=except(keys(v),isplatform)merge(r,hoist(matches,v)or pluck(default,v))elseif istable(v)then 366r[k]=filter_platforms(v,supported)else 367r[k]=r[k]or v 368end 369end 370return r 371end 372return{filter_platforms=filter_platforms,platforms=supported,toplatforms=toplatforms,} 373end 374package.preload['std.functional']=function() 375local _ENV=require'std.normalize'{destructure=next,isfile=function(x)return io.type(x)=='file'end,wrap=coroutine.wrap,yield=coroutine.yield,}local function apply(fn,argu)assert(fn~=nil,'cannot apply nil-valued function')if iscallable(fn)then 376return fn(unpack(argu))end 377return fn 378end 379local function call(fn,...)assert(fn~=nil,'cannot call nil-valued function')if iscallable(fn)then 380return fn(...)end 381return fn 382end 383local function wrapnonnil(iterator)return function(...)local r=list(iterator(...))if r[1]~=nil then 384return r 385end 386end 387end 388local function each(seq)if type(seq)=='function'then 389return wrapnonnil(seq)end 390local i,n=0,int(seq.n)or len(seq)return function()if i<n then 391i=i+1 392return list(seq[i])end 393end 394end 395local function eq(x)return function(y)return x==y 396end 397end 398local function isnonnil(x)return x~=nil 399end 400local function mkpredicate(x)return type(x)=='function'and x or eq(x)end 401local function except(seq,predicate)predicate=mkpredicate(predicate)local r={}for valu in each(seq)do 402if not predicate(unpack(valu))then 403r[#r+1]=unpack(valu)end 404end 405return r 406end 407local function visit(x)if type(x)=='table'then 408for valu in each(x)do 409visit(unpack(valu))end 410else 411yield(x)end 412end 413local function flatten(...)local r={}for v in wrap(visit),except(list(...),nil)do 414r[#r+1]=v 415end 416return r 417end 418return{any=function(seq)for valu in each(seq)do 419if unpack(valu)then 420return true 421end 422end 423return false 424end,apply=apply,bind=function(fn,bound)local n=bound.n or maxn(bound)return function(...)local argu,unbound=copy(bound),list(...)local i=1 425for j=1,unbound.n do 426while argu[i]~=nil do 427i=i+1 428end 429argu[i],i=unbound[j],i+1 430end 431bound.n=n>=i and n or i-1 432return apply(fn,argu)end 433end,call=call,case=function(s,branches)if branches[s]~=nil then 434return call(branches[s],s)end 435local DEFAULT=1 436for pattern,fn in next,branches do 437if pattern~=DEFAULT then 438local argu=list(match(s,'^'..pattern..'$'))if argu[1]~=nil then 439return apply(fn,argu)end 440end 441end 442local default=branches[DEFAULT]if iscallable(default)then 443return call(default,s)end 444return default 445end,cond=function(...)for clauseu in each(list(...))do 446local expr,consequence=destructure(unpack(clauseu))if expr then 447return call(consequence,expr)end 448end 449end,contains=function(seq,predicate)if type(predicate)~='function'then 450predicate=eq(predicate)end 451for valu in each(seq)do 452if predicate(unpack(valu))then 453return true 454end 455end 456end,destructure=destructure,dropuntil=function(seq,predicate,block)if block==nil then 457predicate,block=isnonnil,predicate 458end 459if block~=nil then 460for valu in each(seq)do 461local r=list(block(unpack(valu)))if predicate(unpack(r))then 462return unpack(r)end 463end 464else 465for r in each(seq)do 466if predicate(unpack(r))then 467return unpack(r)end 468end 469end 470end,except=except,filter=function(seq,predicate)predicate=mkpredicate(predicate)local r={}for valu in each(seq)do 471if predicate(unpack(valu))then 472r[#r+1]=unpack(valu)end 473end 474return r 475end,flatten=flatten,foldkeys=function(keymap,dict,combinator)local r={}for k,v in next,dict or{}do 476local key=keymap[k]if key then 477r[key]=combinator(v,dict[key])else 478r[k]=r[k]or v 479end 480end 481return r 482end,get=function(dict,key)return(dict or{})[key]end,hoist=function(keylist,dict)local r={}for keyu in each(keylist)do 483merge(r,dict[unpack(keyu)])end 484return next(r)and r or nil 485end,id=function(...)return...end,isempty=function(x)return type(x)=='table'and not next(x)end,isfile=isfile,isfunction=function(x)return type(x)=='function'end,isnil=function(x)return x==nil 486end,isstring=function(x)return type(x)=='string'end,istable=function(x)return type(x)=='table'end,isnonzero=function(x)return x~=0 487end,keys=function(iterable)local r=list()for k in next,iterable or{}do 488append(r,k)end 489return r 490end,map=function(seq,block)local r=list()for valu in each(seq)do 491append(r,block(unpack(valu)))end 492return r 493end,mapvalues=function(iterable,block)local r={}for k,v in next,iterable or{}do 494r[k]=block(v)or v 495end 496return r 497end,nop=function()end,partition=function(seq,block)local r,s=list(),list()for valu in each(seq)do 498append(block(unpack(valu))and r or s,unpack(valu))end 499return r,s 500end,pluck=function(keylist,dict)local r={}for keyu in each(keylist)do 501local key=unpack(keyu)r[key]=dict[key]end 502return next(r)and r or nil 503end,reduce=function(seq,acc,block)if block==nil then 504acc,block={},acc 505end 506for valu in each(seq)do 507acc=block(acc,unpack(valu))or acc 508end 509return acc 510end,values=function(iterable)local r=list()for _,v in next,iterable or{}do 511append(r,v)end 512return r 513end,zip_with=function(iterable,block)local r=list()for k,v in next,iterable or{}do 514append(r,block(k,v))end 515return r 516end,} 517end 518package.preload['std.normalize']=function() 519local ceil=math.ceil 520local concat=table.concat 521local config=package.config 522local getmetatable=getmetatable 523local loadstring=loadstring 524local match=string.match 525local next=next 526local pack=table.pack or function(...)return{n=select('#',...),...}end 527local setfenv=setfenv 528local sort=table.sort 529local tointeger=math.tointeger 530local tonumber=tonumber 531local tostring=tostring 532local type=type 533local unpack=table.unpack or unpack 534local dirsep,pathsep,pathmark,execdir,igmark=match(config,'^([^\n]+)\n([^\n]+)\n([^\n]+)\n([^\n]+)\n([^\n]+)')local function copy(iterable)local r={}for k,v in next,iterable or{}do 535r[k]=v 536end 537return r 538end 539local int=(function(f)if f==nil then 540return function(x)if type(x)=='number'and ceil(x)-x==0.0 then 541return x 542end 543end 544elseif f'1'~=nil then 545return function(x)if type(x)=='number'then 546return tointeger(x)end 547end 548end 549return f 550end)(tointeger)local function iscallable(x)return type(x)=='function'and x or(getmetatable(x)or{}).__call 551end 552local function getmetamethod(x,n)return iscallable((getmetatable(x)or{})[tostring(n)])end 553local function rawlen(x)if type(x)~='table'then 554return#x 555end 556local n=#x 557for i=1,n do 558if x[i]==nil then 559return i-1 560end 561end 562return n 563end 564local function len(x)local m=getmetamethod(x,'__len')return m and m(x)or rawlen(x)end 565if setfenv then 566local _loadstring=loadstring 567loadstring=function(s,filename,env)chunk,err=_loadstring(s,filename)if chunk~=nil and env~=nil then 568setfenv(chunk,env)end 569return chunk,err 570end 571else 572loadstring=function(s,filename,env)return load(s,filename,"t",env)end 573setfenv=function()end 574end 575local function keysort(a,b)if int(a)then 576return int(b)==nil or a<b 577else 578return int(b)==nil and tostring(a)<tostring(b)end 579end 580local function str(x,roots)roots=roots or{}local function stop_roots(x)return roots[x]or str(x,copy(roots))end 581if type(x)~='table'or getmetamethod(x,'__tostring')then 582return tostring(x)else 583local buf={'{'}roots[x]=tostring(x)local n,keys=1,{}for k in next,x do 584keys[n],n=k,n+1 585end 586sort(keys,keysort)local kp 587for _,k in next,keys do 588if kp~=nil and k~=nil then 589buf[#buf+1]=type(kp)=='number'and k~=kp+1 and'; 'or', 'end 590if k==1 or type(k)=='number'and k-1==kp then 591buf[#buf+1]=stop_roots(x[k])else 592buf[#buf+1]=stop_roots(k)..'='..stop_roots(x[k])end 593kp=k 594end 595buf[#buf+1]='}'return concat(buf)end 596end 597return setmetatable({append=function(seq,v)local n=(int(seq.n)or len(seq))+1 598seq.n,seq[n]=n,v 599return seq 600end,arg=arg,assert=assert,char=string.char,close=io.close,concat=concat,copy=copy,dirsep=dirsep,exit=os.exit,find=string.find,format=string.format,getenv=os.getenv,getmetatable=getmetatable,getmetamethod=getmetamethod,gmatch=string.gmatch,gsub=string.gsub,int=int,iscallable=iscallable,len=len,lines=io.lines,list=pack,loadstring=loadstring,match=string.match,maxn=function(iterable)local n=0 601for k,v in next,iterable or{}do 602local i=int(k)if i and i>n then 603n=i 604end 605end 606return n 607end,merge=function(r,...)local argu=pack(...)for i=1,argu.n do 608for k,v in next,argu[i]or{}do 609r[k]=r[k]or v 610end 611end 612return r 613end,next=next,open=io.open,pack=pack,pcall=pcall,pop=function(seq)local n,r=seq.n or len(seq)r,seq[n]=seq[n]if int(seq.n)and seq.n>0 then 614seq.n=seq.n-1 615end 616return r 617end,popen=io.popen,print=print,rawget=rawget,rawset=rawset,rep=string.rep,rm=os.remove,select=select,setmetatable=setmetatable,sort=sort,stderr=io.stderr,stdout=io.stdout,str=str,sub=string.sub,tmpname=os.tmpname,tonumber=tonumber,type=type,unpack=function(seq,i,j)return unpack(seq,int(i)or 1,int(j)or int(seq.n)or len(seq))end,write=io.write,},{__call=function(self,env,level)local userenv,level=copy(self),level or 1 618for name,value in next,env do 619if int(name)and type(value)=='string'then 620for k,v in next,(require(value))do 621userenv[k]=userenv[k]or v 622end 623else 624userenv[name]=value 625end 626end 627setfenv(level+1,userenv)return userenv 628end,}) 629end 630package.preload['type.context-manager']=function() 631local _ENV=require'std.normalize'{'std.functional',}local contextmanager_mt={__index=function(self,key)if iscallable(self.context[key])then 632return function(_,...)return self.context[key](self.context,...)end 633end 634if key=='filename'then 635return self[1]end 636end,}local function ContextManager(release,acquire,...)local fh,err=acquire(...)if not fh then 637return nil,err 638end 639local cm={context=fh,release=release,n=select("#",...),...}if cm.context~=nil then 640setmetatable(cm,contextmanager_mt)end 641return cm 642end 643local function context_close(cm)return isfile(cm.context)and close(cm.context)end 644local function with(...)local argu=list(...)local block=pop(argu)local r=list(apply(block,argu))map(argu,function(cm)if cm~=nil then 645cm:release()end 646end)return unpack(r)end 647return{ContextManager=ContextManager,CTest=function()local conftest=tmpname()return ContextManager(function(cm)rm(conftest)rm(gsub(conftest,'^.*/','')..'.o')if context_close(cm)then 648return rm(cm.filename)end 649return false 650end,open,conftest..'.c','w')end,File=function(fname,mode)return ContextManager(context_close,open,fname,mode)end,Pipe=function(cmd,mode)return ContextManager(context_close,popen,cmd,mode)end,TmpFile=function(fname,mode)return ContextManager(function(cm)if context_close(cm)then 651return rm(cm.filename)end 652return false 653end,open,fname or tmpname(),mode or'w')end,slurp=function(cm,...)if not cm then 654return cm,...end 655return with(cm,function(h)return h:read'*a'end)end,with=with,} 656end 657package.preload['type.dict']=function() 658local _ENV=require'std.normalize'{destructure=next,}return{OrderedDict=function(...)local r,argu={},list(...)for i=1,argu.n do 659local k,v=destructure(argu[i])append(r,k)r[k]=v 660end 661return r 662end,} 663end 664package.preload['type.path']=function() 665local _ENV=require'std.normalize'{}local BASENAMEPAT='.*'..dirsep 666local DIRNAMEPAT=dirsep..'[^'..dirsep..']*$'return{basename=function(path)return(gsub(path,BASENAMEPAT,''))end,dirname=function(path)return(gsub(path,DIRNAMEPAT,'',1))end,exists=function(path)local fh=open(path)if fh==nil then 667return false 668end 669close(fh)return true 670end,} 671end 672os.exit(require'luke'.main(arg)) 673