Source

Silver / Classes / Types / SVClass.m

Full commit
  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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
//
//  SVClass.m
//  SV
//
//  Created by Michael Tindal on 9/25/10.
//  Copyright (c) 2010 Michael Tindal. All rights reserved.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of
// the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//

#import "SVClass.h"
#import "SVFunction.h"
#import "SVCategory.h"
#import "NSMutableDictionary+SVExtensions.h"
#import "SVControlOperations.h"
#import "SVVariableAssignment.h"
#import "SVVariable.h"
#import "SVClassWrapper.h"
#import <objc/runtime.h>

NSMutableDictionary * sv_block_table;
NSMutableDictionary * sv_undef_table;
NSMutableDictionary * sv_remove_table;

@interface SVFunction (SVClassExtension)

- (SEL) generateSelectorName;

@end

@interface SVFunction (UndocumentedSVClass)

- (void) setLcontext:(id)value;

- (NSString *) stringValueWithDepth:(NSInteger)d isFunctionArgument:(BOOL)f isInClass:(BOOL)c;

@end

@interface SVNativeFunction : NSObject {
    id target;
    NSString * selector;
    int numArgs;
}

@property (retain) id target;
@property (copy) NSString * selector;
@property (assign) int numArgs;
@property (assign) Method objcMethod;
@end

@interface SVFunction (SVPrivate)

- (id) evalDefinitionWithContext:(NSMutableDictionary *)context;

- (id) evalCallWithContext:(NSMutableDictionary *)context;

- (id) evalNativeFunctionWithContext:(NSMutableDictionary *)context;

- (id) initNativeFunctionWithName:(NSString *)name target:(id)target selector:(SEL)sel;

- (id) initBridgedFunctionWithName:(NSString *)name signature:(NSString *)signature;

- (id) evalBridgedFunctionWithContext:(NSMutableDictionary *)context;

- (id) evalMacroFunctionWithContext:(NSMutableDictionary *)context;

- (NSString *) stringValueWithDepth:(NSInteger)d isFunctionArgument:(BOOL)f isInClass:(BOOL)c;

@property (assign) BOOL isCall, isBridged, isNative, isMacro;
@property (retain) SVNativeFunction * nativeFunc;
@property (assign) void * bridgedFunc;
@property (retain) NSMutableDictionary * lcontext;
@property (copy) NSString * text;
@property (retain) SVFunction * yieldFunc;
@end

NSString * __sv_getMethodName(id, SEL);

SVFunction * __sv_lookupMethod(id, NSString *);

NSMutableDictionary * __sv_createFunctionCall(SVFunction *);

void __sv_registerSuper(id, NSMutableDictionary *);

id __sv_stubPropertyGetter(id, SEL);

void __sv_stubPropertySetter(id, SEL, id);

id __sv_noArgumentStub(id, SEL);

id __sv_oneArgumentStub(id, SEL, id);

id __sv_twoArgumentStub(id, SEL, id, id);

id __sv_threeArgumentStub(id, SEL, id, id, id);

id __sv_fourArgumentStub(id, SEL, id, id, id, id);

id __sv_fiveArgumentStub(id, SEL, id, id, id, id, id);

extern NSMutableDictionary* __SV_XCVHolder__;

@implementation SVIvar

+ (SVIvar *) ivarWithName:(NSString *)name
{
    return [[self alloc] initWithName:name];
}


- (id) initWithName:(NSString *)name
{
    if ((self = [super init])) {
        name_ = [name copy];
    }
    return self;
}


@synthesize name = name_;
@end

@implementation SVFunction (SVClassExtension)

