]> git.saurik.com Git - cycript.git/blob - Console.cpp
Bison does not actually care about the stack size.
[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 <fstream>
30 #include <sstream>
31
32 #include <setjmp.h>
33
34 #ifdef HAVE_READLINE_H
35 #include <readline.h>
36 #else
37 #include <readline/readline.h>
38 #endif
39
40 #ifdef HAVE_HISTORY_H
41 #include <history.h>
42 #else
43 #include <readline/history.h>
44 #endif
45
46 #include <errno.h>
47 #include <getopt.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/types.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
60 #include <sys/un.h>
61 #include <pwd.h>
62
63 #include <dlfcn.h>
64
65 #include "Display.hpp"
66 #include "Replace.hpp"
67
68 #include "Cycript.tab.hh"
69 #include "Driver.hpp"
70
71 static volatile enum {
72 Working,
73 Parsing,
74 Running,
75 Sending,
76 Waiting,
77 } mode_;
78
79 static jmp_buf ctrlc_;
80
81 static void sigint(int) {
82 switch (mode_) {
83 case Working:
84 return;
85 case Parsing:
86 longjmp(ctrlc_, 1);
87 case Running:
88 CYCancel();
89 return;
90 case Sending:
91 return;
92 case Waiting:
93 return;
94 }
95 }
96
97 #if YYDEBUG
98 static bool bison_;
99 #endif
100 static bool strict_;
101 static bool pretty_;
102
103 void Setup(CYDriver &driver, cy::parser &parser) {
104 #if YYDEBUG
105 if (bison_)
106 parser.set_debug_level(1);
107 #endif
108 if (strict_)
109 driver.strict_ = true;
110 }
111
112 void Setup(CYOutput &out, CYDriver &driver, CYOptions &options, bool lower) {
113 out.pretty_ = pretty_;
114 CYContext context(options);
115 if (lower)
116 driver.program_->Replace(context);
117 }
118
119 static CYUTF8String Run(CYPool &pool, int client, CYUTF8String code) {
120 const char *json;
121 uint32_t size;
122
123 if (client == -1) {
124 mode_ = Running;
125 #ifdef CY_EXECUTE
126 json = CYExecute(CYGetJSContext(), pool, code);
127 #else
128 json = NULL;
129 #endif
130 mode_ = Working;
131 if (json == NULL)
132 size = 0;
133 else
134 size = strlen(json);
135 } else {
136 mode_ = Sending;
137 size = code.size;
138 _assert(CYSendAll(client, &size, sizeof(size)));
139 _assert(CYSendAll(client, code.data, code.size));
140 mode_ = Waiting;
141 _assert(CYRecvAll(client, &size, sizeof(size)));
142 if (size == _not(uint32_t))
143 json = NULL;
144 else {
145 char *temp(new(pool) char[size + 1]);
146 _assert(CYRecvAll(client, temp, size));
147 temp[size] = '\0';
148 json = temp;
149 }
150 mode_ = Working;
151 }
152
153 return CYUTF8String(json, size);
154 }
155
156 static CYUTF8String Run(CYPool &pool, int client, const std::string &code) {
157 return Run(pool, client, CYUTF8String(code.c_str(), code.size()));
158 }
159
160 static std::ostream *out_;
161
162 static void Write(bool syntax, const char *data, size_t size, std::ostream &out) {
163 if (syntax)
164 CYLexerHighlight(data, size, out);
165 else
166 out.write(data, size);
167 }
168
169 static void Output(bool syntax, CYUTF8String json, std::ostream *out, bool expand = false) {
170 const char *data(json.data);
171 size_t size(json.size);
172
173 if (data == NULL || out == NULL)
174 return;
175
176 if (!expand ||
177 data[0] != '@' && data[0] != '"' && data[0] != '\'' ||
178 data[0] == '@' && data[1] != '"' && data[1] != '\''
179 )
180 Write(syntax, data, size, *out);
181 else for (size_t i(0); i != size; ++i)
182 if (data[i] != '\\')
183 *out << data[i];
184 else switch(data[++i]) {
185 case '\0': goto done;
186 case '\\': *out << '\\'; break;
187 case '\'': *out << '\''; break;
188 case '"': *out << '"'; break;
189 case 'b': *out << '\b'; break;
190 case 'f': *out << '\f'; break;
191 case 'n': *out << '\n'; break;
192 case 'r': *out << '\r'; break;
193 case 't': *out << '\t'; break;
194 case 'v': *out << '\v'; break;
195 default: *out << '\\'; --i; break;
196 }
197
198 done:
199 *out << std::endl;
200 }
201
202 static void Run(int client, bool syntax, const char *data, size_t size, std::ostream *out = NULL, bool expand = false) {
203 CYPool pool;
204 Output(syntax, Run(pool, client, CYUTF8String(data, size)), out, expand);
205 }
206
207 static void Run(int client, bool syntax, std::string &code, std::ostream *out = NULL, bool expand = false) {
208 Run(client, syntax, code.c_str(), code.size(), out, expand);
209 }
210
211 int (*append_history$)(int, const char *);
212
213 static std::string command_;
214
215 static CYExpression *ParseExpression(CYUTF8String code) {
216 std::stringstream stream;
217 stream << '(' << code << ')';
218 CYDriver driver(stream);
219
220 cy::parser parser(driver);
221 Setup(driver, parser);
222
223 if (parser.parse() != 0 || !driver.errors_.empty())
224 return NULL;
225
226 CYOptions options;
227 CYContext context(options);
228
229 CYStatement *statement(driver.program_->code_);
230 _assert(statement != NULL);
231 _assert(statement->next_ == NULL);
232
233 CYExpress *express(dynamic_cast<CYExpress *>(driver.program_->code_));
234 _assert(express != NULL);
235
236 CYParenthetical *parenthetical(dynamic_cast<CYParenthetical *>(express->expression_));
237 _assert(parenthetical != NULL);
238
239 return parenthetical->expression_;
240 }
241
242 static int client_;
243
244 static char **Complete(const char *word, int start, int end) {
245 rl_attempted_completion_over = ~0;
246
247 CYLocalPool pool;
248
249 std::string line(rl_line_buffer, start);
250 std::istringstream stream(command_ + line);
251 CYDriver driver(stream);
252
253 driver.auto_ = true;
254
255 cy::parser parser(driver);
256 Setup(driver, parser);
257
258 if (parser.parse() != 0 || !driver.errors_.empty())
259 return NULL;
260
261 if (driver.mode_ == CYDriver::AutoNone)
262 return NULL;
263
264 CYExpression *expression;
265
266 CYOptions options;
267 CYContext context(options);
268
269 std::ostringstream prefix;
270
271 switch (driver.mode_) {
272 case CYDriver::AutoPrimary:
273 expression = $ CYThis();
274 break;
275
276 case CYDriver::AutoDirect:
277 expression = driver.context_;
278 break;
279
280 case CYDriver::AutoIndirect:
281 expression = $ CYIndirect(driver.context_);
282 break;
283
284 case CYDriver::AutoMessage: {
285 CYDriver::Context &thing(driver.contexts_.back());
286 expression = $M($C1($V("object_getClass"), thing.context_), $S("messages"));
287 for (CYDriver::Context::Words::const_iterator part(thing.words_.begin()); part != thing.words_.end(); ++part)
288 prefix << (*part)->word_ << ':';
289 } break;
290
291 default:
292 _assert(false);
293 }
294
295 std::string begin(prefix.str());
296
297 driver.program_ = $ CYProgram($ CYExpress($C3(ParseExpression(
298 " function(object, prefix, word) {\n"
299 " var names = [];\n"
300 " var before = prefix.length;\n"
301 " prefix += word;\n"
302 " var entire = prefix.length;\n"
303 " for (var name in object)\n"
304 " if (name.substring(0, entire) == prefix)\n"
305 " names.push(name.substr(before));\n"
306 " return names;\n"
307 " }\n"
308 ), expression, $S(begin.c_str()), $S(word))));
309
310 driver.program_->Replace(context);
311
312 std::stringbuf str;
313 CYOutput out(str, options);
314 out << *driver.program_;
315
316 std::string code(str.str());
317 CYUTF8String json(Run(pool, client_, code));
318 // XXX: if this fails we should not try to parse it
319
320 CYExpression *result(ParseExpression(json));
321 if (result == NULL)
322 return NULL;
323
324 CYArray *array(dynamic_cast<CYArray *>(result->Primitive(context)));
325 if (array == NULL) {
326 *out_ << '\n';
327 Output(false, json, out_);
328 rl_forced_update_display();
329 return NULL;
330 }
331
332 // XXX: use an std::set?
333 typedef std::vector<std::string> Completions;
334 Completions completions;
335
336 std::string common;
337 bool rest(false);
338
339 CYForEach (element, array->elements_) {
340 CYString *string(dynamic_cast<CYString *>(element->value_));
341 _assert(string != NULL);
342
343 std::string completion;
344 if (string->size_ != 0)
345 completion.assign(string->value_, string->size_);
346 else if (driver.mode_ == CYDriver::AutoMessage)
347 completion = "]";
348 else
349 continue;
350
351 completions.push_back(completion);
352
353 if (!rest) {
354 common = completion;
355 rest = true;
356 } else {
357 size_t limit(completion.size()), size(common.size());
358 if (size > limit)
359 common = common.substr(0, limit);
360 else
361 limit = size;
362 for (limit = 0; limit != size; ++limit)
363 if (common[limit] != completion[limit])
364 break;
365 if (limit != size)
366 common = common.substr(0, limit);
367 }
368 }
369
370 size_t count(completions.size());
371 if (count == 0)
372 return NULL;
373
374 size_t colon(common.find(':'));
375 if (colon != std::string::npos)
376 common = common.substr(0, colon + 1);
377 if (completions.size() == 1)
378 common += ' ';
379
380 char **results(reinterpret_cast<char **>(malloc(sizeof(char *) * (count + 2))));
381
382 results[0] = strdup(common.c_str());
383 size_t index(0);
384 for (Completions::const_iterator i(completions.begin()); i != completions.end(); ++i)
385 results[++index] = strdup(i->c_str());
386 results[count + 1] = NULL;
387
388 return results;
389 }
390
391 // need char *, not const char *
392 static char name_[] = "cycript";
393 static char break_[] = " \t\n\"\\'`@><=;|&{(" ")}" ".:[]";
394
395 class History {
396 private:
397 std::string histfile_;
398 size_t histlines_;
399
400 public:
401 History(std::string histfile) :
402 histfile_(histfile),
403 histlines_(0)
404 {
405 read_history(histfile_.c_str());
406 }
407
408 ~History() {
409 if (append_history$ != NULL) {
410 int fd(_syscall(open(histfile_.c_str(), O_CREAT | O_WRONLY, 0600)));
411 _syscall(close(fd));
412 _assert((*append_history$)(histlines_, histfile_.c_str()) == 0);
413 } else {
414 _assert(write_history(histfile_.c_str()) == 0);
415 }
416 }
417
418 void operator +=(const std::string &command) {
419 add_history(command.c_str());
420 ++histlines_;
421 }
422 };
423
424 static void Console(CYOptions &options) {
425 std::string basedir;
426 if (const char *home = getenv("HOME"))
427 basedir = home;
428 else {
429 passwd *passwd;
430 if (const char *username = getenv("LOGNAME"))
431 passwd = getpwnam(username);
432 else
433 passwd = getpwuid(getuid());
434 basedir = passwd->pw_dir;
435 }
436
437 basedir += "/.cycript";
438 mkdir(basedir.c_str(), 0700);
439
440 rl_initialize();
441 rl_readline_name = name_;
442
443 History history(basedir + "/history");
444
445 bool bypass(false);
446 bool debug(false);
447 bool expand(false);
448 bool lower(true);
449 bool syntax(true);
450
451 out_ = &std::cout;
452
453 // rl_completer_word_break_characters is broken in libedit
454 rl_basic_word_break_characters = break_;
455
456 rl_completer_word_break_characters = break_;
457 rl_attempted_completion_function = &Complete;
458 rl_bind_key('\t', rl_complete);
459
460 struct sigaction action;
461 sigemptyset(&action.sa_mask);
462 action.sa_handler = &sigint;
463 action.sa_flags = 0;
464 sigaction(SIGINT, &action, NULL);
465
466 restart: for (;;) {
467 command_.clear();
468 std::vector<std::string> lines;
469
470 bool extra(false);
471 const char *prompt("cy# ");
472
473 if (setjmp(ctrlc_) != 0) {
474 mode_ = Working;
475 *out_ << std::endl;
476 goto restart;
477 }
478
479 read:
480
481 #if RL_READLINE_VERSION >= 0x0600
482 if (syntax)
483 rl_redisplay_function = CYDisplayUpdate;
484 else
485 rl_redisplay_function = rl_redisplay;
486 #endif
487
488 mode_ = Parsing;
489 char *line(readline(prompt));
490 mode_ = Working;
491
492 if (line == NULL) {
493 *out_ << std::endl;
494 break;
495 } else if (line[0] == '\0')
496 goto read;
497
498 if (!extra) {
499 extra = true;
500 if (line[0] == '?') {
501 std::string data(line + 1);
502 if (data == "bypass") {
503 bypass = !bypass;
504 *out_ << "bypass == " << (bypass ? "true" : "false") << std::endl;
505 } else if (data == "debug") {
506 debug = !debug;
507 *out_ << "debug == " << (debug ? "true" : "false") << std::endl;
508 } else if (data == "destroy") {
509 CYDestroyContext();
510 } else if (data == "gc") {
511 *out_ << "collecting... " << std::flush;
512 CYGarbageCollect(CYGetJSContext());
513 *out_ << "done." << std::endl;
514 } else if (data == "exit") {
515 return;
516 } else if (data == "expand") {
517 expand = !expand;
518 *out_ << "expand == " << (expand ? "true" : "false") << std::endl;
519 } else if (data == "lower") {
520 lower = !lower;
521 *out_ << "lower == " << (lower ? "true" : "false") << std::endl;
522 } else if (data == "syntax") {
523 syntax = !syntax;
524 *out_ << "syntax == " << (syntax ? "true" : "false") << std::endl;
525 }
526 command_ = line;
527 history += command_;
528 goto restart;
529 }
530 }
531
532 command_ += line;
533 command_ += "\n";
534
535 char *begin(line), *end(line + strlen(line));
536 while (char *nl = reinterpret_cast<char *>(memchr(begin, '\n', end - begin))) {
537 *nl = '\0';
538 lines.push_back(begin);
539 begin = nl + 1;
540 }
541
542 lines.push_back(begin);
543
544 free(line);
545
546 std::string code;
547
548 if (bypass)
549 code = command_;
550 else {
551 CYLocalPool pool;
552
553 std::istringstream stream(command_);
554 CYDriver driver(stream);
555
556 cy::parser parser(driver);
557 Setup(driver, parser);
558
559 if (parser.parse() != 0 || !driver.errors_.empty()) {
560 for (CYDriver::Errors::const_iterator error(driver.errors_.begin()); error != driver.errors_.end(); ++error) {
561 CYPosition begin(error->location_.begin);
562 if (begin.line != lines.size() + 1 || error->warning_) {
563 CYPosition end(error->location_.end);
564
565 if (begin.line != lines.size()) {
566 std::cerr << " | ";
567 std::cerr << lines[begin.line - 1] << std::endl;
568 }
569
570 std::cerr << "....";
571 for (size_t i(0); i != begin.column; ++i)
572 std::cerr << '.';
573 if (begin.line != end.line || begin.column == end.column)
574 std::cerr << '^';
575 else for (size_t i(0), e(end.column - begin.column); i != e; ++i)
576 std::cerr << '^';
577 std::cerr << std::endl;
578
579 std::cerr << " | ";
580 std::cerr << error->message_ << std::endl;
581
582 history += command_.substr(0, command_.size() - 1);
583 goto restart;
584 }
585 }
586
587 driver.errors_.clear();
588
589 prompt = "cy> ";
590 goto read;
591 }
592
593 if (driver.program_ == NULL)
594 goto restart;
595
596 std::stringbuf str;
597 CYOutput out(str, options);
598 Setup(out, driver, options, lower);
599 out << *driver.program_;
600 code = str.str();
601 }
602
603 history += command_.substr(0, command_.size() - 1);
604
605 if (debug) {
606 std::cout << "cy= ";
607 Write(syntax, code.c_str(), code.size(), std::cout);
608 std::cout << std::endl;
609 }
610
611 Run(client_, syntax, code, out_, expand);
612 }
613 }
614
615 void InjectLibrary(pid_t, int, const char *[]);
616
617 int Main(int argc, char * const argv[], char const * const envp[]) {
618 bool tty(isatty(STDIN_FILENO));
619 bool compile(false);
620 bool target(false);
621 CYOptions options;
622
623 append_history$ = (int (*)(int, const char *)) (dlsym(RTLD_DEFAULT, "append_history"));
624
625 #ifdef CY_ATTACH
626 pid_t pid(_not(pid_t));
627 #endif
628
629 const char *host(NULL);
630 const char *port(NULL);
631
632 optind = 1;
633
634 for (;;) {
635 int option(getopt_long(argc, argv,
636 "c"
637 "g:"
638 "n:"
639 #ifdef CY_ATTACH
640 "p:"
641 #endif
642 "r:"
643 "s"
644 , (const struct option[]) {
645 {NULL, no_argument, NULL, 'c'},
646 {NULL, required_argument, NULL, 'g'},
647 {NULL, required_argument, NULL, 'n'},
648 #ifdef CY_ATTACH
649 {NULL, required_argument, NULL, 'p'},
650 #endif
651 {NULL, required_argument, NULL, 'r'},
652 {NULL, no_argument, NULL, 's'},
653 {0, 0, 0, 0}}, NULL));
654
655 switch (option) {
656 case -1:
657 goto getopt;
658
659 case ':':
660 case '?':
661 fprintf(stderr,
662 "usage: cycript [-c]"
663 #ifdef CY_ATTACH
664 " [-p <pid|name>]"
665 #endif
666 " [-r <host:port>]"
667 " [<script> [<arg>...]]\n"
668 );
669 return 1;
670
671 target:
672 if (!target)
673 target = true;
674 else {
675 fprintf(stderr, "only one of -[c"
676 #ifdef CY_ATTACH
677 "p"
678 #endif
679 "r] may be used at a time\n");
680 return 1;
681 }
682 break;
683
684 case 'c':
685 compile = true;
686 goto target;
687
688 case 'g':
689 if (false);
690 else if (strcmp(optarg, "rename") == 0)
691 options.verbose_ = true;
692 #if YYDEBUG
693 else if (strcmp(optarg, "bison") == 0)
694 bison_ = true;
695 #endif
696 else {
697 fprintf(stderr, "invalid name for -g\n");
698 return 1;
699 }
700 break;
701
702 case 'n':
703 if (false);
704 else if (strcmp(optarg, "minify") == 0)
705 pretty_ = true;
706 else {
707 fprintf(stderr, "invalid name for -n\n");
708 return 1;
709 }
710 break;
711
712 #ifdef CY_ATTACH
713 case 'p': {
714 size_t size(strlen(optarg));
715 char *end;
716
717 pid = strtoul(optarg, &end, 0);
718 if (optarg + size != end) {
719 // XXX: arg needs to be escaped in some horrendous way of doom
720 // XXX: this is a memory leak now because I just don't care enough
721 char *command;
722 asprintf(&command, "ps axc|sed -e '/^ *[0-9]/{s/^ *\\([0-9]*\\)\\( *[^ ]*\\)\\{3\\} *-*\\([^ ]*\\)/\\3 \\1/;/^%s /{s/^[^ ]* //;q;};};d'", optarg);
723
724 if (FILE *pids = popen(command, "r")) {
725 char value[32];
726 size = 0;
727
728 for (;;) {
729 size_t read(fread(value + size, 1, sizeof(value) - size, pids));
730 if (read == 0)
731 break;
732 else {
733 size += read;
734 if (size == sizeof(value))
735 goto fail;
736 }
737 }
738
739 size:
740 if (size == 0)
741 goto fail;
742 if (value[size - 1] == '\n') {
743 --size;
744 goto size;
745 }
746
747 value[size] = '\0';
748 size = strlen(value);
749 pid = strtoul(value, &end, 0);
750 if (value + size != end) fail:
751 pid = _not(pid_t);
752 _syscall(pclose(pids));
753 }
754
755 if (pid == _not(pid_t)) {
756 fprintf(stderr, "unable to find process `%s' using ps\n", optarg);
757 return 1;
758 }
759 }
760 } goto target;
761 #endif
762
763 case 'r': {
764 //size_t size(strlen(optarg));
765
766 char *colon(strrchr(optarg, ':'));
767 if (colon == NULL) {
768 fprintf(stderr, "missing colon in hostspec\n");
769 return 1;
770 }
771
772 /*char *end;
773 port = strtoul(colon + 1, &end, 10);
774 if (end != optarg + size) {
775 fprintf(stderr, "invalid port in hostspec\n");
776 return 1;
777 }*/
778
779 host = optarg;
780 *colon = '\0';
781 port = colon + 1;
782 } goto target;
783
784 case 's':
785 strict_ = true;
786 break;
787
788 default:
789 _assert(false);
790 }
791 }
792
793 getopt:
794 argc -= optind;
795 argv += optind;
796
797 const char *script;
798
799 #ifdef CY_ATTACH
800 if (pid != _not(pid_t) && argc > 1) {
801 fprintf(stderr, "-p cannot set argv\n");
802 return 1;
803 }
804 #endif
805
806 if (argc == 0)
807 script = NULL;
808 else {
809 #ifdef CY_EXECUTE
810 // XXX: const_cast?! wtf gcc :(
811 CYSetArgs(argc - 1, const_cast<const char **>(argv + 1));
812 #endif
813 script = argv[0];
814 if (strcmp(script, "-") == 0)
815 script = NULL;
816 }
817
818 #ifdef CY_ATTACH
819 if (pid == _not(pid_t))
820 client_ = -1;
821 else {
822 struct Socket {
823 int fd_;
824
825 Socket(int fd) :
826 fd_(fd)
827 {
828 }
829
830 ~Socket() {
831 close(fd_);
832 }
833
834 operator int() {
835 return fd_;
836 }
837 } server(_syscall(socket(PF_UNIX, SOCK_STREAM, 0)));
838
839 struct sockaddr_un address;
840 memset(&address, 0, sizeof(address));
841 address.sun_family = AF_UNIX;
842
843 const char *tmp;
844 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__))
845 tmp = "/Library/Caches";
846 #else
847 tmp = "/tmp";
848 #endif
849
850 sprintf(address.sun_path, "%s/.s.cy.%u", tmp, getpid());
851 unlink(address.sun_path);
852
853 struct File {
854 const char *path_;
855
856 File(const char *path) :
857 path_(path)
858 {
859 }
860
861 ~File() {
862 unlink(path_);
863 }
864 } file(address.sun_path);
865
866 _syscall(bind(server, reinterpret_cast<sockaddr *>(&address), SUN_LEN(&address)));
867 _syscall(chmod(address.sun_path, 0777));
868
869 _syscall(listen(server, 1));
870 InjectLibrary(pid, 1, (const char *[]) {address.sun_path, NULL});
871 client_ = _syscall(accept(server, NULL, NULL));
872 }
873 #else
874 client_ = -1;
875 #endif
876
877 if (client_ == -1 && host != NULL && port != NULL) {
878 struct addrinfo hints;
879 memset(&hints, 0, sizeof(hints));
880 hints.ai_family = AF_UNSPEC;
881 hints.ai_socktype = SOCK_STREAM;
882 hints.ai_protocol = 0;
883 hints.ai_flags = 0;
884
885 struct addrinfo *infos;
886 _syscall(getaddrinfo(host, port, &hints, &infos));
887
888 _assert(infos != NULL); try {
889 for (struct addrinfo *info(infos); info != NULL; info = info->ai_next) {
890 int client(_syscall(socket(info->ai_family, info->ai_socktype, info->ai_protocol))); try {
891 _syscall(connect(client, info->ai_addr, info->ai_addrlen));
892 client_ = client;
893 break;
894 } catch (...) {
895 _syscall(close(client));
896 throw;
897 }
898 }
899 } catch (...) {
900 freeaddrinfo(infos);
901 throw;
902 }
903 }
904
905 if (script == NULL && tty)
906 Console(options);
907 else {
908 CYLocalPool pool;
909
910 std::istream *stream;
911 if (script == NULL) {
912 stream = &std::cin;
913 script = "<stdin>";
914 } else {
915 stream = new std::fstream(script, std::ios::in | std::ios::binary);
916 _assert(!stream->fail());
917 }
918
919 CYDriver driver(*stream, script);
920 cy::parser parser(driver);
921 Setup(driver, parser);
922
923 if (parser.parse() != 0 || !driver.errors_.empty()) {
924 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i)
925 std::cerr << i->location_.begin << ": " << i->message_ << std::endl;
926 } else if (driver.program_ != NULL) {
927 std::stringbuf str;
928 CYOutput out(str, options);
929 Setup(out, driver, options, true);
930 out << *driver.program_;
931 std::string code(str.str());
932 if (compile)
933 std::cout << code;
934 else
935 Run(client_, false, code, &std::cout);
936 }
937 }
938
939 return 0;
940 }
941
942 int main(int argc, char * const argv[], char const * const envp[]) {
943 try {
944 return Main(argc, argv, envp);
945 } catch (const CYException &error) {
946 CYPool pool;
947 fprintf(stderr, "%s\n", error.PoolCString(pool));
948 return 1;
949 }
950 }