Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.

Close

[664ff0]: pyke / compiler / scanner.py Maximize Restore History

Download this file

scanner.py    485 lines (429 with data), 12.5 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
# $Id$
# coding=utf-8
#
# Copyright Š 2007 Bruce Frederiksen
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
""" See http://www.dabeaz.com/ply/ply.html for syntax of grammer definitions.
"""
from __future__ import with_statement
import contextlib
from ply import lex
debug=0
states = (
('indent', 'exclusive'),
('code', 'exclusive'),
)
keywords = frozenset((
'as',
'assert',
'bc_extras',
'check',
'extending',
'False',
'fc_extras',
'foreach',
'in',
'None',
'plan_extras',
'python',
'step',
'taking',
'True',
'use',
'when',
'with',
'without',
))
tokens = tuple(x.upper() + '_TOK' for x in keywords) + (
'ANONYMOUS_VAR_TOK',
'CODE_TOK',
# 'DATE_TOK', # FIX: Add the definition for this!
'DEINDENT_TOK',
'IDENTIFIER_TOK',
'INDENT_TOK',
# 'LB_TOK',
# 'LC_TOK',
'LP_TOK',
'NL_TOK',
'NUMBER_TOK',
'PATTERN_VAR_TOK',
# 'RB_TOK',
# 'RC_TOK',
'RP_TOK',
'STRING_TOK',
)
literals = '*:,!.='
t_ignore = ' \t'
t_ignore_comment = r'\#.*'
def t_continuation(t):
r'\\(\r)?\n'
t.lexer.lineno += 1
def t_NL_TOK(t):
# newline, followed by any number of empty or comment only lines
r'(\r)?\n([ \t]*(\#.*)?(\r)?\n)*'
t.lexer.lineno += t.value.count('\n')
if nesting_level == 0:
t.lexer.begin('indent')
t.lexer.skip(-1) # put the final '\n' back for tp_indent_sp!
return t
indent_levels = []
# to prevent getting a warning...
t_indent_ignore = ''
def t_indent_sp(t):
# ply doesn't like re's that can be empty, so we'll include the prior
# newline char in the re and then skip over it when we count the indent
# level. The tp_NL_TOK function does a skip(-1) to retain the final '\n'
# for t_indent_sp.
r'\n[ \t]*'
indent = count_indent(t.value[1:])
current_indent = indent_levels[-1] if indent_levels else 0
if debug:
print "t_indent_sp: t.value", repr(t.value), "indent", indent, \
"current_indent", current_indent, \
"indent_levels", indent_levels, \
"t.lexpos", t.lexpos, \
"t.lexer.lexpos", t.lexer.lexpos, \
"t.lexer.lexdata[]", repr(t.lexer.lexdata[t.lexpos])
if indent > current_indent:
t.type = 'INDENT_TOK'
indent_levels.append(indent)
t.lexer.begin('INITIAL')
if debug: print "INDENT_TOK: indent_levels", indent_levels
return t
if indent < current_indent:
if indent > 0 and indent not in indent_levels:
raise SyntaxError(
"%d: deindent doesn't match any previous indent level" %
t.lexer.lineno)
t.type = 'DEINDENT_TOK'
del indent_levels[-1]
if indent < (indent_levels[-1] if indent_levels else 0):
if debug: print " -- pushing indent back"
t.lexer.skip(-len(t.value))
else:
if debug: print " -- doing begin('INITIAL')"
t.lexer.begin('INITIAL')
if debug: print "DEINDENT_TOK: indent_levels", indent_levels
return t
# else indent == current_indent
t.lexer.begin('INITIAL')
if debug: print "no indent: indent_levels", indent_levels
code = []
code_indent_level = 0
def start_code(plan_name = None, multiline = False,
var_format = "context['%s']"):
global current_line, code, current_plan_name, code_indent_level
global pattern_var_format, plan_vars_needed, code_nesting_level
pattern_var_format = var_format
plan_vars_needed = []
current_line = ''
code = []
if multiline: code_indent_level = indent_levels[-1]
else: code_indent_level = 1000000000
current_plan_name = plan_name
code_nesting_level = 0
lexer.begin('code')
# to prevent getting a warning...
t_code_ignore = ''
def t_code_string(t):
r"'''([^\\]|\\.)*?'''|" \
r'"""([^\\]|\\.)*?"""|' \
r"'([^'\\\n\r]|\\.|\\(\r)?\n)*?'|" \
r'"([^"\\\n\r]|\\.|\\(\r)?\n)*?"'
global current_line
current_line += t.value
if debug: print "scanner saw string:", t.value
t.lexer.lineno += t.value.count('\n')
def t_code_comment(t):
r'[ \t\f\r]*\#.*'
global current_line
if debug: print "scanner saw comment:", t.value
current_line += t.value
def t_code_plan(t):
r'\$\$'
global current_line
if debug:
print "scanner saw '$$', current_plan_name is", current_plan_name
if not current_plan_name:
raise SyntaxError("%s(%d): $$ only allowed in plan_specs within the "
"'when' clause" % (t.lexer.filename, t.lexer.lineno))
current_line += pattern_var_format % current_plan_name
plan_vars_needed.append(current_plan_name)
def t_code_pattern_var(t):
r'\$[a-zA-Z_][a-zA-Z0-9_]*\b'
global current_line
if not pattern_var_format:
raise SyntaxError("%s(%d): $<name> only allowed in backward chaining "
"rules" % (t.lexer.filename, t.lexer.lineno))
current_line += pattern_var_format % t.value[1:]
plan_vars_needed.append(t.value[1:])
if debug: print "scanner saw pattern_var:", t.value
def t_code_continuation(t):
r'\\(\r)?\n'
global current_line
t.lexer.lineno += 1
current_line += '\\'
code.append(current_line)
current_line = ''
if debug: print "scanner saw continuation:", t.value
def t_code_open(t):
r'[{([]'
global current_line, code_nesting_level
code_nesting_level += 1
current_line += t.value
def t_code_close(t):
r'[]})]'
global current_line, code_nesting_level
if code_nesting_level <= 0:
raise SyntaxError("%s(%d): unmatched %s" %
(t.lexer.filename, t.lexer.lineno, repr(t.value)))
code_nesting_level -= 1
current_line += t.value
def t_code_symbol(t):
r'''[0-9a-zA-Z_]+'''
global current_line
current_line += t.value
if debug: print "scanner saw symbol:", t.value
def t_code_other(t):
r'''[^][(){}$\\'"\r\n0-9a-zA-Z_]+'''
global current_line
current_line += t.value
if debug: print "scanner saw other chars:", t.value
def t_code_NL_TOK(t):
r'(\r)?\n([ \t]*(\#.*)?(\r)?\n)*[ \t]*'
global current_line
if current_line:
code.append(current_line)
current_line = ''
indent = count_indent(t.value[t.value.rindex('\n') + 1:])
if debug: print "scanner saw nl:", t.value, "new indent is", indent
if indent < code_indent_level and code_nesting_level == 0:
t.lexer.skip(-len(t.value))
t.type = 'CODE_TOK'
if code_indent_level >= 1000000000:
t.value = tuple(code), tuple(plan_vars_needed)
else:
t.value = tuple(code), tuple(plan_vars_needed)
if debug: print "scanner begin('INITIAL')"
t.lexer.begin('INITIAL')
return t
t.lexer.lineno += t.value.count('\n')
current_line = ' ' * (indent - code_indent_level)
# strings:
def t_tsqstring(t):
r"[uU]?[rR]?'''([^\\]|\\.)*?'''"
#t.value = unquote(t.value[3:-3])
t.type = 'STRING_TOK'
t.lexer.lineno += t.value.count('\n')
return t
def t_tdqstring(t):
r'[uU]?[rR]?"""([^\\]|\\.)*?"""'
#t.value = unquote(t.value[3:-3])
t.type = 'STRING_TOK'
t.lexer.lineno += t.value.count('\n')
return t
def t_sqstring(t):
r"[uU]?[rR]?'([^'\\\n\r]|\\.|\\(\r)?\n)*?'"
#t.value = unquote(t.value[1:-1])
t.lexer.lineno += t.value.count('\n')
t.type = 'STRING_TOK'
return t
def t_dqstring(t):
r'[uU]?[rR]?"([^"\\\n\r]|\\.|\\(\r)?\n)*?"'
#t.value = unquote(t.value[1:-1])
t.type = 'STRING_TOK'
t.lexer.lineno += t.value.count('\n')
return t
# end strings
def t_ANONYMOUS_VAR_TOK(t):
r'\$_'
return t
def t_PATTERN_VAR_TOK(t):
r'\$[a-zA-Z_][a-zA-Z0-9_]*'
t.value = "'" + t.value[1:] + "'"
return t
def t_IDENTIFIER_TOK(t):
r'[a-zA-Z_][a-zA-Z0-9_]*'
if t.value in keywords: t.type = t.value.upper() + '_TOK'
return t
# numbers:
def t_float(t):
r'[-+]?([0-9]+(\.[0-9]*([eE][-+][0-9]+)?|[eE][-+][0-9]+)|\.[0-9]+([eE][-+][0-9]+)?)'
t.value = float(t.value)
t.type = 'NUMBER_TOK'
return t
def t_hexint(t):
r'[-+]?0[xX][0-9a-fA-F]+'
t.value = int(t.value, 16)
t.type = 'NUMBER_TOK'
return t
def t_octalint(t):
r'[-+]?0[0-7]*'
t.value = int(t.value, 8)
t.type = 'NUMBER_TOK'
return t
def t_int(t):
r'[-+]?[1-9][0-9]*'
t.value = int(t.value)
t.type = 'NUMBER_TOK'
return t
# end numbers
nesting_level = 0
def t_LB_TOK(t):
r'\['
global nesting_level
nesting_level += 1
#return t
def t_LC_TOK(t):
r'\{'
global nesting_level
nesting_level += 1
#return t
def t_LP_TOK(t):
r'\('
global nesting_level
nesting_level += 1
return t
def t_RB_TOK(t):
r'\]'
global nesting_level
assert nesting_level > 0
nesting_level -= 1
#return t
def t_RC_TOK(t):
r'\}'
global nesting_level
assert nesting_level > 0
nesting_level -= 1
#return t
def t_RP_TOK(t):
r'\)'
global nesting_level
assert nesting_level > 0
nesting_level -= 1
return t
def t_ANY_error(t):
raise SyntaxError("%s(%d): illegal character %s\n" %
(t.lexer.filename, t.lexer.lineno, repr(t.value[0])))
# helper functions:
def count_indent(s):
r'''
>>> count_indent('')
0
>>> count_indent(' ')
3
>>> count_indent('\t')
8
>>> count_indent('\t ')
9
>>> count_indent('\t\t')
16
>>> count_indent(' \t')
8
>>> count_indent(' \t')
8
>>> count_indent(' \t')
16
'''
ans = 0
for c in s:
if c == '\t': ans = (ans + 8) & ~7
else: ans += 1
return ans
escapes = {
'a': '\a',
'b': '\b',
'f': '\f',
'n': '\n',
'r': '\r',
't': '\t',
'v': '\v',
'\\': '\\',
'\'': '\'',
'\"': '\"',
}
def unquote(s):
start = 0
ans = []
i = s.find('\\', start)
while i >= 0:
ans.append(s[start:i])
e = escapes.get(s[i+1])
if e: # single char escape code
ans.append(e)
start = i + 2
elif s[i+1] == '\n': # ignore \ at end of line
start = i + 2
elif s[i+1] == '\r': # ignore \ at end of line
if s[i+2] == '\n': start = i + 3
else: start = i + 2
elif s[i+1:i+3] == 'N{':
end = s.index('}', i + 3)
ans.append(unicodedata.lookup(s[i+3:end]))
start = end + 1
elif s[i+1] == 'u':
ans.append(unichr(int(s[i+2:i+6], 16)))
start = i + 6
elif s[i+1] == 'U':
ans.append(unichr(int(s[i+2:i+10], 16)))
start = i + 10
elif s[i+1] in string.octdigits:
if s[i+2] not in string.octdigits:
ans.append(unichr(int(s[i+2:i+3], 8)))
start = i + 3
elif s[i+3] not in string.octdigits:
ans.append(unichr(int(s[i+2:i+4], 8)))
start = i + 4
else:
ans.append(unichr(int(s[i+2:i+5], 8)))
start = i + 5
elif s[i+1] == 'x':
if s[i+3] not in string.hexdigits:
ans.append(unichr(int(s[i+2:i+3], 16)))
start = i + 3
else:
ans.append(unichr(int(s[i+2:i+4], 16)))
start = i + 4
else:
ans.append(s[i])
start = i + 1
i = s.find('\\', start)
ans.append(s[start:])
return ''.join(ans)
lexer = lex.lex(debug=0)
class token_iterator(object):
def __init__(self, input):
lexer.lineno = 1
lexer.input(input)
def __iter__(self): return self
def next(self):
t = lex.token()
if t: return t
raise StopIteration
def tokenize(filename = 'test'):
with contextlib.closing(file(filename)) as f:
for t in token_iterator(f.read()):
print t
def test():
import doctest
import sys
sys.exit(doctest.testmod()[0])
if __name__ == "__main__":
test()