Pathl.Stona/interpreter.py
2026-01-30 18:08:36 +01:00

74 lines
2.1 KiB
Python

import re, importlib
variables = {}
modules = {}
functions = {}
# Rejestracja “handlerów” dla linii
handlers = []
def eval_expr(expr):
"""Bezpieczne obliczanie wyrażeń z użyciem zmiennych"""
expr = expr.replace("true", "True").replace("false", "False")
return eval(expr, {}, variables)
def handle_use(line):
if line.startswith("use "):
name = line.split()[1]
modules[name] = importlib.import_module(f"apks.{name}")
variables[name] = modules[name]
return True
return False
def handle_print(line):
if line.startswith("print"):
inside = re.search(r"\((.*)\)", line).group(1)
print(eval_expr(inside))
return True
return False
def handle_var(line):
for t in ["int ", "float ", "bool ", "string "]:
if line.startswith(t):
_, rest = line.split(" ", 1)
var, expr = rest.split("=")
val = expr.strip()
if t.strip() == "string":
val = val.strip('"').strip("'")
else:
val = eval_expr(val)
variables[var.strip()] = val
return True
return False
def handle_func_call(line):
if "." in line and "(" in line:
obj, rest = line.split(".", 1)
fname = rest[:rest.find("(")]
args_str = rest[rest.find("(")+1:rest.rfind(")")]
args = [eval_expr(a.strip()) for a in args_str.split(",") if a.strip()]
result = getattr(modules[obj], fname)(*args)
variables["_"] = result # ostatni wynik
return True
return False
# Dodajemy wszystkie handlery do listy
handlers.extend([handle_use, handle_print, handle_var, handle_func_call])
def run(code):
"""Interpreter MKScript"""
lines = code.split(";")
for line in lines:
line = line.strip()
if not line or line.startswith("//"): # komentarze
continue
# uruchamiamy wszystkie handlery aż któryś obsłuży linię
handled = False
for h in handlers:
if h(line):
handled = True
break
if not handled:
print(f"Nieznana linia: {line}")