-
Notifications
You must be signed in to change notification settings - Fork 0
/
ufl_compiler.py
81 lines (70 loc) · 2.52 KB
/
ufl_compiler.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
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
def evaluate_expression(expr, variables):
try:
# Define a safe evaluation environment with the variables
safe_env = {**variables}
result = eval(expr, {"__builtins__": None}, safe_env)
return result
except Exception as e:
print(f"Error: {e}")
return None
def process_line(line, variables):
line = line.strip()
if line.startswith('//') or not line:
# Skip comments and empty lines
return
if line.startswith('let '):
# Variable assignment
_, var, value = line.split(' ', 2)
var, value = var.strip(), value.strip()
try:
value = eval(value, {"__builtins__": None})
except Exception as e:
print(f"Error evaluating value for {var}: {e}")
return
variables[var] = value
return
if line.startswith('ifthis '):
# Conditional statement
condition = line[7:].strip()
if evaluate_expression(condition, variables):
print("Condition met.")
else:
print("Condition not met.")
return
if line.startswith('orelse'):
# Handle 'orelse' logic (alternative branch in conditions)
print("Else condition.")
return
if line.startswith('foreverloop '):
# Infinite loop (basic implementation)
parts = line.split(' ', 1)
loop_body = parts[1]
while True:
process_line(loop_body, variables)
return
if line.startswith('say '):
# Print statement
message = line[4:].strip().strip('"')
print(message)
return
# Handle unknown commands
print(f"Unknown command: {line}")
def interpret_ufl(file_path):
variables = {}
try:
with open(file_path, 'r') as file:
accumulated_line = ""
for line in file:
line = line.strip()
if line.endswith('\\'):
# Accumulate lines ending with line continuation
accumulated_line += line[:-1] # Remove the '\\' and continue
else:
accumulated_line += line
process_line(accumulated_line, variables)
accumulated_line = ""
except Exception as e:
print(f"Error interpreting file '{file_path}': {e}")
# Example usage
if __name__ == "__main__":
interpret_ufl('C:/Users/isaac/Miscellanious/UFL/example.ufl')