compilation/spf.py
2025-03-19 16:29:54 +01:00

104 lines
2.9 KiB
Python
Executable File

#!/usr/bin/env python
# Projet de compilation Umons 2025
# Par Debucquoy Anthony (231687)
import argparse
import lark
import sys
from enum import Enum
variables = {}
class VariableType(Enum):
boolean = 1
integer = 2
string = 3
list = 4
class Variable():
def __init__(self, type, value):
self.type = type
self.value = value
def __str__(self):
if self.type == "booléen":
return "Vrai" if self.value else "Faux"
return f"{self.value}"
def __repr__(self):
if self.type == "texte":
return f"\"{self.value}\""
return f"{self.value}"
class SPFInterpreter(lark.visitors.Interpreter):
def afficher(self, el):
for toprint in el.children[1:]:
print(self.visit_children(toprint)[0])
return
def declaration(self, el):
type = el.children[0].value
name = el.children[1].value
assert el.children[2].value == "=", "Unexpected"
assert el.children[3].data == "expression", "Unexpected"
value = self.visit_children(el.children[3])[0]
variables[name] = Variable(type, value)
def assignation(self, el):
name = el.children[0].value
assert name in variables, f"Unknown variable : {el.children[0].value} not in {variables}"
assert el.children[1].value == "=", "Unexpected"
assert el.children[2].data == "expression", "Unexpected"
value = self.visit_children(el.children[2])[0]
variables[name] = value #TODO: vérifier type
def expressionleft(self, el):
return self.visit_children(el)[0]
def variable(self, el):
assert el.children[0].value in variables, f"Unknown variable : {el.children[0].value} not in {variables}"
return variables[el.children[0].value]
# Literals
string = lambda self, el: el.children[0][1:-1]
entier = lambda self, el: int(el.children[0])
true = lambda self, _: True
false = lambda self, _: False
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("spf_file", help="Fichier source à interpréter")
arg_parser.add_argument("-d", "--dump",
help="affichage de la mémoire du programme",
action="store_true")
arg_parser.add_argument("-t", "--trace",
help="affichage de la mémoire au cours du programme",
action="store_true")
args = arg_parser.parse_args()
if args.trace:
print("Trace activated (TODO)", file=sys.stderr)
with open("spf.lark") as grammar:
spf_parser = lark.Lark(grammar, parser="lalr", strict=True, debug=True)
with open(args.spf_file) as spf_input:
program = spf_input.read()
parsed = spf_parser.parse(program)
interpreter = SPFInterpreter()
interpreted = interpreter.visit(parsed)
if args.dump:
print(variables, file=sys.stderr)
if __name__ == "__main__":
main()