-
Notifications
You must be signed in to change notification settings - Fork 2
/
pyexpander.py
executable file
·3005 lines (2785 loc) · 107 KB
/
pyexpander.py
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/env python2
# -*- coding: UTF-8 -*-
# this is an "amalgamated" version of pyexpander 1.10.2, containing
# the 2 library files and the main command line frontend.
# the sources have been taken from https://files.pythonhosted.org/packages/fb/1f/6497aa7140e44d0f95ab110c95e74d971292d65712a3d2356ffc432a3df0/pyexpander-1.10.2.tar.gz
# pyexpander 1.10.2 has been chosen over the more recent 2.0 release
# as python 2.7 support has been dropped in the latter.
# due to how imports work, the variables INPUT_DEFAULT_ENCODING
# and SYS_DEFAULT_ENCODING had to be declared global both in
# filescope and the function in the if __main__ block using them.
# IMPORTANT! the default token character $ has been modified to ~ as my
# intention is to use this on html files that use jquery javascript
# that makes extensive use of $(...) itself.
# (C) 2012-2020 Goetz Pfeiffer <Goetz.Pfeiffer@helmholtz-berlin.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
# you can find the full license text at:
# https://www.gnu.org/licenses/gpl-3.0.txt
# --------------------- start of imported sources ------------------
# imported from pyexpander 1.10.2 python2/pyexpander/parser.py
"""implement the parser for pyexpander.
"""
import bisect
import re
__version__= "1.10.2" #VERSION#
# pylint: disable= invalid-name
# we use '\n' as line separator and rely on python's built in line end
# conversion to '\n' on all platforms.
# You may howver, use change_linesep() to change the line separator.
LINESEP= "\n"
LINESEP_LEN= len(LINESEP)
def change_linesep(sep):
"""change line separator, this is here just for tests.
"""
# pylint: disable= global-statement
global LINESEP, LINESEP_LEN
LINESEP= sep
LINESEP_LEN= len(sep)
class IndexedString(object):
"""a string together with row column information.
Here is an example:
>>> txt='''01234
... 67
... 9abcd'''
>>> l=IndexedString(txt)
>>> l.rowcol(0)
(1, 1)
>>> l.rowcol(1)
(1, 2)
>>> l.rowcol(4)
(1, 5)
>>> l.rowcol(5)
(1, 6)
>>> l.rowcol(6)
(2, 1)
>>> l.rowcol(7)
(2, 2)
>>> l.rowcol(8)
(2, 3)
>>> l.rowcol(9)
(3, 1)
>>> l.rowcol(13)
(3, 5)
>>> l.rowcol(14)
(3, 6)
>>> l.rowcol(16)
(3, 8)
"""
# pylint: disable= too-few-public-methods
def __init__(self, st):
self._st=st
self._lines=None
self._positions=None
def _list(self):
"""calculate and remember positions where lines begin."""
l= len(self._st)
pos=0
self._lines=[1]
self._positions=[0]
lineno=1
while True:
# look for the standard lineseparator in the string:
p= self._st.find(LINESEP, pos)
if p<0:
# not found
break
pos= p+LINESEP_LEN
if pos>=l:
break
lineno+=1
self._lines.append(lineno)
self._positions.append(pos)
def rowcol(self,pos):
"""calculate (row,column) from a string position."""
if self._lines is None:
self._list()
idx= bisect.bisect_right(self._positions, pos)-1
off= self._positions[idx]
return(self._lines[idx], pos-off+1)
def st(self):
"""return the raw string."""
return self._st
def __str__(self):
return "IndexedString(...)"
def __repr__(self):
# Note: if repr(some object) gets too long since
# repr(IndexedString(..)) basically prints the whole input file
# you may in-comment the following line in order to make
# the output shorter:
#return "IndexedString(...)"
return "IndexedString(%s)" % repr(self._st)
class ParseException(Exception):
"""used for Exceptions in this module."""
def __init__(self, value, pos=None, rowcol=None):
super(ParseException, self).__init__(value, pos, rowcol)
self.value = value
self.pos= pos
self.rowcol= rowcol
def __str__(self):
if self.rowcol is not None:
return "%s line %d, col %d" % \
(self.value,self.rowcol[0],self.rowcol[1])
elif self.pos is not None:
return "%s position: %d" % (self.value,self.pos)
return "%s" % self.value
rx_pyIdent= re.compile(r'([A-Za-z_][\w\.]*)$')
rx_csv=re.compile(r'\s*,\s*')
def scanPyIdentList(st):
"""scan a list of python identifiers.
Here are some examples:
>>> scanPyIdentList("a,b")
['a', 'b']
>>> scanPyIdentList("a,b.d, c")
['a', 'b.d', 'c']
>>> scanPyIdentList("a,b.d, c&")
Traceback (most recent call last):
...
ParseException: list of python identifiers expected
"""
lst= re.split(rx_csv, st)
for elm in lst:
m= rx_pyIdent.match(elm)
if m is None:
raise ParseException("list of python identifiers expected")
return lst
rx_py_in= re.compile(r'^\s*(.*?)\s*\b(in)\b\s*(.*?)\s*$')
def scanPyIn(st):
"""scan a python "in" statement.
Here are some examples:
>>> scanPyIn(" (a,b) in k.items() ")
('(a,b)', 'in', 'k.items()')
"""
m= rx_py_in.match(st)
if m is None:
raise ParseException("python \"in\" expression expected")
return m.groups()
rx_bracketed= re.compile(r'\{[A-Za-z_]\w*\}')
def parseBracketed(idxst,pos):
"""parse an identifier in curly brackets.
Here are some examples:
>>> def test(st,pos):
... idxst= IndexedString(st)
... (a,b)= parseBracketed(idxst,pos)
... print st[a:b]
...
>>> test(r'{abc}',0)
{abc}
>>> test(r'{ab8c}',0)
{ab8c}
>>> test(r'{c}',0)
{c}
>>> test(r'{}',0)
Traceback (most recent call last):
...
ParseException: command enclosed in curly brackets at line 1, col 1
>>> test(r'{abc',0)
Traceback (most recent call last):
...
ParseException: command enclosed in curly brackets at line 1, col 1
>>> test(r'x{ab8c}',1)
{ab8c}
"""
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
m= rx_bracketed.match(st,pos)
if m is None:
raise ParseException("command enclosed in curly brackets at",
rowcol= idxst.rowcol(pos))
return(pos,m.end())
# from python 2 documentation:
# stringprefix ::= "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"
# | "b" | "B" | "br" | "Br" | "bR" | "BR"
rx_StringLiteralStart= re.compile(r'''(br|bR|Br|BR|ur|uR|Ur|UR|b|B|r|R|u|U|)("""|''' + \
"""'''""" + \
r'''|'|")''')
def parseStringLiteral(idxst,pos):
r"""parse a python string literal.
returns 2 numbers, the index where the string starts and
the index of the first character *after* the string
Here are some examples:
>>> def test(st,pos):
... idxst= IndexedString(st)
... (a,b)= parseStringLiteral(idxst,pos)
... print st[a:b]
...
>>> test(r'''"abc"''',0)
"abc"
>>> test("'''ab'c'd'''",0)
'''ab'c'd'''
>>> test("'''ab'cd''''",0)
'''ab'cd'''
>>> test(r'''U"abc"''',0)
U"abc"
>>> test(r'''xU"abc"''',1)
U"abc"
>>> test(r'''xUr"abc"''',1)
Ur"abc"
>>> test(r'''xUr"ab\\"c"''',1)
Ur"ab\\"
>>> test(r'''xUr"ab\"c"''',1)
Ur"ab\"c"
>>> test(r'''xUr"ab\"c"''',0)
Traceback (most recent call last):
...
ParseException: start of string expected at line 1, col 1
>>> test(r'''"ab''',0)
Traceback (most recent call last):
...
ParseException: end of string not found at line 1, col 1
>>> test(r"'''ab'",0)
Traceback (most recent call last):
...
ParseException: end of string not found at line 1, col 1
>>> test(r'''"ab\"''',0)
Traceback (most recent call last):
...
ParseException: end of string not found at line 1, col 1
"""
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
m= rx_StringLiteralStart.match(st,pos)
if m is None:
raise ParseException("start of string expected at",
rowcol= idxst.rowcol(pos))
prefix= m.group(1)
starter= m.group(2) # """ or ''' or " or '
#is_unicode= False
#is_raw= False
#if -1!=prefix.find("r"):
# is_raw= True
#elif -1!=prefix.find("R"):
# is_raw= True
#if -1!=prefix.find("u"):
# is_unicode= True
#elif -1!=prefix.find("U"):
# is_unicode= True
startpos= pos+len(prefix)+len(starter)
while True:
idx= st.find(starter, startpos)
# if startpos>len(st), idx is also -1
if idx==-1:
raise ParseException("end of string not found at",
rowcol= idxst.rowcol(pos))
if st[idx-1]=="\\":
# maybe escaped quote char
try:
if st[idx-2]!="\\":
# only then it is an escaped quote char
startpos= idx+1
continue
except IndexError, _:
raise ParseException("end of string not found at",
rowcol= idxst.rowcol(pos))
break
if len(starter)==1:
# simple single quoted string
return(pos,idx+1)
return(pos,idx+3)
def parseComment(idxst,pos):
r"""parse a python comment.
Here are some examples:
>>> import os
>>> def test(st,pos,sep=None):
... if sep:
... change_linesep(sep)
... idxst= IndexedString(st)
... (a,b)= parseComment(idxst,pos)
... print repr(st[a:b])
... change_linesep(os.linesep)
...
>>> test("#abc",0)
'#abc'
>>> test("#abc\nef",0,"\n")
'#abc\n'
>>> test("#abc\r\nef",0,"\r\n")
'#abc\r\n'
>>> test("xy#abc",2)
'#abc'
>>> test("xy#abc\nef",2,"\n")
'#abc\n'
>>> test("xy#abc\nef",3)
Traceback (most recent call last):
...
ParseException: start of comment not found at line 1, col 4
"""
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
if st[pos]!="#":
raise ParseException("start of comment not found at",
rowcol= idxst.rowcol(pos))
idx_lf= st.find(LINESEP,pos+1)
if idx_lf==-1:
return(pos, len(st))
return(pos,idx_lf+LINESEP_LEN)
rx_CodePart= re.compile(r'''((?:UR|Ur|uR|ur|r|u|R|U|)(?:"""|''' + """'''""" + \
r'''|'|")|#|\(|\))''')
def parseCode(idxst,pos):
r"""parse python code, it MUST start with a '('.
Here are some examples:
>>> def test(st,pos):
... idxst= IndexedString(st)
... (a,b)= parseCode(idxst,pos)
... print st[a:b]
...
>>> test(r'(a+b)',0)
(a+b)
>>> test(r'(a+(b*c))',0)
(a+(b*c))
>>> test(r'(a+(b*c)+")")',0)
(a+(b*c)+")")
>>> test(r"(a+(b*c)+''')''')",0)
(a+(b*c)+''')''')
>>> test(r"(a+(b*c)+''')'''+# comment )\n)",0)
Traceback (most recent call last):
...
ParseException: end of bracket expression not found at line 1, col 1
>>>
>>> test("(a+(b*c)+''')'''+# comment )\n)",0)
(a+(b*c)+''')'''+# comment )
)
"""
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
if st[pos]!="(":
raise ParseException("start of bracket expression not found at",
rowcol= idxst.rowcol(pos))
startpos= pos+1
while True:
m= rx_CodePart.search(st, startpos)
if m is None:
raise ParseException("end of bracket expression not found at",
rowcol= idxst.rowcol(pos))
matched= m.group(1)
if matched=="#":
# a comment
(_,b)= parseComment(idxst, m.start())
startpos= b
continue
if matched=="(":
# an inner bracket
(_,b)= parseCode(idxst, m.start())
startpos= b
continue
if matched==")":
return(pos,m.start()+1)
# from here it must be a string literal
(_,b)= parseStringLiteral(idxst, m.start())
startpos= b
continue
class ParsedItem(object):
"""base class of parsed items."""
def __init__(self, idxst, start, end):
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
self._idxst= idxst
self._start= start
self._end= end
def string(self):
"""return the string that represents the ParsedItem."""
return self._idxst.st()[self._start:self._end+1]
def start(self):
"""return the start of the ParsedItem in the source string."""
return self._start
def end(self):
"""return the end of the ParsedItem in the source string."""
return self._end
def rowcol(self, pos= None):
"""calculate (row,column) from a string position."""
if pos is None:
pos= self.start()
return self._idxst.rowcol(pos)
def positions(self):
"""return start and end of ParsedItem in the source string."""
return "(%d, %d)" % (self._start, self._end)
def __str__(self):
return "('%s', %s, %s)" % (self.__class__.__name__, \
self.positions(), repr(self.string()))
def __repr__(self):
return "%s(%s, %s, %s)" % (self.__class__.__name__, \
repr(self._idxst), repr(self._start), repr(self._end))
class ParsedLiteral(ParsedItem):
"""class of a parsed literal.
A literal is a substring in the input that shouldn't be modified by
pyexpander.
"""
def __init__(self, idxst, start, end):
ParsedItem.__init__(self, idxst, start, end)
class ParsedComment(ParsedItem):
"""class of a parsed comment.
A comment in pyexpander starts with '~#'.
"""
def __init__(self, idxst, start, end):
ParsedItem.__init__(self, idxst, start, end)
class ParsedVar(ParsedItem):
"""class of a parsed variable.
A variable in pyexpander has the form "~(identifier)".
"""
def __init__(self, idxst, start, end):
ParsedItem.__init__(self, idxst, start, end)
class ParsedEval(ParsedItem):
"""class of an pyexpander expression.
A pyexpander expression has the form "~(expression)" e.g. "~(a+1)". This is
different from ParsedVar where the string within the brackets is a simple
identifier.
"""
def __init__(self, idxst, start, end):
ParsedItem.__init__(self, idxst, start, end)
class ParsedPureCommand(ParsedItem):
"""class of a pyexpander command without arguments.
A pure command has the form "~name". Such a command has no arguments which
would be enclosed in round brackets immediately following the name.
"""
def __init__(self, idxst, start, end):
ParsedItem.__init__(self, idxst, start, end)
class ParsedCommand(ParsedItem):
"""class of a pyexpander command with arguments.
A command has the form "~name(argument1, argument2, ...)".
"""
def __init__(self, idxst, start, end, ident):
ParsedItem.__init__(self, idxst, start, end)
self.ident= ident
def args(self):
"""return the arguments of the command."""
return self.string()
def __str__(self):
return "('%s', %s, %s, %s)" % (self.__class__.__name__, \
self.positions(), repr(self.string()), \
repr(self.ident))
def __repr__(self):
return "%s(%s, %s, %s, %s)" % (self.__class__.__name__, \
repr(self._idxst), repr(self._start), repr(self._end), \
repr(self.ident))
rx_DollarFollows= re.compile(r'([A-Za-z_]\w*|\(|\{|#)')
def parseDollar(idxst, pos):
r"""parse things that follow a dollar.
Here are some examples:
>>> def test(st,pos):
... idxst= IndexedString(st)
... (p,elm)= parseDollar(idxst,pos)
... print "Parsed: %s" % elm
... print "rest of string:%s" % st[p:]
...
>>> test("~abc",0)
Parsed: ('ParsedPureCommand', (1, 3), 'abc')
rest of string:
>>> test("~abc%&/",0)
Parsed: ('ParsedPureCommand', (1, 3), 'abc')
rest of string:%&/
>>> test("~abc(2*3)",0)
Parsed: ('ParsedCommand', (5, 7), '2*3', 'abc')
rest of string:
>>> test(" ~abc(2*sin(x))",1)
Parsed: ('ParsedCommand', (6, 13), '2*sin(x)', 'abc')
rest of string:
>>> test(" ~abc(2*sin(x))bn",1)
Parsed: ('ParsedCommand', (6, 13), '2*sin(x)', 'abc')
rest of string:bn
>>> test(" ~# a comment\nnew line",1)
Parsed: ('ParsedComment', (3, 13), ' a comment\n')
rest of string:new line
>>> test("~(abc)",0)
Parsed: ('ParsedVar', (2, 4), 'abc')
rest of string:
>>> test("~(abc*2)",0)
Parsed: ('ParsedEval', (2, 6), 'abc*2')
rest of string:
>>> test(" ~(2*x(y))abc",1)
Parsed: ('ParsedEval', (3, 8), '2*x(y)')
rest of string:abc
"""
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
if st[pos]!="~":
raise ParseException("'~' expected at",
rowcol= idxst.rowcol(pos))
m= rx_DollarFollows.match(st, pos+1)
if m is None:
raise ParseException("unexpected characters after '~' at",
rowcol= idxst.rowcol(pos))
matched= m.group(1)
# pylint: disable= redefined-variable-type
if matched=="#":
# an expander comment
(a, b)= parseComment(idxst, pos+1)
elm= ParsedComment(idxst, a+1, b-1)
return (b, elm)
if matched=="(":
(a, b)= parseCode(idxst, pos+1)
m_ident= rx_pyIdent.match(st, a+1, b-1)
if m_ident is not None:
elm= ParsedVar(idxst, a+1, b-2)
else:
elm= ParsedEval(idxst, a+1, b-2)
return (b, elm)
if matched=="{":
# a purecommand enclosed in "{}" brackets
(a, b)= parseBracketed(idxst, pos+1)
elm= ParsedPureCommand(idxst, a+1, b-2)
return (b, elm)
# from here: a purecommand or a command
try:
nextchar= st[m.end()]
except IndexError, _:
nextchar= None
if nextchar=="(":
(a, b)= parseCode(idxst, m.end())
elm= ParsedCommand(idxst, a+1, b-2, matched)
return (b, elm)
elm= ParsedPureCommand(idxst, pos+1, m.end()-1)
return (m.end(), elm)
def parseBackslash(idxst, pos):
r"""parses a backslash.
>>> import os
>>> def test(st,pos,sep=None):
... if sep:
... change_linesep(sep)
... idxst= IndexedString(st)
... (p,elm)= parseBackslash(idxst,pos)
... print "Parsed: %s" % elm
... print "rest of string:%s" % repr(st[p:])
... change_linesep(os.linesep)
...
>>> test(r"\abc",0)
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:'abc'
>>> test("\\",0)
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:''
>>> test("\\\rab",0,"\r")
Parsed: None
rest of string:'ab'
>>> test("\\\rab",0,"\n")
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:'\rab'
>>> test("\\\rab",0,"\r\n")
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:'\rab'
>>> test("\\\nab",0,"\r")
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:'\nab'
>>> test("\\\nab",0,"\n")
Parsed: None
rest of string:'ab'
>>> test("\\\nab",0,"\r\n")
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:'\nab'
>>> test("\\\r\nab",0,"\r")
Parsed: None
rest of string:'\nab'
>>> test("\\\r\nab",0,"\n")
Parsed: ('ParsedLiteral', (0, 0), '\\')
rest of string:'\r\nab'
>>> test("\\\r\nab",0,"\r\n")
Parsed: None
rest of string:'ab'
"""
# pylint: disable= too-many-return-statements
# backslash found
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
if st[pos]!="\\":
raise ParseException("backslash expected at",
rowcol= idxst.rowcol(pos))
l_= len(st)
if pos+1>=l_:
# no more characters
elm= ParsedLiteral(idxst, pos, pos)
return (pos+1, elm)
else:
# at least one more character
nextchar= st[pos+1]
if nextchar=="\\":
elm= ParsedLiteral(idxst, pos, pos)
return (pos+2, elm)
if nextchar=="~":
elm= ParsedLiteral(idxst, pos+1, pos+1)
return (pos+2, elm)
if pos+LINESEP_LEN>=l_:
# not enough characters for LINESEP
elm= ParsedLiteral(idxst, pos, pos)
return (pos+1, elm)
else:
for i in xrange(LINESEP_LEN):
if st[pos+1+i]!=LINESEP[i]:
# no line separator follows
elm= ParsedLiteral(idxst, pos, pos)
return (pos+1, elm)
return(pos+LINESEP_LEN+1, None)
# WARNING: depending on which character is used to replace the original
# dollar "$" token, the character may or may not be escaped here!
rx_top= re.compile(r'(\~|\\)')
def parseAll(idxst, pos):
r"""parse everything.
>>> def test(st,pos):
... idxst= IndexedString(st)
... pprint(parseAll(idxst,pos))
...
>>> test("abc",0)
('ParsedLiteral', (0, 2), 'abc')
>>> test("abc~xyz",0)
('ParsedLiteral', (0, 2), 'abc')
('ParsedPureCommand', (4, 6), 'xyz')
>>> test("abc~{xyz}efg",0)
('ParsedLiteral', (0, 2), 'abc')
('ParsedPureCommand', (5, 7), 'xyz')
('ParsedLiteral', (9, 11), 'efg')
>>> test("abc~xyz(2*4)",0)
('ParsedLiteral', (0, 2), 'abc')
('ParsedCommand', (8, 10), '2*4', 'xyz')
>>> test("abc~(2*4)ab",0)
('ParsedLiteral', (0, 2), 'abc')
('ParsedEval', (5, 7), '2*4')
('ParsedLiteral', (9, 10), 'ab')
>>> test("abc\\~(2*4)ab",0)
('ParsedLiteral', (0, 2), 'abc')
('ParsedLiteral', (4, 4), '~')
('ParsedLiteral', (5, 11), '(2*4)ab')
>>> test("ab~func(1+2)\\\nnew line",0)
('ParsedLiteral', (0, 1), 'ab')
('ParsedCommand', (8, 10), '1+2', 'func')
('ParsedLiteral', (14, 21), 'new line')
>>> test("ab~func(1+2)\nnew line",0)
('ParsedLiteral', (0, 1), 'ab')
('ParsedCommand', (8, 10), '1+2', 'func')
('ParsedLiteral', (12, 20), '\nnew line')
>>> test("ab~(xyz)(56)",0)
('ParsedLiteral', (0, 1), 'ab')
('ParsedVar', (4, 6), 'xyz')
('ParsedLiteral', (8, 11), '(56)')
>>> test(r'''
... Some text with a macro: ~(xy)
... an escaped dollar: \~(xy)
... a macro within letters: abc~{xy}def
... a pyexpander command structure:
... ~if(a=1)
... here
... ~else
... there
... ~endif
... now a continued\
... line
... from here:~# the rest is a comment
... now an escaped continued\\
... line
... ''',0)
('ParsedLiteral', (0, 24), '\nSome text with a macro: ')
('ParsedVar', (27, 28), 'xy')
('ParsedLiteral', (30, 49), '\nan escaped dollar: ')
('ParsedLiteral', (51, 51), '~')
('ParsedLiteral', (52, 83), '(xy)\na macro within letters: abc')
('ParsedPureCommand', (86, 87), 'xy')
('ParsedLiteral', (89, 124), 'def\na pyexpander command structure:\n')
('ParsedCommand', (129, 131), 'a=1', 'if')
('ParsedLiteral', (133, 138), '\nhere\n')
('ParsedPureCommand', (140, 143), 'else')
('ParsedLiteral', (144, 150), '\nthere\n')
('ParsedPureCommand', (152, 156), 'endif')
('ParsedLiteral', (157, 172), '\nnow a continued')
('ParsedLiteral', (175, 189), 'line\nfrom here:')
('ParsedComment', (192, 214), ' the rest is a comment\n')
('ParsedLiteral', (215, 238), 'now an escaped continued')
('ParsedLiteral', (239, 239), '\\')
('ParsedLiteral', (241, 246), '\nline\n')
"""
if not isinstance(idxst, IndexedString):
raise TypeError, "idxst par wrong: %s" % repr(idxst)
st= idxst.st()
parselist=[]
l= len(st)
while True:
if pos>=l:
return parselist
m= rx_top.search(st, pos)
if m is None:
parselist.append(ParsedLiteral(idxst, pos, len(st)-1))
return parselist
if m.start()>pos:
parselist.append(ParsedLiteral(idxst, pos, m.start()-1))
if m.group(1)=="\\":
(p, elm)= parseBackslash(idxst, m.start())
if elm is not None:
parselist.append(elm)
pos= p
continue
# from here it must be a dollar sign
(pos, elm)= parseDollar(idxst, m.start())
parselist.append(elm)
continue
def pprint(parselist):
"""pretty print a parselist."""
for elm in parselist:
print str(elm)
def _parser_test():
"""perform the doctest tests."""
import doctest
print "testing..."
doctest.testmod()
print "done"
# imported from pyexpander 1.10.2 python2/pyexpander/lib.py
"""The main pyexpander library.
"""
# pylint: disable=too-many-lines
import os
import os.path
import inspect
import sys
import locale
import codecs
import keyword
# pylint: disable=wrong-import-position
# pylint: disable=invalid-name
# ---------------------------------------------
# constants
# ---------------------------------------------
PY_KEYWORDS= set(keyword.kwlist)
# length of line separator
LINESEP_LEN= len(os.linesep)
global SYS_DEFAULT_ENCODING, INPUT_DEFAULT_ENCODING
SYS_DEFAULT_ENCODING= locale.getpreferredencoding()
# INPUT_DEFAULT_ENCODING may be changed by expander.py:
INPUT_DEFAULT_ENCODING= SYS_DEFAULT_ENCODING
INTERNAL_ENCODING= "utf-8"
PURE_CMD_KEYWORDS= set([ \
"else",
"endif",
"endfor",
"endwhile",
"endmacro",
"begin",
"end",
])
CMD_KEYWORDS= set([ \
"py",
"include",
"include_begin",
"template",
"subst",
"pattern",
"default",
"if",
"elif",
"for",
"for_begin",
"while",
"while_begin",
"macro",
"nonlocal",
"extend",
"extend_expr",
])
KEYWORDS= PURE_CMD_KEYWORDS | CMD_KEYWORDS | PY_KEYWORDS
# ---------------------------------------------
# dump utilities
# ---------------------------------------------
def _set2str(val):
"""convert an iterable to the repr string of a set."""
elms= sorted(list(val))
return "set(%s)" % repr(elms)
def _pr_set(val):
"""print an iterable as the repr string of a set."""
print _set2str(val)
def find_file(filename, include_paths):
"""find a file in a list of include paths.
include_paths MUST CONTAIN "" in order to search the
local directory.
"""
if include_paths is None:
return None
for path in include_paths:
p= os.path.join(path, filename)
if os.path.exists(p):
if os.access(p, os.R_OK):
return p
print "warning: file \"%s\" found but it is not readable" % \
p
return None
# ---------------------------------------------
# helper functions
# ---------------------------------------------
def keyword_check(identifiers):
"""indentifiers must not be identical to keywords.
This function may raise an exception.
"""
s= set(identifiers).intersection(KEYWORDS)
if s:
lst= ", ".join(["'%s'" % e for e in sorted(s)])
raise ValueError, "keywords %s cannot be used as identifiers" % lst
_valid_encodings= set()
def test_encoding(encoding):
"""test if an encoding is known.
raises (by encode() method) a LookupError exception in case of an error.
"""
if encoding in _valid_encodings:
return
"a".encode(encoding) # may raise LookupError
_valid_encodings.add(encoding)
def one_or_two_strings(arg):
"""arg must be a single string or a tuple of two strings."""
if isinstance(arg, str):
return (arg, None)
if not isinstance(arg, tuple):
raise TypeError("one or two strings expected")
if len(arg)>2:
raise TypeError("too many arguments (only 2 allowed)")
if not isinstance(arg[0], str):
raise TypeError("1st argument must be a string")
if not isinstance(arg[1], str):
raise TypeError("2nd argument must be a string")
return arg
# ---------------------------------------------
# parse a string or a file
# ---------------------------------------------
def parseString(st):
"""parse a string."""
return parseAll(IndexedString(st), 0)
def parseFile(filename, encoding, no_stdin_warning):
"""parse a file."""
if filename is None:
if not no_stdin_warning:
sys.stderr.write("(reading from stdin)\n")
try:
st= sys.stdin.read()
except KeyboardInterrupt:
sys.exit(" interrupted\n")
else:
exc= None
try:
with open(filename, "rU") as f:
if encoding==INTERNAL_ENCODING:
st= f.read()
else:
st= (f.read()).decode(encoding).encode(INTERNAL_ENCODING)
except (IOError, UnicodeDecodeError) as e:
exc= e
if exc is not None:
# we cannot re-raise UnicodeDecodeError since it needs 5
# undocumented argiments and we just want an error message here
# that includes the filename:
raise IOError("File %s: %s" % (repr(filename), str(exc)))
return parseString(st)
# ---------------------------------------------
# Result text class
# ---------------------------------------------
class ResultText(object):
"""basically a list of strings with a current column property.
"""
def __init__(self):
"""initialize the object."""
self._list= []
self._column= -1
@staticmethod
def current_column(st):
r"""find current column if the string is printed.
Note: With a string ending with '\n' this returns 1.
Here are some examples: >>> current_column("")
-1
>>> ResultText.current_column("ab")