unlogic
Loading...
Searching...
No Matches
Compiler.cpp
Go to the documentation of this file.
1#include "Compiler.h"
2#include <cmath>
3#include "graphic/Scene.h"
4#include "parser/Node.h"
6
7using namespace unlogic;
8
9std::expected<city::Assembly, CompilationError> Compiler::Compile(std::string_view program_text, std::vector<bf::Token<ParserGrammarType>> *tokens)
10{
11 auto ast = this->parser_.Parse(program_text, tokens);
12 if (!ast.has_value())
13 {
14 return std::unexpected(ast.error());
15 }
16 auto ast_body = std::get<std::unique_ptr<Node>>(std::move(*ast));
17
18 this->jit_.RemoveModule("__user");
19
20 try
21 {
22 city::IRModule module{"__user"};
23
24 this->scope_.PushLayer();
25
27 .module = module,
28 .scope = this->scope_,
29 };
30
31 std::visit(IRGenerator{ctx}, *ast_body);
32
33 this->scope_.PopLayer();
34
35 this->jit_.InsertIRModule(std::move(module));
36 }
37 catch (std::runtime_error &e)
38 {
39 return std::unexpected(Error{e.what()});
40 }
41
42 return this->jit_.Link();
43}
44
45extern "C"
46{
48 {
49 scene->AddPlot("anon", function);
50 }
51}
52
53Compiler::Compiler() : parser_(*bf::SLRParser<ParserGrammarType>::Build(unlogic_program))
54{
55 this->scope_.PushLayer();
56
57 city::InterfaceModule stdlib{"std"};
58 city::Function *std_functions[] = {
59 stdlib.InsertBinding("__pow", (double (*)(double, double))std::pow),
60 stdlib.InsertBinding("__sqrt", (double (*)(double))std::sqrt),
61
62 stdlib.InsertBinding("__plot_anon", unlogic_plot_anon),
63 };
64
65 for (auto function: std_functions)
66 {
67 this->scope_.Set(*function->GetName(), function);
68 }
69
70 this->jit_.InsertInterfaceModule(std::move(stdlib));
71}
void unlogic_plot_anon(Scene *scene, Plot2dFunctionType function)
Definition Compiler.cpp:47
std::expected< city::Assembly, CompilationError > Compile(std::string_view program_text, std::vector< bf::Token< ParserGrammarType > > *tokens=nullptr)
Definition Compiler.cpp:9
void PushLayer()
Definition Scope.h:35
void PopLayer()
Definition Scope.h:40
void Set(std::string const &key, city::Value *value)
Definition Scope.h:30
double(*)(double) Plot2dFunctionType
Definition Plot.h:15
bf::GrammarDefinition< ParserValueType, SyntaxHighlightingGroup > ParserGrammarType
Definition Parser.h:20
bf::NonTerminal< ParserGrammarType > & unlogic_program
Definition Parser.cpp:200
city::IRModule &Scope & scope
void AddPlot(char const *name, Plot2dFunctionType function)
Definition Scene.cpp:11