Repository navigation
Expand file tree
/
Copy pathcppsh_core.hpp
More file actions
593 lines (535 loc) · 22.3 KB
/
Copy pathcppsh_core.hpp
File metadata and controls
593 lines (535 loc) · 22.3 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
#pragma once
#include <string>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <algorithm>
#include <cctype>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <filesystem>
#include <termios.h>
#include <unistd.h>
namespace cppsh {
// Utility functions
inline std::string trim(const std::string& s) {
auto start = std::find_if_not(s.begin(), s.end(), [](unsigned char c) { return std::isspace(c); });
auto end = std::find_if_not(s.rbegin(), s.rend(), [](unsigned char c) { return std::isspace(c); }).base();
return (start < end) ? std::string(start, end) : std::string();
}
struct ScriptMetadata {
std::string compiler;
std::string std_version;
std::string debugger;
std::vector<std::string> imports;
};
inline ScriptMetadata extract_metadata(const std::string& script) {
ScriptMetadata meta;
std::stringstream ss(script);
std::string line;
while (std::getline(ss, line)) {
line = trim(line);
if (line.starts_with("// cppsh_compiler:")) {
meta.compiler = trim(line.substr(18));
} else if (line.starts_with("// cppsh_std:")) {
meta.std_version = trim(line.substr(13));
} else if (line.starts_with("// cppsh_debugger:")) {
meta.debugger = trim(line.substr(18));
} else if (line.starts_with("// import ")) {
meta.imports.push_back(trim(line.substr(10)));
}
}
return meta;
}
struct CliOptions {
std::string script_path;
std::vector<std::string> script_args;
bool debug = false;
bool build = false;
bool export_cpp = false;
bool watch = false;
bool repl = false;
};
inline CliOptions parse_cli_args(const std::vector<std::string>& args) {
CliOptions opt;
if (args.empty()) {
opt.repl = true;
return opt;
}
size_t i = 0;
bool flag_seen = false;
while (i < args.size() && args[i].starts_with("-")) {
std::string flag = args[i];
if (flag == "--debug") { opt.debug = true; flag_seen = true; }
else if (flag == "--build") { opt.build = true; flag_seen = true; }
else if (flag == "--export") { opt.export_cpp = true; flag_seen = true; }
else if (flag == "--watch") { opt.watch = true; flag_seen = true; }
else {
throw std::runtime_error("Unknown CLI flag: " + flag);
}
i++;
}
if (opt.build && opt.export_cpp) {
throw std::runtime_error("Conflicting CLI flags provided: --build and --export cannot be used together.");
}
if (i < args.size()) {
opt.script_path = args[i];
i++;
while (i < args.size()) {
opt.script_args.push_back(args[i]);
i++;
}
} else if (flag_seen) {
throw std::runtime_error("Missing script path after CLI flags.");
} else {
opt.repl = true;
}
return opt;
}
struct EnvConfig {
std::string cxx;
std::string cxxflags;
std::string ldflags;
std::string debugger;
};
inline EnvConfig get_env_config() {
EnvConfig cfg;
if (const char* env_cxx = std::getenv("CXX")) {
cfg.cxx = trim(env_cxx);
} else {
if (std::system("which g++-16 >/dev/null 2>&1") == 0) cfg.cxx = "g++-16";
else if (std::system("which g++-15 >/dev/null 2>&1") == 0) cfg.cxx = "g++-15";
else if (std::system("which g++-14 >/dev/null 2>&1") == 0) cfg.cxx = "g++-14";
else cfg.cxx = "g++";
}
if (const char* env_cxxflags = std::getenv("CPPSH_CXXFLAGS")) cfg.cxxflags = trim(env_cxxflags);
if (const char* env_ldflags = std::getenv("CPPSH_LDFLAGS")) cfg.ldflags = trim(env_ldflags);
if (const char* env_dbg = std::getenv("CPPSH_DEBUGGER")) cfg.debugger = trim(env_dbg);
else cfg.debugger = "gdb";
return cfg;
}
inline std::string get_build_output_path(const std::string& script_path) {
if (script_path.empty()) return "./a.out";
size_t pos = script_path.find_last_of("/\\");
std::string filename = (pos == std::string::npos) ? script_path : script_path.substr(pos + 1);
size_t dot_pos = filename.find_last_of('.');
if (dot_pos == std::string::npos || dot_pos == 0) {
return "./" + filename + "_bin";
}
return "./" + filename.substr(0, dot_pos);
}
inline std::string get_export_output_path(const std::string& script_path) {
if (script_path.empty()) return "./script.cpp";
size_t pos = script_path.find_last_of("/\\");
std::string filename = (pos == std::string::npos) ? script_path : script_path.substr(pos + 1);
size_t dot_pos = filename.find_last_of('.');
if (dot_pos == std::string::npos || dot_pos == 0) {
return "./" + filename + ".cpp";
}
return "./" + filename.substr(0, dot_pos) + ".cpp";
}
inline uint64_t compute_fnv1a_hash(const std::string& text) {
uint64_t hash = 14695981039346656037ULL;
for (char c : text) {
hash = (hash ^ static_cast<unsigned char>(c)) * 1099511628211ULL;
}
return hash;
}
inline std::string get_cache_dir() {
const char* home = std::getenv("HOME");
std::string dir = home ? std::string(home) + "/.cache/cppsh" : "/tmp/cppsh_cache";
return dir;
}
inline std::string get_cached_binary_path(const std::string& script_content, const std::string& flags) {
uint64_t h = compute_fnv1a_hash(script_content + "|||" + flags);
char buffer[32];
std::snprintf(buffer, sizeof(buffer), "%016llx", (unsigned long long)h);
return get_cache_dir() + "/" + buffer + ".out";
}
inline int check_stacktrace_support(const std::string& compiler) {
std::string cache_dir = get_cache_dir();
std::filesystem::create_directories(cache_dir);
uint64_t ch = compute_fnv1a_hash(compiler);
char cbuf[32];
std::snprintf(cbuf, sizeof(cbuf), "%016llx", (unsigned long long)ch);
std::string st_cache_file = cache_dir + "/st_mode_" + std::string(cbuf) + ".txt";
if (std::filesystem::exists(st_cache_file)) {
std::ifstream in(st_cache_file);
int mode;
if (in >> mode) return mode;
}
std::string test_file = "/tmp/cppsh_test_st.cpp";
std::ofstream out(test_file);
out << "#include <iostream>\n#if __has_include(<stacktrace>)\n#include <stacktrace>\n#endif\nint main() { #if __has_include(<stacktrace>)\nstd::cout << std::stacktrace::current();\n#endif\nreturn 0; }\n";
out.close();
int mode = -1;
// Check built-in (0)
if (std::system((compiler + " -std=c++23 " + test_file + " -o /tmp/cppsh_test_st.out >/dev/null 2>&1").c_str()) == 0) mode = 0;
// Check -lstdc++_libbacktrace (1)
else if (std::system((compiler + " -std=c++23 " + test_file + " -lstdc++_libbacktrace -o /tmp/cppsh_test_st.out >/dev/null 2>&1").c_str()) == 0) mode = 1;
// Check -lstdc++_exp (2)
else if (std::system((compiler + " -std=c++23 " + test_file + " -lstdc++_exp -o /tmp/cppsh_test_st.out >/dev/null 2>&1").c_str()) == 0) mode = 2;
std::ofstream cout_file(st_cache_file);
cout_file << mode;
cout_file.close();
return mode;
}
inline bool repl_readline(const std::string& prompt, std::string& line, const std::vector<std::string>& history) {
std::cout << prompt << std::flush;
struct termios old_tio, new_tio;
tcgetattr(STDIN_FILENO, &old_tio);
new_tio = old_tio;
new_tio.c_lflag &= ~(ICANON | ECHO); // Disable canonical mode and echoing
tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);
line.clear();
size_t cursor_pos = 0;
int history_index = history.size(); // pointing past the end
auto redraw = [&](const std::string& l, size_t c) {
std::cout << "\r\033[K" << prompt << l;
if (c < l.size()) {
std::cout << "\r\033[" << (prompt.size() + c) << "C";
}
std::cout << std::flush;
};
bool eof = false;
while (true) {
char c;
if (read(STDIN_FILENO, &c, 1) <= 0) {
eof = true;
break;
}
if (c == '\n' || c == '\r') {
std::cout << "\n" << std::flush;
break;
} else if (c == 4) { // Ctrl+D (EOF)
if (line.empty()) { eof = true; break; }
} else if (c == 3) { // Ctrl+C
line.clear();
std::cout << "\n" << std::flush;
break;
} else if (c == 127 || c == 8) { // Backspace
if (cursor_pos > 0) {
line.erase(cursor_pos - 1, 1);
cursor_pos--;
redraw(line, cursor_pos);
}
} else if (c == 27) { // Escape sequence
char seq[2];
if (read(STDIN_FILENO, &seq[0], 1) == 0) break;
if (read(STDIN_FILENO, &seq[1], 1) == 0) break;
if (seq[0] == '[') {
if (seq[1] == 'A') { // Up arrow
if (history_index > 0) {
history_index--;
line = history[history_index];
cursor_pos = line.size();
redraw(line, cursor_pos);
}
} else if (seq[1] == 'B') { // Down arrow
if (history_index + 1 < (int)history.size()) {
history_index++;
line = history[history_index];
cursor_pos = line.size();
redraw(line, cursor_pos);
} else {
history_index = history.size();
line.clear();
cursor_pos = 0;
redraw(line, cursor_pos);
}
} else if (seq[1] == 'C') { // Right arrow
if (cursor_pos < line.size()) {
cursor_pos++;
redraw(line, cursor_pos);
}
} else if (seq[1] == 'D') { // Left arrow
if (cursor_pos > 0) {
cursor_pos--;
redraw(line, cursor_pos);
}
}
}
} else if (std::isprint(static_cast<unsigned char>(c))) {
line.insert(cursor_pos, 1, c);
cursor_pos++;
redraw(line, cursor_pos);
}
}
tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
return !eof;
}
struct ReplState {
std::vector<std::string> history;
std::vector<std::string> input_history;
bool last_was_expr = false;
};
inline bool is_expression(const std::string& line) {
std::string t = trim(line);
if (t.empty()) return false;
if (t.back() == ';') return false;
if (t.starts_with("#") || t.starts_with("//")) return false;
if (t.starts_with("auto ") || t.starts_with("int ") || t.starts_with("str ") ||
t.starts_with("vec ") || t.starts_with("u64 ") || t.starts_with("if ") ||
t.starts_with("for ") || t.starts_with("while ") || t.starts_with("return ")) return false;
if (t.find('=') != std::string::npos) return false;
return true;
}
// Forward declaration of wrap_script
std::string wrap_script(const std::string& input, const std::string& filename, bool emit_line_directives, int stacktrace_mode);
inline std::string process_repl_input(ReplState& state, const std::string& input, int stacktrace_mode = 0) {
std::string t = trim(input);
if (!t.empty()) {
state.input_history.push_back(t);
}
if (t.empty()) return wrap_script("", "repl.cppsh", false, stacktrace_mode);
std::string stmt = t;
bool expr = is_expression(stmt);
state.last_was_expr = expr;
if (expr) {
stmt = "std::println(\"{}\", " + stmt + ");";
} else if (!stmt.starts_with("#") && !stmt.starts_with("//") && stmt.back() != ';' && stmt.back() != '}') {
stmt += ";";
}
if (!expr) {
state.history.push_back(stmt);
}
std::string combined;
for (const auto& h : state.history) {
combined += h + "\n";
}
if (expr) {
combined += stmt + "\n";
}
return wrap_script(combined, "repl.cppsh", false, stacktrace_mode);
}
inline std::string read_file(const std::string& path) {
std::ifstream file(path);
if (!file.is_open()) {
throw std::runtime_error("Could not open file: " + path);
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
// Phase 1 & 2: Wrap script logic inside a standard C++ int main() body with injected shell capabilities
// Phase 3: Added multi-point #line injection and crash dumps
// Phase 4: Added emit_line_directives parameter for IDE ejection
inline std::string wrap_script(const std::string& input, const std::string& filename = "script.cppsh", bool emit_line_directives = true, int stacktrace_mode = 0) {
std::stringstream ss(input);
std::string line;
std::string hoisted =
"#include <vector>\n"
"#include <string>\n"
"#include <cstdint>\n"
"#include <iostream>\n"
"#include <stdexcept>\n"
"#include <format>\n"
"#include <memory>\n"
"#include <array>\n"
"#include <sys/wait.h>\n"
"#include <csignal>\n";
if (emit_line_directives && stacktrace_mode >= 0) {
hoisted +=
"#if __has_include(<stacktrace>)\n"
"#include <stacktrace>\n"
"#endif\n";
}
hoisted +=
"#if __has_include(<print>)\n"
"#include <print>\n"
"#endif\n"
"using str = std::string;\n"
"template <typename T> using vec = std::vector<T>;\n"
"using u64 = uint64_t;\n"
"class ShellException : public std::runtime_error {\n"
"public:\n"
" int exit_code;\n"
" str command;\n"
" ShellException(const str& cmd, int code) \n"
" : std::runtime_error(\"Command '\" + cmd + \"' failed with exit code \" + std::to_string(code)), \n"
" exit_code(code), command(cmd) {}\n"
"};\n"
"template<typename T>\n"
"constexpr str _sh_escape(const T& val) {\n"
" if constexpr (std::is_convertible_v<T, std::string_view>) {\n"
" std::string_view sv = val;\n"
" str res = \"'\";\n"
" for (char c : sv) {\n"
" if (c == '\\'') res += \"'\\\\''\";\n"
" else res += c;\n"
" }\n"
" res += \"'\";\n"
" return res;\n"
" } else {\n"
" return std::format(\"{}\", val);\n"
" }\n"
"}\n"
"inline str _cppsh_sh(const str& cmd) {\n"
" struct PcloseDeleter { void operator()(FILE* f) const { pclose(f); } };\n"
" std::array<char, 128> buffer;\n"
" str result;\n"
" std::unique_ptr<FILE, PcloseDeleter> pipe(popen(cmd.c_str(), \"r\"));\n"
" if (!pipe) throw std::runtime_error(\"popen() failed!\");\n"
" while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {\n"
" result += buffer.data();\n"
" }\n"
" int exit_status = WEXITSTATUS(pclose(pipe.release()));\n"
" if (exit_status != 0) throw ShellException(cmd, exit_status);\n"
" return result;\n"
"}\n"
"inline void _cppsh_signal_handler(int signum) {\n"
" std::cerr << \"\\n[cppsh] CRITICAL ERROR: Script terminated by signal \" << signum << \"\\n\";\n";
if (emit_line_directives && stacktrace_mode >= 0) {
hoisted +=
"#if __has_include(<stacktrace>)\n"
" std::cerr << std::stacktrace::current() << \"\\n\";\n"
"#endif\n";
}
hoisted +=
" std::exit(signum);\n"
"}\n";
std::string raw_body = "";
int line_num = 0;
int last_emitted_line = 0;
while (std::getline(ss, line)) {
line_num++;
std::string tline = trim(line);
if (tline.starts_with("#!")) continue;
if (tline.starts_with("#include") || tline.starts_with("import ")) {
hoisted += line + "\n";
} else {
if (emit_line_directives && last_emitted_line != line_num - 1) {
raw_body += "#line " + std::to_string(line_num) + " \"" + filename + "\"\n";
}
raw_body += line + "\n";
last_emitted_line = line_num;
}
}
// Remove trailing newline from raw_body if it exists so we match exactly
if (!raw_body.empty() && raw_body.back() == '\n') {
raw_body.pop_back();
}
std::string body = "";
bool in_string = false;
bool in_char = false;
bool in_line_comment = false;
bool in_block_comment = false;
bool in_shell = false;
std::string shell_cmd = "";
for (size_t i = 0; i < raw_body.size(); ++i) {
char c = raw_body[i];
char next_c = (i + 1 < raw_body.size()) ? raw_body[i + 1] : '\0';
if (in_line_comment) {
if (c == '\n') in_line_comment = false;
body += c;
continue;
}
if (in_block_comment) {
if (c == '*' && next_c == '/') {
in_block_comment = false;
body += "*/";
i++;
} else {
body += c;
}
continue;
}
if (in_string) {
if (c == '\\') {
body += c;
if (next_c) { body += next_c; i++; }
} else if (c == '"') {
in_string = false;
body += c;
} else {
body += c;
}
continue;
}
if (in_char) {
if (c == '\\') {
body += c;
if (next_c) { body += next_c; i++; }
} else if (c == '\'') {
in_char = false;
body += c;
} else {
body += c;
}
continue;
}
if (in_shell) {
if (c == '`') {
in_shell = false;
// Process shell_cmd to find interpolations {var}
std::string format_str = "";
std::vector<std::string> vars;
bool in_var = false;
std::string current_var = "";
for (char sc : shell_cmd) {
if (in_var) {
if (sc == '}') {
in_var = false;
format_str += "{}";
vars.push_back(current_var);
current_var = "";
} else {
current_var += sc;
}
} else {
if (sc == '{') {
in_var = true;
} else {
format_str += sc;
}
}
}
body += "_cppsh_sh(std::format(R\"cppsh_delim(" + format_str + " 2>&1)cppsh_delim\"";
for (const auto& v : vars) {
body += ", _sh_escape(" + v + ")";
}
body += "))";
shell_cmd = "";
} else {
shell_cmd += c;
}
continue;
}
// Check for state transitions
if (c == '/' && next_c == '/') {
in_line_comment = true;
body += "//";
i++;
} else if (c == '/' && next_c == '*') {
in_block_comment = true;
body += "/*";
i++;
} else if (c == '"') {
in_string = true;
body += '"';
} else if (c == '\'') {
in_char = true;
body += '\'';
} else if (c == '`') {
in_shell = true;
} else {
body += c;
}
}
// Detect if the script defines its own int main() — if so, just inject helpers without wrapping
bool has_own_main = (raw_body.find("int main(") != std::string::npos ||
raw_body.find("int main (") != std::string::npos);
if (has_own_main) {
return hoisted + body + "\n";
}
return hoisted +
"int main(int argc, char* argv[]) {\n"
" std::signal(SIGSEGV, _cppsh_signal_handler);\n"
" std::signal(SIGABRT, _cppsh_signal_handler);\n"
" std::vector<std::string> args(argv, argv + argc);\n"
+ body + "\n"
" return 0;\n"
"}\n";
}
}