-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRedeCompiler.h
1721 lines (1325 loc) · 53.1 KB
/
RedeCompiler.h
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
#if !defined(REDE_COMPILER_H)
#define REDE_COMPILER_H
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum RedeSourceType {
RedeSourceTypeFile,
RedeSourceTypeString,
} RedeSourceType;
typedef struct RedeSource {
RedeSourceType type;
union {
char* path;
char* string;
} data;
} RedeSource;
#define Rede_createStringSource(name, code)\
RedeSource name##__data = {\
.type = RedeSourceTypeString,\
.data = {\
.string = code\
}\
};\
RedeSource* name = &name##__data;
#define Rede_createFileSource(name, pathToFile)\
RedeSource name##__data = {\
.type = RedeSourceTypeFile,\
.data = {\
.path = pathToFile\
}\
};\
RedeSource* name = &name##__data;
typedef enum RedeDestType {
RedeDestTypeBuffer,
RedeDestTypeFile
} RedeDestType;
typedef struct RedeDest {
RedeDestType type;
size_t index;
union {
struct {
unsigned char* buffer;
size_t maxLength;
} buffer;
struct {
char* path;
FILE* fp;
} file;
} data;
} RedeDest;
#define Rede_createBufferDest(name, bufferLength)\
unsigned char name##__buffer[bufferLength];\
memset(name##__buffer, 0, sizeof(name##__buffer));\
RedeDest name##__data = {\
.type = RedeDestTypeBuffer,\
.index = -1,\
.data = {\
.buffer = {\
.buffer = name##__buffer,\
.maxLength = bufferLength,\
}\
}\
};\
RedeDest* name = &name##__data;\
#define Rede_createFileDest(name, filePath)\
RedeDest name##__data = {\
.type = RedeDestTypeFile,\
.index = -1,\
.data = {\
.file = {\
.path = filePath,\
}\
}\
};\
RedeDest* name = &name##__data;\
typedef struct RedeVariableName {
int isBusy;
unsigned char index;
size_t start;
size_t length;
} RedeVariableName;
typedef struct RedeCompilationMemory {
struct {
unsigned char nextIndex;
RedeVariableName* buffer;
size_t bufferSize;
} variables;
} RedeCompilationMemory;
#define Rede_createCompilationMemory(name, variablesBufferSize)\
RedeVariableName name##__names[256];\
memset(name##__names, 0, sizeof(name##__names));\
RedeCompilationMemory name##__data = {\
.variables = {\
.buffer = name##__names,\
.bufferSize = variablesBufferSize,\
.nextIndex = 0,\
}\
};\
RedeCompilationMemory* name = &name##__data;
int Rede_compile(RedeSource* src, RedeCompilationMemory* memory, RedeDest* dist);
#endif // REDE_COMPILER_H
#if defined(REDE_COMPILER_IMPLEMENTATION)
#include <stdio.h>
#if !defined(REDE_SOURCE_ITERATOR)
#define REDE_SOURCE_ITERATOR
typedef enum RedeSourceIteratorType {
RedeSourceIteratorTypeString,
RedeSourceIteratorTypeFile
} RedeSourceIteratorType;
typedef struct RedeSourceIterator {
size_t index;
int finished;
char current;
RedeSourceIteratorType type;
union {
char* string;
struct {
FILE* fp;
} file;
} data;
} RedeSourceIterator;
int RedeSourceIterator_init(RedeSource* src, RedeSourceIterator* iterator);
void RedeSourceIterator_destroy(RedeSourceIterator* iterator);
char RedeSourceIterator_nextChar(RedeSourceIterator* iterator);
char RedeSourceIterator_charAt(RedeSourceIterator* iterator, size_t index);
char RedeSourceIterator_current(RedeSourceIterator* iterator);
void RedeSourceIterator_moveCursorBack(RedeSourceIterator* iterator, size_t shift);
#endif // REDE_SOURCE_ITERATOR
#include <stdio.h>
#include <stdlib.h>
int RedeSourceIterator_init(RedeSource* src, RedeSourceIterator* iterator) {
iterator->index = -1;
iterator->finished = 0;
iterator->current = 0;
switch(src->type) {
case RedeSourceTypeString:
iterator->type = RedeSourceIteratorTypeString;
iterator->data.string = src->data.string;
break;
case RedeSourceTypeFile: {
FILE* fp = fopen(src->data.path, "r");
if(!fp) return -1;
iterator->type = RedeSourceIteratorTypeFile;
iterator->data.file.fp = fp;
break;
}
}
return 0;
}
void RedeSourceIterator_destroy(RedeSourceIterator* iterator) {
if(iterator->type == RedeSourceIteratorTypeFile) {
fclose(iterator->data.file.fp);
}
}
char RedeSourceIterator_nextChar(RedeSourceIterator* iterator) {
if(iterator->finished) return '\0';
iterator->index++;
switch(iterator->type)
case RedeSourceIteratorTypeString: {
iterator->current = iterator->data.string[iterator->index];
if(!iterator->current) iterator->finished = 1;
break;
case RedeSourceIteratorTypeFile:
iterator->current = getc(iterator->data.file.fp);
if(iterator->current == EOF) {
iterator->finished = 1;
iterator->current = '\0';
}
break;
default:
fprintf(stderr, "Unknown iterator type\n");
exit(1);
}
return iterator->current;
}
char RedeSourceIterator_charAt(RedeSourceIterator* iterator, size_t index) {
switch(iterator->type) {
case RedeSourceIteratorTypeString:
return iterator->data.string[index];
case RedeSourceIteratorTypeFile: {
size_t diff = iterator->index - index;
fseek(iterator->data.file.fp, -diff - 1, SEEK_CUR);
char ch = getc(iterator->data.file.fp);
fseek(iterator->data.file.fp, diff, SEEK_CUR);
return ch;
}
default:
fprintf(stderr, "Unknown iterator type\n");
exit(1);
}
}
char RedeSourceIterator_current(RedeSourceIterator* iterator) {
return iterator->current;
}
void RedeSourceIterator_moveCursorBack(RedeSourceIterator* iterator, size_t shift) {
iterator->index -= shift;
switch(iterator->type) {
case RedeSourceIteratorTypeString:
iterator->current = iterator->data.string[iterator->index];
break;
case RedeSourceIteratorTypeFile:
fseek(iterator->data.file.fp, iterator->index, SEEK_SET);
iterator->current = getc(iterator->data.file.fp);
fseek(iterator->data.file.fp, -1, SEEK_CUR);
break;
default:
fprintf(stderr, "Unknown iterator type\n");
exit(1);
}
}
#if !defined(LOGS_H)
#define LOGS_H
#include <stdio.h>
#if defined(REDE_DO_LOGS)
#define LOGS_SCOPE(name)\
const char* logs__scope__name = #name;\
if(!logs__scope__name[0]) logs__scope__name = __func__;\
printf("LOGS '%s'\n", logs__scope__name);\
#define LOG(...)\
do {\
printf("LOGS '%s' ", logs__scope__name);\
printf(__VA_ARGS__);\
} while(0);\
#define LOG_LN(...)\
do {\
LOG(__VA_ARGS__);\
printf("\n");\
} while(0);\
#define CHECK(condition, ...)\
do {\
int LOCAL_STATUS = (condition);\
if(LOCAL_STATUS < 0) {\
printf("LOGS '%s' Status: %d ", logs__scope__name, LOCAL_STATUS);\
printf(__VA_ARGS__);\
printf("\n");\
return LOCAL_STATUS;\
}\
} while(0);\
#define LOGS_ONLY(code) code
#define CHECK_ELSE(condition, elseCode, ...)\
do {\
int CONDITION_VALUE = (condition);\
if(CONDITION_VALUE < 0) {\
printf("LOGS '%s' Status: %d ", logs__scope__name, CONDITION_VALUE);\
printf(__VA_ARGS__);\
printf("\n");\
elseCode;\
}\
} while(0);
#define CHECK_RETURN(condition, ...)\
do {\
int LOCAL_STATUS = (condition);\
if(LOCAL_STATUS < 0) {\
printf("LOGS '%s' Status: %d ", logs__scope__name, LOCAL_STATUS);\
printf(__VA_ARGS__);\
printf("\n");\
}\
return LOCAL_STATUS;\
} while(0);\
#else
#define LOGS_SCOPE(name)
#define LOG(...)
#define LOG_LN(...)
#define CHECK(condition, ...)\
do {\
int LOCAL_STATUS = (condition);\
if(LOCAL_STATUS < 0) return LOCAL_STATUS;\
} while(0);\
#define LOGS_ONLY(code)
#define CHECK_ELSE(condition, elseCode, ...)\
do {\
int CONDITION_VALUE = (condition);\
if(CONDITION_VALUE < 0) {\
elseCode;\
}\
} while(0);
#define CHECK_RETURN(condition, ...) return (condition);
#endif // REDE_DO_LOGS
#endif // LOGS_H
#if !defined(REDE_BYTE_CODES)
#define REDE_BYTE_CODES
#define REDE_TYPE_NUMBER 0x00
#define REDE_TYPE_STRING 0x01
#define REDE_TYPE_VAR 0x02
#define REDE_TYPE_STACK 0x03
#define REDE_TYPE_BOOL 0x04
#define REDE_DIRECTION_FORWARD 0x00
#define REDE_DIRECTION_BACKWARD 0x01
#define REDE_CODE_ASSIGN 0x00
#define REDE_CODE_STACK_PUSH 0x01
#define REDE_CODE_CALL 0x02
#define REDE_CODE_STACK_CLEAR 0x03
#define REDE_CODE_JUMP 0x04
#define REDE_CODE_JUMP_IF 0x05
#define REDE_CODE_JUMP_IF_NOT 0x06
#define REDE_CODE_NOP 0xFE
#define REDE_CODE_END 0xFF
#endif // REDE_BYTE_CODES
int RedeDest_init(RedeDest* dest) {
LOGS_SCOPE();
dest->index = -1;
switch(dest->type) {
case RedeDestTypeFile: {
dest->data.file.fp = fopen(dest->data.file.path, "wb");
if(!dest->data.file.fp) {
LOG_LN("Failed to open file '%s'", dest->data.file.path);
return -1;
}
return 0;
}
case RedeDestTypeBuffer:
return 0;
default:
LOG_LN("Unknown destination type");
return -1;
}
return 0;
}
void RedeDest_destroy(RedeDest* dest) {
LOGS_SCOPE();
if(dest->type == RedeDestTypeFile) {
fclose(dest->data.file.fp);
}
}
int RedeDest_writeByte(RedeDest* dest, unsigned char byte) {
dest->index++;
switch(dest->type) {
case RedeDestTypeBuffer:
if(dest->index != dest->data.buffer.maxLength) {
dest->data.buffer.buffer[dest->index] = byte;
return 0;
} else {
return -1;
}
case RedeDestTypeFile:
if(fputc(byte, dest->data.file.fp) != byte) {
return -1;
};
return 0;
default:
return -1;
}
}
void RedeDest_moveCursorBack(RedeDest* dest, size_t n) {
dest->index -= n;
switch(dest->type) {
case RedeDestTypeFile:
fseek(dest->data.file.fp, -n, SEEK_CUR);
return;
default:
return;
}
}
int RedeDest_writeByteAt(RedeDest* dest, size_t index, unsigned char byte) {
switch(dest->type) {
case RedeDestTypeBuffer:
if(index >= dest->data.buffer.maxLength) return -1;
dest->data.buffer.buffer[index] = byte;
return 0;
case RedeDestTypeFile:
fseek(dest->data.file.fp, index, SEEK_SET);
if(fputc(byte, dest->data.file.fp) != byte) {
return -1;
}
fseek(dest->data.file.fp, dest->index + 1, SEEK_SET);
return 0;
default:
return -1;
}
}
#if !defined(REDE_COMPILER_HELPERS)
#define REDE_COMPILER_HELPERS
/* EOI = End of input */
typedef enum RedeWriteStatus {
RedeWriteStatusError = -1,
RedeWriteStatusOk = 0,
/**
* @brief Statement ended with bracket
*
*/
RedeWriteStatusBracketTerminated = 1,
/**
* @brief Statement ended with EOI
*
*/
RedeWriteStatusEOI = 2
} RedeWriteStatus;
typedef enum RedeExpressionWriteStatus {
RedeExpressionWriteStatusOk = 0,
RedeExpressionWriteStatusError = -1,
/**
* @brief Expression is a function call
*
*/
RedeExpressionWriteStatusFunction = 1,
/**
* @brief Expression ended with bracket
*
*/
RedeExpressionWriteStatusBracketTerminated = 2,
/**
* @brief Expression ended with EOI
*
*/
RedeExpressionWriteStatusEOI = 3,
/**
* @brief Got just closing bracket as brackets block end
*
*/
RedeExpressionWriteStatusBracket = 4,
} RedeExpressionWriteStatus;
typedef struct RedeCompilationContextWhileLoop {
size_t loopStart;
size_t breakJumpStart;
int breakRequired;
} RedeCompilationContextWhileLoop;
typedef struct RedeCompilationContext {
int functionCallDepth;
int isAssignment;
int isIfStatementArgument;
int isWhileLoopArgument;
int bracketsBlockDepth;
RedeCompilationContextWhileLoop* whileLoopCtx;
} RedeCompilationContext;
RedeExpressionWriteStatus RedeCompilerHelpers_writeFloat(
char firstChar,
RedeSourceIterator* iterator, RedeDest* dest, RedeCompilationContext* ctx
);
RedeExpressionWriteStatus RedeCompilerHelpers_writeString(
int singleQuoted,
RedeSourceIterator* iterator, RedeDest* dest
);
RedeExpressionWriteStatus RedeCompilerHelpers_writeVariableValue(
size_t identifierStart, size_t identifierLength,
RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest
);
RedeExpressionWriteStatus RedeCompilerHelpers_writeOperationWithToken(
RedeSourceIterator* iterator,
RedeCompilationMemory* memory,
RedeDest* dest,
RedeCompilationContext* ctx
);
RedeExpressionWriteStatus RedeCompilerHelpers_writeBoolean(int value, RedeDest* dest);
RedeExpressionWriteStatus RedeCompilerHelpers_writeExpression(RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeAssignment(
size_t tokenStart, size_t tokenLength,
RedeSourceIterator* iterator,
RedeCompilationMemory* memory,
RedeDest* dest,
RedeCompilationContext* ctx
);
RedeExpressionWriteStatus RedeCompilerHelpers_writeFunctionCall(
size_t identifierStart, size_t identifierLength,
RedeSourceIterator* iterator,
RedeCompilationMemory* memory,
RedeDest* dest,
RedeCompilationContext* ctx
);
RedeWriteStatus RedeCompilerHelpers_writeStatements(RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeStatement(RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeWhile(RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeContinue(RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeBreak(RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeIfStatement(RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_writeElseStatement(RedeSourceIterator* iterator, RedeCompilationMemory* memory, RedeDest* dest, RedeCompilationContext* ctx);
RedeWriteStatus RedeCompilerHelpers_parseComment(RedeSourceIterator* src);
unsigned long RedeCompilerHelpers_hash(RedeSourceIterator* iterator, size_t identifierStart, size_t identifierLength);
int RedeCompilerHelpers_isToken(char* token, size_t identifierStart, size_t identifierLength, RedeSourceIterator* iterator);
int RedeCompilerHelpers_nextTokenIs(char* token, RedeSourceIterator* iterator);
#endif // REDE_COMPILER_HELPERS
RedeWriteStatus RedeCompilerHelpers_parseComment(RedeSourceIterator* src) {
LOGS_SCOPE(parseComment);
char ch;
while((ch = RedeSourceIterator_nextChar(src))) {
LOG_LN("Char: '%c'(%d)", ch, ch);
int end = 0;
switch(ch) {
case '\r':
case '\n':
case '#':
LOG_LN("End of the comment");
end = 1;
break;
}
if(end) break;
}
return RedeWriteStatusOk;
}
unsigned long RedeCompilerHelpers_hash(
RedeSourceIterator* iterator,
size_t identifierStart,
size_t identifierLength
) {
LOGS_SCOPE(hash);
unsigned long hash = 5381;
for(size_t i = identifierStart; i < identifierStart + identifierLength; i++) {
char ch = RedeSourceIterator_charAt(iterator, i);
LOG_LN("%zu) '%c'(%d)", i, ch, ch);
hash = ((hash << 5) + hash) + ch; /* hash * 33 + c */
}
return hash;
}
int RedeCompilerHelpers_isToken(char* token, size_t tokenStart, size_t tokenLength, RedeSourceIterator* iterator) {
size_t i = 0;
while(1) {
if(i == tokenLength) {
return token[i] == '\0';
}
char tokenChar = token[i];
char strChar = RedeSourceIterator_charAt(iterator, tokenStart + i);
if(tokenChar == '\0' || tokenChar != strChar) return 0;
i++;
}
}
int RedeCompilerHelpers_nextTokenIs(char* token, RedeSourceIterator* iterator) {
LOGS_SCOPE(nextTokenIs);
LOG_LN("Checking for token '%s'", token);
size_t tokenIndex = 0;
char ch;
while((ch = RedeSourceIterator_nextChar(iterator))) {
LOG_LN("Char: %c(%d)", ch, ch);
if(ch == ' ' || ch == '\n' || ch == '\r' || ch == 9/* TAB */) {
if(tokenIndex > 0) {
LOG_LN("Mismatch, reverting %zu token chars", tokenIndex + 1)
RedeSourceIterator_moveCursorBack(iterator, tokenIndex + 1);
return 0;
}
continue;
} else if(ch == token[tokenIndex]) {
tokenIndex++;
if(token[tokenIndex] == '\0') return 1;
} else {
LOG_LN("Mismatch, reverting %zu token chars", tokenIndex + 1)
RedeSourceIterator_moveCursorBack(iterator, tokenIndex + 1);
return 0;
}
}
return 0;
}
RedeExpressionWriteStatus RedeCompilerHelpers_writeBoolean(int value, RedeDest* dest) {
LOGS_SCOPE(writeBoolean);
CHECK(RedeDest_writeByte(dest, REDE_TYPE_BOOL), "Failed to write REDE_TYPE_BOOL");
CHECK(RedeDest_writeByte(dest, value == 0 ? 0 : 1), "Failed to write boolean value");
return RedeExpressionWriteStatusOk;
}
RedeWriteStatus RedeCompilerHelpers_writeAssignment(
size_t tokenStart, size_t tokenLength,
RedeSourceIterator* iterator,
RedeCompilationMemory* memory,
RedeDest* dest,
RedeCompilationContext* ctx
) {
LOGS_SCOPE(writeAssignment);
ctx->isAssignment = 1;
CHECK(RedeDest_writeByte(dest, REDE_CODE_ASSIGN), "Failed to write REDE_CODE_ASSIGN to the buffer");
unsigned long arrayIndex = RedeCompilerHelpers_hash(iterator, tokenStart, tokenLength) % memory->variables.bufferSize;
LOG_LN("VARIABLE_HASH_TABLE_INDEX: %zu", arrayIndex);
RedeVariableName* name = memory->variables.buffer + arrayIndex;
if(!name->isBusy) {
name->isBusy = 1;
name->index = memory->variables.nextIndex++;
name->start = tokenStart;
name->length = tokenLength;
LOG_LN("Registering new variable with index %d", name->index);
}
LOGS_ONLY(
else {
LOG_LN("Variable already exist, index = %d", name->index);
}
)
CHECK(RedeDest_writeByte(dest, name->index), "Failed to write variable index '%d' to the buffer", name->index);
int status = RedeCompilerHelpers_writeExpression(iterator, memory, dest, ctx);
CHECK(status, "Failed to write expression");
if(status == RedeExpressionWriteStatusFunction) {
CHECK(RedeDest_writeByte(dest, REDE_CODE_ASSIGN), "Failed to write REDE_CODE_ASSIGN to the buffer after function call");
CHECK(RedeDest_writeByte(dest, name->index), "Failed to write variable index '%d' to the buffer after function call", name->index);
CHECK(RedeDest_writeByte(dest, REDE_TYPE_STACK), "Failed to write REDE_TYPE_STACK after function call");
}
ctx->isAssignment = 0;
switch(status) {
case RedeExpressionWriteStatusBracketTerminated:
return RedeWriteStatusBracketTerminated;
case RedeExpressionWriteStatusEOI:
return RedeWriteStatusEOI;
default:
return RedeWriteStatusOk;
}
}
RedeWriteStatus RedeCompilerHelpers_writeBreak(
RedeDest* dest,
RedeCompilationContext* ctx
) {
LOGS_SCOPE(writeBreak);
if(!ctx->whileLoopCtx) {
LOG_LN("break keyword used outside of while-loop");
return RedeWriteStatusError;
}
ctx->whileLoopCtx->breakRequired = 1;
CHECK(RedeDest_writeByte(dest, REDE_CODE_JUMP), "Failed to write REDE_CODE_JUMP");
CHECK(RedeDest_writeByte(dest, REDE_DIRECTION_BACKWARD), "Failed to write REDE_DIRECTION_BACKWARD");
size_t bytesDiff = dest->index - ctx->whileLoopCtx->breakJumpStart + 1;
if(bytesDiff > 0xFFFF) {
LOG_LN("The loop is to big to jump backward");
return RedeWriteStatusError;
}
LOG_LN("Back jump length: %zu", bytesDiff);
unsigned char* bytes = (unsigned char*)&bytesDiff;
CHECK(RedeDest_writeByte(dest, bytes[0]), "Failed to write the first byte of the back jump");
CHECK(RedeDest_writeByte(dest, bytes[1]), "Failed to write the second byte of the back jump");
return RedeWriteStatusOk;
}
RedeWriteStatus RedeCompilerHelpers_writeContinue(
RedeDest* dest,
RedeCompilationContext* ctx
) {
LOGS_SCOPE(writeContinue);
if(!ctx->whileLoopCtx) {
LOG_LN("continue keyword used outside of while-loop");
return RedeWriteStatusError;
}
CHECK(RedeDest_writeByte(dest, REDE_CODE_JUMP), "Failed to write REDE_CODE_JUMP");
CHECK(RedeDest_writeByte(dest, REDE_DIRECTION_BACKWARD), "Failed to write REDE_DIRECTION_BACKWARD");
size_t bytesDiff = dest->index - ctx->whileLoopCtx->loopStart + 1;
if(bytesDiff > 0xFFFF) {
LOG_LN("The loop is to big to jump backward");
return RedeWriteStatusError;
}
LOG_LN("Back jump length: %zu", bytesDiff);
unsigned char* bytes = (unsigned char*)&bytesDiff;
CHECK(RedeDest_writeByte(dest, bytes[0]), "Failed to write the first byte of the back jump");
CHECK(RedeDest_writeByte(dest, bytes[1]), "Failed to write the second byte of the back jump");
return RedeWriteStatusOk;
}
RedeWriteStatus RedeCompilerHelpers_writeElseStatement(
RedeSourceIterator* src,
RedeCompilationMemory* memory,
RedeDest* dest,
RedeCompilationContext* ctx
) {
LOGS_SCOPE(writeElseStatement);
if(!RedeCompilerHelpers_nextTokenIs("else", src)) {
LOG_LN("Not 'else' token");
return RedeWriteStatusOk;
}
LOG_LN("Else statement");
// Jump after if-statement to skip the else body
CHECK(RedeDest_writeByte(dest, REDE_CODE_JUMP), "Failed to write REDE_CODE_JUMP after if-statement");
CHECK(RedeDest_writeByte(dest, REDE_DIRECTION_FORWARD), "Failed to write REDE_DIRECTION_FORWARD after if-statement");
CHECK(RedeDest_writeByte(dest, 0), "Failed to write jump size first byte placeholder after if-statement");
size_t jumpSizeStart = dest->index;
CHECK(RedeDest_writeByte(dest, 0), "Failed to write jump size second byte placeholder after if-statement");
int isMultipleStatements = RedeCompilerHelpers_nextTokenIs("(", src);
RedeWriteStatus resultStatus = RedeWriteStatusOk;
if(isMultipleStatements) {
LOG_LN("Multiple statements");
ctx->bracketsBlockDepth++;
CHECK(RedeCompilerHelpers_writeStatements(src, memory, dest, ctx), "failed to parse statements");
ctx->bracketsBlockDepth--;
} else {
LOG_LN("Single statement");
CHECK(resultStatus = RedeCompilerHelpers_writeStatement(src, memory, dest, ctx), "Failed to parse statement");
}
size_t diff = dest->index - (jumpSizeStart + 1);
LOG_LN("Jump size: %zu bytes", diff);
if(diff > 0xFFFF) {
LOG_LN("Else body is too big to jump over");
return RedeWriteStatusError;
}
unsigned char* diffBytes = (unsigned char*)&diff;
CHECK(RedeDest_writeByteAt(dest, jumpSizeStart + 0, diffBytes[0]), "Failed to write jump size first byte");
CHECK(RedeDest_writeByteAt(dest, jumpSizeStart + 1, diffBytes[1]), "Failed to write jump size second byte");
return resultStatus;
}
RedeExpressionWriteStatus RedeCompilerHelpers_writeExpression(
RedeSourceIterator* iterator,
RedeCompilationMemory* memory,
RedeDest* dest,
RedeCompilationContext* ctx
) {
LOGS_SCOPE(writeExpression);
char ch;
while((ch = RedeSourceIterator_nextChar(iterator))) {
LOG_LN("CHAR: '%c'(%d)", ch, ch);
if((ch >= '0' && ch <= '9') || ch == '-') {
LOG_LN("Number assignment");
CHECK_RETURN(RedeCompilerHelpers_writeFloat(ch, iterator, dest, ctx), "Failed to write a float");
} else if(ch == '"' || ch == '\'') {
LOG_LN("String assignment");
CHECK_RETURN(RedeCompilerHelpers_writeString(ch == '\'', iterator, dest), "Failed to write a string");
} else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
LOG_LN("Operation with token");
CHECK_RETURN(RedeCompilerHelpers_writeOperationWithToken(iterator, memory, dest, ctx), "Failed to write function call or variable value");
} else if(ch == ' ' || ch == '\n' || ch == '\r') {
continue;
} else if(ctx->bracketsBlockDepth > 0 && ch == ')') {
LOG_LN("Brackets block end");
return RedeExpressionWriteStatusBracket;
} else if (ch == '#') {
LOG_LN("Comment start");
RedeCompilerHelpers_parseComment(iterator);
} else {
LOG_LN("Unexpected token");
return RedeExpressionWriteStatusError;
}
}
LOG_LN("Unexpected end of input");
return RedeExpressionWriteStatusError;
}
static size_t RedeCompilerHelpers_pow10L(size_t power) {
size_t result = 1;
for(size_t i = 0; i < power; i++) {
result *= 10;
}
return result;
}
RedeExpressionWriteStatus RedeCompilerHelpers_writeFloat(
char firstChar,
RedeSourceIterator* iterator,
RedeDest* dest,
RedeCompilationContext* ctx
) {
LOGS_SCOPE(writeFloat);
int isNegative = firstChar == '-';
float result;
if(isNegative) {
LOG_LN("Negative number");
result = 0;
} else {
LOG_LN("Positive number");
result = firstChar - '0';
}
int floatingPoint = 0;
size_t floatingPointPosition = 1;
int endedWithSeparator = 0;
char ch;
while((ch = RedeSourceIterator_nextChar(iterator))) {
LOG_LN("CHAR: '%c'(%d)", ch, ch);
if(ch >= '0' && ch <= '9') {
if(!floatingPoint) {
result *= 10;
result += ch - '0';
} else {
result += (float)(ch - '0') / RedeCompilerHelpers_pow10L(floatingPointPosition);
floatingPointPosition++;
}
} else if(ch == '.' && !floatingPoint) {
LOG_LN("Floating point");
floatingPoint = 1;
} else if(
ch == ' ' || ch == '\n' || ch == '\r'
||
(ctx->bracketsBlockDepth > 0 && ch == ')')
) {
LOGS_ONLY(
if(ctx->bracketsBlockDepth > 0 && ch == ')') {
LOG_LN("Count as input end because of brackets block depth = %d", ctx->bracketsBlockDepth);
}
)
endedWithSeparator = 1;
break;
} else {
LOG_LN("Unexpected character");
return RedeExpressionWriteStatusError;
}
}
if(isNegative) {
result *= -1;
}
LOG_LN("Result: %f", result);
CHECK(RedeDest_writeByte(dest, REDE_TYPE_NUMBER), "Failed to write REDE_TYPE_NUMBER");
LOG_LN("Serializing");
char* bytes = (char*)&result;
for(size_t i = 0; i < sizeof(float); i++) {
CHECK(RedeDest_writeByte(dest, bytes[i]), "Failed to write float byte with index %zu", i);
}