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