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