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