-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwithmachinecode
More file actions
93 lines (87 loc) · 2.73 KB
/
Copy pathwithmachinecode
File metadata and controls
93 lines (87 loc) · 2.73 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
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
// Token types
typedef enum { TOKEN_NUMBER, TOKEN_PLUS, TOKEN_MINUS, TOKEN_MUL, TOKEN_DIV, TOKEN_EOF } TokenType;
// Token structure
typedef struct {
TokenType type;
int value; // Only used for numbers
} Token;
const char *input;
Token current_token;
// Function to get the next token
Token get_next_token() {
while (*input) {
if (isspace(*input)) {
input++;
continue;
}
if (isdigit(*input)) {
int val = strtol(input, (char **)&input, 10);
return (Token){TOKEN_NUMBER, val};
}
switch (*input) {
case '+': input++; return (Token){TOKEN_PLUS, 0};
case '-': input++; return (Token){TOKEN_MINUS, 0};
case '*': input++; return (Token){TOKEN_MUL, 0};
case '/': input++; return (Token){TOKEN_DIV, 0};
}
fprintf(stderr, "Unexpected character: %c\n", *input);
exit(1);
}
return (Token){TOKEN_EOF, 0};
}
// Stack-based x64 assembly code generation
void expr() {
int stack_top = 0;
current_token = get_next_token();
while (current_token.type != TOKEN_EOF) {
if (current_token.type == TOKEN_NUMBER) {
printf(" mov rax, %d\n", current_token.value);
printf(" push rax\n");
stack_top++;
} else if (current_token.type == TOKEN_PLUS) {
stack_top--;
printf(" pop rbx\n");
printf(" pop rax\n");
printf(" add rax, rbx\n");
printf(" push rax\n");
} else if (current_token.type == TOKEN_MINUS) {
stack_top--;
printf(" pop rbx\n");
printf(" pop rax\n");
printf(" sub rax, rbx\n");
printf(" push rax\n");
} else if (current_token.type == TOKEN_MUL) {
stack_top--;
printf(" pop rbx\n");
printf(" pop rax\n");
printf(" imul rax, rbx\n");
printf(" push rax\n");
} else if (current_token.type == TOKEN_DIV) {
stack_top--;
printf(" pop rbx\n");
printf(" pop rax\n");
printf(" cqo\n");
printf(" idiv rbx\n");
printf(" push rax\n");
}
current_token = get_next_token();
}
printf(" pop rax\n");
printf(" mov rdi, rax\n");
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <expression>\n", argv[0]);
return 1;
}
input = argv[1];
printf(".section .text\n.global _start\n_start:\n");
expr();
printf(" mov rax, 60\n");
printf(" syscall\n");
return 0;
}