-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyler.py
46 lines (36 loc) · 1.38 KB
/
pyler.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
from codeanalysis.evaluator import Evaluator
from codeanalysis.syntaxtree import SyntaxTree
from codeanalysis.parser import Parser
from codeanalysis.syntaxnode import SyntaxNode
from codeanalysis.syntaxkind import SyntaxKind
from codeanalysis.syntaxtoken import SyntaxToken
# minimal compiler
# Take input
# lexer => tokens -> dump()-> list of tokens
# parser => expression trees dump() -> expression tree
# ├── readme.html
# │ ├── code.cpp
# │ └── code.h
def pretty_print(node: SyntaxNode, indent: str = "", isLast: bool = True) -> None:
if not node:
return
marker = "└──" if isLast else "├──"
if isinstance(node, SyntaxToken) and (node.value):
print(f'{indent}{marker}{node.kind()}{" "}{node.value}')
else:
print(f"{indent}{marker}{node.kind()}")
indent += " " if isLast else "│ "
lastChild = node.get_last_child()
for child in node.get_children():
pretty_print(child, indent, child == lastChild)
while True:
inputText = input(">")
parser = Parser(inputText, 0)
syntax_tree = parser.parse()
pretty_print(syntax_tree.root)
if len(syntax_tree.diagnostics) > 0:
print(syntax_tree.diagnostics)
else:
evaluator = Evaluator(syntax_tree.root)
value = evaluator.evaluate()
print(f"Result: {value}")