101
|
1 import collections, re
|
1
|
2
|
|
3 """
|
|
4 Lexical analyzer part. Splits the input character stream into tokens.
|
|
5 """
|
|
6
|
|
7 # Token is used in the lexical analyzer:
|
|
8 Token = collections.namedtuple('Token', 'typ val row col')
|
|
9
|
|
10 keywords = ['and', 'array', 'begin', 'by', 'case', 'const', 'div', 'do', \
|
|
11 'else', 'elsif', 'end', 'false', 'for', 'if', 'import', 'in', 'is', \
|
|
12 'mod', 'module', 'nil', 'not', 'of', 'or', 'pointer', 'procedure', \
|
|
13 'record', 'repeat', 'return', 'then', 'to', 'true', 'type', 'until', 'var', \
|
|
14 'while', 'asm' ]
|
|
15
|
|
16 def tokenize(s):
|
|
17 """
|
|
18 Tokenizer, generates an iterator that
|
|
19 returns tokens!
|
|
20
|
|
21 This GREAT example was taken from python re doc page!
|
|
22 """
|
|
23 tok_spec = [
|
|
24 ('REAL', r'\d+\.\d+'),
|
|
25 ('HEXNUMBER', r'0x[\da-fA-F]+'),
|
|
26 ('NUMBER', r'\d+'),
|
|
27 ('ID', r'[A-Za-z][A-Za-z\d_]*'),
|
|
28 ('NEWLINE', r'\n'),
|
|
29 ('SKIP', r'[ \t]'),
|
|
30 ('COMMENTS', r'{.*}'),
|
|
31 ('LEESTEKEN', r':=|[\.,=:;\-+*\[\]/\(\)]|>=|<=|<>|>|<'),
|
|
32 ('STRING', r"'.*?'")
|
|
33 ]
|
|
34 tok_re = '|'.join('(?P<%s>%s)' % pair for pair in tok_spec)
|
|
35 gettok = re.compile(tok_re).match
|
|
36 line = 1
|
|
37 pos = line_start = 0
|
|
38 mo = gettok(s)
|
|
39 while mo is not None:
|
|
40 typ = mo.lastgroup
|
|
41 val = mo.group(typ)
|
|
42 if typ == 'NEWLINE':
|
|
43 line_start = pos
|
|
44 line += 1
|
|
45 elif typ == 'COMMENTS':
|
|
46 pass
|
|
47 elif typ != 'SKIP':
|
|
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]
|
|
62 yield Token(typ, val, line, mo.start()-line_start)
|
|
63 pos = mo.end()
|
|
64 mo = gettok(s, pos)
|
|
65 if pos != len(s):
|
|
66 col = pos - line_start
|
|
67 raise CompilerException('Unexpected character {0}'.format(s[pos]), line, col)
|
|
68 yield Token('END', '', line, 0)
|
|
69
|