-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.py
More file actions
1428 lines (1300 loc) · 58 KB
/
codegen.py
File metadata and controls
1428 lines (1300 loc) · 58 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 os
import re
from errors import CompilerError, ErrorCode
# Precompiled regexes for better performance
IDENTIFIER_SANITIZE_RE = re.compile(r"[^a-zA-Z0-9_]")
IDENTIFIER_VALIDATE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
def format_parameters(params):
"""Format function parameters with their types, handling type declarations."""
formatted = []
i = 0
while i < len(params):
if i + 1 < len(params) and params[i] in [
"int",
"double",
"float",
"bool",
"string",
]:
param_type = params[i]
param_name = IDENTIFIER_SANITIZE_RE.sub("_", params[i + 1])
# Convert Z types to C types for parameters
if param_type == "string":
c_type = "const char*"
else:
c_type = param_type
formatted.append(f"{c_type} {param_name}")
i += 2
else:
# All parameters must be typed now
raise CompilerError(
f"Parameter {params[i]} must have explicit type",
error_code=ErrorCode.TYPE_ERROR,
)
return formatted
def sanitize_identifier(name):
"""Remove invalid characters from variable names."""
return IDENTIFIER_SANITIZE_RE.sub("_", name)
def is_number(token: str) -> bool:
try:
float(token)
return True
except Exception:
return False
def sanitize_condition(cond):
"""Remove trailing colons from conditions like IF, WHILE."""
return cond.rstrip(":")
def add_overflow_check(
prefix: str, operation: str, a: str, b: str, res_var: str, line_num: int
) -> list[str]:
"""Generate C code with overflow check for arithmetic operations.
Args:
prefix: Indentation prefix
operation: The arithmetic operation ('+', '-', '*', '/', '%')
a: Left operand
b: Right operand
res_var: Result variable name
line_num: Line number for error reporting
Returns:
List of C code lines with overflow checking
"""
lines = []
if operation in ["+", "-", "*"]:
# For +, -, * we can do overflow checking
lines.append(f"{prefix}{{")
lines.append(
f"{prefix} long long _temp = (long long){a} {operation} (long long){b};"
)
lines.append(f"{prefix} if (_temp > INT_MAX || _temp < INT_MIN) {{")
lines.append(
f"{prefix} error_exit({ErrorCode.OVERFLOW.value}, "
f'"Integer overflow in {operation} operation at line {line_num}");'
)
lines.append(f"{prefix} }}")
lines.append(f"{prefix} {res_var} = {a} {operation} {b};")
lines.append(f"{prefix}}}")
else:
# For / and % we just do the operation directly
lines.append(f"{prefix}{res_var} = {a} {operation} {b};")
return lines
def translate_logical_operators(condition):
"""Translate Z logical operators to C logical operators."""
# Replace Z operators with C operators
condition = condition.replace(" AND ", " && ")
condition = condition.replace(" OR ", " || ")
condition = condition.replace(" NOT ", " !")
# Handle cases where operators might be at the beginning or end
condition = condition.replace("AND ", "&& ")
condition = condition.replace(" OR", " ||")
condition = condition.replace(" OR", " ||")
condition = condition.replace("NOT ", "! ")
condition = condition.replace("NOT ", "! ")
# Handle standalone operators (less common but possible)
condition = condition.replace(" AND", " &&")
condition = condition.replace("AND", "&&")
condition = condition.replace(" OR", " ||")
condition = condition.replace("OR", "||")
condition = condition.replace(" NOT", " !")
condition = condition.replace("NOT", "!")
return condition
def compile_imported_file(import_path):
"""Compile an imported Zlang file and extract non-main functions."""
try:
# Import here to avoid circular imports
from lexer import parse_z_file
from optimizer import optimize_instructions
from semantics import validate_const_and_types
# Parse the imported file
instructions, variables, declarations = parse_z_file(import_path)
# Optimize the instructions
optimized = optimize_instructions(instructions, import_path)
# Validate semantics
validate_const_and_types(optimized, declarations, import_path)
# Generate C code
c_code = generate_c_code(optimized, variables, declarations, z_file=import_path)
# Extract non-main functions
return extract_non_main_functions(c_code)
except Exception as e:
raise CompilerError(
f"Failed to compile imported file '{import_path}': {str(e)}",
error_code=ErrorCode.IMPORT_ERROR,
)
def extract_non_main_functions(c_code):
"""Extract all functions except main() from C code."""
lines = c_code.split("\n")
function_lines = []
in_function = False
brace_count = 0
function_start = -1
current_function_lines = []
for i, line in enumerate(lines):
stripped = line.strip()
# Detect function start (excluding main)
if (
(
stripped.startswith("int ")
or stripped.startswith("float ")
or stripped.startswith("double ")
or stripped.startswith("bool ")
or stripped.startswith("string ")
or stripped.startswith("char ")
or stripped.startswith("void ")
)
and "(" in stripped
and ")" in stripped
):
func_name = stripped.split("(")[0].strip().split()[-1]
# Only include user-defined functions (those prefixed with z_) and skip main
if func_name != "main" and func_name.startswith("z_"):
in_function = True
brace_count = 0
function_start = i
current_function_lines = [line]
# Count opening braces in this line
brace_count += line.count("{") - line.count("}")
elif in_function:
current_function_lines.append(line)
# Update brace count
brace_count += line.count("{") - line.count("}")
# Function ends when brace count returns to 0
if brace_count <= 0:
in_function = False
function_lines.extend(current_function_lines)
current_function_lines = []
return function_lines
def generate_c_code(instructions, variables, declarations, z_file="unknown.z"):
"""Generate compilable C code from parsed ZLang instructions."""
# Track pointer variables to avoid double declaration
pointer_vars = set()
c_lines = [
"#define _CRT_SECURE_NO_WARNINGS",
"#include <stdio.h>",
"#include <stdlib.h>",
"#include <string.h>",
"#include <stdbool.h>",
"#include <math.h>",
"#include <limits.h>",
"",
"// Array structure",
"typedef struct {",
" void* data; // Pointer to array data",
" size_t size; // Current number of elements",
" size_t capacity; // Allocated capacity",
" size_t elem_size; // Size of each element",
" char type[10]; // Type of elements",
"} Array;",
"",
"// Array functions implementation",
"Array* array_create_with_capacity(size_t elem_size, const char* type, size_t initial_capacity) {",
" Array* arr = (Array*)malloc(sizeof(Array));",
' if (!arr) { fprintf(stderr, "Memory allocation failed\\n"); exit(1); }',
" arr->size = 0;",
" arr->capacity = initial_capacity > 0 ? initial_capacity : 4; // Ensure minimum capacity of 4",
" arr->elem_size = elem_size;",
" strncpy(arr->type, type, sizeof(arr->type) - 1);",
" arr->type[sizeof(arr->type) - 1] = '\\0';",
" arr->data = malloc(arr->capacity * elem_size);",
' if (!arr->data) { fprintf(stderr, "Memory allocation failed\\n"); exit(1); }',
" return arr;",
"}",
"",
"Array* array_create(size_t elem_size, const char* type) {",
" // Default initial capacity of 4",
" return array_create_with_capacity(elem_size, type, 4);",
"}",
"",
"void array_free(Array* arr) {",
" if (arr) {",
' if (strcmp(arr->type, "string") == 0) {',
" for (size_t i = 0; i < arr->size; i++) {",
" free(*((char**)arr->data + i));",
" }",
" }",
" free(arr->data);",
" free(arr);",
" }",
"}",
"",
"void array_resize(Array* arr) {",
" if (arr->capacity > SIZE_MAX / 2) { ",
' fprintf(stderr, "Error: Array too large\\n"); ',
" exit(1); ",
" }",
" arr->capacity *= 2;",
" void* new_data = realloc(arr->data, arr->capacity * arr->elem_size);",
" if (!new_data) { ",
' fprintf(stderr, "Memory reallocation failed\\n"); ',
" exit(1); ",
" }",
" arr->data = new_data;",
"}",
"",
"void array_push(Array* arr, const void* value) {",
" if (arr->size >= arr->capacity) {",
" array_resize(arr);",
" }",
" memcpy((char*)arr->data + arr->size * arr->elem_size, value, arr->elem_size);",
" arr->size++;",
"}",
"",
"void array_pop(Array* arr, void* out) {",
" if (arr->size == 0) {",
' fprintf(stderr, "Error: Cannot pop from empty array\\n");',
" exit(1);",
" }",
" arr->size--;",
" memcpy(out, (char*)arr->data + arr->size * arr->elem_size, arr->elem_size);",
"}",
"",
"size_t array_length(const Array* arr) {",
' if (!arr) { fprintf(stderr, "Error: Null array\\n"); exit(1); }',
" return arr->size;",
"}",
"",
"void* array_get(Array* arr, size_t index) {",
' if (!arr) { fprintf(stderr, "Error: Null array\\n"); exit(1); }',
" if (index >= arr->size) {",
' fprintf(stderr, "Error: Array index %zu out of bounds (size: %zu)\\n", index, arr->size);',
" exit(1);",
" }",
" return (char*)arr->data + index * arr->elem_size;",
"}",
"",
"// Print array function ",
"void print_array(Array* arr) {",
" if (!arr) {",
' printf("NULL\\n");',
" return;",
" }",
' printf("[");',
" for (size_t i = 0; i < arr->size; i++) {",
' if (i > 0) printf(", ");',
' if (strcmp(arr->type, "int") == 0) {',
' printf("%d", *((int*)array_get(arr, i)));',
' } else if (strcmp(arr->type, "float") == 0) {',
' printf("%f", *((float*)array_get(arr, i)));',
' } else if (strcmp(arr->type, "double") == 0) {',
' printf("%g", *((double*)array_get(arr, i)));',
' } else if (strcmp(arr->type, "bool") == 0) {',
' printf("%s", *((bool*)array_get(arr, i)) ? "true" : "false");',
' } else if (strcmp(arr->type, "string") == 0) {',
' printf("\\"%s\\"", *((const char**)array_get(arr, i)));',
" }",
" }",
' printf("]\\n");',
"}",
"",
"// Print functions",
"void print_int(int i) {",
' printf("%d\\n", i);',
"}",
"",
"void print_bool(int b) {",
' printf("%s\\n", (b) ? "true" : "false");',
"}",
"",
"void print_str(const char* s) {",
' printf("%s\\n", s);',
"}",
"",
"void print_ptr(const void* p) {",
' printf("%p\\n", p);',
"}",
"void error_exit(int code, const char* msg) {",
' fprintf(stderr, "Error [E%d]: %s\\n", code, msg);',
" exit(code);",
"}",
"double read_double(const char* prompt, double d) {",
' printf("%s", prompt);',
' if (scanf("%lf", &d) != 1) error_exit(1, "Failed to read number");',
" return d;",
"}",
"int read_int(const char* prompt, int i) {",
' printf("%s", prompt);',
' if (scanf("%d", &i) != 1) error_exit(1, "Failed to read integer");',
" return i;",
"}",
"const char* read_str(const char* prompt) {",
" (void)prompt; // Explicitly mark as unused to avoid warnings",
" // Use a fixed-size buffer for simplicity",
" static char buffer[1024];",
" if (fgets(buffer, sizeof(buffer), stdin) == NULL) {",
" buffer[0] = '\\0'; // Return empty string on error",
" }",
" // Remove trailing newline if present",
" size_t len = strlen(buffer);",
" if (len > 0 && buffer[len-1] == '\\n') {",
" buffer[len-1] = '\\0';",
" }",
" return buffer;",
"}",
"",
]
# Cache for sanitized identifiers to avoid redundant processing
sanitized_cache = {}
# Helper to check if a variable is const
def is_const(scope, name):
if (scope, name) in declarations:
return declarations[(scope, name)].get("const", False)
if (None, name) in declarations:
return declarations[(None, name)].get("const", False)
return False
# Helper to get C type from Z type
# Helper: map Z type → C type
def get_c_type(z_type):
if isinstance(z_type, str) and z_type.endswith("*"):
return z_type # already a pointer type (e.g., int*, double*)
if z_type == "string":
return "const char*"
return z_type
# Helper to get variable type
def get_var_type(scope, name):
# Handle boolean literals
if name in {"true", "false"}:
return "bool"
if (scope, name) in declarations:
return declarations[(scope, name)].get("type", "double")
if (None, name) in declarations:
return declarations[(None, name)].get("type", "double")
return "double"
# Track variable types: var_name -> type
variable_types = {}
# Track local variables and function names
function_params = {}
function_names = set()
local_vars = {}
normal_types = ["string", "int", "bool", "double", "float"]
current_function = None
func_depth = 0
for op, operands, line_num in instructions:
if op == "FNDEF":
fname = operands[0]
function_names.add(fname)
current_function = fname
func_depth = 0 # will increase on next INDENTs
# Check if return type is specified
if len(operands) > 1 and operands[-1] in [
"int",
"double",
"float",
"bool",
"string",
]:
# Last operand is return type, exclude it from params
params = operands[1:-1]
else:
params = operands[1:]
function_params[fname] = params
local_vars[fname] = set()
# Track parameter types
i = 0
while i < len(params):
if i + 1 < len(params) and params[i] in [
"int",
"double",
"float",
"bool",
"string",
]:
param_type = params[i]
param_name = params[i + 1]
variable_types[param_name] = param_type
i += 2
else:
# All parameters must be typed
raise CompilerError(
f"Parameter {params[i]} must have explicit type",
error_code=ErrorCode.TYPE_ERROR,
)
i += 1
elif current_function and op == "INDENT":
func_depth += 1
elif current_function and op == "DEDENT":
func_depth = max(func_depth - 1, 0)
if func_depth == 0:
current_function = None
elif current_function or op == "LET":
# Collect local identifiers based on operation semantics (including global LET)
dests = []
if op == "LET":
if len(operands) >= 2 and operands[0] in [
"int",
"float",
"double",
"string",
"bool",
]:
# Typed MOV: type dest [value]
var_type = operands[0]
dest = operands[1]
# Track the variable type (for use in other operations)
if dest not in variable_types:
variable_types[dest] = var_type
dests.append(dest)
elif len(operands) == 2:
# Assignment: dest expr - dest should already be declared
dest = operands[0]
dests.append(dest)
elif op == "CONST":
if len(operands) >= 2 and operands[0] in [
"int",
"float",
"double",
"string",
"bool",
]:
var_type = operands[0]
dest = operands[1]
# For CONST, we'll mark the variable as const in the declarations
if current_function:
declarations[(current_function, dest)] = {
"const": True,
"type": var_type,
"line": line_num,
}
else:
declarations[(None, dest)] = {
"const": True,
"type": var_type,
"line": line_num,
}
# Track the variable type (for use in other operations)
if dest not in variable_types:
variable_types[dest] = var_type
dests.append(dest)
elif op in ["ADD", "SUB", "MUL", "DIV", "MOD"] and len(operands) == 3:
a, b, res = operands
# Type inference for result based on operands
res_type = "double" # default
# Check if result variable has explicit type declaration
if res in variable_types:
res_type = variable_types[res]
else:
# Try to infer from operands
a_type = variable_types.get(a, "double")
b_type = variable_types.get(b, "double")
# If both operands are int, result is int (except for division which is double)
if a_type == "int" and b_type == "int" and op != "DIV":
res_type = "int"
# If either operand is double, result is double
elif a_type == "double" or b_type == "double":
res_type = "double"
# If either operand is bool, convert to int for arithmetic
elif a_type == "bool" or b_type == "bool":
res_type = "int"
# Track the inferred type
if res not in variable_types:
variable_types[res] = res_type
dests.append(res)
for d in dests:
if current_function and d in function_params[current_function]:
continue
if d not in sanitized_cache:
sanitized_cache[d] = sanitize_identifier(d)
d_clean = sanitized_cache[d]
if not is_number(d_clean) and IDENTIFIER_VALIDATE_RE.match(d_clean):
if current_function:
local_vars[current_function].add(d_clean)
# For global variables, don't add to local_vars since they're handled separately
# Global variables: filter to identifiers not declared as locals, params or function names
if variables:
declared_locals = set().union(*local_vars.values()) if local_vars else set()
declared_params = set()
for fname, params in function_params.items():
i = 0
while i < len(params):
if params[i] in [
"int",
"float",
"double",
"bool",
"string",
] and i + 1 < len(params):
if params[i + 1] not in sanitized_cache:
sanitized_cache[params[i + 1]] = sanitize_identifier(
params[i + 1]
)
declared_params.add(sanitized_cache[params[i + 1]])
i += 2
else:
if params[i] not in sanitized_cache:
sanitized_cache[params[i]] = sanitize_identifier(params[i])
declared_params.add(sanitized_cache[params[i]])
i += 1
global_var_lines = []
for var in sorted(variables):
if var in {"true", "false"}:
continue
if var not in sanitized_cache:
sanitized_cache[var] = sanitize_identifier(var)
var_clean = sanitized_cache[var]
if (
IDENTIFIER_VALIDATE_RE.match(var_clean)
and var_clean not in function_names
and var_clean not in declared_locals
and var_clean not in declared_params
):
var_type = get_var_type(None, var)
c_type = get_c_type(var_type)
const_prefix = "const " if is_const(None, var) else ""
if c_type in normal_types:
global_var_lines.append(f"{const_prefix}{c_type} {var_clean};")
else:
continue
if global_var_lines:
c_lines.append("// Global variables")
c_lines.extend(global_var_lines)
c_lines.append("")
# Generate functions
indent = " "
indent_level = 0
func_stack = [] # stack of raw function names to know when closing
for op, operands, line_num in instructions:
prefix = indent * indent_level
if op == "FNDEF":
raw_name = operands[0]
is_main = raw_name == "main"
if not is_main and raw_name not in sanitized_cache:
sanitized_cache[raw_name] = sanitize_identifier(raw_name)
fname = (
"main" if is_main else f"z_{sanitized_cache.get(raw_name, raw_name)}"
)
params = operands[1:]
# Check if return type is specified
ret_type = "int" if is_main else "double" # default
if len(operands) > 1 and operands[-1] in [
"int",
"double",
"float",
"bool",
"string",
]:
# Last operand is return type
ret_type = operands[-1]
params = operands[1:-1] # exclude return type from params
else:
params = operands[1:] # no return type specified
# Convert return type to C type
c_ret_type = get_c_type(ret_type)
param_str = ", ".join(format_parameters(params)) if not is_main else "void"
c_lines.append(f"{prefix}{c_ret_type} {fname}({param_str}) {{")
# declare local variables
for var in sorted(local_vars.get(raw_name, set())):
var_type = get_var_type(raw_name, var)
c_type = get_c_type(var_type)
const_prefix = "const " if is_const(raw_name, var) else ""
if const_prefix:
continue
# Initialize variables with appropriate default values based on type
if var_type == "string":
init_value = "NULL"
elif var_type == "int":
init_value = "0"
elif var_type == "bool":
init_value = "false"
else: # double, float
init_value = "0.0"
c_lines.append(
f"{prefix}{indent}{const_prefix}{c_type} {var} = {init_value};"
)
func_stack.append(raw_name)
indent_level += 1
continue
if op == "DEDENT":
indent_level = max(indent_level - 1, 0)
# Only pop from func_stack if we're closing a function (indent_level == 0)
if func_stack and indent_level == 0:
closing_func = func_stack.pop()
if closing_func == "main":
c_lines.append(f"{prefix}{indent}return 0;")
c_lines.append(f"{prefix}}}")
continue
if op in ["IF", "ELIF"]:
cond = " ".join(operands)
cond = sanitize_condition(cond)
cond = translate_logical_operators(cond)
if op == "IF":
c_lines.append(f"{prefix}if ({cond}) {{ ")
else: # ELIF
c_lines.append(f"{prefix}else if ({cond}) {{ ")
elif op in ["ELSE", "ELSE:"]:
if operands and operands != [":"]: # Allow 'ELSE:' as valid syntax
raise CompilerError(
"ELSE does not take any conditions",
line_num,
ErrorCode.SYNTAX_ERROR,
)
c_lines.append(f"{prefix}else {{ ")
elif op == "WHILE":
cond = " ".join(operands)
cond = sanitize_condition(cond)
cond = translate_logical_operators(cond)
c_lines.append(f"{prefix}while ({cond}) {{ ")
elif op == "FOR":
# Default values
var = "i"
start = "0"
end = "10" # Default range end
if operands:
var = operands[0]
if len(operands) >= 4:
# Handle FOR var start .. end format
try:
start = operands[1]
if operands[2] == "..":
end = operands[3] if len(operands) > 3 else "10"
else:
# Handle FOR var start..end format (no spaces around ..)
if ".." in operands[1]:
parts = operands[1].split("..")
start = parts[0] if parts[0] else "0"
end = parts[1] if len(parts) > 1 and parts[1] else "10"
except IndexError:
pass # Use defaults if parsing fails
if var not in sanitized_cache:
sanitized_cache[var] = sanitize_identifier(var)
var_clean = sanitized_cache[var]
c_lines.append(
f"{prefix}for (int {var_clean} = {start}; {var_clean} <= {end}; {var_clean}++) {{"
)
indent_level += 1
continue
if op == "LET":
if len(operands) >= 2 and operands[0] in [
"int",
"float",
"double",
"string",
"bool",
]:
var_type = operands[0]
dest = operands[1]
if dest not in sanitized_cache:
sanitized_cache[dest] = sanitize_identifier(dest)
dest_safe = sanitized_cache[dest]
# Check if a value was provided
if len(operands) > 2:
expr = " ".join(operands[2:])
else:
# No value provided, use type-appropriate default
if var_type == "string":
expr = "NULL"
elif var_type == "int":
expr = "0"
elif var_type == "bool":
expr = "false"
elif var_type in ["double", "float"]:
expr = "0.0"
# Check if this is a string literal
is_string_literal = expr.startswith('"') and expr.endswith('"')
# Check if this is a re-declaration
is_redeclaration = any(
line.strip().startswith(f"{var_type} {dest_safe} =")
or line.strip().startswith(f"const char* {dest_safe} =")
for line in c_lines
)
# Generate appropriate code based on type and declaration status
if is_string_literal:
if not is_redeclaration:
c_lines.append(f"{prefix}const char* {dest_safe} = {expr};")
else:
c_lines.append(f"{prefix}{dest_safe} = {expr};")
else:
if not is_redeclaration:
c_lines.append(f"{prefix}{var_type} {dest_safe} = {expr};")
else:
c_lines.append(f"{prefix}{dest_safe} = {expr};")
# Track the variable type for future reference
if dest_safe not in variable_types:
variable_types[dest_safe] = var_type
elif len(operands) == 2:
# Assignment: dest = expr
dest, expr = operands
# Check for pointer dereferencing (e.g., *ptr = 100)
is_pointer_deref = dest.startswith("*")
if is_pointer_deref:
# Handle pointer dereference assignment: *ptr = value
ptr_name = dest[1:] # Remove the *
if ptr_name not in sanitized_cache:
sanitized_cache[ptr_name] = sanitize_identifier(ptr_name)
ptr_safe = sanitized_cache[ptr_name]
c_lines.append(f"{prefix}*{ptr_safe} = {dest};")
else:
# Check if this is an array access (e.g., numbers[i])
if (
"[" in expr
and "]" in expr
and "=" not in expr
and "==" not in expr
and "!=" not in expr
):
# Handle array access
array_name = expr.split("[")[0]
array_idx = expr.split("[")[1].split("]")[0]
# Get the array type (Aint, Afloat, etc.)
array_type = variable_types.get(
array_name, "Aint"
) # Default to Aint if not found
# Map ZLang array types to C types
type_map = {
"Aint": "int",
"Afloat": "float",
"Adouble": "double",
"Abool": "bool",
"Astring": "const char*",
}
c_type = type_map.get(array_type, "int")
# Sanitize the destination variable name
if dest not in sanitized_cache:
sanitized_cache[dest] = sanitize_identifier(dest)
dest_safe = sanitized_cache[dest]
# Generate the array access code
c_lines.append(
f"{prefix}{c_type} {dest_safe} = *(({c_type}*)array_get({array_name}, {array_idx}));"
)
# Track the variable type for future reference
if dest_safe not in variable_types:
variable_types[dest_safe] = c_type
else:
# Check if source is a pointer dereference (e.g., *ptr)
is_source_pointer_deref = expr.startswith("*") and len(expr) > 1
if is_source_pointer_deref:
# Handle pointer dereferencing in source: dest = *ptr
ptr_name = expr[1:] # Remove the *
if ptr_name not in sanitized_cache:
sanitized_cache[ptr_name] = sanitize_identifier(
ptr_name
)
ptr_safe = sanitized_cache[ptr_name]
# Get the base type of the pointer
ptr_type = variable_types.get(
ptr_safe, "int*"
) # Default to int*
base_type = (
ptr_type.rstrip("*")
if ptr_type.endswith("*")
else "int"
)
# Sanitize the destination variable name
if dest not in sanitized_cache:
sanitized_cache[dest] = sanitize_identifier(dest)
dest_safe = sanitized_cache[dest]
# Generate the pointer dereference assignment
c_lines.append(f"{prefix}{dest_safe} = *{ptr_safe};")
# Track the variable type for future reference
if dest_safe not in variable_types:
variable_types[dest_safe] = base_type
else:
# Regular variable assignment
if dest not in sanitized_cache:
sanitized_cache[dest] = sanitize_identifier(dest)
dest_safe = sanitized_cache[dest]
# Check if this is a re-declaration
is_redeclaration = any(
line.strip().startswith(f"{dest_safe} =")
or line.strip().startswith(f"int {dest_safe} =")
or line.strip().startswith(f"double {dest_safe} =")
or line.strip().startswith(f"const char* {dest_safe} =")
for line in c_lines
)
if not is_redeclaration and dest_safe not in variable_types:
# If we don't know the type, default to int
c_lines.append(f"{prefix}int {dest_safe} = {expr};")
variable_types[dest_safe] = "int"
else:
c_lines.append(f"{prefix}{dest_safe} = {expr};")
continue
if op == "CONST":
if len(operands) >= 2 and operands[0] in [
"int",
"float",
"double",
"string",
"bool",
]:
dest = operands[1]
if dest not in sanitized_cache:
sanitized_cache[dest] = sanitize_identifier(dest)
# Check if a value was provided
if len(operands) > 2:
expr = " ".join(operands[2:])
else:
# No value provided, use type-appropriate default
var_type = operands[0]
if var_type == "string":
expr = "NULL"
elif var_type == "int":
expr = "0"
elif var_type == "bool":
expr = "false"
else: # double, float
expr = "0.0"
# Generate final const line with proper type handling for strings
var_type = operands[0]
if var_type == "string":
# For strings, we don't need an extra 'const' since 'const char*' already includes it
c_lines.append(
f"{prefix}const char* {sanitized_cache[dest]} = {expr};"
)
else:
# For other types, use the original type with const
c_lines.append(
f"{prefix}const {var_type} {sanitized_cache[dest]} = {expr};"
)
continue
if op == "ADD":
a, b, res = operands
if res not in sanitized_cache:
sanitized_cache[res] = sanitize_identifier(res)
c_lines.extend(
add_overflow_check(
prefix, "+", a, b, f"{sanitized_cache[res]}", line_num
)
)
continue
if op == "SUB":
a, b, res = operands
if res not in sanitized_cache:
sanitized_cache[res] = sanitize_identifier(res)
c_lines.extend(
add_overflow_check(
prefix, "-", a, b, f"{sanitized_cache[res]}", line_num
)
)
continue
if op == "MUL":
a, b, res = operands
if res not in sanitized_cache:
sanitized_cache[res] = sanitize_identifier(res)
c_lines.extend(
add_overflow_check(
prefix, "*", a, b, f"{sanitized_cache[res]}", line_num
)
)
continue
if op == "DIV":
a, b, res = operands
if res not in sanitized_cache:
sanitized_cache[res] = sanitize_identifier(res)
c_lines.extend(
add_overflow_check(
prefix, "/", a, b, f"{sanitized_cache[res]}", line_num
)
)
continue
if op == "MOD":
a, b, res = operands
if res not in sanitized_cache:
sanitized_cache[res] = sanitize_identifier(res)
c_lines.extend(
add_overflow_check(
prefix, "%", a, b, f"{sanitized_cache[res]}", line_num
)
)
continue
if op == "IMPORT":
file_name = operands[0]
if len(operands) == 1:
print()
if op == "PRINT":
printing_types = {
"int": "d",
"bool": "d",
"string": "s",
"double": "f",
"pointer": "p",
}
# First, handle the case where there are no operands (just print a newline)
if not operands:
c_lines.append(f'{prefix}printf("\n");')
continue
# Process each operand and generate appropriate print function calls