Skip to content

Instantly share code, notes, and snippets.

@lefticus
Last active July 18, 2024 02:15
Show Gist options
  • Save lefticus/5d94357725413dce5005b0b1b7f77836 to your computer and use it in GitHub Desktop.
Save lefticus/5d94357725413dce5005b0b1b7f77836 to your computer and use it in GitHub Desktop.
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
// This code was originally created by Jason Turner aka @lefticus
// Please examine, modify, and in general use this as an example for
// how scripting + C++ integration works.
//
// The TODOs are intentionally left FOR YOU!
//
// Please consider leaving some mention of the origin of this code
// when you use it for your own purposes.
//
// https://youtube.com/@cppweekly
// https://compiler-explorer.com/z/86558dW56
// https://gist.github.com/lefticus/5d94357725413dce5005b0b1b7f77836
#include <any>
#include <array>
#include <charconv>
#include <functional>
#include <iostream>
#include <map>
#include <ranges>
#include <span>
#include <string>
struct Genesis_Script {
// TODO: attempt to make this use variant instead of `any` and see what changes
struct Function {
std::function<std::any(std::span<std::any>)> callable;
std::size_t arity;
};
// TODO: Transparent comparator for std::string_view?
// TODO: `constexpr` friendly types?
std::map<std::string, Function> functions;
std::map<std::string, std::any> variables;
std::vector<std::any> stack;
[[nodiscard]] auto get_stack_span(const std::size_t size) {
if (stack.size() < size) { throw std::runtime_error("not enough stack elements"); }
return std::span(stack).subspan(stack.size() - size);
}
void pop(std::span<std::any> elements) {
if (elements.size() > stack.size()) { throw std::runtime_error("pop size mismatch"); }
stack.resize(stack.size() - elements.size());
}
// TODO: add overload for member functions
// TODO: add overload that knows how to handle any callable
template <typename Ret, typename... Param>
void add(std::string name, Ret (*func)(Param...)) {
functions.try_emplace(
std::move(name), // map key
[func](std::span<std::any> params) {
if (params.size() != sizeof...(Param)) {
throw std::runtime_error("Wrong number of params sent to function");
}
// need the index sequence to unpack the param in the proper order
return [&]<std::size_t... Index>(std::index_sequence<Index...>) -> std::any {
if constexpr (!std::is_same_v<void, Ret>) {
// if return type is not void, directly return it into the std::any
return func(std::any_cast<std::remove_cvref_t<Param>>(params[Index])...);
} else {
// if it is void, we have to handle it separately
func(std::any_cast<std::remove_cvref_t<Param>>(params[Index])...);
return {};
}
}(std::make_index_sequence<sizeof...(Param)>()); // immediatedly invoked
// and using function template argument
// deduction to generate indices
}, // Function that knows how to unbox span of parameters
sizeof...(Param)); // function arity
}
void exec(const std::string &func_name) {
const auto func = functions.at(func_name);
const auto span = get_stack_span(func.arity);
auto result = func.callable(span);
// TODO: can we rearrange this to avoid the move? I don't think so...
pop(span);
if (result.has_value()) {
stack.push_back(std::move(result));
}
}
[[nodiscard]] bool lookup_id(const auto &map, const auto &id) {
// If it start swith a '.' we call it an identifier
if (id.starts_with('.') && map.contains(id.substr(1))) {
stack.emplace_back(map.at(id.substr(1)));
return true;
}
return false;
}
[[nodiscard]] bool exec_function(const auto &id) {
if (functions.contains(id)) {
exec(id);
return true;
}
return false;
}
[[nodiscard]] bool exec_builtins(const auto &id) {
// TODO: "load" function (alias for . shortcut)
// TODO: "if"
// TODO: "for"
// TODO: Define function?
// TODO: Swap? Duplicate? There are things that builtins can do
// that no regular function can do, because they have access
// to the entire system state
if (id == "store") {
const auto args = get_stack_span(2);
variables[std::any_cast<std::string>(args[1])] = args[0];
pop(args);
return true;
}
return false;
}
template<typename Numeric>
[[nodiscard]] bool parse_numeric(const std::string &input) {
const auto begin = input.data();
const auto end = std::next(input.data(), std::ssize(input));
Numeric value = 0;
if (auto result = std::from_chars(begin, end, value); result.ptr == end) {
stack.emplace_back(value);
return true;
}
return false;
}
void parse(std::string input) {
// Observe that we try things in a particular priority order
// and rely on short circuiting to stop evaluation as soon as
// something succeeds.
if (input.empty()
|| exec_builtins(input)
|| exec_function(input)
|| lookup_id(functions, input)
|| lookup_id(variables, input)
// order matters here, an int will parse as a double, but not the other way
|| parse_numeric<int>(input)
|| parse_numeric<double>(input)) {
return;
}
// Fallthrough is just treating the thing as a string literal
stack.emplace_back(std::move(input));
}
};
constexpr inline std::string_view script = R"(
The Value Was:
9
2
4
+
*
12
-
the_sum
store
.the_sum
.the_sum
+
to_string
append
print
)";
[[nodiscard]] std::string to_string(int x) { return std::to_string(x); }
void print(const std::string &s) { std::puts(s.c_str()); }
int main() {
Genesis_Script se;
// add functions to engine
se.add("+", +[](int x, int y) { return x + y; });
se.add("*", +[](int x, int y) { return x * y; });
se.add("-", +[](int x, int y) { return x - y; });
se.add(
"append", +[](const std::string &lhs, const std::string &rhs) {
return lhs + rhs;
});
se.add("print", print);
se.add("to_string", to_string);
for (const auto line : std::views::split(script, std::string_view{"\n"})) {
se.parse(std::string{line.begin(), line.end()});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment