-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathparser.py
More file actions
120 lines (86 loc) · 2.79 KB
/
parser.py
File metadata and controls
120 lines (86 loc) · 2.79 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""Parser for Howdy Script programming language"""
from core.ast import (
XoAssign,
XoBinOp,
XoEcho,
XoNumber,
XoProgram,
XoVariable
)
class Parser:
def __init__(self, tokens):
self.tokens = list(tokens)
self.pos = 0
def peek(self):
return self.tokens[self.pos] if self.pos < len(self.tokens) else None
def advance(self):
self.pos += 1
def expect(self, token_type):
tok = self.peek()
if tok:
if tok.type == token_type:
self.advance()
return tok
else:
raise SyntaxError(f'Expected {token_type}, got {tok.type}')
else:
raise SyntaxError(f'Unexpected end of file. Expected {token_type}')
def parse(self):
if not (self.peek() and self.peek().type == 'HOWDY'):
raise SyntaxError(f'Script must start with the HOWDY keyword')
self.advance()
statements = []
while self.peek():
statements.append(self.statement())
return XoProgram(statements)
def statement(self):
tok = self.peek()
if tok.type == 'ID':
return self.assignment()
elif tok.type == 'ECHO':
self.advance()
expr = self.expr()
return XoEcho(expr)
else:
return self.expr()
def assignment(self):
name = self.expect('ID').value
if (self.peek() and
self.peek().type == 'OP' and
self.peek().value == ':='):
self.advance()
expr = self.expr()
return XoAssign(name, expr)
raise SyntaxError(f'Invalid assignment {name}')
def expr(self):
return self._term_tail(self.term())
def _term_tail(self, left):
tok = self.peek()
if tok and tok.type == 'OP' and tok.value in ('+', '-'):
self.advance()
right = self.term()
return self._term_tail(XoBinOp(left, tok.value, right))
return left
def term(self):
return self._factor_tail(self.factor())
def _factor_tail(self, left):
tok = self.peek()
if tok and tok.type == 'OP' and tok.value in ('*', '/'):
self.advance()
right = self.factor()
return self._factor_tail(XoBinOp(left, tok.value, right))
return left
def factor(self):
tok = self.peek()
if tok.type == 'NUMBER':
self.advance()
return XoNumber(tok.value)
elif tok.type == 'ID':
self.advance()
return XoVariable(tok.value)
elif tok.type == 'LPAREN':
self.advance()
expr = self.expr()
self.expect('RPAREN')
return expr
raise SyntaxError(f'Unexpected token {tok}')