Initial commit

This commit is contained in:
Quinten Kock 2023-03-11 17:55:59 +01:00
commit 68e979fcec
3 changed files with 117 additions and 0 deletions

76
init.lua Normal file
View File

@ -0,0 +1,76 @@
local mpp = {}
local output = {}
local function process(file)
local script = ""
local f = io.open(file, "r")
coroutine.yield([[
local output = {}
function output:literal(x)
table.insert(self, x)
end
function output:expression(f)
table.insert(self, f)
end
]])
for line in f:lines() do
if line:find("^%s-" .. mpp.directive) then
-- Line starts with MPP directive
-- as such, it contains Lua code.
coroutine.yield(
line:gsub("^(%s-)" .. mpp.directive, " %1", 1))
else
-- Line contains host code
-- do replace inline evaluations
coroutine.yield(
'output:literal("' ..
line
:gsub('\\', '\\\\')
:gsub('"', '\\"')
:gsub('%$(.-)%$', '") output:expression(function() return %1 end) output:literal("')
.. '\\n")'
)
end
coroutine.yield("\n")
end
coroutine.yield("return output")
end
local function loadmpp(file)
local generator = coroutine.wrap(function() process(file) end)
local func = assert(load(generator, file))
return func
end
local function outputmpp(file)
local generator = coroutine.wrap(function() process(file) end)
local f = io.open(file .. ".lua", "w")
for line in generator do
f:write(line)
end
end
function mpp.execute(files)
local outputs = {}
for i,file in ipairs(files) do
outputmpp(file .. ".mpp")
outputs[i] = loadmpp(file .. ".mpp")()
end
for i,output in ipairs(outputs) do
local file = io.open(files[i], "w")
for j, o in ipairs(output) do
if type(o) == "string" then
file:write(o)
elseif type(o) == "function" then
file:write(o())
end
end
file:close()
end
end
mpp.directive = "@"
mpp.execute{ "template.c" }

18
template.c Normal file
View File

@ -0,0 +1,18 @@
#include <stdio.h>
int sum_int(int *xs, size_t len) {
int sum = 0;
for(size_t i = 0; i < len; i++) {
sum += xs[i];
}
return sum;
}
int main() {
int x = sum_int({strlen("foo"), strlen("bar")});
printf("%i\n", x)
return 0;
}

23
template.c.mpp Normal file
View File

@ -0,0 +1,23 @@
#include <stdio.h>
@print("foo")
@function sum_t(type, base)
@local base = base or 0
int sum_$type$($type$ *xs, size_t len) {
$type$ sum = $base$;
for(size_t i = 0; i < len; i++) {
sum += xs[i];
}
return sum;
}
@end
@sum_t("int")
int main() {
int x = sum_int({strlen("foo"), strlen("bar")});
printf("%i\n", x)
return 0;
}