-
Notifications
You must be signed in to change notification settings - Fork 99
/
ttree_lex.py
2257 lines (1962 loc) · 88.8 KB
/
ttree_lex.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
# -*- coding: iso-8859-1 -*-
### -*- coding: utf-8 -*-
# Authors: Eric S. Raymond, 21 Dec 1998
# Andrew Jewett (jewett.aij at g mail)
# LICENSE: The PSF license:
# https://docs.python.org/3/license.html
# The PSF license is compatible with the GPL license. It is not a copyleft
# license. It is apparently similar to the BSD and MIT licenses.
#
# Contributions:
# Module and documentation by Eric S. Raymond, 21 Dec 1998
# Input stacking and error message cleanup added by ESR, March 2000
# push_source() and pop_source() made explicit by ESR, January 2001.
# Posix compliance, split(), string arguments, and
# iterator interface by Gustavo Niemeyer, April 2003.
# Unicode support hack ("wordterminators") and numerous other hideous
# ttree-specific hacks added by Andrew Jewett September 2011.
"""A lexical analyzer class for simple shell-like syntaxes.
This version has been modified slightly to work better with unicode.
It was forked from the version of shlex that ships with python 3.2.2.
A few minor features and functions have been added. -Andrew Jewett 2011 """
import os.path
import sys
from collections import deque
import re
import fnmatch
import string
#import gc
try:
from cStringIO import StringIO
except ImportError:
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
__all__ = ["TtreeShlex",
"split",
"LineLex",
"SplitQuotedString",
"ExtractVarName",
"GetVarName",
"EscCharStrToChar",
"SafelyEncodeString",
"RemoveOuterQuotes",
"MaxLenStr",
"VarNameToRegex",
"HasRE",
"HasWildcard",
"MatchesPattern",
"InputError",
"ErrorLeader",
"SrcLoc",
"OSrcLoc",
"TextBlock",
"VarRef",
"VarNPtr",
"VarBinding",
"SplitTemplate",
"SplitTemplateMulti",
"TableFromTemplate",
"ExtractCatName",
#"_TableFromTemplate",
#"_DeleteLineFromTemplate",
"DeleteLinesWithBadVars",
"TemplateLexer"]
class TtreeShlex(object):
""" A lexical analyzer class for simple shell-like syntaxes.
TtreeShlex is a backwards-compatible version of python's standard shlex
module. It has the additional member: "self.wordterminators", which
overrides the "self.wordchars" member. This enables better handling of
unicode characters by allowing a much larger variety of characters to
appear in words or tokens parsed by TtreeShlex.
"""
def __init__(self,
instream=None,
infile=None,
posix=False):
if isinstance(instream, str):
instream = StringIO(instream)
if instream is not None:
self.instream = instream
self.infile = infile
else:
self.instream = sys.stdin
self.infile = None
self.posix = posix
if posix:
self.eof = None
else:
self.eof = ''
self.commenters = '#'
self.wordchars = ('abcdfeghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_')
#if self.posix:
# self.wordchars += ('ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
# 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ')
if self.posix:
self.wordchars += ('��������������������������������'
'������������������������������')
self.wordterminators = set([])
self.prev_space_terminator = ''
self.whitespace = ' \t\r\f\n'
self.whitespace_split = False
self.quotes = '\'"'
self.escape = '\\'
self.escapedquotes = '"'
self.operators = '=' #binary numeric operators like +-*/ might be added
self.state = ' '
self.pushback = deque()
self.lineno = 1
self.debug = 0
self.token = ''
self.filestack = deque()
# self.source_triggers
# are tokens which allow the seamless insertion of other
# files into the file being read.
self.source_triggers = set(['source'])
self.source_triggers_x = set([])
# self.source_triggers_x is a subset of self.source_triggers.
# In this case file inclusion is exclusive.
# In other words, the file is only included
# if it has not been included already. It does this
# by checking if one of these tokens has been encountered.
self.source_files_restricted = set([])
self.include_path = []
if 'TTREE_PATH' in os.environ:
include_path_list = os.environ['TTREE_PATH'].split(':')
self.include_path += [d for d in include_path_list if len(d) > 0]
if self.debug:
sys.stderr.write('TtreeShlex: reading from %s, line %d'
% (self.instream, self.lineno))
self.end_encountered = False
@staticmethod
def _belongs_to(char, include_chars, exclude_chars):
if ((not exclude_chars) or (len(exclude_chars)==0)):
return char in include_chars
else:
return char not in exclude_chars
def push_raw_text(self, text):
"""Push a block of text onto the stack popped by the ReadLine() method.
(If multiple lines are present in the text, (which is determined by
self.line_terminators), then the text is split into multiple lines
and each one of them is pushed onto this stack individually.
The "self.lineno" counter is also adjusted, depending on the number
of newline characters in "line".
Do not strip off the newline, or other line terminators
at the end of the text block before using push_raw_text()!
"""
if self.debug >= 1:
sys.stderr.write("TtreeShlex: pushing token " + repr(text))
for c in reversed(text):
self.pushback.appendleft(c)
if c == '\n':
self.lineno -= 1
if len(text) > 0:
self.end_encountered = False
def push_token(self, text):
"Push a token onto the stack popped by the get_token method"
self.push_raw_text(text + self.prev_space_terminator)
def push_source(self, newstream, newfile=None):
"Push an input source onto the lexer's input source stack."
if isinstance(newstream, str):
newstream = StringIO(newstream)
self.filestack.appendleft((self.infile, self.instream, self.lineno))
self.infile = newfile
self.instream = newstream
self.lineno = 1
if self.debug:
if newfile is not None:
sys.stderr.write('TtreeShlex: pushing to file %s' % (self.infile,))
else:
sys.stderr.write('TtreeShlex: pushing to stream %s' % (self.instream,))
def pop_source(self):
"Pop the input source stack."
self.instream.close()
(self.infile, self.instream, self.lineno) = self.filestack.popleft()
if self.debug:
sys.stderr.write('TtreeShlex: popping to %s, line %d'
% (self.instream, self.lineno))
self.state = ' '
def get_token(self):
"Get a token from the input stream (or from stack if it's nonempty)"
#### #CHANGING: self.pushback is now a stack of characters, not tokens
#### if self.pushback:
#### tok = self.pushback.popleft()
#### if self.debug >= 1:
#### sys.stderr.write("TtreeShlex: popping token " + repr(tok))
#### return tok
#### No pushback. Get a token.
raw = self.read_token()
# Handle inclusions
if self.source_triggers is not None:
while raw in self.source_triggers:
fname = self.read_token()
spec = self.sourcehook(fname)
if spec:
(newfile, newstream) = spec
if ((raw not in self.source_triggers_x) or
(newfile not in self.source_files_restricted)):
self.push_source(newstream, newfile)
if raw in self.source_triggers_x:
self.source_files_restricted.add(newfile)
else:
if self.debug >= 1:
sys.stderr.write(
'\ndebug warning: duplicate attempt to import file:\n \"' + newfile + '\"\n')
raw = self.get_token()
# Maybe we got EOF instead?
while raw == self.eof:
if not self.filestack:
return self.eof
else:
self.pop_source()
raw = self.get_token()
# Neither inclusion nor EOF
if self.debug >= 1:
if raw != self.eof:
sys.stderr.write("TtreeShlex: token=" + repr(raw))
else:
sys.stderr.write("TtreeShlex: token=EOF")
if raw == self.eof:
self.end_encountered = True
return raw
def read_char(self):
if self.pushback:
nextchar = self.pushback.popleft()
assert((type(nextchar) is str) and (len(nextchar)==1))
else:
nextchar = self.instream.read(1)
return nextchar
def read_token(self):
self.prev_space_terminator = ''
quoted = False
escapedstate = ' '
while True:
#### self.pushback is now a stack of characters, not tokens
nextchar = self.read_char()
if nextchar == '\n':
self.lineno = self.lineno + 1
if self.debug >= 3:
sys.stderr.write("TtreeShlex: in state", repr(self.state),
"I see character:", repr(nextchar))
if self.state is None:
self.token = '' # past end of file
break
elif self.state == ' ':
if not nextchar:
self.state = None # end of file
break
elif nextchar in self.whitespace:
if self.debug >= 2:
sys.stderr.write("TtreeShlex: I see whitespace in whitespace state")
if self.token or (self.posix and quoted):
# Keep track of which whitespace
# character terminated the token.
self.prev_space_terminator = nextchar
break # emit current token
else:
continue
elif nextchar in self.commenters:
self.instream.readline()
self.lineno = self.lineno + 1
elif self.posix and nextchar in self.escape:
escapedstate = 'a'
self.state = nextchar
elif TtreeShlex._belongs_to(nextchar,
self.wordchars,
self.wordterminators):
self.token = nextchar
self.state = 'a'
elif nextchar in self.quotes:
if not self.posix:
self.token = nextchar
self.state = nextchar
elif self.whitespace_split:
self.token = nextchar
self.state = 'a'
else:
self.token = nextchar
if self.token or (self.posix and quoted):
break # emit current token
else:
continue
elif self.state in self.quotes:
quoted = True
if not nextchar: # end of file
if self.debug >= 2:
sys.stderr.write("TtreeShlex: I see EOF in quotes state")
# XXX what error should be raised here?
raise ValueError("Error at or before " + self.error_leader() + "\n"
" No closing quotation.")
if nextchar == self.state:
if not self.posix:
self.token = self.token + nextchar
self.state = ' '
break
else:
self.state = 'a'
elif self.posix and nextchar in self.escape and \
self.state in self.escapedquotes:
escapedstate = self.state
self.state = nextchar
else:
self.token = self.token + nextchar
elif self.state in self.escape:
if not nextchar: # end of file
if self.debug >= 2:
sys.stderr.write("TtreeShlex: I see EOF in escape state")
# What error should be raised here?
raise InputError('File terminated immediately following an escape character.')
# In posix shells, only the quote itself or the escape
# character may be escaped within quotes.
if escapedstate in self.quotes and \
nextchar != self.state and nextchar != escapedstate:
self.token = self.token + self.state
self.token = self.token + nextchar
self.state = escapedstate
elif self.state == 'a':
if not nextchar:
self.state = None # end of file
break
elif nextchar in self.whitespace:
if self.debug >= 2:
sys.stderr.write("TtreeShlex: I see whitespace in word state")
self.state = ' '
if self.token or (self.posix and quoted):
# Keep track of which whitespace
# character terminated the token.
self.prev_space_terminator = nextchar
break # emit current token
else:
continue
elif nextchar in self.commenters:
comment_contents = self.instream.readline()
self.lineno = self.lineno + 1
if self.posix:
self.state = ' '
if self.token or (self.posix and quoted):
# Keep track of which character(s) terminated
# the token (including whitespace and comments).
self.prev_space_terminator = nextchar + comment_contents
break # emit current token
else:
continue
elif self.posix and nextchar in self.quotes:
self.state = nextchar
elif self.posix and nextchar in self.escape:
escapedstate = 'a'
self.state = nextchar
elif (TtreeShlex._belongs_to(nextchar,
self.wordchars,
self.wordterminators)
or (nextchar in self.quotes)
or (self.whitespace_split)):
self.token = self.token + nextchar
else:
self.pushback.appendleft(nextchar)
if self.debug >= 2:
sys.stderr.write("TtreeShlex: I see punctuation in word state")
self.state = ' '
if self.token:
break # emit current token
else:
continue
result = self.token
self.token = ''
if self.posix and not quoted and result == '':
result = None
if self.debug > 1:
if result:
sys.stderr.write("TtreeShlex: raw token=" + repr(result))
else:
sys.stderr.write("TtreeShlex: raw token=EOF")
return result
def sourcehook(self, newfile):
"Hook called on a filename to be sourced."
newfile = RemoveOuterQuotes(newfile)
# This implements cpp-like semantics for relative-path inclusion.
newfile_full = newfile
if isinstance(self.infile, str) and not os.path.isabs(newfile):
newfile_full = os.path.join(os.path.dirname(self.infile), newfile)
try:
f = open(newfile_full, "r")
except IOError:
# If not found,
err = True
# ...then check to see if the file is in one of the
# directories in the self.include_path list.
for d in self.include_path:
newfile_full = os.path.join(d, newfile)
try:
f = open(newfile_full, "r")
err = False
break
except IOError:
err = True
if err:
raise InputError('Error at ' + self.error_leader() + '\n'
' unable to open file \"' + newfile + '\"\n'
' for reading.\n')
return (newfile, f)
def error_leader(self, infile=None, lineno=None):
"Emit a C-compiler-like, Emacs-friendly error-message leader."
if infile is None:
infile = self.infile
if lineno is None:
lineno = self.lineno
return "\"%s\", line %d: " % (infile, lineno)
def __iter__(self):
return self
def __next__(self):
token = self.get_token()
if token == self.eof:
raise StopIteration
return token
def __bool__(self):
return not self.end_encountered
# For compatibility with python 2.x, I must also define:
def __nonzero__(self):
return self.__bool__()
# The split() function was originally from shlex
# It is included for backwards compatibility.
def split(s, comments=False, posix=True):
lex = TtreeShlex(s, posix=posix)
lex.whitespace_split = True
if not comments:
lex.commenters = ''
return list(lex)
##################### NEW ADDITIONS (may be removed later) #################
#"""
# -- linelex.py --
# linelex.py defines the LineLex class, which inherits from, and further
# augments the capabilities of TtreeShlex by making it easier to parse
# individual lines one at a time. (The original shlex's "source" inclusion
# ability still works when reading entire lines, and lines are still counted.)
#
#"""
#import sys
class InputError(Exception):
""" A generic exception object containing a string for error reporting.
(Raising this exception implies that the caller has provided
a faulty input file or argument.)
"""
def __init__(self, err_msg):
self.err_msg = err_msg
def __str__(self):
return self.err_msg
def __repr__(self):
return str(self)
def ErrorLeader(infile, lineno):
return '\"' + infile + '\", line ' + str(lineno)
class SrcLoc(object):
""" SrcLoc is essentially nothing more than a 2-tuple containing the name
of a file (str) and a particular line number inside that file (an integer).
"""
__slots__ = ["infile", "lineno"]
def __init__(self, infile='', lineno=-1):
self.infile = infile
self.lineno = lineno
def SplitQuotedString(string,
quotes='\'\"',
delimiters=' \t\r\f\n',
escape='\\',
comment_char='#',
endquote=None):
tokens = []
token = ''
reading_token = True
escaped_state = False
quote_state = None
for c in string:
if (c in comment_char) and (not escaped_state) and (quote_state == None):
tokens.append(token)
return tokens
elif (c in delimiters) and (not escaped_state) and (quote_state == None):
if reading_token:
tokens.append(token)
token = ''
reading_token = False
elif c in escape:
if escaped_state:
token += c
reading_token = True
escaped_state = False
else:
escaped_state = True
# and leave c (the '\' character) out of token
elif (c == quote_state) and (not escaped_state) and (quote_state != None):
quote_state = None
if include_endquote:
token += c
elif (c in quotes) and (not escaped_state):
if quote_state == None:
if endquote != None:
quote_state = endquote
else:
quote_state = c
# Now deal with strings like
# a "b" "c d" efg"h i j"
# Assuming quotes='"', then we want this to be split into:
# ['a', 'b', 'c d', 'efg"h i j"']
# ...in other words, include the end quote if the token did
# not begin with a quote
include_endquote = False
if token != '':
# if this is not the first character in the token
include_endquote = True
token += c
reading_token = True
else:
if (c == 'n') and (escaped_state == True):
c = '\n'
elif (c == 't') and (escaped_state == True):
c = '\t'
elif (c == 'r') and (escaped_state == True):
c = '\r'
elif (c == 'f') and (escaped_state == True):
c = '\f'
token += c
reading_token = True
escaped_state = False
# Remove any empty strings from the front or back of the list,
# just in case SplitQuotedString() fails to remove them.
# (Possible bug in SplitQuotedString(), but too lazy to investigate.)
if (len(tokens) > 0) and (tokens[0] == ''):
del tokens[0]
if (len(tokens) > 0) and (tokens[-1] == ''):
del tokens[-1]
if (len(string) > 0) and (token != ''):
tokens.append(token)
return tokens
def GetVarName(lex):
""" Read a string like 'atom:A ' or '{/atom:A B/C/../D }ABC '
and return ('','atom:A',' ') or ('{','/atom:A B/C/../D ','}ABC')
These are 3-tuples containing the portion of the text containing
only the variable's name (assumed to be within the text),
...in addition to the text on either side of the variable name.
"""
escape = '\''
lparen = '{'
rparen = '}'
if hasattr(lex, 'escape'):
escape = lex.escape
if hasattr(lex, 'var_open_paren'):
lparen = lex.var_open_paren
if hasattr(lex, 'var_close_paren'):
rparen = lex.var_close_paren
nextchar = lex.read_char()
# Skip past the left-hand side paren '{'
paren_depth = 0
escaped = False
if nextchar == lparen:
paren_depth = 1
elif nextchar in lex.escape:
escaped = True
elif (hasattr(lex, 'wordterminators') and
(nextchar in lex.wordterminators)):
lex.push_raw_text(nextchar)
return ''
else:
lex.push_raw_text(nextchar)
# Now read the variable name:
var_name_l = []
while lex:
nextchar=lex.read_char()
if nextchar == '':
break
elif nextchar == '\n':
lex.lineno += 1
if paren_depth > 0:
var_name_l.append(nextchar)
else:
lex.push_raw_text(nextchar)
break
elif escaped:
var_name_l.append(nextchar)
escaped = False
elif nextchar in lex.escape:
escaped = True
elif nextchar == lparen:
paren_depth += 1
if (hasattr(lex, 'wordterminators') and
(nextchar in lex.wordterminators)):
lex.push_raw_text(nextchar)
break
else:
var_name_l.append(nextchar)
elif nextchar == rparen:
paren_depth -= 1
if paren_depth == 0:
break
elif (hasattr(lex, 'wordterminators') and
(nextchar in lex.wordterminators)):
lex.push_raw_text(nextchar)
break
else:
var_name_l.append(nextchar)
elif paren_depth > 0:
var_name_l.append(nextchar)
escaped = False
elif nextchar in lex.whitespace:
lex.push_raw_text(nextchar)
break
elif (hasattr(lex, 'wordterminators') and
(nextchar in lex.wordterminators) and
(paren_depth == 0)):
lex.push_raw_text(nextchar)
break
elif nextchar in lex.commenters:
lex.instream.readline()
lex.lineno += 1
break
else:
var_name_l.append(nextchar)
escaped = False
var_name = ''.join(var_name_l)
return var_name
def ExtractVarName(text,
commenters = '#',
whitespace = ' \t\r\f\n'):
""" Read a string like 'atom:A ' or '{/atom:A B/C/../D }ABC '
and return ('','atom:A',' ') or ('{','/atom:A B/C/../D ','}ABC')
These are 3-tuples containing the portion of the text containing
only the variable's name (assumed to be within the text),
...in addition to the text on either side of the variable name.
"""
ibegin = 0
left_paren = ''
if text[0] == '{':
ibegin = 1
left_paren = text[0] #(GetVarName() strips the leading '{' character)
# The best way to insure consistency with other code is to use
# lex.GetVarName() to figure out where the variable name ends.
lex = TtreeShlex(StringIO(text))
var_name = GetVarName(lex)
# Any text following the end of the variable name should be returned as well
text_after_list = []
if left_paren:
text_after_list.append('}') #(GetVarName() strips the trailing '}' char)
while lex:
c = lex.read_char()
if c == '':
break
text_after_list.append(c)
text_after = ''.join(text_after_list)
return (left_paren, var_name, text_after)
def EscCharStrToChar(s_in, escape='\\'):
"""
EscCharStrToChar() replaces any escape sequences
in a string with their 1-character equivalents.
"""
assert(len(escape) > 0)
out_lstr = []
escaped_state = False
for c in s_in:
if escaped_state:
if (c == 'n'):
out_lstr.append('\n')
elif (c == 't'):
out_lstr.append('\t')
elif (c == 'r'):
out_lstr.append('\r')
elif (c == 'f'):
out_lstr.append('\f')
elif (c == '\''):
out_lstr.append('\'')
elif (c == '\"'):
out_lstr.append('\"')
elif c in escape:
out_lstr.append(c)
else:
out_lstr.append(escape + c) # <- keep both characters
escaped_state = False
else:
if c in escape:
escaped_state = True
else:
out_lstr.append(c)
return ''.join(out_lstr)
def SafelyEncodeString(in_str,
quotes='\'\"',
delimiters=' \t\r\f\n',
escape='\\',
comment_char='#'):
"""
SafelyEncodeString(in_str) scans through the input string (in_str),
and returns a new string in which probletic characters
(like newlines, tabs, quotes, etc), are replaced by their two-character
backslashed equivalents (like '\n', '\t', '\'', '\"', etc).
The escape character is the backslash by default, but it too can be
overridden to create custom escape sequences
(but this does not effect the encoding for characters like '\n', '\t').
"""
assert(len(escape) > 0)
out_lstr = []
use_outer_quotes = False
for c in in_str:
if (c == '\n'):
c = '\\n'
elif (c == '\t'):
c = '\\t'
elif (c == '\r'):
c = '\\r'
elif (c == '\f'):
c = '\\f'
elif c in quotes:
c = escape[0] + c
elif c in escape:
c = c + c
elif c in delimiters:
use_outer_quotes = True
# hmm... that's all that comes to mind. Did I leave anything out?
out_lstr.append(c)
if use_outer_quotes:
out_lstr = ['\"'] + out_lstr + ['\"']
return ''.join(out_lstr)
def RemoveOuterQuotes(text, quotes='\"\''):
if ((len(text) >= 2) and (text[0] in quotes) and (text[-1] == text[0])):
return text[1:-1]
else:
return text
def MaxLenStr(s1, s2):
if len(s2) > len(s1):
return s2
else:
return s1
def VarNameToRegex(s):
"""
Returns the portion of a TTREE-style variable name (eg "@atom:re.C[1-5]")
that corresponds to a regular expression (eg "C[1-5]"). A variable name
is assumed to encode a regular expression if it begins with "re.", OR if
the a ':' character is followed by "re.".
If so, the text in s (excluding "re.") is assumed to be a regular expresion
and is returned to the caller.
If not, the empty string ('') is returned.
If the first or second character is a '{', and if the final character
is '}', they will be deleted. Consequently:
VarNameToRegex('@atom:C') returns ''
VarNameToRegex('@atom:re.C[1-5]') returns '@atom:C[1-5]'
VarNameToRegex('@{/atom:re.C[1-5]}') returns '@/atom:C[1-5]'
VarNameToRegex('@bond:AB') returns ''
VarNameToRegex('@bond:re.A*B') returns '@bond:a*b'
VarNameToRegex('bond:re.A*B') returns 'bond:a*b'
VarNameToRegex('{bond:re.A*B}') returns 'bond:a*b'
VarNameToRegex('@{bond:re.A*B}') returns '@bond:a*b'
"""
# First, deal with parenthesis {}
iparen_L = s.find('{')
iparen_R = s.rfind('}')
if (((iparen_L == 0) or (iparen_L == 1)) and (iparen_R == len(s)-1)):
optional_char = ''
if iparen_L == 1:
optional_char = s[0]
s = optional_char + s[iparen_L+1:iparen_R]
# Now check to see if the remaining string contains 're.' or ':re.'
icolon = s.find(':')
# If 're.' is not found immediately after the first ':' character
# or following a '/' character
# (or if it is not found at the beginning when no ':' is present)
# then there is no regular expression. In that case, return ''
ire = s.find('re.')
if ((ire == -1) or
(not ((ire > 0) and ((s[ire-1] == ':') or (s[ire-1] == '/'))))):
return ''
return s[0:ire] + s[ire+3:]
def HasRE(pat):
"""
Returns true if a string (pat) begins with 're.'
"""
return len(VarNameToRegex(pat)) > 0
def HasWildcard(pat):
"""
Returns true if a string (pat) contains a '*' or '?' character.
"""
return (pat.find('*') != -1) or (pat.find('?') != -1)
# def HasWildcard(pat):
# """
# Returns true if a string (pat) contains a non-backslash-protected
# * or ? character.
#
# """
# N=len(pat)
# i=0
# while i < N:
# i = pat.find('*', i, N)
# if i == -1:
# break
# elif (i==0) or (pat[i-1] != '\\'):
# return True
# i += 1
# i=0
# while i < N:
# i = pat.find('?', i, N)
# if i == -1:
# break
# elif (i==0) or (pat[i-1] != '\\'):
# return True
# i += 1
# return False
def MatchesPattern(s, pattern):
if type(pattern) is str:
# old code:
# if ((len(s) > 1) and (s[0] == '/') and (s[-1] == '/'):
# re_string = p[1:-1] # strip off the slashes '/' and '/'
# if not re.search(re_string, s):
# return False
# new code:
# uses precompiled regular expressions (See "pattern.search" below)
if HasWildcard(pattern):
if not fnmatch.fnmatchcase(s, pattern):
return False
elif s != pattern:
return False
else:
#assert(type(p) is _sre.SRE_Match)
# I assume pattern = re.compile(some_reg_expr)
if not pattern.search(s):
return False
return True
def MatchesAll(multi_string, pattern):
assert(len(multi_string) == len(pattern))
for i in range(0, len(pattern)):
if not MatchesPattern(multi_string[i], pattern[i]):
return False
return True
class LineLex(TtreeShlex):
""" This class extends the TtreeShlex module (a slightly modified
version of the python 3.2.2 version of shlex). LineLex has the
ability to read one line at a time (in addition to one token at a time).
(Many files and scripts must be parsed one line at a time instead of one
token at a time. In these cases, the whitespace position also matters.)
Arguably, this class might not be necessary.
I could get rid of this class completely. That would be nice. To do that
we would need to augment and generalize shlex's get_token() member function
to make it read lines, not just tokens. Of course, you can always
change the wordchars (or wordterminators). Even so, there are two other
difficulties using the current version of shlex.get_token() to read lines:
1) File inclusion happen whenever the beginning of a line/token matches one
of the "source_triggers" (not the whole line as required by get_token()).
2) Lines ending in a special character (by default the backslash character)
continue on to the next line.
This code seems to work on our test files, but I'm sure there are bugs.
Andrew 2012-3-25
"""
def __init__(self,
instream=None,
infile=None,
posix=False):
TtreeShlex.__init__(self, instream, infile, posix)
self.line_terminators = '\n'
self.line_extend_chars = '\\'
self.skip_comments_during_readline = True
def _StripComments(self, line):
if self.skip_comments_during_readline:
for i in range(0, len(line)):
if ((line[i] in self.commenters) and
((i == 0) or (line[i - 1] not in self.escape))):
return line[:i]
return line
def _ReadLine(self,
recur_level=0):
"""
This function retrieves a block of text, halting at a
terminal character. Escape sequences are respected.
The self.lineno (newline counter) is also maintained.
The main difference between Readline and get_token()
is the way they handle the "self.source_triggers" member.
Both Readline() and get_token() insert text from other files when they
encounter a string in "self.source_triggers" in the text they read.
However ReadLine() ONLY inserts text from other files if the token which
matches with self.source_triggers appears at the beginning of the line.
get_token() inserts text only if lex.source matches the entire token.
comment-to-self:
At some point, once I'm sure this code is working, I should replace
shlex.get_token() with the code from ReadLine() which is more general.
It would be nice to get rid of "class LineLex" entirely. ReadLine()
is the only new feature that LineLex which was lacking in shlex.
To do this I would need to add a couple optional arguments to
"get_token()", allowing it to mimic ReadLine(), such as:
"override_wordterms" argument (which we can pass a '\n'), and
"token_extender" argument (like '\' for extending lines)
"""
first_token = ''
line = ''
escaped_state = False
found_space = False
while True:
nextchar = self.read_char()
# sys.stderr.write('nextchar=\"'+nextchar+'\"\n')
while nextchar == '':
if not self.filestack:
return self._StripComments(line), '', first_token, found_space
else:
self.pop_source()
nextchar = self.read_char()
if nextchar == '\n':
self.lineno += 1