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', \
|
148
|
13 'import', 'package' ]
|
|
14
|
|
15 def tokenize(s):
|
|
16 """
|
|
17 Tokenizer, generates an iterator that
|
|
18 returns tokens!
|
|
19
|
|
20 This GREAT example was taken from python re doc page!
|
|
21 """
|
|
22 tok_spec = [
|
|
23 ('REAL', r'\d+\.\d+'),
|
|
24 ('HEXNUMBER', r'0x[\da-fA-F]+'),
|
|
25 ('NUMBER', r'\d+'),
|
|
26 ('ID', r'[A-Za-z][A-Za-z\d_]*'),
|
|
27 ('NEWLINE', r'\n'),
|
|
28 ('SKIP', r'[ \t]'),
|
|
29 ('COMMENTS', r'//.*'),
|
204
|
30 ('LONGCOMMENTBEGIN', r'\/\*'),
|
|
31 ('LONGCOMMENTEND', r'\*\/'),
|
205
|
32 ('LEESTEKEN', r'==|[\.,=:;\-+*\[\]/\(\)]|>=|<=|<>|>|<|{|}|&|\^|\|'),
|
148
|
33 ('STRING', r"'.*?'")
|
|
34 ]
|
|
35 tok_re = '|'.join('(?P<%s>%s)' % pair for pair in tok_spec)
|
|
36 gettok = re.compile(tok_re).match
|
|
37 line = 1
|
|
38 pos = line_start = 0
|
|
39 mo = gettok(s)
|
204
|
40 incomment = False
|
148
|
41 while mo is not None:
|
|
42 typ = mo.lastgroup
|
|
43 val = mo.group(typ)
|
|
44 if typ == 'NEWLINE':
|
|
45 line_start = pos
|
|
46 line += 1
|
205
|
47 elif typ == 'COMMENTS':
|
148
|
48 pass
|
204
|
49 elif typ == 'LONGCOMMENTBEGIN':
|
|
50 incomment = True
|
|
51 elif typ == 'LONGCOMMENTEND':
|
|
52 incomment = False
|
148
|
53 elif typ == 'SKIP':
|
|
54 pass
|
204
|
55 elif incomment:
|
|
56 pass # Wait until we are not in a comment section
|
148
|
57 else:
|
|
58 if typ == 'ID':
|
|
59 if val in keywords:
|
|
60 typ = val
|
|
61 elif typ == 'LEESTEKEN':
|
|
62 typ = val
|
|
63 elif typ == 'NUMBER':
|
|
64 val = int(val)
|
|
65 elif typ == 'HEXNUMBER':
|
|
66 val = int(val[2:], 16)
|
|
67 typ = 'NUMBER'
|
|
68 elif typ == 'REAL':
|
|
69 val = float(val)
|
|
70 elif typ == 'STRING':
|
|
71 val = val[1:-1]
|
163
|
72 loc = SourceLocation(line, mo.start()-line_start, mo.end() - mo.start())
|
148
|
73 yield Token(typ, val, loc)
|
|
74 pos = mo.end()
|
|
75 mo = gettok(s, pos)
|
|
76 if pos != len(s):
|
205
|
77 col = pos - line_start
|
|
78 loc = SourceLocation(line, col, 1)
|
|
79 raise CompilerError('Unexpected character "{0}"'.format(s[pos]), loc)
|
194
|
80 loc = SourceLocation(line, 0, 0)
|
|
81 yield Token('END', '', loc)
|
148
|
82
|