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 ('comparison_level_operator', r'(<=|>=|==|!=|<|>)'),
43 ('assignment_operator', r'='),
44 ('addition_level_operator', r'(\+|-)'),
45 ('multiplication_level_operator', r'(\*|//|%)'),
49 _TOKEN_MATCHERS = list(map(_make_token_matcher, _TOKEN_MATCHERS))
51 @util.force_generator(tuple)
56 while index < len(source):
57 if source[index] == ' ':
63 for matcher in _TOKEN_MATCHERS:
64 success, index, token = matcher(index, source, line)
71 raise Exception('Unexpected character "{}" on line {}'.format(
76 if token.type == 'newline':
79 if __name__ == '__main__':
82 class TokenizeTests(unittest.TestCase):
83 def test_tokenizes_open_parenthese(self):
87 type='open_parenthese',
94 def test_tokenizes_close_parenthese(self):
98 type='close_parenthese',
105 def test_tokenizes_symbol(self):
116 def test_tokenizes_single_quoted_string_literal(self):
118 tokenize("'Hello, world'"),
120 type='single_quoted_string_literal',
121 match="'Hello, world'",
127 def test_tokenizes_plus(self):
131 type='addition_level_operator',
138 def test_tokenizes_minus(self):
142 type='addition_level_operator',
149 def test_tokenizes_times(self):
153 type='multiplication_level_operator',
160 def test_tokenizes_integer_divide(self):
164 type='multiplication_level_operator',
171 def test_tokenizes_modular_divide(self):
175 type='multiplication_level_operator',
182 def test_tokenizes_comma(self):
193 def test_tokenizes_assignment_operator(self):
197 type='assignment_operator',
204 def test_tokenizes_equality_operator(self):
208 type='comparison_level_operator',
215 def test_tokenizes_greater_than_or_equal_operator(self):
219 type='comparison_level_operator',
226 def test_tokenizes_less_than_or_equal_operator(self):
230 type='comparison_level_operator',
237 def test_tokenizes_greater_than_equal_operator(self):
241 type='comparison_level_operator',
248 def test_tokenizes_less_than_equal_operator(self):
252 type='comparison_level_operator',
259 def test_tokenizes_not_equal_operator(self):
263 type='comparison_level_operator',
270 def test_tokenizes_newline(self):
281 def test_handles_leading_space(self):
292 def test_tokenizes_with_proper_line_numbers(self):
294 tokenize('print\n('),
309 type='open_parenthese',