- (SEL) generateSelectorName
{
    NSMutableString * mstring = [NSMutableString string];
    [mstring appendString:self.name];
    if([mstring isEqualToString:@".."]) return NSSelectorFromString(@"..:");
    if([mstring isEqualToString:@"..."]) return NSSelectorFromString(@"...:");
    if([mstring isEqualToString:@"|"]) return NSSelectorFromString(@"|:");
    if([mstring isEqualToString:@"^"]) return NSSelectorFromString(@"^:");
    if([mstring isEqualToString:@"&"]) return NSSelectorFromString(@"&:");
    if([mstring isEqualToString:@"<=>"]) return NSSelectorFromString(@"<=>:");
    if([mstring isEqualToString:@"=="]) return NSSelectorFromString(@"==:");
    if([mstring isEqualToString:@"==="]) return NSSelectorFromString(@"===:");
    if([mstring isEqualToString:@"=~"]) return NSSelectorFromString(@"=~:");
    if([mstring isEqualToString:@"<"]) return NSSelectorFromString(@"<:");
    if([mstring isEqualToString:@"<="]) return NSSelectorFromString(@"<=:");
    if([mstring isEqualToString:@">"]) return NSSelectorFromString(@">:");
    if([mstring isEqualToString:@">="]) return NSSelectorFromString(@">=:");
    if([mstring isEqualToString:@"+"]) return NSSelectorFromString(@"+:");
    if([mstring isEqualToString:@"-"]) return NSSelectorFromString(@"-:");
    if([mstring isEqualToString:@"*"]) return NSSelectorFromString(@"*:");
    if([mstring isEqualToString:@"/"]) return NSSelectorFromString(@"/:");
    if([mstring isEqualToString:@"%"]) return NSSelectorFromString(@"%:");
    if([mstring isEqualToString:@"**"]) return NSSelectorFromString(@"**:");
    if([mstring isEqualToString:@"<<"]) return NSSelectorFromString(@"<<:");
    if([mstring isEqualToString:@">>"]) return NSSelectorFromString(@">>:");
    if([mstring isEqualToString:@"+@"]) return NSSelectorFromString(@"+@");
    if([mstring isEqualToString:@"-@"]) return NSSelectorFromString(@"-@");
    if([mstring isEqualToString:@"[]"]) return NSSelectorFromString(@"[]:");
    if([mstring isEqualToString:@"[]="]) return NSSelectorFromString(@"[]=:");
    int j = 0;
    BOOL foundFuncArg = NO;
    for (NSUInteger i = 0; i < self.arguments.count; i++) {
        SVFunctionArgument * argInfo = [self.arguments objectAtIndex:i];
        if (argInfo.isFunction) {
            foundFuncArg = YES;
        }
        NSString * aname = argInfo.selName ? argInfo.selName : argInfo.name;
        if ([aname isEqualToString:@"self"]) {
            continue;
        }
        if (j == 0) {
            [mstring appendString:@":"];
            j++;
        } else if(aname) {
            [mstring appendFormat:@"%@:",aname];
        }
    }
    __block BOOL (^checkForYieldStatements)(SVNode *) = nil;
    checkForYieldStatements = ^BOOL (SVNode * node) {
        BOOL found = NO;
        unsigned int ivarCount;
        if (!strcmp (@encode (typeof (node)), @encode (typeof (id)))) {
            __strong Ivar * ivars = (__strong Ivar *)class_copyIvarList ([node class], &ivarCount);
            for (int i = 0; i < ivarCount; i++) {
                id n = object_getIvar (node, ivars[i]);
                if (!strcmp (ivar_getTypeEncoding (ivars[i]), @encode (id)) && [n isKindOfClass:[SVYieldStatement class]])
                    return YES;
            }
        }
        if ([node isKindOfClass:[SVBlock class]]) {
            for (SVNode * child in [(SVBlock *)node statements]) {
                found = checkForYieldStatements (child);
                if (found)
                    break;
            }
        } else if ([node isKindOfClass:[SVYieldStatement class]]) {
            found = YES;
        } else if ([node isKindOfClass:[SVParallelAssignment class]]) {
            for(id obj in [(SVParallelAssignment*)node rvalues]) {
                if([obj isKindOfClass:[SVYieldStatement class]]) {
                    found = YES;
                    break;
                }
            }
        }
        return found;
    };
    BOOL yield = self.isCall ? self.yieldFunc != nil : checkForYieldStatements (self);
    if (yield) {
        if (j == 0) {
            [mstring appendString:@":"];
            j++;
        } else {
            [mstring appendString:@"yield:"];
        }
    }

    return NSSelectorFromString ([mstring description]);
}

