forked from pmougin/F-Script
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFSExecutor.m
323 lines (262 loc) · 10.6 KB
/
FSExecutor.m
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/* Executor.m Copyright (c) 1998-2009 Philippe Mougin. */
/* This software is open source. See the license. */
#import "build_config.h"
#import "FSExecutor.h"
#import "FSCompiler.h"
#import <objc/objc.h>
#import "FScriptFunctions.h"
#if !GNU_RUNTIME
# import "objc/objc-class.h"
#endif
#import "string.h"
#import "FSSymbolTable.h"
#import "FSExecEngine.h"
#import <Foundation/Foundation.h>
#import <Foundation/NSDebug.h>
#import "FSArray.h"
#import "FSCompilationResult.h"
#import "FSBoolean.h"
#import "FSSystem.h"
#import "FSInterpreterResultPrivate.h"
#import "Space.h"
#import "BlockStackElem.h"
#import "FSBlock.h"
#import "BlockPrivate.h"
#import "BlockInspector.h"
#import "FSNumber.h"
#import "FSVoid.h"
#import "FSMiscTools.h"
#import "FSReturnSignal.h"
void __attribute__ ((constructor)) initializeFSExecutor(void)
{
[NSKeyedUnarchiver setClass:[FSExecutor class] forClassName:@"Executor"];
[NSUnarchiver decodeClassName:@"Executor" asClassName:@"FSExecutor"];
}
@implementation FSExecutor
+ (void)initialize
{
static BOOL tooLate = NO;
if ( !tooLate )
{
[self setVersion:1];
[FSVoid initialize]; // to have the fsVoid global variable initialized
[FSBoolean initialize]; // to have the fsTrue and fsFalse global variables initialized
//[NSAutoreleasePool enableFreedObjectCheck:YES];
tooLate = YES;
}
}
- (FSArray *) allDefinedSymbols
{
return [localSymbolTable allDefinedSymbols];
}
- (void) breakCycles
{
// Break the potential cycles caused by localSymbolTable
// for example: localSymbolTable --> a block --> a symbolTable -(parent)-> localSymbolTable
[localSymbolTable removeAllObjects];
}
- (void) dealloc
{
//NSLog(@"Executor dealloc");
[journalName release];
[journal release];
[localSymbolTable release];
[compiler release];
[super dealloc];
}
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeConditionalObject:interpreter forKey:@"interpreter"];
[coder encodeBool:should_journal forKey:@"shouldJournal"];
[coder encodeObject:localSymbolTable forKey:@"symbolTable"];
}
-(FSInterpreterResult *)execute:(NSString *)command
{
FSCompilationResult *compilationResult;
struct res_exec execResult;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
FSInterpreterResult *r;
if (should_journal && journal)
{
[journal writeData:[command dataUsingEncoding:NSUTF8StringEncoding]];
[journal writeData:[@"\n" dataUsingEncoding:NSUTF8StringEncoding]];
[journal synchronizeFile];
}
compilationResult = [compiler compileCode:[command UTF8String] withParentSymbolTable:localSymbolTable];
switch(compilationResult->type)
{
case ERROR :
if (compilationResult->errorLastCharacterIndex == -1)
r = [FSInterpreterResult interpreterResultWithStatus:FS_SYNTAX_ERROR result:nil errorRange:NSMakeRange(0,0) errorMessage:compilationResult->errorMessage callStack:nil];
else
r = [FSInterpreterResult interpreterResultWithStatus:FS_SYNTAX_ERROR result:nil errorRange:NSMakeRange(compilationResult->errorFirstCharacterIndex, 1+compilationResult->errorLastCharacterIndex - compilationResult->errorFirstCharacterIndex) errorMessage:compilationResult->errorMessage callStack:nil];
break;
case OK :
{
if (verboseLevel >= 5) NSLog(@"before execute()");
@try
{
execResult = execute(compilationResult->code, localSymbolTable); // may raise
if (execResult.errorStr)
{
id callStack = [execResult.exception isKindOfClass:[NSException class]] ? [[execResult.exception userInfo] objectForKey:@"FScriptBlockStack"] : nil;
r = [FSInterpreterResult interpreterResultWithStatus:FS_EXECUTION_ERROR result:nil errorRange:NSMakeRange(execResult.errorFirstCharIndex, 1+execResult.errorLastCharIndex - execResult.errorFirstCharIndex) errorMessage:execResult.errorStr callStack:callStack];
}
else
r = [FSInterpreterResult interpreterResultWithStatus:FS_OK result:execResult.result errorRange:NSMakeRange(0,0) errorMessage:nil callStack:nil];
}
@catch (FSReturnSignal *returnSignal)
{
r = [FSInterpreterResult interpreterResultWithStatus:FS_EXECUTION_ERROR result:nil errorRange:NSMakeRange(0,0) errorMessage:@"invalid return" callStack:nil];
}
break;
}
default :
r = nil; // Should not happend. It's here to avoid a compiler warning.
assert(0);
}
[r retain]; // to move r out of pool
if (verboseLevel >= 5) NSLog(@"before [pool release]");
[pool release];
if (verboseLevel >= 5) NSLog(@"after [pool release]\n-------------------------------");
return [r autorelease];
}
- (id)initWithInterpreter:(FSInterpreter *)theInterpreter
{
if ((self = [super init]))
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
interpreter = theInterpreter; // WARNING : no retain in order to avoid a cycle
should_journal = NO;
verboseLevel = 0;
localSymbolTable = [[FSSymbolTable alloc] initWithParent:nil tryToAttachWhenDecoding:NO];
[localSymbolTable insertSymbol:@"sys" object:[FSSystem system:self]];
compiler = [[FSCompiler alloc] init];
[pool release];
return self;
}
return nil;
}
- (id)initWithCoder:(NSCoder *)coder
{
struct FSContextIndex ind;
self = [super init];
verboseLevel = 0;
if ([coder allowsKeyedCoding])
{
interpreter = [coder decodeObjectForKey:@"interpreter"]; // WARNING : no retain in order to avoid a cycle
should_journal =[coder decodeBoolForKey:@"shouldJournal"];
localSymbolTable = [[coder decodeObjectForKey:@"symbolTable"] retain];
}
else
{
interpreter = [coder decodeObject]; // WARNING : no retain in order to avoid a cycle
[coder decodeValueOfObjCType:@encode(typeof(should_journal)) at:&should_journal];
if ([coder versionForClassName:@"Executor"] == 0)
{
int temp;
[coder decodeObject]; // In version 0 we stored the journal Name.
[coder decodeValueOfObjCType:@encode(typeof(verboseLevel)) at:&temp];
}
localSymbolTable = [[coder decodeObject] retain];
}
ind = [localSymbolTable indexOfSymbol:@"sys"];
if (ind.index != -1)
[localSymbolTable setObject:[FSSystem system:self] forIndex:ind];
else
[localSymbolTable insertSymbol:@"sys" object:[FSSystem system:self]];
compiler = [[FSCompiler alloc] init];
return self;
}
- (void)installFlightTutorial // Flight tutorial installation. May raise.
{
NSString *path;
NSString *tutorialInstalation;
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
BOOL shouldJournal = [self shouldJournal];
if ((path = [bundle pathForResource:@"FlightTutorial" ofType:@"txt"]))
{
FSInterpreterResult *res;
NSStringEncoding usedEncoding;
NSError *error;
tutorialInstalation = [NSString stringWithContentsOfFile:path usedEncoding:&usedEncoding error:&error];
if (!tutorialInstalation)
{
NSLog(@"Unable to read the flight tutorial instalation file: %@", [error localizedDescription]);
}
[self setShouldJournal:NO];
res = [self execute:tutorialInstalation];
[self setShouldJournal:shouldJournal];
if (![res isOK]) [[NSException exceptionWithName:@"FSInternalError" reason:[NSString stringWithFormat:@"Error during Flight tutorial installation: %@",[res errorMessage]] userInfo:nil] raise];
}
}
-(FSInterpreter *)interpreter // Will return nil if the associated interpreter no longer exists
{ return interpreter; }
- (void)interpreterIsDeallocating
{
interpreter = nil; // WARNING: no retain/release on this pointer in order to avoid a cycle
}
- (id)objectForSymbol:(NSString *)symbol found:(BOOL *)found // foud may be passed as NULL
{
return [localSymbolTable objectForSymbol:symbol found:found];
}
- (id)performOpenFile:(NSString *)file
{
NSString *fname = [file lastPathComponent];
NSUInteger nb = [fname length];
while (nb != ([fname = [fname stringByDeletingPathExtension] length]))
nb = [fname length]; // remove all extensions
return self;
}
- (BOOL)setJournalName:(NSString *)filename
{
NSString *oldJournalName = journalName;
NSFileHandle *oldJournal = journal;
NSDictionary *fileAttributes;
NSUInteger maxLength = 80000000; // The journal file will be truncated if it is bigger than 80 Mo.
if (!filename) return NO;
if (![[NSFileManager defaultManager] fileExistsAtPath:filename]) [[NSFileManager defaultManager] createFileAtPath:filename contents:[NSData data] attributes:nil];
fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filename error:NULL];
if ([[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue] > maxLength)
{
NSData *journalData = [NSData dataWithContentsOfFile:filename];
NSData *truncatedJournalData = [journalData subdataWithRange:NSMakeRange([journalData length]-(maxLength/2), (maxLength/2))];
[truncatedJournalData writeToFile:filename atomically:YES];
}
journal = [[NSFileHandle fileHandleForWritingAtPath:filename] retain];
[journal seekToEndOfFile];
if (journal)
{
[oldJournal release];
journalName = [filename copy];
[oldJournalName release];
return YES;
}
else return NO;
}
- (void)setShouldJournal:(BOOL)shouldJournal { should_journal = shouldJournal; }
-(void)setObject:(id)object forSymbol:(NSString *)symbol
{
[localSymbolTable setObject:object forSymbol:symbol];
}
- (void) setVerboseLevel:(NSInteger)theVerboseLevel {verboseLevel = theVerboseLevel;}
- (BOOL)shouldJournal
{ return should_journal; }
// ULSYSTEM PROTOCOL (informal)
- (void)setSpace:(Space*)space // must be called from an interpreter execution (a user command) because of intruction (A)
{
struct FSContextIndex ind;
[localSymbolTable autorelease]; // There is a problem here: a symbolTable can have several retain cycles involving Blocks and the parent pointer of their symbolTables. So this autorelease may not avoid a memory leak.
[self breakCycles]; // This solve the problem discussed above, but create another one: the symbolTable is now empty, so objects that migth access it may not like it (ex: a block wich is executed may get a "symbol not defined" error).
localSymbolTable = [[space localSymbolTable] retain];
ind = [localSymbolTable indexOfSymbol:@"sys"];
if (ind.index != -1) [localSymbolTable setObject:[FSSystem system:self] forIndex:ind];
else [localSymbolTable insertSymbol:@"sys" object:[FSSystem system:self]];
[(FSBlock *)[self objectForSymbol:@"fs_latent" found:NULL] value]; // (A) This instruction may raise (value is a user method)
}
- (Space*)space
{
return [[[Space alloc] initSymbolTableLocale:localSymbolTable] autorelease];
}
- (FSSymbolTable *) symbolTable { return localSymbolTable;}
@end