]>
Commit | Line | Data |
---|---|---|
1 | /* Cycript - The Truly Universal Scripting Language | |
2 | * Copyright (C) 2009-2016 Jay Freeman (saurik) | |
3 | */ | |
4 | ||
5 | /* GNU Affero General Public License, Version 3 {{{ */ | |
6 | /* | |
7 | * This program is free software: you can redistribute it and/or modify | |
8 | * it under the terms of the GNU Affero General Public License as published by | |
9 | * the Free Software Foundation, either version 3 of the License, or | |
10 | * (at your option) any later version. | |
11 | ||
12 | * This program is distributed in the hope that it will be useful, | |
13 | * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
15 | * GNU Affero General Public License for more details. | |
16 | ||
17 | * You should have received a copy of the GNU Affero General Public License | |
18 | * along with this program. If not, see <http://www.gnu.org/licenses/>. | |
19 | **/ | |
20 | /* }}} */ | |
21 | ||
22 | #include "cycript.hpp" | |
23 | ||
24 | #ifdef CY_EXECUTE | |
25 | #include "JavaScript.hpp" | |
26 | #endif | |
27 | ||
28 | #include <cstdio> | |
29 | #include <complex> | |
30 | #include <fstream> | |
31 | #include <sstream> | |
32 | ||
33 | #ifdef HAVE_READLINE_H | |
34 | #include <readline.h> | |
35 | #else | |
36 | #include <readline/readline.h> | |
37 | #endif | |
38 | ||
39 | #ifdef HAVE_HISTORY_H | |
40 | #include <history.h> | |
41 | #else | |
42 | #include <readline/history.h> | |
43 | #endif | |
44 | ||
45 | #include <errno.h> | |
46 | #include <getopt.h> | |
47 | #include <setjmp.h> | |
48 | #include <signal.h> | |
49 | #include <unistd.h> | |
50 | ||
51 | #include <sys/socket.h> | |
52 | #include <sys/types.h> | |
53 | #include <sys/stat.h> | |
54 | #include <fcntl.h> | |
55 | #include <netdb.h> | |
56 | ||
57 | #include <sys/ioctl.h> | |
58 | #include <sys/types.h> | |
59 | #include <sys/socket.h> | |
60 | #include <netinet/in.h> | |
61 | #include <sys/un.h> | |
62 | ||
63 | #include <dlfcn.h> | |
64 | #include <pwd.h> | |
65 | #include <term.h> | |
66 | ||
67 | #ifdef __APPLE__ | |
68 | #include <mach/mach_time.h> | |
69 | #endif | |
70 | ||
71 | #include "Code.hpp" | |
72 | #include "Driver.hpp" | |
73 | #include "Error.hpp" | |
74 | #include "Highlight.hpp" | |
75 | #include "Syntax.hpp" | |
76 | ||
77 | extern "C" int rl_display_fixed; | |
78 | extern "C" int _rl_vis_botlin; | |
79 | extern "C" int _rl_last_c_pos; | |
80 | extern "C" int _rl_last_v_pos; | |
81 | ||
82 | typedef std::complex<int> CYCursor; | |
83 | ||
84 | static CYCursor current_; | |
85 | static int width_; | |
86 | static size_t point_; | |
87 | ||
88 | unsigned CYDisplayWidth() { | |
89 | struct winsize info; | |
90 | if (ioctl(1, TIOCGWINSZ, &info) != -1) | |
91 | return info.ws_col; | |
92 | return tgetnum(const_cast<char *>("co")); | |
93 | } | |
94 | ||
95 | void CYDisplayOutput_(bool display, const char *&data) { | |
96 | for (;; ++data) { | |
97 | char next(*data); | |
98 | if (next == '\0' || next == CYIgnoreEnd) | |
99 | return; | |
100 | if (display) | |
101 | putchar(next); | |
102 | } | |
103 | } | |
104 | ||
105 | CYCursor CYDisplayOutput(bool display, int width, const char *data, ssize_t offset = 0) { | |
106 | CYCursor point(current_); | |
107 | ||
108 | for (;;) { | |
109 | if (offset-- == 0) | |
110 | point = current_; | |
111 | switch (char next = *data++) { | |
112 | case '\0': | |
113 | return point; | |
114 | break; | |
115 | ||
116 | case CYIgnoreStart: | |
117 | CYDisplayOutput_(display, data); | |
118 | case CYIgnoreEnd: | |
119 | ++offset; | |
120 | break; | |
121 | ||
122 | default: | |
123 | if (display) | |
124 | putchar(next); | |
125 | current_ += CYCursor(0, 1); | |
126 | if (current_.imag() != width) | |
127 | break; | |
128 | current_ = CYCursor(current_.real() + 1, 0); | |
129 | if (display) | |
130 | putp(clr_eos); | |
131 | break; | |
132 | ||
133 | case '\n': | |
134 | current_ = CYCursor(current_.real() + 1, 4); | |
135 | if (display) { | |
136 | putp(clr_eol); | |
137 | putchar('\n'); | |
138 | putchar(' '); | |
139 | putchar(' '); | |
140 | putchar(' '); | |
141 | putchar(' '); | |
142 | } | |
143 | break; | |
144 | ||
145 | } | |
146 | } | |
147 | } | |
148 | ||
149 | void CYDisplayMove_(char *negative, char *positive, int offset) { | |
150 | if (offset < 0) | |
151 | putp(tparm(negative, -offset)); | |
152 | else if (offset > 0) | |
153 | putp(tparm(positive, offset)); | |
154 | } | |
155 | ||
156 | void CYDisplayMove(CYCursor target) { | |
157 | CYCursor offset(target - current_); | |
158 | ||
159 | CYDisplayMove_(parm_up_cursor, parm_down_cursor, offset.real()); | |
160 | ||
161 | if (char *parm = tparm(column_address, target.imag())) | |
162 | putp(parm); | |
163 | else | |
164 | CYDisplayMove_(parm_left_cursor, parm_right_cursor, offset.imag()); | |
165 | ||
166 | current_ = target; | |
167 | } | |
168 | ||
169 | void CYDisplayUpdate() { | |
170 | current_ = CYCursor(_rl_last_v_pos, _rl_last_c_pos); | |
171 | ||
172 | const char *prompt(rl_display_prompt); | |
173 | ||
174 | std::ostringstream stream; | |
175 | CYLexerHighlight(rl_line_buffer, rl_end, stream, true); | |
176 | std::string string(stream.str()); | |
177 | const char *buffer(string.c_str()); | |
178 | ||
179 | int width(CYDisplayWidth()); | |
180 | if (width_ != width) { | |
181 | current_ = CYCursor(); | |
182 | CYDisplayOutput(false, width, prompt); | |
183 | current_ = CYDisplayOutput(false, width, buffer, point_); | |
184 | } | |
185 | ||
186 | CYDisplayMove(CYCursor()); | |
187 | CYDisplayOutput(true, width, prompt); | |
188 | CYCursor target(CYDisplayOutput(true, width, stream.str().c_str(), rl_point)); | |
189 | ||
190 | _rl_vis_botlin = current_.real(); | |
191 | ||
192 | if (current_.imag() == 0) | |
193 | CYDisplayOutput(true, width, " "); | |
194 | putp(clr_eos); | |
195 | ||
196 | CYDisplayMove(target); | |
197 | fflush(stdout); | |
198 | ||
199 | _rl_last_v_pos = current_.real(); | |
200 | _rl_last_c_pos = current_.imag(); | |
201 | ||
202 | width_ = width; | |
203 | point_ = rl_point; | |
204 | } | |
205 | ||
206 | static volatile enum { | |
207 | Working, | |
208 | Parsing, | |
209 | Running, | |
210 | Sending, | |
211 | Waiting, | |
212 | } mode_; | |
213 | ||
214 | static jmp_buf ctrlc_; | |
215 | ||
216 | static void sigint(int) { | |
217 | switch (mode_) { | |
218 | case Working: | |
219 | return; | |
220 | case Parsing: | |
221 | longjmp(ctrlc_, 1); | |
222 | case Running: | |
223 | #ifndef __ANDROID__ | |
224 | CYCancel(); | |
225 | #endif | |
226 | return; | |
227 | case Sending: | |
228 | return; | |
229 | case Waiting: | |
230 | return; | |
231 | } | |
232 | } | |
233 | ||
234 | static bool bison_; | |
235 | static bool timing_; | |
236 | static bool strict_; | |
237 | static bool pretty_; | |
238 | ||
239 | void Setup(CYDriver &driver) { | |
240 | if (bison_) | |
241 | driver.debug_ = 1; | |
242 | if (strict_) | |
243 | driver.strict_ = true; | |
244 | } | |
245 | ||
246 | void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) { | |
247 | out.pretty_ = pretty_; | |
248 | if (lower) | |
249 | driver.Replace(options); | |
250 | } | |
251 | ||
252 | static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) { | |
253 | const char *json; | |
254 | uint32_t size; | |
255 | ||
256 | if (client == -1) { | |
257 | mode_ = Running; | |
258 | #ifdef CY_EXECUTE | |
259 | json = CYExecute(CYGetJSContext(), pool, code); | |
260 | #else | |
261 | json = NULL; | |
262 | #endif | |
263 | mode_ = Working; | |
264 | if (json == NULL) | |
265 | size = 0; | |
266 | else | |
267 | size = strlen(json); | |
268 | } else { | |
269 | mode_ = Sending; | |
270 | size = code.size; | |
271 | _assert(CYSendAll(client, &size, sizeof(size))); | |
272 | _assert(CYSendAll(client, code.data, code.size)); | |
273 | mode_ = Waiting; | |
274 | _assert(CYRecvAll(client, &size, sizeof(size))); | |
275 | if (size == _not(uint32_t)) | |
276 | json = NULL; | |
277 | else { | |
278 | char *temp(new(pool) char[size + 1]); | |
279 | _assert(CYRecvAll(client, temp, size)); | |
280 | temp[size] = '\0'; | |
281 | json = temp; | |
282 | } | |
283 | mode_ = Working; | |
284 | } | |
285 | ||
286 | return CYUTF8String(json, size); | |
287 | } | |
288 | ||
289 | static CYUTF8String Run(CYPool &pool, int client, const std::string &code) { | |
290 | return Run(pool, client, CYUTF8String(code.c_str(), code.size())); | |
291 | } | |
292 | ||
293 | static std::ostream *out_; | |
294 | ||
295 | static void Output(CYUTF8String json, std::ostream *out, bool expand = false, bool reparse = false) { | |
296 | CYPool pool; | |
297 | ||
298 | if (reparse) do { | |
299 | CYStream stream(json.data, json.data + json.size); | |
300 | CYDriver driver(pool, stream); | |
301 | if (driver.Parse(CYMarkExpression)) | |
302 | break; | |
303 | std::stringbuf str; | |
304 | CYOptions options; | |
305 | CYOutput out(str, options); | |
306 | out.pretty_ = true; | |
307 | out << *driver.context_; | |
308 | std::string data(str.str()); | |
309 | json = CYPoolUTF8String(pool, data); | |
310 | if (json.size == 0) | |
311 | json.data = NULL; | |
312 | } while (false); | |
313 | ||
314 | const char *data(json.data); | |
315 | size_t size(json.size); | |
316 | ||
317 | if (data == NULL || out == NULL) | |
318 | return; | |
319 | ||
320 | if (!expand || | |
321 | data[0] != '@' && data[0] != '"' && data[0] != '\'' || | |
322 | data[0] == '@' && data[1] != '"' && data[1] != '\'' | |
323 | ) | |
324 | CYLexerHighlight(data, size, *out); | |
325 | else for (size_t i(0); i != size; ++i) | |
326 | if (data[i] != '\\') | |
327 | *out << data[i]; | |
328 | else switch(data[++i]) { | |
329 | case '\0': goto done; | |
330 | case '\\': *out << '\\'; break; | |
331 | case '\'': *out << '\''; break; | |
332 | case '"': *out << '"'; break; | |
333 | case 'b': *out << '\b'; break; | |
334 | case 'f': *out << '\f'; break; | |
335 | case 'n': *out << '\n'; break; | |
336 | case 'r': *out << '\r'; break; | |
337 | case 't': *out << '\t'; break; | |
338 | case 'v': *out << '\v'; break; | |
339 | default: *out << '\\'; --i; break; | |
340 | } | |
341 | ||
342 | done: | |
343 | *out << std::endl; | |
344 | } | |
345 | ||
346 | int (*append_history$)(int, const char *); | |
347 | ||
348 | static std::string command_; | |
349 | ||
350 | static int client_; | |
351 | ||
352 | static CYUTF8String Run(CYPool &pool, const std::string &code) { | |
353 | return Run(pool, client_, code); | |
354 | } | |
355 | ||
356 | static char **Complete(const char *word, int start, int end) { | |
357 | rl_attempted_completion_over = ~0; | |
358 | std::string line(rl_line_buffer, start); | |
359 | char **values(CYComplete(word, command_ + line, &Run)); | |
360 | mode_ = Parsing; | |
361 | return values; | |
362 | } | |
363 | ||
364 | // need char *, not const char * | |
365 | static char name_[] = "cycript"; | |
366 | static char break_[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]"; | |
367 | ||
368 | class History { | |
369 | private: | |
370 | std::string histfile_; | |
371 | size_t histlines_; | |
372 | ||
373 | public: | |
374 | History(std::string histfile) : | |
375 | histfile_(histfile), | |
376 | histlines_(0) | |
377 | { | |
378 | read_history(histfile_.c_str()); | |
379 | ||
380 | for (HIST_ENTRY *history((history_set_pos(0), current_history())); history; history = next_history()) | |
381 | for (char *character(history->line); *character; ++character) | |
382 | if (*character == '\x01') *character = '\n'; | |
383 | } | |
384 | ||
385 | ~History() { try { | |
386 | for (HIST_ENTRY *history((history_set_pos(0), current_history())); history; history = next_history()) | |
387 | for (char *character(history->line); *character; ++character) | |
388 | if (*character == '\n') *character = '\x01'; | |
389 | ||
390 | if (append_history$ != NULL) { | |
391 | int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600))); | |
392 | _syscall(close(fd)); | |
393 | _assert((*append_history$)(histlines_, histfile_.c_str()) == 0); | |
394 | } else { | |
395 | _assert(write_history(histfile_.c_str()) == 0); | |
396 | } | |
397 | } catch (const CYException &error) { | |
398 | CYPool pool; | |
399 | std::cout << error.PoolCString(pool) << std::endl; | |
400 | } } | |
401 | ||
402 | void operator +=(std::string command) { | |
403 | add_history(command.c_str()); | |
404 | ++histlines_; | |
405 | } | |
406 | }; | |
407 | ||
408 | template <typename Type_> | |
409 | static Type_ *CYmemrchr(Type_ *data, Type_ value, size_t size) { | |
410 | while (size != 0) | |
411 | if (data[--size] == value) | |
412 | return data + size; | |
413 | return NULL; | |
414 | } | |
415 | ||
416 | static void _lblcall(int (*command)(int, int), int count, int key) { | |
417 | int last(_rl_last_c_pos); | |
418 | // rl_rubout crashes in _rl_erase_at_end_of_line if _rl_last_c_pos != 0 | |
419 | if (command == &rl_rubout) | |
420 | _rl_last_c_pos = 0; | |
421 | for (int i(0); i != count; ++i) | |
422 | if (command(1, key) != 0) | |
423 | _assert(false); | |
424 | _rl_last_c_pos = last; | |
425 | } | |
426 | ||
427 | static int CYConsoleKeyReturn(int count, int key) { | |
428 | if (rl_point != rl_end) { | |
429 | if (memchr(rl_line_buffer, '\n', rl_end) == NULL) { | |
430 | _lblcall(&rl_newline, count, key); | |
431 | return 0; | |
432 | } | |
433 | ||
434 | insert: | |
435 | char *before(CYmemrchr(rl_line_buffer, '\n', rl_point)); | |
436 | if (before == NULL) | |
437 | before = rl_line_buffer; | |
438 | ||
439 | int space(before + 1 - rl_line_buffer); | |
440 | while (space != rl_point && rl_line_buffer[space] == ' ') | |
441 | ++space; | |
442 | ||
443 | int adjust(rl_line_buffer + space - 1 - before); | |
444 | if (space == rl_point && adjust != 0) | |
445 | _lblcall(&rl_rubout, adjust, '\b'); | |
446 | ||
447 | _lblcall(&rl_insert, count, '\n'); | |
448 | if (adjust != 0) | |
449 | _lblcall(&rl_insert, adjust, ' '); | |
450 | ||
451 | return 0; | |
452 | } | |
453 | ||
454 | bool done(false); | |
455 | if (rl_line_buffer[0] == '?') | |
456 | done = true; | |
457 | else { | |
458 | std::string command(rl_line_buffer, rl_end); | |
459 | command += '\n'; | |
460 | std::stringbuf stream(command); | |
461 | ||
462 | size_t last(std::string::npos); | |
463 | for (size_t i(0); i != std::string::npos; i = command.find('\n', i + 1)) | |
464 | ++last; | |
465 | ||
466 | CYPool pool; | |
467 | CYDriver driver(pool, stream); | |
468 | if (driver.Parse() || !driver.errors_.empty()) | |
469 | for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) { | |
470 | if (error->location_.begin.line != last + 1) | |
471 | done = true; | |
472 | break; | |
473 | } | |
474 | else | |
475 | done = true; | |
476 | } | |
477 | ||
478 | if (done) { | |
479 | _lblcall(&rl_newline, count, key); | |
480 | return 0; | |
481 | } | |
482 | ||
483 | // XXX: this was the most obvious fix, but is seriously dumb | |
484 | goto insert; | |
485 | } | |
486 | ||
487 | static int CYConsoleKeyUp(int count, int key) { | |
488 | for (; count != 0; --count) { | |
489 | char *after(CYmemrchr(rl_line_buffer, '\n', rl_point)); | |
490 | if (after == NULL) { | |
491 | if (int value = rl_get_previous_history(1, key)) | |
492 | return value; | |
493 | continue; | |
494 | } | |
495 | ||
496 | char *before(CYmemrchr(rl_line_buffer, '\n', after - rl_line_buffer)); | |
497 | if (before == NULL) | |
498 | before = rl_line_buffer - 1; | |
499 | ||
500 | ptrdiff_t offset(rl_line_buffer + rl_point - after); | |
501 | if (offset > after - before) | |
502 | rl_point = after - rl_line_buffer; | |
503 | else | |
504 | rl_point = before + offset - rl_line_buffer; | |
505 | } | |
506 | ||
507 | return 0; | |
508 | } | |
509 | ||
510 | static int CYConsoleKeyDown(int count, int key) { | |
511 | for (; count != 0; --count) { | |
512 | char *after(static_cast<char *>(memchr(rl_line_buffer + rl_point, '\n', rl_end - rl_point))); | |
513 | if (after == NULL) { | |
514 | int where(where_history()); | |
515 | if (int value = rl_get_next_history(1, key)) | |
516 | return value; | |
517 | if (where != where_history()) { | |
518 | char *first(static_cast<char *>(memchr(rl_line_buffer, '\n', rl_end))); | |
519 | if (first != NULL) | |
520 | rl_point = first - 1 - rl_line_buffer; | |
521 | } | |
522 | continue; | |
523 | } | |
524 | ||
525 | char *before(CYmemrchr(rl_line_buffer, '\n', rl_point)); | |
526 | if (before == NULL) | |
527 | before = rl_line_buffer - 1; | |
528 | ||
529 | char *next(static_cast<char *>(memchr(after + 1, '\n', rl_line_buffer + rl_end - after - 1))); | |
530 | if (next == NULL) | |
531 | next = rl_line_buffer + rl_end; | |
532 | ||
533 | ptrdiff_t offset(rl_line_buffer + rl_point - before); | |
534 | if (offset > next - after) | |
535 | rl_point = next - rl_line_buffer; | |
536 | else | |
537 | rl_point = after + offset - rl_line_buffer; | |
538 | } | |
539 | ||
540 | return 0; | |
541 | } | |
542 | ||
543 | static int CYConsoleLineBegin(int count, int key) { | |
544 | while (rl_point != 0 && rl_line_buffer[rl_point - 1] != '\n') | |
545 | --rl_point; | |
546 | return 0; | |
547 | } | |
548 | ||
549 | static int CYConsoleLineEnd(int count, int key) { | |
550 | while (rl_point != rl_end && rl_line_buffer[rl_point] != '\n') | |
551 | ++rl_point; | |
552 | if (rl_point != rl_end && rl_editing_mode == 0) | |
553 | --rl_point; | |
554 | return 0; | |
555 | } | |
556 | ||
557 | static int CYConsoleKeyBack(int count, int key) { | |
558 | for (; count != 0; --count) { | |
559 | if (rl_point == 0) | |
560 | return 1; | |
561 | ||
562 | char *before(CYmemrchr(rl_line_buffer, '\n', rl_point)); | |
563 | if (before == NULL) { | |
564 | int adjust(std::min(count, rl_point)); | |
565 | _lblcall(&rl_rubout, adjust, key); | |
566 | count -= adjust - 1; | |
567 | continue; | |
568 | } | |
569 | ||
570 | int start(before + 1 - rl_line_buffer); | |
571 | if (start == rl_point) rubout: { | |
572 | _lblcall(&rl_rubout, 1, key); | |
573 | continue; | |
574 | } | |
575 | ||
576 | for (int i(start); i != rl_point; ++i) | |
577 | if (rl_line_buffer[i] != ' ') | |
578 | goto rubout; | |
579 | _lblcall(&rl_rubout, (rl_point - start) % 4 ?: 4, key); | |
580 | } | |
581 | ||
582 | return 0; | |
583 | } | |
584 | ||
585 | static int CYConsoleKeyTab(int count, int key) { | |
586 | char *before(CYmemrchr(rl_line_buffer, '\n', rl_point)); | |
587 | if (before == NULL) complete: | |
588 | return rl_complete_internal(rl_completion_mode(&CYConsoleKeyTab)); | |
589 | int start(before + 1 - rl_line_buffer); | |
590 | for (int i(start); i != rl_point; ++i) | |
591 | if (rl_line_buffer[i] != ' ') | |
592 | goto complete; | |
593 | _lblcall(&rl_insert, 4 - (rl_point - start) % 4, ' '); | |
594 | return 0; | |
595 | } | |
596 | ||
597 | static void CYConsoleRemapBind(Keymap map, rl_command_func_t *from, rl_command_func_t *to) { | |
598 | char **keyseqs(rl_invoking_keyseqs_in_map(from, map)); | |
599 | if (keyseqs == NULL) | |
600 | return; | |
601 | for (char **keyseq(keyseqs); *keyseq != NULL; ++keyseq) { | |
602 | rl_bind_keyseq_in_map(*keyseq, to, map); | |
603 | free(*keyseq); | |
604 | } | |
605 | free(keyseqs); | |
606 | } | |
607 | ||
608 | static void CYConsoleRemapKeys(Keymap map) { | |
609 | CYConsoleRemapBind(map, &rl_beg_of_line, &CYConsoleLineBegin); | |
610 | CYConsoleRemapBind(map, &rl_end_of_line, &CYConsoleLineEnd); | |
611 | ||
612 | CYConsoleRemapBind(map, &rl_get_previous_history, &CYConsoleKeyUp); | |
613 | CYConsoleRemapBind(map, &rl_get_next_history, &CYConsoleKeyDown); | |
614 | ||
615 | CYConsoleRemapBind(map, &rl_rubout, &CYConsoleKeyBack); | |
616 | CYConsoleRemapBind(map, &rl_complete, &CYConsoleKeyTab); | |
617 | } | |
618 | ||
619 | static void CYConsolePrepTerm(int meta) { | |
620 | rl_prep_terminal(meta); | |
621 | ||
622 | CYConsoleRemapKeys(emacs_standard_keymap); | |
623 | CYConsoleRemapKeys(emacs_meta_keymap); | |
624 | CYConsoleRemapKeys(emacs_ctlx_keymap); | |
625 | CYConsoleRemapKeys(vi_insertion_keymap); | |
626 | CYConsoleRemapKeys(vi_movement_keymap); | |
627 | } | |
628 | ||
629 | static void CYOutputRun(const std::string &code, bool expand = false, bool reparse = false) { | |
630 | CYPool pool; | |
631 | Output(Run(pool, client_, code), &std::cout, expand, reparse); | |
632 | } | |
633 | ||
634 | static void Console(CYOptions &options) { | |
635 | std::string basedir; | |
636 | #ifdef __ANDROID__ | |
637 | basedir = "/data/local/tmp"; | |
638 | #else | |
639 | if (const char *home = getenv("HOME")) | |
640 | basedir = home; | |
641 | else { | |
642 | passwd *passwd; | |
643 | if (const char *username = getenv("LOGNAME")) | |
644 | passwd = getpwnam(username); | |
645 | else | |
646 | passwd = getpwuid(getuid()); | |
647 | basedir = passwd->pw_dir; | |
648 | } | |
649 | #endif | |
650 | ||
651 | basedir += "/.cycript"; | |
652 | mkdir(basedir.c_str(), 0700); | |
653 | ||
654 | rl_initialize(); | |
655 | rl_readline_name = name_; | |
656 | ||
657 | History history(basedir + "/history"); | |
658 | ||
659 | bool bypass(false); | |
660 | bool debug(false); | |
661 | bool expand(false); | |
662 | bool lower(true); | |
663 | bool reparse(false); | |
664 | ||
665 | out_ = &std::cout; | |
666 | ||
667 | rl_completer_word_break_characters = break_; | |
668 | rl_attempted_completion_function = &Complete; | |
669 | ||
670 | if (cur_term != NULL) { | |
671 | rl_redisplay_function = CYDisplayUpdate; | |
672 | rl_prep_term_function = CYConsolePrepTerm; | |
673 | } | |
674 | ||
675 | CYOutputRun(""); | |
676 | ||
677 | struct sigaction action; | |
678 | sigemptyset(&action.sa_mask); | |
679 | action.sa_handler = &sigint; | |
680 | action.sa_flags = 0; | |
681 | sigaction(SIGINT, &action, NULL); | |
682 | ||
683 | for (;;) { | |
684 | if (setjmp(ctrlc_) != 0) { | |
685 | mode_ = Working; | |
686 | *out_ << std::endl; | |
687 | continue; | |
688 | } | |
689 | ||
690 | if (bypass) { | |
691 | rl_bind_key('\r', &rl_newline); | |
692 | rl_bind_key('\n', &rl_newline); | |
693 | } else { | |
694 | rl_bind_key('\r', &CYConsoleKeyReturn); | |
695 | rl_bind_key('\n', &CYConsoleKeyReturn); | |
696 | } | |
697 | ||
698 | mode_ = Parsing; | |
699 | char *line(readline("cy# ")); | |
700 | mode_ = Working; | |
701 | ||
702 | if (line == NULL) { | |
703 | *out_ << std::endl; | |
704 | break; | |
705 | } | |
706 | ||
707 | std::string command(line); | |
708 | free(line); | |
709 | if (command.empty()) | |
710 | continue; | |
711 | history += command; | |
712 | ||
713 | if (command[0] == '?') { | |
714 | std::string data(command.substr(1)); | |
715 | if (data == "bypass") { | |
716 | bypass = !bypass; | |
717 | *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl; | |
718 | } else if (data == "debug") { | |
719 | debug = !debug; | |
720 | *out_ << "debug == " << (debug ? "true" : "false") << std::endl; | |
721 | } else if (data == "destroy") { | |
722 | CYDestroyContext(); | |
723 | } else if (data == "gc") { | |
724 | *out_ << "collecting... " << std::flush; | |
725 | CYGarbageCollect(CYGetJSContext()); | |
726 | *out_ << "done." << std::endl; | |
727 | } else if (data == "exit") { | |
728 | return; | |
729 | } else if (data == "expand") { | |
730 | expand = !expand; | |
731 | *out_ << "expand == " << (expand ? "true" : "false") << std::endl; | |
732 | } else if (data == "lower") { | |
733 | lower = !lower; | |
734 | *out_ << "lower == " << (lower ? "true" : "false") << std::endl; | |
735 | } else if (data == "reparse") { | |
736 | reparse = !reparse; | |
737 | *out_ << "reparse == " << (reparse ? "true" : "false") << std::endl; | |
738 | } | |
739 | ||
740 | continue; | |
741 | } | |
742 | ||
743 | std::string code; | |
744 | if (bypass) | |
745 | code = command; | |
746 | else try { | |
747 | std::stringbuf stream(command); | |
748 | ||
749 | CYPool pool; | |
750 | CYDriver driver(pool, stream); | |
751 | Setup(driver); | |
752 | ||
753 | if (driver.Parse() || !driver.errors_.empty()) { | |
754 | for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) { | |
755 | CYPosition begin(error->location_.begin); | |
756 | CYPosition end(error->location_.end); | |
757 | ||
758 | /*if (begin.line != lines2.size()) { | |
759 | std::cerr << " | "; | |
760 | std::cerr << lines2[begin.line - 1] << std::endl; | |
761 | }*/ | |
762 | ||
763 | std::cerr << "...."; | |
764 | for (size_t i(0); i != begin.column; ++i) | |
765 | std::cerr << '.'; | |
766 | if (begin.line != end.line || begin.column == end.column) | |
767 | std::cerr << '^'; | |
768 | else for (size_t i(0), e(end.column - begin.column); i != e; ++i) | |
769 | std::cerr << '^'; | |
770 | std::cerr << std::endl; | |
771 | ||
772 | std::cerr << " | "; | |
773 | std::cerr << error->message_ << std::endl; | |
774 | ||
775 | break; | |
776 | } | |
777 | ||
778 | continue; | |
779 | } | |
780 | ||
781 | if (driver.script_ == NULL) | |
782 | continue; | |
783 | ||
784 | std::stringbuf str; | |
785 | CYOutput out(str, options); | |
786 | Setup(out, driver, options, lower); | |
787 | out << *driver.script_; | |
788 | code = str.str(); | |
789 | } catch (const CYException &error) { | |
790 | CYPool pool; | |
791 | std::cout << error.PoolCString(pool) << std::endl; | |
792 | continue; | |
793 | } | |
794 | ||
795 | if (debug) { | |
796 | std::cout << "cy= "; | |
797 | CYLexerHighlight(code.c_str(), code.size(), std::cout); | |
798 | std::cout << std::endl; | |
799 | } | |
800 | ||
801 | CYOutputRun(code, expand, reparse); | |
802 | } | |
803 | } | |
804 | ||
805 | void InjectLibrary(pid_t, int, const char *const []); | |
806 | ||
807 | static uint64_t CYGetTime() { | |
808 | #ifdef __APPLE__ | |
809 | return mach_absolute_time(); | |
810 | #else | |
811 | struct timespec spec; | |
812 | clock_gettime(CLOCK_MONOTONIC, &spec); | |
813 | return spec.tv_sec * UINT64_C(1000000000) + spec.tv_nsec; | |
814 | #endif | |
815 | } | |
816 | ||
817 | int Main(int argc, char * const argv[], char const * const envp[]) { | |
818 | bool tty(isatty(STDIN_FILENO)); | |
819 | bool compile(false); | |
820 | bool target(false); | |
821 | CYOptions options; | |
822 | ||
823 | append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history")); | |
824 | ||
825 | #ifdef CY_ATTACH | |
826 | pid_t pid(_not(pid_t)); | |
827 | #endif | |
828 | ||
829 | const char *host(NULL); | |
830 | const char *port(NULL); | |
831 | ||
832 | const char *argv0(argv[0]); | |
833 | ||
834 | optind = 1; | |
835 | ||
836 | for (;;) { | |
837 | int option(getopt_long(argc, argv, | |
838 | "c" | |
839 | "g:" | |
840 | "n:" | |
841 | #ifdef CY_ATTACH | |
842 | "p:" | |
843 | #endif | |
844 | "r:" | |
845 | "s" | |
846 | , (const struct option[]) { | |
847 | {NULL, no_argument, NULL, 'c'}, | |
848 | {NULL, required_argument, NULL, 'g'}, | |
849 | {NULL, required_argument, NULL, 'n'}, | |
850 | #ifdef CY_ATTACH | |
851 | {NULL, required_argument, NULL, 'p'}, | |
852 | #endif | |
853 | {NULL, required_argument, NULL, 'r'}, | |
854 | {NULL, no_argument, NULL, 's'}, | |
855 | {0, 0, 0, 0}}, NULL)); | |
856 | ||
857 | switch (option) { | |
858 | case -1: | |
859 | goto getopt; | |
860 | ||
861 | case ':': | |
862 | case '?': | |
863 | fprintf(stderr, | |
864 | "usage: cycript [-c]" | |
865 | #ifdef CY_ATTACH | |
866 | " [-p <pid|name>]" | |
867 | #endif | |
868 | " [-r <host:port>]" | |
869 | " [<script> [<arg>...]]\n" | |
870 | ); | |
871 | return 1; | |
872 | ||
873 | target: | |
874 | if (!target) | |
875 | target = true; | |
876 | else { | |
877 | fprintf(stderr, "only one of -[c" | |
878 | #ifdef CY_ATTACH | |
879 | "p" | |
880 | #endif | |
881 | "r] may be used at a time\n"); | |
882 | return 1; | |
883 | } | |
884 | break; | |
885 | ||
886 | case 'c': | |
887 | compile = true; | |
888 | goto target; | |
889 | ||
890 | case 'g': | |
891 | if (false); | |
892 | else if (strcmp(optarg, "rename") == 0) | |
893 | options.verbose_ = true; | |
894 | else if (strcmp(optarg, "bison") == 0) | |
895 | bison_ = true; | |
896 | else if (strcmp(optarg, "timing") == 0) | |
897 | timing_ = true; | |
898 | else { | |
899 | fprintf(stderr, "invalid name for -g\n"); | |
900 | return 1; | |
901 | } | |
902 | break; | |
903 | ||
904 | case 'n': | |
905 | if (false); | |
906 | else if (strcmp(optarg, "minify") == 0) | |
907 | pretty_ = true; | |
908 | else { | |
909 | fprintf(stderr, "invalid name for -n\n"); | |
910 | return 1; | |
911 | } | |
912 | break; | |
913 | ||
914 | #ifdef CY_ATTACH | |
915 | case 'p': { | |
916 | size_t size(strlen(optarg)); | |
917 | char *end; | |
918 | ||
919 | pid = strtoul(optarg, &end, 0); | |
920 | if (optarg + size != end) { | |
921 | // XXX: arg needs to be escaped in some horrendous way of doom | |
922 | // XXX: this is a memory leak now because I just don't care enough | |
923 | char *command; | |
924 | int writ(asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg)); | |
925 | _assert(writ != -1); | |
926 | ||
927 | if (FILE *pids = popen(command, "r")) { | |
928 | char value[32]; | |
929 | size = 0; | |
930 | ||
931 | for (;;) { | |
932 | size_t read(fread(value + size, 1, sizeof(value) - size, pids)); | |
933 | if (read == 0) | |
934 | break; | |
935 | else { | |
936 | size += read; | |
937 | if (size == sizeof(value)) | |
938 | goto fail; | |
939 | } | |
940 | } | |
941 | ||
942 | size: | |
943 | if (size == 0) | |
944 | goto fail; | |
945 | if (value[size - 1] == '\n') { | |
946 | --size; | |
947 | goto size; | |
948 | } | |
949 | ||
950 | value[size] = '\0'; | |
951 | size = strlen(value); | |
952 | pid = strtoul(value, &end, 0); | |
953 | if (value + size != end) fail: | |
954 | pid = _not(pid_t); | |
955 | _syscall(pclose(pids)); | |
956 | } | |
957 | ||
958 | if (pid == _not(pid_t)) { | |
959 | fprintf(stderr, "unable to find process `%s' using ps\n", optarg); | |
960 | return 1; | |
961 | } | |
962 | } | |
963 | } goto target; | |
964 | #endif | |
965 | ||
966 | case 'r': { | |
967 | //size_t size(strlen(optarg)); | |
968 | ||
969 | char *colon(strrchr(optarg, ':')); | |
970 | if (colon == NULL) { | |
971 | fprintf(stderr, "missing colon in hostspec\n"); | |
972 | return 1; | |
973 | } | |
974 | ||
975 | /*char *end; | |
976 | port = strtoul(colon + 1, &end, 10); | |
977 | if (end != optarg + size) { | |
978 | fprintf(stderr, "invalid port in hostspec\n"); | |
979 | return 1; | |
980 | }*/ | |
981 | ||
982 | host = optarg; | |
983 | *colon = '\0'; | |
984 | port = colon + 1; | |
985 | } goto target; | |
986 | ||
987 | case 's': | |
988 | strict_ = true; | |
989 | break; | |
990 | ||
991 | default: | |
992 | _assert(false); | |
993 | } | |
994 | } | |
995 | ||
996 | getopt: | |
997 | argc -= optind; | |
998 | argv += optind; | |
999 | ||
1000 | const char *script; | |
1001 | ||
1002 | #ifdef CY_ATTACH | |
1003 | if (pid != _not(pid_t) && argc > 1) { | |
1004 | fprintf(stderr, "-p cannot set argv\n"); | |
1005 | return 1; | |
1006 | } | |
1007 | #endif | |
1008 | ||
1009 | if (argc == 0) | |
1010 | script = NULL; | |
1011 | else { | |
1012 | script = argv[0]; | |
1013 | if (strcmp(script, "-") == 0) | |
1014 | script = NULL; | |
1015 | --argc; | |
1016 | ++argv; | |
1017 | } | |
1018 | ||
1019 | #ifdef CY_EXECUTE | |
1020 | // XXX: const_cast?! wtf gcc :( | |
1021 | CYSetArgs(argv0, script, argc, const_cast<const char **>(argv)); | |
1022 | #endif | |
1023 | ||
1024 | #ifdef CY_ATTACH | |
1025 | if (pid == _not(pid_t)) | |
1026 | client_ = -1; | |
1027 | else { | |
1028 | struct Socket { | |
1029 | int fd_; | |
1030 | ||
1031 | Socket(int fd) : | |
1032 | fd_(fd) | |
1033 | { | |
1034 | } | |
1035 | ||
1036 | ~Socket() { | |
1037 | close(fd_); | |
1038 | } | |
1039 | ||
1040 | operator int() { | |
1041 | return fd_; | |
1042 | } | |
1043 | } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); | |
1044 | ||
1045 | struct sockaddr_un address; | |
1046 | memset(&address, 0, sizeof(address)); | |
1047 | address.sun_family = AF_UNIX; | |
1048 | ||
1049 | const char *tmp; | |
1050 | #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__)) | |
1051 | tmp = "/Library/Caches"; | |
1052 | #else | |
1053 | tmp = "/tmp"; | |
1054 | #endif | |
1055 | ||
1056 | sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid()); | |
1057 | unlink(address.sun_path); | |
1058 | ||
1059 | struct File { | |
1060 | const char *path_; | |
1061 | ||
1062 | File(const char *path) : | |
1063 | path_(path) | |
1064 | { | |
1065 | } | |
1066 | ||
1067 | ~File() { | |
1068 | unlink(path_); | |
1069 | } | |
1070 | } file(address.sun_path); | |
1071 | ||
1072 | _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), sizeof(address))); | |
1073 | _syscall(chmod(address.sun_path, 0777)); | |
1074 | ||
1075 | _syscall(listen(server, 1)); | |
1076 | const char *const argv[] = {address.sun_path, NULL}; | |
1077 | InjectLibrary(pid, 1, argv); | |
1078 | client_ = _syscall(accept(server, NULL, NULL)); | |
1079 | } | |
1080 | #else | |
1081 | client_ = -1; | |
1082 | #endif | |
1083 | ||
1084 | if (client_ == -1 && host != NULL && port != NULL) { | |
1085 | struct addrinfo hints; | |
1086 | memset(&hints, 0, sizeof(hints)); | |
1087 | hints.ai_family = AF_UNSPEC; | |
1088 | hints.ai_socktype = SOCK_STREAM; | |
1089 | hints.ai_protocol = 0; | |
1090 | hints.ai_flags = 0; | |
1091 | ||
1092 | struct addrinfo *infos; | |
1093 | _syscall(getaddrinfo(host, port, &hints, &infos)); | |
1094 | ||
1095 | _assert(infos != NULL); try { | |
1096 | for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) { | |
1097 | int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try { | |
1098 | _syscall(connect(client, info->ai_addr, info->ai_addrlen)); | |
1099 | client_ = client; | |
1100 | break; | |
1101 | } catch (...) { | |
1102 | _syscall(close(client)); | |
1103 | throw; | |
1104 | } | |
1105 | } | |
1106 | } catch (...) { | |
1107 | freeaddrinfo(infos); | |
1108 | throw; | |
1109 | } | |
1110 | } | |
1111 | ||
1112 | if (script == NULL && tty) | |
1113 | Console(options); | |
1114 | else { | |
1115 | std::istream *stream; | |
1116 | if (script == NULL) { | |
1117 | stream = &std::cin; | |
1118 | script = "<stdin>"; | |
1119 | } else { | |
1120 | stream = new std::fstream(script, std::ios::in | std::ios::binary); | |
1121 | _assert(!stream->fail()); | |
1122 | } | |
1123 | ||
1124 | if (timing_) { | |
1125 | std::stringbuf buffer; | |
1126 | stream->get(buffer, '\0'); | |
1127 | _assert(!stream->fail()); | |
1128 | ||
1129 | double average(0); | |
1130 | int samples(-50); | |
1131 | uint64_t start(CYGetTime()); | |
1132 | ||
1133 | for (;;) { | |
1134 | stream = new std::istringstream(buffer.str()); | |
1135 | ||
1136 | CYPool pool; | |
1137 | CYDriver driver(pool, *stream->rdbuf(), script); | |
1138 | Setup(driver); | |
1139 | ||
1140 | uint64_t begin(CYGetTime()); | |
1141 | driver.Parse(); | |
1142 | uint64_t end(CYGetTime()); | |
1143 | ||
1144 | delete stream; | |
1145 | ||
1146 | average += (end - begin - average) / ++samples; | |
1147 | ||
1148 | uint64_t now(CYGetTime()); | |
1149 | if (samples == 0) | |
1150 | average = 0; | |
1151 | else if ((now - start) / 1000000000 >= 1) | |
1152 | std::cout << std::fixed << average << '\t' << (end - begin) << '\t' << samples << std::endl; | |
1153 | else continue; | |
1154 | ||
1155 | start = now; | |
1156 | } | |
1157 | ||
1158 | stream = new std::istringstream(buffer.str()); | |
1159 | std::cin.get(); | |
1160 | } | |
1161 | ||
1162 | CYPool pool; | |
1163 | CYDriver driver(pool, *stream->rdbuf(), script); | |
1164 | Setup(driver); | |
1165 | ||
1166 | bool failed(driver.Parse()); | |
1167 | ||
1168 | if (failed || !driver.errors_.empty()) { | |
1169 | for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i) | |
1170 | std::cerr << i->location_.begin << ": " << i->message_ << std::endl; | |
1171 | return 1; | |
1172 | } else if (driver.script_ != NULL) { | |
1173 | std::stringbuf str; | |
1174 | CYOutput out(str, options); | |
1175 | Setup(out, driver, options, true); | |
1176 | out << *driver.script_; | |
1177 | std::string code(str.str()); | |
1178 | if (compile) | |
1179 | std::cout << code; | |
1180 | else { | |
1181 | CYUTF8String json(Run(pool, client_, code)); | |
1182 | if (CYStartsWith(json, "throw ")) { | |
1183 | CYLexerHighlight(json.data, json.size, std::cerr); | |
1184 | std::cerr << std::endl; | |
1185 | return 1; | |
1186 | } | |
1187 | } | |
1188 | } | |
1189 | } | |
1190 | ||
1191 | return 0; | |
1192 | } | |
1193 | ||
1194 | _visible int main(int argc, char * const argv[], char const * const envp[]) { | |
1195 | try { | |
1196 | return Main(argc, argv, envp); | |
1197 | } catch (const CYException &error) { | |
1198 | CYPool pool; | |
1199 | fprintf(stderr, "%s\n", error.PoolCString(pool)); | |
1200 | return 1; | |
1201 | } | |
1202 | } |