Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
395 lines (339 loc) · 10.2 KB
/
Copy pathmain.cpp
File metadata and controls
395 lines (339 loc) · 10.2 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
#include "codegenerator.h"
#include "compiler.h"
#include "global.h"
#include "print.h"
#include <QtCore/QtCore>
#include <cstdlib>
#include <iostream>
#include <list>
#ifdef Q_OS_WIN
#include <windows.h>
#else
#include <csignal>
#include <unistd.h>
#endif
using namespace cpi;
// Version
constexpr auto CPI_VERSION_STR = "2.0.4";
#ifdef Q_CC_MSVC
constexpr auto DEFAULT_CONFIG = "[General]\n"
"CXX=cl.exe\n"
"CXXFLAGS=\n"
"LDFLAGS=\n"
"COMMON_INCLUDES=\n";
#else
#if QT_VERSION < 0x060000
constexpr auto DEFAULT_CONFIG = "[General]\n"
"### Example option for Qt5\n"
"#CXX=%1\n"
"#CXXFLAGS=-fPIC -pipe -std=c++14 -D_REENTRANT -I/usr/include/qt5\n"
"#LDFLAGS=-lQt5Core\n"
"#COMMON_INCLUDES=\n"
"\n"
"CXX=\n"
"CXXFLAGS=-fPIC -pipe -std=c++14 -D_REENTRANT\n"
"LDFLAGS=\n"
"COMMON_INCLUDES=\n";
#else
constexpr auto DEFAULT_CONFIG = "[General]\n"
"### Example option for Qt6\n"
"#CXX=\n"
"#CXXFLAGS=-fPIC -pipe -std=c++17 -D_REENTRANT -I/usr/include/qt6\n"
"#LDFLAGS=-lQt6Core\n"
"#COMMON_INCLUDES=\n"
"\n"
"CXX=\n"
"CXXFLAGS=-fPIC -pipe -std=c++17 -D_REENTRANT\n"
"LDFLAGS=\n"
"COMMON_INCLUDES=\n";
#endif
#endif
// Entered headers and code
static QStringList headers, code;
static int lastLineNumber = 0; // line number added recently
QSettings *conf = nullptr;
QStringList cppsArgs;
QString aoutName()
{
static QString aout;
if (aout.isEmpty()) {
aout = QDir::tempPath() + QDir::separator();
#ifdef Q_OS_WIN
aout += ".cpiout" + QString::number(QCoreApplication::applicationPid()) + ".exe";
#else
aout += ".cpi" + QString::number(QCoreApplication::applicationPid()) + ".out";
#endif
}
return aout;
}
#ifdef Q_OS_WIN
static BOOL WINAPI signalHandler(DWORD ctrlType)
{
switch (ctrlType) {
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT: {
// cleanup
if (QFileInfo(aoutName()).exists()) {
QFile::remove(aoutName());
}
break;
}
default:
return FALSE;
}
while (true)
Sleep(1);
return TRUE;
}
#else
static void signalHandler(int)
{
// cleanup
if (QFileInfo(aoutName()).exists()) {
QFile::remove(aoutName());
}
std::exit(0);
}
static void watchUnixSignal(int sig)
{
if (sig < NSIG) {
struct sigaction sa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_RESTART;
sa.sa_handler = signalHandler;
sigaction(sig, &sa, 0);
}
}
#endif
static QString isSetFileOption()
{
QString ret;
for (int i = 1; i < QCoreApplication::arguments().length(); i++) {
auto opt = QCoreApplication::arguments()[i];
if (!opt.startsWith("-") && QFileInfo(opt).exists()) {
ret = opt;
cppsArgs = QCoreApplication::arguments().mid(i + 1);
break;
}
}
return ret;
}
static void showHelp()
{
char help[] = " .conf Display the current values for various settings.\n"
" .help Display this help.\n"
" .rm LINENO Remove the code of the specified line number.\n"
" .clear Clear the code all.\n"
" .show Show the current source code.\n"
" .quit Exit this program.\n";
print() << help;
}
static void showConfigs(const QSettings &conf)
{
QStringList confkeys;
confkeys << "CXX"
<< "CXXFLAGS"
<< "LDFLAGS"
<< "COMMON_INCLUDES";
QStringList configs = conf.allKeys();
for (QStringListIterator it(conf.allKeys()); it.hasNext();) {
const QString &key = it.next();
if (confkeys.contains(key))
printf("%s=%s\n", qPrintable(key), qPrintable(conf.value(key).toString()));
}
}
static void deleteLine(int n)
{
int h = headers.count();
int c = code.count();
if (n > 0) {
if (n <= h) {
headers.removeAt(n - 1);
} else if (n <= h + c) {
code.removeAt(n - h - 1);
} else {
// ignore
}
lastLineNumber = 0;
}
}
static void deleteLines(const std::list<int> &numbers)
{
std::list<int> numlist = numbers;
numlist.sort(std::greater<int>());
numlist.unique(); // removes duplicates
for (auto d : numlist) {
deleteLine(d);
}
}
static void showCode()
{
int num = 1;
if (!headers.isEmpty()) {
for (int i = 0; i < headers.count(); ++i)
printf("%3d| %s\n", num++, qPrintable(headers.at(i)));
printf(" --------------------\n");
}
for (int i = 0; i < code.count(); ++i)
printf("%3d| %s\n", num++, qPrintable(code.at(i)));
}
static int interpreter()
{
print() << "Cpi " << CPI_VERSION_STR << endl;
print() << "Type \".help\" for more information." << endl;
print() << "Loaded INI file: " << conf->fileName() << endl;
print().flush();
Compiler compiler;
QStringList includes = conf->value("COMMON_INCLUDES").toString().split(" ", SkipEmptyParts);
for (QStringListIterator i(includes); i.hasNext();) {
QString s = i.next().trimmed();
if (!s.isEmpty()) {
if (s.startsWith("<") || s.startsWith('"')) {
headers << QString("#include ") + s;
} else {
headers << QString("#include <") + s + ">";
}
lastLineNumber = headers.count();
}
}
bool end = false;
auto readfunc = [&]() {
// read and write to the process
QString str;
std::string s;
if (std::getline(std::cin, s)) {
str = QString::fromStdString(s);
} else {
end = true;
return;
}
auto line = QString(str).trimmed();
if (line == ".quit" || line == ".q") {
end = true;
return;
}
class PromptOut {
public:
~PromptOut() { print() << "cpi> " << flush; }
} promptOut;
if (line == ".help" || line == "?") { // shows help
showHelp();
return;
}
if (line == ".show" || line == ".code") { // shows code
showCode();
return;
}
if (line == ".conf") { // shows configs
showConfigs(*conf);
return;
}
if (line.startsWith(".del ") || line.startsWith(".rm ")) { // Deletes code
int n = line.indexOf(' ');
line.remove(0, n + 1);
QStringList list = line.split(QRegularExpression("[,\\s]"), SkipEmptyParts);
std::list<int> numbers; // line-numbers
for (QStringListIterator it(list); it.hasNext();) {
const QString &s = it.next();
bool ok;
int n = s.toInt(&ok);
if (ok && n > 0)
numbers.push_back(n);
}
deleteLines(numbers);
showCode();
return;
}
if (line == ".clear") {
headers.clear();
code.clear();
lastLineNumber = 0;
return;
}
if (line.startsWith('#') || line.startsWith("using ")) {
headers << line;
lastLineNumber = headers.count();
} else {
if (!line.isEmpty()) {
code << line;
lastLineNumber = headers.count() + code.count();
}
}
if (code.isEmpty())
return;
// compile
CodeGenerator cdgen(headers.join("\n"), code.join("\n"));
QString src = cdgen.generateMainFunc();
int cpl = compiler.compileAndExecute(src);
if (cpl) {
// compile only once more
src = cdgen.generateMainFuncSafe();
cpl = compiler.compileAndExecute(src);
}
if (cpl) {
compiler.printContextCompilationError();
// delete last line
if (lastLineNumber > 0) {
deleteLine(lastLineNumber);
}
}
};
print() << "cpi> " << flush;
#ifdef Q_OS_WIN
HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
while (!end) {
if (WaitForSingleObject(h, 50) == WAIT_OBJECT_0) {
readfunc();
}
}
#else
QSocketNotifier notifier(fileno(stdin), QSocketNotifier::Read);
QObject::connect(¬ifier, &QSocketNotifier::activated, readfunc);
while (!end) {
QThread::msleep(50);
qApp->processEvents();
}
#endif
return 0;
}
int main(int argv, char *argc[])
{
QCoreApplication app(argv, argc);
#if (defined Q_OS_WIN) || (defined Q_OS_DARWIN)
conf = new QSettings(QSettings::IniFormat, QSettings::UserScope, "cpi/cpi");
#else
conf = new QSettings(QSettings::NativeFormat, QSettings::UserScope, "cpi/cpi");
#endif
QFile confFile(conf->fileName());
if (!confFile.exists()) {
QFileInfo(confFile).absoluteDir().mkpath(".");
if (confFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
confFile.write(DEFAULT_CONFIG);
confFile.close();
}
conf->sync();
}
#ifdef Q_OS_WIN
SetConsoleCtrlHandler(signalHandler, TRUE);
#else
watchUnixSignal(SIGTERM);
watchUnixSignal(SIGINT);
#endif
QString file = isSetFileOption();
if (!file.isEmpty()) {
Compiler compiler;
int ret = compiler.compileFileAndExecute(file);
if (ret) {
compiler.printLastCompilationError();
}
return ret;
}
// Check compiler
Compiler::cxx();
int ret = interpreter();
delete conf;
return ret;
}