forked from pmougin/F-Script
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathFSCompiler.m
1809 lines (1522 loc) · 63.6 KB
/
FSCompiler.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
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* FSCompiler.m Copyright (c) 1998-2009 Philippe Mougin. */
/* This software is open source. See the license. */
#import "FSCompiler.h"
#import "FSNumber.h"
#import "FSBoolean.h"
#import "FSCompilationResult.h"
#import "FSArray.h"
#import "FSBlock.h"
#import "MessagePatternCodeNode.h"
#import <Cocoa/Cocoa.h>
#import "FSSymbolTable.h"
#import <objc/objc.h> // sel_getName()
#import <objc/runtime.h>
#import "FSConstantsInitialization.h"
#import "FSMethod.h"
#import "FSCNClassDefinition.h"
#import "FSCNCategory.h"
#import "FSCNIdentifier.h"
#import "FSCNSuper.h"
#import "FSPattern.h"
#import "FSCNUnaryMessage.h"
#import "FSCNBinaryMessage.h"
#import "FSCNKeywordMessage.h"
#import "FSCNCascade.h"
#import "FSCNStatementList.h"
#import "FSCNPrecomputedObject.h"
#import "FSCNArray.h"
#import "FSCNBlock.h"
#import "FSCNAssignment.h"
#import "FSCNMethod.h"
#import "FSCNReturn.h"
#import "BlockRep.h"
#import "FSMiscTools.h"
#import "FSVoid.h"
#import "FSCNDictionary.h"
#define isnonascii(c) ((((unsigned int)(c)) & 0x80) != 0)
enum e_type_compilation {TC_STATEMENT_LIST, TC_BLOCK /*, TC_METHOD*/};
static NSString * symbol_operator_tab[256];
static NSMutableDictionary * symbol_operator_dict;
static NSMutableDictionary *constant_dict;
static char * keywords[] = {"false", "true", "NO", "YES", "nil", "super"};
static enum e_token_type keyword_type[] = {KW_FALSE, KW_TRUE, KW_FALSE, KW_TRUE, KW_NIL, KW_SUPER};
struct codeNodePatternElementPair
{
FSCNBase *codeNode;
id patternElement;
};
struct compilationContext
{
FSSymbolTable *symbolTable;
NSString *className;
BOOL isInClassMethod;
};
static BOOL isHexadecimalDigit(char digit)
{
switch (digit)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
return YES;
default:
return NO;
}
}
static struct codeNodePatternElementPair makeCodeNodePatternElementPair(FSCNBase *codeNode, id patternElement)
{
struct codeNodePatternElementPair r;
r.codeNode = codeNode;
r.patternElement = patternElement;
return r;
}
static NSMutableString *operator_name(NSString *op_elements) //ex: "++" -> "_plus_plus"
{
char i,nb;
NSMutableString *r = [NSMutableString stringWithCapacity:[op_elements length]*7];
const char *op_elements_cstr = [op_elements UTF8String];
for (i = 0, nb = [op_elements length]; i < nb; i++)
{
[r appendString:@"_"];
[r appendString:symbol_operator_tab[(unsigned char)op_elements_cstr[(short)i]]];
}
return r;
}
// returns nil if no mapping exists
static NSString *FSOperatorFromObjCOperatorName(NSString *operatorName) // ex: "operator_plus_plus:" --> "++"
{
NSScanner *scanner = [NSScanner scannerWithString:operatorName];
NSString *subObjCOperatorName, *subFSOperator;
NSMutableString *r = [NSMutableString stringWithCapacity:1];
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@"_:"];
/* first we test that the selector is in a form acceptable for an F-Script operator */
[scanner setCaseSensitive:YES];
if (![operatorName hasPrefix:@"operator_"]) return nil;
[scanner scanUpToString:@":" intoString:NULL];
if (![scanner scanString:@":" intoString:NULL]) return nil;
if ([scanner isAtEnd] == NO) return nil;
/* Now, we try to construct the name of the F-Script operator from the Objective-C selector string */
[scanner setScanLocation:0];
[scanner scanString:@"operator" intoString:NULL];
while ([scanner scanString:@"_" intoString:NULL])
{
[scanner scanUpToCharactersFromSet:charSet intoString:&subObjCOperatorName];
if (!(subFSOperator = [symbol_operator_dict objectForKey:subObjCOperatorName])) return nil;
[r appendString:subFSOperator];
}
return r;
}
@interface FSCompiler(InternalMethodsFSCompiler)
- (FSCNBase *) statementListWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNBase *) statementWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNReturn *) returnStatementWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNBase *) expWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNKeywordMessage *) keywordSelWithCompilationContext:(struct compilationContext)compilationContext receiver:(FSCNBase *)receiver patternElement:(id)pattern_elt;
- (struct codeNodePatternElementPair) exp1WithCompilationContext:(struct compilationContext)compilationContext;
- (struct codeNodePatternElementPair) exp1RemainingWithCompilationContext:(struct compilationContext)compilationContext left:(FSCNBase *)left patternElement:(id)pattern_elt;
- (struct codeNodePatternElementPair) exp2WithCompilationContext:(struct compilationContext)compilationContext;
- (struct codeNodePatternElementPair) exp2RemainingWithCompilationContext:(struct compilationContext)compilationContext left:(FSCNBase *)left patternElement:(id)pattern_elt;
- (FSCNBase *) exp3WithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNPrecomputedObject *) number;
- (FSCNIdentifier *) identifierWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNArray *) arrayWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNBlock *) blockWithCompilationContext:(struct compilationContext)compilationContext parentSymbolTable:(FSSymbolTable *)symbTab;
- (FSCNDictionary *) dictionaryWithCompilationContext:(struct compilationContext)compilationContext;
- (id) patternElt;
- (FSCNMethod *)methodWithCompilationContext:(struct compilationContext)compilationContext;
- (NSString *)typeWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNBase *)methodBodyWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNClassDefinition *)classDefinitionWithCompilationContext:(struct compilationContext)compilationContext;
- (FSCNCategory *)categoryWithCompilationContext:(struct compilationContext)compilationContext;
@end
@implementation FSCompiler
+ (id)compiler
{
return [[[self alloc] init] autorelease];
}
// This method returns an FSCNMethod equivalent to: - (void)dealloc { super dealloc }
+ (FSMethod *)dummyDeallocMethodForClassNamed:(NSString *)className
{
FSSymbolTable *symbolTable = [FSSymbolTable symbolTable];
FSCNSuper *receiver = [[[FSCNSuper alloc] initWithLocationInContext:[symbolTable insertSymbol:@"self" object:nil status:UNDEFINED] className:className isInClassMethod:NO] autorelease];
FSCNMessage *code = [[[FSCNUnaryMessage alloc] initWithReceiver:receiver selectorString:@"dealloc" pattern:nil] autorelease];
FSMethod *method = [[[FSMethod alloc] initWithSelector:@selector(dealloc) fsEncodedTypes:@"v@:" types:@"v@:" typesByArgument:[NSArray arrayWithObjects:@"@", @":", nil] argumentCount:2 code:code symbolTable:symbolTable] autorelease];
return method;
}
+ (BOOL)isValidIdentifier:(NSString *)str
{
const char *cstr = [str UTF8String];
if (*cstr == '\0') return NO; // because must be at least one character
if (isalpha(cstr[0]) || cstr[0] == '_')
{
cstr++;
while (*cstr != '\0' && (isalnum(*cstr) || *cstr == '_')) cstr++;
}
return *cstr == '\0';
}
+ (void)initialize
{
static BOOL tooLate = NO;
if (!tooLate)
{
tooLate = YES;
if ( self == [FSCompiler class] )
{
NSInteger i;
for(i = 0; i < 255; i++)
{
symbol_operator_tab[i] = nil;
}
symbol_operator_tab['+'] = @"plus";
symbol_operator_tab['-'] = @"hyphen";
symbol_operator_tab['<'] = @"less";
symbol_operator_tab['>'] = @"greater";
symbol_operator_tab['='] = @"equal";
symbol_operator_tab['*'] = @"asterisk";
symbol_operator_tab['/'] = @"slash";
symbol_operator_tab['?'] = @"question";
symbol_operator_tab['~'] = @"tilde";
symbol_operator_tab['!'] = @"exclam";
symbol_operator_tab['%'] = @"percent";
symbol_operator_tab['&'] = @"ampersand";
symbol_operator_tab['|'] = @"bar";
symbol_operator_tab['\\'] = @"backslash";
symbol_operator_dict = [[NSMutableDictionary alloc] init];
[symbol_operator_dict setObject:@"+" forKey:@"plus"];
[symbol_operator_dict setObject:@"-" forKey:@"hyphen"];
[symbol_operator_dict setObject:@"<" forKey:@"less"];
[symbol_operator_dict setObject:@">" forKey:@"greater"];
[symbol_operator_dict setObject:@"=" forKey:@"equal"];
[symbol_operator_dict setObject:@"*" forKey:@"asterisk"];
[symbol_operator_dict setObject:@"/" forKey:@"slash"];
[symbol_operator_dict setObject:@"?" forKey:@"question"];
[symbol_operator_dict setObject:@"~" forKey:@"tilde"];
[symbol_operator_dict setObject:@"!" forKey:@"exclam"];
[symbol_operator_dict setObject:@"%" forKey:@"percent"];
[symbol_operator_dict setObject:@"&" forKey:@"ampersand"];
[symbol_operator_dict setObject:@"|" forKey:@"bar"];
[symbol_operator_dict setObject:@"\\" forKey:@"backslash"];
constant_dict = [[NSMutableDictionary alloc] initWithCapacity:8500];
FSConstantsInitialization(constant_dict);
}
}
}
+ (NSString *)stringFromSelector:(SEL)selector
{
const char *rawCString = sel_getName(selector);
NSString *rawString;
NSString *r;
NSAssert(rawCString, @"sel_get_name() returned NULL !");
if (!rawCString) return @"FS_NULL_SELECTOR";
rawString = [NSString stringWithUTF8String:rawCString];
if ((strncmp(rawCString,"operator_", 9) == 0) && (r = FSOperatorFromObjCOperatorName(rawString)))
return r;
else
return rawString;
}
+ (SEL)selectorFromString:(NSString *)selectorStr
{
const char *cstr = [selectorStr UTF8String];
if (isalpha(cstr[0]) || (cstr[0] == '_'))
return sel_getUid(cstr);
else if ( strcmp(cstr,"<null selector>") == 0)
return (SEL)0;
else
return sel_getUid([[NSString stringWithFormat:@"operator%@:",operator_name(selectorStr)] UTF8String]);
}
- (id)init
{
// NSLog(@"FSCompiler init");
if ((self = [super init]))
{
return self;
}
return nil;
}
- (void)dealloc
{
// NSLog(@"FSCompiler dealloc");
[errorStr release];
[super dealloc];
}
- (void)syntaxError:(NSString *)c firstCharIndex:(NSInteger)firstCharIndex lastCharIndex:(NSInteger)lastCharIndex
{
[errorStr autorelease];
errorStr = [[@"syntax error: " stringByAppendingString:c] retain];
errorFirstCharIndex = firstCharIndex;
errorLastCharIndex = lastCharIndex;
longjmp(error_handler, 1);
}
- (void)syntaxError:(NSString *)c
{
[self syntaxError:c firstCharIndex:token_first_char_index lastCharIndex:string_index];
}
- (void)goToNextToken
{
while(isspace(string[string_index]) && string_index != string_size)
string_index++;
while(1)
{
if (isspace(string[string_index]))
string_index++;
else if (string[string_index]=='\"')
{
string_index++;
while (string[string_index] != '\"' && string_index != string_size)
string_index++;
if (string[string_index] == '\"')
string_index++;
}
else break;
}
}
- (void)scan
{
NSInteger j, k, firstDigitIndex;
char * buf;
[self goToNextToken];
token_first_char_index = string_index;
if (string_index == string_size)
{
rs.type = END;
return;
}
// Check for non-ASCII characters here, that would be an error
if (isnonascii(string[string_index])) [self syntaxError:@"Non ASCII character detected"];
if (isalpha(string[string_index]) || string[string_index] == '_')
{
j = string_index;
string_index++;
while( string_index < string_size && (isalnum(string[string_index]) || string[string_index] == '_') )
string_index++;
buf = malloc(string_index-j+1);
memcpy(buf,&(string[j]),string_index-j);
buf[string_index-j] = '\0';
for(k = 0; k < (NSInteger)(sizeof(keywords) / sizeof(char *)) && strcmp(buf, keywords[k]) != 0; k++);
if(k == sizeof(keywords)/sizeof(char *))/*This is not a keyword */
{
id predefinedObject;
rs.value = [NSMutableString stringWithUTF8String:buf];
free(buf);
// Is this a predefined constant ?
if ((predefinedObject = [constant_dict objectForKey:rs.value]) != nil)
{
// This is a predefined constant
rs.type = PREDEFINED_OBJECT;
rs.value = predefinedObject;
}
else // This is not a predefined constant
{
rs.type = NAME;
}
}
else /* This is a keyword */
{
rs.type = keyword_type[k];
free(buf);
}
return;
}
switch (string[string_index])
{
case '[' :rs.type = OPEN_BRACKET ; string_index++; return;
case ']' :rs.type = CLOSE_BRACKET ; string_index++; return;
case '(' :rs.type = OPEN_PARENTHESE ; string_index++; return;
case ')' :rs.type = CLOSE_PARENTHESE ; string_index++; return;
case '{' :rs.type = OPEN_BRACE ; string_index++; return;
case '}' :rs.type = CLOSE_BRACE ; string_index++; return;
case ',' :rs.type = COMMA ; string_index++; return;
case ';' :rs.type = SEMICOLON ; string_index++; return;
case '@' :rs.type = AT ; string_index++; return;
case '.' :rs.type = PERIOD ; string_index++; return;
case '^' :rs.type = CARET ; string_index++; return;
case '#' :
{
j = string_index;
string_index++;
if (string[string_index] == '{')
{
rs.type = DICTIONARY_BEGIN;
string_index++;
return;
}
else
{
if (symbol_operator_tab[(unsigned char)string[string_index]])
{
if (string[string_index] == '<' && strncmp(string+string_index, "<null selector>", 15) == 0)
string_index += 15;
else
while (symbol_operator_tab[(unsigned char)string[string_index]])
string_index++;
}
else if (isalpha(string[string_index]) || string[string_index] == '_')
{
string_index++;
//HH: changed ordering, might be incorrect !
while ( string_index < string_size && (isalnum(string[string_index]) || string[string_index] == '_' || string[string_index] == ':') )
string_index++;
}
else [self syntaxError:@"open brace or method selector expected"];
rs.type = COMPACT_BLOCK;
buf = malloc(1+string_index-j);
memcpy(buf,&(string[j]),string_index-j);
buf[string_index-j] = '\0';
rs.value = [NSMutableString stringWithUTF8String:buf];
free(buf);
return;
}
}
case ':' :
if (string[string_index+1] == '=')
{
rs.type = SASSIGNMENT ;
string_index += 2; return;
}
else
{
rs.type = COLON;
string_index ++ ; return;
}
case '\'':
string_index++;
j = string_index;
while(string_index < string_size)
{
if (string[string_index] == '\\')
string_index += 2;
else if (string[string_index] == '\'')
if (string[string_index+1] == '\'') string_index += 2;
else break;
else
string_index++;
}
if (string_index < string_size)
{
rs.type = SSTRING;
buf = malloc(string_index-j+1);
k = 0;
while(j < string_index)
{
if (string[j] == '\\')
{
j++;
switch (string[j])
{
case 'a' : buf[k] = '\a'; break;
case 'b' : buf[k] = '\b'; break;
case 'f' : buf[k] = '\f'; break;
case 'n' : buf[k] = '\n'; break;
case 'r' : buf[k] = '\r'; break;
case 't' : buf[k] = '\t'; break;
case 'v' : buf[k] = '\v'; break;
case '\\': buf[k] = '\\'; break;
case '\'': buf[k] = '\''; break;
default : buf[k] = '\\'; k++; buf[k] = string[j]; break;
}
}
else if (string[j] == '\'')
{
NSAssert(string[j+1] == '\'', @"");
buf[k] = string[j];
j++;
}
else
buf[k] = string[j];
j++; k++;
}
buf[k] = '\0';
rs.value = [NSMutableString stringWithUTF8String:buf];
free(buf);
string_index++;
return;
}
else
{
[self syntaxError:@"end of string (\') missing"];
}
} // end_switch
if (symbol_operator_tab[(unsigned char)string[string_index]])
{
char ch;
rs.value = [NSMutableString stringWithFormat:@"%c",string[string_index]];
string_index++;
ch = string[string_index];
while(symbol_operator_tab[(unsigned char)ch])
{
[rs.value appendFormat:@"%c",ch];
string_index++;
ch = string[string_index];
}
rs.type = OPERATOR;
}
else if (isdigit(string[string_index]))
{
NSInteger exponentLetterIndex = -1;
NSInteger hexadecimalRadixSpecifierIndex = -1;
firstDigitIndex = string_index;
string_index++;
while( string_index < string_size && (isdigit(string[string_index])) )
string_index++;
if (string_index < string_size)
{
if (string[string_index] == 'r')
{
if (string_index == firstDigitIndex+2 && string[firstDigitIndex] == '1' && string[firstDigitIndex+1] == '6')
{
hexadecimalRadixSpecifierIndex = firstDigitIndex;
string_index++;
if (string_index == string_size || !isHexadecimalDigit(string[string_index]))
[self syntaxError:@"invalid number literal"];
while( string_index < string_size && (isHexadecimalDigit(string[string_index])) )
string_index++;
}
}
else
{
if (string[string_index] == '.' && isdigit(string[string_index+1]))
{
string_index++;
while( string_index < string_size && (isdigit(string[string_index])) )
string_index++;
}
if (string_index < string_size && (string[string_index] == 'e'|| string[string_index] == 'd' || string[string_index] == 'q'))
{
exponentLetterIndex = string_index;
string_index++;
if (string_index == string_size || (!isdigit(string[string_index]) && string[string_index] != '+' && string[string_index] != '-'))
[self syntaxError:@"invalid number literal"];
if (string[string_index] == '+' || string[string_index] == '-')
string_index++;
if (string_index == string_size || !isdigit(string[string_index]))
[self syntaxError:@"invalid number literal"];
while( string_index < string_size && (isdigit(string[string_index])) )
string_index++;
}
}
}
rs.type = SNUMBER;
buf = malloc(string_index-firstDigitIndex+1);
memcpy(buf, &(string[firstDigitIndex]), string_index-firstDigitIndex);
buf[string_index-firstDigitIndex] = '\0';
// Translate into a format understood by the strtod() C function used latter to get a double from the string representation of the number
if (hexadecimalRadixSpecifierIndex != -1)
{
buf[hexadecimalRadixSpecifierIndex - firstDigitIndex] = '0';
buf[1 + hexadecimalRadixSpecifierIndex - firstDigitIndex] = 'x';
buf[2 + hexadecimalRadixSpecifierIndex - firstDigitIndex] = '0';
}
if (exponentLetterIndex != -1) buf[exponentLetterIndex - firstDigitIndex] = 'e';
rs.value = [NSMutableString stringWithUTF8String:buf];
free(buf);
}
else
{
[self syntaxError:[NSString stringWithFormat:@"unknown character '%c'", string[string_index]]];
}
}
- (void)checkLValue:(FSCNBase *)codeNode
{
switch (codeNode->nodeType)
{
case IDENTIFIER :
{
if ( [((FSCNIdentifier *)codeNode)->identifierString isEqualToString:@"sys"] )
{
[self syntaxError:@"assigment to \"sys\" is not permitted"];
}
break;
}
case ARRAY :
{
for (NSUInteger i = 0; i < ((FSCNArray *)codeNode)->count; i++)
{
[self checkLValue:((FSCNArray *)codeNode)->elements[i]];
}
break;
}
default :
{
[self syntaxError:@"the left hand side of an assignment must be an identifier or an array of identifiers"];
break;
}
}
}
- (void)checkToken:(enum e_token_type)type :(NSString *)str
{
if (rs.type != type)
[self syntaxError:str];
}
- (FSCompilationResult *) compileCode:(const char *)utf8str withParentSymbolTable:(FSSymbolTable *)symbol_table typeCompilation:(enum e_type_compilation)typeCompilation
{
NSInteger val;
FSCNBase *code;
struct compilationContext compilationContext = {symbol_table, nil, NO};
string = utf8str;
string_index = 0;
string_size = strlen(string);
if ((val = setjmp(error_handler)) == 0)
{
[self scan];
switch(typeCompilation)
{
case TC_STATEMENT_LIST: code = [self statementListWithCompilationContext:compilationContext];
break;
case TC_BLOCK: code = [self blockWithCompilationContext:compilationContext parentSymbolTable:symbol_table];
break;
/*case TC_METHOD: compilationContext = (struct compilationContext){nil};
code = [self methodWithCompilationContext:compilationContext];
break;*/
default: code = nil; assert(0); // Not supposed to happend. It's here to supress a compilation warning.
}
/* NO SYNTAX ERROR */
if (rs.type == END)
return [FSCompilationResult compilationResultWithType:OK errorMessage:nil errorFirstCharacterIndex:-1 errorLastCharacterIndex:-1 code:code];
else
{
errorStr = @"end of command expected";
errorFirstCharIndex = string_index-1;
errorLastCharIndex = string_index;
}
}
/* SYNTAX ERROR DETECTED */
return [FSCompilationResult compilationResultWithType:ERROR errorMessage:errorStr errorFirstCharacterIndex:errorFirstCharIndex errorLastCharacterIndex:errorLastCharIndex code:nil];
}
- (FSCompilationResult *) compileCode:(const char *)utf8str withParentSymbolTable:(FSSymbolTable *)symbol_table
{
return [self compileCode:utf8str withParentSymbolTable:symbol_table typeCompilation:TC_STATEMENT_LIST];
}
- (FSCompilationResult *) compileCodeForBlock:(const char *)utf8str withParentSymbolTable:(FSSymbolTable *)symbol_table
{
return [self compileCode:utf8str withParentSymbolTable:symbol_table typeCompilation:TC_BLOCK];
}
- (FSCNBase *) statementListWithCompilationContext:(struct compilationContext)compilationContext
{
NSMutableArray *statements = [NSMutableArray array];
do
{
[statements addObject:[self statementWithCompilationContext:compilationContext]];
if (rs.type == PERIOD) [self scan];
else break;
}
while (rs.type != CLOSE_BRACKET && rs.type != CLOSE_BRACE && rs.type != END);
if (rs.type == CLOSE_BRACE)
{
if ( ((FSCNBase *)[statements lastObject])->nodeType == RETURN )
{
// If the return statement is the last statement of the method, we compile it at a simple expression
// in order to optimize out the non-local return machinery which is unneeded in this case
// (it is also unneeded in other cases, but they are not as easy to detect)
[statements replaceObjectAtIndex:[statements count]-1 withObject:((FSCNReturn *)[statements lastObject])->expression];
}
else
{
[statements addObject: [[[FSCNPrecomputedObject alloc] initWithObject:[FSVoid fsVoid]] autorelease]];
}
}
if ([statements count] == 1)
return [statements objectAtIndex:0];
else
{
FSCNStatementList *result = [[[FSCNStatementList alloc] initWithStatements:statements] autorelease];
[result setFirstCharIndex:((FSCNBase *)[statements objectAtIndex:0])->firstCharIndex lastCharIndex:((FSCNBase *)[statements lastObject])->lastCharIndex];
return result;
}
}
- (FSCNBase *) statementWithCompilationContext:(struct compilationContext)compilationContext
{
if (rs.type == CARET)
return [self returnStatementWithCompilationContext:compilationContext];
else
return [self expWithCompilationContext:compilationContext];
}
- (FSCNReturn *) returnStatementWithCompilationContext:(struct compilationContext)compilationContext
{
int32_t firstCharIndex = token_first_char_index;
[self checkToken:CARET :@"\"^\" expected"];
[self scan];
FSCNBase *expression = [self expWithCompilationContext:compilationContext];
FSCNReturn *returnNode = [[[FSCNReturn alloc] initWithExpression:expression] autorelease];
[returnNode setFirstCharIndex:firstCharIndex lastCharIndex:expression->lastCharIndex];
return returnNode;
}
- (FSCNBase *) expWithCompilationContext:(struct compilationContext)compilationContext
{
struct codeNodePatternElementPair exp1_res;
FSCNBase *node;
BOOL messageToSuper = (rs.type == KW_SUPER);
exp1_res = [self exp1WithCompilationContext:compilationContext];
if (rs.type == NAME || rs.type == COLON)
{
node = [self keywordSelWithCompilationContext:compilationContext receiver:exp1_res.codeNode patternElement:exp1_res.patternElement] ;
}
else if (messageToSuper && exp1_res.codeNode->nodeType != UNARY_MESSAGE && exp1_res.codeNode->nodeType != BINARY_MESSAGE && exp1_res.codeNode->nodeType != KEYWORD_MESSAGE)
{
[self syntaxError:@"message expected"]; assert(0); return nil;
}
else if (rs.type == SASSIGNMENT)
{
int32_t firstCharIndex = token_first_char_index;
int32_t lastCharIndex = string_index;
[self checkLValue:exp1_res.codeNode];
[self scan];
FSCNBase *right = [self expWithCompilationContext:compilationContext];
FSCNAssignment *assignmentNode = [[[FSCNAssignment alloc] initWithLeft:exp1_res.codeNode right:right] autorelease];
[assignmentNode setFirstCharIndex:firstCharIndex lastCharIndex:lastCharIndex];
return assignmentNode;
}
else node = exp1_res.codeNode;
if (rs.type == SEMICOLON)
{
if (node->nodeType != UNARY_MESSAGE && node->nodeType != BINARY_MESSAGE && node->nodeType != KEYWORD_MESSAGE)
[self syntaxError:@"no cascade expected here"];
int32_t firstCharIndex = token_first_char_index;
NSMutableArray *messages = [NSMutableArray arrayWithObject:node];
FSCNBase *message;
do
{
NSArray *patternElement;
[self scan];
patternElement = [self patternElt];
switch (rs.type)
{
case NAME:
if (string[string_index] == ':') message = [self keywordSelWithCompilationContext:compilationContext receiver:nil patternElement:patternElement];
else
{
struct codeNodePatternElementPair unaryMsg = [self exp2RemainingWithCompilationContext:compilationContext left:nil patternElement:patternElement];
if (unaryMsg.patternElement != [NSNull null]) [self syntaxError:@"no pattern specification expected here"];
message = unaryMsg.codeNode;
}
break;
case OPERATOR:
{
struct codeNodePatternElementPair operatorMsg = [self exp1RemainingWithCompilationContext:compilationContext left:nil patternElement:patternElement];
if (operatorMsg.patternElement != [NSNull null]) [self syntaxError:@"no pattern specification expected here"];
message = operatorMsg.codeNode;
break;
}
default:
[self syntaxError:@"cascade expected"];
return nil; // to suppress a useless warning
}
[messages addObject:message];
} while (rs.type == SEMICOLON);
FSCNCascade *cascadeNode = [[[FSCNCascade alloc] initWithReceiver:((FSCNMessage *)node)->receiver messages:messages] autorelease];
[cascadeNode setFirstCharIndex:firstCharIndex lastCharIndex:message->lastCharIndex];
return cascadeNode;
}
else return node;
}
- (FSCNKeywordMessage *) keywordSelWithCompilationContext:(struct compilationContext)compilationContext receiver:(FSCNBase *)receiver patternElement:(id)pattern_elt // pattern_elt may be an NSArray or [NSNull null]
{
FSCNKeywordMessage *msg;
NSMutableString *selstr;
FSCNBase *argument = nil; // = nil to avoid the "may be used uninitialized" warning
NSMutableArray *patternElements = [NSMutableArray arrayWithObject:pattern_elt];
FSPattern *pattern;
int32_t firstCharIndex;
NSInteger i, pattern_count;
FSArray *args = (id)[FSArray array];
NSNull * nsnull;
firstCharIndex = token_first_char_index;
selstr = [NSMutableString stringWithCapacity:0];
if (rs.type == NAME)
{
[selstr appendString:rs.value];
[self scan];
[self checkToken:COLON :@"\":\" expected"];
}
while (rs.type == COLON)
{
[selstr appendString:@":"];
[self scan];
[patternElements addObject:[self patternElt]];
argument = [self exp1WithCompilationContext:compilationContext].codeNode;
[args addObject:argument];
if (rs.type == NAME)
{
[selstr appendString:rs.value];
[self scan];
[self checkToken:COLON :@"\":\" expected"];
}
}
for (i = 0, pattern_count = [patternElements count], nsnull = [NSNull null]; i < pattern_count; i++)
{
if ([patternElements objectAtIndex:i] != nsnull) break;
}
if (i == pattern_count)
pattern = nil;
else
pattern = [FSPattern patternFromIntermediateRepresentation:patternElements];
msg = [[[FSCNKeywordMessage alloc] initWithReceiver:receiver selectorString:selstr pattern:pattern arguments:args] autorelease];
[msg setFirstCharIndex:firstCharIndex lastCharIndex:argument->lastCharIndex];
return msg;
}
- (struct codeNodePatternElementPair) exp1WithCompilationContext:(struct compilationContext)compilationContext
{
struct codeNodePatternElementPair exp2_res = [self exp2WithCompilationContext:compilationContext];
if (rs.type == OPERATOR)
return [self exp1RemainingWithCompilationContext:compilationContext left:exp2_res.codeNode patternElement:exp2_res.patternElement];
else
return exp2_res;
}
- (struct codeNodePatternElementPair) exp1RemainingWithCompilationContext:(struct compilationContext)compilationContext left:(FSCNBase *)left patternElement:(id)pattern_elt // pattern_elt may be an NSArray or [NSNull null]
{
FSCNBinaryMessage *r;
FSPattern *pattern;
NSMutableString *selectorString;
id pattern_elt_next; // pattern_elt_next may be an NSArray or [NSNull null]
struct codeNodePatternElementPair exp2_res;
long firstCharIndex, lastCharIndex;
[self checkToken:OPERATOR :@"operator expected"];
firstCharIndex = token_first_char_index;
lastCharIndex = string_index;
selectorString = operator_name(rs.value);
[selectorString insertString:@"operator" atIndex:0];
[selectorString appendString:@":"];
[self scan];
pattern_elt_next = [self patternElt];
if (pattern_elt == [NSNull null] && pattern_elt_next == [NSNull null])
pattern = nil;
else
pattern = [FSPattern patternFromIntermediateRepresentation:[NSArray arrayWithObjects:pattern_elt, pattern_elt_next, nil]];
exp2_res = [self exp2WithCompilationContext:compilationContext];
r = [[[FSCNBinaryMessage alloc] initWithReceiver:left selectorString:selectorString pattern:pattern argument:exp2_res.codeNode] autorelease];
[r setFirstCharIndex:firstCharIndex lastCharIndex:lastCharIndex];
if (rs.type == OPERATOR) return [self exp1RemainingWithCompilationContext:compilationContext left:r patternElement:exp2_res.patternElement];
else return makeCodeNodePatternElementPair(r,exp2_res.patternElement);
}
- (struct codeNodePatternElementPair) exp2WithCompilationContext:(struct compilationContext)compilationContext
{
FSCNBase *exp3Node = [self exp3WithCompilationContext:compilationContext];
NSArray *pattern_elt = [self patternElt];
if (rs.type == NAME && string[string_index] != ':') return [self exp2RemainingWithCompilationContext:compilationContext left:exp3Node patternElement:pattern_elt];
else return makeCodeNodePatternElementPair(exp3Node, pattern_elt);
}
- (struct codeNodePatternElementPair) exp2RemainingWithCompilationContext:(struct compilationContext)compilationContext left:(FSCNBase *)left patternElement:(id)pattern_elt // pattern_elt may an NSArray or [NSNull null]
{
FSCNUnaryMessage *r;
FSPattern *pattern;
NSArray *pattern_elt_next;
[self checkToken:NAME :@"unary message expected"];
if (pattern_elt == [NSNull null]) pattern = nil;
else pattern = [FSPattern patternFromIntermediateRepresentation:[NSArray arrayWithObject:pattern_elt]];
r = [[[FSCNUnaryMessage alloc] initWithReceiver:left selectorString:rs.value pattern:pattern] autorelease];
[r setFirstCharIndex:token_first_char_index lastCharIndex:string_index];
[self scan];
pattern_elt_next = [self patternElt];
if (rs.type == NAME && string[string_index] != ':') return [self exp2RemainingWithCompilationContext:compilationContext left:r patternElement:pattern_elt_next];
else return makeCodeNodePatternElementPair(r, pattern_elt_next);
}
/*
- (CompiledCodeNode*)exp3
{
CompiledCodeNode *exp4Node = [self exp4];
if (rs.type == OPEN_BRACKET) return [self exp3_remaining:exp4Node];
else return exp4Node;
}
- (CompiledCodeNode *) exp3_remaining:(CompiledCodeNode *)left
{
CompiledCodeNode *indexNode;
CompiledCodeNode *r = [CompiledCodeNode compiledCodeNode];
[r setFirstCharIndex:token_first_char_index];
[self checkToken:OPEN_BRACKET :@"\"[\" expected"];
[self scan];
indexNode = [self exp];
[self checkToken:CLOSE_BRACKET :@"\"]\" expected"];
[r setLastCharIndex:token_first_char_index];
[r setMessageWithReceiver: left
selector: @"at:"
operatorSymbols: nil];
[r addSubnode:indexNode];
[self scan];
if (rs.type == OPEN_BRACKET) return [self exp3_remaining:r];
else return r;
}
*/