2019-09-30 11:29:05 +02:00
|
|
|
# fx-92 Scientifique Collège+ language interpreter: AST printer
|
|
|
|
|
|
|
|
from ast import N, Node
|
|
|
|
__all__ = ["print_ast"]
|
|
|
|
|
|
|
|
#---
|
|
|
|
# Message definitions
|
|
|
|
#---
|
|
|
|
|
2019-10-01 07:04:02 +02:00
|
|
|
class MessageAST:
|
|
|
|
forward = "FORWARD {}"
|
|
|
|
rotate = "ROTATE {}"
|
|
|
|
orient = "ORIENT {}"
|
|
|
|
goto = "GOTO {}, {}"
|
|
|
|
pendown = "PENDOWN"
|
|
|
|
penup = "PENUP"
|
|
|
|
|
2019-09-30 11:29:05 +02:00
|
|
|
class MessageFrench:
|
2019-10-01 07:04:02 +02:00
|
|
|
forward = "Avancer de {} pixels"
|
|
|
|
rotate = "Tourner de {} degrés"
|
|
|
|
orient = "S'orienter à {} degrés"
|
|
|
|
goto = "Aller à x={}; y={}"
|
|
|
|
pendown = "Stylo écrit"
|
|
|
|
penup = "Stylo relevé"
|
2019-09-30 11:29:05 +02:00
|
|
|
|
|
|
|
class MessageEnglish:
|
|
|
|
pass
|
|
|
|
|
|
|
|
#---
|
|
|
|
# Printer
|
|
|
|
#---
|
|
|
|
|
|
|
|
def print_ast(n, lang="en", indent=0):
|
2019-10-01 07:04:02 +02:00
|
|
|
if lang == "fr": lang = MessageFrench
|
|
|
|
if lang == "en": lang = MessageEnglish
|
|
|
|
if lang == "ast": lang = MessageAST
|
|
|
|
|
|
|
|
if n.type == N.PROGRAM:
|
|
|
|
for arg in n.args:
|
|
|
|
print_ast(arg, lang=lang, indent=indent)
|
|
|
|
return
|
2019-09-30 11:29:05 +02:00
|
|
|
|
|
|
|
print(" " * indent, end="")
|
|
|
|
|
|
|
|
if not isinstance(n, Node):
|
|
|
|
print(f"{type(n)}({n})")
|
|
|
|
return
|
|
|
|
|
|
|
|
if n.type == N.CONST:
|
|
|
|
print(n.args[0])
|
2019-10-01 07:04:02 +02:00
|
|
|
return
|
|
|
|
|
|
|
|
if n.type == N.VAR:
|
|
|
|
print(f"{n.args[0]}")
|
|
|
|
return
|
|
|
|
|
|
|
|
id = n.type.name.lower()
|
|
|
|
|
|
|
|
if hasattr(lang, id):
|
|
|
|
print(getattr(lang, id).format(*n.args))
|
2019-09-30 11:29:05 +02:00
|
|
|
else:
|
|
|
|
print(f"{n.type.name}")
|
2019-10-01 07:04:02 +02:00
|
|
|
|
|
|
|
if n.type in [N.FORWARD, N.ROTATE, N.ORIENT, N.GOTO] and \
|
|
|
|
n.constchildren():
|
|
|
|
return
|
|
|
|
|
2019-10-01 18:05:22 +02:00
|
|
|
if n.type == N.ASSIGN:
|
|
|
|
print_ast(n.args[0], lang=lang, indent=indent+2)
|
|
|
|
print(" " * (indent+2), end="")
|
|
|
|
print(f"->{n.args[1]}")
|
|
|
|
return
|
|
|
|
|
2019-10-01 07:04:02 +02:00
|
|
|
for arg in n.args:
|
|
|
|
print_ast(arg, lang=lang, indent=indent+2)
|