forked from cnlohr/noeuclid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TCC.h
55 lines (50 loc) · 1.5 KB
/
TCC.h
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
#ifndef TCC_H
#define TCC_H
#include <string>
#include <libtcc.h>
#include <vector>
#include <stdexcept>
using string=std::string;
struct TCCSymbol { string name; void* func;};
class TCC {
public:
template<typename T>
void add(string name, T* func) {
//TODO memory leak
if(!tcc) tcc = tcc_new();
symbols.push_back({name, (void*) func});
}
void addheader(string header) {
headers += header+"\n";
}
template<typename T> T* compile(string code, string symbol) {
if(!tcc) tcc = tcc_new();
tcc_define_symbol(tcc, "IS_TCC_RUNTIME", nullptr);
for(TCCSymbol& s:symbols) tcc_add_symbol(tcc, s.name.c_str(), s.func);
code = headers + code;
int state = tcc_compile_string(tcc, code.c_str());
if(state == -1) {
throw std::invalid_argument("Error compiling code (("+code+"))");
}
#ifdef WIN32
tcc_add_library_path(tcc,".");
tcc_add_library(tcc, "./libtcc1.a");
#endif
int size = tcc_relocate(tcc, TCC_RELOCATE_AUTO);
if(size == -1) {
throw std::invalid_argument("Error compiling code 2 (("+code+"))");
}
T* fn = (T*) tcc_get_symbol(tcc, symbol.c_str());
tcc = 0;
return fn;
}
// returns a pointer to a function called "fun" in the given c code
template<typename T> T* eval(string code) {
return compile<T>(code, "fun");
}
private:
TCCState* tcc;
std::string headers;
std::vector<TCCSymbol> symbols;
};
#endif /* TCC_H */