- (SEL) generateSelectorNameNoYield
{
    NSMutableString * mstring = [NSMutableString string];
    [mstring appendString:self.name];
    if([mstring isEqualToString:@".."]) return NSSelectorFromString(@"..:");
    if([mstring isEqualToString:@"..."]) return NSSelectorFromString(@"...:");
    if([mstring isEqualToString:@"|"]) return NSSelectorFromString(@"|:");
    if([mstring isEqualToString:@"^"]) return NSSelectorFromString(@"^:");
    if([mstring isEqualToString:@"&"]) return NSSelectorFromString(@"&:");
    if([mstring isEqualToString:@"<=>"]) return NSSelectorFromString(@"<=>:");
    if([mstring isEqualToString:@"=="]) return NSSelectorFromString(@"==:");
    if([mstring isEqualToString:@"==="]) return NSSelectorFromString(@"===:");
    if([mstring isEqualToString:@"=~"]) return NSSelectorFromString(@"=~:");
    if([mstring isEqualToString:@"<"]) return NSSelectorFromString(@"<:");
    if([mstring isEqualToString:@"<="]) return NSSelectorFromString(@"<=:");
    if([mstring isEqualToString:@">"]) return NSSelectorFromString(@">:");
    if([mstring isEqualToString:@">="]) return NSSelectorFromString(@">=:");
    if([mstring isEqualToString:@"+"]) return NSSelectorFromString(@"+:");
    if([mstring isEqualToString:@"-"]) return NSSelectorFromString(@"-:");
    if([mstring isEqualToString:@"*"]) return NSSelectorFromString(@"*:");
    if([mstring isEqualToString:@"/"]) return NSSelectorFromString(@"/:");
    if([mstring isEqualToString:@"%"]) return NSSelectorFromString(@"%:");
    if([mstring isEqualToString:@"**"]) return NSSelectorFromString(@"**:");
    if([mstring isEqualToString:@"<<"]) return NSSelectorFromString(@"<<:");
    if([mstring isEqualToString:@">>"]) return NSSelectorFromString(@">>:");
    if([mstring isEqualToString:@"+@"]) return NSSelectorFromString(@"+@");
    if([mstring isEqualToString:@"-@"]) return NSSelectorFromString(@"-@");
    if([mstring isEqualToString:@"[]"]) return NSSelectorFromString(@"[]:");
    if([mstring isEqualToString:@"[]="]) return NSSelectorFromString(@"[]=:");
    int j = 0;
    BOOL foundFuncArg = NO;
    for (NSUInteger i = 0; i < self.arguments.count; i++) {
        SVFunctionArgument * argInfo = [self.arguments objectAtIndex:i];
        if (argInfo.isFunction) {
            foundFuncArg = YES;
        }
        NSString * aname = argInfo.selName ? argInfo.selName : argInfo.name;
        if ([aname isEqualToString:@"self"]) {
            continue;
        }
        if (j == 0) {
            [mstring appendString:@":"];
            j++;
        } else if(aname) {
            [mstring appendFormat:@"%@:",aname];
        }
    }
    
    return NSSelectorFromString ([mstring description]);
}

@end

@interface SVClass ()

@property (retain) NSMutableArray * contents;

@end

static NSMutableDictionary * __XDV_Holder__;
static NSMutableDictionary * __XSV_Holder__;

@implementation NSObject (SVDynIvarExtension)

- (NSMutableDictionary *) svIvars
{
    if (!__XDV_Holder__) {
        __XDV_Holder__ = [NSMutableDictionary dictionary];
    }
    if(!CFDictionaryGetValue((CFDictionaryRef)__XDV_Holder__, self)) {
        CFDictionarySetValue((CFMutableDictionaryRef)__XDV_Holder__, self, [NSMutableDictionary dictionary]);
    }
    return CFDictionaryGetValue((CFDictionaryRef)__XDV_Holder__,self);
}

- (NSMutableDictionary *) svSingletonMethods {
    if (!__XSV_Holder__) {
        __XSV_Holder__ = [NSMutableDictionary dictionary];
    }
    if(!CFDictionaryGetValue((CFDictionaryRef)__XSV_Holder__, self)) {
        CFDictionarySetValue((CFMutableDictionaryRef)__XSV_Holder__, self, [NSMutableDictionary dictionary]);
    }
    return CFDictionaryGetValue((CFDictionaryRef)__XSV_Holder__,self);
}

@end

