From 860cdb7b387723eddea9bd110c85ebeaaa6c5b70 Mon Sep 17 00:00:00 2001 From: Clyne Sullivan Date: Sat, 30 Nov 2024 10:21:59 -0500 Subject: [PATCH] compile time initialize --- main.cpp | 8 ++++++-- sforth/forth.hpp | 28 ++++++++++++---------------- 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/main.cpp b/main.cpp index 99f5ecc..60653dc 100644 --- a/main.cpp +++ b/main.cpp @@ -23,7 +23,12 @@ #include static std::array dict; -static auto fth = new (dict.data()) sforth::forth; +static sforth::forth *fth = + [] constexpr { + fth = new (dict.data()) sforth::forth; + sforth::initialize<&fth>(dict.end()); + return fth; + }(); static bool parse_stream(sforth::forth *, std::istream&, bool say_okay = false); @@ -31,7 +36,6 @@ int main(int argc, const char *argv[]) { std::span args (argv + 1, argc - 1); - sforth::initialize<&fth>(dict.end()); fth->add(".", [](auto) { char buf[32] = {}; std::to_chars(buf, buf + sizeof(buf), fth->pop(), fth->base); diff --git a/sforth/forth.hpp b/sforth/forth.hpp index 91c580c..32f5d53 100644 --- a/sforth/forth.hpp +++ b/sforth/forth.hpp @@ -194,20 +194,6 @@ struct forth : public word_list std::array rstack; }; -template -void prologue(const void *bodyf) -{ - static auto& fth = **fthp; - - auto body = (func *)bodyf; - fth.rpush(fth.ip); - - for (fth.ip = body + 1; *fth.ip; fth.ip++) - fth.execute(std::bit_cast(*fth.ip)); - - fth.ip = fth.rpop(); -} - template void initialize(cell *end_value) { @@ -216,6 +202,16 @@ void initialize(cell *end_value) static auto& fth = **fthp; static auto _d = std::bit_cast(*fthp); + constexpr static auto prologue = +[](const void *bodyf) { + auto body = (func *)bodyf; + fth.rpush(fth.ip); + + for (fth.ip = body + 1; *fth.ip; fth.ip++) + fth.execute(std::bit_cast(*fth.ip)); + + fth.ip = fth.rpop(); + }; + constexpr static func lit_impl = [](auto) { auto ptr = std::bit_cast(++fth.ip); fth.push(*ptr); @@ -264,7 +260,7 @@ void initialize(cell *end_value) , S{":" }, [](auto) { auto w = fth.parse(); fth.add(w); - *fth.here++ = std::bit_cast(&prologue); + *fth.here++ = std::bit_cast(prologue); fth.compiling = true; }, 0 , S{";" }, [](auto) { *fth.here++ = 0; fth.compiling = false; }, word_base::immediate , S{"\\" }, [](auto) { fth.sourcei = forth::npos; }, word_base::immediate @@ -284,7 +280,7 @@ void initialize(cell *end_value) assert(g.has_value()); *fth.here++ = std::bit_cast((*g)->body()); }, word_base::immediate >::word; - constexpr static auto& dict2 = comp_dict, &dict1 + constexpr static auto& dict2 = comp_dict