-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclex.py
More file actions
44 lines (38 loc) · 1.03 KB
/
Copy pathclex.py
File metadata and controls
44 lines (38 loc) · 1.03 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
"""
clex.py: Simple C lexer.
"""
import re
SPACERE = re.compile("\s+")
IDRE = re.compile("\w+")
OTHER_TOKENS = {
"...",
"[[noreturn]]",
"[[deprecated]]"
}
def clex(text):
"""clex(text): Simple lexer for C code.
Args:
- text: str, the text to lex
This is a simple lexer, that only separates runs of [[:alnum:]_] from spaces
and other symbols. Especially, it will separate tokens that are usually
multiple symbols, like "+=".
Return: list of str, the tokens.
"""
tokens = list()
while text:
if match := SPACERE.match(text):
text = text[match.end():]
continue
if match := IDRE.match(text):
tokens.append(match.group())
text = text[match.end():]
continue
for other in OTHER_TOKENS:
if text.startswith(other):
tokens.append(other)
text = text[len(other):]
break
else:
tokens.append(text[0])
text = text[1:]
return tokens