@implementation SVClass

NSString * __sv_getMethodName(id self, SEL _cmd)
{
    return NSStringFromSelector(_cmd);
}


SVFunction * __sv_lookupMethod(id self, NSString * methodName)
{
    static NSString * oldPClass, * oldSClass;
    if([methodName isEqualToString:@".."]) methodName = @"..:";
    if([methodName isEqualToString:@"..."]) methodName = @"...:";
    if([methodName isEqualToString:@"|"]) methodName = @"|:";
    if([methodName isEqualToString:@"^"]) methodName = @"^:";
    if([methodName isEqualToString:@"&"]) methodName = @"&:";
    if([methodName isEqualToString:@"<=>"]) methodName = @"<=>:";
    if([methodName isEqualToString:@"=="]) methodName = @"==:";
    if([methodName isEqualToString:@"==="]) methodName = @"===:";
    if([methodName isEqualToString:@"=~"]) methodName = @"=~:";
    if([methodName isEqualToString:@"<"]) methodName = @"<:";
    if([methodName isEqualToString:@"<="]) methodName = @"<=:";
    if([methodName isEqualToString:@">"]) methodName = @">:";
    if([methodName isEqualToString:@">="]) methodName = @">=:";
    if([methodName isEqualToString:@"+"]) methodName = @"+:";
    if([methodName isEqualToString:@"-"]) methodName = @"-:";
    if([methodName isEqualToString:@"*"]) methodName = @"*:";
    if([methodName isEqualToString:@"/"]) methodName = @"/:";
    if([methodName isEqualToString:@"%"]) methodName = @"%:";
    if([methodName isEqualToString:@"**"]) methodName = @"**:";
    if([methodName isEqualToString:@"<<"]) methodName = @"<<:";
    if([methodName isEqualToString:@">>"]) methodName = @">>:";
    if([methodName isEqualToString:@"+@"]) methodName = @"+@";
    if([methodName isEqualToString:@"-@"]) methodName = @"-@";
    if([methodName isEqualToString:@"[]"]) methodName = @"[]:";
    if([methodName isEqualToString:@"[]="]) methodName = @"[]=::";
    NSString * objectClass = NormalizedClassNameFor([self class]);

    SVClass * klass = [[[SVSymbolTable sharedTable] symbolWithName:[NSString stringWithFormat:@"%@", objectClass]] value];
    if (!klass) {
        if (!klass) {
            NSString * parentClass = NormalizedClassNameFor(class_getSuperclass([self class]));
            do {
                klass = [[[SVSymbolTable sharedTable] symbolWithName:[NSString stringWithFormat:@"%@", parentClass]] value];
                parentClass = NormalizedClassNameFor(class_getSuperclass(NSClassFromString(parentClass)));
            } while (!klass && parentClass);
        }
        if (!klass) {
            return nil;
        }
    }
    if ([sv_remove_table objectForKey:[NSString stringWithFormat:@"%@%@", objectClass, methodName]]) {
        return nil;
    } else if([sv_undef_table objectForKey:[NSString stringWithFormat:@"%@%@", objectClass, methodName]]) {
        Class parentClass = class_getSuperclass([self class]);
        NSString * pclass = NormalizedClassNameFor(parentClass);
        if([oldPClass isEqualToString:pclass])
            parentClass = [NSObject class];
        oldPClass = pclass;
        NSString * sclass = NormalizedClassNameFor([self class]);
        if([oldSClass isEqualToString:sclass])
            parentClass = [NSObject class];
        oldSClass = sclass;
        return __sv_lookupMethod([parentClass alloc], methodName);
    } else if ([sv_block_table objectForKey:[NSString stringWithFormat:@"%@%@", objectClass, methodName]]) {
        return [sv_block_table objectForKey:[NSString stringWithFormat:@"%@%@", objectClass, methodName]];
    } else if ([klass respondsToSelector:@selector(parentName)] && klass.parentName) {
        Class parentClass = NSClassFromString(klass.parentName);
        if (parentClass) {
            return __sv_lookupMethod([[parentClass alloc] init], methodName);
        }
    } else if(class_getSuperclass([self class]) != [self class]) {
        Class parentClass = class_getSuperclass([self class]);
        NSString * pclass = NormalizedClassNameFor(parentClass);
        if([oldPClass isEqualToString:pclass])
            parentClass = [NSObject class];
        oldPClass = pclass;
        NSString * sclass = NormalizedClassNameFor([self class]);
        if([oldSClass isEqualToString:sclass])
            parentClass = [NSObject class];
        oldSClass = sclass;
        return __sv_lookupMethod([parentClass alloc], methodName);
    }

    return nil;
}


