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