-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathCompiler.cpp
More file actions
62 lines (50 loc) · 1.91 KB
/
Copy pathCompiler.cpp
File metadata and controls
62 lines (50 loc) · 1.91 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
#include "Compiler.h"
#include "StringUtils.h"
#include <iostream>
int Compiler::CompileFile(const std::string& filename) {
std::string jscFilename(filename);
std::vector<uint8_t> jsBuffer = FileUtils::readFile(filename);
if (jsBuffer.empty()) {
std::cerr << "err: File is empty or name is invalid!" << std::endl;
return 1;
}
std::string script(jsBuffer.begin(), jsBuffer.end());
std::cout << script;
if (StringUtils::EndsWith(jscFilename, ".js")) {
jscFilename.substr(0, jscFilename.length() - 3);
jscFilename.append(".jsc");
} else {
jscFilename.append(".jsc");
}
CompileScript(script, jscFilename);
return 0;
}
int Compiler::CompileScript(const std::string& script, const std::string& dst_filename) {
JSValue bytecode = JS_Eval(JSEnv::ctx, script.c_str(), script.length(), "@aiot/1", JS_EVAL_FLAG_COMPILE_ONLY);
if (JS_IsException(bytecode)) {
JSValue exception = JS_GetException(JSEnv::ctx);
const char *error = JS_ToCString(JSEnv::ctx, exception);
std::cerr << "Compile Error: " << error << std::endl;
JS_FreeCString(JSEnv::ctx, error);
JS_FreeValue(JSEnv::ctx, exception);
return 1;
} else {
size_t bytecode_len;
uint8_t *bytecode_buf = JS_WriteObject(JSEnv::ctx, &bytecode_len, bytecode, 1);
if (!bytecode_buf) {
std::cerr << "Failed to write compile result" << std::endl;
return 1;
} else {
FILE *file = fopen(dst_filename.c_str(), "wb");
if (file) {
fwrite(bytecode_buf, 1, bytecode_len, file);
fclose(file);
std::cerr << "Bytecode has been written to bytecode.bin" << std::endl;
} else {
std::cerr << "Failed to open dst file" << std::endl;
}
js_free(JSEnv::ctx, bytecode_buf);
}
}
return 0;
}