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),
35 ('keyword', r'(def|do|else|end|if)(?![a-z_])'),
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] == ' ':
61 if source[index] == '#':
62 while index < len(source) and source[index] != '\n':
69 for matcher in _TOKEN_MATCHERS:
70 success, index, token = matcher(index, source, line)
77 raise Exception('Unexpected character "{}" on line {}'.format(
82 if token.type == 'newline':
85 if __name__ == '__main__':
88 class TokenizeTests(unittest.TestCase):
89 def test_tokenizes_open_parenthese(self):
93 type='open_parenthese',
100 def test_tokenizes_close_parenthese(self):
104 type='close_parenthese',
111 def test_tokenizes_symbol(self):
122 def test_tokenizes_single_quoted_string_literal(self):
124 tokenize("'Hello, world'"),
126 type='single_quoted_string_literal',
127 match="'Hello, world'",
133 def test_tokenizes_plus(self):
137 type='addition_level_operator',
144 def test_tokenizes_minus(self):
148 type='addition_level_operator',
155 def test_tokenizes_times(self):
159 type='multiplication_level_operator',
166 def test_tokenizes_integer_divide(self):
170 type='multiplication_level_operator',
177 def test_tokenizes_modular_divide(self):
181 type='multiplication_level_operator',
188 def test_tokenizes_comma(self):
199 def test_tokenizes_assignment_operator(self):
203 type='assignment_operator',
210 def test_tokenizes_equality_operator(self):
214 type='comparison_level_operator',
221 def test_tokenizes_greater_than_or_equal_operator(self):
225 type='comparison_level_operator',
232 def test_tokenizes_less_than_or_equal_operator(self):
236 type='comparison_level_operator',
243 def test_tokenizes_greater_than_equal_operator(self):
247 type='comparison_level_operator',
254 def test_tokenizes_less_than_equal_operator(self):
258 type='comparison_level_operator',
265 def test_tokenizes_not_equal_operator(self):
269 type='comparison_level_operator',
276 def test_tokenizes_newline(self):
287 def test_handles_leading_space(self):
298 def test_tokenizes_with_proper_line_numbers(self):
300 tokenize('print\n('),
315 type='open_parenthese',