56 lines
1.6 KiB
Python
56 lines
1.6 KiB
Python
from typing import Any
|
|
|
|
from core.primitives.list import cons, car, cdr, isList
|
|
from core.primitives.symbol import isSymbol, symbolName
|
|
from core.tokens import BaseToken, Lambda, Dambda, Macro, SpecialForm
|
|
from core.primitives.list import NIL
|
|
|
|
|
|
def Representation(obj: Any) -> str:
|
|
"""Return a showable string representation of an object in Lisp notation.
|
|
|
|
Args:
|
|
obj: The object to represent.
|
|
|
|
Returns:
|
|
A string that could be parsed back by the Lisp parser.
|
|
"""
|
|
if obj is None:
|
|
obj = NIL
|
|
|
|
if isList(obj):
|
|
result_str: str = ""
|
|
is_first: bool = True
|
|
current_item: Any = obj
|
|
while current_item != NIL:
|
|
if is_first:
|
|
is_first = False
|
|
else:
|
|
result_str += " "
|
|
result_str += Representation(car(current_item))
|
|
current_item = cdr(current_item)
|
|
return f"({result_str})"
|
|
|
|
elif isSymbol(obj):
|
|
return symbolName(obj) # type: ignore
|
|
|
|
elif isinstance(obj, str):
|
|
return f'"{obj}"'
|
|
|
|
elif isinstance(obj, BaseToken):
|
|
return obj.value
|
|
|
|
elif isinstance(obj, bool):
|
|
return "true" if obj else "false"
|
|
|
|
elif isinstance(obj, Lambda):
|
|
return f"({Representation(SpecialForm.LAMBDA)} {Representation(obj.args)} {Representation(obj.body)})"
|
|
|
|
elif isinstance(obj, Dambda):
|
|
return f"({Representation(SpecialForm.DAMBDA)} {Representation(obj.args)} {Representation(obj.body)})"
|
|
|
|
elif isinstance(obj, Macro):
|
|
return f"({Representation(SpecialForm.MACRO)} {Representation(obj.args)} {Representation(obj.body)})"
|
|
|
|
return str(obj)
|