148
|
1 import collections, re
|
152
|
2
|
191
|
3 from ppci import CompilerError, SourceLocation, Token
|
148
|
4
|
|
5 """
|
|
6 Lexical analyzer part. Splits the input character stream into tokens.
|
|
7 """
|
|
8
|
213
|
9 keywords = ['and', 'or', 'not', 'true', 'false', \
|
148
|
10 'else', 'if', 'while', 'return', \
|
163
|
11 'function', 'var', 'type', 'const', \
|
221
|
12 'struct', 'cast', \
|
284
|
13 'import', 'module' ]
|
148
|
14
|
287
|
15 def tokenize(input_file):
|
|
16 """
|
148
|
17 Tokenizer, generates an iterator that
|
|
18 returns tokens!
|
|
19
|
287
|
20 Input is a file like object.
|
|
21
|
148
|
22 This GREAT example was taken from python re doc page!
|
287
|
23 """
|
|
24 filename = input_file.name if hasattr(input_file, 'name') else ''
|
|
25 s = input_file.read()
|
|
26 tok_spec = [
|
148
|
27 ('REAL', r'\d+\.\d+'),
|
|
28 ('HEXNUMBER', r'0x[\da-fA-F]+'),
|
|
29 ('NUMBER', r'\d+'),
|
|
30 ('ID', r'[A-Za-z][A-Za-z\d_]*'),
|
|
31 ('NEWLINE', r'\n'),
|
|
32 ('SKIP', r'[ \t]'),
|
|
33 ('COMMENTS', r'//.*'),
|
204
|
34 ('LONGCOMMENTBEGIN', r'\/\*'),
|
|
35 ('LONGCOMMENTEND', r'\*\/'),
|
232
|
36 ('LEESTEKEN', r'==|->|<<|>>|[\.,=:;\-+*\[\]/\(\)]|>=|<=|<>|>|<|{|}|&|\^|\|'),
|
148
|
37 ('STRING', r"'.*?'")
|
|
38 ]
|
287
|
39 tok_re = '|'.join('(?P<%s>%s)' % pair for pair in tok_spec)
|
|
40 gettok = re.compile(tok_re).match
|
|
41 line = 1
|
|
42 pos = line_start = 0
|
|
43 mo = gettok(s)
|
|
44 incomment = False
|
|
45 while mo is not None:
|
148
|
46 typ = mo.lastgroup
|
|
47 val = mo.group(typ)
|
|
48 if typ == 'NEWLINE':
|
|
49 line_start = pos
|
|
50 line += 1
|
205
|
51 elif typ == 'COMMENTS':
|
148
|
52 pass
|
204
|
53 elif typ == 'LONGCOMMENTBEGIN':
|
|
54 incomment = True
|
|
55 elif typ == 'LONGCOMMENTEND':
|
|
56 incomment = False
|
148
|
57 elif typ == 'SKIP':
|
|
58 pass
|
204
|
59 elif incomment:
|
|
60 pass # Wait until we are not in a comment section
|
148
|
61 else:
|
|
62 if typ == 'ID':
|
|
63 if val in keywords:
|
|
64 typ = val
|
|
65 elif typ == 'LEESTEKEN':
|
|
66 typ = val
|
|
67 elif typ == 'NUMBER':
|
|
68 val = int(val)
|
|
69 elif typ == 'HEXNUMBER':
|
|
70 val = int(val[2:], 16)
|
|
71 typ = 'NUMBER'
|
|
72 elif typ == 'REAL':
|
|
73 val = float(val)
|
|
74 elif typ == 'STRING':
|
|
75 val = val[1:-1]
|
287
|
76 loc = SourceLocation(filename, line, mo.start() - line_start, mo.end() - mo.start())
|
148
|
77 yield Token(typ, val, loc)
|
|
78 pos = mo.end()
|
|
79 mo = gettok(s, pos)
|
287
|
80 if pos != len(s):
|
|
81 col = pos - line_start
|
|
82 loc = SourceLocation(filename, line, col, 1)
|
|
83 raise CompilerError('Unexpected character "{0}"'.format(s[pos]), loc)
|
|
84 loc = SourceLocation(filename, line, 0, 0)
|
|
85 yield Token('END', '', loc)
|
148
|
86
|