-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlex.py
More file actions
executable file
·1767 lines (1213 loc) · 50.6 KB
/
lex.py
File metadata and controls
executable file
·1767 lines (1213 loc) · 50.6 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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
## ^^^ python 2.7 ~~~
#
# author: nikomu@ gmail.com
# state: "proof of concept" / "pre-alpha"
# licence: LGPL ( WTFPL - friendly )
#
"""
implementing ~lex format in python:
-- no definitions yet ;
-- a line should start with either '<', space, or start a string ;
-- '<' or string start a "trigger", anything started with space characters is action code and lasts till the next "trigger"
-- an example:
===
<CODE> ".|\n" # actually, we could probably have optional comment here -- and just skip to '\n'
print ... # yet have to decide on the variable names
# more comments
<STRING, COMMENT> ".|\n"
# some action
===
NB: this module may contain some not-so-well thought bits since it was written in ~1.5 days by a human with a slightly raised temperature ))
NB(2): states are exclusive!
NB(3): at the moment *not* the longest, but *the earliest* sequence is matched!
// could be changed by matching the regexps one-by-one and then comparing the lenghts of the matches
NB(4): if 'INITIAL' state is not silently defined, then the first defined state becomes, well, the first state ) /* the one that starts the state machine for the lexer */
NB(5): can't use '''-delimiters for strings in the action code ( only \"\"\", ' , " delimiters left ) )
// this could be avoided via using repr(), but repr() kills code readabilty
TODO: replace all the fragments of the following kind with a decent function!
msg = "expected an '(' after a GOTO:"
e = ParseError(msg, tok_tuple = _last_tuple)
# dbg
print >>sys.stderr, msg, '\n', e.make_message( _last_tuple )
raise e
TODO(2): write an action checker that looks for '''/r''' string prefixes and issues a warning (see NB(3)) ;
## TODO(3): parse "pre-trigger action code" and move it into __init__() ) // DONE
TODO(4): longest match instead of 'first matched' ?
TODO(5): 'yy-ify' local variables and attributes for the generated code )
---
ref: [ http://eli.thegreenplace.net/2013/06/25/regex-based-lexical-analysis-in-python-and-javascript/ ]
"""
# ----------------------------------------------------------------------------------
## ===============================================================================
import re
# import os
import sys # stderr
import tokenize as T
from cStringIO import StringIO as io
## from collections import deque
from pprint import pprint
from collections import OrderedDict # not that important, but let's preserve the order of the states for better readability
import os # os.path.split(), etc
# ----------------------------------------------------------------------------------
## ===============================================================================
#
# our exception class
#
class ParseError(Exception):
""" for syntactic errors in the spec, mostly """
@staticmethod
def make_message( tok_tuple ):
toktype, token, (srow, scol), (erow, ecol), line = tok_tuple
lineno = srow
message = "unexpected token '%(token)s' at line %(lineno)d, %(scol)d:%(ecol)d (logical line follows): \n%(line)s" % locals()
return message
def __init__(self, message = '', tok_tuple = None):
if tok_tuple is not None:
msg = self.make_message( tok_tuple )
if message: # prepend it to msg if 'message' is not empty
message = message + ":\n\t" + msg
else:
message = msg
Exception.__init__(self, message)
# ----------------------------------------------------------------------------------
## ===============================================================================
VERSION_STRING = '0.0.0' # a very minimalist way to compare this file to future bugfixes )
#
# accessory constants
#
# since tokenize constants live within { 0 .. 54, 256 }, let us start our own constants from 1000
_CONST_BASE = max(max(T.tok_name.keys()), 1000 )
## _NL = NEWLINE = 1
## CR = 2 # DEDENT ''
LT = 3 + _CONST_BASE # OP, '<'
GT = 4 + _CONST_BASE # OP, '>'
COMMA = 5 + _CONST_BASE # OP, ','
STR = 6 + _CONST_BASE # STRING, 'sth'
NAME = 7 + _CONST_BASE # NAME, 'sth'
# "default state"
INITIAL = 'INITIAL'
GOTO_METHOD_NAME = '_yy_set_state'
# "macro expansions"
YYLVAL_STRING = 'self._yylval' # <= 'yylval'
RETURN_STRING = 'self._yy_result' # <= 'RETURN'
# ----------------------------------------------------------------------------------
## ===============================================================================
#
# utils
#
def indent(text, indentation):
lines = []
for L in text.split('\n'):
lines.append( indentation + L )
return '\n'.join( lines )
# ----------------------------------------------------------------------------------
'''
def _list_find( L, item, default = None ):
""" returns the index or None if not found """
i = default
try:
i = L.index( item )
except IndexError:
pass
return i
def _list_rfind( L, item, default = None ):
""" terribly inefficient """
L.reverse()
r_ind = _list_find( L, item )
ret = None
if r_ind is not None:
ret = len( L ) - 1 - r_ind
L.reverse() # return back )
return ret
# a test:
if 0:
L = list("abcdef")
print L[ _list_rfind(L, 'e') ] # works )
sys.exit(0)
'''
'''
# [ http://stackoverflow.com/questions/8534256/python-find-first-element-in-a-sequence-that-matches-a-predicate ]
# works, but is completely unreadable ))
def seq_find( sequence, predicate ):
""" returns a tuple (ind, elem) where predicate(seq[ind]) is True or None """
gen = ( (n,el) for n, el in enumerate(sequence) )
cond = lambda tu: predicate(tu[1])
ret = next( (x for x in gen if cond(x)), None)
return ret
'''
def seq_find( sequence, predicate ):
""" returns a tuple (ind, elem) where predicate(seq[ind]) is True or None """
ret = None
for n, e in enumerate( sequence ):
if predicate(e):
ret = ( n, e )
break
return ret
# a test:
if 0:
L = list("abcdef")
cond = lambda x: x == 'e'
print L[ seq_find(L, cond)[0] ] # works
cond2 = lambda x: x == 'A'
assert seq_find(L, cond2) is None # still works )
sys.exit(0)
"""
# (1,2,3,4,5,...) => '_1', '_2', ...
def make_next_idder():
def next_id(counter = [0]): # 'counter' is initialized once per make_.._idder() call )
counter[0] += 1 # starts from '1'
ret = '_%d' % ( counter[0], )
return ret
return next_id
## # actually, we need only one )
## next_id = make_next_idder()
"""
# ----------------------------------------------------------------------------------
def strip_string_literal( literal ):
""" <r'''abc'''> => <abc> and so on """
# debugging
dbg_ref_ = literal
## literal = literal.lstrip('r')
# more expressive:
if literal.startswith('r'):
literal = literal[1:]
# longest matches first:
if literal.startswith("'''"):
ret = literal[3:-3]
elif literal.startswith('"""'):
ret = literal[3:-3]
elif literal.startswith('"'):
ret = literal[1:-1]
elif literal.startswith("'"):
ret = literal[1:-1]
else:
raise ParseError( "weird literal: %s" % ( dbg_ref_, ) )
return ret
# ----------------------------------------------------------------------------------
#
# "unindent" the code
#
def tokenize_expanded( code_text ) :
""" text => [ ( toknum, tokstr, ... ), ... ] """
buffer = io( code_text )
g = T.generate_tokens( buffer.readline )
for tok_tuple in g:
yield tok_tuple
def tokenize( code_text ):
""" text => [ ( toknum, tokstr ), ... ] """
"""
buffer = io( code_text )
g = T.generate_tokens( buffer.readline )
for toknum, tokstr, _, _, _ in g:
yield ( toknum, tokstr )
"""
for toknum, tokstr, _, _, _ in tokenize_expanded( code_text ):
yield ( toknum, tokstr )
def remove_leading_indentation( code_text ):
"""
buffer = io( code_text )
g = T.generate_tokens( buffer.readline )
indent_level = 0
tokens = [ ( toknum, tokstr ) for toknum, tokstr, _, _, _ in g ]
"""
tokens = [ tu for tu in tokenize(code_text) ]
# there is _quite likely_ to be some indentation, nevertheless:
tu_found = seq_find( tokens, lambda tu: tu[0] == T.INDENT )
if tu_found is not None:
pos, tu_ = tu_found
tokens.pop( pos )
tokens.reverse() # in-place !!
found = seq_find( tokens, lambda tu: tu[0] == T.DEDENT ) # the last one, there should be one for each indent level
# assert found is not None
if found is None:
msg = "no corresponding (final) 'DEDENT'ation found! "
e = ParseError( msg )
# dbg
print >>sys.stderr, msg
raise e
# else ..
pos, tu_ = found
tokens.pop( pos )
# return back
tokens.reverse()
return T.untokenize( tokens )
# a test
if 0:
code = \
"""
a = 5
for c in "test":
print c
"""
print '-' * 10
print code
print '-' * 10
code_2 = remove_leading_indentation( code )
print code_2
print '-' * 10
C = compile( code_2, '', 'exec' )
exec C # works !!
sys.exit(0)
# ----------------------------------------------------------------------------------
#
# expand the "GOTO(<state>)" macro
#
"""
def _goto_found( toknum, tokstr ):
## if toknum == T.NAME
if tokstr
"""
_tu_goto_replacement = \
( ( T.NAME , 'self' ), # 0
( T.OP , '.' ), # 1
( T.NAME , '<goto>' ), # 2
( T.OP , '(' ), # 3
( T.STRING , '<LABEL>' ), # 4 ***
( T.OP , ')' ) # 5
)
def _make_replacement_sequence( label_name, goto_name ):
""" GOTO ( LABEL ) => self.<goto_name> ( ' LABEL ' ) """
ret = list( _tu_goto_replacement )
ret[2] = ( T.NAME, goto_name )
ret[4] = ( T.STRING, "'%s'" % ( label_name ) )
return ret
## def expand_goto_macro( code_text, goto_name = '_set_state' ):
def expand_goto_macro( code_text, goto_name = GOTO_METHOD_NAME ):
""" GOTO(STATENAME) => self._set_state('STATENAME') """
## # could have done that with a sequence, but let's keep it plain simple so far ))
## tokens = [ tu for tu in tokenize(code_text) ]
## # states
## NOT_FOUND = 0 # no sequence have started yet )
## GOTO_FOUND = 1 # GOTO _ ( LABEL )
## END = -1
## ERROR = -2
##
## state = NOT_FOUND
gen = tokenize_expanded( code_text )
ret = []
## while state != END :
while True :
tok_tuple = next( gen, None )
if tok_tuple is None:
break
toknum, tokstr, _, _, _ = tok_tuple
## ## if toknum != T.NAME
## # since string literals _include_ the delimiters, we can check only the strings (albeit that would be a bit slower?)
## # ("slower") -- is it so? (a) we'll still have to unref an object (b) quite frequently it's enough to compare the first character ..
## if tokstr == 'GOTO':
## assert toknum == T.NAME
## state = GOTO_FOUND
## if toknum != T.NAME
# since string literals _include_ the delimiters, we can check only the strings (albeit that would be a bit slower?)
# ("slower") -- is it so? (a) we'll still have to unref an object (b) quite frequently it's enough to compare the first character ..
if tokstr == 'GOTO':
assert toknum == T.NAME
# for debugging
_last_tuple = tok_tuple
# start accepting a sequence:
# 0. GOTO _ ( LABEL )
tok_tuple = next( gen, None )
toknum, tokstr, _, _, _ = tok_tuple
if tokstr != '(' :
msg = "expected an '(' after a GOTO:"
e = ParseError(msg, tok_tuple = _last_tuple)
# dbg
print >>sys.stderr, msg, '\n', e.make_message( _last_tuple )
raise e
# else ..
# 1. GOTO ( _ LABEL )
tok_tuple = next( gen, None )
toknum, tokstr, _, _, _ = tok_tuple
if toknum != T.NAME :
msg = 'expected a _name_ after a "GOTO(" :'
e = ParseError(msg, tok_tuple = _last_tuple)
# dbg
print >>sys.stderr, msg, '\n', e.make_message( _last_tuple )
raise e
# else ..
label = tokstr
# 2. GOTO ( LABEL _ )
tok_tuple = next( gen, None )
toknum, tokstr, _, _, _ = tok_tuple
if tokstr != ')' :
msg = "expected an ')' after a GOTO( %s :" % ( label, )
e = ParseError(msg, tok_tuple = _last_tuple)
# dbg
print >>sys.stderr, msg, '\n', e.make_message( _last_tuple )
raise e
# else -- we're done:
insert = _make_replacement_sequence( label, goto_name )
ret.extend( insert )
else: # any other token but 'GOTO'
ret.append( (toknum, tokstr) )
# assemble it back:
return T.untokenize( ret )
# a test
if 0:
correct_code = \
"""
a = 5
if a > 8:
GOTO( INITIAL )
print "GOTO"
"""
print '-' * 10
print correct_code
print '-' * 10
replaced = expand_goto_macro( correct_code, goto_name = 'goto' )
print replaced
print '-' * 10
wrong_code = \
"""
a = 5
if a > 8:
GOTO INITIAL
print "GOTO"
"""
print '-' * 10
print wrong_code
print '-' * 10
replaced = expand_goto_macro( wrong_code, goto_name = 'goto' )
print replaced
print '-' * 10
sys.exit(0)
# ----------------------------------------------------------------------------------
#
# replace single tokens: yylval => 'self._yylval', 'return' => 'self._yy_result = '
#
'''
def _replace_name_token( tok_seq, tok_name, tok_repl ):
""" 'tok_seq' is a sequence of (tok_type, tok_str);
'tok_name' is "tok_str" for a .NAME token ;
finally,
'tok_repl' is a sequence of tokens to replace;
## NB: first arg can be a generator, but the last arg
## is concidered to be a
return value: yields a new sequence )
"""
for tok_type, tok_str in tok_seq:
if tok_str != tok_name:
yield (tok_type, tok_str)
else: # token found
for tu in tok_repl:
yield tu
'''
def _replace_tokens( tok_seq, replacements ):
""" 'tok_seq' is a sequence of (tok_type, tok_str);
'replacements' is a dictionary: {
'token_string' => ( sequence of (type, str) to replace )
return value: yields a new sequence )
"""
keys = replacements.keys()
for tok_type, tok_str in tok_seq:
if tok_str in keys:
repl = replacements[ tok_str ]
for tu in repl:
yield tu
else: # not in replacements
yield (tok_type, tok_str)
def _make_tok_list( text ):
return list( tokenize(text) )
## YYLVAL_STRING = 'self._yylval' # <= 'yylval'
## RETURN_STRING = 'self._yy_result' # <= 'RETURN'
_expansions = {
'yylval' : _make_tok_list( 'self._yylval' ),
# let's stress that this is a macro
'RETURN' : _make_tok_list( 'self._yy_result =' )
# could have made this a " = .. ; break ; ",
# or raise/catch, but let's stick with this for the moment
}
def _expand_tokens( text, expansions = _expansions ):
gen = _replace_tokens( tokenize(text), replacements = expansions )
ret = T.untokenize( gen )
return ret
# a test
if 0:
test_code = \
"""
a = 5
b = '123'
yylval = b
RETURN a
"""
print '-' * 10
print test_code
print '-' * 10
replaced = _expand_tokens( test_code )
print replaced
print '-' * 10
sys.exit(0)
# ----------------------------------------------------------------------------------
def preprocess_action_code( action_code_text ):
## action = remove_leading_indentation( action )
## action = expand_goto_macro( action )
result = remove_leading_indentation( action_code_text )
result = expand_goto_macro( result )
result = _expand_tokens( result )
return result
# ----------------------------------------------------------------------------------
## ===============================================================================
# ----------------------------------------------------------------------------------
#
# the template for the generated lexer
#
LEXER_TEMPLATE = \
r"""#!/usr/bin/python
## ^^^ python 2.6+ ~~~
import re
# ----------------------------------------------------------------------------------
#
# our exception object
#
class LexerError(Exception):
''' current state has failed to recognize any match '''
# ----------------------------------------------------------------------------------
# ACTIONS = {
# '_1' : \
# r'''code_fragment_1''' [,] [\n]
# '_2' : \
# r'''code_fragment_2''' [,] [\n]
# }
%(code_fragments)s
# compile the action code
__filename = __name__ + ' (inline)' # refer to the same file instead of sth like "''"
kompile = lambda code: compile( code, __filename, 'exec' )
COMPILED = { k: kompile(v) for k, v in ACTIONS.iteritems() }
# ----------------------------------------------------------------------------------
#
# regular expression definitions
#
%(regexp_defs)s
# ----------------------------------------------------------------------------------
#
# an accessory method, an alternative would be to compile() it,
# echanging one extra function call
# for having this function code precompiled with the module
#
def _yy_state_code( self, _yy_regexp, _yy_lex_state_name ):
''' internal code shared by any lexer state '''
#
# check for end-of-input
#
if self._yy_offset == self._yy_length:
self._yy_state = None # we're done
return # None
yymatch = _yy_regexp.match( self.yy_input_text, self._yy_offset )
if yymatch is None:
raise LexerError( "no matches found at offset %%s at state %%s" %% (self._yy_offset, _yy_lex_state_name) )
# else ..
yygname = yymatch.lastgroup
yytext = yymatch.group( yygname )
## yyspan = yymatch.span()
yyleng = yymatch.end() - yymatch.start() # does this really optimize anything substantially ?
self._yy_offset = yymatch.end()
exec ACTIONS[yygname]
class Lexer:
''' '''
def reset( self, input_text = '' ):
''' reset the splitter '''
self.yy_input_text = input_text
self._yy_offset = 0
self._yy_state = self.state_%(start_state)s
## self._yy_result = None # 'yylval'; if != None, we return this
%(yylval_string)s = None
%(yyreturn_string)s = None # misleading semantics, don't use this
# user-defined initialization code, if any:
%(initialization_code)s
def add_input( self, input_text, reset=False, eof_as_nl = True ):
''' add another piece of code to 'split' '''
if reset:
self.reset()
tail = self.yy_input_text
if tail:
if eof_as_nl:
# simulate end-of-line on end of input:
self.yy_input_text = '\n'.join( (tail, input_text) )
else: # don't insert any "fake" newlines
self.yy_input_text += input_text
else: # empty buffer so far, just reset it
self.yy_input_text = input_text
# don't check for the length in every sub-state:
self._yy_length = len( self.yy_input_text )
# ----------------------------------------------------------------------------------
def __init__( self, input_text ):
self.reset( input_text )
# ----------------------------------------------------------------------------------
def %(goto_name)s(self, state_name):
self._yy_state = getattr( self, 'state_' + state_name )
# ----------------------------------------------------------------------------------
def run(self):
''' calls self.state_...() one-by-one,
until internal ._state reference would be set to None '''
## YYLVAL_STRING = 'self._yylval' # <= 'yylval'
## RETURN_STRING = 'self._yy_result' # <= 'RETURN'
while( self._yy_state is not None ):
# clear flags:
%(yylval_string)s = None
%(yyreturn_string)s = None
self._yy_state()
# return ?
if %(yylval_string)s is not None:
return %(yylval_string)s
# obsolete, misleading semantics, do not use
if %(yyreturn_string)s is not None:
return %(yyreturn_string)s
## return None
# ----------------------------------------------------------------------------------
%(sublexer_methods)s
#
# a very simple test: read stdin, then parse it
#
if __name__ == "__main__":
import sys
text = sys.stdin.read()
lexer = Lexer('')
## lexer.add_input(''' aaa bbb''')
lexer.add_input( text )
## lexer.run()
ret = lexer.run()
while ret is not None:
state, text = ret
print "\t state: '%%s', text: '%%s'" %% ( state, text )
ret = lexer.run()
"""
## sss
# ----------------------------------------------------------------------------------
# generate "%(code_fragments)s" for the above:
def print_code_defs_init():
""" hiding "local"/"static function variables in a closure" """
header = \
r"""
ACTIONS = {
"""
## # remove leading '\n':
## header = header.lstrip()
footer = \
r"""
}
"""
entry_template = \
r"""
'_%d' : \
r'''%s''',
"""
def print_code_defs( action_map, const_name = 'ACTIONS' ):
""" { 1: action_1, ... } =>
===
ACTIONS = {
'_1' : \
r'''code_fragment_1''',
'_2': \
r'''code_fragment_2''',
...
}
===
*** NB: we could have used "%s" % repr(code) in the template instaed of "r'''%s'''" % code, but this *kills* readability ***
"""
# action_map is assumed to be an OrderedDict, so there's no need for sorting the keys
parts = [ header ]
for key, value in action_map.iteritems():
# repr() is a bit ugly, but since the action code
# may possibly contain '''/""" - strings,
# this is actually the only way (((
# // TODO: better repr() ? // w/some '''/"""/r'''/r""" heuristics ?
## text = repr(value)
text = value
parts.append( entry_template % ( key, text ) )
parts.append( footer )
return ''.join( parts )
return print_code_defs
# we need only one instance )
print_code_defs = print_code_defs_init()
# ----------------------------------------------------------------------------------
# generate regular expression definitions
def make_state_regexp_init( ):
""" hiding "local"/"static function variables in a closure" """
header = \
r"""
re_%(state_name)s_str = r'''
"""
template = '(?P<_%(action_id)d>%(regexp)s)' # implicitly contains <%d> => '_%d' transformation
footer = \
r"""
'''
re_%(state_name)s = re.compile( re_%(state_name)s_str, re.VERBOSE )
"""
def make_state_regexp( state_name, components, indent = ' ' ):
""" 'state_name' is, well, a state name, and
'components' is a sequence of ( trigger_re, action_id <a number> ) ;
the result would be an (unindented) method definition,
that could be indented with 'indent(text, indentation)' from above
"""
## make_verbose = lambda reg_exp: reg_exp.replace(' ', '[ ]').replace('\t', r'\t')
# ^^^ not good inside character classes ~~~
make_verbose = lambda reg_exp: reg_exp.replace(' ', r'\ ').replace('\t', r'\t')
parts = [ header % locals() ]
regexp_parts = []
for re_trigger, action_id in components:
## regexps are just string literals, so to make them printable, we eval() them:
## regexp = eval( re_trigger )
### regexp = re.escape( eval( re_trigger ) )
re_str = strip_string_literal( re_trigger )
regexp = make_verbose( re_str )
regexp_parts.append( template % locals() )
regexp_part = ( '\n%s|' % indent ).join( regexp_parts )
# indent the first one:
prefix = indent + ' ' # ' ' is for '|'
parts.append( prefix + regexp_part )
parts.append( footer % locals() )
return ''.join( parts )
return make_state_regexp
# we need only one instance )
make_state_regexp = make_state_regexp_init()
# ----------------------------------------------------------------------------------
# generate "%(sublexer_methods)s" for the above:
def print_sublexer_method_init( ):
""" hiding "local"/"static function variables in a closure" """
header_template = \
r"""
def state_%(state_name)s(self, _yy_regexp = re_%(state_name)s, _yy_lex_state_name = '%(state_name)s'):
''' state '%(state_name)s' '''
_yy_state_code( self, _yy_regexp, _yy_lex_state_name )
"""
# unfortunately, the compiled code may not have any 'return' statements
## ret = _yy_state_code( self, _yy_regexp, _yy_lex_state_name )
## if ret is not None:
## return ret
## ** All the code below repeats for every method, so we can just compile() it; **
## // we could have mede it an extra method function, since the parameters are rather well defined,
## // but what's the big difference ? ( function is compiled with the module,
## // but is one extra call; the code is compiled on import instead )
##
## #
## # check for end-of-input
## #
## if self._yy_offset == self._yy_length:
## self._yy_state = None # we're done
## return # None
##
## yymatch = _regexp.match( self.yy_input_text, self._yy_offset )
## if yymatch is None:
## raise LexerError( "no matches found at offset %%s at state %%s" %% (self._yy_offset, _yy_lex_state_name) )
##