/
main.c
1176 lines (1058 loc) · 28.2 KB
/
main.c
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
/*
Copyright (c) 2023 Masahiro Oono
This software is a translator for HL.
HL (Haribote Language) is a programming language
designed in 2021 by Hidemi Kawai.
https://essen.osask.jp/?a21_txt01
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#if defined(__APPLE__) || defined(__linux__)
#include <unistd.h>
#include <termios.h>
#endif
typedef unsigned char *String;
int loadText(String path, String text, int size)
{
unsigned char buf[1000];
int startPos = path[0] == '"'; // ダブルクォートがあれば外す
int i = 0;
while (path[startPos + i] != 0 && path[startPos + i] != '"') {
buf[i] = path[startPos + i];
++i;
}
buf[i] = 0;
FILE *fp = fopen(buf, "rt");
if (fp == NULL) {
printf("Failed to open %s\n", path);
return 1;
}
int nItems = fread(text, 1, size - 1, fp);
fclose(fp);
text[nItems] = 0;
return 0;
}
#define MAX_TOKEN_CODE 1000 // トークンコードの最大値
String tokenStrs[MAX_TOKEN_CODE + 1];
int tokenLens[MAX_TOKEN_CODE + 1];
int vars[MAX_TOKEN_CODE + 1];
int getTokenCode(String str, int len)
{
static unsigned char tokenBuf[(MAX_TOKEN_CODE + 1) * 10];
static int nTokens = 0, unusedHead = 0; // 登録済みのトークンの数, 未使用領域へのポインタ
int i;
for (i = 0; i < nTokens; ++i) { // 登録済みのトークンコードの中から探す
if (len == tokenLens[i] && strncmp(str, tokenStrs[i], len) == 0)
break;
}
if (i == nTokens) {
if (nTokens >= MAX_TOKEN_CODE) {
printf("Too many tokens\n");
exit(1);
}
strncpy(&tokenBuf[ unusedHead ], str, len); // 見つからなければ新規登録
tokenBuf[ unusedHead + len ] = 0;
tokenStrs[i] = &tokenBuf[ unusedHead ];
tokenLens[i] = len;
unusedHead += len + 1;
++nTokens;
vars[i] = strtol(tokenStrs[i], NULL, 0); // 定数であれば初期値を設定(定数でなければ0になる)
}
return i;
}
inline static int isAlphabet(unsigned char ch)
{
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') || ch == '_';
}
inline static int isNumber(unsigned char ch)
{
return '0' <= ch && ch <= '9';
}
int lexer(String str, int *tc)
{
int pos = 0, nTokens = 0; // 現在読んでいる位置, これまでに変換したトークンの数
int len;
for (;;) {
while (str[pos] == ' ' || str[pos] == '\t' || str[pos] == '\n' || str[pos] == '\r')
++pos;
if (str[pos] == 0)
return nTokens;
len = 0;
if (strchr("(){}[];,", str[pos]) != NULL)
len = 1;
else if (isAlphabet(str[pos]) || isNumber(str[pos])) {
while (isAlphabet(str[pos + len]) || isNumber(str[pos + len]))
++len;
}
else if (strchr("=+-*/!%&~|<>?:.#", str[pos]) != NULL) {
while (strchr("=+-*/!%&~|<>?:.#", str[pos + len]) != NULL && str[pos + len] != 0)
++len;
}
else {
printf("Lexing error: %.10s\n", &str[pos]);
exit(1);
}
tc[nTokens] = getTokenCode(&str[pos], len);
pos += len;
++nTokens;
}
}
int tc[10000]; // トークンコード列を格納する
enum {
PlusPlus,
Equal,
NotEq,
Les,
GtrEq,
LesEq,
Gtr,
Plus,
Minus,
Multi,
Divi,
Mod,
And,
ShiftRight,
Assign,
Lparen,
Rparen,
Lbracket,
Rbracket,
Lbrace,
Rbrace,
Period,
Comma,
Semicolon,
Colon,
Print,
Time,
Goto,
If,
Else,
For,
Continue,
Break,
Wildcard,
Expr,
Expr0,
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Tmp0,
Tmp1,
Tmp2,
Tmp3,
Tmp4,
Tmp5,
Tmp6,
Tmp7,
Tmp8,
Tmp9,
EndOfKeys
};
String defaultTokens[] = {
"++",
"==",
"!=",
"<",
">=",
"<=",
">",
"+",
"-",
"*",
"/",
"%",
"&",
">>",
"=",
"(",
")",
"[",
"]",
"{",
"}",
".",
",",
";",
":",
"print",
"time",
"goto",
"if",
"else",
"for",
"continue",
"break",
"!!*",
"!!**",
"!!***",
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"_t0",
"_t1",
"_t2",
"_t3",
"_t4",
"_t5",
"_t6",
"_t7",
"_t8",
"_t9",
};
void initTc(String *defaultTokens, int len)
{
assert(len == EndOfKeys);
for (int i = 0; i < len; ++i)
tc[i] = getTokenCode(defaultTokens[i], strlen(defaultTokens[i]));
}
typedef enum {
Prefix_PlusPlus = 2,
Prefix_Minus = 2,
Infix_Multi = 4,
Infix_Divi = 4,
Infix_Mod = 4,
Infix_Plus = 5,
Infix_Minus = 5,
Infix_ShiftRight = 6,
Infix_LesEq = 7,
Infix_GtrEq = 7,
Infix_Les = 7,
Infix_Gtr = 7,
Infix_Equal = 8,
Infix_NotEq = 8,
Infix_And = 9,
Infix_Assign = 15,
LowestPrecedence = 99,
NoPrecedence = 100
} Precedence;
Precedence precedenceTable[][2] = {
[PlusPlus] = {NoPrecedence, Prefix_PlusPlus},
[Equal] = {Infix_Equal, NoPrecedence},
[NotEq] = {Infix_NotEq, NoPrecedence},
[LesEq] = {Infix_LesEq, NoPrecedence},
[GtrEq] = {Infix_GtrEq, NoPrecedence},
[Les] = {Infix_Les, NoPrecedence},
[Gtr] = {Infix_Gtr, NoPrecedence},
[Plus] = {Infix_Plus, NoPrecedence},
[Minus] = {Infix_Minus, Prefix_Minus},
[Multi] = {Infix_Multi, NoPrecedence},
[Divi] = {Infix_Divi, NoPrecedence},
[Mod] = {Infix_Mod, NoPrecedence},
[And] = {Infix_And, NoPrecedence},
[ShiftRight] = {Infix_ShiftRight, NoPrecedence},
[Assign] = {Infix_Assign, NoPrecedence},
};
enum { Infix, Prefix, EndOfStyles };
inline static Precedence getPrecedence(int style, int operator)
{
assert(0 <= style && style < EndOfStyles);
return 0 <= operator && operator <= Assign
? precedenceTable[operator][style]
: NoPrecedence;
}
#define MAX_PHRASE_LEN 31
#define N_WILDCARDS 10
int phraseTc[(MAX_PHRASE_LEN + 1) * 100]; // フレーズを字句解析して得たトークンコード列を格納する
int wpc[N_WILDCARDS * 2]; // ワイルドカードにマッチしたトークンを指す
int nextPc; // マッチしたフレーズの末尾の次のトークンを指す
inline static int End_(int num)
{
return N_WILDCARDS + num;
}
int match(int id, String phrase, int pc)
{
int head = id * (MAX_PHRASE_LEN + 1), phraseLen;
if (phraseTc[head + MAX_PHRASE_LEN] == 0) {
phraseLen = lexer(phrase, &phraseTc[head]);
assert(phraseLen <= MAX_PHRASE_LEN);
phraseTc[head + MAX_PHRASE_LEN] = phraseLen;
}
phraseLen = phraseTc[head + MAX_PHRASE_LEN];
for (int pos = 0; pos < phraseLen; ++pos) {
int phraTc = phraseTc[head + pos];
if (phraTc == Wildcard || phraTc == Expr || phraTc == Expr0) {
++pos;
int num = phraseTc[head + pos] - Zero;
wpc[num] = pc; // トークンの位置(式の場合は式の開始位置)
if (phraTc == Wildcard) {
++pc;
continue;
}
int depth = 0; // 括弧の深さ
for (;;) {
if (tc[pc] == Semicolon)
break;
if (tc[pc] == Comma && depth == 0)
break;
if (tc[pc] == Lparen || tc[pc] == Lbracket)
++depth;
if (tc[pc] == Rparen || tc[pc] == Rbracket)
--depth;
if (depth < 0)
break;
++pc;
}
wpc[End_(num)] = pc; // 式の終了位置
if (phraTc == Expr && wpc[num] == pc)
return 0;
if (depth > 0)
return 0;
continue;
}
if (phraTc != tc[pc])
return 0;
++pc;
}
nextPc = pc;
return 1;
}
typedef int *IntPtr;
IntPtr internalCodes[10000]; // ソースコードをコンパイルして生成した内部コードを格納する
IntPtr *icp;
typedef enum {
OpEnd,
OpCpy,
OpCeq,
OpCne,
OpClt,
OpCge,
OpCle,
OpCgt,
OpAdd,
OpSub,
OpMul,
OpDiv,
OpMod,
OpBand,
OpShr,
OpAdd1,
OpNeg,
OpGoto,
OpJeq,
OpJne,
OpJlt,
OpJge,
OpJle,
OpJgt,
OpLop,
OpPrint,
OpTime,
} Opcode;
void putIc(Opcode op, IntPtr p1, IntPtr p2, IntPtr p3, IntPtr p4)
{
icp[0] = (IntPtr) op;
icp[1] = p1;
icp[2] = p2;
icp[3] = p3;
icp[4] = p4;
icp += 5;
}
#define N_TMPS 10
char tmpFlags[N_TMPS];
int tmpAlloc()
{
int i = 0;
while (tmpFlags[i] != 0) {
assert(i < N_TMPS);
++i;
}
tmpFlags[i] = 1;
return Tmp0 + i;
}
void tmpFree(int i)
{
if (Tmp0 <= i && i <= Tmp9)
tmpFlags[i - Tmp0] = 0;
}
int epc, epcEnd; // expression()のためのpc, その式の直後のトークンを指す
int evalExpression(Precedence precedence);
int expression(int num);
inline static Opcode getOpcode(int i) // for infix operators
{
assert(Equal <= i && i < Assign);
return OpCeq + i - Equal;
}
int evalInfixExpression(int lhs, Precedence precedence, int op)
{
++epc;
int rhs = evalExpression(precedence);
int res = tmpAlloc();
putIc(getOpcode(op), &vars[res], &vars[lhs], &vars[rhs], 0);
tmpFree(lhs);
tmpFree(rhs);
if (lhs < 0 || rhs < 0)
return -1;
return res;
}
int evalExpression(Precedence precedence)
{
int res = -1, e0 = 0;
nextPc = 0;
if (match(99, "( !!**0 )", epc)) { // 括弧
res = expression(0);
}
else if (tc[epc] == PlusPlus) { // 前置インクリメント
++epc;
res = evalExpression(getPrecedence(Prefix, PlusPlus));
putIc(OpAdd1, &vars[res], 0, 0, 0);
}
else if (tc[epc] == Minus) { // 単項マイナス
++epc;
e0 = evalExpression(getPrecedence(Prefix, Minus));
res = tmpAlloc();
putIc(OpNeg, &vars[res], &vars[e0], 0, 0);
}
else { // 変数もしくは定数
res = tc[epc];
++epc;
}
if (nextPc > 0)
epc = nextPc;
for (;;) {
tmpFree(e0);
if (res < 0 || e0 < 0) // ここまででエラーがあれば、処理を打ち切り
return -1;
if (epc >= epcEnd)
break;
Precedence encountered; // ぶつかった演算子の優先順位を格納する
e0 = 0;
if (tc[epc] == PlusPlus) { // 後置インクリメント
++epc;
e0 = res;
res = tmpAlloc();
putIc(OpCpy, &vars[res], &vars[e0], 0, 0);
putIc(OpAdd1, &vars[e0], 0, 0, 0);
}
else if (precedence >= (encountered = getPrecedence(Infix, tc[epc]))) {
/*
「引数として渡された優先順位」が「ぶつかった演算子の優先順位」よりも
低いか又は等しい(値が大きいか又は等しい)ときは、このブロックを実行して
中置演算子を評価する。
「引数として渡された優先順位」が「ぶつかった演算子の優先順位」よりも
高い(値が小さい)ときは、このブロックを実行せずにこれまでに式を評価した
結果を呼び出し元に返す。
*/
switch (tc[epc]) {
case Multi: case Divi: case Mod:
case Plus: case Minus:
case ShiftRight:
case Les: case LesEq: case Gtr: case GtrEq:
case Equal: case NotEq:
case And:
res = evalInfixExpression(res, encountered - 1, tc[epc]);
break;
case Assign:
++epc;
e0 = evalExpression(encountered);
putIc(OpCpy, &vars[res], &vars[e0], 0, 0);
break;
}
}
else
break;
}
return res;
}
// 引数として渡したワイルドカード番号にマッチした式をコンパイルしてinternalCodes[]に書き込む
int expression(int num)
{
if (wpc[num] == wpc[End_(num)])
return 0;
int i, end = N_WILDCARDS * 2, buf[end + 1];
for (i = 0; i < end; ++i)
buf[i] = wpc[i];
buf[i] = nextPc;
int oldEpc = epc, oldEpcEnd = epcEnd;
epc = wpc[num]; epcEnd = wpc[End_(num)];
int res = evalExpression(LowestPrecedence);
if (epc < epcEnd)
return -1;
for (i = 0; i < end; ++i)
wpc[i] = buf[i];
nextPc = buf[i];
epc = oldEpc; epcEnd = oldEpcEnd;
return res;
}
enum { ConditionIsTrue, ConditionIsFalse };
// 条件式wpc[i]を評価して、その結果に応じてlabelに分岐する内部コードを生成する
void ifgoto(int i, int not, int label)
{
int begin = wpc[i];
if (begin + 3 == wpc[End_(i)] && Equal <= tc[begin + 1] && tc[begin + 1] <= Gtr) {
Opcode op = OpJeq + ((tc[begin + 1] - Equal) ^ not);
putIc(op, &vars[label], &vars[tc[begin]], &vars[tc[begin + 2]], 0);
}
else {
i = expression(i);
putIc(OpJne - not, &vars[label], &vars[i], &vars[Zero], 0);
tmpFree(i);
}
}
int tmpLabelNo;
int tmpLabelAlloc()
{
char str[10];
sprintf(str, "_l%d", tmpLabelNo);
++tmpLabelNo;
return getTokenCode(str, strlen(str));
}
#define BLOCK_INFO_SIZE 10
int blockInfo[BLOCK_INFO_SIZE * 100], blockDepth, loopDepth;
enum { BlockType, IfBlock, ForBlock };
enum { IfLabel0 = 1, IfLabel1 };
enum { ForBegin = 1, ForContinue, ForBreak, ForDepth, ForWpc1, ForWpcEnd1, ForWpc2, ForWpcEnd2 };
inline static int *initBlockInfo()
{
blockDepth = loopDepth = 0;
return blockInfo;
}
inline static int *beginBlock()
{
blockDepth += BLOCK_INFO_SIZE;
return &blockInfo[blockDepth];
}
inline static int *endBlock()
{
blockDepth -= BLOCK_INFO_SIZE;
return &blockInfo[blockDepth];
}
inline static void startLoop(int **loopBlock)
{
blockInfo[blockDepth + ForDepth] = loopDepth;
loopDepth = blockDepth;
*loopBlock = &blockInfo[loopDepth];
}
inline static void stopLoop(int **loopBlock)
{
loopDepth = blockInfo[blockDepth + ForDepth];
*loopBlock = loopDepth == 0 ? NULL : &blockInfo[loopDepth];
}
inline static void saveExpr(int i)
{
assert(blockInfo[blockDepth + BlockType] == ForBlock);
blockInfo[blockDepth + ForWpc1 - 2 + 2 * i] = wpc[i];
blockInfo[blockDepth + ForWpc1 - 2 + 2 * i + 1] = wpc[End_(i)];
}
inline static void restoreExpr(int i)
{
assert(blockInfo[blockDepth + BlockType] == ForBlock);
wpc[i] = blockInfo[blockDepth + ForWpc1 - 2 + 2 * i];
wpc[End_(i)] = blockInfo[blockDepth + ForWpc1 - 2 + 2 * i + 1];
}
int compile(String src)
{
int nTokens = lexer(src, tc);
tc[nTokens++] = Semicolon; // 末尾に「;」を付け忘れることが多いので、付けてあげる
tc[nTokens] = tc[nTokens + 1] = tc[nTokens + 2] = tc[nTokens + 3] = Period; // エラー表示用
icp = internalCodes;
for (int i = 0; i < N_TMPS; ++i)
tmpFlags[i] = 0;
tmpLabelNo = 0;
int *curBlock = initBlockInfo(), *loopBlock = NULL;
int pc;
for (pc = 0; pc < nTokens;) {
int e0 = 0, e2 = 0;
if (match(0, "!!*0 = !!*1;", pc)) {
putIc(OpCpy, &vars[tc[wpc[0]]], &vars[tc[wpc[1]]], 0, 0);
}
else if (match(10, "!!*0 = !!*1 + 1; if (!!*2 < !!*3) goto !!*4;", pc) && tc[wpc[0]] == tc[wpc[1]] && tc[wpc[0]] == tc[wpc[2]]) {
putIc(OpLop, &vars[tc[wpc[4]]], &vars[tc[wpc[0]]], &vars[tc[wpc[3]]], 0);
}
else if (match(9, "!!*0 = !!*1 + 1;", pc) && tc[wpc[0]] == tc[wpc[1]]) { // +1専用の命令
putIc(OpAdd1, &vars[tc[wpc[0]]], 0, 0, 0);
}
else if (match(1, "!!*0 = !!*1 + !!*2;", pc)) {
putIc(OpAdd, &vars[tc[wpc[0]]], &vars[tc[wpc[1]]], &vars[tc[wpc[2]]], 0);
}
else if (match(2, "!!*0 = !!*1 - !!*2;", pc)) {
putIc(OpSub, &vars[tc[wpc[0]]], &vars[tc[wpc[1]]], &vars[tc[wpc[2]]], 0);
}
else if (match(3, "print !!**0;", pc)) {
e0 = expression(0);
putIc(OpPrint, &vars[e0], 0, 0, 0);
}
else if (match(4, "!!*0:", pc)) { // ラベル定義命令
vars[tc[wpc[0]]] = icp - internalCodes; // ラベル名の変数にその時のicpの相対位置を入れておく
}
else if (match(5, "goto !!*0;", pc)) {
putIc(OpGoto, &vars[tc[wpc[0]]], 0, 0, 0);
}
else if (match(6, "if (!!**0) goto !!*1;", pc)) {
ifgoto(0, ConditionIsTrue, tc[wpc[1]]);
}
else if (match(7, "time;", pc)) {
putIc(OpTime, 0, 0, 0, 0);
}
else if (match(11, "if (!!**0) {", pc)) { // if文
curBlock = beginBlock();
curBlock[ BlockType ] = IfBlock;
curBlock[ IfLabel0 ] = tmpLabelAlloc(); // 条件不成立のときの飛び先
curBlock[ IfLabel1 ] = 0;
ifgoto(0, ConditionIsFalse, curBlock[IfLabel0]);
}
else if (match(13, "} else {", pc) && curBlock[BlockType] == IfBlock) {
curBlock[IfLabel1] = tmpLabelAlloc(); // else節の終端
putIc(OpGoto, &vars[curBlock[IfLabel1]], 0, 0, 0);
vars[curBlock[IfLabel0]] = icp - internalCodes;
}
else if (match(12, "}", pc) && curBlock[BlockType] == IfBlock) {
int ifLabel = curBlock[IfLabel1] ? IfLabel1 : IfLabel0;
vars[curBlock[ifLabel]] = icp - internalCodes;
curBlock = endBlock();
}
else if (match(14, "for (!!***0; !!***1; !!***2) {", pc)) { // for文
curBlock = beginBlock();
curBlock[ BlockType ] = ForBlock;
curBlock[ ForBegin ] = tmpLabelAlloc();
curBlock[ ForContinue ] = tmpLabelAlloc();
curBlock[ ForBreak ] = tmpLabelAlloc();
startLoop(&loopBlock);
e0 = expression(0);
saveExpr(1);
if (wpc[1] < wpc[End_(1)])
ifgoto(1, ConditionIsFalse, curBlock[ForBreak]);
saveExpr(2);
vars[curBlock[ForBegin]] = icp - internalCodes;
}
else if (match(12, "}", pc) && curBlock[BlockType] == ForBlock) {
vars[curBlock[ForContinue]] = icp - internalCodes;
restoreExpr(2);
e2 = expression(2);
restoreExpr(1);
if (wpc[1] < wpc[End_(1)])
ifgoto(1, ConditionIsTrue, curBlock[ForBegin]);
else
putIc(OpGoto, &vars[curBlock[ForBegin]], 0, 0, 0);
vars[curBlock[ForBreak]] = icp - internalCodes;
stopLoop(&loopBlock);
curBlock = endBlock();
}
else if (match(15, "continue;", pc) && loopBlock) {
putIc(OpGoto, &vars[loopBlock[ForContinue]], 0, 0, 0);
}
else if (match(16, "break;", pc) && loopBlock) {
putIc(OpGoto, &vars[loopBlock[ForBreak]], 0, 0, 0);
}
else if (match(17, "if (!!**0) continue;", pc) && loopBlock) {
ifgoto(0, ConditionIsTrue, loopBlock[ForContinue]);
}
else if (match(18, "if (!!**0) break;", pc) && loopBlock) {
ifgoto(0, ConditionIsTrue, loopBlock[ForBreak]);
}
else if (match(8, "!!***0;", pc)) {
e0 = expression(0);
}
else {
goto err;
}
tmpFree(e0);
tmpFree(e2);
if (e0 < 0 || e2 < 0)
goto err;
pc = nextPc;
}
if (blockDepth > 0) {
printf("Block nesting error: blockDepth=%d loopDepth=%d", blockDepth, loopDepth);
return -1;
}
putIc(OpEnd, 0, 0, 0, 0);
IntPtr *end = icp;
Opcode op;
for (icp = internalCodes; icp < end; icp += 5) { // goto先の設定
op = (Opcode) icp[0];
if (OpGoto <= op && op <= OpLop)
icp[1] = (IntPtr) (internalCodes + *icp[1]);
}
return end - internalCodes;
err:
printf("Syntax error: %s %s %s %s\n", tokenStrs[tc[pc]], tokenStrs[tc[pc + 1]], tokenStrs[tc[pc + 2]], tokenStrs[tc[pc + 3]]);
return 1;
}
void exec()
{
clock_t begin = clock();
icp = internalCodes;
int i;
for (;;) {
switch ((Opcode) icp[0]) {
case OpEnd:
return;
case OpNeg: *icp[1] = -*icp[2]; icp += 5; continue;
case OpAdd1: ++(*icp[1]); icp += 5; continue;
case OpMul: *icp[1] = *icp[2] * *icp[3]; icp += 5; continue;
case OpDiv: *icp[1] = *icp[2] / *icp[3]; icp += 5; continue;
case OpMod: *icp[1] = *icp[2] % *icp[3]; icp += 5; continue;
case OpAdd: *icp[1] = *icp[2] + *icp[3]; icp += 5; continue;
case OpSub: *icp[1] = *icp[2] - *icp[3]; icp += 5; continue;
case OpShr: *icp[1] = *icp[2] >> *icp[3]; icp += 5; continue;
case OpClt: *icp[1] = *icp[2] < *icp[3]; icp += 5; continue;
case OpCle: *icp[1] = *icp[2] <= *icp[3]; icp += 5; continue;
case OpCgt: *icp[1] = *icp[2] > *icp[3]; icp += 5; continue;
case OpCge: *icp[1] = *icp[2] >= *icp[3]; icp += 5; continue;
case OpCeq: *icp[1] = *icp[2] == *icp[3]; icp += 5; continue;
case OpCne: *icp[1] = *icp[2] != *icp[3]; icp += 5; continue;
case OpBand: *icp[1] = *icp[2] & *icp[3]; icp += 5; continue;
case OpCpy: *icp[1] = *icp[2]; icp += 5; continue;
case OpPrint:
printf("%d\n", *icp[1]);
icp += 5;
continue;
case OpGoto: icp = (IntPtr *) icp[1]; continue;
case OpJeq: if (*icp[2] == *icp[3]) { icp = (IntPtr *) icp[1]; continue; } icp += 5; continue;
case OpJne: if (*icp[2] != *icp[3]) { icp = (IntPtr *) icp[1]; continue; } icp += 5; continue;
case OpJle: if (*icp[2] <= *icp[3]) { icp = (IntPtr *) icp[1]; continue; } icp += 5; continue;
case OpJge: if (*icp[2] >= *icp[3]) { icp = (IntPtr *) icp[1]; continue; } icp += 5; continue;
case OpJlt: if (*icp[2] < *icp[3]) { icp = (IntPtr *) icp[1]; continue; } icp += 5; continue;
case OpJgt: if (*icp[2] > *icp[3]) { icp = (IntPtr *) icp[1]; continue; } icp += 5; continue;
case OpTime:
printf("time: %.3f[sec]\n", (clock() - begin) / (double) CLOCKS_PER_SEC);
icp += 5;
continue;
case OpLop:
i = *icp[2];
++i;
*icp[2] = i;
if (i < *icp[3]) {
icp = (IntPtr *) icp[1];
continue;
}
icp += 5;
continue;
}
}
}
int run(String src)
{
if (compile(src) < 0)
return 1;
exec();
return 0;
}
String removeTrailingSemicolon(String str, size_t len) {
for (int i = len - 1; i >= 0; --i) {
if (str[i] != ';')
continue;
str[i] = 0;
return &str[i];
}
return NULL;
}
#if defined(__APPLE__) || defined(__linux__)
struct termios initial_term;
void loadHistory();
void initTerm()
{
tcgetattr(0, &initial_term);
loadHistory();
}
void saveHistory();
void destroyTerm()
{
saveHistory();
}
inline static void setNonCanonicalMode()
{
struct termios new_term;
new_term = initial_term;
new_term.c_oflag |= ONOCR;
new_term.c_lflag &= ~(ICANON | ECHO);
new_term.c_cc[VMIN] = 1;
new_term.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &new_term);
}
inline static void setCanonicalMode()
{
tcsetattr(0, TCSANOW, &initial_term);
}
int cursorX;
inline static void eraseLine()
{
printf("\e[2K\r");
cursorX = 0;
}
inline static void eraseAll()
{
printf("\e[2J\e[H");
cursorX = 0;
}
#else
void initTerm() {}
void destroyTerm() {}
#endif
#define LINE_SIZE 100
#if defined(__APPLE__) || defined(__linux__)
#define HISTORY_SIZE 100
typedef struct { char str[LINE_SIZE]; int len; } Command;
typedef struct {
Command buf[HISTORY_SIZE];
int head, tail, count, pos;
} CmdHistory;
CmdHistory cmdHist;
void setHistory(char *cmd, int len)
{
if (len == 0)
return;
strncpy((char *) &cmdHist.buf[cmdHist.tail].str, cmd, len);
cmdHist.buf[cmdHist.tail].str[len] = 0;
cmdHist.buf[cmdHist.tail].len = len;
if (cmdHist.count < HISTORY_SIZE)
++cmdHist.count;
else
cmdHist.head = (cmdHist.head + 1) % HISTORY_SIZE;
cmdHist.tail = (cmdHist.tail + 1) % HISTORY_SIZE;
}
enum { Prev, Next };
void showHistory(int dir, char *buf)
{
if (cmdHist.count == 0)
return;
if (dir == Prev && cmdHist.pos < cmdHist.count)
++cmdHist.pos;
else if (dir == Prev && cmdHist.pos >= cmdHist.count)
cmdHist.pos = cmdHist.count;
else if (dir == Next && cmdHist.pos > 1)
--cmdHist.pos;
else if (dir == Next && cmdHist.pos <= 1) {
cmdHist.pos = 0;
return;
}
int i = (cmdHist.head + cmdHist.count - cmdHist.pos) % cmdHist.count;
Command *cmd = &cmdHist.buf[i];
printf("%s", cmd->str);
strncpy(buf, cmd->str, cmd->len + 1);
cursorX = cmd->len;
}
void saveHistory()
{
FILE *fp;
if (cmdHist.count > 0 && (fp = fopen(".haribote_history", "wt")) == NULL)
return;
int counter = cmdHist.count;
while (counter > 0) {
int i = (cmdHist.head + cmdHist.count - counter) % cmdHist.count;
fprintf(fp, "%s\n", cmdHist.buf[i].str);
--counter;
}
fclose(fp);
}
void loadHistory()
{
FILE *fp;
if ((fp = fopen(".haribote_history", "rt")) == NULL)
return;
for (int i = 0; i < HISTORY_SIZE; ++i) {
char line[LINE_SIZE];
if (fgets(line, LINE_SIZE, fp) == NULL)
break;
setHistory(line, strlen(line) - 1);
}
fclose(fp);
}
char *readLine(char *str, int size, FILE *stream)
{
assert(size > 0);
setNonCanonicalMode();
int i = cursorX ? cursorX : 0, end = size - 1, ch, nDeleted = 0, nInserted = 0;
char insertBuf[LINE_SIZE + 1] = "";
while ((i < end) && ((ch = fgetc(stream)) != EOF)) {
if (nInserted > 0 && (ch < 32 || ch == 127)) {
memmove(&str[cursorX], &str[cursorX - nInserted], insertBuf[LINE_SIZE]);
strncpy(&str[cursorX - nInserted], insertBuf, nInserted);
insertBuf[0] = nInserted = 0;
}
if (ch == 8 || ch == 127) { // Backspace or Delete
if (cursorX == 0)
continue;
write(0, "\e[D\e[K", 6);
if (cursorX < i) {