forked from ccgus/CocoaScript
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcocoascript_tool.m
More file actions
119 lines (72 loc) · 2.37 KB
/
cocoascript_tool.m
File metadata and controls
119 lines (72 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#import <Cocoa/Cocoa.h>
#import "COSListener.h"
#import "COScript.h"
BOOL JSCErrorHandlerExitOnError = YES;
@interface NullDebugController : NSObject<CODebugController>
@end
@implementation NullDebugController
- (void)output:(NSString*)format args:(va_list)args
{
}
@end
@interface JSCErrorHandler : NSObject {
}
@end
@implementation JSCErrorHandler
- (void)JSTalk:(COScript*)jstalk hadError:(NSString*)error onLineNumber:(NSInteger)lineNumber atSourceURL:(id)url {
printf("Error line %d, %s\n", (int)lineNumber, [[error description] UTF8String]);
if (JSCErrorHandlerExitOnError) {
exit(1);
}
}
@end
void runREPL(COScript *t) {
// thanks http://tlrobinson.net/blog/2008/10/10/command-line-interpreter-and-repl-for-jscocoa/ !
JSCErrorHandlerExitOnError = NO;
while (1) {
char buffer[1024];
printf("js> ");
if (fgets(buffer, 1024, stdin) == NULL) {
exit(0);
}
NSString *s = [[NSString alloc] initWithUTF8String:buffer];
id o = [t executeString:s];
if (o) {
printf("%s\n", [[o description] UTF8String]);
}
}
}
int main(int argc, char *argv[]) {
COScript *t = [[COScript alloc] init];
[t setErrorController:[[JSCErrorHandler alloc] init]];
if (argc < 2) {
runREPL(t);
exit(0);
}
NSString *source = nil;
NSString *arg = [NSString stringWithUTF8String:argv[1]];
if ([arg isEqualToString:@"-e"] && argc == 3) {
source = [NSString stringWithUTF8String:argv[2]];
}
else {
source = [NSString stringWithContentsOfFile:arg encoding:NSUTF8StringEncoding error:nil];
}
if (!source) {
printf("usage: %s <path to file>\n", argv[0]);
exit(0);
}
[t.env setObject:[NSURL fileURLWithPath:arg] forKey:@"scriptURL"];
if ([source hasPrefix:@"#!"]) {
NSRange r = [source rangeOfString:@"\n"];
if (r.location != NSNotFound) {
source = [source substringFromIndex:r.location];
}
}
[COScript setDebugController:[NullDebugController new]];
id o = [t executeString:source];
if (o) {
printf("%s\n", [[o description] UTF8String]);
}
[t cleanup];
return 0;
}