NSMutableDictionary * __sv_createFunctionCall(SVFunction * func)
{
    NSMutableDictionary * c = [NSMutableDictionary dictionary];

    [c setObject:[SVSymbolTable table] forKey:SV_SYMBOL_TABLE_KEY];
    SVSymbol * sym = [[c symbolTable] symbolWithName:@"__SV_CLASS_FUNCTION_NAME"];
    sym.value = func;
    return c;
}


void __sv_registerSuper(id self, NSMutableDictionary * context)
{
    SVSymbol * sym = [[context symbolTable] symbolWithName:@"super"];
    sym.value = self;
}


id __sv_stubPropertyGetter (id self, SEL _cmd)
{
    NSString * ivarName = NSStringFromSelector(_cmd);

    void * outValue;
    if (!object_getInstanceVariable(self, [ivarName UTF8String], &outValue)) {
        return [[self svIvars] objectForKey:ivarName];
    }
    return (id)outValue;
}


void __sv_stubPropertySetter(id self, SEL _cmd, id value)
{
    NSString * ivarName =
        [[NSStringFromSelector (_cmd) substringWithRange:NSMakeRange(3, [NSStringFromSelector (_cmd) length] - 4)] lowercaseString];

    if (!object_setInstanceVariable(self, [ivarName UTF8String], (void *)value)) {
        [[self svIvars] setObject:value forKey:ivarName];
        if (!class_getInstanceMethod([self class], NSSelectorFromString(ivarName))) {
            class_addMethod([self class], NSSelectorFromString(ivarName), (IMP)__sv_stubPropertyGetter, "@@:");
            class_addMethod([self class], NSSelectorFromString([NSString stringWithFormat:@"set%@:",
                                                                 [ivarName capitalizedString]]), (IMP)__sv_stubPropertySetter, "v@:@");
        }
    }
}


id __sv_noArgumentStub(id self, SEL _cmd)
{
    NSString * selName = __sv_getMethodName(self, _cmd);

    SVFunction * func = __sv_lookupMethod(self, selName);
    if(!func)
        return nil;
    NSMutableDictionary * context = __sv_createFunctionCall(func);
    __sv_registerSuper(self, context);
    SVFunction * funccall =
        [SVFunction functionCallWithName:@"__SV_CLASS_FUNCTION_NAME" arguments:[NSArray arrayWithObjects:[SVFunctionArgument
                                                                                                          argumentWithName:
                                                                                                          @"self" value:self], nil]];

    return [funccall evaluateWithContext:context];
}


id __sv_oneArgumentStub(id self, SEL _cmd, id arg0)
{
    NSString * selName = __sv_getMethodName(self, _cmd);

    SVFunction * func = __sv_lookupMethod(self, selName);
    if(!func)
        return nil;
    NSMutableDictionary * context = __sv_createFunctionCall(func);
    __sv_registerSuper(self, context);
    SVFunction * funccall =
        [SVFunction functionCallWithName:@"__SV_CLASS_FUNCTION_NAME" arguments:[NSArray arrayWithObjects:[SVFunctionArgument
                                                                                                          argumentWithName:
                                                                                                          @"self" value:self],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg0], nil]];

    return [funccall evaluateWithContext:context];
}


id __sv_twoArgumentStub(id self, SEL _cmd, id arg0, id arg1)
{
    NSString * selName = __sv_getMethodName(self, _cmd);

    SVFunction * func = __sv_lookupMethod(self, selName);
    if(!func)
        return nil;
    NSMutableDictionary * context = __sv_createFunctionCall(func);
    __sv_registerSuper(self, context);
    SVFunction * funccall =
        [SVFunction functionCallWithName:@"__SV_CLASS_FUNCTION_NAME" arguments:[NSArray arrayWithObjects:[SVFunctionArgument
                                                                                                          argumentWithName:
                                                                                                          @"self" value:self],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg0],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg1], nil]];

    return [funccall evaluateWithContext:context];
}


