Repository navigation
Expand file tree
/
Copy pathcode_generator.py
More file actions
904 lines (796 loc) · 37.2 KB
/
Copy pathcode_generator.py
File metadata and controls
904 lines (796 loc) · 37.2 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
from symbol import Symbol, SymbolKind
from symbol_table import SymbolTable
from ast_nodes import *
# 代码生成器
class CodeGenerator:
def __init__(self, symbol_table: SymbolTable):
self.symbol_table = symbol_table # 符号表
self.label_counter = 0 # 标签计数器
self.variables = {} # 变量字典
self.data_section = [] # 数据段
self.code_section = [] # 代码段
self.struct_definitions = {} # 结构体定义字典
self.string_literals = {} # 字符串字面量字典
self.temp_var_counter = 0 # 临时变量计数器
# 获取表达式类型
def _get_expression_type(self, node: ASTNode) -> str:
# 处理字面量节点
if isinstance(node, LiteralNode):
return node.literal_type
# 处理标识符节点
elif isinstance(node, IdentifierNode):
var_type = self.variables.get(node.name, "int")
if var_type in self.struct_definitions:
return var_type
return var_type
# 处理二元表达式节点
elif isinstance(node, BinaryExpressionNode):
left_type = self._get_expression_type(node.left)
right_type = self._get_expression_type(node.right)
if left_type == "float" or right_type == "float":
return "float"
return "int"
# 处理数组访问节点
elif isinstance(node, ArrayAccessNode):
if isinstance(node.array, IdentifierNode):
arr_name = node.array.name
arr_type = self.variables.get(arr_name, "int")
if arr_type.endswith("[]"):
base_type = arr_type[:-2]
return base_type
return arr_type
elif isinstance(node.array, MemberAccessNode):
if isinstance(node.array.obj, IdentifierNode):
obj_name = node.array.obj.name
obj_type = self.variables.get(obj_name, "")
member_name = node.array.member
field_type = self._get_struct_field_type(obj_type, member_name)
if field_type.endswith("[]"):
return field_type[:-2]
return field_type
# 处理成员访问节点
elif isinstance(node, MemberAccessNode):
if isinstance(node.obj, IdentifierNode):
obj_name = node.obj.name
obj_type = self.variables.get(obj_name, "")
return self._get_struct_field_type(obj_type, node.member)
return "int"
# 生成汇编代码
def generate(self, node: ASTNode) -> str:
node.accept(self) # 访问AST节点
output = []
output.append("section .data") # 数据段
for line in self.data_section:
output.append(line)
# 输出字符串字面量
for name, value in self.string_literals.items():
escaped = value.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace('\t', '\\t')
output.append(f' {name} db "{escaped}", 0')
output.append("")
output.append("section .bss") # BSS段
output.append(" temp_buffer resb 256") # 临时缓冲区
output.append("")
output.append("section .text") # 代码段
output.append(" global _start")
output.append("")
output.append("_start:")
for line in self.code_section:
output.append(line)
output.append("")
output.append(" mov eax, 1") # 系统调用号
output.append(" mov ebx, 0") # 退出码
output.append(" int 0x80") # 系统调用
output.append("")
output.append(self._generate_helper_functions()) # 辅助函数
return '\n'.join(output)
# 生成辅助函数
def _generate_helper_functions(self) -> str:
return '''
print_int:
push ebp
mov ebp, esp
sub esp, 16
mov eax, [ebp + 8]
mov ecx, 0
mov ebx, 10
test eax, eax
jns .positive
neg eax
push eax
mov eax, 4
mov ebx, 1
mov ecx, minus_char
mov edx, 1
int 0x80
pop eax
.positive:
test eax, eax
jnz .convert
mov byte [temp_buffer], '0'
mov ecx, 1
jmp .print
.convert:
mov edi, temp_buffer
add edi, 15
mov byte [edi], 0
dec edi
.convert_loop:
test eax, eax
jz .print
xor edx, edx
div ebx
add dl, '0'
mov [edi], dl
dec edi
inc ecx
jmp .convert_loop
.print:
inc edi
mov eax, 4
mov ebx, 1
mov edx, ecx
mov ecx, edi
int 0x80
mov esp, ebp
pop ebp
ret
print_float:
push ebp
mov ebp, esp
sub esp, 8
mov eax, [ebp + 8]
mov ebx, 100
xor edx, edx
div ebx
mov [ebp - 4], eax
mov [ebp - 8], edx
test eax, eax
jns .positive_f
neg eax
push eax
mov eax, 4
mov ebx, 1
mov ecx, minus_char
mov edx, 1
int 0x80
pop eax
.positive_f:
push eax
call print_int
add esp, 4
mov eax, 4
mov ebx, 1
mov ecx, dot_char
mov edx, 1
int 0x80
mov eax, [ebp - 8]
push eax
call print_int
add esp, 4
mov esp, ebp
pop ebp
ret
print_string:
push ebp
mov ebp, esp
mov eax, [ebp + 8]
push eax
call strlen
add esp, 4
mov edx, eax
mov ecx, [ebp + 8]
mov ebx, 1
mov eax, 4
int 0x80
mov esp, ebp
pop ebp
ret
strlen:
push ebp
mov ebp, esp
mov esi, [ebp + 8]
xor ecx, ecx
.strlen_loop:
mov al, [esi + ecx]
test al, al
jz .strlen_done
inc ecx
jmp .strlen_loop
.strlen_done:
mov eax, ecx
pop ebp
ret
section .data
minus_char db '-', 0
dot_char db '.', 0
newline_char db 10, 0
space_char db ' ', 0
'''
# 访问程序节点
def visit_program(self, node: ProgramNode):
for struct in node.structs:
struct.accept(self) # 访问结构体
for function in node.functions:
function.accept(self) # 访问函数
# 访问结构体定义节点
def visit_struct_definition(self, node: StructDefinitionNode):
self.struct_definitions[node.name] = node # 保存结构体定义
# 访问函数定义节点
def visit_function_definition(self, node: FunctionDefinitionNode):
if node.name == "main":
if node.body:
node.body.accept(self) # 访问函数体
# 访问变量声明节点
def visit_variable_declaration(self, node: VariableDeclarationNode):
var_name = node.name # 变量名称
var_type = node.var_type # 变量类型
# 检查变量是否已定义
if var_name in self.variables:
return
# 处理数组声明
if node.is_array():
size = node.array_size
if var_type == "float":
self.data_section.append(f" {var_name} times {size * 4} dd 0") # 浮点数组
elif var_type == "char":
self.data_section.append(f" {var_name} times {size} db 0") # 字符数组
else:
self.data_section.append(f" {var_name} times {size * 4} dd 0") # 整数数组
# 处理结构体变量
elif var_type in self.struct_definitions:
struct = self.struct_definitions[var_type]
total_size = self._calculate_struct_size(struct)
self.data_section.append(f" {var_name} times {total_size} db 0") # 结构体变量
# 处理浮点变量
elif var_type == "float":
self.data_section.append(f" {var_name} dd 0") # 浮点变量
# 处理字符变量
elif var_type == "char":
self.data_section.append(f" {var_name} db 0") # 字符变量
# 处理指针变量
elif var_type.endswith("*"):
self.data_section.append(f" {var_name} dd 0") # 指针变量
else:
self.data_section.append(f" {var_name} dd 0") # 整数变量
self.variables[var_name] = var_type # 保存变量
# 处理初始化
if node.initializer:
if var_type in self.struct_definitions and isinstance(node.initializer, InitializerListNode):
self._initialize_struct(var_name, var_type, node.initializer) # 初始化结构体
else:
node.initializer.accept(self) # 访问初始化表达式
self.code_section.append(f" mov [{var_name}], eax")
# 计算结构体大小
def _calculate_struct_size(self, struct: StructDefinitionNode) -> int:
total_size = 0 # 总大小
for field in struct.fields:
# 处理数组字段
if field.is_array():
if field.var_type == "float":
total_size += field.array_size * 4 # 浮点数组
elif field.var_type == "char":
total_size += field.array_size # 字符数组
else:
total_size += field.array_size * 4 # 整数数组
else:
# 处理普通字段
if field.var_type == "float":
total_size += 4 # 浮点字段
elif field.var_type == "char":
total_size += 1 # 字符字段
elif field.var_type.endswith("*"):
total_size += 4 # 指针字段
else:
total_size += 4 # 整数字段
return total_size
# 获取结构体字段偏移
def _get_struct_field_offset(self, struct_name: str, field_name: str) -> int:
if struct_name not in self.struct_definitions:
return 0
struct = self.struct_definitions[struct_name]
offset = 0 # 偏移量
for field in struct.fields:
if field.name == field_name:
return offset # 返回字段偏移
# 计算下一个字段的偏移
if field.is_array():
if field.var_type == "float":
offset += field.array_size * 4 # 浮点数组
elif field.var_type == "char":
offset += field.array_size # 字符数组
else:
offset += field.array_size * 4 # 整数数组
else:
if field.var_type == "float":
offset += 4 # 浮点字段
elif field.var_type == "char":
offset += 1 # 字符字段
elif field.var_type.endswith("*"):
offset += 4
else:
offset += 4
return offset
# 获取结构体字段类型
def _get_struct_field_type(self, struct_name: str, field_name: str) -> str:
if struct_name not in self.struct_definitions:
return "int"
struct = self.struct_definitions[struct_name]
for field in struct.fields:
if field.name == field_name:
return field.var_type # 返回字段类型
return "int"
# 初始化结构体
def _initialize_struct(self, var_name: str, struct_type: str, init_list: InitializerListNode):
elements = init_list.elements # 初始化元素列表
struct = self.struct_definitions.get(struct_type)
if not struct:
return
offset = 0 # 偏移量
for i, field in enumerate(struct.fields):
if i >= len(elements):
break
element = elements[i]
# 处理数组字段初始化
if field.is_array() and isinstance(element, InitializerListNode):
for j, arr_elem in enumerate(element.elements):
# 处理浮点数组元素
if field.var_type == "float" and isinstance(arr_elem, LiteralNode) and arr_elem.literal_type == "int":
try:
int_val = int(arr_elem.value)
fixed_point = int_val * 100 # 转换为定点数
self.code_section.append(f" mov eax, {fixed_point}")
except ValueError:
arr_elem.accept(self)
else:
arr_elem.accept(self) # 访问数组元素
self.code_section.append(f" mov ebx, {var_name}") # 变量地址
self.code_section.append(f" add ebx, {offset + j * 4}") # 元素地址
self.code_section.append(f" mov [ebx], eax") # 存储元素值
# 处理字符数组字段初始化
elif field.is_array() and field.var_type == "char":
if isinstance(element, LiteralNode) and element.literal_type == "string":
str_name = f"str_{len(self.string_literals)}"
self.string_literals[str_name] = element.value # 保存字符串
self.code_section.append(f" mov esi, {str_name}") # 源地址
self.code_section.append(f" mov edi, {var_name}") # 目标地址
self.code_section.append(f" add edi, {offset}") # 字段地址
copy_label = f"copy_str_{self.temp_var_counter}"
self.temp_var_counter += 1
self.code_section.append(f"{copy_label}:")
self.code_section.append(f" mov al, [esi]")
self.code_section.append(f" mov [edi], al")
self.code_section.append(f" test al, al")
self.code_section.append(f" jz {copy_label}_done")
self.code_section.append(f" inc esi")
self.code_section.append(f" inc edi")
self.code_section.append(f" jmp {copy_label}")
self.code_section.append(f"{copy_label}_done:")
else:
element.accept(self)
self.code_section.append(f" mov ebx, {var_name}")
self.code_section.append(f" add ebx, {offset}")
self.code_section.append(f" mov [ebx], eax")
if field.is_array():
if field.var_type == "float":
offset += field.array_size * 4
elif field.var_type == "char":
offset += field.array_size
else:
offset += field.array_size * 4
else:
if field.var_type == "float":
offset += 4
elif field.var_type == "char":
offset += 1
elif field.var_type.endswith("*"):
offset += 4
else:
offset += 4
# 访问赋值节点
def visit_assignment(self, node: AssignmentNode):
node.value.accept(self) # 访问值
# 处理标识符赋值
if isinstance(node.target, IdentifierNode):
self.code_section.append(f" mov [{node.target.name}], eax") # 存储值到变量
# 处理数组访问赋值
elif isinstance(node.target, ArrayAccessNode):
self.code_section.append(" push eax") # 保存值
node.target.index.accept(self) # 访问索引
self.code_section.append(" shl eax, 2") # 计算偏移量
if isinstance(node.target.array, IdentifierNode):
self.code_section.append(f" mov ebx, {node.target.array.name}") # 获取数组地址
self.code_section.append(" add ebx, eax") # 计算元素地址
elif isinstance(node.target.array, MemberAccessNode):
if isinstance(node.target.array.obj, IdentifierNode):
obj_name = node.target.array.obj.name
member_name = node.target.array.member
obj_type = self.variables.get(obj_name, "")
offset = self._get_struct_field_offset(obj_type, member_name)
self.code_section.append(f" mov ebx, {obj_name}") # 获取对象地址
self.code_section.append(f" add ebx, {offset}") # 计算字段地址
self.code_section.append(" pop eax") # 恢复值
self.code_section.append(" mov [ebx], eax") # 存储值到数组元素
# 处理成员访问赋值
elif isinstance(node.target, MemberAccessNode):
self.code_section.append(" push eax") # 保存值
if isinstance(node.target.obj, IdentifierNode):
obj_name = node.target.obj.name
member_name = node.target.member
obj_type = self.variables.get(obj_name, "")
offset = self._get_struct_field_offset(obj_type, member_name)
self.code_section.append(f" mov ebx, {obj_name}") # 获取对象地址
self.code_section.append(f" add ebx, {offset}") # 计算字段地址
self.code_section.append(" pop eax") # 恢复值
self.code_section.append(" mov [ebx], eax") # 存储值到成员
# 访问二元表达式节点
def visit_binary_expression(self, node: BinaryExpressionNode):
node.right.accept(self) # 访问右操作数
self.code_section.append(" push eax") # 保存右操作数
node.left.accept(self) # 访问左操作数
self.code_section.append(" pop ebx") # 恢复右操作数
op = node.operator
# 处理加法
if op == "+":
self.code_section.append(" add eax, ebx") # 加法运算
# 处理减法
elif op == "-":
self.code_section.append(" sub eax, ebx") # 减法运算
# 处理乘法
elif op == "*":
self.code_section.append(" imul ebx") # 乘法运算
left_type = self._get_expression_type(node.left)
right_type = self._get_expression_type(node.right)
if left_type == "float" or right_type == "float":
self.code_section.append(" mov ebx, 100") # 浮点数处理
self.code_section.append(" xor edx, edx")
self.code_section.append(" idiv ebx")
# 处理除法
elif op == "/":
left_type = self._get_expression_type(node.left)
right_type = self._get_expression_type(node.right)
if left_type == "float" or right_type == "float":
self.code_section.append(" mov ecx, eax") # 浮点数除法
self.code_section.append(" mov eax, ebx")
self.code_section.append(" mov ebx, 100")
self.code_section.append(" xor edx, edx")
self.code_section.append(" imul ebx")
self.code_section.append(" mov ebx, eax")
self.code_section.append(" mov eax, ecx")
self.code_section.append(" xor edx, edx")
self.code_section.append(" idiv ebx")
else:
self.code_section.append(" xor edx, edx") # 整数除法
self.code_section.append(" idiv ebx")
# 处理小于比较
elif op == "<":
label1 = f"less_true_{self.label_counter}"
label2 = f"less_done_{self.label_counter}"
self.label_counter += 1
self.code_section.append(" cmp eax, ebx")
self.code_section.append(f" jl {label1}")
self.code_section.append(" mov eax, 0")
self.code_section.append(f" jmp {label2}")
self.code_section.append(f"{label1}:")
self.code_section.append(" mov eax, 1")
self.code_section.append(f"{label2}:")
elif op == ">":
label1 = f"greater_true_{self.label_counter}"
label2 = f"greater_done_{self.label_counter}"
self.label_counter += 1
self.code_section.append(" cmp eax, ebx")
self.code_section.append(f" jg {label1}")
self.code_section.append(" mov eax, 0")
self.code_section.append(f" jmp {label2}")
self.code_section.append(f"{label1}:")
self.code_section.append(" mov eax, 1")
self.code_section.append(f"{label2}:")
elif op == "<=":
label1 = f"le_true_{self.label_counter}"
label2 = f"le_done_{self.label_counter}"
self.label_counter += 1
self.code_section.append(" cmp eax, ebx")
self.code_section.append(f" jle {label1}")
self.code_section.append(" mov eax, 0")
self.code_section.append(f" jmp {label2}")
self.code_section.append(f"{label1}:")
self.code_section.append(" mov eax, 1")
self.code_section.append(f"{label2}:")
elif op == ">=":
label1 = f"ge_true_{self.label_counter}"
label2 = f"ge_done_{self.label_counter}"
self.label_counter += 1
self.code_section.append(" cmp eax, ebx")
self.code_section.append(f" jge {label1}")
self.code_section.append(" mov eax, 0")
self.code_section.append(f" jmp {label2}")
self.code_section.append(f"{label1}:")
self.code_section.append(" mov eax, 1")
self.code_section.append(f"{label2}:")
elif op == "==":
label1 = f"eq_true_{self.label_counter}"
label2 = f"eq_done_{self.label_counter}"
self.label_counter += 1
self.code_section.append(" cmp eax, ebx")
self.code_section.append(f" je {label1}")
self.code_section.append(" mov eax, 0")
self.code_section.append(f" jmp {label2}")
self.code_section.append(f"{label1}:")
self.code_section.append(" mov eax, 1")
self.code_section.append(f"{label2}:")
elif op == "!=":
label1 = f"ne_true_{self.label_counter}"
label2 = f"ne_done_{self.label_counter}"
self.label_counter += 1
self.code_section.append(" cmp eax, ebx")
self.code_section.append(f" jne {label1}")
self.code_section.append(" mov eax, 0")
self.code_section.append(f" jmp {label2}")
self.code_section.append(f"{label1}:")
self.code_section.append(" mov eax, 1")
self.code_section.append(f"{label2}:")
elif op == "&&":
self.code_section.append(" and eax, ebx")
elif op == "||":
self.code_section.append(" or eax, ebx")
# 访问一元表达式节点
def visit_unary_expression(self, node: UnaryExpressionNode):
op = node.operator
# 处理自增运算
if op == "++":
node.operand.accept(self) # 访问操作数
self.code_section.append(" inc eax") # 自增
if isinstance(node.operand, IdentifierNode):
self.code_section.append(f" mov [{node.operand.name}], eax") # 存储结果
# 处理自减运算
elif op == "--":
node.operand.accept(self) # 访问操作数
self.code_section.append(" dec eax") # 自减
if isinstance(node.operand, IdentifierNode):
self.code_section.append(f" mov [{node.operand.name}], eax") # 存储结果
# 处理负号运算
elif op == "-":
node.operand.accept(self) # 访问操作数
self.code_section.append(" neg eax") # 取负
# 处理逻辑非运算
elif op == "!":
node.operand.accept(self) # 访问操作数
self.code_section.append(" test eax, eax") # 测试是否为0
self.code_section.append(" setz al") # 设置结果
self.code_section.append(" movzx eax, al") # 扩展为32位
else:
node.operand.accept(self) # 访问操作数
# 访问标识符节点
def visit_identifier(self, node: IdentifierNode):
self.code_section.append(f" mov eax, [{node.name}]") # 加载变量值
# 访问字面量节点
def visit_literal(self, node: LiteralNode):
# 处理整数字面量
if node.literal_type == "int":
value_str = node.value
try:
# 处理十六进制
if value_str.startswith('0x') or value_str.startswith('0X'):
int_value = int(value_str, 16)
# 处理八进制
elif value_str.startswith('0') and len(value_str) > 1 and value_str[1].isdigit():
int_value = int(value_str, 8)
else:
int_value = int(value_str)
self.code_section.append(f" mov eax, {int_value}") # 加载整数
except ValueError:
self.code_section.append(f" mov eax, {value_str}")
# 处理浮点字面量
elif node.literal_type == "float":
try:
float_val = float(node.value)
fixed_point = round(float_val * 100) # 转换为定点数
self.code_section.append(f" mov eax, {fixed_point}") # 加载浮点数
except ValueError:
self.code_section.append(" mov eax, 0")
# 处理字符串字面量
elif node.literal_type == "string":
str_name = f"str_{self.label_counter}"
self.label_counter += 1
self.string_literals[str_name] = node.value # 保存字符串
self.code_section.append(f" mov eax, {str_name}") # 加载字符串地址
# 访问数组访问节点
def visit_array_access(self, node: ArrayAccessNode):
node.index.accept(self) # 访问索引
self.code_section.append(" push eax") # 保存索引
# 获取数组地址
if isinstance(node.array, IdentifierNode):
self.code_section.append(f" mov ebx, {node.array.name}") # 数组地址
elif isinstance(node.array, MemberAccessNode):
if isinstance(node.array.obj, IdentifierNode):
obj_name = node.array.obj.name
member_name = node.array.member
obj_type = self.variables.get(obj_name, "")
offset = self._get_struct_field_offset(obj_type, member_name)
self.code_section.append(f" mov ebx, {obj_name}") # 对象地址
self.code_section.append(f" add ebx, {offset}") # 字段偏移
self.code_section.append(" pop eax") # 恢复索引
self.code_section.append(" shl eax, 2") # 计算偏移量(4字节)
self.code_section.append(" add ebx, eax") # 计算元素地址
self.code_section.append(" mov eax, [ebx]") # 加载元素值
# 访问成员访问节点
def visit_member_access(self, node: MemberAccessNode):
if isinstance(node.obj, IdentifierNode):
obj_name = node.obj.name # 对象名称
member_name = node.member # 成员名称
obj_type = self.variables.get(obj_name, "") # 对象类型
offset = self._get_struct_field_offset(obj_type, member_name) # 成员偏移
field_type = self._get_struct_field_type(obj_type, member_name) # 成员类型
struct = self.struct_definitions.get(obj_type)
is_char_array = False
if struct:
for field in struct.fields:
if field.name == member_name:
is_char_array = field.is_array() and field.var_type == "char" # 检查是否是字符数组
break
# 处理字符数组
if is_char_array:
self.code_section.append(f" mov eax, {obj_name}") # 对象地址
self.code_section.append(f" add eax, {offset}") # 成员地址
else:
self.code_section.append(f" mov ebx, {obj_name}") # 对象地址
self.code_section.append(f" add ebx, {offset}") # 成员地址
self.code_section.append(" mov eax, [ebx]") # 加载成员值
# 访问函数调用节点
def visit_function_call(self, node: FunctionCallNode):
# 处理printf函数
if node.function_name == "printf":
self._handle_printf(node) # 处理printf
else:
# 处理其他函数调用
for arg in reversed(node.arguments):
arg.accept(self) # 访问参数
self.code_section.append(" push eax") # 保存参数
self.code_section.append(f" call {node.function_name}") # 调用函数
arg_count = len(node.arguments)
if arg_count > 0:
self.code_section.append(f" add esp, {arg_count * 4}") # 清理栈
# 处理printf函数
def _handle_printf(self, node: FunctionCallNode):
if not node.arguments:
return
format_arg = node.arguments[0] # 格式字符串参数
# 处理字符串字面量格式
if isinstance(format_arg, LiteralNode) and format_arg.literal_type == "string":
format_str = format_arg.value
arg_index = 1 # 参数索引
i = 0 # 字符索引
while i < len(format_str):
# 处理格式说明符
if format_str[i] == '%' and i + 1 < len(format_str):
spec = format_str[i + 1]
# 处理%d或%i格式(整数)
if spec == 'd' or spec == 'i':
if arg_index < len(node.arguments):
node.arguments[arg_index].accept(self) # 访问参数
self.code_section.append(" push eax") # 保存参数
self.code_section.append(" call print_int") # 调用print_int
self.code_section.append(" add esp, 4") # 清理栈
arg_index += 1
# 处理%f格式(浮点数)
elif spec == 'f':
if arg_index < len(node.arguments):
node.arguments[arg_index].accept(self) # 访问参数
self.code_section.append(" push eax") # 保存参数
self.code_section.append(" call print_float") # 调用print_float
self.code_section.append(" add esp, 4") # 清理栈
arg_index += 1
# 处理%s格式(字符串)
elif spec == 's':
if arg_index < len(node.arguments):
node.arguments[arg_index].accept(self) # 访问参数
self.code_section.append(" push eax") # 保存参数
self.code_section.append(" call print_string") # 调用print_string
self.code_section.append(" add esp, 4") # 清理栈
arg_index += 1
# 处理%.nf格式(指定精度的浮点数)
elif spec == '.' and i + 3 < len(format_str) and format_str[i + 2].isdigit():
if format_str[i + 3] == 'f':
if arg_index < len(node.arguments):
node.arguments[arg_index].accept(self) # 访问参数
self.code_section.append(" push eax") # 保存参数
self.code_section.append(" call print_float") # 调用print_float
self.code_section.append(" add esp, 4") # 清理栈
arg_index += 1
i += 2
i += 2
# 处理换行符
elif format_str[i] == '\n':
self.code_section.append(" mov eax, 4") # 系统调用号
self.code_section.append(" mov ebx, 1") # 文件描述符
self.code_section.append(" mov ecx, newline_char") # 换行符地址
self.code_section.append(" mov edx, 1") # 长度
self.code_section.append(" int 0x80") # 系统调用
i += 1
# 处理制表符
elif format_str[i] == '\t':
self.code_section.append(" mov eax, 4") # 系统调用号
self.code_section.append(" mov ebx, 1") # 文件描述符
self.code_section.append(" mov ecx, space_char") # 空格地址
self.code_section.append(" mov edx, 1") # 长度
self.code_section.append(" int 0x80") # 系统调用
i += 1
# 处理普通字符
else:
char_str_name = f"printf_char_{self.temp_var_counter}"
self.temp_var_counter += 1
self.string_literals[char_str_name] = format_str[i] # 保存字符
self.code_section.append(f" mov eax, 4") # 系统调用号
self.code_section.append(f" mov ebx, 1") # 文件描述符
self.code_section.append(f" mov ecx, {char_str_name}") # 字符地址
self.code_section.append(f" mov edx, 1") # 长度
self.code_section.append(f" int 0x80") # 系统调用
i += 1
else:
# 处理变量格式字符串
format_arg.accept(self) # 访问格式字符串
self.code_section.append(" push eax") # 保存格式字符串
self.code_section.append(" call print_string") # 调用print_string
self.code_section.append(" add esp, 4") # 清理栈
# 访问for循环语句节点
def visit_for_statement(self, node: ForStatementNode):
if node.initialization:
node.initialization.accept(self) # 访问初始化
loop_start = f"for_start_{self.label_counter}" # 循环开始标签
loop_end = f"for_end_{self.label_counter}" # 循环结束标签
self.label_counter += 1
self.code_section.append(f"{loop_start}:") # 循环开始
if node.condition:
node.condition.accept(self) # 访问条件
self.code_section.append(" test eax, eax") # 测试条件
self.code_section.append(f" jz {loop_end}") # 条件为假则跳转
if node.body:
node.body.accept(self) # 访问循环体
if node.increment:
node.increment.accept(self) # 访问增量
self.code_section.append(f" jmp {loop_start}") # 跳转到循环开始
self.code_section.append(f"{loop_end}:") # 循环结束
# 访问if语句节点
def visit_if_statement(self, node: IfStatementNode):
node.condition.accept(self) # 访问条件
else_label = f"if_else_{self.label_counter}" # else标签
end_label = f"if_end_{self.label_counter}" # end标签
self.label_counter += 1
self.code_section.append(" test eax, eax") # 测试条件
if node.else_statement:
self.code_section.append(f" jz {else_label}")
node.then_statement.accept(self)
self.code_section.append(f" jmp {end_label}")
self.code_section.append(f"{else_label}:")
node.else_statement.accept(self)
self.code_section.append(f"{end_label}:")
else:
self.code_section.append(f" jz {end_label}")
node.then_statement.accept(self)
self.code_section.append(f"{end_label}:")
# 访问return语句节点
def visit_return_statement(self, node: ReturnStatementNode):
if node.value:
node.value.accept(self) # 访问返回值
# 访问while循环语句节点
def visit_while_statement(self, node: WhileStatementNode):
loop_start = f"while_start_{self.label_counter}" # 循环开始标签
loop_end = f"while_end_{self.label_counter}" # 循环结束标签
self.label_counter += 1
self.code_section.append(f"{loop_start}:")
node.condition.accept(self)
self.code_section.append(" test eax, eax")
self.code_section.append(f" jz {loop_end}")
node.body.accept(self)
self.code_section.append(f" jmp {loop_start}")
self.code_section.append(f"{loop_end}:")
# 访问复合语句节点
def visit_compound_statement(self, node: CompoundStatementNode):
for statement in node.statements:
statement.accept(self) # 访问每个语句
# 访问表达式语句节点
def visit_expression_statement(self, node: ExpressionStatementNode):
node.expression.accept(self) # 访问表达式
# 访问初始化列表节点
def visit_initializer_list(self, node: InitializerListNode):
if node.elements:
node.elements[0].accept(self) # 访问第一个元素