-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPythonInterpreter.c
More file actions
142 lines (117 loc) · 2.79 KB
/
PythonInterpreter.c
File metadata and controls
142 lines (117 loc) · 2.79 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
//Supports simple print statements, Integers and operators
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//Forward Declarations
int parse_term();
int parse_factor();
int parse_expression();
void interpreter(const char* input);
int parse_number();
void skip_whitespace();
char advance();
char peek();
/**
* Lexer
*/
//Gobal State
const char* src; //The current line of code to interpret
int pos; //The current index
//Helpers
char peek() { return src[pos]; } //Looks ahead
char advance() { return src[pos++]; } //Moves to next character
void skip_whitespace() {
while (isspace(peek())) advance();
}
int parse_number() {
int val = 0;
while (isdigit(peek())) {
val = val * 10 + (advance() - '0'); // Converts to int with ASCII code
}
return val;
}
/**
* Parser (Recursive Descent)
*/
int parse_term() {
int value = parse_factor();
while (1) {
skip_whitespace();
if (peek() == '*' || peek() == '/') {
char op = advance();
int rhs = parse_factor();
if (op == '*') {
value *= rhs;
} else {
if (rhs == 0) {
printf("Can't divide by 0");
exit(1);
}
value /= rhs;
}
} else {
break;
}
}
return value;
}
int parse_factor() {
skip_whitespace();
if (isdigit(peek())) {
return parse_number();
} else if (peek() == '(') {
advance();
int value = parse_expression();
if (peek() == ')') advance();
return value;
}
printf("Invalid Context Free Grammar: %c\n", peek());
exit(1);
}
int parse_expression() {
int value = parse_term();
while (1) {
skip_whitespace();
if (peek() == '+' || peek() == '-') {
char op = advance();
int rhs = parse_term();
if (op == '+') value += rhs;
else value -= rhs;
} else {
break;
}
}
return value;
}
// Starting Point
void interpreter(const char* input) {
src = input;
pos = 0;
skip_whitespace();
int length = 5;
if (strncmp(src + pos, "print", length) == 0) {
pos += 5;
skip_whitespace();
if (peek() == '(') {
advance();
int result = parse_expression();
if (peek() == ')') advance();
printf("%d\n", result);
} else {
printf("Syntax error: expected '('\n");
}
} else {
printf("Only 'print(expr)' is supported.\n");
}
}
// Main
int main() {
char line[256];
printf("Simple Python Interpreter\n> ");
while (fgets(line, sizeof(line), stdin)) {
interpreter(line);
printf("> ");
}
return 0;
}