-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.c
More file actions
100 lines (85 loc) · 2.91 KB
/
main.c
File metadata and controls
100 lines (85 loc) · 2.91 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "lexer.h"
#include "parser.h"
#include "codegen.h"
#include "ast.h"
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <source_file.c>\n", argv[0]);
return 1;
}
// Read source code from file
FILE* fp = fopen(argv[1], "r");
if (!fp) {
fprintf(stderr, "Error: Could not open source file '%s'\n", argv[1]);
return 1;
}
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* source_code = (char*)malloc(file_size + 1);
if (!source_code) {
fprintf(stderr, "Memory allocation failed for source code.\n");
fclose(fp);
return 1;
}
fread(source_code, 1, file_size, fp);
source_code[file_size] = '\0';
fclose(fp);
printf("--- Source Code ---\n%s\n", source_code);
// Phase 1: Lexical Analysis
lexer_init(source_code);
printf("--- Lexing Initialized ---\n");
// Phase 2 & 3: Syntax Analysis and AST Construction
// The parser will call getNextToken internally.
// Advance once to get the first token for the parser.
advance();
ASTNode* program_ast = parse_program();
printf("--- Parsing and AST Construction Complete ---\n");
printf("--- Generated AST ---\n");
ast_print(program_ast, 0); // Print AST for verification
// Phase 4: Code Generation
printf("--- Generating Assembly Code ---\n");
// Redirect stdout to a file for assembly output
FILE* assembly_fp = fopen("output.s", "w");
if (!assembly_fp) {
fprintf(stderr, "Error: Could not open output assembly file.\n");
ast_free(program_ast);
free(source_code);
return 1;
}
// Temporarily redirect stdout to file
// Save the current stdout file descriptor
int original_stdout_fd = dup(fileno(stdout));
if (original_stdout_fd == -1) {
fprintf(stderr, "Error: Could not duplicate stdout file descriptor.\n");
ast_free(program_ast);
free(source_code);
fclose(assembly_fp);
return 1;
}
// Redirect stdout to the file
if (dup2(fileno(assembly_fp), fileno(stdout)) == -1) {
fprintf(stderr, "Error: Could not redirect stdout.\n");
ast_free(program_ast);
free(source_code);
fclose(assembly_fp);
close(original_stdout_fd);
return 1;
}
generate_code(program_ast);
// Flush and restore stdout
fflush(stdout);
dup2(original_stdout_fd, fileno(stdout));
close(original_stdout_fd);
fclose(assembly_fp);
printf("--- Assembly Code Generated to output.s ---\n");
// Clean up AST and source code memory
ast_free(program_ast);
free(source_code);
printf("Compilation successful!\n");
return 0;
}