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