-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathLoadLFortran.js
More file actions
211 lines (195 loc) · 8.14 KB
/
Copy pathLoadLFortran.js
File metadata and controls
211 lines (195 loc) · 8.14 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import Script from "next/script";
import { useRouter } from "next/router";
import { useCallback, useEffect } from "react";
// lfortran exported functions
function getLfortranExportedFuncs() {
return new Promise((resolve, reject) => {
Module.onRuntimeInitialized = function () {
resolve({
emit_ast_from_source: Module.cwrap("emit_ast_from_source", "string", ["string"]),
emit_asr_from_source: Module.cwrap("emit_asr_from_source", "string", ["string"]),
emit_wat_from_source: Module.cwrap("emit_wat_from_source", "string", ["string"]),
emit_cpp_from_source: Module.cwrap("emit_cpp_from_source", "string", ["string"]),
emit_py_from_source: Module.cwrap("emit_wat_from_source", "string", ["string"]),
emit_wasm_from_source: Module.cwrap("emit_wasm_from_source", "string", ["string"]),
});
};
});
}
var memory;
function define_imports(outputBuffer, exit_code, stdout_print) {
const flushBuffer = () => {
stdout_print(outputBuffer.join(""));
outputBuffer.length = 0;
}
const fd_write = (file_type, iov_location, no_of_iovs, return_val_mem_loc) => {
const mem_data = new DataView(memory.buffer, iov_location, Int32Array.BYTES_PER_ELEMENT * 2);
const strLoc = mem_data.getInt32(0, true);
const strLen = mem_data.getInt32(4, true);
const s = new TextDecoder("utf8").decode(new Uint8Array(memory.buffer, strLoc, strLen));
outputBuffer.push(s);
return 0;
}
const proc_exit = (exit_code_val) => exit_code.val = exit_code_val;
const cpu_time = (time) => (Date.now() / 1000); // Date.now() returns milliseconds, so divide by 1000
const show_image = (cols, rows, arr) => {
var arr2D_data = new DataView(memory.buffer, arr, Int32Array.BYTES_PER_ELEMENT * rows * cols);
var canvas = document.createElement("CANVAS");
canvas.width = cols;
canvas.height = rows;
var ctx = canvas.getContext("2d");
var imgData = ctx.createImageData(cols, rows);
for (var i = 0; i < imgData.data.length; i += 4) {
imgData.data[i + 0] = arr2D_data.getInt32(i, true);
imgData.data[i + 1] = arr2D_data.getInt32(i, true);
imgData.data[i + 2] = arr2D_data.getInt32(i, true);
imgData.data[i + 3] = 255; // alpha channel (from 0-255), 0 is transparent and 255 is fully visible
}
ctx.putImageData(imgData, 0, 0);
outputBuffer.push(`<img alt="constructed image" src="${canvas.toDataURL('image/jpeg')}" height="${rows}" width="${cols}" style="aspect-ratio: 1 / 1;"/>\n`)
flushBuffer();
}
const show_image_color = (cols, rows, arr) => {
var arr2D_data = new DataView(memory.buffer, arr, Int32Array.BYTES_PER_ELEMENT * 4 * rows * cols);
var canvas = document.createElement("CANVAS");
canvas.width = cols;
canvas.height = rows;
var ctx = canvas.getContext("2d");
var imgData = ctx.createImageData(cols, rows);
// The data in DataView is stored as i32 per channel, while it
// should be i8. Currently we have to copy the i32 integer and assign
// it to the canvas' i8 integer. We have to index it with 4*i, because
// the getInt32 method accepts a byte index.
for (var i = 0; i < imgData.data.length; i++) {
imgData.data[i] = arr2D_data.getInt32(4*i, true);
}
ctx.putImageData(imgData, 0, 0);
outputBuffer.push(`<img alt="constructed image" src="${canvas.toDataURL('image/jpeg')}" height="${rows}" width="${cols}" style="aspect-ratio: 1 / 1;"/>\n`)
flushBuffer();
}
var imports = {
wasi_snapshot_preview1: {
/* wasi functions */
fd_write: fd_write,
proc_exit: proc_exit,
},
js: {
/* custom functions */
cpu_time: cpu_time,
show_img: show_image,
show_img_color: show_image_color
},
};
return imports;
}
async function setup_lfortran_funcs(lfortran_funcs, CustomPrint) {
const compiler_funcs = await getLfortranExportedFuncs();
lfortran_funcs.emit_ast_from_source = function (source_code) {
try {
return compiler_funcs.emit_ast_from_source(source_code);
} catch (e) {
console.log(e);
CustomPrint(e + "\nERROR: AST could not be generated from the code");
return 0;
}
}
lfortran_funcs.emit_asr_from_source = function (source_code) {
try {
return compiler_funcs.emit_asr_from_source(source_code);
} catch (e) {
console.log(e);
CustomPrint(e + "\nERROR: ASR could not be generated from the code");
return 0;
}
}
lfortran_funcs.emit_wat_from_source = function (source_code) {
try {
return compiler_funcs.emit_wat_from_source(source_code);
} catch (e) {
console.log(e);
CustomPrint(e + "\nERROR: WAT could not be generated from the code");
return 0;
}
}
lfortran_funcs.emit_cpp_from_source = function (source_code) {
try {
return compiler_funcs.emit_cpp_from_source(source_code);
} catch (e) {
console.log(e);
CustomPrint(e + "\nERROR: CPP could not be generated from the code");
return 0;
}
}
lfortran_funcs.emit_py_from_source = function (source_code) {
try {
return compiler_funcs.emit_py_from_source(source_code);
} catch (e) {
console.log(e);
CustomPrint(e + "\nERROR: LLVM could not be generated from the code");
return 0;
}
}
lfortran_funcs.compile_code = function (source_code) {
try {
return compiler_funcs.emit_wasm_from_source(source_code);
} catch (e) {
console.log(e);
CustomPrint(e + "\nERROR: The code could not be compiled. Either there is a compile-time error or there is an issue at our end.");
return 0;
}
};
lfortran_funcs.execute_code = async function (bytes, stdout_print) {
var exit_code = {val: 1}; /* non-zero exit code */
var outputBuffer = [];
var imports = define_imports(outputBuffer, exit_code, stdout_print);
var start_exec, end_exec;
const printResults = () => {
const duration_exec = end_exec - start_exec;
const duration_compile = sessionStorage.getItem("duration_compile");
outputBuffer.push(`\nCompilation time: ${duration_compile} ms`);
outputBuffer.push(`\nExecution time: ${duration_exec} ms`);
stdout_print(outputBuffer.join(""));
}
try {
var res = await WebAssembly.instantiate(bytes, imports);
memory = res.instance.exports.memory;
start_exec = performance.now();
res.instance.exports._start();
end_exec = performance.now();
printResults();
} catch(err_msg) {
end_exec = performance.now();
printResults();
if (exit_code.val == 0) {
return;
}
stdout_print(`\n${err_msg}\nERROR: The code could not be executed. Either there is a runtime error or there is an issue at our end.`);
}
};
}
function LoadLFortran({
moduleReady,
setModuleReady,
lfortran_funcs,
openNotification,
CustomPrint,
}) {
const { basePath } = useRouter();
useEffect(() => {
window.Module = {
locateFile: (filePath) => `${basePath}/${filePath}`
}
return () => { window.Module = null }
}, [basePath]);
const setupLFortran = useCallback(async () => {
await setup_lfortran_funcs(lfortran_funcs, CustomPrint);
setModuleReady(true);
openNotification("LFortran Module Initialized!", "bottomRight");
}, [moduleReady]); // update the callback if the state changes
return (
<div>
<Script src={`${basePath}/lfortran.js`} onLoad={setupLFortran}></Script>
</div>
);
}
export default LoadLFortran;