id __sv_threeArgumentStub(id self, SEL _cmd, id arg0, id arg1, id arg2)
{
    NSString * selName = __sv_getMethodName(self, _cmd);

    SVFunction * func = __sv_lookupMethod(self, selName);
    if(!func)
        return nil;
    NSMutableDictionary * context = __sv_createFunctionCall(func);
    __sv_registerSuper(self, context);
    SVFunction * funccall =
        [SVFunction functionCallWithName:@"__SV_CLASS_FUNCTION_NAME" arguments:[NSArray arrayWithObjects:[SVFunctionArgument
                                                                                                          argumentWithName:
                                                                                                          @"self" value:self],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg0],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg1],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg2], nil]];

    return [funccall evaluateWithContext:context];
}


id __sv_fourArgumentStub(id self, SEL _cmd, id arg0, id arg1, id arg2, id arg3)
{
    NSString * selName = __sv_getMethodName(self, _cmd);

    SVFunction * func = __sv_lookupMethod(self, selName);
    if(!func)
        return nil;
    NSMutableDictionary * context = __sv_createFunctionCall(func);
    __sv_registerSuper(self, context);
    SVFunction * funccall =
        [SVFunction functionCallWithName:@"__SV_CLASS_FUNCTION_NAME" arguments:[NSArray arrayWithObjects:[SVFunctionArgument
                                                                                                          argumentWithName:
                                                                                                          @"self" value:self],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg0],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg1],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg2],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg3], nil]];

    return [funccall evaluateWithContext:context];
}


id __sv_fiveArgumentStub(id self, SEL _cmd, id arg0, id arg1, id arg2, id arg3, id arg4)
{
    NSString * selName = __sv_getMethodName(self, _cmd);

    SVFunction * func = __sv_lookupMethod(self, selName);
    if(!func)
        return nil;
    NSMutableDictionary * context = __sv_createFunctionCall(func);
    __sv_registerSuper(self, context);
    SVFunction * funccall =
        [SVFunction functionCallWithName:@"__SV_CLASS_FUNCTION_NAME" arguments:[NSArray arrayWithObjects:[SVFunctionArgument
                                                                                                          argumentWithName:
                                                                                                          @"self" value:self],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg0],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg1],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg2],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg3],
                                                                                [SVFunctionArgument argumentWithName:nil value:arg4], nil]];

    return [funccall evaluateWithContext:context];
}

IMP __sv_imps[] =
{ (IMP)__sv_noArgumentStub, (IMP)__sv_oneArgumentStub, (IMP)__sv_twoArgumentStub, (IMP)__sv_threeArgumentStub, (IMP)__sv_fourArgumentStub,
  (IMP)__sv_fiveArgumentStub };
char * __sv_encodings[] = { "@@:", "@@:@", "@@:@@", "@@:@@@", "@@:@@@@", "@@:@@@@@" };

+ (void) load
{
    if (!sv_block_table) {
        sv_block_table = [NSMutableDictionary dictionary];
        sv_undef_table = [NSMutableDictionary dictionary];
        sv_remove_table = [NSMutableDictionary dictionary];
        SVSymbol* usym = [[SVSymbolTable sharedTable] symbolWithName:@"sv_undef_table"];
        usym.value = sv_undef_table;
        SVSymbol* rsym = [[SVSymbolTable sharedTable] symbolWithName:@"sv_remove_table"];
        rsym.value = sv_remove_table;
    }
    
}


+ (SVClass *) classWithName:(NSString *)n parent:(NSString *)par protocols:(NSMutableArray *)p contents:(NSMutableArray *)contents
{
    return [[self alloc] initWithName:n parent:par protocols:p contents:contents];
}


- (id) initWithName:(NSString *)n parent:(NSString *)par protocols:(NSMutableArray *)p contents:(NSMutableArray *)_contents
{
    if ((self = [super init])) {
        name_ = n;
        parentName_ = par;
        protocols_ = p;
        contents_ = _contents;
    }
    return self;
}

