]> git.saurik.com Git - cycript.git/blob - Application.mm
4dc765bde2a6a03b57402ae765cb3acaa7bd3f5a
[cycript.git] / Application.mm
1 #define _GNU_SOURCE
2
3 #include <substrate.h>
4 #include "cycript.h"
5
6 #include <cstdio>
7 #include <sstream>
8
9 #include <setjmp.h>
10
11 #include <readline/readline.h>
12 #include <readline/history.h>
13
14 #include "Cycript.tab.hh"
15
16 static jmp_buf ctrlc_;
17
18 void sigint(int) {
19 longjmp(ctrlc_, 1);
20 }
21
22 int main(int argc, const char *argv[]) {
23 FILE *fout(stdout);
24
25 rl_bind_key('\t', rl_insert);
26
27 struct sigaction action;
28 sigemptyset(&action.sa_mask);
29 action.sa_handler = &sigint;
30 action.sa_flags = 0;
31 sigaction(SIGINT, &action, NULL);
32
33 restart: for (;;) {
34 std::string command;
35 std::vector<std::string> lines;
36
37 if (setjmp(ctrlc_) != 0) {
38 fputs("\n", fout);
39 fflush(fout);
40 goto restart;
41 }
42
43 const char *prompt("cy# ");
44 read:
45 char *line(readline(prompt));
46 if (line == NULL)
47 break;
48 lines.push_back(line);
49 command += line;
50 free(line);
51
52 CYDriver driver("");
53 cy::parser parser(driver);
54
55 driver.data_ = command.c_str();
56 driver.size_ = command.size();
57
58 if (parser.parse() != 0) {
59 for (CYDriver::Errors::const_iterator i(driver.errors_.begin()); i != driver.errors_.end(); ++i) {
60 cy::position begin(i->location_.begin);
61 if (begin.line != lines.size() || begin.column - 1 != lines.back().size()) {
62 std::cerr << i->message_ << std::endl;
63 goto restart;
64 }
65 }
66
67 driver.errors_.clear();
68
69 command += '\n';
70 prompt = "cy> ";
71 goto read;
72 }
73
74 if (driver.source_ == NULL)
75 goto restart;
76
77 add_history(command.c_str());
78
79 std::ostringstream str;
80 driver.source_->Show(str);
81
82 std::string code(str.str());
83 std::cout << code << std::endl;
84
85 _pooled
86
87 JSStringRef script(JSStringCreateWithUTF8CString(code.c_str()));
88
89 JSContextRef context(CYGetJSContext());
90
91 JSValueRef exception(NULL);
92 JSValueRef result(JSEvaluateScript(context, script, NULL, NULL, 0, &exception));
93 JSStringRelease(script);
94
95 if (exception != NULL)
96 result = exception;
97
98 if (JSValueIsUndefined(context, result))
99 goto restart;
100
101 CFStringRef json;
102
103 @try { json:
104 json = CYCopyJSONString(context, result);
105 } @catch (id error) {
106 CYThrow(context, error, &result);
107 goto json;
108 }
109
110 fputs([reinterpret_cast<const NSString *>(json) UTF8String], fout);
111 CFRelease(json);
112
113 fputs("\n", fout);
114 fflush(fout);
115 }
116
117 fputs("\n", fout);
118 fflush(fout);
119
120 return 0;
121 }