-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.py
executable file
·116 lines (101 loc) · 2.23 KB
/
lexer.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#!env python2.7
import logging
import ply.lex as lex
logger = logging.getLogger('lexer')
keywords = (
'enum',
'type',
'fn',
'let',
'var',
'if',
'else',
'while',
)
tokens = (
'ID',
'LPAREN',
'RPAREN',
'LBRACE',
'RBRACE',
'LESS',
'GREATER',
'DOT',
'COMMA',
'COLON',
'EQ',
'ARROW',
'INT',
'FLOAT',
) + tuple(k.upper() for k in keywords)
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_LBRACE = r'\{'
t_RBRACE = r'\}'
t_DOT = r'\.'
t_COMMA = r'\,'
t_COLON = r'\:'
t_LESS = r'\<'
t_GREATER = r'\>'
t_EQ = r'='
t_ARROW = '->'
t_INT = r'\-?[0-9]+'
t_FLOAT = r'\-?[0-9]+\.[0-9]+'
t_ignore = '\t '
def t_ID(t):
r'[a-zA-Z][a-zA-Z_0-9]*'
if t.value in keywords:
t.type = t.value.upper()
return t
def t_error(t):
lines = t.lexer.lexdata.splitlines()
line = lines[t.lineno - 1]
error = 'Lexer error in line %s: unexpected symbol: %r\n%s' % (t.lineno, t.value[0], line)
t.lexer.errors.append(error)
logger.error(error)
t.lexer.skip(1)
def t_comment(t):
r'(/\*(.|\n)*?\*/)|(//.*)'
t.lexer.lineno += t.value.count('\n')
def t_newline(t):
r'\n+'
t.lexer.lineno += len(t.value)
def lexer():
res = lex.lex()
res.errors = []
return res
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('path')
args = parser.parse_args()
content = open(args.path).read()
l = lexer()
l.input(content)
while True:
tok = l.token()
if not tok:
sys.stdout.write('\n')
break
if l.errors:
sys.exit(1)
l = lexer()
l.input(content)
lines = content.splitlines()
last_line = None
while True:
tok = l.token()
if not tok:
sys.stdout.write('\n')
break
if last_line != tok.lineno:
last_line = tok.lineno
sys.stdout.write('\n')
line = lines[tok.lineno - 1]
prefix = len(line) - len(line.lstrip())
sys.stdout.write(' ' * prefix)
else:
sys.stdout.write(' ')
sys.stdout.write('%s(%r)' % (tok.type, tok.value))