6 Token = collections.namedtuple(
16 def _make_token_matcher(definition):
17 name, regex = definition
18 regex_matcher = re.compile(regex)
20 def token_matcher(index, source, line):
21 match = regex_matcher.match(source[index:])
24 return False, index, None
28 index + len(match.group()),
29 Token(type=name, match=match.group(), index=index, line=line),
36 ('open_parenthese', r'\('),
37 ('close_parenthese', r'\)'),
39 ('integer_literal', r'\d+'),
40 ('symbol', r'[a-z]+'),
41 ('single_quoted_string_literal', r"'.*?'"),
42 ('equality_level_operator', r'(<=|>=|==|!=|<|>)'),
43 ('addition_level_operator', r'(\+|-)'),
44 ('multiplication_level_operator', r'(\*|//|%)'),
45 ('assignment_operator', r'='),
48 _TOKEN_MATCHERS = list(map(_make_token_matcher, _TOKEN_MATCHERS))
50 @util.force_generator(tuple)
55 while index < len(source):
56 if source[index] == ' ':
62 for matcher in _TOKEN_MATCHERS:
63 success, index, token = matcher(index, source, line)
70 raise Exception('Unexpected character "{}"'.format(source[index]))
72 while index < len(source) and source[index] in set(['\n']):
76 if __name__ == '__main__':
79 class TokenizeTests(unittest.TestCase):
80 def test_tokenizes_open_parenthese(self):
84 type='open_parenthese',
91 def test_tokenizes_close_parenthese(self):
95 type='close_parenthese',
102 def test_tokenizes_symbol(self):
113 def test_tokenizes_single_quoted_string_literal(self):
115 tokenize("'Hello, world'"),
117 type='single_quoted_string_literal',
118 match="'Hello, world'",
124 def test_tokenizes_plus(self):
128 type='addition_level_operator',
135 def test_tokenizes_minus(self):
139 type='addition_level_operator',
146 def test_tokenizes_times(self):
150 type='multiplication_level_operator',
157 def test_tokenizes_integer_divide(self):
161 type='multiplication_level_operator',
168 def test_tokenizes_modular_divide(self):
172 type='multiplication_level_operator',
179 def test_tokenizes_comma(self):
190 def test_tokenizes_assignment_operator(self):
194 type='assignment_operator',
201 def test_tokenizes_equality_operator(self):
205 type='equality_level_operator',
212 def test_tokenizes_greater_than_or_equal_operator(self):
216 type='equality_level_operator',
223 def test_tokenizes_less_than_or_equal_operator(self):
227 type='equality_level_operator',
234 def test_tokenizes_greater_than_equal_operator(self):
238 type='equality_level_operator',
245 def test_tokenizes_less_than_equal_operator(self):
249 type='equality_level_operator',
256 def test_tokenizes_not_equal_operator(self):
260 type='equality_level_operator',
267 def test_handles_trailing_newline(self):
278 def test_handles_leading_space(self):
289 def test_tokenizes_with_proper_line_numbers(self):
291 tokenize('print\n('),
300 type='open_parenthese',