-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkat.py
executable file
·1968 lines (1792 loc) · 83.3 KB
/
kat.py
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
#!/usr/bin/env python3
#
# The__ __. __ .__
# | |/ _|____ _/ |______ | | ___.__. ____
# | < \__ \\ __\__ \ | |< | |/ \
# | | \ / __ \| | / __ \| |_\___ | | \
# |____|__ (____ /__| (____ /____/ ____|___| /
# \/ \/ \/ Programming Language
#
# Started by Lartu on July 3, 2024 (01:13 AM).
#
# For 0.0.2:
# TODO: Lógica de cortocircuito para 'and' and 'or' (Es saltar al final del right side si and es false u or es true en el left side)
# TODO: poder seek en un archivo
# TODO: and, or e in en lugar de &&, || y :: (opcionales)
# TODO: Not in operator: !:
# TODO: break tiene break X pero continue no tiene continue X!
from __future__ import annotations
import sys
from typing import Dict, List, Tuple, Optional, Set
from enum import Enum, auto
from sys import exit
import time
import random
import os
VERSION = "0.1.0"
OPERATOR_PRESEDENCE = ("*", "^", "/", "%", "//", "+", "&", "-", "::", "!", "<", ">", "<=", ">=", "<>", "!=", "=", "||", "&&")
LOOP_TAGS = ("while", "until", "for")
NON_DEF_BLOCK_TAGS = ("if", "unless", "while", "until")
ARGS_VAR = "$_"
RESULT_VAR = "$_r"
FLAGS_VAR = "$_args"
EXEC_STDOUT_VAR = "$_stdout"
EXEC_STDERR_VAR = "$_stderr"
EXEC_EXITCODE_VAR = "$_exitcode"
CALLER_VAR = "$_caller"
CONTEXT_VAR = "$_context"
STDLIB_LOCATION = os.path.abspath(os.path.dirname(__file__))
class ScopeSearchType(Enum):
LOCAL_AND_GLOBAL = auto()
ONLY_GLOBAL = auto()
ONLY_LOCAL = auto()
class CompilerState:
def __init__(self):
self.block_count: int = 0
self.__block_end_code_stack: List[Tuple[str, Token]] = []
self.__declared_variables: List[Dict[str, str]] = []
self.__open_loop_tags: List[Tuple[str, str]] = []
self.__function_to_labels: Dict[str, Tuple[str, str]] = {}
self.__expected_functions: Dict[str, Token, Tuple[str, str]] = {}
self.shadower_functions: List[Tuple[str, str]] = [] # Must be ordered. Thus, a list.
self.add_scope()
def add_open_loop(self, start_label: str, end_label: str) -> None:
self.__open_loop_tags.append((start_label, end_label))
def close_open_loop(self) -> None:
"""Closes an open loop only if the current scope is that of a loop.
"""
if self.__block_end_code_stack:
if self.__block_end_code_stack[-1][1].value in LOOP_TAGS:
self.__open_loop_tags.pop()
def get_open_loop_tags(self, depth: int = 0) -> Optional[Tuple[str, str]]:
"""Returns the start and end tags of a loop if a loops is open, otherwise None.
"""
if self.__open_loop_tags:
index: int = 1 + depth
if index > len(self.__open_loop_tags):
index = 0
return self.__open_loop_tags[-index]
else:
return None
def add_scope(self) -> None:
self.__declared_variables.append({})
def del_scope(self, command_token: Token) -> str:
"""Deletes a variable scope only if the current scope is that of a function
"""
compiled_code: str = ""
if self.__block_end_code_stack:
if self.__block_end_code_stack[-1][1].value in self.__function_to_labels:
self.__declared_variables.pop()
else:
parse_error(f"Unexpected '{command_token.value}'. Do you have mismatched blocks?", command_token.line, command_token.file)
return compiled_code
def get_var_identifier(self, var: Token, fail_if_not_found: bool, scope_type: ScopeSearchType = ScopeSearchType.LOCAL_AND_GLOBAL, unsafe: bool = False) -> Optional[str]:
"""Gets the scope id (the id for the variable in the current context) of
the variable with name var_name. If the variable hasn't been declared yet,
returns None. If force_global, the variable is only looked for in the global
scope. If unsafe, its identifier is returned and doesn't fail if not found.
"""
scopes = []
if scope_type in [ScopeSearchType.LOCAL_AND_GLOBAL, ScopeSearchType.ONLY_LOCAL]:
scopes.append(len(self.__declared_variables) - 1)
if scope_type in [ScopeSearchType.LOCAL_AND_GLOBAL, ScopeSearchType.ONLY_GLOBAL]:
scopes.append(0)
var_name: str = var.get_var_name()
for scope in scopes:
if var_name in self.__declared_variables[scope]:
return self.__declared_variables[scope][var_name]
if unsafe:
return var_name
if fail_if_not_found:
if not self.get_in_function_declaration():
expression_error(f"Variable {var.value} read before assignment.", var.line, var.file)
else:
expression_error(
f"Variable {var.value} read before assignment. If you are sure this variable will "\
f"be declared by the point this function is called, use unsafe({var.value}) instead "\
f"of just {var.value}. Bear in mind that if the variable hasn't been initialized by this "\
f"point, its value will be nil and your program will likely crash."
, var.line, var.file)
return None
def declare_variable(self, var: Token, global_var: bool = False) -> str:
"""Adds a new variable, if it didn't exist, to the context. Then,
existed or not, returns its scope_id (the id for the variable in
the current context). If the variable is declared as global_var, the
variable is declared only if it didn't exist in the global context.
"""
var_name = var.get_var_name()
scope_search_type: ScopeSearchType = ScopeSearchType.ONLY_LOCAL
if global_var:
scope_search_type = ScopeSearchType.ONLY_GLOBAL
if self.get_var_identifier(var, False, scope_search_type) is not None:
return self.get_var_identifier(var, True, scope_search_type)
self.__declared_variables[-1][var_name] = var_name
return var_name
def unset_variable(self, var: Token, global_var: bool = False):
i = len(self.__declared_variables) - 1
if global_var:
i = 0
var_name: str = var.get_var_name()
while i >= 0:
if var_name in self.__declared_variables[i]:
del self.__declared_variables[i][var_name]
i -= 1
def add_block_end_code(self, code: str, reference_token: Token, group_id: int = -1):
"""Sets the next block end code to be used when an 'ok;' is found.
The reference token is there so that if that 'ok;' is missing, we
can reference which block is missing it.
"""
self.__block_end_code_stack.append((code, reference_token, group_id))
def get_block_end_data(self, caller_command: Token) -> Tuple[str, Token, int]:
"""Gets the next block end code to be used when an 'ok;' is found.
"""
if not self.__block_end_code_stack:
parse_error("Unexpected 'ok' command.", caller_command.line, caller_command.file)
return self.__block_end_code_stack.pop()
def add_function(self, caller_command: Token, start_label: str, end_label: str, post_label: str):
"""Adds a function and links it to its label
"""
function_name: str = caller_command.value
#if function_name in self.__function_to_labels:
# parse_error(f"Duplicate function declaration for '{function_name}'.", caller_command.line, caller_command.file)
self.__function_to_labels[function_name] = (start_label, end_label, post_label)
def get_function_label(self, caller_command: Token, force_new: bool = False) -> Tuple[str, str]:
function_name: str = caller_command.value
if function_name not in self.__function_to_labels or force_new:
if force_new and function_name in self.__function_to_labels:
#parse_error(
# f"Redefining function '{caller_command.value}'.",
# caller_command.line,
# caller_command.file,
#)
self.shadower_functions.append((caller_command.value, self.__function_to_labels[caller_command.value]))
# This function ^^^ is a shadower to ^^^ this function
# The proper way to add function shadowing would be to replace all jumps and calls
# to the previous function with calls to the new one
if not force_new: # The force new logic doesn't make sense in function calls, only defs.
if function_name in self.__expected_functions:
return self.__expected_functions[caller_command.value][1]
block_number: int = self.block_count
self.block_count += 1
start_label: str = f"FUN_{block_number}_START"
end_label: str = f"FUN_{block_number}_END"
post_label: str = f"FUN_{block_number}_POST"
self.__expected_functions[caller_command.value] = [caller_command, (start_label, end_label, post_label)]
return (start_label, end_label, post_label)
return self.__function_to_labels[function_name]
def check_for_errors(self):
"""Checks that the state was left in a valid state after compiling.
"""
if self.__block_end_code_stack:
parse_error("Missing 'ok' command.", self.__block_end_code_stack[0][1].line, self.__block_end_code_stack[0][1].file)
for function in self.__expected_functions:
if function not in self.__function_to_labels:
parse_error(
f"Call to nonexistent function '{function}'.",
self.__expected_functions[function][0].line,
self.__expected_functions[function][0].file,
)
def get_in_function_declaration(self) -> bool:
"""Returns if the current code is inside a function declaration.
"""
for tuple_code_token in self.__block_end_code_stack:
if tuple_code_token[1] not in NON_DEF_BLOCK_TAGS:
return True
return False
def get_in_if_chain(self) -> bool:
"""Returns if the current code is inside an if chain. (But not else!)
"""
token = self.__block_end_code_stack[-1][1]
return token.type == LexType.WORD and token.value in ("if", "elif")
def get_group_id(self) -> int:
"""Returns the current group id for the current block.
"""
return self.__block_end_code_stack[-1][2]
class LexType(Enum):
WORD = auto()
INTEGER = auto()
FLOAT = auto()
STRING = auto()
OPERATOR = auto()
VARIABLE = auto()
TABLE = auto()
ACCESS_OPEN = auto()
ACCESS_CLOSE = auto()
PAR_OPEN = auto()
PAR_CLOSE = auto()
DECORATION = auto()
UNKNOWN = auto()
class Token:
def __init__(self, value: str, line: int, file: str) -> None:
self.value: str = value
self.line: int = line
self.file: str = file
self.type: LexType = LexType.UNKNOWN
def set_type(self, type: LexType):
self.type = type
def __repr__(self):
return f"{self.value} ({self.file}:{self.line})"
def __str__(self):
color: str = "\033[31;40m"
if self.type == LexType.WORD:
color = "\033[37;44m"
elif self.type == LexType.STRING:
color = "\033[33;40m"
elif self.type == LexType.INTEGER:
color = "\033[37;45m"
elif self.type == LexType.FLOAT:
color = "\033[30;43m"
elif self.type == LexType.OPERATOR:
color = "\033[36;40m"
elif self.type == LexType.VARIABLE:
color = "\x1b[30;46m"
elif self.type == LexType.TABLE:
color = "\033[31;47m"
elif self.type == LexType.ACCESS_OPEN or self.type == LexType.ACCESS_CLOSE:
color = "\033[32;47m"
elif self.type == LexType.PAR_OPEN or self.type == LexType.PAR_CLOSE:
color = "\033[35;47m"
elif self.type == LexType.DECORATION:
color = "\033[30;47m"
return f"{color} {self.value} \033[0m"
def get_nambly_string(self) -> str:
"""Returns a nambly formatted string to be able to push string values to the nvm.
"""
if self.type == LexType.TABLE:
return '"TABLE"'
else:
return str(self.value).replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n')
def get_var_name(self) -> str:
""""Returns a nambly formated variable name (without the $)
"""
if self.type == LexType.VARIABLE:
return self.value[1:]
else:
parse_error(f"{self} is not a variable.", self.line, self.file)
def katalyn_error(title: str, lines: List[str]):
"""Prints a Katalyn standard error with the passed lines and exits.
"""
print("")
print(f"=== {title} ===")
for line in lines:
total_length = 0
tokens = line.split()
for token in tokens:
token_length = len(token)
if total_length > 0:
token_length += 1 # To account for spaces
if total_length + token_length > 80:
print(f"")
total_length = 2
token_length = len(token)
print(f" ", end="")
total_length += token_length
print(f"{token} ", end="")
print("")
print("")
exit(1)
def tokenization_error(message: str, line: int, filename: str):
"""Prints a tokenization error and exits.
"""
error_title = "Katayln Tokenization Error"
error_lines = [
f"- Where? In file '{filename}', on line {line}.",
f"- Error Message: {message}",
]
katalyn_error(error_title, error_lines)
def lexing_error(message: str, line: int, filename: str):
"""Prints a lexing error and exits.
"""
error_title = "Katayln Lexing Error"
error_lines = [
f"- Where? In file '{filename}', on line {line}.",
f"- Error Message: {message}",
]
katalyn_error(error_title, error_lines)
def expression_error(message: str, line: int, filename: str):
"""Prints an expression error and exits.
"""
error_title = "Katayln Expression Error"
error_lines = [
f"- Where? In file '{filename}', on line {line}.",
f"- Error Message: {message}",
]
katalyn_error(error_title, error_lines)
def parse_error(message: str, line: int, filename: str):
"""Prints an expression error and exits.
"""
error_title = "Katayln Parse Error"
error_lines = [
f"- Where? In file '{filename}', on line {line}.",
f"- Error Message: {message}",
]
katalyn_error(error_title, error_lines)
def tokenize_source(code: str, filename: str) -> List[List[Token]]:
"""Takes Katalyn source code and splits it into tokens.
"""
last_string_open_line = 1 # For error reporting purposes
line_num = 1
lines: List[List[Token]] = []
current_line: List[Token] = []
code += " " # To simplify tokenization
current_token = ""
in_string = False
in_access_string = False
comment_depth: int = 0
in_inline_comment: bool = False
# Katalyn supports nested comments, but doesn't make any distinction between (* ... *) inside strings
# once that string is inside an already open comment (such as (* "(* *)" *))
i = 0
while i < len(code) - 1:
current_char = code[i]
next_char = code[i + 1]
if not in_inline_comment and not in_string and not in_access_string and comment_depth == 0 and current_char == "#":
# Inline comment
in_inline_comment = True
elif not in_string and not in_access_string and current_char == "(" and next_char == "*":
# (*...*) comments can be opened and closed from within an inline comment
comment_depth += 1
i += 1
elif comment_depth > 0 and not in_string and not in_access_string and current_char == "*" and next_char == ")":
# (*...*) comments can be opened and closed from within an inline comment
comment_depth -= 1
i += 1
elif not in_inline_comment and comment_depth == 0 and (in_string or in_access_string) and current_char == '\\':
# This block should always go before any that match "" or {}
if next_char == "n":
current_token += "\n"
elif next_char == "t":
current_token += "\t"
elif next_char == '"':
current_token += '"'
elif next_char.isspace():
idx: int = i + 1
while code[idx].isspace():
idx += 1
i += 1
i -= 1
else:
current_token += next_char
i += 1
elif not in_inline_comment and comment_depth == 0 and not in_string and not in_access_string and current_char == '"':
if len(current_token):
current_line.append(Token(current_token, line_num, filename))
current_token = ""
current_token += current_char
in_string = True
last_string_open_line = line_num
elif not in_inline_comment and comment_depth == 0 and in_string and not in_access_string and current_char == '"':
current_token += current_char
in_string = False
if len(current_token):
current_line.append(Token(current_token, last_string_open_line, filename))
current_token = ""
elif not in_inline_comment and comment_depth == 0 and not in_string and not in_access_string and current_char == '{':
if len(current_token):
current_line.append(Token(current_token, line_num, filename))
current_token = ""
current_line.append(Token("[", line_num, filename))
current_token += '"'
in_access_string = True
last_string_open_line = line_num
elif not in_inline_comment and comment_depth == 0 and not in_string and in_access_string and current_char == '}':
current_token += '"'
in_access_string = False
if len(current_token):
current_line.append(Token(current_token, last_string_open_line, filename))
current_token = ""
current_line.append(Token("]", line_num, filename))
elif not in_inline_comment and comment_depth == 0 and not in_string and not in_access_string and current_char == ";":
if len(current_token):
current_line.append(Token(current_token, line_num, filename))
current_token = ""
if len(current_line):
lines.append(current_line)
current_line = []
elif not in_inline_comment and comment_depth == 0 and not in_string and not in_access_string and current_char + next_char in (">=", "<=", "::", "<>", "!=", "//", "&&", "||"):
# Biglyphs
if len(current_token):
current_line.append(Token(current_token, line_num, filename))
current_token = ""
current_line.append(Token(current_char + next_char, line_num, filename))
i += 1
elif not in_inline_comment and comment_depth == 0 and not in_string and not in_access_string and current_char in "(){}[]=<>!+-/&%^*:#,":
# Single glyphs
if len(current_token):
current_line.append(Token(current_token, line_num, filename))
current_token = ""
current_line.append(Token(current_char, line_num, filename))
elif not in_inline_comment and comment_depth == 0 and not in_string and not in_access_string and current_char.isspace():
if len(current_token):
current_line.append(Token(current_token, line_num, filename))
current_token = ""
elif not in_inline_comment and comment_depth == 0:
current_token += current_char
if current_char == "\n":
line_num += 1
in_inline_comment = False
i += 1
# Check for consistency
# I want to be able to leave comments open til the end of the file
if in_string:
tokenization_error("Open string, missing '\"'", last_string_open_line, filename)
if in_access_string:
tokenization_error("Open access string, missing '}'", last_string_open_line, filename)
if len(current_line):
tokenization_error("Missing ';'", current_line[-1].line, filename)
if len(current_token):
tokenization_error("Missing ';'", line_num, filename)
return lines
def pad_string(text: str, padding_size: int) -> str:
"""Pads a string to a given number of chars (left side)
"""
if len(text) > padding_size:
return text
else:
return text + " " * (padding_size - len(text))
def print_tokens(tokenized_lines: List[List[Token]], filename: str, step: str):
"""Prints the result of a tokenization.
"""
padding_size: int = len(str(tokenized_lines[-1][0].line)) + 1 # This +1 is to account for the ':'.
print("")
print(f"=== {step} Result for File '{filename}' ===")
for line in tokenized_lines:
print(f"Line {pad_string(str(line[0].line) + ':', padding_size)} ", end="")
tokens_str: List[str] = []
for token in line:
tokens_str.append(str(token).replace("\n", ""))
print(", ".join(tokens_str))
print("")
def is_integer(text: str) -> bool:
"""Returns true if the string represents an integer number.
"""
if not len(text):
return False
for char in text:
if char not in "0987654321":
return False
return True
def is_float(text: str) -> bool:
"""Returns true if the string represents an floating point number.
"""
if not len(text):
return False
found_point = False
for char in text:
if char == ".":
if found_point:
return False
else:
found_point = True
continue
elif char not in "0987654321":
return False
if text[0] == "." or text[-1] == ".":
return False
return found_point
def is_valid_variable(text: str) -> bool:
"""Returns true if the string represents a valid variable name.
"""
if len(text) < 2:
return False
if text[0] != "$":
return False
for char in text[1:]:
if char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789":
return False
return True
def is_valid_identifier(text: str) -> bool:
"""Returns true if the string represents a valid identifier name.
"""
if not len(text):
return False
if text[0] not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_":
return False
for char in text[1:]:
if char not in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789":
return False
return True
def is_almost_number(text: str) -> bool:
"""Returns true if the string almost represents a valid number.
"""
if not len(text):
return False
for char in text:
if char not in "0123456789.":
return False
return True
def lex_tokens(tokenized_lines: List[List[Token]]) -> List[List[Token]]:
"""Given a list of tokenized lines, lexes each token attatching extra information
to make the parsing simpler. It modifies the list in place.
"""
for line in tokenized_lines:
for token in line:
if token.value[0] == '"' and token.value[-1] == '"':
token.value = token.value[1:-1]
token.type = LexType.STRING
elif is_valid_variable(token.value):
token.type = LexType.VARIABLE
elif token.value == "(":
token.type = LexType.PAR_OPEN
elif token.value == ")":
token.type = LexType.PAR_CLOSE
elif token.value == "[":
token.type = LexType.ACCESS_OPEN
elif token.value == "]":
token.type = LexType.ACCESS_CLOSE
elif token.value in (":", ","):
token.type = LexType.DECORATION
elif token.value == "table":
token.type = LexType.TABLE
elif is_integer(token.value):
token.type = LexType.INTEGER
elif is_float(token.value):
token.type = LexType.FLOAT
elif token.value in OPERATOR_PRESEDENCE:
token.type = LexType.OPERATOR
elif is_valid_identifier(token.value):
token.type = LexType.WORD
else:
# If we reached this point, there's an error
if token.value[0] == "$":
lexing_error(f"The string '{token.value}' is not a valid variable name.", token.line, token.file)
elif is_almost_number(token.value):
lexing_error(f"The string '{token.value}' is not a valid number.", token.line, token.file)
else:
lexing_error(f"The string '{token.value}' is not a valid identifier.", token.line, token.file)
return tokenized_lines
def get_debug_info(token: Token):
return f"\n;line {token.line}\n;file {token.file}"
def compile_expression(expr_tokens: List[Token], discard_return_value: bool = False, unsafe: bool = False) -> str:
"""Takes an expression and turns it into Nambly code.
Terminators are not compiled by this function.
This is the flojest part of the code and should probably
be turned into an AST first.
"""
compiled_code: str = ""
depth_0_token_count: int = 0
left_side_tokens: List[Token] = []
right_side_tokens: List[Token] = []
operator: Optional[Token] = None
par_depth: int = 0
access_depth: int = 0
last_line: int = 0
last_file: str = ""
for token in expr_tokens:
last_line = token.line
last_file = token.file
initial_depth: int = par_depth + access_depth
if token.type == LexType.PAR_OPEN:
par_depth += 1
elif token.type == LexType.PAR_CLOSE:
par_depth -= 1
if par_depth < 0:
expression_error(
"')' before '('",
token.line,
token.file
)
elif token.type == LexType.ACCESS_OPEN:
access_depth += 1
elif token.type == LexType.ACCESS_CLOSE:
access_depth -= 1
if access_depth < 0:
expression_error(
"']' before '['",
token.line,
token.file
)
if par_depth + access_depth == 0 and token.type == LexType.OPERATOR:
if operator is None:
operator = token
else:
if OPERATOR_PRESEDENCE.index(operator.value) <= OPERATOR_PRESEDENCE.index(token.value):
left_side_tokens.append(operator)
left_side_tokens += right_side_tokens
right_side_tokens = []
operator = token
else:
right_side_tokens.append(token)
else:
if operator is None:
left_side_tokens.append(token)
else:
right_side_tokens.append(token)
if initial_depth == 0 or par_depth + access_depth == 0:
depth_0_token_count += 1
if par_depth > 0:
expression_error(
"Missing ')'",
last_line,
last_file
)
if access_depth > 0:
expression_error(
"Missing ']'",
last_line,
last_file
)
if False:
# print(depth_0_token_count)
print("-------------")
print("OPERATOR:", operator)
if left_side_tokens:
print("LSIDE: ", end = "")
for token in left_side_tokens:
print(token, end="")
print("")
if right_side_tokens:
print("RSIDE: ", end = "")
for token in right_side_tokens:
print(token, end="")
print("")
# Reevaluate expressions completely enclosed by parenthesis
if depth_0_token_count == 2 and expr_tokens[0].type == LexType.PAR_OPEN and expr_tokens[-1].type == LexType.PAR_CLOSE:
compiled_code += "\n" + compile_expression(expr_tokens[1:-1])
else:
if operator is not None and not right_side_tokens:
expression_error(
f"Expecting expression after operator {operator.value}",
operator.line,
operator.file
)
elif operator is None: # Caso de los function calls
compiled_code += "\n" + compile_terminator(left_side_tokens, unsafe)
elif operator.value == "-" and not left_side_tokens:
compiled_code += "\n" + compile_terminator([operator] + right_side_tokens, unsafe)
operator = None
else:
compiled_code += "\n" + compile_expression(left_side_tokens)
compiled_code += "\n" + compile_expression(right_side_tokens)
if operator:
infix: bool = False
if operator.value == "*":
compiled_code += "\nMULT"
elif operator.value == "^":
compiled_code += "\nPOWR"
elif operator.value == "/":
compiled_code += "\nFDIV"
elif operator.value == "//":
compiled_code += "\nIDIV"
elif operator.value == "-":
compiled_code += "\nSUBT"
elif operator.value == "+":
compiled_code += "\nADDV"
elif operator.value == "&":
compiled_code += "\nJOIN"
elif operator.value == "%":
compiled_code += "\nMODL"
elif operator.value == "=":
compiled_code += "\nISEQ"
elif operator.value in ("<>", "!="):
compiled_code += "\nISNE"
elif operator.value == "<":
compiled_code += "\nISLT"
elif operator.value == ">":
compiled_code += "\nISGT"
elif operator.value == "<=":
compiled_code += "\nISLE"
elif operator.value == ">=":
compiled_code += "\nISGE"
elif operator.value == "&&":
compiled_code += "\nLAND"
elif operator.value == "||":
compiled_code += "\nLGOR"
elif operator.value == "::":
compiled_code += "\nISIN"
elif operator.value == "!":
compiled_code += "\nLNOT"
infix = True
else:
expression_error(
f"The operator {operator.value} cannot be used as an infix operator.",
operator.line,
operator.file
)
if infix and left_side_tokens:
expression_error(
f"The operator {operator.value} can only be used as an infix operator.",
operator.line,
operator.file
)
if discard_return_value:
compiled_code += "\nPOPV"
return compiled_code
def compile_terminator(expr_tokens: List[Token], unsafe: bool = False) -> str:
"""Generates Nambly for an expression terminator.
This is the second flojest part of the code and should
probably be turned into an AST first.
"""
compiled_code: str = ""
add_minus_code: bool = False
access_depth: int = 0
access_tokens: List[Token] = []
terminator_type: LexType = LexType.UNKNOWN
function_call_token: Optional[Token] = None
while expr_tokens:
token = expr_tokens.pop(0)
if access_depth > 0:
if token.type == LexType.ACCESS_OPEN:
access_depth += 1
access_tokens.append(token)
elif token.type == LexType.ACCESS_CLOSE:
access_depth -= 1
if access_depth == 0:
compiled_code += "\n" + compile_expression(access_tokens)
compiled_code += "\nPGET"
if expr_tokens:
if expr_tokens[0].type not in (LexType.ACCESS_OPEN, LexType.PAR_OPEN):
expression_error(
f"Unexpected expression element: {expr_tokens[0].value} (did you forget a ';'?)",
token.line,
token.file
)
else:
access_tokens.append(token)
else:
access_tokens.append(token)
else:
next_token = None
if len(expr_tokens) > 0:
next_token = expr_tokens[0]
if token.type == LexType.OPERATOR and token.value == "-":
if next_token is None:
expression_error(
"Missing value after '-'",
token.line,
token.file
)
if next_token.type in [LexType.INTEGER, LexType.FLOAT]:
if terminator_type != LexType.UNKNOWN:
expression_error(f"Unexpected token '{token.value}'.", token.line, token.file)
compiled_code += f"\nPUSH -{next_token.value}"
terminator_type = next_token.type
expr_tokens.pop(0)
else:
add_minus_code = True
elif token.type == LexType.TABLE:
if terminator_type != LexType.UNKNOWN:
expression_error(f"Unexpected token '{token.value}'.", token.line, token.file)
compiled_code += f'\nTABL'
terminator_type = token.type
elif token.type == LexType.VARIABLE:
if terminator_type != LexType.UNKNOWN:
expression_error(f"Unexpected token '{token.value}'.", token.line, token.file)
var_id: Optional[str] = global_compiler_state.get_var_identifier(token, True, unsafe=unsafe)
compiled_code += f'\nVGET "{var_id}"'
terminator_type = token.type
elif token.type == LexType.STRING:
if terminator_type != LexType.UNKNOWN:
expression_error(f"Unexpected token '{token.value}'.", token.line, token.file)
compiled_code += f'\nPUSH "{token.get_nambly_string()}"'
terminator_type = token.type
elif token.type == LexType.ACCESS_OPEN:
if terminator_type == LexType.UNKNOWN:
expression_error(
"Found a table access without a variable or a function.",
token.line,
token.file
)
elif terminator_type not in [LexType.VARIABLE, LexType.WORD, LexType.STRING, LexType.FLOAT, LexType.INTEGER, LexType.TABLE]:
expression_error(
"Attempting to access something that cannot be a table.",
token.line,
token.file
)
access_tokens = []
access_depth += 1
elif token.type in [LexType.INTEGER, LexType.FLOAT]:
if terminator_type != LexType.UNKNOWN:
expression_error(f"Unexpected token '{token.value}'.", token.line, token.file)
compiled_code += f"\nPUSH {token.value}"
terminator_type = token.type
elif token.type == LexType.WORD:
if terminator_type != LexType.UNKNOWN:
expression_error(f"Unexpected token '{token.value}'.", token.line, token.file)
terminator_type = token.type
function_call_token = token
if next_token is None or next_token.type != LexType.PAR_OPEN:
expression_error(
"Expecting argument list after function call.",
token.line,
token.file
)
elif token.type == LexType.PAR_OPEN:
if terminator_type not in [LexType.VARIABLE, LexType.WORD]:
expression_error(
"Calling non-functional value.",
token.line,
token.file
)
arguments_list: List[List[Token]] = []
arguments: List[Token] = []
open_pars: int = 1
prev_token: Optional[Token] = None
while expr_tokens:
token: Token = expr_tokens[0]
if token.type == LexType.PAR_OPEN:
open_pars += 1
if open_pars > 1:
arguments.append(token)
elif token.type == LexType.PAR_CLOSE:
if open_pars > 1:
arguments.append(token)
open_pars -= 1
if open_pars == 0:
if not arguments and (prev_token is not None and prev_token.type == LexType.DECORATION and prev_token.value == ","):
#expression_error(
# f"Empty argument for function call",
# token.line,
# token.file
#)
pass
else:
if arguments:
arguments_list.append(arguments)
arguments = []
expr_tokens.pop(0)
break
elif open_pars > 1:
arguments.append(token)
elif token.type == LexType.DECORATION:
if token.value != ",":
expression_error(
f"Unexpected string '{token.value}'",
token.line,
token.file
)
elif not arguments:
expression_error(
f"Empty argument for function call",
token.line,
token.file
)
else:
if arguments:
arguments_list.append(arguments)
arguments = []
else:
arguments.append(token)
prev_token = token
expr_tokens.pop(0)
if expr_tokens:
if expr_tokens[0].type not in (LexType.ACCESS_OPEN, LexType.PAR_OPEN):
expression_error(
f"Unexpected expression element: {expr_tokens[0].value} (did you forget a ';'?)",
token.line,
token.file
)
# Call the function
if terminator_type == LexType.WORD:
compiled_code += "\n" + compile_function_call(function_call_token, arguments_list)
# TODO $a(2, 3, 4)
else:
expression_error(
f"Unexpected operator: '{token.value}'",
token.line,
token.file
)
if add_minus_code:
compiled_code += "\nPUSH -1"
compiled_code += "\nMULT"
return compiled_code
def stylize_namby(code: str) -> str:
"""Stilizes the nambly code by removing unnecessary breaks.
"""
new_lines = ""
for line in code.split("\n"):
if line:
new_lines += line + "\n"
return new_lines
def compile_lines(tokenized_lines: List[List[Token]]) -> str:
"""Takes a list of list of lexed tokens and compiles them into Nambly code.
"""
compiled_code: str = ""
for line in tokenized_lines:
# Check first token in the line, this is our command
command = line[0]
compiled_code += get_debug_info(command)
args = []
if len(line) > 1:
args = line[1:]
if command.type == LexType.WORD:
# --- in command ---
if command.value == "in":
compiled_code += "\n" + parse_command_in(command, args, False)
elif command.value == "global":
compiled_code += "\n" + parse_command_in(command, args, True)
elif command.value == "while":
compiled_code += "\n" + parse_command_while(command, args)
elif command.value == "whileis":
compiled_code += "\n" + parse_command_whileis(command, args)
elif command.value == "for":
compiled_code += "\n" + parse_command_for(command, args)
elif command.value == "until":
compiled_code += "\n" + parse_command_until(command, args)
elif command.value == "if":
compiled_code += "\n" + parse_command_if(command, args)
elif command.value == "elif":
compiled_code += "\n" + parse_command_elif(command, args)