-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAECforWebAssembly.cpp
More file actions
348 lines (342 loc) · 13.9 KB
/
AECforWebAssembly.cpp
File metadata and controls
348 lines (342 loc) · 13.9 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
* So, this is the main program, the driver which reads the source code
* and lets the tokenizer, the parser and the compiler communicate.
*
* TODO: What if some part of the compiler (most likely tokenizer) wants
* to read some file other than the main AEC program? Such a problem
* isn't easily solvable with this design.
*/
#ifndef NDEBUG // So that CMAKE does not complain about it being redefined...
#define NDEBUG // If deleted, the tokenizer and parser will output verbose
// output.
#endif
#if defined(_WIN32) && !defined(WIN32) // https://stackoverflow.com/a/5080453
#define WIN32 // Or else CLANG on Windows will read the input files
// character-by-character instead of using memory mapping.
#endif
bool areWeCurrentlyTesting = false;
#include <string>
std::string compilation_target; // WASI (WebAssembly System Interface) or
// browser (default).
bool the_cpp_runtime_library_supports_regexes = true;
#include "TreeRootNode.cpp"
#define OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS
#include "compiler.cpp"
#include "parser.cpp"
#include "tests.cpp"
#include "tokenizer.cpp"
#include <chrono>
#include <ciso646> // Necessary for Microsoft C++ Compiler.
#include <exception>
#include <fstream>
#include <iostream>
#include <typeinfo>
#if defined(WIN32)
#include <windows.h>
#elif defined(__linux__)
#include <unistd.h>
#endif
#if defined(_POSIX_MAPPED_FILES)
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#endif
using namespace std;
int main(int argc, char **argv) {
using namespace std::regex_constants;
using namespace std::chrono;
try {
if (argc < 2 or not(regex_search(
argv[1], regex(R"(\.AEC$)", ECMAScript bitor icase)))) {
if (argc >= 2 and
(ends_with(argv[1], ".aec") or
ends_with(argv[1],
".AEC"))) // Damn, CLANG on Linux is to C++ what Internet
// Explorer 6 (or, maybe better say, Opera Mini,
// because it appears to be fast by disobeying
// the standards) is to JavaScript. I don't
// understand how it manages to compile itself,
// yet it miscompiles something every now and
// then in a 5'500-lines-of-code program.
#if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ <= 8)
// Please do not modify the code here to try to feature-detect whether
// the compiler supports regex_error, as GCC 4.8.5 (the C++ compiler you
// get with Oracle Linux 7) compiles regex_error, but the linking fails
// then.
throw exception();
#else
throw regex_error(error_complexity);
#endif
cerr << "Please invoke this program as follows, from the command line:\n"
<< argv[0] << " name_of_the_program.aec"
<< R"(
Or, alternatively, open an AEC source code with this program.
For more information, see:
https://flatassembler.github.io/AEC_specification#AEC_to_WebAssembly
TL;DR
An example AEC program can be downloaded here:
https://sourceforge.net/p/aecforwebassembly/code/ci/master/tree/analogClock/analogClock.aec?format=raw
You need to assemble the result using a program called "wat2wasm"
from WebAssembly Binary Toolkit (WABT), perhaps like this
(if you have NodeJS installed and an Internet connection):
npx -p wabt wat2wasm analogClock.wat
Then you need to write a JavaScript program runnable in NodeJS
which will invoke that AEC program, an example is available here:
https://sourceforge.net/p/aecforwebassembly/code/ci/master/tree/analogClock/analogClock.js?format=raw
And then, of course, you can run that program in NodeJS.
NodeJS 11 or newer is required because the code this program produces relies
on "WebAssembly.Global" being available.)"
<< endl;
#ifdef WIN32
system("PAUSE");
#endif // WIN32
return -1;
}
#if defined(__GNUC__) && (__GNUC__ == 4 && __GNUC_MINOR__ <= 8)
} catch (exception &error) {
#else
} catch (regex_error &error) {
#endif
the_cpp_runtime_library_supports_regexes = false;
cerr <<
R"(The C++ compiler this executable has been compiled
with doesn't appear to support JavaScript-style regular
expressions. Parts of this program that rely on them
will not work. The C++ runtime library sends this message when
attempting to use regexes: )"
<< error.what() << endl;
}
cout << "Running the tests..." << endl;
auto beginningOfTests = chrono::high_resolution_clock::now();
runTests();
auto endOfTests = chrono::high_resolution_clock::now();
cout << "All the tests passed in "
<< ((endOfTests - beginningOfTests).count() *
high_resolution_clock::period::num * 1000 /
high_resolution_clock::period::den)
<< " milliseconds." << endl;
string rawInput;
#if defined(WIN32)
cout
<< "We will try to load the entire AEC file into RAM using Windows API..."
<< endl;
auto beginningOfReading = chrono::high_resolution_clock::now();
HANDLE inputFile = CreateFileA(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (inputFile == INVALID_HANDLE_VALUE) {
cerr << "Can't open the file \"" << argv[1]
<< "\" for reading! Error code: " << GetLastError() << endl;
return -1;
}
LARGE_INTEGER fileSize;
if (!GetFileSizeEx(inputFile, &fileSize)) {
cerr << "Fetching the size of the file \"" << argv[1]
<< "\" failed! Did you try to open a device file such as CON? Error "
"code: "
<< GetLastError() << endl;
CloseHandle(inputFile);
return -1;
}
HANDLE hMap = CreateFileMappingA(inputFile, NULL, PAGE_READONLY, 0, 0, NULL);
if (hMap == NULL) {
cerr << "The function \"CreateFileMappingA\" failed with the error code "
<< GetLastError() << "!" << endl;
CloseHandle(inputFile);
return -1;
}
LPVOID lpBasePtr = MapViewOfFile(hMap, FILE_MAP_READ, 0, 0, 0);
if (lpBasePtr == NULL) {
cerr << "The function \"MapViewOfFile\" failed with the error code "
<< GetLastError() << "!" << endl;
CloseHandle(hMap);
CloseHandle(inputFile);
}
char *charPtr = (char *)lpBasePtr;
rawInput = string(charPtr, fileSize.LowPart);
UnmapViewOfFile(lpBasePtr);
CloseHandle(hMap);
CloseHandle(inputFile);
#elif defined(_POSIX_MAPPED_FILES)
cout << "We will try to load the entire AEC file into RAM using the Linux "
"mmap directive."
<< endl;
auto beginningOfReading = chrono::high_resolution_clock::now();
int file_descriptor = open(argv[1], O_RDONLY);
if (file_descriptor == -1) {
cerr << "The file \"" << argv[1]
<< "\" cannot be opened for reading. Error code: " << errno << endl;
return -1;
}
struct stat sb;
if (fstat(file_descriptor, &sb) == -1) {
cerr << "Cannot fetch the size of the file \"" << argv[1]
<< "\". Error code: " << errno << endl;
close(file_descriptor);
return -1;
}
if (not(sb.st_size)) {
cerr << "The file \"" << argv[1] << "\" is empty!" << endl;
return -1;
}
void *addr =
mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, file_descriptor, 0);
if (addr == MAP_FAILED) {
cerr << "Mapping the file \"" << argv[1]
<< "\" into RAM failed! Error code: " << errno << endl;
close(file_descriptor);
return -1;
}
rawInput = string((char *)addr, sb.st_size);
munmap(addr,
sb.st_size); // Kind of weird here that a Linux function takes more
// arguments than a corresponding Windows function that is
// UnmapViewOfFile, isn't it? Especially since the second
// argument seems completely unnecessary (what else could
// the second argument be rather than the size of the file
// that has been mapped into RAM). I've asked a Quora
// question about that: https://qr.ae/pCbILK
close(file_descriptor);
#else
ifstream input(argv[1]);
if (!input) {
cerr << "Can't open the file \"" << argv[1] << "\" for reading!" << endl;
return -1;
}
cout << "Reading the file \"" << argv[1] << "\"..." << endl;
auto beginningOfReading = chrono::high_resolution_clock::now();
while (true) {
char currentCharacter;
input.get(currentCharacter);
if (input.eof())
break;
if (currentCharacter != '\r')
rawInput += currentCharacter; // Some text editors store new-lines as
// "\r\n" instead of '\n'.
}
input.close();
#endif
auto endOfReading = chrono::high_resolution_clock::now();
cout << "All characters read in "
<< ((endOfReading - beginningOfReading).count() *
high_resolution_clock::period::num * 1000 /
high_resolution_clock::period::den)
<< " milliseconds." << endl;
cout << "Tokenizing the program..." << endl;
auto beginningOfTokenizing = chrono::high_resolution_clock::now();
vector<TreeNode> tokenized = TreeNode::tokenize(rawInput);
auto endOfTokenizing = chrono::high_resolution_clock::now();
cout << "Finished tokenizing the program in "
<< ((endOfTokenizing - beginningOfTokenizing).count() *
high_resolution_clock::period::num * 1000 /
high_resolution_clock::period::den)
<< R"( milliseconds.
I have made a forum thread about how to speed up the tokenizer,
in case you are interested:
https://www.forum.hr/showthread.php?t=1243509
Parsing the program...)"
<< endl;
if (tokenized.size() and
tokenized[0].text == "#") { // If we are setting the compilation target
if (tokenized.size() >= 2 and tokenized[1].text != "target") {
cerr << "Preprocessor error: Line " << tokenized[1].lineNumber
<< ", Column " << tokenized[1].columnNumber
<< ": Unrecognized preprocessor directive \"" << tokenized[1].text
<< "\"!" << endl;
exit(1);
} else if (tokenized.size() < 2) {
cerr << "Preprocessor error: Line " << tokenized[0].lineNumber
<< ", Column " << tokenized[0].columnNumber
<< ": The preprocessor directive seems to be missing!" << endl;
exit(1);
}
if (tokenized.size() >= 3 and tokenized[2].text != "browser" and
tokenized[2].text != "WASI") {
cerr << "Preprocessor error: Line " << tokenized[2].lineNumber
<< ", Column " << tokenized[2].columnNumber
<< ": Unrecognized target name \"" << tokenized[2].text
<< "\". Supported targets are \"browser\" and \"WASI\"." << endl;
exit(1);
} else if (tokenized.size() < 3) {
cerr << "Preprocessor error: Line " << tokenized[1].lineNumber
<< ", Column " << tokenized[1].columnNumber
<< ": The compilation target seems not to be specified!" << endl;
exit(1);
}
compilation_target = tokenized[2].text;
tokenized.erase(tokenized.begin(), tokenized.begin() + 3);
} else
compilation_target = "browser";
auto beginningOfParsing = chrono::high_resolution_clock::now();
vector<TreeNode> parsed = TreeNode::parse(tokenized);
auto endOfParsing = chrono::high_resolution_clock::now();
cout << "Finished parsing the program in "
<< ((endOfParsing - beginningOfParsing).count() *
high_resolution_clock::period::num * 1000 /
high_resolution_clock::period::den)
<< " milliseconds." << endl;
TreeRootNode AST = TreeRootNode();
AST.children = parsed;
cout << "Compiling the program..." << endl;
auto beginningOfCompilation = chrono::high_resolution_clock::now();
string assembly;
try {
assembly = AST.compile();
} catch (const exception &error) {
cerr << "Internal compiler error: Uncaught exception in the compiler: "
<< typeid(error).name() << ": " << error.what() << std::endl;
if (typeid(error).hash_code() ==
typeid(const CorruptCompilationContextException &).hash_code()) {
cerr << "The JSON of the compilation context, at the time of throwing "
"that exception, was:\n"
<< ((const CorruptCompilationContextException bitand)(error))
.getContext()
.JSONify()
<< std::endl;
}
if (typeid(error).hash_code() !=
typeid(const NotImplementedException &).hash_code())
cerr
<< R"(If you have time, please report this to me on GitHub as an issue:
https://github.com/FlatAssembler/AECforWebAssembly/issues)"
<< std::endl;
return 1;
}
auto endOfCompilation = chrono::high_resolution_clock::now();
cout << "Compilation finished in "
<< ((endOfCompilation - beginningOfCompilation).count() *
high_resolution_clock::period::num * 1000 /
high_resolution_clock::period::den)
<< " milliseconds!" << endl;
#ifdef OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS
cout << "If you want faster compilation times and smaller assembly output, "
"you can delete the\n"
"#define OUTPUT_DEBUG_COMMENTS_IN_ASSEMBLY_COMMENTS\n"
"line from the file `AECforWebAssembly.cpp` and recompile this "
"compiler."
<< endl;
#endif
string assemblyFileName =
string(argv[1]).substr(0,
string(argv[1]).size() - string(".aec").size()) +
".wat";
cout << "Saving the assembly into the file \"" << assemblyFileName << "\"..."
<< endl;
ofstream assemblyFile(assemblyFileName.c_str());
if (!assemblyFile) {
cerr << "Can't open \"" << assemblyFileName << "\" for output!" << endl;
return -1;
}
// CLANG 10 (but not GCC 9.3.0) appears to miscompile "regex_replace" on
// Oracle Linux 7.
string temporaryString;
for (unsigned int i = 0; i < assembly.size(); i++)
if (assembly[i] == '\t')
temporaryString += " ";
else
temporaryString += assembly[i];
assembly = temporaryString;
assemblyFile << assembly << endl;
assemblyFile.close();
cout << "Assembly successfully saved, quitting now." << endl;
return 0;
}