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_bracket', r'\['),
37 ('close_bracket', r'\]'),
38 ('open_parenthese', r'\('),
39 ('close_parenthese', r'\)'),
41 ('integer_literal', r'\d+'),
42 ('symbol', r'[a-z_]+'),
43 ('single_quoted_string_literal', r"'.*?'"),
44 ('comparison_level_operator', r'(<=|>=|==|!=|<|>)'),
45 ('assignment_operator', r'='),
46 ('addition_level_operator', r'(\+|-)'),
47 ('multiplication_level_operator', r'(\*|//|%)'),
51 _TOKEN_MATCHERS = list(map(_make_token_matcher, _TOKEN_MATCHERS))
53 @util.force_generator(tuple)
58 while index < len(source):
59 if source[index] == ' ':
63 if source[index] == '#':
64 while index < len(source) and source[index] != '\n':
71 for matcher in _TOKEN_MATCHERS:
72 success, index, token = matcher(index, source, line)
79 raise Exception('Unexpected character "{}" on line {}'.format(
84 if token.type == 'newline':
87 if __name__ == '__main__':
90 class TokenizeTests(unittest.TestCase):
91 def test_tokenizes_open_parenthese(self):
95 type='open_parenthese',
102 def test_tokenizes_close_parenthese(self):
106 type='close_parenthese',
113 def test_tokenizes_symbol(self):
124 def test_tokenizes_single_quoted_string_literal(self):
126 tokenize("'Hello, world'"),
128 type='single_quoted_string_literal',
129 match="'Hello, world'",
135 def test_tokenizes_plus(self):
139 type='addition_level_operator',
146 def test_tokenizes_minus(self):
150 type='addition_level_operator',
157 def test_tokenizes_times(self):
161 type='multiplication_level_operator',
168 def test_tokenizes_integer_divide(self):
172 type='multiplication_level_operator',
179 def test_tokenizes_modular_divide(self):
183 type='multiplication_level_operator',
190 def test_tokenizes_comma(self):
201 def test_tokenizes_assignment_operator(self):
205 type='assignment_operator',
212 def test_tokenizes_equality_operator(self):
216 type='comparison_level_operator',
223 def test_tokenizes_greater_than_or_equal_operator(self):
227 type='comparison_level_operator',
234 def test_tokenizes_less_than_or_equal_operator(self):
238 type='comparison_level_operator',
245 def test_tokenizes_greater_than_equal_operator(self):
249 type='comparison_level_operator',
256 def test_tokenizes_less_than_equal_operator(self):
260 type='comparison_level_operator',
267 def test_tokenizes_not_equal_operator(self):
271 type='comparison_level_operator',
278 def test_tokenizes_newline(self):
289 def test_handles_leading_space(self):
300 def test_tokenizes_with_proper_line_numbers(self):
302 tokenize('print\n('),
317 type='open_parenthese',