-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1159 lines (1049 loc) · 40.4 KB
/
main.py
File metadata and controls
1159 lines (1049 loc) · 40.4 KB
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
import sys, threading, time
environment = {}
user_types = {}
user_functions = {}
class ReturnException(Exception):
def __init__(self, value):
super().__init__("ReturnException")
self.value = value
class BreakException(Exception):
pass
class ContinueException(Exception):
pass
class Token:
def __init__(self, ttype, value):
self.type = ttype
self.value = value
def __repr__(self):
return f"Token({self.type}, {self.value})"
def tokenize(code):
tokens = []
i = 0
while i < len(code):
c = code[i]
# 다중행 주석 /* ... */
if c == '/' and i+1 < len(code) and code[i+1] == '*':
i += 2
while i < len(code)-1:
if code[i] == '*' and code[i+1] == '/':
i += 2
break
i += 1
continue
# 한줄 주석 // or #
if (c == '/' and i+1 < len(code) and code[i+1] == '/') or c == '#':
while i < len(code) and code[i] != '\n':
i += 1
continue
if c.isspace():
i += 1
continue
# 식별자(알파벳/언더스코어 시작)
if c.isalpha() or c=='_':
start = i
while i < len(code) and (code[i].isalnum() or code[i]=='_'):
i += 1
word = code[start:i]
tokens.append(Token("IDENT", word))
continue
# 숫자
if c.isdigit():
start = i
dot_count = 0
while i < len(code) and (code[i].isdigit() or code[i]=='.'):
if code[i]=='.':
dot_count += 1
i += 1
num_str = code[start:i]
if dot_count>0:
tokens.append(Token("NUMBER_FL", float(num_str)))
else:
tokens.append(Token("NUMBER_NUM", int(num_str)))
continue
# 문자열
if c=='"':
i += 1
start = i
while i < len(code) and code[i]!='"':
if code[i]=='\\' and i+1<len(code):
i += 1
i += 1
string_val = code[start:i].encode().decode("unicode_escape")
i += 1
tokens.append(Token("STRING", string_val))
continue
# 세미콜론
if c==';':
tokens.append(Token("SEMICOLON", ';'))
i += 1
continue
# 2글자 연산자(>=, <= 등), 단일
if c in ['>', '<', '=', '!']:
if i+1<len(code) and code[i+1]=='=':
tokens.append(Token("SYMBOL", c+'='))
i += 2
else:
tokens.append(Token("SYMBOL", c))
i += 1
continue
# 기타 기호
tokens.append(Token("SYMBOL", c))
i += 1
return tokens
class Parser:
def __init__(self, tokens):
self.tokens = tokens
self.pos = 0
def current_token(self):
if self.pos < len(self.tokens):
return self.tokens[self.pos]
return Token("EOF", None)
def advance(self):
self.pos += 1
def peek_token(self, offset=1):
idx = self.pos+offset
if idx < len(self.tokens):
return self.tokens[idx]
return Token("EOF", None)
def parse_program(self):
statements = []
while self.current_token().type!="EOF":
stmt = self.parse_statement()
if stmt:
statements.append(stmt)
return statements
def parse_statement(self):
t = self.current_token()
if t.type=="IDENT":
if t.value=="use":
return self.parse_use_stmt()
if t.value=="newtype":
return self.parse_newtype_stmt()
if t.value=="func":
return self.parse_func_decl()
if t.value=="always":
return self.parse_always_stmt()
if t.value=="if":
return self.parse_if_stmt()
if t.value=="while":
return self.parse_while_stmt()
if t.value=="return":
return self.parse_return_stmt()
if t.value in ["break","continue"]:
self.advance()
if self.current_token().type=="SEMICOLON":
self.advance()
return (t.value+"_stmt",)
# 변수 선언
# ex) num x = 10;
if (self.peek_token(1).type=="IDENT" and
self.peek_token(2).type=="SYMBOL" and
self.peek_token(2).value=='='):
return self.parse_var_decl()
# 그 외
return self.parse_expr_statement()
def parse_use_stmt(self):
# use { 모듈이름 };
self.advance() # 'use'
if self.current_token().type!="SYMBOL" or self.current_token().value!='{':
raise Exception("use 오류: '{' 필요")
self.advance()
if self.current_token().type!="IDENT":
raise Exception("use 오류: 모듈 이름 필요")
modname = self.current_token().value
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='}':
raise Exception("use 오류: '}' 필요")
self.advance()
if self.current_token().type=="SEMICOLON":
self.advance()
return ("use", modname)
def parse_newtype_stmt(self):
# newtype <타입이름>:
# <필드타입> <필드이름>;
# func <메서드>...
# end;
self.advance() # 'newtype'
if self.current_token().type!="IDENT":
raise Exception("newtype 오류: 타입 이름 필요")
tname = self.current_token().value
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("newtype 오류: ':' 필요")
self.advance()
fields=[]
methods=[]
while True:
tk = self.current_token()
# end; 이면 종료
if tk.type=="IDENT" and tk.value=="end":
if self.peek_token(1).type=="SEMICOLON":
self.advance()
self.advance()
break
else:
raise Exception("newtype 오류: 'end;' 필요")
# func 메서드
if tk.type=="IDENT" and tk.value=="func":
fdec = self.parse_func_decl_inside_newtype()
methods.append(fdec)
continue
# 필드로 간주
if tk.type=="IDENT":
ftype = tk.value
self.advance()
if self.current_token().type!="IDENT":
raise Exception("newtype 필드 선언 오류: 이름 필요")
fname = self.current_token().value
self.advance()
if self.current_token().type!="SEMICOLON":
raise Exception("newtype 필드 선언 오류: 세미콜론 필요")
self.advance()
fields.append((ftype,fname))
continue
else:
raise Exception("newtype 오류: 예기치 않은 토큰 "+str(tk))
return ("newtype", tname, fields, methods)
def parse_func_decl_inside_newtype(self):
# func <이름>(...) : ... end;
self.advance() # 'func'
if self.current_token().type!="IDENT":
raise Exception("메서드 선언 오류: 함수 이름 필요")
fname = self.current_token().value
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='(':
raise Exception("메서드 선언 오류: '(' 필요")
self.advance()
params = []
if not(self.current_token().type=="SYMBOL" and self.current_token().value==')'):
while True:
if self.current_token().type!="IDENT":
raise Exception("메서드 선언 오류: 매개변수 타입 필요")
ptype = self.current_token().value
self.advance()
if self.current_token().type!="IDENT":
raise Exception("메서드 선언 오류: 매개변수 이름 필요")
pname = self.current_token().value
self.advance()
params.append((ptype,pname))
if self.current_token().type=="SYMBOL" and self.current_token().value==',':
self.advance()
else:
break
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("메서드 선언 오류: ')' 필요")
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("메서드 선언 오류: ':' 필요")
self.advance()
body=[]
while True:
t2 = self.current_token()
if t2.type=="IDENT" and t2.value=="end":
if self.peek_token(1).type=="SEMICOLON":
self.advance()
self.advance()
break
else:
raise Exception("메서드 선언 오류: 'end;' 필요")
if t2.type=="EOF":
raise Exception("메서드 선언 오류: EOF")
s2 = self.parse_statement()
body.append(s2)
return ("func_decl", fname, params, body)
def parse_func_decl(self):
# func <함수이름>(...) : ... end;
self.advance()
if self.current_token().type!="IDENT":
raise Exception("함수 선언 오류: 이름 필요")
fname = self.current_token().value
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='(':
raise Exception("함수 선언 오류: '(' 필요")
self.advance()
params=[]
if not(self.current_token().type=="SYMBOL" and self.current_token().value==')'):
while True:
if self.current_token().type!="IDENT":
raise Exception("함수 선언 오류: 매개변수 타입 필요")
ptype = self.current_token().value
self.advance()
if self.current_token().type!="IDENT":
raise Exception("함수 선언 오류: 매개변수 이름 필요")
pname = self.current_token().value
self.advance()
params.append((ptype,pname))
if self.current_token().type=="SYMBOL" and self.current_token().value==',':
self.advance()
else:
break
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("함수 선언 오류: ')' 필요")
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("함수 선언 오류: ':' 필요")
self.advance()
body=[]
while True:
t2 = self.current_token()
if t2.type=="IDENT" and t2.value=="end":
if self.peek_token(1).type=="SEMICOLON":
self.advance()
self.advance()
break
else:
raise Exception("함수 선언 오류: 'end;' 필요")
if t2.type=="EOF":
raise Exception("함수 선언 오류: EOF")
s2 = self.parse_statement()
body.append(s2)
return ("func_decl", fname, params, body)
def parse_always_stmt(self):
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='(':
raise Exception("always 오류: '(' 필요")
self.advance()
interval_expr = self.parse_expression()
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("always 오류: ')' 필요")
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("always 오류: ':' 필요")
self.advance()
bstmts=[]
while True:
t3 = self.current_token()
if t3.type=="IDENT" and t3.value=="end":
if self.peek_token(1).type=="SEMICOLON":
self.advance()
self.advance()
break
else:
raise Exception("always 오류: 'end;' 필요")
if t3.type=="EOF":
raise Exception("always 오류: EOF")
st3 = self.parse_statement()
bstmts.append(st3)
return ("always_block", interval_expr, bstmts)
def parse_if_stmt(self):
self.advance() # if
if self.current_token().type!="SYMBOL" or self.current_token().value!='(':
raise Exception("if 오류: '(' 필요")
self.advance()
ifcond = self.parse_expression()
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("if 오류: ')' 필요")
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("if 오류: ':' 필요")
self.advance()
ifblock=[]
while True:
t4 = self.current_token()
if t4.type=="IDENT" and t4.value in ["elif","else","end"]:
break
if t4.type=="EOF":
raise Exception("if 오류: EOF")
sb = self.parse_statement()
ifblock.append(sb)
elifs=[]
while self.current_token().type=="IDENT" and self.current_token().value=="elif":
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='(':
raise Exception("elif 오류: '(' 필요")
self.advance()
ec = self.parse_expression()
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("elif 오류: ')' 필요")
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("elif 오류: ':' 필요")
self.advance()
eb=[]
while True:
t5 = self.current_token()
if t5.type=="IDENT" and t5.value in ["elif","else","end"]:
break
if t5.type=="EOF":
raise Exception("elif 오류: EOF")
s5 = self.parse_statement()
eb.append(s5)
elifs.append((ec, eb))
elseb=None
if self.current_token().type=="IDENT" and self.current_token().value=="else":
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("else 오류: ':' 필요")
self.advance()
elseb=[]
while True:
t6 = self.current_token()
if t6.type=="IDENT" and t6.value=="end":
break
if t6.type=="EOF":
raise Exception("else 오류: EOF")
s6 = self.parse_statement()
elseb.append(s6)
if self.current_token().type=="IDENT" and self.current_token().value=="end":
if self.peek_token(1).type=="SEMICOLON":
self.advance()
self.advance()
else:
raise Exception("if 오류: 'end;' 필요")
else:
raise Exception("if 오류: 'end;' 필요")
return ("if_stmt", ifcond, ifblock, elifs, elseb)
def parse_while_stmt(self):
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='(':
raise Exception("while 오류: '(' 필요")
self.advance()
cexpr = self.parse_expression()
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("while 오류: ')' 필요")
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!=':':
raise Exception("while 오류: ':' 필요")
self.advance()
wstmts=[]
while True:
tw = self.current_token()
if tw.type=="IDENT" and tw.value=="end":
if self.peek_token(1).type=="SEMICOLON":
self.advance()
self.advance()
break
else:
raise Exception("while 오류: 'end;' 필요")
if tw.type=="EOF":
raise Exception("while 오류: EOF")
sw = self.parse_statement()
wstmts.append(sw)
return ("while_stmt", cexpr, wstmts)
def parse_return_stmt(self):
self.advance() # return
rexpr = self.parse_expression()
if self.current_token().type!="SEMICOLON":
raise Exception("return 오류: 세미콜론 필요")
self.advance()
return ("return_stmt", rexpr)
def parse_var_decl(self):
vtype = self.current_token().value
self.advance()
if self.current_token().type!="IDENT":
raise Exception("var_decl 오류: 식별자 필요")
vname = self.current_token().value
self.advance()
if self.current_token().type!="SYMBOL" or self.current_token().value!='=':
raise Exception("var_decl 오류: '=' 필요")
self.advance()
init = self.parse_expression()
if self.current_token().type=="SEMICOLON":
self.advance()
else:
raise Exception("var_decl 오류: ';' 필요")
return ("var_decl", vtype, vname, init)
def parse_expr_statement(self):
e = self.parse_expression()
if self.current_token().type=="SEMICOLON":
self.advance()
else:
raise Exception("expr_stmt 오류: 세미콜론 ';' 필요")
return ("expr_stmt", e)
def parse_expression(self):
return self.parse_assignment()
def parse_assignment(self):
expr = self.parse_logical_or()
if self.current_token().type=="SYMBOL" and self.current_token().value=='=':
self.advance()
rhs = self.parse_assignment()
expr = ("assign", expr, rhs)
return expr
def parse_logical_or(self):
expr = self.parse_logical_and()
while self.current_token().type=="IDENT" and self.current_token().value=="or":
self.advance()
right = self.parse_logical_and()
expr = ("binary","or",expr,right)
return expr
def parse_logical_and(self):
expr = self.parse_comparison()
while self.current_token().type=="IDENT" and self.current_token().value=="and":
self.advance()
right = self.parse_comparison()
expr = ("binary","and",expr,right)
return expr
def parse_comparison(self):
expr = self.parse_additive()
while self.current_token().type=="SYMBOL" and self.current_token().value in ['>','<','>=','<=','==','!=']:
op = self.current_token().value
self.advance()
r = self.parse_additive()
expr = ("binary",op,expr,r)
return expr
def parse_additive(self):
expr = self.parse_multiplicative()
while self.current_token().type=="SYMBOL" and self.current_token().value in ['+','-']:
op = self.current_token().value
self.advance()
r = self.parse_multiplicative()
expr = ("binary", op, expr, r)
return expr
def parse_multiplicative(self):
expr = self.parse_unary()
while self.current_token().type=="SYMBOL" and self.current_token().value in ['*','/','%']:
op = self.current_token().value
self.advance()
r = self.parse_unary()
expr = ("binary", op, expr, r)
return expr
def parse_unary(self):
if ((self.current_token().type=="SYMBOL" and self.current_token().value in ['+','-']) or
(self.current_token().type=="IDENT" and self.current_token().value=="not")):
op = self.current_token().value
self.advance()
operand = self.parse_unary()
return ("unary", op, operand)
else:
return self.parse_postfix()
def parse_postfix(self):
expr = self.parse_primary()
while True:
t0 = self.current_token()
if t0.type=="SYMBOL" and t0.value=='(':
# 함수 호출
self.advance()
args=[]
if not(self.current_token().type=="SYMBOL" and self.current_token().value==')'):
while True:
arg = self.parse_expression()
args.append(arg)
if self.current_token().type=="SYMBOL" and self.current_token().value==',':
self.advance()
else:
break
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("함수 호출 오류: ')' 필요")
self.advance()
expr = ("func_call", expr, args)
elif t0.type=="SYMBOL" and t0.value=='.':
# 멤버 접근 or 호출
self.advance()
if self.current_token().type!="IDENT":
raise Exception("멤버 접근 오류: 식별자 필요")
memb = self.current_token().value
self.advance()
t1 = self.current_token()
if t1.type=="SYMBOL" and t1.value=='(':
# 멤버 함수 호출
self.advance()
margs=[]
if not(self.current_token().type=="SYMBOL" and self.current_token().value==')'):
while True:
aa = self.parse_expression()
margs.append(aa)
if self.current_token().type=="SYMBOL" and self.current_token().value==',':
self.advance()
else:
break
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("멤버 호출 오류: ')' 필요")
self.advance()
expr = ("member_call", expr, memb, margs)
else:
expr = ("member_access", expr, memb)
elif t0.type=="SYMBOL" and t0.value=='[':
# 인덱스
self.advance()
idx_expr = self.parse_expression()
if self.current_token().type!="SYMBOL" or self.current_token().value!=']':
raise Exception("인덱스 오류: ']' 필요")
self.advance()
expr = ("index", expr, idx_expr)
else:
break
return expr
def parse_primary(self):
tk = self.current_token()
if tk.type=="IDENT" and tk.value in ["true","false"]:
self.advance()
return ("literal","BOOL",True if tk.value=="true" else False)
if tk.type=="SYMBOL" and tk.value=='[':
self.advance()
arr=[]
if self.current_token().type=="SYMBOL" and self.current_token().value==']':
self.advance()
return ("li", arr)
while True:
e2 = self.parse_expression()
arr.append(e2)
if self.current_token().type=="SYMBOL" and self.current_token().value==',':
self.advance()
elif self.current_token().type=="SYMBOL" and self.current_token().value==']':
self.advance()
break
else:
raise Exception("배열 리터럴 오류: ',' 또는 ']' 필요")
return ("li", arr)
if tk.type=="SYMBOL" and tk.value=='{':
# 레코드
self.advance()
rec=[]
if self.current_token().type=="SYMBOL" and self.current_token().value=='}':
self.advance()
return ("record", rec)
while True:
e3 = self.parse_expression()
rec.append(e3)
if self.current_token().type=="SYMBOL" and self.current_token().value==',':
self.advance()
elif self.current_token().type=="SYMBOL" and self.current_token().value=='}':
self.advance()
break
else:
raise Exception("레코드 리터럴 오류: ',' 또는 '}' 필요")
return ("record", rec)
if tk.type in ["NUMBER_NUM","NUMBER_FL","STRING"]:
self.advance()
return ("literal", tk.type, tk.value)
if tk.type=="IDENT":
self.advance()
return ("ident", tk.value)
if tk.type=="SYMBOL" and tk.value=='(':
self.advance()
e4 = self.parse_expression()
if self.current_token().type!="SYMBOL" or self.current_token().value!=')':
raise Exception("괄호 오류: ')' 필요")
self.advance()
return e4
raise Exception(("표현식 파싱 오류", tk))
def interpret(statements):
for st in statements:
exec_stmt(st)
def exec_stmt(stmt):
global environment
stype = stmt[0]
if stype=="newtype":
# ("newtype", tname, fields, methods)
_, tname, fields, methods = stmt
user_types[tname] = {"fields":fields, "methods":methods}
# 환경에도 등록
environment[tname] = {"newtype":tname, "fields":fields, "methods":methods}
return
elif stype=="func_decl":
# ("func_decl", fn, params, body)
_, fn, ps, bd = stmt
func_obj = ("function", ps, bd, environment.copy())
user_functions[fn] = func_obj
environment[fn] = func_obj
return
elif stype=="var_decl":
# ("var_decl", vtype, vname, init)
_, vt, vn, init = stmt
val = eval_expr(init)
# 기본 타입 변환
if vt=="num":
val = int(val)
elif vt=="fl":
val = float(val)
elif vt=="str":
val = str(val)
elif vt=="bool":
val = bool(val)
elif vt in user_types:
# 사용자 정의 타입
type_info = user_types[vt]
fields = type_info["fields"]
methods = type_info["methods"]
if isinstance(val, list):
# record(...)의 결과
if len(val)!=len(fields):
raise Exception(vt+" 타입 필드 수 불일치")
rec={}
for ((ft,fnm), fv) in zip(fields,val):
rec[fnm] = fv
# 메서드 삽입
for m in methods:
(_, mname, mparams, mbody) = m
func_obj = ("function", mparams, mbody, environment.copy())
rec[mname] = func_obj
val = rec
elif isinstance(val, dict):
pass
else:
raise Exception("레코드 초기값은 { ... } 형태여야 합니다.")
else:
pass
environment[vn] = val
return
elif stype=="use":
_, mname = stmt
fname = mname+".sst"
try:
with open(fname,"r",encoding="utf-8") as f:
mc = f.read()
except Exception as e:
raise Exception("파일 읽기 실패: "+str(e))
tks = tokenize(mc)
p2 = Parser(tks)
sms = p2.parse_program()
backup = environment.copy()
environment.clear()
interpret(sms)
mod_defs = environment.copy()
environment.clear()
environment.update(backup)
environment[mname] = mod_defs
return
elif stype=="expr_stmt":
eval_expr(stmt[1])
return
elif stype=="return_stmt":
_, exr = stmt
rv = eval_expr(exr)
raise ReturnException(rv)
elif stype=="if_stmt":
_, ifc, ifb, elifs, elseb = stmt
cval = eval_expr(ifc)
if cval:
for s1 in ifb:
exec_stmt(s1)
else:
done=False
for ccond,cblk in elifs:
cc = eval_expr(ccond)
if cc:
for s2 in cblk:
exec_stmt(s2)
done=True
break
if not done and elseb is not None:
for s3 in elseb:
exec_stmt(s3)
return
elif stype=="while_stmt":
_, cexpr, wblk = stmt
while True:
condv = eval_expr(cexpr)
if not condv:
break
try:
for s4 in wblk:
exec_stmt(s4)
except BreakException:
break
except ContinueException:
continue
return
elif stype=="always_block":
_, intex, b1 = stmt
ival = eval_expr(intex)
def loopf():
while True:
for s5 in b1:
exec_stmt(s5)
time.sleep(ival)
t = threading.Thread(target=loopf)
t.daemon=True
t.start()
return
elif stype=="break_stmt":
raise BreakException()
elif stype=="continue_stmt":
raise ContinueException()
else:
pass
def eval_expr(expr):
global environment
etype = expr[0]
if etype=="literal":
_, tkt, val = expr
return val
elif etype=="ident":
_, nm = expr
if nm in environment:
return environment[nm]
else:
raise Exception("정의되지 않은 식별자: "+nm)
elif etype=="assign":
_, lhs, rhs = expr
if lhs[0]!="ident":
raise Exception("할당 왼쪽은 식별자여야 합니다.")
vn = lhs[1]
v2 = eval_expr(rhs)
environment[vn] = v2
return v2
elif etype=="unary":
_, op, inr = expr
rv = eval_expr(inr)
if op=='-':
return -rv
elif op=='+':
return +rv
elif op=="not":
return not rv
else:
raise Exception("알수없는 단항연산자: "+op)
elif etype=="binary":
_, op, le, re = expr
lv = eval_expr(le)
rv = eval_expr(re)
if op=='+':
return lv+rv
elif op=='-':
return lv-rv
elif op=='*':
return lv*rv
elif op=='/':
if isinstance(lv,int) and isinstance(rv,int):
return lv//rv
else:
return lv/rv
elif op=='%':
return lv%rv
elif op=='>':
return lv>rv
elif op=='<':
return lv<rv
elif op=='>=':
return lv>=rv
elif op=='<=':
return lv<=rv
elif op=='==':
return lv==rv
elif op=='!=':
return lv!=rv
elif op=="or":
return lv or rv
elif op=="and":
return lv and rv
else:
raise Exception("미지원연산자: "+op)
elif etype=="func_call":
# ("func_call", fx, argl)
_, fx, argl = expr
if fx[0]!="ident":
raise Exception("함수이름은 식별자여야 함")
fn = fx[1]
# 내장함수
if fn=="output":
vals = [eval_expr(a) for a in argl]
print(" ".join(str(v) for v in vals))
return None
if fn=="input":
ac=len(argl)
if ac<1:
raise Exception("input에 식별자 최소 1개 필요")
var_names=[]
for texpr in argl:
if texpr[0]!="ident":
raise Exception("input 인자는 식별자여야함")
var_names.append(texpr[1])
needed=ac
gathered=[]
while len(gathered)<needed:
ln = sys.stdin.readline()
if not ln:
raise Exception("입력중단")
parts = ln.strip().split()
gathered.extend(parts)
for i in range(ac):
varn = var_names[i]
rawv = gathered[i]
if varn in environment:
oldv = environment[varn]
if isinstance(oldv,int):
newv = int(rawv)
elif isinstance(oldv,float):
newv = float(rawv)
elif isinstance(oldv,bool):
newv = (rawv.lower() in ["true","1"])
else:
newv = rawv
else:
newv = rawv
environment[varn] = newv
return None
if fn=="error":
vall = [eval_expr(a) for a in argl]
msg = " ".join(str(v) for v in vall)
raise Exception("Error: "+msg)
if fn=="exec":
if len(argl)!=1:
raise Exception("exec는 code 하나 필요")
code_val = eval_expr(argl[0])
if not(isinstance(code_val,dict) and "source" in code_val):
raise Exception("exec 인자는 {source:'...'} 형태여야 함")
code_str = code_val["source"]
if not isinstance(code_str,str):
raise Exception("code 자료형의 source 필드는 문자열이어야함")
tokens_ = tokenize(code_str)
parser_ = Parser(tokens_)
statements_ = parser_.parse_program()
interpret(statements_)
return None
# 사용자함수
if fn not in user_functions:
raise Exception("함수정의안됨: "+fn)
finfo = user_functions[fn]
fkind, fparams, fbody, fdefenv = finfo
if fkind!="function":
raise Exception("함수 아님: "+fn)
if len(fparams)!=len(argl):
raise Exception("함수호출 오류: 매개변수 수 불일치")
localenv = fdefenv.copy()
for (pt,pn), ax in zip(fparams,argl):
av = eval_expr(ax)
if pt=="num":
av = int(av)
elif pt=="fl":
av = float(av)
elif pt=="str":
av = str(av)
elif pt=="bool":
av = bool(av)
localenv[pn] = av
bkup = environment.copy()
environment.update(localenv)
retv=None
try:
for stx in fbody:
exec_stmt(stx)