Repository navigation
Expand file tree
/
Copy pathrepl.cpp
More file actions
436 lines (415 loc) · 14.3 KB
/
Copy pathrepl.cpp
File metadata and controls
436 lines (415 loc) · 14.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
/**
* @file repl.cpp
* @brief Legacy REPL wrapper (kept for compatibility) with high-precision printing.
*/
#include "repl.h"
#include "clang/AST/Type.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Interpreter/Interpreter.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include <cmath>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <sstream>
#include <vector>
namespace {
static std::string formatFloatHighPrec(float v) {
std::string out;
llvm::raw_string_ostream ss(out);
if (std::isnan(v) || std::isinf(v))
ss << llvm::format("%g", v);
else if (v == static_cast<float>(static_cast<int64_t>(v)))
ss << llvm::format("%.1f", v);
else
ss << llvm::format("%#.9g", v);
ss << 'f';
return ss.str();
}
static std::string formatDoubleHighPrec(double v) {
std::string out;
llvm::raw_string_ostream ss(out);
if (std::isnan(v) || std::isinf(v))
ss << llvm::format("%g", v);
else if (v == static_cast<double>(static_cast<int64_t>(v)))
ss << llvm::format("%.1f", v);
else
ss << llvm::format("%#.17g", v);
return ss.str();
}
static std::string formatLongDoubleHighPrec(long double v) {
std::string out;
llvm::raw_string_ostream ss(out);
if (std::isnan(v) || std::isinf(v))
ss << llvm::format("%Lg", v);
else if (v == static_cast<long double>(static_cast<int64_t>(v)))
ss << llvm::format("%.1Lf", v);
else {
constexpr int prec = std::numeric_limits<long double>::max_digits10;
std::string fmt = "%#." + std::to_string(prec) + "Lg";
ss << llvm::format(fmt.c_str(), v);
}
ss << 'L';
return ss.str();
}
static void highPrecisionDump(const clang::Value &V) {
if (!V.isValid() || V.isVoid())
return;
std::string typeStr;
{
llvm::raw_string_ostream ts(typeStr);
V.printType(ts);
}
std::string dataStr;
bool handled = false;
switch (V.getKind()) {
case clang::Value::K_Float:
dataStr = formatFloatHighPrec(V.getFloat());
handled = true;
break;
case clang::Value::K_Double:
dataStr = formatDoubleHighPrec(V.getDouble());
handled = true;
break;
case clang::Value::K_LongDouble:
dataStr = formatLongDoubleHighPrec(V.getLongDouble());
handled = true;
break;
default:
break;
}
if (!handled) {
clang::QualType qt = V.getType();
clang::QualType nonRef = qt.getNonReferenceType();
const clang::Type *canon = nonRef.getCanonicalType().getTypePtr();
if (auto *bt = llvm::dyn_cast<clang::BuiltinType>(canon)) {
if ((bt->getKind() == clang::BuiltinType::Float ||
bt->getKind() == clang::BuiltinType::Double ||
bt->getKind() == clang::BuiltinType::LongDouble) &&
V.getKind() == clang::Value::K_PtrOrObj && V.getPtr()) {
void *p = V.getPtr();
if (bt->getKind() == clang::BuiltinType::Float) {
dataStr = formatFloatHighPrec(*static_cast<float *>(p));
handled = true;
} else if (bt->getKind() == clang::BuiltinType::Double) {
dataStr = formatDoubleHighPrec(*static_cast<double *>(p));
handled = true;
} else {
dataStr = formatLongDoubleHighPrec(*static_cast<long double *>(p));
handled = true;
}
}
}
}
if (!handled) {
llvm::raw_string_ostream ds(dataStr);
V.printData(ds);
}
llvm::outs() << "(" << typeStr << ") " << dataStr << "\n";
}
} // namespace
namespace repl {
Repl::Repl() = default;
Repl::~Repl() = default;
bool Repl::init(std::string &err) {
// Ensure native target is initialized even when VM scaffold is skipped
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
// Build incremental compiler – minimal args, O0, no optimization.
clang::IncrementalCompilerBuilder builder;
// Bare C++17 with include paths from system. Use default driver args.
// Explicit resource dir needed so builtin headers (stddef.h) are found.
#ifndef CLANG_RESOURCE_DIR
#define CLANG_RESOURCE_DIR "/usr/lib/clang/22"
#endif
std::string resDir = CLANG_RESOURCE_DIR;
{
std::error_code ec;
if (!std::filesystem::exists(resDir, ec)) {
const std::vector<std::string> alt = {"/usr/lib/llvm-22/lib/clang/22", "/usr/lib/clang/22",
"/usr/lib/llvm/lib/clang/22"};
for (auto &c : alt)
if (std::filesystem::exists(c, ec)) {
resDir = c;
break;
}
}
}
std::vector<const char *> args = {"-std=c++17", "-O0", "-resource-dir", resDir.c_str()};
builder.SetCompilerArgs(args);
auto CI = builder.CreateCpp();
if (!CI) {
llvm::handleAllErrors(CI.takeError(), [&](llvm::ErrorInfoBase &EIB) { err = EIB.message(); });
return false;
}
auto interpOrErr = clang::Interpreter::create(std::move(*CI));
if (!interpOrErr) {
llvm::handleAllErrors(interpOrErr.takeError(),
[&](llvm::ErrorInfoBase &EIB) { err = EIB.message(); });
return false;
}
interp_ = std::move(*interpOrErr);
initialized_ = true;
return true;
}
static inline std::string trim_copy(const std::string &s) {
size_t a = s.find_first_not_of(" \t\r\n");
if (a == std::string::npos)
return "";
size_t b = s.find_last_not_of(" \t\r\n");
return s.substr(a, b - a + 1);
}
static inline std::string rtrim_semi(const std::string &s) {
std::string t = trim_copy(s);
while (!t.empty() && (t.back() == ';' || t.back() == '\n' || t.back() == '\r' ||
t.back() == ' ' || t.back() == '\t')) {
// only strip one trailing ';' and surrounding whitespace for value printing
if (t.back() == ';') {
t.pop_back();
t = trim_copy(t);
break;
}
t.pop_back();
}
return t;
}
bool Repl::eval(const std::string &code, std::string &err) {
if (!initialized_ || !interp_) {
err = "REPL not initialized";
return false;
}
std::string trimmed = trim_copy(code);
if (trimmed.empty())
return true;
// Interpreter-like pre-processing: auto-add ';' for declarations missing it,
// but keep bare expressions without ';' for value printing (python-like).
// This avoids the diagnostic spam of trying then retrying.
std::string toEval = code;
bool needsSemi = false;
if (!trimmed.empty() && trimmed.back() != ';' && trimmed.back() != '}' && trimmed.back() != '{' &&
trimmed[0] != '#') {
// decl-like if contains '=' or starts with type keyword
bool isDecl = trimmed.find('=') != std::string::npos || trimmed.rfind("int ", 0) == 0 ||
trimmed.rfind("auto ", 0) == 0 || trimmed.rfind("float ", 0) == 0 ||
trimmed.rfind("double ", 0) == 0 || trimmed.rfind("char ", 0) == 0 ||
trimmed.rfind("std::", 0) == 0 || trimmed.rfind("const ", 0) == 0 ||
trimmed.rfind("string ", 0) == 0 || trimmed.rfind("long ", 0) == 0 ||
trimmed.rfind("unsigned ", 0) == 0;
if (isDecl) {
toEval = trimmed + ";\n";
needsSemi = true;
}
}
clang::Value V;
auto e = interp_->ParseAndExecute(toEval, &V);
if (e) {
std::string msg;
llvm::handleAllErrors(std::move(e), [&](llvm::ErrorInfoBase &EIB) { msg = EIB.message(); });
// If we pre-added ';' and still failed, try original without it (fallback)
if (needsSemi) {
clang::Value V2;
auto e2 = interp_->ParseAndExecute(code, &V2);
if (!e2) {
if (V2.isValid()) {
highPrecisionDump(V2);
std::cout << "\n";
}
if (!code.empty())
history_.push_back(code);
return true;
}
llvm::handleAllErrors(std::move(e2), [&](llvm::ErrorInfoBase &) {});
}
// No pre-processing case: try adding ';' as last resort (for other missing
// semi cases)
if (!needsSemi && !trimmed.empty() && trimmed.back() != ';' && trimmed.back() != '}' &&
trimmed.back() != '{') {
std::string withSemi = trimmed + ";\n";
clang::Value V2;
auto e2 = interp_->ParseAndExecute(withSemi, &V2);
if (!e2) {
if (V2.isValid()) {
highPrecisionDump(V2);
std::cout << "\n";
}
if (!code.empty())
history_.push_back(code);
return true;
}
// fall through to report original error if retry also fails
llvm::handleAllErrors(std::move(e2), [&](llvm::ErrorInfoBase &) {});
}
err = msg;
return false;
}
// Success – handle value printing like python interpreter:
// If input ended with ';', V is often invalid (statement). For raw
// expressions like "x;" we want to show value, so retry without trailing ';'.
if (V.isValid()) {
// Python-like: don't print void or std::ostream results (side effect only)
bool shouldPrint = true;
if (V.isVoid())
shouldPrint = false;
else if (trimmed.find("std::cout") != std::string::npos ||
trimmed.find("printf") != std::string::npos) {
// cout/printf already prints to stdout, don't also dump ostream value
shouldPrint = false;
}
if (shouldPrint) {
highPrecisionDump(V);
std::cout << "\n";
}
} else {
// Heuristic: if code looks like bare expression with trailing ';', try
// without it
std::string t = trim_copy(code);
if (!t.empty() && t.back() == ';') {
// quick filter: don't retry for declarations/controls/includes
bool likelyExpr = true;
// if contains declaration keywords, it's not bare expr
if (t.find("int ") != std::string::npos || t.find("auto ") != std::string::npos ||
t.find("#include") != std::string::npos || t.find("for") == 0 || t.find("while") == 0 ||
t.find("if") == 0 || t.find("struct ") != std::string::npos ||
t.find("class ") != std::string::npos || t.find("using ") != std::string::npos ||
t.find("std::cout") != std::string::npos || t.find("printf") != std::string::npos) {
likelyExpr = false;
}
// also check that after stripping ';' it's a short single expression (no
// ';' inside)
std::string stripped = rtrim_semi(code);
if (likelyExpr && stripped.find(';') == std::string::npos && stripped.size() < 200) {
clang::Value V2;
auto e2 = interp_->ParseAndExecute(stripped, &V2);
if (!e2 && V2.isValid()) {
highPrecisionDump(V2);
std::cout << "\n";
// Undo the just-executed expression's PTU side-effect? We already
// executed original "x;" which was no-op value, so duplicate
// execution is okay for pure expr. For impure like "x++;" double
// execution would double increment – avoid. Only show value if
// original had no side effect? For now, we re-executed once extra. To
// avoid double increment, we undo the first and keep second.
// Simplest: undo original's PTU and re-execute stripped once.
// But Interpreter::Undo is expensive; for now just print second value
// and keep both.
} else if (e2) {
llvm::handleAllErrors(std::move(e2), [&](llvm::ErrorInfoBase &) {});
}
}
}
}
if (!code.empty())
history_.push_back(code);
return true;
}
bool Repl::eval(const std::string &code, std::string &err, bool &incomplete) {
incomplete = false;
// Heuristic: empty is complete
std::string trimmed = code;
// Very low-level check: if braces/parens unbalanced, treat as incomplete
int braces = 0, parens = 0, brackets = 0;
for (char c : code) {
if (c == '{')
++braces;
else if (c == '}')
--braces;
else if (c == '(')
++parens;
else if (c == ')')
--parens;
else if (c == '[')
++brackets;
else if (c == ']')
--brackets;
}
if (braces > 0 || parens > 0 || brackets > 0) {
incomplete = true;
return true;
}
return eval(code, err);
}
bool Repl::loadFile(const std::string &path, std::string &err) {
std::ifstream f(path);
if (!f) {
err = "cannot open file: " + path;
return false;
}
std::ostringstream ss;
ss << f.rdbuf();
return eval(ss.str(), err);
}
bool Repl::loadLibrary(const std::string &path, std::string &err) {
if (!initialized_ || !interp_) {
err = "REPL not initialized";
return false;
}
if (auto e = interp_->LoadDynamicLibrary(path.c_str())) {
llvm::handleAllErrors(std::move(e), [&](llvm::ErrorInfoBase &EIB) { err = EIB.message(); });
return false;
}
return true;
}
bool Repl::undo(unsigned n, std::string &err) {
if (!initialized_ || !interp_) {
err = "REPL not initialized";
return false;
}
if (auto e = interp_->Undo(n)) {
llvm::handleAllErrors(std::move(e), [&](llvm::ErrorInfoBase &EIB) { err = EIB.message(); });
return false;
}
// Also pop from history
while (n-- > 0 && !history_.empty())
history_.pop_back();
return true;
}
void Repl::dump() const {
std::cout << "=== REPL history (" << history_.size() << " inputs) ===\n";
for (size_t i = 0; i < history_.size(); ++i) {
std::cout << "[" << i << "] " << history_[i];
if (history_[i].empty() || history_[i].back() != '\n')
std::cout << "\n";
std::cout << "---\n";
}
if (history_.empty())
std::cout << "(no inputs yet)\n";
}
void Repl::reset(std::string &err) {
std::string local;
interp_.reset();
initialized_ = false;
history_.clear();
if (!init(local)) {
err = local;
} else {
err.clear();
}
}
void Repl::help() const {
std::cout << "C++ REPL (LLVM VM, O0, no optimizations)\n"
"Commands:\n"
" :help :h show this help\n"
" :quit :exit :q exit REPL\n"
" :dump dump accumulated inputs\n"
" :reset reset interpreter state\n"
" :load <file> load and execute file\n"
" :lib <path> load dynamic library\n"
" :undo [n] undo last n inputs (default 1)\n"
"\n"
"Enter C++ code. Supports incremental declarations:\n"
" cpp> int x = 42;\n"
" cpp> x + 1\n"
" cpp> #include <iostream>\n"
" std::cout << \"hi\" << std::endl;\n"
" cpp> int add(int a,int b){return a+b;}\n"
" cpp> add(2,3)\n"
"\n"
"Multiline: unbalanced { ( [ keeps buffering with ...> prompt\n"
"Diagnostics: errors printed to stderr, history not updated on "
"failure\n";
}
} // namespace repl