compile/squish.compile.lua

1
local cs = require "minichunkspy"
2
 
3
function compile_string(str, name)
4
	-- Strips debug info, if you're wondering :)
5
	local chunk = string.dump(loadstring(str, name));
6
	if ((not opts.debug) or opts.compile_strip) and opts.compile_strip ~= false then
7
		local c = cs.disassemble(chunk);
8
		local function strip_debug(c)
9
			c.source_lines, c.locals, c.upvalues = {}, {}, {};
10
			
11
			for i, f in ipairs(c.prototypes) do
12
				strip_debug(f);
13
			end
14
		end
15
		print_verbose("Stripping debug info...");
16
		strip_debug(c.body);
17
		return cs.assemble(c);
18
	end
19
	return chunk;
20
end
21
 
22
function compile_file(infile_fn, outfile_fn)
23
	local infile, err = io.open(infile_fn);
24
	if not infile then
25
		print_err("Can't open input file for reading: "..tostring(err));
26
		return;
27
	end
28
	
29
	local outfile, err = io.open(outfile_fn..".compiled", "w+");
30
	if not outfile then
31
		print_err("Can't open output file for writing: "..tostring(err));
32
		return;
33
	end
34
	
35
	local data = infile:read("*a");
36
	infile:close();
37
	
38
	local shebang, newdata = data:match("^(#.-\n)(.+)$");
39
	local code = newdata or data;
40
	if shebang then
41
		outfile:write(shebang)
42
	end
43
 
44
	outfile:write(compile_string(code, outfile_fn));
45
	
46
	os.rename(outfile_fn..".compiled", outfile_fn);
47
end
48
 
49
if opts.compile then
50
	print_info("Compiling "..out_fn.."...");
51
	compile_file(out_fn, out_fn);
52
	print_info("OK!");
53
end