-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.py
78 lines (62 loc) · 2.21 KB
/
tokenizer.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
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
import string
import sys
from mathtoken import Token, TokenType
from dataclasses import dataclass
from exceptions import InvalidCharacter
@dataclass
class TokenMapItem:
type: TokenType
characters: list[str]
stringed: bool
# A map that keeps track of each token, their characters, and if they are stringed.
token_map = [
TokenMapItem(TokenType.NUMBER, [*string.digits, '.'], True),
TokenMapItem(TokenType.IGNORE, [" "], True),
TokenMapItem(TokenType.ADDITION, ["+"], False),
TokenMapItem(TokenType.SUBTRACTION, ["-"], False),
TokenMapItem(TokenType.DIVISION, ["/"], False),
TokenMapItem(TokenType.MULTIPLICATION, ["*"], False),
TokenMapItem(TokenType.LEFT_PARENTHESIS, ["("], False),
TokenMapItem(TokenType.RIGHT_PARENTHESIS, [")"], False),
TokenMapItem(TokenType.EXPONENT, ["^"], False),
]
class Tokenizer:
def __init__(self, string_to_tokenize):
self.current_char = ""
self.string = iter([*string_to_tokenize])
self.advance()
"""
Tokenize an entire string.
"""
def tokenize(self):
results = []
while self.current_char is not None:
char_map_item = self.get_character_type(self.current_char)
if char_map_item.type == TokenType.IGNORE:
self.advance()
continue
# If it's not a stringed type
if not char_map_item.stringed:
results.append(Token(char_map_item.type))
else:
if len(results) == 0 or results[-1].type != char_map_item.type:
results.append(Token(char_map_item.type, ""))
results[-1].value += self.current_char
self.advance()
return results
"""
Advances our current position in the string.
"""
def advance(self):
try:
self.current_char = next(self.string)
except StopIteration:
self.current_char = None
"""
Returns the tokentype of a character.
"""
def get_character_type(self, character):
for token_item in token_map:
if character in token_item.characters:
return token_item
raise InvalidCharacter(f"Illegal character '{character}'")