This repository was archived by the owner on Jun 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrysc
More file actions
executable file
·1503 lines (1195 loc) · 52.4 KB
/
Copy pathrysc
File metadata and controls
executable file
·1503 lines (1195 loc) · 52.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
#!/usr/bin/env python3
"""rys"""
import fcntl
import os
import struct
import sys
import termios
import warnings
from dataclasses import dataclass
from enum import Enum, auto
from typing import Any, Generator, Optional
import numpy as np
warnings.filterwarnings("error", category=Warning)
EXIT_OK: int = 0
EXIT_ERR: int = 1
RYS_ARGS: set[str] = set()
MAX_64 = 2**64
__version__ = "0.2"
__author__ = "Ari Archer <ari.web.xyz@gmail.com>"
class TokenType(Enum):
PUSH_INT = auto()
PUSH_STR = auto()
INSTRUCTION = auto()
DROP = auto()
ASSEMBLY = auto()
CHARZ = auto()
OPERATOR = auto()
STACKSZ = auto()
CPY = auto()
NOP = auto()
CLEAR = auto()
PROCCESSABLE = auto()
SASSERT = auto()
class ProceesableToken(Enum):
PROC_INCLUDE = auto()
class OperatorType(Enum):
PLUS = auto()
MINUS = auto()
MULTIPLY = auto()
DIVIDE = auto()
MODULO = auto()
POWER = auto()
class AsmFeatures(Enum):
EXIT = auto()
WRITEFD = auto()
WRITEFD_INT = auto()
SLEEP = auto()
class InstructionType(Enum):
INSTRUCTION_EXIT = auto()
INSTRUCTION_WRITEFD = auto()
INSTRUCTION_SLEEP = auto()
class RysType(Enum):
STR = auto()
INT = auto()
@dataclass
class Token:
t_type: TokenType
t_pos: tuple[int, int, str] # line, column, file
t_value: Any
NASM_ASM_FEATURES: dict[AsmFeatures, list[str]] = {
AsmFeatures.EXIT: ["_std_rys_exit:", " mov rax, 60", " syscall", " ret"],
AsmFeatures.WRITEFD: [
"_std_rys_writefd:",
" mov rax, 1",
" syscall",
" ret",
],
AsmFeatures.WRITEFD_INT: [
"_std_rys_writefd_int:",
" mov r9, -3689348814741910323",
" sub rsp, 40",
" lea rcx, [rsp+30]",
".L2:",
" mov rax, rdi",
" lea r8, [rsp+32]",
" mul r9",
" mov rax, rdi",
" sub r8, rcx",
" shr rdx, 3",
" lea rsi, [rdx+rdx*4]",
" add rsi, rsi",
" sub rax, rsi",
" add eax, 48",
" mov BYTE [rcx], al",
" mov rax, rdi",
" mov rdi, rdx",
" mov rdx, rcx",
" sub rcx, 1",
" cmp rax, 9",
" ja .L2",
" lea rax, [rsp+32]",
" sub rdx, rax",
" xor eax, eax",
" lea rsi, [rsp+32+rdx]",
" mov rdx, r8",
" mov rax, 1",
" syscall",
" add rsp, 40",
" ret",
],
AsmFeatures.SLEEP: [
"struc timespec",
" .tv_sec resq 1",
" .tv_nsec resq 1",
"endstruc",
"_std_rys_sleep:",
" mov rax, 35",
" mov rdi, _g_nanosleep_st",
" mov rsi, 0",
" syscall",
" ret",
],
}
def msg(message: str, header: str = "ERROR", pad: str = " ") -> int:
"""Print message and return error exit code"""
if "quiet" not in RYS_ARGS:
sys.stderr.write(
(
pad
+ "{message:"
+ str(
min(
struct.unpack(
"HHHH",
fcntl.ioctl(
0, termios.TIOCGWINSZ, struct.pack("HHHH", 0, 0, 0, 0)
),
)[1]
- len(header)
- len(pad) * 2,
128,
)
)
+ "s}{header}\n"
).format(message=message, header=header)
)
return EXIT_ERR
def minfo(message: str) -> None:
"""wrapper for msg() for info messages"""
msg(message, "INFO")
def tk_die(message: str, token: Token) -> None:
sys.exit(
msg(f"{token.t_pos[2]}:{token.t_pos[0] or 1}:{token.t_pos[1] or 1}: {message}")
)
def vprint(message: str) -> None:
if "verbose" not in RYS_ARGS:
return
msg(message, "DEBUG")
assert len(RysType) == 2, "Unhandled types in type-to-string"
def type_to_str(r_type: RysType) -> str:
type_name = f"Unknown ({r_type})"
if r_type == RysType.INT:
type_name = "integer"
elif r_type == RysType.STR:
type_name = "string"
return type_name
assert len(TokenType) == 13, "Unhandled token types in AST generation"
assert len(InstructionType) == 3, "Unhandled instructions in AST generation"
assert len(RysType) == 2, "Unhandled types in AST generation"
assert len(OperatorType) == 6, "Unhandled operator types in AST generation"
assert len(ProceesableToken) == 1, "Unhandled processable token types in AST generation"
def rys_to_ast(file_path: str) -> Generator[Token, None, None]:
minfo(f"Generating AST for {file_path!r}...")
config: dict[str, Any] = {}
token_ctx: set[str] = set()
tmp_stack: list[Any] = []
def new_token(token_type: TokenType, value: Any) -> Token:
vprint(f"New token with type {token_type!r} and value of {value!r}")
return Token(
token_type,
(
config.get("line", 1),
config.get("column", 1),
file_path,
),
value,
)
def die(message: str) -> None:
sys.exit(
msg(
f"{file_path}:{config.get('line', 1)}:{config.get('column', 1)}: {message}"
)
)
with open(file_path, "r") as rys_code:
for lidx, line in enumerate(rys_code, 1):
if "in.literal" in token_ctx:
die(
f'No closing double quote (") to close {type_to_str(RysType.STR)}',
)
config["line"] = lidx
for cidx, token in enumerate(line.split(" "), 1):
config["column"] = cidx
token = token.rstrip()
# String parsing sux
# TODO: better parsing like wtf does this even fucking
# like I mean it works, but I have no idea how to
# maintain it, please help :')
# btw "\\" does not work
if "in.literal" in token_ctx:
if not token.endswith('"') or token.endswith('\\"'):
tmp_stack.append(" " + token)
continue
elif token == '"' and "in.literal" not in token_ctx:
token_ctx.add("in.literal")
continue
if (
token.startswith('"')
and token.endswith('"')
and not token.endswith('\\"')
and "in.literal" not in token_ctx
):
yield new_token(TokenType.PUSH_STR, token[1:-1])
continue
elif token.endswith('"') and not token.endswith('\\"'):
tmp_stack.append(" " + token.removesuffix('"'))
full_str: str = "".join(tmp_stack)
yield new_token(TokenType.PUSH_STR, full_str)
tmp_stack = []
token_ctx.remove("in.literal")
continue
elif token.startswith('"'):
tmp_stack.append(token.removeprefix('"'))
token_ctx.add("in.literal")
continue
if token.startswith("--"):
# Ignore comments and everything after in the same line
break
if not token.strip():
# Ignore empty tokens
continue
if token.isnumeric():
try:
yield new_token(TokenType.PUSH_INT, int(token))
except ValueError:
die(
f"Failed to convert {token!r} to {type_to_str(RysType.INT)}"
)
else:
if token == "exit":
yield new_token(
TokenType.INSTRUCTION, InstructionType.INSTRUCTION_EXIT
)
elif token == "writefd":
yield new_token(
TokenType.INSTRUCTION, InstructionType.INSTRUCTION_WRITEFD
)
elif token == "sleep":
yield new_token(
TokenType.INSTRUCTION, InstructionType.INSTRUCTION_SLEEP
)
elif token == "cpy":
yield new_token(TokenType.CPY, None)
elif token == "drop":
yield new_token(TokenType.DROP, None)
elif token == "assembly":
yield new_token(TokenType.ASSEMBLY, None)
elif token == "charz":
yield new_token(TokenType.CHARZ, None)
elif token == "+":
yield new_token(TokenType.OPERATOR, OperatorType.PLUS)
elif token == "-":
yield new_token(TokenType.OPERATOR, OperatorType.MINUS)
elif token == "*":
yield new_token(TokenType.OPERATOR, OperatorType.MULTIPLY)
elif token == "/":
yield new_token(TokenType.OPERATOR, OperatorType.DIVIDE)
elif token == "%":
yield new_token(TokenType.OPERATOR, OperatorType.MODULO)
elif token == "**":
yield new_token(TokenType.OPERATOR, OperatorType.POWER)
elif token == "stacksz":
yield new_token(TokenType.STACKSZ, None)
elif token == "nop":
yield new_token(TokenType.NOP, None)
elif token == "clear":
yield new_token(TokenType.CLEAR, None)
elif token == "include":
yield new_token(
TokenType.PROCCESSABLE, ProceesableToken.PROC_INCLUDE
)
elif token == "sassert":
yield new_token(TokenType.SASSERT, None)
else:
die(f"Unknown token: {token!r}")
if "in.literal" in token_ctx:
die(f'No closing double quote (") to close {type_to_str(RysType.STR)}')
assert (
len(TokenType) == 13
), "Unhandled token types in nasm x86_64 linux assembly generation"
assert len(InstructionType) == 3, "Unhandled instructions in assembly generation"
assert len(RysType) == 2, "Unhandled types in assembly generation"
assert (
len(AsmFeatures) == 4
), "Unhandled asm features in generate_x86_64_nasm_assembly_linux()"
assert len(OperatorType) == 6, "Unhandled operator types in assembly generation"
assert (
len(ProceesableToken) == 1
), "Unhandled processable token types in nasm x86_64 linux assembly generation"
def generate_x86_64_nasm_assembly_linux(
ast: Generator[Token, None, None],
full: bool = True,
start_iname: int = 0,
stack: Optional[list[tuple[Any, RysType]]] = None,
features: Optional[set[AsmFeatures]] = None,
do_msg: bool = True,
) -> Generator[tuple[str, int], None, None]:
"""
API ([1] of return value)
-----------------------
0 -- assembly
(reserved) 1 -- data
2 -- bss
3 -- read-only data
"""
if do_msg:
minfo("Generating nasm x86_64 linux assembly from AST...")
asm_stack: list[tuple[Any, RysType]] = stack or []
asm_rodata: list[str] = []
asm_bss: list[str] = []
asm_features: set[AsmFeatures] = features or set()
start_lb: list[str] = []
tmp_stack: list[Any] = []
if full:
vprint("Generating nasm x86_64 64-bit initial header")
yield "BITS 64", 0
yield "segment .text", 0
for token in ast:
iname: str = f"_{start_iname}_{token.t_pos[0]}_{token.t_pos[1]}"
vprint(f"Parsing token {iname!r}")
if token.t_type == TokenType.PUSH_INT:
vprint(
f"Checking if {type_to_str(RysType.INT)} {token.t_value!r} fits into 64 bits"
)
if token.t_value > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {token.t_value!r} does not fit into 64 bits",
token,
)
asm_stack.append((token.t_value, RysType.INT))
elif token.t_type == TokenType.PUSH_STR:
vprint(f"Pushing {type_to_str(RysType.STR)} {token.t_value!r} onto stack")
asm_stack.append(
(
token.t_value.encode("raw_unicode_escape", errors="ignore").decode(
"unicode_escape", errors="ignore"
),
RysType.STR,
)
)
elif token.t_type == TokenType.DROP:
drop_ammount = asm_stack.pop()[0]
vprint(f"Droppping {drop_ammount} of elements from the stack")
for _ in range(drop_ammount):
asm_stack.pop()
elif token.t_type == TokenType.ASSEMBLY:
assembly_ammount: int = asm_stack.pop()[0]
vprint(f"Injecting extra {assembly_ammount} lines of assembly code")
for _ in range(assembly_ammount):
start_lb.append(asm_stack.pop()[0])
elif token.t_type == TokenType.CHARZ:
charz_ammount = asm_stack.pop()[0]
vprint(
f"Converting {charz_ammount} of charcodes into {type_to_str(RysType.STR)}"
)
for _ in range(charz_ammount):
tmp_stack.append(chr(asm_stack.pop()[0]))
asm_stack.append(("".join(tmp_stack), RysType.STR))
tmp_stack = []
elif token.t_type == TokenType.CPY:
cpy_ammount = asm_stack.pop()[0]
vprint(f"Copying {cpy_ammount} items from the stack")
for idx in range(cpy_ammount):
tmp_stack.append(asm_stack[-(idx + 1)])
asm_stack += tmp_stack[::-1]
tmp_stack = []
elif token.t_type == TokenType.OPERATOR:
if token.t_value == OperatorType.PLUS:
value1 = asm_stack.pop()[0]
value2 = asm_stack.pop()[0]
vprint(f"Summing {value1} and {value2}")
final = value1 + value2
if final > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {final!r} does not fit into 64 bits",
token,
)
asm_stack.append((final, RysType.INT))
elif token.t_value == OperatorType.MINUS:
value1 = asm_stack.pop()[0]
value2 = asm_stack.pop()[0]
vprint(f"Subtracting {value2} from {value1}")
final = value1 - value2
if final > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {final!r} does not fit into 64 bits",
token,
)
asm_stack.append((final, RysType.INT))
elif token.t_value == OperatorType.MULTIPLY:
value1 = asm_stack.pop()[0]
value2 = asm_stack.pop()[0]
vprint(f"Multipying {value1} {value2} times")
final = np.multiply(value1, value2)
if final > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {final!r} does not fit into 64 bits",
token,
)
asm_stack.append((final, RysType.INT))
elif token.t_value == OperatorType.DIVIDE:
value1 = asm_stack.pop()[0]
value2 = asm_stack.pop()[0]
vprint(f"Dividing {value1} into {value2} parts")
final = np.floor_divide(value1, value2)
if final > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {final!r} does not fit into 64 bits",
token,
)
asm_stack.append((final, RysType.INT))
elif token.t_value == OperatorType.MODULO:
value1 = asm_stack.pop()[0]
value2 = asm_stack.pop()[0]
vprint(f"Calculating {value1} modulo of {value2}")
final = np.mod(value1, value2)
if final > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {final!r} does not fit into 64 bits",
token,
)
asm_stack.append((final, RysType.INT))
elif token.t_value == OperatorType.POWER:
value1 = asm_stack.pop()[0]
value2 = asm_stack.pop()[0]
vprint(f"Raising {value1} to the power of {value2}")
final = np.power(value1, value2)
if final > MAX_64:
tk_die(
f"{type_to_str(RysType.INT)} {final!r} does not fit into 64 bits",
token,
)
asm_stack.append((final, RysType.INT))
else:
tk_die(f"Unknown operator: {token.t_value}", token)
elif token.t_type == TokenType.STACKSZ:
vprint("Pushing stack size onto the stack")
asm_stack.append((len(asm_stack), RysType.INT))
elif token.t_type == TokenType.NOP:
vprint("Adding a `nop` instruction to _start label")
start_lb.append(" nop")
elif token.t_type == TokenType.CLEAR:
vprint("Clearing the stack")
asm_stack = []
elif token.t_type == TokenType.PROCCESSABLE:
vprint(
"This is most likely a compiler bug, processable token detected in generate_x86_64_nasm_assembly_linux()"
)
tk_die(f"This token should be handled in preprocessing: {token}", token)
elif token.t_type == TokenType.SASSERT:
vprint("Passing assembly generation for static assert")
pass
elif token.t_type == TokenType.INSTRUCTION:
vprint("Generating assembly for instruction")
if token.t_value == InstructionType.INSTRUCTION_EXIT:
vprint("Adding a call to _std_rys_exit in _start label")
start_lb += [
f" mov rdi, {asm_stack.pop()[0]}",
r" call _std_rys_exit",
]
vprint("Adding EXIT feature to assembly features")
asm_features.add(AsmFeatures.EXIT)
elif token.t_value == InstructionType.INSTRUCTION_WRITEFD:
writefd_fd, writefd_string, writefd_string_type = (
asm_stack.pop()[0],
*asm_stack.pop(),
)
if writefd_string_type == RysType.STR:
vprint("Adding call to _std_rys_writefd to start label")
start_lb += [
f" mov rdi, {writefd_fd}",
f" mov rsi, str{iname}",
f" mov rdx, str_len{iname}",
r" call _std_rys_writefd",
]
rys_str: str = ",".join(
map(lambda char: str(ord(char)), writefd_string)
)
asm_rodata += [
f"str{iname}: db {rys_str if rys_str else 0}",
f"str_len{iname}: equ $-str{iname}",
]
vprint("Adding WRITEFD feature to assembly features")
asm_features.add(AsmFeatures.WRITEFD)
elif writefd_string_type == RysType.INT:
vprint("Adding call to _std_rys_writefd_int to start label")
start_lb += [
f" mov rdi, {writefd_fd}",
f" mov edi, {writefd_string}",
r" call _std_rys_writefd_int",
]
vprint("Adding WRITEFD_INT feature to assembly features")
asm_features.add(AsmFeatures.WRITEFD_INT)
vprint("Pushing the string length onto the stack")
asm_stack.append((len(str(writefd_string)), RysType.INT))
elif token.t_value == InstructionType.INSTRUCTION_SLEEP:
vprint("Generating sleep instruction assembly")
sleep_seconds, sleep_nanoseconds = (
asm_stack.pop()[0],
asm_stack.pop()[0],
)
vprint(f"nanosleep for {sleep_seconds}s and {sleep_nanoseconds}ns")
vprint("Adding call to _std_rys_sleep")
start_lb += [
f" mov qword [_g_nanosleep_st+timespec.tv_sec], {sleep_seconds}",
f" mov qword [_g_nanosleep_st+timespec.tv_nsec], {sleep_nanoseconds}",
r" call _std_rys_sleep",
]
if AsmFeatures.SLEEP not in asm_features:
vprint("Adding _g_nanosleep_st to .bss")
asm_bss.append("_g_nanosleep_st: resb timespec_size")
vprint("Adding SLEEP feature to assembly features")
asm_features.add(AsmFeatures.SLEEP)
else:
tk_die(f"Unknown instruction: {token.t_value}", token)
else:
tk_die(f"Unknown token: {token.t_type}", token)
vprint("Checking for unhandled stack items...")
if asm_stack:
msg(f"{len(asm_stack)} item(s) left on the stack:")
for val, typ in asm_stack:
sys.stderr.write(f" * {val!r}{type_to_str(typ):>10s}\n")
sys.exit(EXIT_ERR)
vprint("Generating features...")
for feature in asm_features:
for line in NASM_ASM_FEATURES[feature]:
yield line, 0
vprint("Looking for code")
if not start_lb:
msg("No actual code found")
sys.exit(EXIT_ERR)
if full:
vprint("Generating _start label header")
yield "global _start", 0
yield "_start:", 0
vprint("Generating _start")
for line in start_lb:
yield line, 0
if full and asm_rodata:
vprint("Generating .rodata segment header")
yield "segment .rodata", 3
vprint("generating .rodata")
for rodata in asm_rodata:
yield rodata, 3
if full and asm_bss:
vprint("Generating .bss segment header")
yield "segment .bss", 2
vprint("generating .bss")
for bss in asm_bss:
yield bss, 2
def usage() -> int:
help_text = [
f" Usage: {{ENV}}={{VAL}}... {os.path.basename(sys.argv[0])} <file | -help> -flag(s)",
"",
" FLAGS",
f" -help -- [{'on' if '-help' in sys.argv else 'off'}] print help",
f" -debug -- [{'on' if '-debug' in sys.argv else 'off'}] use debug build flags",
f" -release -- [{'on' if '-release' in sys.argv else 'off'}] use release/production build flags",
f" -linux-elf64-x86_64-nasm -- [{'on' if '-linux-elf64-x86_64-nasm' in sys.argv else 'off'}] generate linux elf64 x86_64 binary and assembly",
f" -run -- [{'on' if '-run' in sys.argv else 'off'}] run binary after compilation",
f" -- -- [{'on' if '--' in sys.argv[1:] else 'off'}] treat next argument as filename",
f" -o <filename> -- [{'on' if '-o' in sys.argv[1:] else 'off'}] output binary",
f" -strip -- [{'on' if '-strip' in sys.argv else 'off'}] strip binary after compiling",
f" -quiet -- [{'on' if '-quiet' in sys.argv else 'off'}] run quietly",
f" -verbose -- [{'on' if '-quiet' in sys.argv else 'off'}] print debug/verbose information",
f" -typecheck -- [{'on' if '-typecheck' in sys.argv else 'off'}] only typecheck, don't compile",
f" -no-typecheck -- [{'on' if '-no-typecheck' in sys.argv else 'off'}] never typecheck",
f" -size -- [{'on' if '-size' in sys.argv else 'off'}] optimise for size and memory usage",
"",
" ENV",
" RYS_LD_FLAGS -- all linker flags",
" RYS_USER_LD_FLAGS -- extra linker flags to add on top of LD flags",
" RYS_ASM_FLAGS -- all assembly flags",
" RYS_USER_ASM_FLAGS -- extra assembly flags to add on top of ASM flags",
" RYS_OFLAGS -- flags to pass to output binary if -run is passed",
]
print("\n".join(help_text), file=sys.stderr)
return EXIT_ERR
def parse_args() -> tuple[str, str]:
"""Returns the filename and output binary name"""
if sys.argv[1] == "-help":
usage()
sys.exit(EXIT_OK)
ctx: set = set()
filename: str = sys.argv[1]
output: str = ""
for arg in sys.argv[1:]:
if "literal" in ctx:
filename = arg
ctx.remove("literal")
continue
elif "output" in ctx:
output = arg
ctx.remove("output")
continue
if arg == "-help":
usage()
sys.exit()
elif arg == "-debug":
RYS_ARGS.add("debug_flags")
elif arg == "-release":
RYS_ARGS.add("release_flags")
elif arg == "-linux-elf64-x86_64-nasm":
RYS_ARGS.add("format_linux_elf64_x86_64_nasm")
elif arg == "-run":
RYS_ARGS.add("run")
elif arg == "--":
ctx.add("literal")
elif arg == "-o":
ctx.add("output")
elif arg == "-strip":
RYS_ARGS.add("strip")
elif arg == "-quiet":
RYS_ARGS.add("quiet")
elif arg == "-verbose":
RYS_ARGS.add("verbose")
elif arg == "-typecheck":
RYS_ARGS.add("typing")
elif arg == "-no-typecheck":
RYS_ARGS.add("no-typing")
elif arg == "-size":
RYS_ARGS.add("size")
elif os.path.exists(arg):
continue
else:
sys.exit(msg(f"Unknown argument: {arg!r}"))
vprint("Finished parsing arguments")
return (filename, output or os.path.splitext(os.path.basename(filename))[0])
assert len(TokenType) == 13, "Unhandled token types in type checking"
assert len(InstructionType) == 3, "Unhandled instructions in type checking"
assert len(RysType) == 2, "Unhandled types in type checking"
assert len(OperatorType) == 6, "Unhandled operator types in type checking"
assert len(ProceesableToken) == 1, "Unhandled processable token types in type checking"
def type_check_ast(
ast: Generator[Token, None, None],
do_msg: bool = True,
tp_stack: Optional[list[tuple[RysType, Any]]] = None,
) -> Generator[Token, None, None]:
if "no-typing" in RYS_ARGS:
vprint("Not type-checking AST")
for token in ast:
yield token
return
vprint("Type checking AST")
if do_msg:
minfo("Type checking program...")
stack: list[tuple[RysType, Any]] = tp_stack or []
tmp_stack: list[Any] = []
for token in ast:
if token.t_type == TokenType.PUSH_INT:
vprint(f"Type checking stack: push {type_to_str(RysType.INT)}")
stack.append((RysType.INT, token.t_value))
elif token.t_type == TokenType.PUSH_STR:
vprint(f"Type checking stack: push {type_to_str(RysType.STR)}")
stack.append((RysType.STR, token.t_value))
elif token.t_type == TokenType.INSTRUCTION:
vprint("Found instruction")
if token.t_value == InstructionType.INSTRUCTION_EXIT:
vprint("Type checking exit instruction")
if len(stack) < 1:
tk_die("Exit code not supplied", token)
exit_code_type = stack.pop()[0]
if exit_code_type != RysType.INT:
tk_die(
f"Exit expected {type_to_str(RysType.INT)} on the stack as exit code, but got {type_to_str(exit_code_type)}",
token,
)
elif token.t_value == InstructionType.INSTRUCTION_WRITEFD:
vprint("Type checking writefd instruction")
if len(stack) < 2:
tk_die("Not enough arguments for writefd", token)
vprint("Checking file descriptor type")
fd_type = stack.pop()[0]
if fd_type != RysType.INT:
tk_die(
f"WriteFD expected a {type_to_str(RysType.INT)} {type_to_str(RysType.INT)} the stack as the file descriptor, but got {type_to_str(fd_type)}",
token,
)
vprint("Checking string compatibility")
string_type, string = stack.pop()
if string_type not in (RysType.STR, RysType.INT):
tk_die(
f"writefd expected one of {', '.join(type_to_str(typ) for typ in (RysType.INT, RysType.STR))} on the stack as the content, but got {type_to_str(string_type)}",
token,
)
stack.append((RysType.INT, len(str(string))))
elif token.t_value == InstructionType.INSTRUCTION_SLEEP:
vprint("Type checking sleep instruction")
vprint("Checking stack size")
if len(stack) < 2:
tk_die("Not enough arguments for sleep", token)
vprint("Checking sleep argument types")
(
sleep_seconds_type,
sleep_seconds,
sleep_nanoseconds_type,
sleep_nanoseconds,
) = (
*stack.pop(),
*stack.pop(),
)
vprint("Checking seconds type...")
if sleep_seconds_type != RysType.INT:
tk_die(
f"sleep expected {type_to_str(RysType.INT)} for seconds, but got {type_to_str(sleep_seconds_type)}",
token,
)
vprint("Checking seconds range...")
if sleep_seconds > 2147483647 or sleep_seconds < 0:
tk_die(
"sleep expected seconds to be in the range of 0 and 2147483647",
token,
)
vprint("Checking nanoseconds type...")
if sleep_nanoseconds_type != RysType.INT:
tk_die(
f"sleep expected {type_to_str(RysType.INT)} for nanoseconds, but got {type_to_str(sleep_nanoseconds_type)}",
token,
)
vprint("Checking nanoseconds range...")
if sleep_nanoseconds > 999999999 or sleep_nanoseconds < 0:
tk_die(
"sleep expected nanoseconds to be in the range of 0 and 999999999",
token,
)
else:
tk_die(
f"Unknown instruction: {token.t_value}",
token,
)
elif token.t_type == TokenType.DROP:
vprint("Type checking drop")
if len(stack) < 2:
tk_die("Not enough arguments for drop", token)
vprint("Checking drop ammount type")
drop_ammount_type, drop_ammount = stack.pop()
if drop_ammount_type != RysType.INT:
tk_die(
f"Drop expected a {type_to_str(RysType.INT)} on the stack as the ammount of items to drop, but got {type_to_str(drop_ammount_type)}",
token,
)
vprint("Checking stack size")
if len(stack) < drop_ammount:
tk_die(
f"Drop: {drop_ammount} is bigger than the elements on the stack: {len(stack)}",
token,
)
vprint(f"Dropping {drop_ammount} elements from the type checking stack")
for _ in range(drop_ammount):
stack.pop()
elif token.t_type == TokenType.ASSEMBLY:
vprint("Type checking assembly")
if len(stack) < 2:
tk_die("Not enough arguments for drop", token)
vprint("Checking assembly ammount")
assembly_ammount_type, assembly_ammount = stack.pop()
if assembly_ammount_type != RysType.INT:
tk_die(
f"Assembly expected {type_to_str(RysType.INT)} on the stack as the assembly ammount, but got {type_to_str(assembly_ammount_type)}",
token,
)
vprint("Checking stack size")
if len(stack) < assembly_ammount:
tk_die(
f"Assembly: {assembly_ammount} is bigger than the elements on the stack: {len(stack)}",
token,
)
vprint("Cheking assembly lines")
for _ in range(assembly_ammount):
assembly_line_type = stack.pop()[0]
if assembly_line_type != RysType.STR:
tk_die(
f"Assembly: expected type {type_to_str(RysType.STR)}, got {type_to_str(assembly_line_type)}",
token,
)
elif token.t_type == TokenType.CHARZ:
vprint("Type checking charz")
vprint("Checking charz ammount")
charz_ammount_type, charz_ammount = stack.pop()
if charz_ammount_type != RysType.INT:
tk_die(
f"Charz expected {type_to_str(RysType.INT)} on the stack as the charz ammount, but got {type_to_str(charz_ammount_type)}",
token,
)
vprint("Checking stack size")
if len(stack) < charz_ammount:
tk_die(
f"Charz: {charz_ammount} is bigger than the elements on the stack: {len(stack)}",
token,
)
vprint(f"Checking {charz_ammount} charcodes")
for _ in range(charz_ammount):
charz_charcode_type, charz_charcode = stack.pop()
if charz_charcode_type != RysType.INT:
tk_die(
f"Charz: expected type {type_to_str(RysType.INT)}, got {type_to_str(charz_charcode_type)}",
token,
)
tmp_stack.append(chr(charz_charcode))
vprint(f"Pushing {type_to_str(RysType.STR)} onto the typechecking stack")
stack.append((RysType.STR, "".join(tmp_stack)))
tmp_stack = []
elif token.t_type == TokenType.OPERATOR: