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