]> git.saurik.com Git - cycript.git/blob - Console.cpp
Break completions at :.
[cycript.git] / Console.cpp
1 /* Cycript - Inlining/Optimizing JavaScript Compiler
2 * Copyright (C) 2009 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 #include "cycript.hpp"
41
42 #ifdef CY_EXECUTE
43 #include "JavaScript.hpp"
44 #endif
45
46 #include <cstdio>
47 #include <sstream>
48
49 #include <setjmp.h>
50
51 #ifdef HAVE_READLINE_H
52 #include <readline.h>
53 #else
54 #include <readline/readline.h>
55 #endif
56
57 #ifdef HAVE_HISTORY_H
58 #include <history.h>
59 #else
60 #include <readline/history.h>
61 #endif
62
63 #include <sys/mman.h>
64
65 #include <errno.h>
66 #include <unistd.h>
67
68 #include <sys/types.h>
69 #include <sys/stat.h>
70 #include <fcntl.h>
71
72 #include "Cycript.tab.hh"
73
74 #include <sys/types.h>
75 #include <sys/socket.h>
76 #include <netinet/in.h>
77 #include <sys/un.h>
78 #include <pwd.h>
79
80 #include <apr_getopt.h>
81
82 #include <dlfcn.h>
83
84 #include "Replace.hpp"
85
86 static volatile enum {
87 Working,
88 Parsing,
89 Running,
90 Sending,
91 Waiting,
92 } mode_;
93
94 static jmp_buf ctrlc_;
95
96 static void sigint(int) {
97 switch (mode_) {
98 case Working:
99 return;
100 case Parsing:
101 longjmp(ctrlc_, 1);
102 case Running:
103 throw "*** Ctrl-C";
104 case Sending:
105 return;
106 case Waiting:
107 return;
108 }
109 }
110
111 #if YYDEBUG
112 static bool bison_;
113 #endif
114 static bool strict_;
115 static bool pretty_;
116
117 void Setup(CYDriver &driver, cy::parser &parser) {
118 #if YYDEBUG
119 if (bison_)
120 parser.set_debug_level(1);
121 #endif
122 if (strict_)
123 driver.strict_ = true;
124 }
125
126 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options) {
127 out.pretty_ = pretty_;
128 CYContext context(driver.pool_, options);
129 driver.program_->Replace(context);
130 }
131
132 static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
133 const char *json;
134 size_t size;
135
136 if (client == -1) {
137 mode_ = Running;
138 #ifdef CY_EXECUTE
139 json = CYExecute(pool, code.data);
140 #else
141 json = NULL;
142 #endif
143 mode_ = Working;
144 if (json != NULL)
145 size = strlen(json);
146 } else {
147 mode_ = Sending;
148 CYSendAll(client, &size, sizeof(size));
149 CYSendAll(client, code.data, size);
150 mode_ = Waiting;
151 CYRecvAll(client, &size, sizeof(size));
152 if (size == _not(size_t))
153 json = NULL;
154 else {
155 char *temp(new(pool) char[size + 1]);
156 CYRecvAll(client, temp, size);
157 temp[size] = '\0';
158 json = temp;
159 }
160 mode_ = Working;
161 }
162
163 return CYUTF8String(json, size);
164 }
165
166 static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
167 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
168 }
169
170 void Run(int client, const char *data, size_t size, FILE *fout = NULL, bool expand = false) {
171 CYPool pool;
172 CYUTF8String json(Run(pool, client, CYUTF8String(data, size)));
173
174 data = json.data;
175 size = json.size;
176
177 if (data != NULL && fout != NULL) {
178 if (!expand || data[0] != '"' && data[0] != '\'')
179 fputs(data, fout);
180 else for (size_t i(0); i != size; ++i)
181 if (data[i] != '\\')
182 fputc(data[i], fout);
183 else switch(data[++i]) {
184 case '\0': goto done;
185 case '\\': fputc('\\', fout); break;
186 case '\'': fputc('\'', fout); break;
187 case '"': fputc('"', fout); break;
188 case 'b': fputc('\b', fout); break;
189 case 'f': fputc('\f', fout); break;
190 case 'n': fputc('\n', fout); break;
191 case 'r': fputc('\r', fout); break;
192 case 't': fputc('\t', fout); break;
193 case 'v': fputc('\v', fout); break;
194 default: fputc('\\', fout); --i; break;
195 }
196
197 done:
198 fputs("\n", fout);
199 fflush(fout);
200 }
201 }
202
203 static void Run(int client, std::string &code, FILE *fout = NULL, bool expand = false) {
204 Run(client, code.c_str(), code.size(), fout, expand);
205 }
206
207 int (*append_history$)(int, const char *);
208
209 static std::string command_;
210
211 static CYExpression *ParseExpression(CYPool &pool, CYUTF8String code) {
212 std::ostringstream str;
213 str << '(' << code << ')';
214 std::string string(str.str());
215
216 CYDriver driver(pool);
217 driver.data_ = string.c_str();
218 driver.size_ = string.size();
219
220 cy::parser parser(driver);
221 Setup(driver, parser);
222
223 if (parser.parse() != 0 || !driver.errors_.empty())
224 _assert(false);
225
226 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->statements_));
227 _assert(express != NULL);
228 return express->expression_;
229 }
230
231 static int client_;
232
233 static char **Complete(const char *word, int start, int end) {
234 rl_attempted_completion_over = TRUE;
235
236 CYPool pool;
237
238 CYDriver driver(pool);
239 cy::parser parser(driver);
240 Setup(driver, parser);
241
242 std::string line(rl_line_buffer, start);
243 std::string command(command_ + line);
244
245 driver.data_ = command.c_str();
246 driver.size_ = command.size();
247
248 driver.auto_ = true;
249
250 if (parser.parse() != 0 || !driver.errors_.empty())
251 return NULL;
252
253 if (driver.mode_ == CYDriver::AutoNone)
254 return NULL;
255
256 CYExpression *expression;
257
258 CYOptions options;
259 CYContext context(driver.pool_, options);
260
261 std::ostringstream prefix;
262
263 switch (driver.mode_) {
264 case CYDriver::AutoPrimary:
265 expression = $ CYThis();
266 break;
267
268 case CYDriver::AutoDirect:
269 expression = driver.context_;
270 break;
271
272 case CYDriver::AutoIndirect:
273 expression = $ CYIndirect(driver.context_);
274 break;
275
276 case CYDriver::AutoMessage: {
277 CYDriver::Context &thing(driver.contexts_.back());
278 expression = $M($M($ CYIndirect(thing.context_), $S("isa")), $S("messages"));
279 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
280 prefix << (*part)->word_ << ':';
281 } break;
282
283 default:
284 _assert(false);
285 }
286
287 std::string begin(prefix.str() + word);
288
289 driver.program_ = $ CYProgram($ CYExpress($C2(ParseExpression(pool,
290 " function(object, prefix) {\n"
291 " var names = [];\n"
292 " var pattern = '^' + prefix;\n"
293 " for (name in object)\n"
294 " if (name.match(pattern) != null)\n"
295 " names.push(name);\n"
296 " return names;\n"
297 " }\n"
298 ), expression, $S(begin.c_str()))));
299
300 driver.program_->Replace(context);
301
302 std::ostringstream str;
303 CYOutput out(str, options);
304 out << *driver.program_;
305
306 std::string code(str.str());
307 CYUTF8String json(Run(pool, client_, code));
308
309 CYExpression *result(ParseExpression(pool, json));
310 CYArray *array(dynamic_cast<CYArray *>(result));
311 _assert(array != NULL);
312
313 // XXX: use an std::set?
314 typedef std::vector<std::string> Completions;
315 Completions completions;
316
317 std::string common;
318 bool rest(false);
319
320 for (CYElement *element(array->elements_); element != NULL; element = element->next_) {
321 CYString *string(dynamic_cast<CYString *>(element->value_));
322 _assert(string != NULL);
323
324 std::string completion(string->value_, string->size_);
325 completions.push_back(completion);
326
327 if (!rest) {
328 common = completion;
329 rest = true;
330 } else {
331 size_t limit(completion.size()), size(common.size());
332 if (size > limit)
333 common = common.substr(0, limit);
334 else
335 limit = size;
336 for (limit = 0; limit != size; ++limit)
337 if (common[limit] != completion[limit])
338 break;
339 if (limit != size)
340 common = common.substr(0, limit);
341 }
342 }
343
344 size_t count(completions.size());
345 if (count == 0)
346 return NULL;
347
348 if (!common.empty()) {
349 size_t size(prefix.str().size());
350 _assert(common.size() >= size);
351 common = common.substr(size);
352 }
353
354 size_t colon(common.find(':'));
355 if (colon != std::string::npos)
356 common = common.substr(0, colon + 1);
357
358 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
359
360 results[0] = strdup(common.c_str());
361 size_t index(0);
362 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
363 results[++index] = strdup(i->c_str());
364 results[count + 1] = NULL;
365
366 return results;
367 }
368
369 // need char *, not const char *
370 static char name_[] = "cycript";
371 static char break_[] = " \t\n\"\\'`@$><=;|&{(" ".:";
372
373 static void Console(apr_pool_t *pool, CYOptions &options) {
374 passwd *passwd;
375 if (const char *username = getenv("LOGNAME"))
376 passwd = getpwnam(username);
377 else
378 passwd = getpwuid(getuid());
379
380 const char *basedir(apr_psprintf(pool, "%s/.cycript", passwd->pw_dir));
381 const char *histfile(apr_psprintf(pool, "%s/history", basedir));
382 size_t histlines(0);
383
384 rl_initialize();
385 rl_readline_name = name_;
386
387 mkdir(basedir, 0700);
388 read_history(histfile);
389
390 bool bypass(false);
391 bool debug(false);
392 bool expand(false);
393
394 FILE *fout(stdout);
395
396 // rl_completer_word_break_characters is broken in libedit
397 rl_basic_word_break_characters = break_;
398 rl_attempted_completion_function = &Complete;
399 rl_bind_key('\t', rl_complete);
400
401 struct sigaction action;
402 sigemptyset(&action.sa_mask);
403 action.sa_handler = &sigint;
404 action.sa_flags = 0;
405 sigaction(SIGINT, &action, NULL);
406
407 restart: for (;;) {
408 command_.clear();
409 std::vector<std::string> lines;
410
411 bool extra(false);
412 const char *prompt("cy# ");
413
414 if (setjmp(ctrlc_) != 0) {
415 mode_ = Working;
416 fputs("\n", fout);
417 fflush(fout);
418 goto restart;
419 }
420
421 read:
422 mode_ = Parsing;
423 char *line(readline(prompt));
424 mode_ = Working;
425 if (line == NULL)
426 break;
427 if (line[0] == '\0')
428 goto read;
429
430 if (!extra) {
431 extra = true;
432 if (line[0] == '?') {
433 std::string data(line + 1);
434 if (data == "bypass") {
435 bypass = !bypass;
436 fprintf(fout, "bypass == %s\n", bypass ? "true" : "false");
437 fflush(fout);
438 } else if (data == "debug") {
439 debug = !debug;
440 fprintf(fout, "debug == %s\n", debug ? "true" : "false");
441 fflush(fout);
442 } else if (data == "expand") {
443 expand = !expand;
444 fprintf(fout, "expand == %s\n", expand ? "true" : "false");
445 fflush(fout);
446 }
447 add_history(line);
448 ++histlines;
449 goto restart;
450 }
451 }
452
453 command_ += line;
454
455 char *begin(line), *end(line + strlen(line));
456 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
457 *nl = '\0';
458 lines.push_back(begin);
459 begin = nl + 1;
460 }
461
462 lines.push_back(begin);
463
464 free(line);
465
466 std::string code;
467
468 if (bypass)
469 code = command_;
470 else {
471 CYDriver driver;
472 cy::parser parser(driver);
473 Setup(driver, parser);
474
475 driver.data_ = command_.c_str();
476 driver.size_ = command_.size();
477
478 if (parser.parse() != 0 || !driver.errors_.empty()) {
479 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
480 cy::position begin(error->location_.begin);
481 if (begin.line != lines.size() || begin.column - 1 != lines.back().size() || error->warning_) {
482 cy::position end(error->location_.end);
483
484 if (begin.line != lines.size()) {
485 std::cerr << " | ";
486 std::cerr << lines[begin.line - 1] << std::endl;
487 }
488
489 std::cerr << "....";
490 for (size_t i(0); i != begin.column - 1; ++i)
491 std::cerr << '.';
492 if (begin.line != end.line || begin.column == end.column)
493 std::cerr << '^';
494 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
495 std::cerr << '^';
496 std::cerr << std::endl;
497
498 std::cerr << " | ";
499 std::cerr << error->message_ << std::endl;
500
501 add_history(command_.c_str());
502 ++histlines;
503 goto restart;
504 }
505 }
506
507 driver.errors_.clear();
508
509 command_ += '\n';
510 prompt = "cy> ";
511 goto read;
512 }
513
514 if (driver.program_ == NULL)
515 goto restart;
516
517 if (client_ != -1)
518 code = command_;
519 else {
520 std::ostringstream str;
521 CYOutput out(str, options);
522 Setup(out, driver, options);
523 out << *driver.program_;
524 code = str.str();
525 }
526 }
527
528 add_history(command_.c_str());
529 ++histlines;
530
531 if (debug)
532 std::cout << code << std::endl;
533
534 Run(client_, code, fout, expand);
535 }
536
537 if (append_history$ != NULL) {
538 _syscall(close(_syscall(open(histfile, O_CREAT | O_WRONLY, 0600))));
539 (*append_history$)(histlines, histfile);
540 } else {
541 write_history(histfile);
542 }
543
544 fputs("\n", fout);
545 fflush(fout);
546 }
547
548 static void *Map(const char *path, size_t *psize) {
549 int fd;
550 _syscall(fd = open(path, O_RDONLY));
551
552 struct stat stat;
553 _syscall(fstat(fd, &stat));
554 size_t size(stat.st_size);
555
556 *psize = size;
557
558 void *base;
559 _syscall(base = mmap(NULL, size, PROT_READ, MAP_SHARED, fd, 0));
560
561 _syscall(close(fd));
562 return base;
563 }
564
565 void InjectLibrary(pid_t pid);
566
567 int Main(int argc, char const * const argv[], char const * const envp[]) {
568 bool tty(isatty(STDIN_FILENO));
569 bool compile(false);
570 CYOptions options;
571
572 append_history$ = reinterpret_cast<int (*)(int, const char *)>(dlsym(RTLD_DEFAULT, "append_history"));
573
574 #ifdef CY_ATTACH
575 pid_t pid(_not(pid_t));
576 #endif
577
578 CYPool pool;
579 apr_getopt_t *state;
580 _aprcall(apr_getopt_init(&state, pool, argc, argv));
581
582 for (;;) {
583 char opt;
584 const char *arg;
585
586 apr_status_t status(apr_getopt(state,
587 "cg:n:"
588 #ifdef CY_ATTACH
589 "p:"
590 #endif
591 "s"
592 , &opt, &arg));
593
594 switch (status) {
595 case APR_EOF:
596 goto getopt;
597 case APR_BADCH:
598 case APR_BADARG:
599 fprintf(stderr,
600 "usage: cycript [-c]"
601 #ifdef CY_ATTACH
602 " [-p <pid|name>]"
603 #endif
604 " [<script> [<arg>...]]\n"
605 );
606 return 1;
607 default:
608 _aprcall(status);
609 }
610
611 switch (opt) {
612 case 'c':
613 compile = true;
614 break;
615
616 case 'g':
617 if (false);
618 else if (strcmp(arg, "rename") == 0)
619 options.verbose_ = true;
620 #if YYDEBUG
621 else if (strcmp(arg, "bison") == 0)
622 bison_ = true;
623 #endif
624 else {
625 fprintf(stderr, "invalid name for -g\n");
626 return 1;
627 }
628 break;
629
630 case 'n':
631 if (false);
632 else if (strcmp(arg, "minify") == 0)
633 pretty_ = true;
634 else {
635 fprintf(stderr, "invalid name for -n\n");
636 return 1;
637 }
638 break;
639
640 #ifdef CY_ATTACH
641 case 'p': {
642 size_t size(strlen(arg));
643 char *end;
644
645 pid = strtoul(arg, &end, 0);
646 if (arg + size != end) {
647 // XXX: arg needs to be escaped in some horrendous way of doom
648 const char *command(apr_psprintf(pool, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", arg));
649
650 if (FILE *pids = popen(command, "r")) {
651 char value[32];
652 size = 0;
653
654 for (;;) {
655 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
656 if (read == 0)
657 break;
658 else {
659 size += read;
660 if (size == sizeof(value)) {
661 pid = _not(pid_t);
662 goto fail;
663 }
664 }
665 }
666
667 size:
668 if (size == 0)
669 goto fail;
670 if (value[size - 1] == '\n') {
671 --size;
672 goto size;
673 }
674
675 value[size] = '\0';
676 size = strlen(value);
677 pid = strtoul(value, &end, 0);
678 if (value + size != end) fail:
679 pid = _not(pid_t);
680 _syscall(pclose(pids));
681 }
682
683 if (pid == _not(pid_t)) {
684 fprintf(stderr, "invalid pid for -p\n");
685 return 1;
686 }
687 }
688 } break;
689 #endif
690
691 case 's':
692 strict_ = true;
693 break;
694 }
695 } getopt:;
696
697 const char *script;
698 int ind(state->ind);
699
700 #ifdef CY_ATTACH
701 if (pid != _not(pid_t) && ind < argc - 1) {
702 fprintf(stderr, "-p cannot set argv\n");
703 return 1;
704 }
705
706 if (pid != _not(pid_t) && compile) {
707 fprintf(stderr, "-p conflicts with -c\n");
708 return 1;
709 }
710 #endif
711
712 if (ind == argc)
713 script = NULL;
714 else {
715 #ifdef CY_EXECUTE
716 // XXX: const_cast?! wtf gcc :(
717 CYSetArgs(argc - ind - 1, const_cast<const char **>(argv + ind + 1));
718 #endif
719 script = argv[ind];
720 if (strcmp(script, "-") == 0)
721 script = NULL;
722 }
723
724 #ifdef CY_ATTACH
725 if (pid != _not(pid_t) && script == NULL && !tty) {
726 fprintf(stderr, "non-terminal attaching to remote console\n");
727 return 1;
728 }
729 #endif
730
731 #ifdef CY_ATTACH
732 if (pid == _not(pid_t))
733 client_ = -1;
734 else {
735 int server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0))); try {
736 struct sockaddr_un address;
737 memset(&address, 0, sizeof(address));
738 address.sun_family = AF_UNIX;
739
740 sprintf(address.sun_path, "/tmp/.s.cy.%u", getpid());
741
742 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
743 _syscall(chmod(address.sun_path, 0777));
744
745 try {
746 _syscall(listen(server, 1));
747 InjectLibrary(pid);
748 client_ = _syscall(accept(server, NULL, NULL));
749 } catch (...) {
750 // XXX: exception?
751 unlink(address.sun_path);
752 throw;
753 }
754 } catch (...) {
755 _syscall(close(server));
756 throw;
757 }
758 }
759 #else
760 client_ = -1;
761 #endif
762
763 if (script == NULL && tty)
764 Console(pool, options);
765 else {
766 CYDriver driver(pool, script ?: "<stdin>");
767 cy::parser parser(driver);
768 Setup(driver, parser);
769
770 char *start, *end;
771
772 if (script == NULL) {
773 start = NULL;
774 end = NULL;
775
776 driver.file_ = stdin;
777 } else {
778 size_t size;
779 start = reinterpret_cast<char *>(Map(script, &size));
780 end = start + size;
781
782 if (size >= 2 && start[0] == '#' && start[1] == '!') {
783 start += 2;
784
785 if (void *line = memchr(start, '\n', end - start))
786 start = reinterpret_cast<char *>(line);
787 else
788 start = end;
789 }
790
791 driver.data_ = start;
792 driver.size_ = end - start;
793 }
794
795 if (parser.parse() != 0 || !driver.errors_.empty()) {
796 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
797 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
798 } else if (driver.program_ != NULL)
799 if (client_ != -1) {
800 std::string code(start, end-start);
801 Run(client_, code, stdout);
802 } else {
803 std::ostringstream str;
804 CYOutput out(str, options);
805 Setup(out, driver, options);
806 out << *driver.program_;
807 std::string code(str.str());
808 if (compile)
809 std::cout << code;
810 else
811 Run(client_, code, stdout);
812 }
813 }
814
815 return 0;
816 }
817
818 int main(int argc, char const * const argv[], char const * const envp[]) {
819 apr_status_t status(apr_app_initialize(&argc, &argv, &envp));
820
821 if (status != APR_SUCCESS) {
822 fprintf(stderr, "apr_app_initialize() != APR_SUCCESS\n");
823 return 1;
824 } else try {
825 return Main(argc, argv, envp);
826 } catch (const CYException &error) {
827 CYPool pool;
828 fprintf(stderr, "%s\n", error.PoolCString(pool));
829 return 1;
830 }
831 }