]> git.saurik.com Git - cycript.git/blob - Console.cpp
Avoid breaking normal down-arrow cursor semantics.
[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 CYConsoleKeyBypass(int count, int key) {
393 rl_point = rl_end;
394 rl_insert(count, '\n');
395 return rl_newline(count, key);
396 }
397
398 static int CYConsoleKeyReturn(int count, int key) {
399 if (rl_point != rl_end) {
400 if (memchr(rl_line_buffer, '\n', rl_end) == NULL)
401 return CYConsoleKeyBypass(count, key);
402
403 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
404 if (before == NULL)
405 before = rl_line_buffer;
406
407 int space(before + 1 - rl_line_buffer);
408 while (space != rl_point && rl_line_buffer[space] == ' ')
409 ++space;
410
411 int adjust(rl_line_buffer + space - 1 - before);
412 if (space == rl_point && adjust != 0)
413 rl_rubout(adjust, '\b');
414
415 rl_insert(count, '\n');
416 if (adjust != 0)
417 rl_insert(adjust, ' ');
418
419 return 0;
420 }
421
422 rl_insert(count, '\n');
423
424 bool done(false);
425 if (rl_line_buffer[0] == '?')
426 done = true;
427 else {
428 std::string command(rl_line_buffer, rl_end);
429 std::istringstream stream(command);
430
431 size_t last(std::string::npos);
432 for (size_t i(0); i != std::string::npos; i = command.find('\n', i + 1))
433 ++last;
434
435 CYPool pool;
436 CYDriver driver(pool, stream);
437 if (driver.Parse() || !driver.errors_.empty())
438 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
439 if (error->location_.begin.line != last + 1)
440 done = true;
441 break;
442 }
443 else
444 done = true;
445 }
446
447 if (done)
448 return rl_newline(count, key);
449 return 0;
450 }
451
452 static int CYConsoleKeyUp(int count, int key) {
453 while (count-- != 0) {
454 char *after(CYmemrchr(rl_line_buffer, '\n', rl_point));
455 if (after == NULL) {
456 if (int value = rl_get_previous_history(1, key))
457 return value;
458 continue;
459 }
460
461 char *before(CYmemrchr(rl_line_buffer, '\n', after - rl_line_buffer));
462 if (before == NULL)
463 before = rl_line_buffer - 1;
464
465 ptrdiff_t offset(rl_line_buffer + rl_point - after);
466 if (offset > after - before)
467 rl_point = after - rl_line_buffer;
468 else
469 rl_point = before + offset - rl_line_buffer;
470 }
471
472 return 0;
473 }
474
475 static int CYConsoleKeyDown(int count, int key) {
476 while (count-- != 0) {
477 char *after(static_cast<char *>(memchr(rl_line_buffer + rl_point, '\n', rl_end - rl_point)));
478 if (after == NULL) {
479 int where(where_history());
480 if (int value = rl_get_next_history(1, key))
481 return value;
482 if (where != where_history()) {
483 char *first(static_cast<char *>(memchr(rl_line_buffer, '\n', rl_end)));
484 if (first != NULL)
485 rl_point = first - 1 - rl_line_buffer;
486 }
487 continue;
488 }
489
490 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
491 if (before == NULL)
492 before = rl_line_buffer - 1;
493
494 char *next(static_cast<char *>(memchr(after + 1, '\n', rl_line_buffer + rl_end - after - 1)));
495 if (next == NULL)
496 next = rl_line_buffer + rl_end;
497
498 ptrdiff_t offset(rl_line_buffer + rl_point - before);
499 if (offset > next - after)
500 rl_point = next - rl_line_buffer;
501 else
502 rl_point = after + offset - rl_line_buffer;
503 }
504
505 return 0;
506 }
507
508 static int CYConsoleLineBegin(int count, int key) {
509 while (rl_point != 0 && rl_line_buffer[rl_point - 1] != '\n')
510 --rl_point;
511 return 0;
512 }
513
514 static int CYConsoleLineEnd(int count, int key) {
515 while (rl_point != rl_end && rl_line_buffer[rl_point] != '\n')
516 ++rl_point;
517 return 0;
518 }
519
520 static int CYConsoleKeyBack(int count, int key) {
521 while (count-- != 0) {
522 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
523 if (before == NULL)
524 return rl_rubout(count, key);
525
526 int start(before + 1 - rl_line_buffer);
527 if (start == rl_point) rubout: {
528 rl_rubout(1, key);
529 continue;
530 }
531
532 for (int i(start); i != rl_point; ++i)
533 if (rl_line_buffer[i] != ' ')
534 goto rubout;
535 rl_rubout((rl_point - start) % 4 ?: 4, key);
536 }
537
538 return 0;
539 }
540
541 static int CYConsoleKeyTab(int count, int key) {
542 char *before(CYmemrchr(rl_line_buffer, '\n', rl_point));
543 if (before == NULL) complete:
544 return rl_complete_internal(rl_completion_mode(&CYConsoleKeyTab));
545 int start(before + 1 - rl_line_buffer);
546 for (int i(start); i != rl_point; ++i)
547 if (rl_line_buffer[i] != ' ')
548 goto complete;
549 return rl_insert(4 - (rl_point - start) % 4, ' ');
550 }
551
552 static void CYConsoleRemapBind(rl_command_func_t *from, rl_command_func_t *to) {
553 char **keyseqs(rl_invoking_keyseqs(from));
554 if (keyseqs == NULL)
555 return;
556 for (char **keyseq(keyseqs); *keyseq != NULL; ++keyseq) {
557 rl_bind_keyseq(*keyseq, to);
558 free(*keyseq);
559 }
560 free(keyseqs);
561 }
562
563 static void CYConsolePrepTerm(int meta) {
564 rl_prep_terminal(meta);
565
566 CYConsoleRemapBind(&rl_beg_of_line, &CYConsoleLineBegin);
567 CYConsoleRemapBind(&rl_end_of_line, &CYConsoleLineEnd);
568 CYConsoleRemapBind(&rl_rubout, &CYConsoleKeyBack);
569 }
570
571 static void Console(CYOptions &options) {
572 std::string basedir;
573 if (const char *home = getenv("HOME"))
574 basedir = home;
575 else {
576 passwd *passwd;
577 if (const char *username = getenv("LOGNAME"))
578 passwd = getpwnam(username);
579 else
580 passwd = getpwuid(getuid());
581 basedir = passwd->pw_dir;
582 }
583
584 basedir += "/.cycript";
585 mkdir(basedir.c_str(), 0700);
586
587 rl_initialize();
588 rl_readline_name = name_;
589
590 History history(basedir + "/history");
591
592 bool bypass(false);
593 bool debug(false);
594 bool expand(false);
595 bool lower(true);
596
597 out_ = &std::cout;
598
599 rl_completer_word_break_characters = break_;
600 rl_attempted_completion_function = &Complete;
601
602 rl_bind_key(TAB, &CYConsoleKeyTab);
603
604 rl_redisplay_function = CYDisplayUpdate;
605 rl_prep_term_function = CYConsolePrepTerm;
606
607 #if defined (__MSDOS__)
608 rl_bind_keyseq("\033[0A", &CYConsoleKeyUp);
609 rl_bind_keyseq("\033[0D", &CYConsoleKeyDown);
610 #endif
611 rl_bind_keyseq("\033[A", &CYConsoleKeyUp);
612 rl_bind_keyseq("\033[B", &CYConsoleKeyDown);
613 rl_bind_keyseq("\033OA", &CYConsoleKeyUp);
614 rl_bind_keyseq("\033OB", &CYConsoleKeyDown);
615 #if defined (__MINGW32__)
616 rl_bind_keyseq("\340H", &CYConsoleKeyUp);
617 rl_bind_keyseq("\340P", &CYConsoleKeyDown);
618 rl_bind_keyseq("\\000H", &CYConsoleKeyUp);
619 rl_bind_keyseq("\\000P", &CYConsoleKeyDown);
620 #endif
621
622 struct sigaction action;
623 sigemptyset(&action.sa_mask);
624 action.sa_handler = &sigint;
625 action.sa_flags = 0;
626 sigaction(SIGINT, &action, NULL);
627
628 for (;;) {
629 if (setjmp(ctrlc_) != 0) {
630 mode_ = Working;
631 *out_ << std::endl;
632 continue;
633 }
634
635 if (bypass) {
636 rl_bind_key('\r', &CYConsoleKeyBypass);
637 rl_bind_key('\n', &CYConsoleKeyBypass);
638 } else {
639 rl_bind_key('\r', &CYConsoleKeyReturn);
640 rl_bind_key('\n', &CYConsoleKeyReturn);
641 }
642
643 mode_ = Parsing;
644 char *line(readline("cy# "));
645 mode_ = Working;
646
647 if (line == NULL) {
648 *out_ << std::endl;
649 break;
650 }
651
652 std::string command(line);
653 free(line);
654 _assert(!command.empty());
655 _assert(command[command.size() - 1] == '\n');
656 command.resize(command.size() - 1);
657 if (command.empty())
658 continue;
659
660 if (command[0] == '?') {
661 std::string data(command.substr(1));
662 if (data == "bypass") {
663 bypass = !bypass;
664 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
665 } else if (data == "debug") {
666 debug = !debug;
667 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
668 } else if (data == "destroy") {
669 CYDestroyContext();
670 } else if (data == "gc") {
671 *out_ << "collecting... " << std::flush;
672 CYGarbageCollect(CYGetJSContext());
673 *out_ << "done." << std::endl;
674 } else if (data == "exit") {
675 return;
676 } else if (data == "expand") {
677 expand = !expand;
678 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
679 } else if (data == "lower") {
680 lower = !lower;
681 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
682 }
683
684 history += command;
685 continue;
686 }
687
688 std::string code;
689 if (bypass)
690 code = command;
691 else {
692 std::istringstream stream(command);
693
694 CYPool pool;
695 CYDriver driver(pool, stream);
696 Setup(driver);
697
698 if (driver.Parse() || !driver.errors_.empty()) {
699 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
700 CYPosition begin(error->location_.begin);
701 CYPosition end(error->location_.end);
702
703 /*if (begin.line != lines2.size()) {
704 std::cerr << " | ";
705 std::cerr << lines2[begin.line - 1] << std::endl;
706 }*/
707
708 std::cerr << "....";
709 for (size_t i(0); i != begin.column; ++i)
710 std::cerr << '.';
711 if (begin.line != end.line || begin.column == end.column)
712 std::cerr << '^';
713 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
714 std::cerr << '^';
715 std::cerr << std::endl;
716
717 std::cerr << " | ";
718 std::cerr << error->message_ << std::endl;
719
720 history += command;
721 break;
722 }
723
724 continue;
725 }
726
727 if (driver.script_ == NULL)
728 continue;
729
730 std::stringbuf str;
731 CYOutput out(str, options);
732 Setup(out, driver, options, lower);
733 out << *driver.script_;
734 code = str.str();
735 }
736
737 history += command;
738
739 if (debug) {
740 std::cout << "cy= ";
741 CYLexerHighlight(code.c_str(), code.size(), std::cout);
742 std::cout << std::endl;
743 }
744
745 CYPool pool;
746 Output(Run(pool, client_, code), &std::cout, expand);
747 }
748 }
749
750 void InjectLibrary(pid_t, int, const char *const []);
751
752 static uint64_t CYGetTime() {
753 #ifdef __APPLE__
754 return mach_absolute_time();
755 #else
756 struct timespec spec;
757 clock_gettime(CLOCK_MONOTONIC, &spec);
758 return spec.tv_sec * UINT64_C(1000000000) + spec.tv_nsec;
759 #endif
760 }
761
762 int Main(int argc, char * const argv[], char const * const envp[]) {
763 bool tty(isatty(STDIN_FILENO));
764 bool compile(false);
765 bool target(false);
766 CYOptions options;
767
768 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
769
770 #ifdef CY_ATTACH
771 pid_t pid(_not(pid_t));
772 #endif
773
774 const char *host(NULL);
775 const char *port(NULL);
776
777 optind = 1;
778
779 for (;;) {
780 int option(getopt_long(argc, argv,
781 "c"
782 "g:"
783 "n:"
784 #ifdef CY_ATTACH
785 "p:"
786 #endif
787 "r:"
788 "s"
789 , (const struct option[]) {
790 {NULL, no_argument, NULL, 'c'},
791 {NULL, required_argument, NULL, 'g'},
792 {NULL, required_argument, NULL, 'n'},
793 #ifdef CY_ATTACH
794 {NULL, required_argument, NULL, 'p'},
795 #endif
796 {NULL, required_argument, NULL, 'r'},
797 {NULL, no_argument, NULL, 's'},
798 {0, 0, 0, 0}}, NULL));
799
800 switch (option) {
801 case -1:
802 goto getopt;
803
804 case ':':
805 case '?':
806 fprintf(stderr,
807 "usage: cycript [-c]"
808 #ifdef CY_ATTACH
809 " [-p <pid|name>]"
810 #endif
811 " [-r <host:port>]"
812 " [<script> [<arg>...]]\n"
813 );
814 return 1;
815
816 target:
817 if (!target)
818 target = true;
819 else {
820 fprintf(stderr, "only one of -[c"
821 #ifdef CY_ATTACH
822 "p"
823 #endif
824 "r] may be used at a time\n");
825 return 1;
826 }
827 break;
828
829 case 'c':
830 compile = true;
831 goto target;
832
833 case 'g':
834 if (false);
835 else if (strcmp(optarg, "rename") == 0)
836 options.verbose_ = true;
837 else if (strcmp(optarg, "bison") == 0)
838 bison_ = true;
839 else if (strcmp(optarg, "timing") == 0)
840 timing_ = true;
841 else {
842 fprintf(stderr, "invalid name for -g\n");
843 return 1;
844 }
845 break;
846
847 case 'n':
848 if (false);
849 else if (strcmp(optarg, "minify") == 0)
850 pretty_ = true;
851 else {
852 fprintf(stderr, "invalid name for -n\n");
853 return 1;
854 }
855 break;
856
857 #ifdef CY_ATTACH
858 case 'p': {
859 size_t size(strlen(optarg));
860 char *end;
861
862 pid = strtoul(optarg, &end, 0);
863 if (optarg + size != end) {
864 // XXX: arg needs to be escaped in some horrendous way of doom
865 // XXX: this is a memory leak now because I just don't care enough
866 char *command;
867 int writ(asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg));
868 _assert(writ != -1);
869
870 if (FILE *pids = popen(command, "r")) {
871 char value[32];
872 size = 0;
873
874 for (;;) {
875 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
876 if (read == 0)
877 break;
878 else {
879 size += read;
880 if (size == sizeof(value))
881 goto fail;
882 }
883 }
884
885 size:
886 if (size == 0)
887 goto fail;
888 if (value[size - 1] == '\n') {
889 --size;
890 goto size;
891 }
892
893 value[size] = '\0';
894 size = strlen(value);
895 pid = strtoul(value, &end, 0);
896 if (value + size != end) fail:
897 pid = _not(pid_t);
898 _syscall(pclose(pids));
899 }
900
901 if (pid == _not(pid_t)) {
902 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
903 return 1;
904 }
905 }
906 } goto target;
907 #endif
908
909 case 'r': {
910 //size_t size(strlen(optarg));
911
912 char *colon(strrchr(optarg, ':'));
913 if (colon == NULL) {
914 fprintf(stderr, "missing colon in hostspec\n");
915 return 1;
916 }
917
918 /*char *end;
919 port = strtoul(colon + 1, &end, 10);
920 if (end != optarg + size) {
921 fprintf(stderr, "invalid port in hostspec\n");
922 return 1;
923 }*/
924
925 host = optarg;
926 *colon = '\0';
927 port = colon + 1;
928 } goto target;
929
930 case 's':
931 strict_ = true;
932 break;
933
934 default:
935 _assert(false);
936 }
937 }
938
939 getopt:
940 argc -= optind;
941 argv += optind;
942
943 const char *script;
944
945 #ifdef CY_ATTACH
946 if (pid != _not(pid_t) && argc > 1) {
947 fprintf(stderr, "-p cannot set argv\n");
948 return 1;
949 }
950 #endif
951
952 if (argc == 0)
953 script = NULL;
954 else {
955 #ifdef CY_EXECUTE
956 // XXX: const_cast?! wtf gcc :(
957 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
958 #endif
959 script = argv[0];
960 if (strcmp(script, "-") == 0)
961 script = NULL;
962 }
963
964 #ifdef CY_ATTACH
965 if (pid == _not(pid_t))
966 client_ = -1;
967 else {
968 struct Socket {
969 int fd_;
970
971 Socket(int fd) :
972 fd_(fd)
973 {
974 }
975
976 ~Socket() {
977 close(fd_);
978 }
979
980 operator int() {
981 return fd_;
982 }
983 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
984
985 struct sockaddr_un address;
986 memset(&address, 0, sizeof(address));
987 address.sun_family = AF_UNIX;
988
989 const char *tmp;
990 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
991 tmp = "/Library/Caches";
992 #else
993 tmp = "/tmp";
994 #endif
995
996 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
997 unlink(address.sun_path);
998
999 struct File {
1000 const char *path_;
1001
1002 File(const char *path) :
1003 path_(path)
1004 {
1005 }
1006
1007 ~File() {
1008 unlink(path_);
1009 }
1010 } file(address.sun_path);
1011
1012 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
1013 _syscall(chmod(address.sun_path, 0777));
1014
1015 _syscall(listen(server, 1));
1016 const char *const argv[] = {address.sun_path, NULL};
1017 InjectLibrary(pid, 1, argv);
1018 client_ = _syscall(accept(server, NULL, NULL));
1019 }
1020 #else
1021 client_ = -1;
1022 #endif
1023
1024 if (client_ == -1 && host != NULL && port != NULL) {
1025 struct addrinfo hints;
1026 memset(&hints, 0, sizeof(hints));
1027 hints.ai_family = AF_UNSPEC;
1028 hints.ai_socktype = SOCK_STREAM;
1029 hints.ai_protocol = 0;
1030 hints.ai_flags = 0;
1031
1032 struct addrinfo *infos;
1033 _syscall(getaddrinfo(host, port, &hints, &infos));
1034
1035 _assert(infos != NULL); try {
1036 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
1037 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
1038 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
1039 client_ = client;
1040 break;
1041 } catch (...) {
1042 _syscall(close(client));
1043 throw;
1044 }
1045 }
1046 } catch (...) {
1047 freeaddrinfo(infos);
1048 throw;
1049 }
1050 }
1051
1052 if (script == NULL && tty)
1053 Console(options);
1054 else {
1055 std::istream *stream;
1056 if (script == NULL) {
1057 stream = &std::cin;
1058 script = "<stdin>";
1059 } else {
1060 stream = new std::fstream(script, std::ios::in | std::ios::binary);
1061 _assert(!stream->fail());
1062 }
1063
1064 if (timing_) {
1065 std::stringbuf buffer;
1066 stream->get(buffer, '\0');
1067 _assert(!stream->fail());
1068
1069 double average(0);
1070 int samples(-50);
1071 uint64_t start(CYGetTime());
1072
1073 for (;;) {
1074 stream = new std::istringstream(buffer.str());
1075
1076 CYPool pool;
1077 CYDriver driver(pool, *stream, script);
1078 Setup(driver);
1079
1080 uint64_t begin(CYGetTime());
1081 driver.Parse();
1082 uint64_t end(CYGetTime());
1083
1084 delete stream;
1085
1086 average += (end - begin - average) / ++samples;
1087
1088 uint64_t now(CYGetTime());
1089 if (samples == 0)
1090 average = 0;
1091 else if ((now - start) / 1000000000 >= 1)
1092 std::cout << std::fixed << average << '\t' << (end - begin) << '\t' << samples << std::endl;
1093 else continue;
1094
1095 start = now;
1096 }
1097
1098 stream = new std::istringstream(buffer.str());
1099 std::cin.get();
1100 }
1101
1102 CYPool pool;
1103 CYDriver driver(pool, *stream, script);
1104 Setup(driver);
1105
1106 bool failed(driver.Parse());
1107
1108 if (failed || !driver.errors_.empty()) {
1109 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
1110 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
1111 } else if (driver.script_ != NULL) {
1112 std::stringbuf str;
1113 CYOutput out(str, options);
1114 Setup(out, driver, options, true);
1115 out << *driver.script_;
1116 std::string code(str.str());
1117 if (compile)
1118 std::cout << code;
1119 else {
1120 CYUTF8String json(Run(pool, client_, code));
1121 if (CYStartsWith(json, "throw ")) {
1122 CYLexerHighlight(json.data, json.size, std::cerr);
1123 std::cerr << std::endl;
1124 return 1;
1125 }
1126 }
1127 }
1128 }
1129
1130 return 0;
1131 }
1132
1133 int main(int argc, char * const argv[], char const * const envp[]) {
1134 try {
1135 return Main(argc, argv, envp);
1136 } catch (const CYException &error) {
1137 CYPool pool;
1138 fprintf(stderr, "%s\n", error.PoolCString(pool));
1139 return 1;
1140 }
1141 }