+ (id) evaluate:(id)cl withObject:(id)obj withContext:(NSMutableDictionary*) context {
    // instead of isMemberOfClass:, which may be blocked by an NSProtocolChecker
    Class klass = object_getClass(cl);
    // we're going to send the message to the handler of its superclass instead of one defined for its class.
    if ((cl->isa == [SVClassWrapper class]) || (cl->isa == [SVClass class])) {
        klass = (cl->isa == [SVClassWrapper class]) ?[(SVClassWrapper *) cl wrappedClass] : NSClassFromString([(SVClass *) cl name]);
    }
    NSString * name = NormalizedClassNameFor(klass);
    NSMutableArray* contents = [NSMutableArray arrayWithObject:obj];
    SVCategory * cat = [SVCategory categoryForClass:name contents:contents];
    return [cat evaluateWithContext:context];
}

- (id) evaluateWithContext:(NSMutableDictionary *)context
{
    NSString * name = self.name;
    if(![name isKindOfClass:[NSString class]]) {
        name = [name evaluateWithContext:context];
        if(!name)
            return nil;
       
        name = NormalizedClassNameFor([name class]);
    }
    if (NSClassFromString(name) && ![context objectForKey:name]) {
        SVCategory * cat = [SVCategory categoryForClass:name contents:self.contents];
        return [cat evaluateWithContext:context];
    }

    if (self.parentName) {
        if (!NSClassFromString(self.parentName)) {
            @throw([NSException exceptionWithName:@"SVUnknownClassException" reason:[NSString stringWithFormat:
                                                                                     @"Parent class %@ does not exist",
                                                                                     self.parentName] userInfo:nil]);
        }
    }

    Class _svClass =
        objc_allocateClassPair(self.parentName != nil ? NSClassFromString(self.parentName) :[NSObject class], [name UTF8String], 0);

    if (_svClass == Nil) {
        return BL(NO);
    }

    for (NSString * protocol in self.protocols) {
        if (!objc_getProtocol([protocol UTF8String])) {
            @throw([NSException exceptionWithName:@"SVUnknownProtocolException" reason:[NSString stringWithFormat:@"Unknown protocol %@",
                                                                                        protocol] userInfo:nil]);
        }

        class_addProtocol(_svClass, objc_getProtocol([protocol UTF8String]));
    }

    objc_registerClassPair(_svClass);

    id result = nil;
    [context setObject:BL(YES) forKey:name];
    [context createSymbolTable];
    SVSymbolTable * table = [context symbolTable];
    SVSymbol * _self = [table symbolWithName:@"self"];
    _self.value = _svClass;
    SVSymbol * _super = [table symbolWithName:@"super" isConst:YES];
    _super.value = class_getSuperclass(_svClass);
    [context setObject:name forKey:@"__SV_CLASS_DEF"];
    
    for (id content in self.contents) {
        if([content isKindOfClass:[SVClass class]]) {
            [(SVClass*)content setName:[NSString stringWithFormat:@"%@#%@",name,[content name]]];
            [content evaluateWithContext:context];
        } else if([content isKindOfClass:[SVAliasStatement class]]) {
            SEL from = NSSelectorFromString([content fromIdentifier]);
            SVFunction * fromFunc = __sv_lookupMethod(_svClass, NSStringFromSelector(from));
            if(fromFunc) {
                SEL to = NSSelectorFromString([content toIdentifier]);
                NSString * selName = NSStringFromSelector(to);
                NSInteger argCount = [[selName componentsSeparatedByString:@":"] count] - 1;
                class_addMethod(_svClass, to, __sv_imps[argCount], __sv_encodings[argCount]);
                [sv_block_table setObject:fromFunc forKey:[NSString stringWithFormat:@"%@%@",name,selName]];
            } else {
                OCLog(@"silver",warning,@"Failed to add alias for %@ (no method found)",NSStringFromSelector(from));
            }
        } else if ([content isKindOfClass:[SVIvar class]]) {
            NSString * ivarName = [content name];
            if (!class_addMethod(_svClass, NSSelectorFromString(ivarName), (IMP)__sv_stubPropertyGetter, "@@:")) {
                return BL(NO);
            }

            if (!class_addMethod(_svClass,
                                 NSSelectorFromString([NSString stringWithFormat:@"set%@:",
                                                       [ivarName capitalizedString]]), (IMP)__sv_stubPropertySetter, "v@:@")) {
                return BL(NO);
            }
        } else if([content isKindOfClass:[SVClassFunction class]] && [[content singleton] isKindOfClass:[SVVariable class]] && [V_([content singleton]) isEqual:name]) {
            Class _svMetaClass = object_getClass(_svClass);
            [content setLcontext:context];
            [(NSMutableArray *)[content arguments] insertObject:[SVFunctionArgument argumentWithName:@"self"] atIndex:0];
            NSString * selName = NSStringFromSelector([content generateSelectorName]);
            NSInteger argCount = [[selName componentsSeparatedByString:@":"] count] - 1;
            class_addMethod(_svMetaClass, [content generateSelectorName], __sv_imps[argCount], __sv_encodings[argCount]);
            [sv_block_table setObject:content forKey:[NSString stringWithFormat:@"%@%@", name, selName]];
            if([sv_undef_table objectForKey:[NSString stringWithFormat:@"%@%@", name, selName]])
                [sv_undef_table removeObjectForKey:[NSString stringWithFormat:@"%@%@", name, selName]];
            if([sv_remove_table objectForKey:[NSString stringWithFormat:@"%@%@", name, selName]])
                [sv_remove_table removeObjectForKey:[NSString stringWithFormat:@"%@%@", name, selName]];
        } else if ([content isKindOfClass:[SVFunction class]] && ![content isCall]) {
            [content setLcontext:context];
            [(NSMutableArray *)[content arguments] insertObject:[SVFunctionArgument argumentWithName:@"self"] atIndex:0];
            NSString * selName = NSStringFromSelector([content generateSelectorName]);
            NSInteger argCount = [[selName componentsSeparatedByString:@":"] count] - 1;
            class_addMethod(_svClass, [content generateSelectorName], __sv_imps[argCount], __sv_encodings[argCount]);
            [sv_block_table setObject:content forKey:[NSString stringWithFormat:@"%@%@", name, selName]];
            if([sv_undef_table objectForKey:[NSString stringWithFormat:@"%@%@", name, selName]])
                [sv_undef_table removeObjectForKey:[NSString stringWithFormat:@"%@%@", name, selName]];
            if([sv_remove_table objectForKey:[NSString stringWithFormat:@"%@%@", name, selName]])
                [sv_remove_table removeObjectForKey:[NSString stringWithFormat:@"%@%@", name, selName]];        
        } else {
            result = [content evaluateWithContext:context];
        }
    }
    [context removeObjectForKey:name];
    [context removeObjectForKey:@"__SV_CLASS_DEF"];
    SVSymbol * sym = [[SVSymbolTable sharedTable] symbolWithName:[NSString stringWithFormat:@"%@", name]];
    sym.value = self;

    return result ? result : _svClass;
}


