-
-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathmain.cpp
More file actions
70 lines (56 loc) · 2.67 KB
/
main.cpp
File metadata and controls
70 lines (56 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <pl.hpp>
#include <format>
const static std::map<pl::core::LogConsole::Level, std::string> LogLevels = {
{ pl::core::LogConsole::Level::Debug, "Debug" },
{ pl::core::LogConsole::Level::Info, "Info" },
{ pl::core::LogConsole::Level::Warning, "Warning" },
{ pl::core::LogConsole::Level::Error, "Error" }
};
int main() {
// Create an instance of the pattern language runtime
pl::PatternLanguage patternLanguage;
// Create some data to analyze
constexpr static auto Data = []{
std::array<pl::u8, 0x100> data = { };
for (size_t i = 0; i < data.size(); i++)
data[i] = i;
return data;
}();
// Tell the runtime where and how to read data
patternLanguage.setDataSource(0x00, Data.size(), [](pl::u64 address, pl::u8 *buffer, size_t size){
std::memcpy(buffer, &Data[address], size);
});
// Tell the runtime how to handle dangerous functions being called
patternLanguage.setDangerousFunctionCallHandler([]{
// Print a message
printf("Dangerous function called!\n");
// Allow all dangerous functions to be run
return true;
});
// Create a normal builtin function called `test::normal_function` that takes a single parameter
patternLanguage.addFunction({ "test" }, "normal_function", pl::api::FunctionParameterCount::exactly(1), [](pl::core::Evaluator *ctx, const std::vector<pl::core::Token::Literal> ¶ms) -> std::optional<pl::core::Token::Literal>{
printf("%s", std::format("normal_function {}\n", std::get<pl::i128>(params[0])).c_str());
return std::nullopt;
});
// Create a dangerous function called `test::dangerous_function` that takes no parameters
patternLanguage.addDangerousFunction({ "test" }, "dangerous_function", pl::api::FunctionParameterCount::none(), [](pl::core::Evaluator *, const std::vector<pl::core::Token::Literal> &) -> std::optional<pl::core::Token::Literal>{
printf("dangerous_function\n");
return 1337;
});
patternLanguage.setLogCallback([](auto level, const std::string &message) {
printf("[%s] %s\n", LogLevels.at(level).c_str(), message.c_str());
});
// Evaluate some pattern language source code
bool result = patternLanguage.executeString(R"(
fn main() {
s32 x = test::dangerous_function();
test::normal_function(x);
};
)");
// Check if execution completed successfully
if (!result) {
// If not, print the error string
auto error = patternLanguage.getEvalError();
printf("Error: %d:%d %s\n", error->line, error->column, error->message.c_str());
}
}