forked from Shando/game_engine_for_esp8266_with_compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.js
1928 lines (1908 loc) · 62.6 KB
/
compiler.js
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
"use strict";
//token breakdown
function tokenize(s) {
var tokens = [];
var thisToken = 0;
var l;
var lastDefine;
var tokenReplace = [
'S_X', 0, 'S_Y', 1, 'S_SPEEDX', 2, 'S_SPEEDY', 3, 'S_WIDTH', 4, 'S_HEIGHT', 5,
'S_ANGLE', 6, 'S_LIVES', 7, 'S_COLLISION', 8, 'S_SOLID', 9, 'S_GRAVITY', 10,
'S_ON_COLLISION', 11, 'S_ON_EXIT_SCREEN', 12, 'S_IS_SCROLLED', 13, 'S_IS_ONEBIT', 14,
'S_FLIP_HORIZONTAL', 15,
'KEY_UP', 1, 'KEY_LEFT', 4, 'KEY_DOWN', 2, 'KEY_RIGHT', 8, 'KEY_A', 16, 'KEY_B', 32
];
//simplified version of #define, just a replacement
function define(s) {
lastDefine = [''];
while (lastDefine.length != 0) {
lastDefine = [];
s = s.replace(/#define\s*([^\s]*)\s*([^\n]*)/, function (str, def, repl, offset, s) {
lastDefine = [def, repl];
return ' ';
});
if (lastDefine.length > 0)
s = s.replace(new RegExp(lastDefine[0], 'g'), lastDefine[1]);
}
return s;
}
s = define(s);
s = s.replace(/#include[^\n]*/g, ''); //removal of inclusions, so as not to interfere
l = s.length;
tokens[0] = '';
for (var i = 0; i < l; i++) {
switch (s[i]) {
case '"':
//line processing
if (tokens[thisToken] != '')
thisToken++;
tokens[thisToken] = s[i++];
while (i < l && s[i] != '"') {
tokens[thisToken] += s[i++];
//special character replacement
if (s[i] == '\\' && s[i + 1] == '"') {
tokens[thisToken] += '\\"';
i += 2;
}
}
tokens[thisToken] += s[i];
thisToken++;
tokens[thisToken] = '';
break;
case '\'':
//single character processing
if (tokens[thisToken] != '')
thisToken++;
if (s[i + 2] == '\'') {
tokens[thisToken] = '' + s.charCodeAt(i + 1);
thisToken++;
tokens[thisToken] = '';
i += 2;
}
break;
case '=':
if (s[i - 1] == '=' || s[i - 1] == '!' || s[i - 1] == '+' || s[i - 1] == '-' || s[i - 1] == '*' || s[i - 1] == '/') {
tokens[thisToken - 1] += '=';
break;
}
case '+':
case '-':
case '*':
case '%':
case '/':
//if comments, then remove, leaving line feeds
if (s[i + 1] == '/') {
while (s[i + 1] != '\n')
i++;
break;
}
if (s[i + 1] == '*') {
i += 2;
while (!(s[i] == '*' && s[i + 1] == '/')) {
if (s[i] == '\n') {
if (tokens[thisToken] != '')
thisToken++;
tokens[thisToken] = s[i];
thisToken++;
tokens[thisToken] = '';
}
i++;
if (i >= l)
break;
}
i++;
break;
}
case '>':
case '<':
case '!':
case '&':
case '^':
case '|':
case '(':
case ')':
case '{':
case '}':
case '[':
case ']':
case ';':
case '?':
case ':':
case ',':
case '\n':
if (tokens[thisToken] != '')
thisToken++;
tokens[thisToken] = s[i];
if ((s[i] == '>' || s[i] == '<') && s[i + 1] == '=') {
i++;
tokens[thisToken] += s[i];
}
if (!(s[i] == '-'
&& (tokens[thisToken - 1] == '=' || tokens[thisToken - 1] == '(' || tokens[thisToken - 1] == ',' || tokens[thisToken - 1] == '>' || tokens[thisToken - 1] == '<')
&& s[i + 1] >= '0' && s[i + 1] <= '9')) {
thisToken++;
tokens[thisToken] = '';
}
break;
case '\t':
case ' ':
//remove extra whitespace characters
while (l < i && s[i + 1] == ' ')
i++;
if (tokens[thisToken] != '') {
thisToken++;
tokens[thisToken] = '';
}
break;
default:
tokens[thisToken] += s[i];
}
}
for (var i = 0; i < tokens.length; i++) {
var n = tokenReplace.indexOf(tokens[i]);
if (n > -1 && n % 2 == 0)
tokens[i] = '' + tokenReplace[n + 1];
}
return tokens;
}
function compile(t) {
var asm = []; //core assembler code
var dataAsm = []; //assembler code to be added at the end of the main
var thisTokenNumber = 0; //current token number
var thisToken; //current token
var lastToken; //previous token
var varTable = []; //variable table
var localVarTable = []; //table of local variables
var functionTable = []; //table containing the names of the functions and their source code in assembler
var thisFunction;
var isIntoFunction = false; //are we in the function body
var functionVarTable = []; //table of variables specified in the declaration of the current function being processed
var lineCount = 0; //current line number
var registerCount = 1; //pointer to the processor register currently in use
var lastEndString = 0; //pointer to the last token in the previous line
var labelNumber = 0; //link number, needed to create unique link names
var localStackLength = 0; //used in functions for working with local variables relative to the stack pointer
var switchStack = []; //points to the last switch, necessary for processing break
function putError(line, error, par) {
var er = 'unknown';
if (language == 'rus')
switch (error) {
case 0:
er = "функция " + par + " уже была объявлена";
break;
case 1:
er = "функция " + par + " не соответствует прототипу";
case 2:
er = "ожидалось определение типа";
break;
case 3:
er = "ожидалась запятая или закрывающая скобка";
break;
case 4:
er = "ожидалась фигурная открывающая скобка";
break;
case 5:
er = "ожидалась закрывающая скобка в функции " + par;
break;
case 6:
er = "ожидался аргумент в функции " + par;
break;
case 7:
er = "ожидалась открывающая скобка в функции " + par;
break;
case 8:
er = "функция " + par + " не может возвращать значение";
break;
case 9:
er = "работа с локальными массивами не поддерживается";
break;
case 10:
er = "не указана длина массива";
break;
case 11:
er = "неправильное объявление массива";
break;
case 12:
er = "неверное количество аргументов";
break;
case 13:
er = "ожидалась открывающая скобка в конструкции " + par;
break;
case 14:
er = "отсутствует конструкция switch";
break;
case 15:
er = "ожидалось двоеточие";
break;
case 16:
er = "ожидалось число";
break;
case 17:
er = "неподдерживаемое объявление переменных";
break;
case 18:
er = "ожидалась скобка";
break;
case 19:
er = "предупреждение, unsigned не реализовано";
break;
case 20:
er = "неизвестный токен " + par;
break;
case 21:
er = "не найдена точка входа в функцию main";
break;
}
else
switch (error) {
case 0:
er = "the " + par + " function has already been declared";
break;
case 1:
er = "the function " + par + " does not match the prototype";
case 2:
er = "expected type definition";
break;
case 3:
er = "expected comma or closing bracket";
break;
case 4:
er = "expected curly opening bracket";
break;
case 5:
er = "expected closing bracket in function " + par;
break;
case 6:
er = "expected argument in function " + par;
break;
case 7:
er = "expected opening bracket in function " + par;
break;
case 8:
er = "the function " + par + " cannot return a value";
break;
case 9:
er = "working with local arrays is not supported";
break;
case 10:
er = "array length not specified";
break;
case 11:
er = "invalid array declaration";
break;
case 12:
er = "invalid number of arguments";
break;
case 13:
er = "expected opening bracket in construction " + par;
break;
case 14:
er = "no switch design";
break;
case 15:
er = "colon is expected";
break;
case 16:
er = "expected number";
break;
case 17:
er = "unsupported variable declaration";
break;
case 18:
er = "expected brace";
break;
case 19:
er = "warning, unsigned not implemented";
break;
case 20:
er = "unknown token " + par;
break;
case 21:
er = "main function entry point not found";
break;
}
info("" + line + " " + er);
}
//get the next token, return false if the next token does not exist
function getToken() {
lastToken = thisToken;
if (thisTokenNumber < t.length) {
thisToken = t[thisTokenNumber];
thisTokenNumber++;
return true;
}
thisToken = false;
return false;
}
//roll back to the previous token
function previousToken() {
if (thisTokenNumber > 1) {
thisTokenNumber--;
thisToken = t[thisTokenNumber - 1];
if (thisTokenNumber > 1) {
lastToken = t[thisTokenNumber - 2];
} else {
lastToken = '';
}
return true;
} else
return false;
}
//getting the rank of an operation for the correct order of performing mathematical operations
function getRangOperation(t) {
switch (t) {
case '>':
case '<':
case '!':
case '==':
case '!=':
case '<=':
case '>=':
case '?':
case ':':
return 1;
case '|':
case '&':
case '^':
return 2;
case '+':
case '-':
return 3;
case '*':
case '/':
case '%':
return 4;
}
return 0;
}
//function registration: name, type of returned data, operands, whether a function is declared, source code, whether to insert a function instead of a jump
function registerFunction(name, ftype, operands, declar, asm, inline, varLength) {
var pos = -1;
for (var i = 0; i < functionTable.length; i++) {
if (functionTable[i].name == name)
pos = i;
}
if (pos >= 0 && functionTable[pos].declar == 1) {
putError(lineCount, 0, name);
//info("" + lineCount + " the function " + name + " has already been declared");
} else if (pos == -1) {
//function name, return type, operands, whether a function is declared, whether a function is used, function code, whether to insert a function instead of a jump
functionTable.push({
name: name,
type: ftype,
operands: operands,
declar: declar,
use: 0,
asm: asm,
inline: inline,
varLength: varLength
});
} else {
if (!(functionTable[pos].type == ftype)) {
putError(lineCount, 1, name);
//info("" + lineCount + " function " + name + " does not match the prototype");
}
functionTable[pos].declar = declar;
functionTable[pos].asm = asm;
functionTable[pos].varLength = varLength;
}
}
//processing the function met in the code
function addFunction(type) {
var name = thisToken;
var start = 0;
thisFunction = name;
localVarTable = [];
functionVarTable = [];
registerCount = 1;
//main is always called, so for now just jump it
if (name == 'main')
asm.push('JMP _end_main');
getToken();
getToken();
//add function variables to the table, immediately type, then name, in a row to simplify the search (the name still cannot match the type
while (thisToken != ')') {
if (isType(thisToken))
functionVarTable.push(thisToken);
else {
putError(lineCount, 2, '');
//info("" + lineCount + "expected type definition");
return false;
}
getToken();
if (!thisToken)
return;
if (thisToken == ')' && lastToken == 'void' && functionVarTable.length == 1) {
functionVarTable = [];
} else {
functionVarTable.push(thisToken);
getToken();
if (thisToken == '[') {
getToken();
getToken();
}
if (thisToken == ',')
getToken();
else if (thisToken != ')') {
putError(lineCount, 3, '');
//info("" + lineCount + "expected comma or closing bracket");
return false;
}
}
}
getToken();
removeNewLine();
//if a semicolon follows, then the function body will be described later. Register a function so that you can use it
if (thisToken == ';') {
registerFunction(name, type, functionVarTable, 0, [], 0, 0);
}
//otherwise we process the contents of the function
else {
isIntoFunction = true;
registerFunction(name, type, functionVarTable, 0, [], 0, 0);
if (thisToken != '{') {
putError(lineCount, 4, '');
//info("" + lineCount + "expected curly opening bracket");
return false;
}
//remember the beginning of the assembler code belonging to the function
start = asm.length;
asm.push(' ');
asm.push('_' + name + ':');
skipBrace();
asm.push(' RET');
asm.push(' ');
//if it is main, indicate the end of the function
if (name == 'main') {
registerFunction(name, type, functionVarTable, 1, [], false, localVarTable.length);
asm.push(' ');
asm.push('_end_main:');
}
//otherwise, we cut out the entire function code from the asm table and save it in the function table. This will allow to add only used functions to the final code.
else
registerFunction(name, type, functionVarTable, 1, asm.splice(start, asm.length - start), false, localVarTable.length);
localVarTable = [];
isIntoFunction = false;
}
thisFunction = '';
}
//function code insertion
function inlineFunction(func) {
getToken();
if (thisToken != ')') {
previousToken();
while (!(thisToken == ')' || thisToken == ';')) {
i++;
getToken();
if (!thisToken)
return;
while (!(thisToken == ',' || thisToken == ')' || thisToken == ';')) {
execut();
if (!thisToken)
return;
if (getRangOperation(thisToken) > 0)
execut();
else if (!(thisToken == ',' || thisToken == ')' || thisToken == ';'))
getToken();
}
if (i > func.operands.length / 2 && !longArg) {
putError(lineCount, 3, t);
//info("" + lineCount + " expected closing bracket in function " + t);
return false;
}
}
}
//check the number of arguments declared
if (i < func.operands.length / 2 && !longArg) {
putError(lineCount, 6, t);
//info("" + lineCount + " expected argument in function " + t);
return false;
}
asm.push(func.asm.replace(/[Rr]\%(\d)/g, function (str, reg, offset, s) {
return 'R' + (registerCount - parseInt(reg));
}));
registerCount -= func.operands.length / 2;
if (func.type != 'void')
registerCount++;
getToken();
if (getRangOperation(thisToken) > 0)
execut();
else if (thisToken == ';')
previousToken();
}
//function call processing
function callFunction(t) {
var func;
var longArg = false;
var operandsCount = 0;
var pushOnStack = 0;
//localStackLength = 0;
var copyLocalStackLength = localStackLength;
for (var i = 0; i < functionTable.length; i++) {
if (functionTable[i].name == t) {
func = functionTable[i];
break;
}
}
//checking for an indefinite number of arguments
if (func.operands.length > 0 && func.operands[func.operands.length - 1] == '...')
longArg = true;
getToken();
if (thisToken != '(') {
if (thisToken == ')' || thisToken == ',') {
asm.push(' LDI R' + registerCount + ',_' + func.name);
func.use++;
registerCount++;
return;
} else
putError(lineCount, 7, t);
//info("" + lineCount + " expected opening bracket in function " + t);
return false;
}
if (func.inline == true) {
inlineFunction(func);
return;
}
func.use++;
i = 0;
if (registerCount > 1) {
//if the function should return a value, then we stack on the stack all the values of the registers containing the data, so that the function does not damage them
if (func.type != 'void') {
asm.push(' PUSHN R' + (registerCount - 1));
pushOnStack = registerCount - 1;
localStackLength += (registerCount - 1);
} else
putError(lineCount, 8, func.name);
//info('' + lineCount + ' function ' + func.name + ' cannot return a value');
} else
registerCount++;
getToken();
if (thisToken != ')') {
previousToken();
while (!(thisToken == ')' || thisToken == ';')) {
i++;
getToken();
if (!thisToken)
return;
while (!(thisToken == ',' || thisToken == ')' || thisToken == ';')) {
execut();
if (!thisToken)
return;
if (getRangOperation(thisToken) > 0)
execut();
else if (!(thisToken == ',' || thisToken == ')' || thisToken == ';'))
getToken();
}
registerCount--;
operandsCount++;
asm.push(' PUSH R' + registerCount);
localStackLength += 1;
if (i > func.operands.length / 2 && !longArg) {
putError(lineCount, 5, t);
//info("" + lineCount + " expected closing bracket in function " + t);
return false;
}
}
}
//check the number of arguments declared
if (i < func.operands.length / 2 && !longArg) {
putError(lineCount, 6, t);
//info("" + lineCount + " expected argument in function " + t);
return false;
}
if (longArg)
asm.push(' LDC R1,' + (operandsCount * 2));
//free up stack space for variables
if (func.varLength == 0 && thisFunction == func.name)
func.varLength = localVarTable.length;
if (func.varLength > 0) {
if (func.varLength < 15)
asm.push(' DEC R0,' + func.varLength);
else
asm.push(' LDC R15,' + func.varLength + '\n SUB R0,R15');
}
asm.push(' CALL _' + func.name);
//functions return the value in the first register, transfer to the one we need
if (func.type != 'void') {
if (registerCount != 1) {
asm.push(' MOV R' + registerCount + ',R1');
}
}
//restoring the stack pointer
if ((operandsCount * 2 + func.varLength) > 0xf)
asm.push(' LDC R15,' + (operandsCount * 2 + func.varLength) + '\n ADD R0,R15');
else if ((operandsCount * 2 + func.varLength) > 0)
asm.push(' INC R0,' + (operandsCount * 2 + func.varLength));
//we return all the register data from the stack
if (registerCount > 1) {
if (pushOnStack > 0)
asm.push(' POPN R' + pushOnStack);
localStackLength = 0;
}
registerCount++;
localStackLength = copyLocalStackLength;
getToken();
if (getRangOperation(thisToken) > 0)
execut();
else if (thisToken == ';')
previousToken();
}
//add a new variable to the table
function addVar(type) {
if (isIntoFunction) {
localVarTable.push(type);
localVarTable.push(thisToken);
} else {
varTable.push({
name: thisToken,
type: type,
length: 1
});
asm.push(' _' + thisToken + ' word ? ');
asm.push(' ');
}
}
//return the type and name of the variable, if one exists
function getVar(t) {
for (var i = 0; i < varTable.length; i++) {
if (varTable[i].name == t)
return varTable[i];
}
return {
name: 'null',
type: 'void',
length: 1
}
}
//process variables whose data is on the stack
function localVarToken() {
var type,
l,
op;
var point = false;
if (lastToken == '*' && registerCount == 1)
point = true;
var number = functionVarTable.indexOf(thisToken);
if (number == -1) {
number = localVarTable.indexOf(thisToken);
type = localVarTable[number - 1];
l = localStackLength * 2 + number + 1; //variable position relative to stack pointer
} else {
type = functionVarTable[number - 1];
//number += localVarTable.length;
l = localStackLength * 2 + functionVarTable.length + localVarTable.length - number + 1;
}
var token = thisToken;
getToken();
//if the variable is an array
if (thisToken == '[') {
//calculating the array cell number
while (thisToken != ']') {
getToken();
if (!thisToken)
return;
execut();
}
getToken();
//load cell array
if (thisToken != '=') {
previousToken();
if (type == 'char' || type == '*char') {
if (type == '*char' && !point) {
asm.push(' LDI R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' LDC R' + (registerCount - 1) + ',(R' + (registerCount + 1) + '+R' + (registerCount - 1) + ')');
} else
putError(lineCount, 9, '');
//info("" + lineCount + " work with local arrays is not supported");
} else {
if (type == '*int' && !point) {
asm.push(' LDIAL R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' LDC R' + (registerCount - 1) + ',(R' + (registerCount + 1) + '+R' + (registerCount - 1) + ')');
} else
putError(lineCount, 9, '');
//info("" + lineCount + " work with local arrays is not supported");
}
}
//save cell array
else {
getToken();
execut();
getToken();
//if the variable is followed by a mathematical operation, then we continue to translate the code
if (getRangOperation(thisToken) > 0)
execut();
registerCount--;
if (type == 'char' || type == '*char') {
if (type == '*char' && !point) {
asm.push(' LDI R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' STC (R' + (registerCount + 1) + '+R' + (registerCount - 1) + '),R' + registerCount);
} else {
putError(lineCount, 9, '');
//info("" + lineCount + " work with local arrays is not supported");
}
} else {
if (type == '*int' && !point) {
asm.push(' LDIAL R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' STC (R' + (registerCount + 1) + '+R' + (registerCount - 1) + '),R' + registerCount);
} else {
putError(lineCount, 9, '');
//info("" + lineCount + " work with local arrays is not supported");
}
}
registerCount--;
}
}
//get the value of a variable
else if (thisToken != '=' && thisToken != '+=' && thisToken != '-=' && thisToken != '*=' && thisToken != '/=') {
previousToken();
if (type == 'char')
asm.push(' LDC R' + registerCount + ',(' + l + '+R0) ;' + token);
else
asm.push(' LDI R' + registerCount + ',(' + l + '+R0) ;' + token);
registerCount++;
}
//assign a value to a variable
else {
op = thisToken;
getToken();
execut();
if (getRangOperation(thisToken) > 0)
execut();
getToken();
if (getRangOperation(thisToken) > 0)
execut();
registerCount--;
if (op == '+=') {
asm.push(' LDI R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' ADD R' + registerCount + ',R' + (registerCount + 1));
} else if (op == '-=') {
asm.push(' LDI R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' SUB R' + (registerCount + 1) + ',R' + registerCount);
asm.push(' MOV R' + registerCount + ',R' + (registerCount + 1));
} else if (op == '*=') {
asm.push(' LDI R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' MUL R' + registerCount + ',R' + (registerCount + 1));
} else if (op == '/=') {
asm.push(' LDI R' + (registerCount + 1) + ',(' + l + '+R0) ;' + token);
asm.push(' DIV R' + (registerCount + 1) + ',R' + registerCount);
asm.push(' MOV R' + registerCount + ',R' + (registerCount + 1));
} else
previousToken();
//---------
if (type == 'char')
asm.push(' STC (' + l + '+R0),R' + registerCount + ' ;' + token);
else
asm.push(' STI (' + l + '+R0),R' + registerCount + ' ;' + token);
}
}
//converting a string to a format understandable to assembler, with the replacement of special characters with their numeric code
function pushString() {
var s = '';
while (thisToken[0] == '"') {
for (var i = 0; i < thisToken.length; i++) {
if (thisToken[i] == ';') {
s += '",59,"';
} else if (thisToken[i] == '\\') {
i++;
if (thisToken[i] == '\\')
s += '",92,"';
else if (thisToken[i] == 'n')
s += '",10,"';
else if (thisToken[i] == 't')
s += '",9,"';
else if (thisToken[i] == '"')
s += '",34,"';
} else
s += thisToken[i];
}
getToken();
removeNewLine();
s += ',';
}
previousToken();
//dataAsm is inserted into the asm table after compilation is complete
dataAsm.push('DB ' + s + '0');
dataAsm.push(' ');
}
//add an array
function addArray(type) {
var name = lastToken;
var length = 1;
var buf = '';
getToken();
//number of items not specified
if (thisToken == ']') {
getToken();
if (thisToken != '=')
putError(lineCount, 10, '');
//info("" + lineCount + " the length of the array is not specified");
else
getToken();
//an array is a string of characters
if (thisToken[0] == '"') {
length = thisToken.length - 2;
dataAsm.push(' ');
dataAsm.push('_' + name + ':');
pushString();
varTable.push({
name: name,
type: type,
length: length
});
}
//the array is already filled, count the number of elements
else if (thisToken == '{') {
while (thisToken && thisToken != '}') {
getToken();
removeNewLine();
if (!thisToken)
return;
if (isNumber(parseInt(thisToken)))
buf += parseInt(thisToken) + ',';
else if (isVar(thisToken))
buf += '_' + thisToken + ',';
else
buf += '0,';
length++;
getToken();
removeNewLine();
if (!(thisToken == '}' || thisToken == ','))
putError(lineCount, 11, '');
//info("" + lineCount + " invalid array declaration");
}
if (type == 'int') {
dataAsm.push('_' + name + ': \n DW ' + buf.substring(0, buf.length - 1));
dataAsm.push(' ');
} else if (type == 'char') {
dataAsm.push('_' + name + ': \n DB ' + buf.substring(0, buf.length - 1));
dataAsm.push(' ');
}
varTable.push({
name: name,
type: type,
length: length
});
}
}
//number of items indicated
else if (isNumber(thisToken)) {
length = thisToken * 1 + 1;
var newArr = '';
if (type == 'char')
newArr = (' _' + name + ' byte ' + length + ' dup(?)');
else
newArr = (' _' + name + ' word ' + length + ' dup(?)');
varTable.push({
name: name,
type: type,
length: length
});
getToken();
if (thisToken != ']')
putError(lineCount, 11, '');
//info("" + lineCount + " invalid array declaration");
getToken();
if (thisToken == '=') {
getToken();
if (thisToken != '{')
putError(lineCount, 11, '');
var nlength = 1;
while (thisToken && thisToken != '}') {
getToken();
removeNewLine();
if (!thisToken)
return;
if (isNumber(parseInt(thisToken)))
buf += parseInt(thisToken) + ',';
else if (isVar(thisToken))
buf += '_' + thisToken + ',';
else
buf += '0,';
nlength++;
getToken();
removeNewLine();
if (!(thisToken == '}' || thisToken == ','))
putError(lineCount, 11, '');
//info("" + lineCount + " invalid array declaration");
}
if (type == 'int')
newArr = ('_' + name + ': \n DW ' + buf.substring(0, buf.length - 1));
else if (type == 'char')
newArr = ('_' + name + ': \n DB ' + buf.substring(0, buf.length - 1));
if (nlength < length) {
console.log(nlength);
for (var i = nlength; i <= length; i++)
newArr += ',0';
} else
length = nlength;
varTable.push({
name: name,
type: type,
length: length
});
}
dataAsm.push(newArr);
dataAsm.push(' ');
} else
putError(lineCount, 11, '');
//info("" + lineCount + " invalid array declaration");
}
//checking if token t is a function
function isFunction(t) {
for (var i = 0; i < functionTable.length; i++) {
if (functionTable[i].name == t)
return true;
}
return false;
}
//checking if token t is a variable
function isVar(t) {
for (var i = 0; i < varTable.length; i++) {
if (varTable[i].name == t)
return true;
}
return false;
}
//checking if the token t is a type declaration
function isType(t) {
if (t == 'int' || t == 'char' || t == 'void')
return true;
if (t == '*int' || t == '*char' || t == '*void')
return true;
return false;
}
//checking if token t is a number
function isNumber(t) {
return !isNaN(parseFloat(t)) && isFinite(t);
}
//process the variable
function varToken() {
var v = getVar(thisToken);
var point = false;
var op;
var thisLine = lineCount;
if (lastToken == '*' && registerCount == 1)
point = true;
getToken();
//if the variable is an array
if (thisToken == '[') {
//calculating the array cell number
getToken();
while (thisToken != ']') {
if (!thisToken) {
putError(thisLine, 18, '');
return;
}
execut();
if (getRangOperation(thisToken) == 0 && thisToken != ']') {
getToken();
execut();
}
}
getToken();
//load cell array
if (thisToken != '=' && thisToken != '+=' && thisToken != '-=' && thisToken != '*=' && thisToken != '/=') {
previousToken();
if (v.type == 'char' || v.type == '*char') {
if (v.type == '*char' && !point) {
asm.push(' LDI R' + registerCount + ',(_' + v.name + ')');
asm.push(' LDC R' + (registerCount - 1) + ',(R' + registerCount + '+R' + (registerCount - 1) + ')');
} else
asm.push(' LDC R' + (registerCount - 1) + ',(_' + v.name + '+R' + (registerCount - 1) + ')');
} else {
if (v.type == '*int' && !point) {