-
Notifications
You must be signed in to change notification settings - Fork 0
/
interpreter.py
49 lines (39 loc) · 1.18 KB
/
interpreter.py
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
"""Interpreter for a simple language."""
import sys
# read arguments
if len(sys.argv) != 2:
print("Usage: python interpreter.py <program_filepath>")
sys.exit(1)
program_filepath = sys.argv[1]
###########################
# Tokenize Program
###########################
tokens = []
# read file lines and tokenize
with open(program_filepath, "r") as program_file:
for line in program_file:
stripped_line = line.strip()
if stripped_line:
# Simple tokenizer: splits on spaces, assumes no strings or
# complex expressions
tokens.extend(stripped_line.split())
###########################
# Parse Tokens
###########################
# Placeholder for a simple parser - creates a list of (command, value) tuples
commands = []
i = 0
while i < len(tokens):
if tokens[i] == "PRINT": # For example, a command
commands.append(("PRINT", tokens[i + 1]))
i += 2
else:
print(f"Unknown command {tokens[i]}")
sys.exit(1)
###########################
# Execute Commands
###########################
# Execute parsed commands
for command, value in commands:
if command == "PRINT":
print(value)