commit 68e979fcec1f2b152501675034cb2a6f238488ab Author: Quinten Kock Date: Sat Mar 11 17:55:59 2023 +0100 Initial commit diff --git a/init.lua b/init.lua new file mode 100644 index 0000000..19d5a99 --- /dev/null +++ b/init.lua @@ -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" } \ No newline at end of file diff --git a/template.c b/template.c new file mode 100644 index 0000000..c065a6b --- /dev/null +++ b/template.c @@ -0,0 +1,18 @@ +#include + + + + 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; +} + diff --git a/template.c.mpp b/template.c.mpp new file mode 100644 index 0000000..ef2b753 --- /dev/null +++ b/template.c.mpp @@ -0,0 +1,23 @@ +#include + +@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; +} + \ No newline at end of file