-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconsole.cpp
More file actions
415 lines (359 loc) · 14.9 KB
/
Copy pathconsole.cpp
File metadata and controls
415 lines (359 loc) · 14.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
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
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "quanta/core/engine/Engine.h"
#include "quanta/core/runtime/Async.h"
#include "quanta/core/runtime/Generator.h"
#include "quanta/core/runtime/Iterator.h"
#include "quanta/core/runtime/ProxyReflect.h"
#include "quanta/lexer/Lexer.h"
#include "quanta/parser/Parser.h"
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cstdio>
#include <chrono>
#ifdef _WIN32
#include <conio.h>
#endif
#ifdef USE_READLINE
#include <readline/readline.h>
#include <readline/history.h>
#endif
using namespace Quanta;
static const std::string RESET = "";
static const std::string BOLD = "";
static const std::string RED = "";
static const std::string GREEN = "";
static const std::string YELLOW = "";
static const std::string BLUE = "";
static const std::string MAGENTA = "";
static const std::string CYAN = "";
class QuantaConsole {
private:
std::unique_ptr<Engine> engine_;
public:
bool has_es6_module_syntax(const std::string& content) {
std::istringstream stream(content);
std::string line;
bool in_block_comment = false;
while (std::getline(stream, line)) {
// Track block comment state
size_t pos = 0;
while (pos < line.size()) {
if (in_block_comment) {
size_t end = line.find("*/", pos);
if (end == std::string::npos) {
pos = line.size(); // whole line inside block comment
} else {
in_block_comment = false;
pos = end + 2;
}
continue;
}
if (pos + 1 < line.size() && line[pos] == '/' && line[pos+1] == '*') {
in_block_comment = true;
pos += 2;
continue;
}
if (pos + 1 < line.size() && line[pos] == '/' && line[pos+1] == '/') {
break; // rest of line is a line comment
}
break;
}
if (in_block_comment) continue;
size_t start = line.find_first_not_of(" \t\r\n");
if (start == std::string::npos) continue;
std::string trimmed = line.substr(start);
// Skip line comments
if (trimmed.size() >= 2 && trimmed[0] == '/' && trimmed[1] == '/') continue;
if (trimmed.substr(0, 6) == "import" || trimmed.substr(0, 6) == "export") {
if (trimmed.length() == 6 || std::isspace(trimmed[6]) || trimmed[6] == '{' || trimmed[6] == '*') {
return true;
}
}
}
return false;
}
private:
public:
QuantaConsole() {
engine_ = std::make_unique<Engine>();
bool init_result = engine_->initialize();
if (!init_result) {
std::cout << "Engine initialization failed!" << std::endl;
}
}
bool execute_as_module(const std::string& filename, bool silent = false) {
try {
if (!silent) {
std::cout << CYAN << "Auto-detected ES6 module syntax - loading as module..." << RESET << std::endl;
}
ModuleLoader* module_loader = engine_->get_module_loader();
if (!module_loader) {
if (!silent) {
std::cout << RED << "Error: ModuleLoader not available" << RESET << std::endl;
}
return false;
}
Module* module = module_loader->load_module(filename, "");
// Module top-level code can schedule microtasks and timers (dynamic import, top-level await) -- run them now or $DONE never fires.
if (Context* gctx = engine_->get_global_context()) {
engine_->run_event_loop_to_completion(*gctx);
}
if (module) {
// A body that suspended on a top-level await finished during
// the event loop above, and a rejected completion is how it
// reports the error it threw after suspending.
if (!module->has_thrown_exception()) {
Value evaluation = module->get_evaluation_promise();
if (Promise* p = Quanta::as_promise(evaluation.as_object_or_null())) {
if (p->get_state() == PromiseState::REJECTED) {
module->set_thrown_exception(p->take_settled_value());
}
}
}
if (module->has_thrown_exception()) {
Value exc = module->get_thrown_exception();
std::cerr << exc.to_string() << std::endl;
return false;
}
if (!silent) {
std::cout << GREEN << "Module loaded successfully!" << RESET << std::endl;
}
return true;
} else {
if (module_loader->has_last_module_exception()) {
std::cerr << module_loader->get_last_module_exception().to_string() << std::endl;
} else if (!silent) {
std::cout << RED << "Module loading failed!" << RESET << std::endl;
}
return false;
}
} catch (const std::exception& e) {
std::cerr << "SyntaxError: " << e.what() << std::endl;
return false;
}
}
void show_tokens(const std::string& input) {
try {
Lexer lexer(input);
TokenSequence tokens = lexer.tokenize();
std::cout << BLUE << "Tokens:\n" << RESET;
for (size_t i = 0; i < tokens.size(); ++i) {
const Token& token = tokens[i];
if (token.get_type() == TokenType::EOF_TOKEN) break;
std::cout << " " << i << ": " << YELLOW << token.type_name() << RESET
<< " '" << tokens.text_of(token) << "'\n";
}
} catch (const std::exception& e) {
std::cout << RED << "Lexer error: " << e.what() << RESET << "\n";
}
}
void show_ast(const std::string& input) {
try {
Lexer lexer(input);
TokenSequence tokens = lexer.tokenize();
Parser parser(tokens);
auto ast = parser.parse_expression();
std::cout << BLUE << "AST Structure:\n" << RESET;
std::cout << " " << ast->to_string() << "\n";
} catch (const std::exception& e) {
std::cout << RED << "Parser error: " << e.what() << RESET << "\n";
}
}
bool evaluate_expression(const std::string& input, bool show_prompt = true, bool show_result = true, const std::string& filename = "<console>") {
try {
auto start = std::chrono::high_resolution_clock::now();
auto result = engine_->execute(input, filename);
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
if (!result.success) {
std::cout << RED;
if (filename != "<console>" && (result.line_number > 0 || result.column_number > 0)) {
std::cout << filename;
if (result.line_number > 0) {
std::cout << ":" << result.line_number;
if (result.column_number > 0) {
std::cout << ":" << result.column_number;
}
}
std::cout << "\n";
}
std::cout << result.error_message << RESET << std::endl;
return false;
}
if (show_result && !result.value.is_undefined()) {
std::cout << GREEN << result.value.to_string() << RESET << std::endl;
}
return true;
} catch (const std::exception& e) {
std::cout << RED << "Error: " << e.what() << RESET << std::endl;
return false;
}
}
void clear_screen() {
std::cout << "\033[2J\033[H";
}
std::string get_input() {
#ifdef USE_READLINE
std::string prompt = GREEN + ">> " + RESET;
char* line = readline(prompt.c_str());
if (!line) return "";
std::string input(line);
if (!input.empty()) {
add_history(line);
}
free(line);
return input;
#else
std::cout << GREEN << ">> " << RESET;
std::string input;
if (!std::getline(std::cin, input)) {
return "";
}
return input;
#endif
}
void run() {
std::string input;
while (true) {
input = get_input();
if (input.empty()) {
break;
}
if (input[0] == '.') {
std::istringstream iss(input);
std::string command;
iss >> command;
if (command == ".quit" || command == ".exit") {
std::cout << CYAN << "Goodbye!\n" << RESET;
break;
} else if (command == ".help") {
std::cout << GREEN << " .help" << RESET << " - Show this help message\n";
std::cout << GREEN << " .quit" << RESET << " - Exit the console\n";
std::cout << GREEN << " .clear" << RESET << " - Clear the screen\n";
std::cout << GREEN << " .tokens" << RESET << " - Show tokens for expression\n";
std::cout << GREEN << " .ast" << RESET << " - Show AST for expression\n";
} else if (command == ".tokens") {
std::string rest;
std::getline(iss, rest);
if (!rest.empty()) {
rest.erase(0, rest.find_first_not_of(" \t"));
show_tokens(rest);
} else {
std::cout << YELLOW << "Usage: .tokens <expression>\n" << RESET;
}
} else if (command == ".ast") {
std::string rest;
std::getline(iss, rest);
if (!rest.empty()) {
rest.erase(0, rest.find_first_not_of(" \t"));
show_ast(rest);
} else {
std::cout << YELLOW << "Usage: .ast <expression>\n" << RESET;
}
} else if (command == ".clear") {
clear_screen();
} else {
std::cout << RED << "Unknown command: " << command << RESET << "\n";
std::cout << "Type " << BOLD << ".help" << RESET << " for available commands.\n";
}
} else {
evaluate_expression(input);
}
}
}
};
int main(int argc, char* argv[]) {
try {
bool execute_code = false;
bool force_module = false;
std::string code_to_execute;
std::string filename;
std::vector<std::string> preloads;
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "-c" && i + 1 < argc) {
execute_code = true;
code_to_execute = argv[i + 1];
i++;
continue;
} else if (arg == "--module") {
force_module = true;
continue;
} else if (arg == "--preload" && i + 1 < argc) {
preloads.push_back(argv[i + 1]);
i++;
continue;
} else if (arg == "--version" || arg == "-v") {
#ifdef QUANTA_VERSION
std::cout << QUANTA_VERSION << std::endl;
#else
std::cout << "Version unknown, check build configuration" << std::endl;
#endif
return 0;
} else if (arg == "--help" || arg == "-h") {
std::cout << "Usage: quanta [options] [file]\n\n"
<< "Options:\n"
<< " -c <code> Execute the given code and exit\n"
<< " --module Force-load the file as an ES module\n"
<< " --preload <f> Run <f> as a script in the same realm first (repeatable)\n"
<< " -v, --version Print the engine version and exit\n"
<< " -h, --help Show this help message and exit\n\n"
<< "With no file and no -c, starts the interactive REPL.\n";
return 0;
} else if (arg.find("--") == 0) {
continue;
} else if (filename.empty()) {
filename = arg;
}
}
QuantaConsole console;
// Preloads share the realm with whatever runs next, which is the only
// way a module can see names a script defined: its own imports are
// instantiated before any of its statements run, so code inside the
// module is already too late. They run ahead of -c and of the REPL for
// the same reason -- the flag means the same thing wherever it appears.
for (const std::string& pre : preloads) {
std::ifstream pf(pre);
if (!pf.is_open()) {
std::cerr << "Error: Cannot open preload file " << pre << std::endl;
return 1;
}
std::stringstream pbuf;
pbuf << pf.rdbuf();
if (!console.evaluate_expression(pbuf.str(), false, false, pre)) return 1;
}
if (execute_code) {
bool success = console.evaluate_expression(code_to_execute, false, true);
return success ? 0 : 1;
}
if (!filename.empty()) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error: Cannot open file " << filename << std::endl;
return 1;
}
std::stringstream buffer;
buffer << file.rdbuf();
std::string content = buffer.str();
bool success = false;
bool run_as_module = force_module;
if (run_as_module) {
success = console.execute_as_module(filename, true);
} else {
success = console.evaluate_expression(content, false, false, filename);
}
return success ? 0 : 1;
}
console.run();
return 0;
} catch (const std::exception& e) {
std::cerr << "Fatal error: " << e.what() << std::endl;
return 1;
}
}