-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlexar.py
More file actions
47 lines (46 loc) · 1.44 KB
/
Copy pathlexar.py
File metadata and controls
47 lines (46 loc) · 1.44 KB
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
import re
def lexer(code):
token_specification = [
('NUMBER', r'\d+'),
('IDENT', r'[A-Za-z_]\w*'),
('ASSIGN', r'='),
('PRINT', r'print'),
('IF', r'if'),
('WHILE', r'while'),
('DEF', r'def'),
('CLASS', r'class'),
('NEW', r'new'),
('EQ', r'=='),
('NE', r'!='),
('LT', r'<'),
('GT', r'>'),
('LE', r'<='),
('GE', r'>='),
('LPAREN', r'\('),
('RPAREN', r'\)'),
('LBRACE', r'\{'),
('RBRACE', r'\}'),
('LBRACK', r'\['),
('RBRACK', r'\]'),
('COLON', r':'),
('PLUS', r'\+'),
('MINUS', r'-'),
('TIMES', r'\*'),
('DIVIDE', r'/'),
('SEMI', r';'),
('COMMA', r','),
('DOT', r'\.'),
('SKIP', r'[ \t\n]+'), # Skip spaces, tabs, and newlines
('MISMATCH', r'.') # Any other character
]
tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification)
tokens = []
for mo in re.finditer(tok_regex, code):
kind = mo.lastgroup
value = mo.group()
if kind == 'SKIP':
continue
elif kind == 'MISMATCH':
raise RuntimeError(f'{value} unexpected')
tokens.append((kind, value))
return tokens