- (BOOL) isEqual:(SVNode *)object
{
    if (object == self) {
        return YES;
    }
    if (![object isKindOfClass:[SVNode class]]) {
        return NO;
    }
    return YES;
}


- (NSComparisonResult) compare:(SVNode *)object
{
    return ![self isEqual:object];
}


- (id) copyWithZone:(NSZone *)zone
{
    return [[SVNode alloc] init];
}


static NSString * parentProtocolString(SVClass * klass)
{
    NSMutableString * string = [NSMutableString string];
    if (klass.parentName) {
        [string appendFormat:@" : %@", klass.parentName];
    }
    if (klass.protocols && klass.protocols.count) {
        [string appendString:@" <"];
        for (NSString * protocol in klass.protocols)
            [string appendFormat:@"%@,", protocol];
        [string replaceCharactersInRange:NSMakeRange(string.length - 1, 1) withString:@""];
        [string appendString:@"> "];
    }
    return string;
}


- (NSString *) stringValueWithDepth:(NSInteger)d
{
    NSMutableString * string = [NSMutableString stringWithFormat:@"%@%@ %@{\n\r", generateDepth(d), self.name, parentProtocolString(self)];
    [string appendFormat:@"%@};\n\r", generateDepth(d)];
    return string;
}


- (NSString *) description
{
    return self.name;
}


@synthesize protocols = protocols_, name = name_, parentName = parentName_, contents = contents_;
@end