Repository navigation
Expand file tree
/
Copy pathAssembler.py
More file actions
2117 lines (1783 loc) · 78.7 KB
/
Copy pathAssembler.py
File metadata and controls
2117 lines (1783 loc) · 78.7 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
from pathlib import Path
# Capacities, 4 MiB
INPUT_LIMIT = 4 * 1024 * 1024 # global
OUTPUT_LIMIT = 4 * 1024 * 1024 # global
EOF_PADDING = 17 # global
memory = [] # global memory
output_buffer = [] # global output buffer
sectionMemory = list([0] * 1024 * 1024) # global
functionMemory = list([0] * 1024 * 1024) # global
output_path = "" # global
input_name = "" # global
# imported WASI function, did not use nread_ptr, but WAL version would write the number of bytes read to memory at that address.
# WASI will implement this function in the WAL version.
def fd_read(fd, iovs_ptr, iovs_len, nread_ptr):
iovs_ptr.extend(fd.read(iovs_len))
return 0
# imported WASI function, did not use nwritten_ptr, but WAL version would write the number of bytes written to memory at that address.
# WASI will implement this function in the WAL version.
def fd_write(fd, iovs_ptr, iovs_len, nwritten_ptr):
if fd == 2:
fd = sys.stderr.buffer
written = fd.write(bytes(iovs_ptr[:iovs_len]))
if written != iovs_len:
exit_program(1)
return 0
# imported WASI function
def proc_exit(status):
sys.exit(status)
SECTION_BYTES_OUT = 0 # global
SECTION_LAST_BYTES_OUT = 0 # global
FUNCTION_BYTES_OUT = 0 # global
FUNCTION_LAST_BYTES_OUT = 0 # global
WRITING_TO_FUNCTION = 0 # global
LAST_SYMBOL_ID = 0 # global
CURRENT_SECTION: int = 0 # global
COUNT: int = 0 # global
IMPORT_FUNCTION_COUNT: int = 0 # global
IMPORT_MEMORY_COUNT: int = 0 # global
LOCAL_VARIABLE_COUNT: int = 0 # global
FUNCTION_SYMBOL_NAMES_START: int = 0 # global
FUNCTION_SYMBOL_VALUES_START: int = 0 # global
FUNCTION_SYMBOL_ID_START: int = 0 # global
# All named things use the same two flat stacks.
# Names are stored as ID, KIND, STR_LENGTH, STRING_BYTES.
# Values are stored as ID, VALUE.
# KIND 0 is a normal variable, KIND 1 is a control-flow label.
SYMBOL_VARIABLE = 0
SYMBOL_LABEL = 1
symbol_names = list([0] * 1024 * 4) # global
symbol_names_stack_index: int = 0 # global
symbol_values = list([0] * 1024 * 4) # global
symbol_values_stack_index: int = 0 # global
LABEL_SCOPE = 0 # global
LABEL_FIRST_SYMBOL_ID = 0 # global; labels from earlier functions are invalid
# Tracing
CURRENT_LINE = 1 # global
# Strings
s_ei_start = "Error `\0"
s_ei_end = "`: \0"
s_vdne_start = "Variable `\0"
s_vdne_end = "` does not exist.\n\0"
s_ihc_start = "Invalid hex character `\0"
s_ihc_end = "`, valid characters (0-9 and A-F).\n\0"
s_ibc_start = "Invalid binary character `\0"
s_ibc_end = "`, valid characters (0 and 1).\n\0"
s_iuc_start = "Invalid uleb character `\0"
s_iuc_end = "`, valid characters (0-9).\n\0"
s_iac_start = "Invalid ascii character `\0"
s_iac_end = "`, Expected a single character with ascii value within 1-127.\n\0"
s_ise_start = "Invalid SLEB 128 encoding `\0"
s_ise_end = "`, valid characters are (0-9 and '-') and expected atleast 1 digit after '-'.\n\0"
s_ifpn_start = "Invalid Floating-Point number `\0"
s_ifpn_end = "`, valid characters are (0-9, '-', and '.'), expects atleast 1 digit after sign if present, and number must not exceed exponent limit (i.e. 1.7976931348623157e+308).\n\0"
s_sizilc_start = "Scope is zero invalid label call `\0"
s_sizilc_end = "`.\n\0"
s_ik_start = "Invalid keyword `\0"
s_ik_end = "`.\n\0"
s_ldne_start = "Label `\0"
s_ldne_end = "` does not exist.\n\0"
s_ecind_start = "Error Code `\0"
s_ecind_end = "` is not defined.\n\0"
s_eool_start = "Error occurred on line `\0"
s_eool_end = "`.\n\0"
s_ois_start = "Occurred in Section `\0"
s_ois_end = "`.\n\0"
s_ois_TYPE = "TYPE\0"
s_ois_IMPORT = "IMPORT\0"
s_ois_FUNCTION = "FUNCTION\0"
s_ois_MEMORY = "MEMORY\0"
s_ois_EXPORT = "EXPORT\0"
s_ois_CODE = "CODE\0"
s_ois_DATA = "DATA\0"
s_ois_CUSTOM = "CUSTOM\0"
s_pf = "Program Fault.\0"
s_idsuw_start = "Invalid define syntax. Unexpected word `\0"
s_define_type_end = "`. Valid syntax is 'define_type FUNCTION <parameter1_type> <parameter2_type...> -> <return_type>'. Additionally can not have void as parameter type unless it is the only parameter. Void is a valid return type.\n\0"
s_define_import_end = "`. Valid syntax is 'define_import <module> <name> FUNCTION_KIND <type_index>' or 'define_import <module> <name> MEMORY_KIND <flags> <min> [<max>]'. Memory flags: 0 = minimum only, 1 = minimum and maximum; sizes are in 64 KiB pages.\n\0"
s_define_function_end = "`. Valid syntax is 'define_function <type_index> <name>'\n\0"
s_define_export_end = "`. Valid syntax is 'define_export FUNCTION_KIND <function_index> <name>'\n\0"
s_define_memory_end = "`. Valid syntax is 'define_memory <flags> <min> [<max>] <name>'. Flags: 0 = minimum only, 1 = minimum and maximum; sizes are in 64 KiB pages, with 0 <= min <= max <= 65536.\n\0"
s_define_data_end = "`. Valid syntax is 'define_data <active/passive> <destination_address> <STRING/STRING_NT> \"<text>\"' or 'define_data <active/passive> <destination_address> DATA <length> <bytes>\n\0"
s_define_code_end = "`. Valid syntax is 'define_code <parameter1_type> <parameter1_name> <parameters...>' or 'define_code none' AND expected next keyword to be 'define_locals'\n\0"
s_define_locals_end = "`. Valid syntax is 'define_locals <local1_type> <local1_name> <locals...>' or 'define_locals none'\n\0"
# runtime error strings
s_output_limit = "Generated binary exceeds the output buffer capacity\0"
s_cli_arguments = "Expected two arguments: python Assembler.py input.wal output.wasm\0"
s_input_file = "Input file does not exist or is not a regular file\0"
s_same_input_output = "Input and output must be different files\0"
s_input_limit = "Source exceeds the input region capacity\0"
s_non_ascii_source = "Source must contain only ASCII bytes\0"
s_nul_source = "Source must not contain embedded NUL bytes\0"
s_eof_padding = "Source leaves insufficient room for EOF padding\0"
s_output_directory = "Output directory does not exist\0"
s_output_file = "Output path is not a regular file\0"
s_function_capacity = "Function scratch buffer capacity exceeded\0"
s_section_capacity = "Section scratch buffer capacity exceeded\0"
s_symbol_names_capacity = "Symbol-name buffer capacity exceeded\0"
s_symbol_values_capacity = "Symbol-value buffer capacity exceeded\0"
def print_i32(value):
value = value & 0xFFFFFFFF
negative = value >= 0x80000000
if negative:
value = 0x100000000 - value
digits = bytearray()
while True:
digits.append(48 + value % 10)
value //= 10
if value == 0:
break
if negative:
digits.append(45)
digits.reverse()
fd_write(2, digits, len(digits), 0)
def print_char(value):
fd_write(2, bytes([value & 255]), 1, 0) # bytes([value & 255]) just means an array of one byte with the value of value & 255
def print_string(value: str):
# Python strings stand in for WAL pointers to zero-terminated strings.
data = value.split("\0", 1)[0].encode("utf-8")
fd_write(2, data, len(data), 0)
def write_char(char: int):
if len(output_buffer) >= OUTPUT_LIMIT:
runtime_error(s_output_limit)
output_buffer.append(char)
def exit_program(status):
proc_exit(status)
def runtime_error(message: str):
print_string("Assembler: ")
print_string(message)
print_char(10)
exit_program(1)
def handle_cli_input():
global output_path, input_name, memory
if len(sys.argv) != 3:
# The `python` command will not be in the WAL version, this is for the Python PythonTesting version.
runtime_error(s_cli_arguments)
input_name = sys.argv[1]
source_path = Path(input_name)
output_path = Path(sys.argv[2])
# validate the input and output paths
if not source_path.is_file():
runtime_error(s_input_file)
if (source_path.resolve() == output_path.resolve() or (output_path.exists() and source_path.samefile(output_path))):
runtime_error(s_same_input_output)
# Read the source bytes into source, up to the input limit plus one extra byte to detect overflow.
source = bytearray()
with source_path.open("rb") as source_file:
fd_read(source_file, source, INPUT_LIMIT + 1, 0)
source_length = len(source) # in wasi, the nread_ptr would be used to get source byte count, but to simplify fd_read, len(source) is used
if source_length > INPUT_LIMIT:
runtime_error(s_input_limit)
# Validate the source bytes.
index = 0
while index < source_length:
character = source[index]
if character > 127:
runtime_error(s_non_ascii_source)
if character == 0:
runtime_error(s_nul_source)
index += 1
# Normalize line endings in place - The write position never moves ahead of the read position.
# This is for CRLF normalization for end of line: `\n`, `\r\n`, `\r` -> `\n`
read_index = 0
write_index = 0
while read_index < source_length:
character = source[read_index]
read_index += 1
if character == 13: # CR
character = 10 # Replace with LF.
# Consume the LF following CR, if present.
if read_index < source_length:
if source[read_index] == 10:
read_index += 1
source[write_index] = character
write_index += 1
source_length = write_index
# Determine whether a trailing newline is needed.
needs_newline = 1
if source_length > 0:
if source[source_length - 1] == 10:
needs_newline = 0
# Reserve space for the newline and EOF padding before writing them.
if source_length + needs_newline + EOF_PADDING > INPUT_LIMIT:
runtime_error(s_eof_padding)
# Allocate destination memory with room for the optional newline and padding.
memory = [0] * (source_length + needs_newline + EOF_PADDING)
# Copy only the normalized source bytes.
index = 0
while index < source_length:
memory[index] = source[index]
index += 1
if needs_newline == 1:
memory[source_length] = 10
source_length += 1
# EOF padding is already zero from allocation.
output_buffer.clear()
def handle_cli_output():
if not output_path.parent.is_dir():
runtime_error(s_output_directory)
if output_path.exists() and not output_path.is_file():
runtime_error(s_output_file)
with output_path.open("wb") as output_file:
fd_write(output_file, output_buffer, len(output_buffer), 0)
def writeSectionChar(char: int) -> None:
global SECTION_BYTES_OUT
global FUNCTION_BYTES_OUT
global WRITING_TO_FUNCTION
if WRITING_TO_FUNCTION == 1:
if FUNCTION_BYTES_OUT >= len(functionMemory):
runtime_error(s_function_capacity)
functionMemory[FUNCTION_BYTES_OUT] = char
FUNCTION_BYTES_OUT = FUNCTION_BYTES_OUT + 1
else:
if SECTION_BYTES_OUT >= len(sectionMemory):
runtime_error(s_section_capacity)
sectionMemory[SECTION_BYTES_OUT] = char
SECTION_BYTES_OUT = SECTION_BYTES_OUT + 1
def writeSection(writing_function: int, type: int, length: int, start: int) -> None:
section_length = length
count = COUNT
if writing_function == 0:
write_char(type)
remaining_count = count
while remaining_count > 0:
length += 1
remaining_count >>= 7
# write length and count as ULEB128
length_byte = 0
while length > 0:
length_byte = length & 0x7F
if length >= 128:
length_byte |= 0x80
if writing_function == 1:
writeSectionChar(length_byte)
else:
write_char(length_byte)
length = length >> 7
count_byte = 0
while count > 0 and writing_function == 0: # if COUNT == 0, don't write, so count > 0 is fine
count_byte = count & 0x7F
if count >= 128:
count_byte |= 0x80
write_char(count_byte)
count = count >> 7
# write section data
index = start
while index < start + section_length:
if writing_function == 1:
writeSectionChar(functionMemory[index])
else:
write_char(sectionMemory[index])
index += 1
def isWhiteSpace(index: int) -> int:
return memory[index] == ord(' ') or memory[index] == ord('\t') or memory[index] == ord('\n')
def skipWhiteSpace(index: int) -> int:
global CURRENT_LINE
while True:
if memory[index] == ord('\n'):
CURRENT_LINE = CURRENT_LINE + 1
if not isWhiteSpace(index):
break
index = index + 1
return index
def isComment(index: int) -> int:
return memory[index] == ord(';')
def skipComment(index: int) -> int:
while True:
if memory[index] == ord('\n'):
break
index = index + 1
return index
def equals2(index: int, c1: int, c2: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and isWhiteSpace(index + 2)
def equals3(index: int, c1: int, c2: int, c3: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and isWhiteSpace(index + 3)
def equals4(index: int, c1: int, c2: int, c3: int, c4: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and isWhiteSpace(index + 4)
def equals5(index: int, c1: int, c2: int, c3: int, c4: int, c5: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and isWhiteSpace(index + 5)
def equals6(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and isWhiteSpace(index + 6)
def equals7(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and isWhiteSpace(index + 7)
def equals8(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and isWhiteSpace(index + 8)
def equals9(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and isWhiteSpace(index + 9)
def equals10(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and isWhiteSpace(index + 10)
def equals11(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int, c11: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and memory[index + 10] == c11 and isWhiteSpace(index + 11)
def equals12(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int, c11: int, c12: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and memory[index + 10] == c11 and memory[index + 11] == c12 and isWhiteSpace(index + 12)
def equals13(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int, c11: int, c12: int, c13: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and memory[index + 10] == c11 and memory[index + 11] == c12 and memory[index + 12] == c13 and isWhiteSpace(index + 13)
def equals14(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int, c11: int, c12: int, c13: int, c14: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and memory[index + 10] == c11 and memory[index + 11] == c12 and memory[index + 12] == c13 and memory[index + 13] == c14 and isWhiteSpace(index + 14)
def equals15(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int, c11: int, c12: int, c13: int, c14: int, c15: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and memory[index + 10] == c11 and memory[index + 11] == c12 and memory[index + 12] == c13 and memory[index + 13] == c14 and memory[index + 14] == c15 and isWhiteSpace(index + 15)
def equals16(index: int, c1: int, c2: int, c3: int, c4: int, c5: int, c6: int, c7: int, c8: int, c9: int, c10: int, c11: int, c12: int, c13: int, c14: int, c15: int, c16: int) -> int:
return memory[index] == c1 and memory[index + 1] == c2 and memory[index + 2] == c3 and memory[index + 3] == c4 and memory[index + 4] == c5 and memory[index + 5] == c6 and memory[index + 6] == c7 and memory[index + 7] == c8 and memory[index + 8] == c9 and memory[index + 9] == c10 and memory[index + 10] == c11 and memory[index + 11] == c12 and memory[index + 12] == c13 and memory[index + 13] == c14 and memory[index + 14] == c15 and memory[index + 15] == c16 and isWhiteSpace(index + 16)
def error(index, value):
print_string(s_ei_start)
print_i32(value)
print_string(s_ei_end)
index_pointer = index
if value == 0x01:
print_string(s_ihc_start)
print_char(memory[index_pointer])
print_string(s_ihc_end)
if value == 0x02:
print_string(s_ibc_start)
print_char(memory[index_pointer])
print_string(s_ibc_end)
if value == 0x03:
print_string(s_vdne_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_vdne_end)
if value == 0x04:
print_string(s_ik_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_ik_end)
if value == 0x05:
print_string(s_ldne_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_ldne_end)
if value == 0x06:
print_string(s_sizilc_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_sizilc_end)
if value == 0x07:
print_string(s_iac_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_iac_end)
if value == 0x08:
print_string(s_ise_start)
print_char(memory[index_pointer])
print_string(s_ise_end)
if value == 0x09:
print_string(s_iuc_start)
print_char(memory[index_pointer])
print_string(s_iuc_end)
if value == 0x0A:
print_string(s_ifpn_start)
print_char(memory[index_pointer])
print_string(s_ifpn_end)
if value == 0x0B:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_type_end)
if value == 0x0C:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_import_end)
if value == 0x0D:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_function_end)
if value == 0x0E:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_export_end)
if value == 0x0F:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_memory_end)
if value == 0x10:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_data_end)
if value == 0x11:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_code_end)
if value == 0x12:
print_string(s_idsuw_start)
while not isWhiteSpace(index_pointer):
print_char(memory[index_pointer])
index_pointer += 1
print_string(s_define_locals_end)
if value > 0x12 or value < 0x01:
print_i32(value)
print_string(s_ecind_end)
print_string(s_ois_start)
if CURRENT_SECTION == 0x00:
print_string(s_ois_CUSTOM)
if CURRENT_SECTION == 0x01:
print_string(s_ois_TYPE)
if CURRENT_SECTION == 0x02:
print_string(s_ois_IMPORT)
if CURRENT_SECTION == 0x03:
print_string(s_ois_FUNCTION)
if CURRENT_SECTION == 0x05:
print_string(s_ois_MEMORY)
if CURRENT_SECTION == 0x07:
print_string(s_ois_EXPORT)
if CURRENT_SECTION == 0x0A:
print_string(s_ois_CODE)
if CURRENT_SECTION == 0x0B:
print_string(s_ois_DATA)
print_string("` of file `")
print_string(input_name)
print_string("`.\n")
print_string(s_eool_start)
print_i32(CURRENT_LINE)
print_string(s_eool_end)
index_pointer = index
while index_pointer > 0 and memory[index_pointer - 1] != ord('\n'):
index_pointer -= 1
start_of_line = index_pointer
print_char(ord('\n'))
while memory[index_pointer] != ord('\n'):
print_char(memory[index_pointer])
index_pointer += 1
print_char(ord('\n'))
while start_of_line < index:
print_char(ord(' '))
start_of_line += 1
while not isWhiteSpace(start_of_line):
print_char(ord('~'))
start_of_line += 1
print_char(ord('\n'))
print_char(ord('\n'))
print_string(s_pf)
exit_program(value)
def writeByte(number: int):
byte = 0
if number == 0:
writeSectionChar(0x00)
return
while number > 0:
byte = number & 0x7F
if number >= 128:
byte |= 0x80
writeSectionChar(byte)
number = number >> 7
def writeSignedByte(number: int):
while True:
byte = number & 0x7F
number >>= 7
finished = (
(number == 0 and (byte & 0x40) == 0) or
(number == -1 and (byte & 0x40) != 0)
)
if not finished:
byte |= 0x80
writeSectionChar(byte)
if finished:
return
def writeFromHex(index: int) -> int:
index = skipWhiteSpace(index)
result = 0
val = 0
char = 0
while True:
char = memory[index]
if char >= ord('0') and char <= ord('9'):
val = char - ord('0')
elif char >= ord('A') and char <= ord('F'):
val = char - ord('A') + 10
elif char >= ord('a') and char <= ord('f'):
val = char - ord('a') + 10
else:
error(index, 0x01)
result = result * 16 + val
index = index + 1
if isWhiteSpace(index):
break
writeByte(result)
return index
def writeFromBin(index: int) -> int:
index = skipWhiteSpace(index)
result = 0
val = 0
char = 0
while True:
char = memory[index]
if char == ord('0') or char == ord('1'):
val = char - ord('0')
else:
error(index, 0x02)
result = (result << 1) | val
index = index + 1
if isWhiteSpace(index):
break
writeByte(result)
return index
def writeFromString(index: int) -> int:
index = skipWhiteSpace(index)
while True:
writeSectionChar(memory[index])
index = index + 1
if isWhiteSpace(index):
break
return index
def writeFromUleb(index: int) -> int:
index = skipWhiteSpace(index)
result = 0
digit = 0
while True:
if memory[index] < ord('0') or memory[index] > ord('9'):
error(index, 0x09)
digit = memory[index] - ord('0')
result = result * 10 + digit
index += 1
if isWhiteSpace(index):
break
writeByte(result)
return index
def writeFromSleb(index: int) -> int:
index = skipWhiteSpace(index)
number_start = index
negative = 0
number = 0
if memory[index] == ord('-'):
negative = 1
index += 1
if memory[index] < ord('0') or memory[index] > ord('9'):
error(number_start, 0x08)
while memory[index] != 0 and not isWhiteSpace(index):
char = memory[index]
if char < ord('0') or char > ord('9'):
error(index, 0x08)
number = number * 10 + char - ord('0')
index += 1
if negative:
number = -number
if number < -2147483648 or number > 2147483647:
error(number_start, 0x04)
writeSignedByte(number)
return index
def writeFromAscii(index: int) -> int:
index = skipWhiteSpace(index)
char = memory[index]
if char > 127:
error(index, 0x07)
if memory[index + 1] != 0 and not isWhiteSpace(index + 1):
error(index, 0x07)
if char >= 64:
writeSectionChar(char | 0x80)
writeSectionChar(0)
else:
writeSectionChar(char)
return index + 1
def writeFromFloat32(index: int) -> int:
return writeFromFloat(index, 23, 8, 127)
def writeFromFloat64(index: int) -> int:
return writeFromFloat(index, 52, 11, 1023)
def writeFromFloat(index: int, fraction_bits: int, exponent_bits: int, bias: int) -> int:
index = skipWhiteSpace(index)
number_start = index
negative = 0
decimal_seen = 0
digit_count = 0
number = 0.0
scale = 1.0
if memory[index] == 45:
negative = 1
index += 1
while memory[index] != 0 and not isWhiteSpace(index):
char = memory[index]
if char == 46:
if decimal_seen:
error(index, 0x0A)
decimal_seen = 1
else:
if char < 48 or char > 57:
error(index, 0x0A)
number = number * 10.0 + (char - 48)
digit_count += 1
if decimal_seen:
scale *= 10.0
if number > 1.7976931348623157e308:
error(number_start, 0x0A)
if scale > 1.7976931348623157e308:
error(number_start, 0x0A)
index += 1
if digit_count == 0:
error(number_start, 0x0A)
number = number / scale
writeFloatBits(number, negative, fraction_bits, exponent_bits, bias, number_start)
return index
def writeFloatBits(number: float, negative: int, fraction_bits: int, exponent_bits: int, bias: int, number_start: int):
exponent = 0
encoded_exponent = 0
fraction = 0
exponent_limit = (1 << exponent_bits) - 1
if number != 0.0:
while number >= 2.0: # Normalize towards 1 <= number < 2.
number /= 2.0
exponent += 1
while number < 1.0 and exponent > 1 - bias: # Stop at the smallest normal exponent.
number *= 2.0
exponent -= 1
if number < 1.0: # Subnormal: no implicit leading 1.
encoded_exponent = 0
else:
encoded_exponent = exponent + bias
number -= 1.0
if encoded_exponent >= exponent_limit:
error(number_start, 0x0A)
# Extract the fraction one binary digit at a time.
bit_index = 0
while bit_index < fraction_bits:
number *= 2.0
fraction <<= 1
if number >= 1.0:
fraction |= 1
number -= 1.0
bit_index += 1
# Round to nearest, resolving exact ties towards even.
if number > 0.5 or (
number == 0.5 and (fraction & 1) != 0
):
fraction += 1
# Rounding can carry into the exponent.
if fraction == (1 << fraction_bits):
fraction = 0
encoded_exponent += 1
if encoded_exponent >= exponent_limit:
error(number_start, 0x0A)
bits = (negative << (fraction_bits + exponent_bits)) | (encoded_exponent << fraction_bits) | fraction
byte_count = (1 + exponent_bits + fraction_bits) // 8
byte_index = 0
# Least-significant byte first: little endian.
while byte_index < byte_count:
writeSectionChar(bits & 0xFF)
bits >>= 8
byte_index += 1
def check_symbol_capacity(name_length: int):
if symbol_names_stack_index + 3 + name_length > len(symbol_names):
runtime_error(s_symbol_names_capacity)
if symbol_values_stack_index + 2 > len(symbol_values):
runtime_error(s_symbol_values_capacity)
def setVariable(index: int) -> int:
global LAST_SYMBOL_ID
global symbol_names_stack_index
global symbol_values_stack_index
variable_name_start = index
variable_name_length = 0
loop_index = 0
result = 0
while memory[index + variable_name_length] != 0 and not isWhiteSpace(index + variable_name_length):
variable_name_length += 1
index += variable_name_length
index = skipWhiteSpace(index)
# Get value
while True:
digit = memory[index] - ord('0')
result = result * 10 + digit
index += 1
if isWhiteSpace(index):
break
# Check if variable already exists
name_index = 0
while name_index < symbol_names_stack_index:
symbol_id = symbol_names[name_index]
symbol_kind = symbol_names[name_index + 1]
name_length = symbol_names[name_index + 2]
if symbol_kind == SYMBOL_VARIABLE and name_length == variable_name_length:
matches = True
for i in range(variable_name_length):
if symbol_names[name_index + 3 + i] != memory[variable_name_start + i]:
matches = False
break
if matches:
# Find existing value by symbol ID
value_index = 0
while value_index < symbol_values_stack_index:
if symbol_values[value_index] == symbol_id:
symbol_values[value_index + 1] = result
return index
value_index += 2
# Move to next symbol
name_index += 3 + name_length
# Variable does not exist; create it
check_symbol_capacity(variable_name_length)
# Store variable name
symbol_names[symbol_names_stack_index] = LAST_SYMBOL_ID
symbol_names_stack_index += 1
symbol_names[symbol_names_stack_index] = SYMBOL_VARIABLE
symbol_names_stack_index += 1
symbol_names[symbol_names_stack_index] = variable_name_length
symbol_names_stack_index += 1
while loop_index < variable_name_length:
symbol_names[symbol_names_stack_index] = memory[variable_name_start + loop_index]
symbol_names_stack_index += 1
loop_index += 1
# Store variable value
symbol_values[symbol_values_stack_index] = LAST_SYMBOL_ID
symbol_values_stack_index += 1
symbol_values[symbol_values_stack_index] = result
symbol_values_stack_index += 1
LAST_SYMBOL_ID += 1
return index
def getVariable(index: int, signed_bits: int = 0) -> int:
variable_name_start = index
variable_name_length = 0
vname_pointer = 0
variable_id = 0
matches = 0
stored_name_length = 0
while memory[index + variable_name_length] != 0 and not isWhiteSpace(index + variable_name_length):
variable_name_length += 1
index += variable_name_length
# Search symbol names for a normal variable.
while vname_pointer < symbol_names_stack_index:
variable_id = symbol_names[vname_pointer]
vname_pointer += 1
symbol_kind = symbol_names[vname_pointer]
vname_pointer += 1
stored_name_length = symbol_names[vname_pointer]
vname_pointer += 1
matches = 1
# Lengths must match first
if stored_name_length != variable_name_length:
matches = 0
if symbol_kind != SYMBOL_VARIABLE:
matches = 0
# Compare characters
loop_index = 0
while loop_index < stored_name_length:
if matches == 1:
if memory[variable_name_start + loop_index] != symbol_names[vname_pointer + loop_index]:
matches = 0
loop_index += 1
if matches == 1:
value_pointer = 0
while value_pointer < symbol_values_stack_index:
if symbol_values[value_pointer] == variable_id:
value = symbol_values[value_pointer + 1]
if signed_bits:
if value < -(1 << (signed_bits - 1)) or value >= (1 << signed_bits):
error(variable_name_start, 0x04)
# Accept the unsigned spelling of an integer bit pattern.
if value >= (1 << (signed_bits - 1)):
value -= 1 << signed_bits
writeSignedByte(value)
else:
writeByte(value)
return index
value_pointer += 2
vname_pointer += stored_name_length
error(variable_name_start, 0x03)
def setLabel(index: int) -> int:
global LAST_SYMBOL_ID
global symbol_names_stack_index
global symbol_values_stack_index
label_start = index
label_length = 0
loop_index = 0
while memory[index + label_length] != 0 and not isWhiteSpace(index + label_length):
label_length += 1
index += label_length
if label_length == 0 or LABEL_SCOPE == 0:
error(label_start, 0x05)
check_symbol_capacity(label_length)
# Store label name: ID, kind, length, then each character byte.
symbol_names[symbol_names_stack_index] = LAST_SYMBOL_ID