-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpreppy.py
More file actions
1704 lines (1561 loc) · 62.4 KB
/
Copy pathpreppy.py
File metadata and controls
1704 lines (1561 loc) · 62.4 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
#copyright ReportLab Inc. 2000-2022
#see license.txt for license details
"""preppy - a Python preprocessor.
This is the Python equivalent of ASP or JSP - a preprocessor which lets you
embed python expressions, loops and conditionals, and 'scriptlets' in any
kind of text file. It provides a very natural solution for generating
dynamic HTML pages, which is not connected to any particular web server
architecture.
You create a template file (conventionally ending in .prep) containing
python expressions, loops and conditionals, and scripts. These occur
between double curly braces:
Dear {{surname}},
You owe us {{amount}} {{if amount>1000}}which is pretty serious{{endif}}
The preppy.getModule function transforms a prep source into a python module which
is stored in a cache. The module contains functions which allow passing values into
the template and which return the interpolated result.
The command line options let you run modules with hand-input parameters -
useful for basic testing - and also to batch-compile or clean directories.
As with python scripts, it is a good idea to compile prep files on installation,
since unix applications may run as a different user and not have the needed
permission to store compiled modules.
"""
VERSION = '5.2.1'
__version__ = VERSION
USAGE = """
The command line interface lets you test, compile and clean up:
preppy modulename [arg1=value1, arg2=value2.....]
- shorthand for 'preppy run ...', see below.
preppy run modulename [arg1=value1, arg2=value2.....]
- runs the module, optionally with arguments. e.g.
preppy.py flintstone.prep name=fred sex=m
preppy.py compile [-f] [-v] [-p] module1[.prep] module2[.prep] module3 ...
- compiles explicit modules
preppy.py compile [-f] [-v] [-p] dirname1 dirname2 ...
- compiles all prep files in directory recursively
preppy.py clean dirname1 dirname2 ...19
- removes any py or pyc files created from past compilations
"""
STARTDELIMITER = "{{"
ENDDELIMITER = "}}"
QSTARTDELIMITER = "{${"
QENDDELIMITER = "}$}"
QUOTE = "$"
QUOTEQUOTE = "$$"
# SEQUENCE OF REPLACEMENTS FOR UNESCAPING A STRING.
UNESCAPES = ((QSTARTDELIMITER, STARTDELIMITER), (QENDDELIMITER, ENDDELIMITER), (QUOTEQUOTE, QUOTE))
import re, sys, os, struct, tokenize, token, ast, traceback, time, marshal, pickle, inspect, textwrap
from collections import OrderedDict
from hashlib import md5
isPy3 = sys.version_info.major == 3
isPy33 = isPy3 and sys.version_info.minor>=3
isPy34 = isPy3 and sys.version_info.minor>=4
isPy37 = isPy3 and sys.version_info.minor>=7
isPy38 = isPy3 and sys.version_info.minor>=8
isPy39 = isPy3 and sys.version_info.minor>=9
isPy310 = isPy3 and sys.version_info.minor>=10
isPy311 = isPy3 and sys.version_info.minor>=11
isPy312 = isPy3 and sys.version_info.minor>=12
isPy313 = isPy3 and sys.version_info.minor>=13
isPy315 = isPy3 and sys.version_info.minor>=15
ast_Str = ast.Constant if isPy38 else ast.Str
_usePyCache = isPy3 and False #change if you don't have legacy ie python 2.7 usage
from xml.sax.saxutils import escape as xmlEscape
from collections import namedtuple
Token = namedtuple('Token','kind start end')
_verbose = int(os.environ.get('RL_verbose','0'))
if isPy313:
def astSimpleCall(func=None,args=None):
return ast.Call(func=func,args=args)
else:
def astSimpleCall(func=None,args=None):
return ast.Call(func=func,args=args,keywords=[],starargs=None,kwargs=None)
from keyword import iskeyword
if isPy3:
xrange = range
from io import BytesIO, StringIO
def __preppy__vlhs__(s):
try:
s = s.strip()
return s.isidentifier() and not iskeyword(s)
except:
return False
class SafeString(bytes):
'''either a SafeString or a SafeUnicode depending on argument type'''
def __new__(cls,v):
return str.__new__(SafeUnicode,v) if isinstance(v,str) else bytes.__new__(cls,v)
class SafeUnicode(str):
'''either a SafeString or a SafeUnicode depending on argument type'''
def __new__(cls,v):
return bytes.__new__(SafeString,v) if isinstance(v,bytes) else str.__new__(cls,v)
_ucvn = '__str__' #unicode conversion
_bcvn = '__bytes__' #bytes conversion
bytesT = bytes
unicodeT = str
strTypes = (str,bytes)
import builtins
rl_exec = getattr(builtins,'exec')
del builtins
else:
from StringIO import StringIO
BytesIO = StringIO
try:
isidentifier = tokenize.Name
except AttributeError:
isidentifier = '[a-zA-Z_][a-zA-Z0-9_]*'
isidentifier = re.compile('^%s$' % isidentifier).match
def __preppy__vlhs__(s):
try:
s = s.strip()
return s!='None' and isidentifier(s) and not iskeyword(s)
except:
return False
class SafeString(str):
'''either a SafeString or a SafeUnicode depending on argument type'''
def __new__(cls,v):
return unicode.__new__(SafeUnicode,v) if isinstance(v,unicode) else str.__new__(cls,v)
class SafeUnicode(unicode):
'''either a SafeString or a SafeUnicode depending on argument type'''
def __new__(cls,v):
return str.__new__(SafeString,v) if isinstance(v,str) else unicode.__new__(cls,v)
_ucvn = '__unicode__'
_bcvn = '__str__'
bytesT = str
unicodeT = unicode
strTypes = basestring
def rl_exec(obj, G=None, L=None):
if G is None:
frame = sys._getframe(1)
G = frame.f_globals
if L is None:
L = frame.f_locals
del frame
elif L is None:
L = G
exec("""exec obj in G, L""")
class AstTry:
_attributes = ('lineno','col_offset')
_fields = ('body','handlers','orelse','finalbody')
def __init__(self,**kwds):
self.lineno = 1
self.col_offset = 0
self.__dict__.update(kwds)
def convertTry(self):
if not self.handlers:
return ast.TryFinally(lineno=self.lineno,col_offset=self.col_offset,body=self.body,finalbody=self.finalbody)
elif not self.finalbody:
return ast.TryExcept(lineno=self.lineno,col_offset=self.col_offset,body=self.body,handlers=self.handlers,orelse=self.orelse)
else:
return ast.TryFinally(lineno=self.lineno,col_offset=self.col_offset,
body=[ast.TryExcept(lineno=self.lineno,col_offset=self.col_offset,body=self.body,handlers=self.handlers,orelse=self.orelse)],
finalbody=self.finalbody)
ast.Try = AstTry
defaultLConv = ['unicode','str']
def asUtf8(s):
return s if isinstance(s,bytesT) else s.encode('utf8')
def asUnicode(s):
return s if isinstance(s,unicodeT) else s.decode('utf8')
def getMd5(s):
return md5(asUtf8(s)+asUtf8(VERSION),usedforsecurity=False).hexdigest()
class AbsLineNo(int):
pass
def uStdConv(s):
if not isinstance(s,strTypes):
if s is None: return u'' #we usually don't want output
cnv = getattr(s,_ucvn,None)
if not cnv:
cnv = getattr(s,_bcvn,None)
s = cnv() if cnv else str(s)
if not isinstance(s,unicodeT):
s = s.decode('utf8')
return s
def bStdConv(s):
return uStdConv(s).encode('utf8')
def __get_conv__(qf,lqf,b):
'''return the quoteFunc, lquoteFunc given values for same and
whether the original was bytes'''
if qf and not lqf:
lqf = asUtf8 if isinstance(qf(''),bytesT) else asUnicode
elif lqf and not qf:
qf = bStdConv if isinstance(lqf(''),bytesT) else uStdConv
elif not qf and not lqf:
if b:
qf = bStdConv
lqf = bytesT
else:
qf = uStdConv
lqf = unicodeT
return qf, lqf
class __wsscontroller__:
class ignore(str):
pass
wsc = u''.join((
#u'\u000A', # LINE FEED
u'\u0009', # HORIZONTAL TABULATION
u'\u000B', # VERTICAL TABULATION
u'\u000C', # FORM FEED
u'\u000D', # CARRIAGE RETURN
u'\u001C', # FILE SEPARATOR
u'\u001D', # GROUP SEPARATOR
u'\u001E', # RECORD SEPARATOR
u'\u001F', # UNIT SEPARATOR
u'\u0020', # SPACE
u'\u0085', # NEXT LINE
u'\u00A0', # NO-BREAK SPACE
u'\u1680', # OGHAM SPACE MARK
u'\u2000', # EN QUAD
u'\u2001', # EM QUAD
u'\u2002', # EN SPACE
u'\u2003', # EM SPACE
u'\u2004', # THREE-PER-EM SPACE
u'\u2005', # FOUR-PER-EM SPACE
u'\u2006', # SIX-PER-EM SPACE
u'\u2007', # FIGURE SPACE
u'\u2008', # PUNCTUATION SPACE
u'\u2009', # THIN SPACE
u'\u200A', # HAIR SPACE
u'\u200B', # ZERO WIDTH SPACE
u'\u2028', # LINE SEPARATOR
u'\u2029', # PARAGRAPH SEPARATOR
u'\u202F', # NARROW NO-BREAK SPACE
u'\u205F', # MEDIUM MATHEMATICAL SPACE
u'\u3000', # IDEOGRAPHIC SPACE
))
pats = {
1: re.compile(u'^[%s]*' % wsc),
2: re.compile(u'^[%s]*' % (wsc+u'\u000A')),
}
def __init__(self):
self.ws = 0
def dnl(self):
self.ws = 1 #delete following white space to next line
return self.ignore('')
def dws(self):
self.ws = 2 #delete following white space
return self.ignore('')
def x(self,s):
if not isinstance(s,self.ignore):
self.ws = 0
return s
def c(self,s):
ws = self.ws
self.ws = 0
if ws:
b = isinstance(s,bytesT)
if b: s = asUnicode(s)
s = self.pats[ws].sub('',s)
if ws==1 and s[0]==u'\n': s = s[1:]
if b: s = asUtf8(s)
return s
#Andy's standard quote for django
_safeBase = SafeString, SafeUnicode
def uStdQuote(s):
if not isinstance(s,strTypes):
if s is None: return u'' #we usually don't want output
cnv = getattr(s,_ucvn,None)
if not cnv:
cnv = getattr(s,_bcvn,None)
s = cnv() if cnv else unicodeT(s)
if isinstance(s,_safeBase):
if isinstance(s,SafeString):
s = s.decode('utf8')
return s
elif not isinstance(s,unicodeT):
s = s.decode('utf8')
return xmlEscape(s)
def bStdQuote(s):
return uStdQuote(s).encode('utf8')
stdQuote = bStdQuote
def pnl(s):
'''print without a lineend'''
if not isPy3 and isinstance(s,unicodeT):
s = s.encode(sys.stdout.encoding,'replace')
sys.stdout.write(s)
def pel(s):
'''print with a line ending'''
pnl(s)
pnl('\n')
def unescape(s, unescapes=UNESCAPES):
for (old, new) in unescapes:
s = s.replace(old, new)
return s
teststring = """
this test script should produce a runnable program
{{script}}
class X:
pass
x = X()
x.a = "THE A VALUE OF X"
yislonger = "y is longer!"
import math
a = dictionary = {"key": "value", "key2": "value2", "10%": "TEN PERCENT"}
loop = "LOOP"
{{endscript}}
this line has a percent in it 10%
here is the a value in x: {{x.a}}
just a norml value here: {{yislonger}} string {{a["10%"]}}
the sine of 12.3 is {{math.sin(12.3)}}
{{script}} a=0 {{endscript}}
these parens should be empty
({{if a:}}
conditional text{{endif}})
{{script}} a=1
{{endscript}}
these parens should be full
({{if a:}}
conditional text{{endif}})
stuff between endif and while
{{while a==1:}} infinite {{loop}} forever!
{{script}} a=0 {{endscript}}
{{for (a,b) in dictionary.items():}}
the key in the dictionary is {{a}} and the value is {{b}}. And below is a script
{{script}}
# THIS IS A SCRIPT
x = 2
y = 3
# END OF THE SCRIPT
{{endscript}}
stuff after the script
{{endfor}}
stuff after the for stmt
{{endwhile}}
stuff after the while stmt
{{script}}
# test the free variables syntax error problem is gone
alpha = 3
def myfunction1(alpha=alpha):
try:
return free_variable # this would cause an error in an older version of preppy with python 2.2
except:
pass
try:
return alpha
except:
return "oops"
beta = myfunction1()
{{endscript}}
alpha = {{alpha}} and beta = {{beta}}
{${this is invalid but it's escaped, so no problem!}$}
end of text
{{script}}
# just a comment
{{endscript}}
stop here
"""
"""
# test code for quotestring
(qs, ds, c) = PreProcessor().quoteString(teststring, cursor=0)
print "---------quoted to ", c, `teststring[c:c+20]`
print qs
print "---------dict string"
print ds
"""
def dedent(text):
"""get rid of redundant indentation in text this dedenter IS NOT smart about converting tabs to spaces!!!"""
lines = text.split("\n")
# omit empty lines
lempty = 0
while lines:
line0 = lines[0].strip()
if line0 and line0[0]!='#': break
del lines[0]
lempty += 1
if not lines: return (0,"") # completely white
line0 = lines[0]
findfirstword = line0.find(line0.strip().split()[0])
if findfirstword<0: raise ValueError('internal dedenting error')
indent = line0[:findfirstword]
linesout = []
for l in lines:
lines0 = l.strip()
if not lines0 or lines0[0]=='#':
linesout.append("")
continue
lindent = l[:findfirstword]
if lindent!=indent:
raise ValueError("inconsistent indent expected %s got %s in %s" % (repr(indent), repr(lindent), l))
linesout.append(l[findfirstword:])
return len(indent),'\n'.join(lempty*['']+linesout)
_line_d = re.compile('line\\s+\\d+',re.M)
_pat = re.compile('{{\\s*|}}',re.M)
_s = (
r'^(?P<start>while|if|elif|for|continue|break|try|except|raise|with|import|from|assert|return)(?P<startend>\s+|$)'
r'|(?P<tdef>def\s*[_a-zA-Z])(?P<tdefend>\w*\s*\(.*\)\s*$)'
r'|(?P<def>def\s*)(?P<defend>\(|$)'
r'|(?P<end>else|script|eval|endwhile|endif|endscript|endeval|endfor|finally|endtry|endwith|enddef)(?:\s*$|(?P<endend>.+$))'
)
if isPy310:
_s = _s.replace(r'return)',r'return|match|case)')
_s = _s.replace(r'enddef)',r'enddef|endmatch)')
_s = re.compile(_s,re.DOTALL|re.M)
class PreppyParser:
def __init__(self,source,filename='[unknown]',sourcechecksum=None):
self.__mangle = '_%s__'%self.__class__.__name__
self._defSeen = 0
self.source = source
self.filename = filename
self.sourcechecksum = sourcechecksum
self.__inFor = self.__inWhile = self.__inMatch = self.__inCase = 0
self.__inTdef = []
self._isBytes = isinstance(source,bytesT)
def compile(self, display=0):
ast = self.__get_ast()
self.codeobject = compile(ast,self.filename,'exec')
def __lexerror(self, msg, pos):
text = self.source
pos0 = text.rfind('\n',0,pos)+1
pos1 = text.find('\n',pos)
if pos1<0: pos1 = len(text)
lnum = text.count('\n',0,pos)+1
msg = _line_d.sub('line %d' % lnum,msg)
raise SyntaxError('%s\n%s\n%s (near line %d of %s)' %(text[pos0:pos1],(' '*(pos-pos0)),msg, lnum, self.filename))
def __tokenize(self):
text = self.source
self._tokens = tokens = []
a = tokens.append
state = 0
ix = 0
for i in _pat.finditer(text):
i0 = i.start()
i1 = i.end()
if i.group()!='}}':
if state:
self.__lexerror('Unexpected {{', i0)
else:
state = 1
if i0!=ix: a(Token('const',ix,i0))
ix = i1
elif state:
state = 0
#here's where a preppy token is finalized
m = _s.match(text[ix:i0])
if m:
t = m.group('start')
if t:
if not m.group('startend'):
if t not in ('continue','break','try','except','return','raise'):
self.__lexerror('Bad %s' % t, i0)
else:
t = m.group('end')
if t:
ee = m.group('endend')
if ee and t!='else' and ee.strip()!=':': self.__lexerror('Bad %s' % t, i0)
else:
t = m.group('def')
if t:
if not m.group('defend'): self.__lexerror('Bad %s' % t, i0)
if self._defSeen:
if self._defSeen>0:
self.__lexerror('Only one def may be used',i0)
else:
self.__lexerror('def must come first',i0)
else:
self._defSeen = 1
else:
t = m.group('tdef')
if not m.group('tdefend'): self.__lexerror('Bad %s' % t, i0)
t = 'tdef'
else:
t = 'expr' #expression
if not self._defSeen: self._defSeen = -1
if i0!=ix: a(Token(t,ix,i0))
ix = i1
else:
lineno = 0
if state: self.__lexerror('Unterminated preppy token', ix)
textLen = len(text)
if ix!=textLen:
a(Token('const',ix,textLen))
a(Token('eof',textLen,textLen))
self._tokenX = 0
return tokens
def __tokenText(self, colonRemove=False, strip=True, forceColonPass=False):
t = self._tokens[self._tokenX]
text = self.source[t.start:t.end]
if strip: text = text.strip()
if colonRemove or forceColonPass:
if text.endswith(':'): text = text[:-1]
if forceColonPass==3:
text = 'match None:\n\t%s:\n\t\tpass' % text
elif forceColonPass==2:
text += ':\n\tcase _:\n\t\tpass\n'
elif forceColonPass:
text += ':\tpass\n'
return unescape(text)
def __tokenPop(self):
t = self._tokens[self._tokenX]
self._tokenX += 1
return t
def __colOffset(self,t):
'''obtain the column offset corresponding to a specific token'''
start = t.start if isinstance(t,Token) else t
return start-max(self.source.rfind('\n',0,start)+1,0)
def __lineno(self,t):
start = t.start if isinstance(t,Token) else t
return self.source.count('\n',0,start) + 1
def __rparse(self,text):
'''parse a raw fragment of code'''
try:
tf = ast.parse(text,filename=self.filename,mode='exec').body
except SyntaxError:
s = text.strip()
b = isinstance(s,bytesT)
if s not in (u'.dnl', u'.dws'): raise
if b: s = asUnicode(s)
s = u'__wss__%s()' % s
if b: s = asUtf8(s)
tf = ast.parse(s,filename=self.filename,mode='exec').body
return tf
def __iparse(self,text):
'''parse a start fragment of code'''
return self.__rparse(text)[0]
def __preppy(self,
funcs=('const expr while if for script eval def continue break try raise with import from assert tdef return'
+(' match case' if isPy310 else '')).split(),
followers=['eof'],pop=True,fixEmpty=False):
C = []
a = C.append
mangle = self.__mangle
tokens = self._tokens
while 1:
t = tokens[self._tokenX].kind
if t in followers: break
p = t in funcs and getattr(self,mangle+t) or self.__serror
r = p()
if isinstance(r,list): C += r
elif r is not None: a(r)
if not C and fixEmpty:
r = ast.Pass(lineno=1,col_offset=0)
self.__renumber(r,self._tokens[self._tokenX])
C = [r]
if pop:
self.__tokenPop()
return C
if isPy38:
def _transfer_end_attributes(self,nodes,i=-1):
t = self._tokens[i if isinstance(i, AbsLineNo) else (self._tokenX+i)]
end_lineno = self.__lineno(t.end)
end_col_offset = self.__colOffset(t.end)
for n in nodes:
if hasattr(n,'end_lineno'):
n.end_lineno = end_lineno
n.end_col_offset = end_col_offset
def __def(self):
try:
n = self.__iparse('def get'+(self.__tokenText(forceColonPass=1).strip()[3:]))
except:
self.__error()
t = self.__tokenPop()
self._fnc_defn = t,n
return None
def __tdef(self):
self.__inTdef.append((self.__inWhile,self.__inFor))
self.__inWhile = self.__inFor = 0
try:
n = self.__iparse(self.__tokenText(forceColonPass=1).strip())
except:
self.__error()
t = self.__tokenPop()
self.__renumber(n,t)
n.body = self.__preppy(followers=['enddef'],fixEmpty=True)
r = ast.Return(value=ast_Str(''))
self.__renumber(r,self._tokens[self._tokenX-1])
n.body.append(r)
if isPy38: self._transfer_end_attributes([n])
self.__inWhile, self.__inFor = self.__inTdef.pop()
return n
def __return(self,stmt='return'):
if not self.__inTdef:
self.__serror(msg='%s statement outside while or for loop' % stmt)
text = self.__tokenText()
try:
n = self.__rparse(text)
except:
self.__error()
t = self.__tokenPop()
self.__renumber(n,t)
if isPy38: self._transfer_end_attributes([n])
return n
def __break(self,stmt='break'):
text = self.__tokenText()
if text!=stmt:
self.__serror(msg='invalid %s statement' % stmt)
elif not self.__inWhile and not self.__inFor:
self.__serror(msg='%s statement outside while or for loop' % stmt)
t = self.__tokenPop()
n = getattr(ast,stmt.capitalize())(lineno=1,col_offset=0)
self.__renumber(n,t)
return n
def __continue(self):
return self.__break(stmt='continue')
def __raise(self):
text = self.__tokenText()
try:
n = self.__rparse(text)
except:
self.__error()
t = self.__tokenPop()
self.__renumber(n,t)
return n
def __renumber(self,node,t,dcoffs=0):
if isinstance(node,list):
for f in node:
self.__renumber(f,t,dcoffs=dcoffs)
return
if isinstance(t,Token):
lineno_offset = self.__lineno(t)-1
col_offset = self.__colOffset(t)
if isPy38:
end_lineno_offset = self.__lineno(t.end)-1
end_col_offset = self.__colOffset(t.end)
elif isPy38:
lineno_offset, col_offset, end_lineno_offset, end_col_offset = t
else:
lineno_offset, col_offset = t
if 'col_offset' in node._attributes:
if getattr(node,'lineno',1)==1:
node.col_offset = getattr(node,'col_offset',0)+col_offset+dcoffs
elif not hasattr(node,'col_offset'):
node.col_offset = dcoffs
else:
node.col_offset += dcoffs
if 'lineno' in node._attributes:
node.lineno = int(lineno_offset) if isinstance(lineno_offset,AbsLineNo) else getattr(node,'lineno',1)+lineno_offset
if isPy38:
if 'end_lineno' in node._attributes:
e = getattr(node,'end_lineno',None)
if e is None: e = 1
node.end_lineno = int(end_lineno_offset) if isinstance(end_lineno_offset,AbsLineNo) else e+end_lineno_offset
if 'end_col_offset' in node._attributes:
e = getattr(node,'end_col_offset',None) or 0
if not isinstance(getattr(node,'end_lineno',None),AbsLineNo):
e += end_col_offset
node.end_col_offset = e + dcoffs
t = lineno_offset, col_offset, end_lineno_offset, end_col_offset
else:
t = lineno_offset,col_offset
for f in ast.iter_child_nodes(node):
self.__renumber(f,t,dcoffs=dcoffs)
def __while(self):
self.__inWhile += 1
try:
t = self._tokenX
n = self.__iparse(self.__tokenText(forceColonPass=1))
except:
self.__error()
self.__tokenPop()
tokens = self._tokens
self.__renumber(n,tokens[t])
n.body = self.__preppy(followers=['endwhile','else'],fixEmpty=True)
if tokens[self._tokenX-1].kind=='else':
n.orelse = self.__preppy(followers=['endwhile'])
if isPy38: self._transfer_end_attributes([n])
self.__inWhile -= 1
return n
if isPy310:
def __match(self):
self.__inMatch += 1
try:
t = self._tokenX
n = self.__iparse(self.__tokenText(forceColonPass=2))
except:
self.__error()
tokens = self._tokens
self.__tokenPop()
while True:
_s = tokens[self._tokenX]
if not _s.kind=='const': break
_ss = self.source[_s.start:_s.end].strip()
if _ss:
self.__serror('unexpected text, %r, in start of match' % _ss)
self.__tokenPop()
self.__renumber(n,tokens[t])
n.cases = self.__preppy(followers=['endmatch'],fixEmpty=True)
self._transfer_end_attributes([n])
self.__inMatch -= 1
return n
def __case(self):
self.__inCase += 1
aR = [].append
tokens = self._tokens
while True:
x = self._tokenX
t = tokens[x]
if t.kind!='case': break
try:
n = self.__iparse(self.__tokenText(forceColonPass=3))
except:
self.__error()
self.__tokenPop()
self.__renumber(n,t)
n.cases[0].body = self.__preppy(followers=['case','endmatch'],fixEmpty=True, pop=False)
self._transfer_end_attributes([n])
aR(n.cases[0])
self.__inCase -= 1
return aR.__self__
def __for(self):
self.__inFor += 1
try:
n = self.__iparse(self.__tokenText(forceColonPass=1))
except:
self.__error()
t = self.__tokenPop()
self.__renumber(n,t)
n.body = self.__preppy(followers=['endfor','else'],fixEmpty=True)
if self._tokens[self._tokenX-1].kind=='else':
n.orelse = self.__preppy(followers=['endfor'])
if isPy38: self._transfer_end_attributes([n])
self.__inFor -= 1
return n
def __try(self):
text = self.__tokenText(colonRemove=1)
if text!='try':
self.__serror(msg='invalid try statement')
t = self.__tokenPop()
n = ast.Try(lineno=1,col_offset=0,body=[],handlers=[],orelse=[],finalbody=[])
self.__renumber(n,t)
n.body = self.__preppy(followers=['except','finally'],pop=False,fixEmpty=True)
while 1:
text = self.__tokenText(colonRemove=1)
t = self.__tokenPop()
if text.startswith('endtry'):
if text != 'endtry':
self.__error('invalid endtry statement')
return n if isPy3 else n.convertTry()
elif text.startswith('finally'):
if text != 'finally':
self.__error('invalid finally statement')
n.finalbody = self.__preppy(followers=['endtry'])
return n if isPy3 else n.convertTry()
elif text.startswith('else'):
if text != 'else':
self.__error('invalid else statement')
n.orelse = self.__preppy(followers=['finally','endtry'],pop=False)
elif text.startswith('except'):
exh = self.__iparse('try:\n\tpass\n%s:\n\tpass\n' % text).handlers[0]
exh.lineno = 1
exh.col_offset = 0
self.__renumber(exh,t)
F = ['finally','else','endtry'] if text=='except' else ['except','finally','endtry','else']
exh.body = self.__preppy(followers=F,pop=False,fixEmpty=True)
n.handlers.append(exh)
else:
self.__serr('invalid syntax in try statement')
def __with(self):
try:
n = self.__iparse(self.__tokenText(forceColonPass=1))
except:
self.__error()
t = self.__tokenPop()
self.__renumber(n,t)
n.body = self.__preppy(followers=['endwith'],fixEmpty=True)
if isPy38: self._transfer_end_attributes([n])
return n
def __import(self,stmt='import'):
text = self.__tokenText()
try:
n = self.__iparse(text)
except:
self.__error()
t = self.__tokenPop()
self.__renumber(n,t)
if isPy38: self._transfer_end_attributes([n])
return n
def __from(self):
return self.__import(stmt='from')
def __assert(self):
return self.__import(stmt='assert')
def __script(self,mode='script'):
end = 'end'+mode
self.__tokenPop()
if self._tokens[self._tokenX].kind==end:
self.__tokenPop()
return []
dcoffs, text = dedent(self.__tokenText(strip=0,colonRemove=False))
scriptMode = 'script'==mode
if text:
try:
n = self.__rparse(text)
except:
self.__error()
t = self.__tokenPop()
try:
assert self._tokens[self._tokenX].kind==end
self.__tokenPop()
except:
self.__error(end+' expected')
if not text: return []
if mode=='eval':
if not isinstance(n[-1],ast.Expr):
self.__error('{{eval}} should end with an expression')
n[-1] = ast.Expr(value=astSimpleCall(func=ast.Name(id='__swrite__',ctx=ast.Load()),args=[n[-1].value]))
if len(n)==1: n = n[0]
self.__renumber(n,t,dcoffs=dcoffs)
return n
def __eval(self):
return self.__script(mode='eval')
def __if(self):
tokens = self._tokens
k = 'elif'
I = None
while k=='elif':
try:
t = self._tokenX
text = self.__tokenText(forceColonPass=1)
if text.startswith('elif'): text = 'if '+text[4:]
n = self.__iparse(text)
except:
self.__error()
self.__tokenPop()
self.__renumber(n,tokens[t])
n.body = self.__preppy(followers=['endif','elif','else'],fixEmpty=True)
if I:
p.orelse = [n]
else:
I = n
p = n
k = tokens[self._tokenX-1].kind #we consumed the terminal in __preppy
if k=='elif': self._tokenX -= 1
if k=='else':
p.orelse = self.__preppy(followers=['endif'])
if isPy38: self._transfer_end_attributes([I])
return I
def __const(self):
try:
n = ast.Expr(value=astSimpleCall(func=ast.Name(id='__write__',ctx=ast.Load()),args=[ast_Str(self.__tokenText(strip=0))]))
except:
self.__error('bad constant')
t = self.__tokenPop()
self.__renumber(n,t)
return n
def __expr(self):
t = self.__tokenText()
n = self.__rparse(t)
if len(n)!=1:
self.__error('{{expr}} needs only one expression, got %d' % len(n))
elif not isinstance(n[0],ast.Expr):
self.__error('{{expr}} should be an expression, got %s' % n[0].__class__.__name__)
try:
n = ast.Expr(value=astSimpleCall(func=ast.Name(id='__swrite__',ctx=ast.Load()),args=[n[0].value]))
except:
self.__error('bad expression')
t = self.__tokenPop()
self.__renumber(n,t)
if isPy38: self._transfer_end_attributes([n])
return n
def __error(self,msg='invalid syntax'):
pos = self._tokens[self._tokenX].start
f = StringIO()
traceback.print_exc(file=f)
f = f.getvalue()
m = 'File "<string>", line '
i = f.rfind('File "<string>", line ')
if i<0:
t, v = map(str,sys.exc_info()[:2])
self.__lexerror('%s %s(%s)' % (msg, t, v),pos)
else:
i += len(m)
f = f[i:].split('\n')
n = int(f[0].strip())+self.source[:pos].count('\n')
raise SyntaxError(' File %s, line %d\n%s' % (self.filename,n,'\n'.join(f[1:])))
def __serror(self,msg='invalid syntax'):
self.__lexerror(msg,self._tokens[self._tokenX].start)
def __parse(self,text=None):
if text: self.source = text
self.__tokenize()
return self.__preppy()
@staticmethod
def dump(node,annotate_fields=False,include_attributes=True):
return ('[%s]' % ', '.join(PreppyParser.dump(x,annotate_fields=annotate_fields,include_attributes=include_attributes) for x in node)
if isinstance(node,list)
else ast.dump(node,annotate_fields=annotate_fields, include_attributes=include_attributes))
def __get_pre_preamble(self):
return ('from preppy import include, __preppy__vlhs__, __get_conv__, __wsscontroller__\n'
if self._defSeen==1
else 'from preppy import include, rl_exec as __rl_exec__, __preppy__vlhs__, __get_conv__, __wsscontroller__\n')
def __get_ast(self):
preppyNodes = self.__parse()
flno = (AbsLineNo(1),0)
if isPy38: flno = flno+flno
llno = (AbsLineNo(self.__lineno(self._tokens[-1].end)),0) #last line number information
if isPy38: llno = llno + llno
if self._defSeen==1:
t, F = self._fnc_defn
args = F.args
if args.kwarg:
kwargName = args.kwarg.arg if isPy34 else args.kwarg
CKWA = []
else:
if isPy3:
argNames = [a.arg for a in args.args] + [a.arg for a in args.kwonlyargs]
if args.vararg: argNames += [args.vararg.arg if isPy34 else args.vararg]
else:
argNames = [a.id for a in args.args]
if args.vararg: argNames += [args.vararg]
#choose a kwargName not in existing names
kwargName = '__kwds__'
while kwargName in argNames:
kwargName = kwargname.replace('s_','ss_')
if isPy34:
args.kwarg = ast.arg(kwargName,None)
args.kwarg.lineno = F.lineno
args.kwarg.col_offset = F.col_offset
else:
args.kwarg = kwargName
CKWA = ["if %s: raise TypeError('get: unexpected keyword arguments %%r' %% %s)" % (kwargName,kwargName)]
leadNodes=self.__rparse('\n'.join([
"__lquoteFunc__=%s.setdefault('__lquoteFunc__',None)" % kwargName,
"%s.pop('__lquoteFunc__')" % kwargName,
"__quoteFunc__=%s.setdefault('__quoteFunc__',None)" % kwargName,
"%s.pop('__quoteFunc__')" % kwargName,
'__qFunc__,__lqFunc__=__get_conv__(__quoteFunc__,__lquoteFunc__,%s)' % self._isBytes
] + CKWA + [