forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcartesian_config.py
executable file
·1969 lines (1548 loc) · 63.7 KB
/
cartesian_config.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/python
# pylint: disable=W1401
"""
Cartesian configuration format file parser.
Filter syntax:
, means OR
.. means AND
. means IMMEDIATELY-FOLLOWED-BY
(xx=yy) where xx=VARIANTS_name and yy=VARIANT
Example:
qcow2..(guest_os=Fedora).14, RHEL.6..raw..boot, smp2..qcow2..migrate..ide
means match all dicts whose names have:
(qcow2 AND ((guest_os=Fedora) IMMEDIATELY-FOLLOWED-BY 14)) OR
((RHEL IMMEDIATELY-FOLLOWED-BY 6) AND raw AND boot) OR
(smp2 AND qcow2 AND migrate AND ide)
Note:
'qcow2..Fedora.14' is equivalent to 'Fedora.14..qcow2'.
'qcow2..Fedora.14' is not equivalent to 'qcow2..14.Fedora'.
'ide, scsi' is equivalent to 'scsi, ide'.
Filters can be used in 3 ways:
only <filter>
no <filter>
<filter>:
The last one starts a conditional block.
Formal definition:
regexp from python http://docs.python.org/2/library/re.html
Not deterministic but more readable for people.
Spaces between terminals and nontermials are only for better
reading of definitions.
E={\n, #, :, "-", =, +=, <=, ?=, ?+=, ?<=, !, < , del, @, variants, include,
only, no, name, value}
N={S, DEL, FILTER, FILTER_NAME, FILTER_GROUP, PN_FILTER_GROUP,
STAT, VARIANT, VAR-TYPE, VAR-NAME, VAR-NAME-F, VAR, COMMENT,
TEXT, DEPS, DEPS-NAME-F, META-DATA, IDENTIFIER}
I = I^n | n in N // indentation from start of line
// where n is indentation length.
I = I^n+x | n,x in N // indentation with shift
start symbol = S
end symbol = eps
S -> I^0+x STATV | eps
#
#I^n STATV
#I^n STATV
#
I^n STATV -> I^n STATV \n I^n STATV | I^n STAT | I^n variants VARIANT
I^n STAT -> I^n STAT \n I^n STAT | I^n COMMENT | I^n include INC
I^n STAT -> I^n del DEL | I^n FILTER
DEL -> name \n
I^n STAT -> I^n name = VALUE | I^n name += VALUE | I^n name <= VALUE
I^n STAT -> I^n name ?= VALUE | I^n name ?+= VALUE | I^n name ?<= VALUE
VALUE -> TEXT \n | 'TEXT' \n | "TEXT" \n
COMMENT_BLOCK -> #TEXT | //TEXT
COMMENT -> COMMENT_BLOCK\n
COMMENT -> COMMENT_BLOCK\n
TEXT = [^\n] TEXT //python format regexp
#
#I^n variants VAR #comments: add possibility for comment
#I^n+x VAR-NAME: DEPS
#I^n+x+x2 STATV
#I^n VAR-NAME:
#
IDENTIFIER -> [A-Za-z0-9][A-Za-z0-9_-]*
VARIANT -> VAR COMMENT_BLOCK\n I^n+x VAR-NAME
VAR -> VAR-TYPE: | VAR-TYPE META-DATA: | : // Named | unnamed variant
VAR-TYPE -> IDENTIFIER
#
# variants _name_ [xxx] [zzz=yyy] [uuu]:
#
META-DATA -> [IDENTIFIER] | [IDENTIFIER=TEXT] | META-DATA META-DATA
I^n VAR-NAME -> I^n VAR-NAME \n I^n VAR-NAME | I^n VAR-NAME-N \n I^n+x STATV
VAR-NAME-N -> - @VAR-NAME-F: DEPS | - VAR-NAME-F: DEPS
VAR-NAME-F -> [a-zA-Z0-9\._-]+ // Python regexp
DEPS -> DEPS-NAME-F | DEPS-NAME-F,DEPS
DEPS-NAME-F -> [a-zA-Z0-9\._- ]+ // Python regexp
INC -> name \n
#
# FILTER_GROUP: STAT
# STAT
#
I^n STAT -> I^n PN_FILTER_GROUP | I^n ! PN_FILTER_GROUP
PN_FILTER_GROUP -> FILTER_GROUP: \n I^n+x STAT
PN_FILTER_GROUP -> FILTER_GROUP: STAT \n I^n+x STAT
#
# only FILTER_GROUP
# no FILTER_GROUP
FILTER -> only FILTER_GROUP \n | no FILTER_GROUP \n
FILTER_GROUP -> FILTER_NAME
FILTER_GROUP -> FILTER_GROUP..FILTER_GROUP
FILTER_GROUP -> FILTER_GROUP,FILTER_GROUP
FILTER_NAME -> FILTER_NAME.FILTER_NAME
FILTER_NAME -> VAR-NAME-F | (VAR-NAME-F=VAR-NAME-F)
@copyright: Red Hat 2008-2013
"""
import os, collections, optparse, logging, re, string, sys
_reserved_keys = set(("name", "shortname", "dep"))
num_failed_cases = 5
class ParserError(Exception):
def __init__(self, msg, line=None, filename=None, linenum=None):
Exception.__init__(self)
self.msg = msg
self.line = line
self.filename = filename
self.linenum = linenum
def __str__(self):
if self.line:
return "%s: %r (%s:%s)" % (self.msg, self.line,
self.filename, self.linenum)
else:
return "%s (%s:%s)" % (self.msg, self.filename, self.linenum)
class LexerError(ParserError):
pass
class MissingIncludeError(Exception):
def __init__(self, line, filename, linenum):
Exception.__init__(self)
self.line = line
self.filename = filename
self.linenum = linenum
def __str__(self):
return ("%r (%s:%s): file does not exist or it's not a regular "
"file" % (self.line, self.filename, self.linenum))
if sys.version_info[0] == 2 and sys.version_info[1] < 6:
def enum(iterator, start_pos=0):
for i in iterator:
yield start_pos, i
start_pos += 1
else:
enum = enumerate
def _match_adjacent(block, ctx, ctx_set):
"""
It try to match as many blocks as possible from context.
@return: Count of matched blocks.
"""
if block[0] not in ctx_set:
return 0
if len(block) == 1:
return 1 # First match and length is 1.
if block[1] not in ctx_set:
return int(ctx[-1] == block[0]) # Check match with last from ctx.
k = 0
i = ctx.index(block[0])
while i < len(ctx): # Try to match all of blocks.
if k > 0 and ctx[i] != block[k]: # Block not match
i -= k - 1
k = 0 # Start from first block in next ctx.
if ctx[i] == block[k]:
k += 1
if k >= len(block): # match all of blocks
break
if block[k] not in ctx_set: # block in not in whole ctx.
break
i += 1
return k
def _might_match_adjacent(block, ctx, ctx_set, descendant_labels):
matched = _match_adjacent(block, ctx, ctx_set)
for elem in block[matched:]: # Try to find rest of blocks in subtree
if elem not in descendant_labels:
#print "Can't match %s, ctx %s" % (block, ctx)
return False
return True
# Filter must inherit from object (otherwise type() won't work)
class Filter(object):
__slots__ = ["filter"]
def __init__(self, lfilter):
self.filter = lfilter
#print self.filter
def match(self, ctx, ctx_set):
for word in self.filter: # Go through ,
for block in word: # Go through ..
if _match_adjacent(block, ctx, ctx_set) != len(block):
break
else:
#print "Filter pass: %s ctx: %s" % (self.filter, ctx)
return True # All match
return False
def might_match(self, ctx, ctx_set, descendant_labels):
# There is some posibility to match in children blocks.
for word in self.filter:
for block in word:
if not _might_match_adjacent(block, ctx, ctx_set,
descendant_labels):
break
else:
return True
#print "Filter not pass: %s ctx: %s" % (self.filter, ctx)
return False
class NoOnlyFilter(Filter):
__slots__ = ("line")
def __init__(self, lfilter, line):
super(NoOnlyFilter, self).__init__(lfilter)
self.line = line
def __eq__(self, o):
if isinstance(o, self.__class__):
if self.filter == o.filter:
return True
return False
class OnlyFilter(NoOnlyFilter):
# pylint: disable=W0613
def is_irrelevant(self, ctx, ctx_set, descendant_labels):
# Matched in this tree.
return self.match(ctx, ctx_set)
def requires_action(self, ctx, ctx_set, descendant_labels):
# Impossible to match in this tree.
return not self.might_match(ctx, ctx_set, descendant_labels)
def might_pass(self, failed_ctx, failed_ctx_set, ctx, ctx_set,
descendant_labels):
for word in self.filter:
for block in word:
if (_match_adjacent(block, ctx, ctx_set) >
_match_adjacent(block, failed_ctx, failed_ctx_set)):
return self.might_match(ctx, ctx_set, descendant_labels)
return False
def __str__(self):
return "Only %s" % (self.filter)
def __repr__(self):
return "Only %s" % (self.filter)
class NoFilter(NoOnlyFilter):
def is_irrelevant(self, ctx, ctx_set, descendant_labels):
return not self.might_match(ctx, ctx_set, descendant_labels)
# pylint: disable=W0613
def requires_action(self, ctx, ctx_set, descendant_labels):
return self.match(ctx, ctx_set)
# pylint: disable=W0613
def might_pass(self, failed_ctx, failed_ctx_set, ctx, ctx_set,
descendant_labels):
for word in self.filter:
for block in word:
if (_match_adjacent(block, ctx, ctx_set) <
_match_adjacent(block, failed_ctx, failed_ctx_set)):
return not self.match(ctx, ctx_set)
return False
def __str__(self):
return "No %s" % (self.filter)
def __repr__(self):
return "No %s" % (self.filter)
class BlockFilter(object):
__slots__ = ["blocked"]
def __init__(self, blocked):
self.blocked = blocked
def apply_to_dict(self, d):
pass
class Condition(NoFilter):
__slots__ = ["content"]
# pylint: disable=W0231
def __init__(self, lfilter, line):
super(Condition, self).__init__(lfilter, line)
self.content = []
def __str__(self):
return "Condition %s:%s" % (self.filter, self.content)
def __repr__(self):
return "Condition %s:%s" % (self.filter, self.content)
class NegativeCondition(OnlyFilter):
__slots__ = ["content"]
# pylint: disable=W0231
def __init__(self, lfilter, line):
super(NegativeCondition, self).__init__(lfilter, line)
self.content = []
def __str__(self):
return "NotCond %s:%s" % (self.filter, self.content)
def __repr__(self):
return "NotCond %s:%s" % (self.filter, self.content)
class StrReader(object):
"""
Preprocess an input string for easy reading.
"""
def __init__(self, s):
"""
Initialize the reader.
@param s: The string to parse.
"""
self.filename = "<string>"
self._lines = []
self._line_index = 0
self._stored_line = None
for linenum, line in enumerate(s.splitlines()):
line = line.rstrip().expandtabs()
stripped_line = line.lstrip()
indent = len(line) - len(stripped_line)
if (not stripped_line
or stripped_line.startswith("#")
or stripped_line.startswith("//")):
continue
self._lines.append((stripped_line, indent, linenum + 1))
def get_next_line(self, prev_indent):
"""
Get the next line in the current block.
@param prev_indent: The indentation level of the previous block.
@return: (line, indent, linenum), where indent is the line's
indentation level. If no line is available, (None, -1, -1) is
returned.
"""
if self._stored_line:
ret = self._stored_line
self._stored_line = None
return ret
if self._line_index >= len(self._lines):
return None, -1, -1
line, indent, linenum = self._lines[self._line_index]
if indent <= prev_indent:
return None, indent, linenum
self._line_index += 1
return line, indent, linenum
def set_next_line(self, line, indent, linenum):
"""
Make the next call to get_next_line() return the given line instead of
the real next line.
"""
line = line.strip()
if line:
self._stored_line = line, indent, linenum
class FileReader(StrReader):
"""
Preprocess an input file for easy reading.
"""
def __init__(self, filename):
"""
Initialize the reader.
@parse filename: The name of the input file.
"""
StrReader.__init__(self, open(filename).read())
self.filename = filename
class Label(object):
__slots__ = ["name", "var_name", "long_name", "hash_val", "hash_var"]
def __init__(self, name, next_name=None):
if next_name is None:
self.name = name
self.var_name = None
else:
self.name = next_name
self.var_name = name
if self.var_name is None:
self.long_name = "%s" % (self.name)
else:
self.long_name = "(%s=%s)" % (self.var_name, self.name)
self.hash_val = self.hash_name()
self.hash_var = None
if self.var_name:
self.hash_var = self.hash_variant()
def __str__(self):
return self.long_name
def __repr__(self):
return self.long_name
def __eq__(self, o):
"""
The comparison is asymmetric due to optimization.
"""
if o.var_name:
if self.long_name == o.long_name:
return True
else:
if self.name == o.name:
return True
return False
def __ne__(self, o):
"""
The comparison is asymmetric due to optimization.
"""
if o.var_name:
if self.long_name != o.long_name:
return True
else:
if self.name != o.name:
return True
return False
def __hash__(self):
return self.hash_val
def hash_name(self):
return sum([i + 1 * ord(x) for i, x in enumerate(self.name)])
def hash_variant(self):
return sum([i + 1 * ord(x) for i, x in enumerate(str(self))])
class Node(object):
__slots__ = ["var_name", "name", "dep", "content", "children", "labels",
"append_to_shortname", "failed_cases", "default", "q_dict"]
def __init__(self):
self.var_name = []
self.name = []
self.dep = []
self.content = []
self.children = []
self.labels = set()
self.append_to_shortname = False
self.failed_cases = collections.deque()
self.default = False
def dump(self, indent, recurse=False):
print("%s%s" % (" " * indent, self.name))
print("%s%s" % (" " * indent, self.var_name))
print("%s%s" % (" " * indent, self))
print("%s%s" % (" " * indent, self.content))
print("%s%s" % (" " * indent, self.failed_cases))
if recurse:
for child in self.children:
child.dump(indent + 3, recurse)
match_subtitute = re.compile("\$\{(.+)\}")
def _subtitution(value, d):
"""
Only optimization string Template subtitute is quite expensive operation.
@param value: String where could be $string for subtitution.
@param d: Dictionary from which should be value subtituted to value.
@return: Substituted string
"""
if "$" in value:
start = 0
st = ""
try:
match = match_subtitute.search(value, start)
while match:
val = eval(match.group(1), None, d)
st += value[start:match.start()] + str(val)
start = match.end()
match = match_subtitute.search(value, start)
except:
pass
st += value[start:len(value)]
return st
else:
return value
class Token(object):
identifier = ""
def __str__(self):
return self.identifier
def __repr__(self):
return "'%s'" % self.identifier
def __ne__(self, o):
"""
The comparison is asymmetric due to optimization.
"""
if o.identifier != self.identifier:
return True
return False
class LIndent(Token):
__slots__ = ["length"]
identifier = "indent"
def __init__(self, lenght):
self.length = lenght
def __str__(self):
return "%s %s" % (self.identifier, self.length)
def __repr__(self):
return "%s %s" % (self.identifier, self.length)
class LEndL(Token):
identifier = "endl"
class LEndBlock(LIndent):
pass
class LIdentifier(str):
identifier = "Identifier re([A-Za-z0-9][A-Za-z0-9_-]*)"
def __str__(self):
return super(LIdentifier, self).__str__()
def __repr__(self):
return "'%s'" % self
def checkChar(self, chars):
for t in self:
if not (t in chars):
raise ParserError("Wrong char %s in %s" % (t, self))
return self
def checkAlpha(self):
"""
Check if string contain only chars
"""
if not self.isalpha():
raise ParserError("Some of chars is not alpha in %s" % (self))
return self
def checkNumbers(self):
"""
Check if string contain only chars
"""
if not self.isdigit():
raise ParserError("Some of chars is not digit in %s" % (self))
return self
def checkCharAlpha(self, chars):
"""
Check if string contain only chars
"""
for t in self:
if not (t in chars or t.isalpha()):
raise ParserError("Char %s is not alpha or one of special"
"chars [%s] in %s" % (t, chars, self))
return self
def checkCharAlphaNum(self, chars):
"""
Check if string contain only chars
"""
for t in self:
if not (t in chars or t.isalnum()):
raise ParserError("Char %s is not alphanum or one of special"
"chars [%s] in %s" % (t, chars, self))
return self
def checkCharNumeric(self, chars):
"""
Check if string contain only chars
"""
for t in self:
if not (t in chars or t.isdigit()):
raise ParserError("Char %s is not digit or one of special"
"chars [%s] in %s" % (t, chars, self))
return self
class LWhite(LIdentifier):
identifier = "WhiteSpace re(\\s)"
class LString(LIdentifier):
identifier = "String re(.+)"
class LColon(Token):
identifier = ":"
class LVariants(Token):
identifier = "variants"
class LDot(Token):
identifier = "."
class LVariant(Token):
identifier = "-"
class LDefault(Token):
identifier = "@"
class LOnly(Token):
identifier = "only"
class LNo(Token):
identifier = "no"
class LCond(Token):
identifier = ""
class LNotCond(Token):
identifier = "!"
class LOr(Token):
identifier = ","
class LAnd(Token):
identifier = ".."
class LCoc(Token):
identifier = "."
class LComa(Token):
identifier = ","
class LLBracket(Token):
identifier = "["
class LRBracket(Token):
identifier = "]"
class LLRBracket(Token):
identifier = "("
class LRRBracket(Token):
identifier = ")"
class LRegExpStart(Token):
identifier = "${"
class LRegExpStop(Token):
identifier = "}"
class LInclude(Token):
identifier = "include"
class LOperators(Token):
__slots__ = ["name", "value"]
identifier = ""
function = None
def set_operands(self, name, value):
# pylint: disable=W0201
self.name = str(name)
# pylint: disable=W0201
self.value = str(value)
return self
class LSet(LOperators):
identifier = "="
def apply_to_dict(self, d):
"""
@param d: Dictionary for apply value
"""
if self.name not in _reserved_keys:
d[self.name] = _subtitution(self.value, d)
class LAppend(LOperators):
identifier = "+="
def apply_to_dict(self, d):
if self.name not in _reserved_keys:
d[self.name] = d.get(self.name, "") + _subtitution(self.value, d)
class LPrepend(LOperators):
identifier = "<="
def apply_to_dict(self, d):
if self.name not in _reserved_keys:
d[self.name] = _subtitution(self.value, d) + d.get(self.name, "")
class LRegExpSet(LOperators):
identifier = "?="
def apply_to_dict(self, d):
exp = re.compile("%s$" % self.name)
value = _subtitution(self.value, d)
for key in d:
if key not in _reserved_keys and exp.match(key):
d[key] = value
class LRegExpAppend(LOperators):
identifier = "?+="
def apply_to_dict(self, d):
exp = re.compile("%s$" % self.name)
value = _subtitution(self.value, d)
for key in d:
if key not in _reserved_keys and exp.match(key):
d[key] += value
class LRegExpPrepend(LOperators):
identifier = "?<="
def apply_to_dict(self, d):
exp = re.compile("%s$" % self.name)
value = _subtitution(self.value, d)
for key in d:
if key not in _reserved_keys and exp.match(key):
d[key] = value + d[key]
class LDel(LOperators):
identifier = "del"
def apply_to_dict(self, d):
exp = re.compile("%s$" % self.name)
keys_to_del = collections.deque()
for key in d:
if key not in _reserved_keys and exp.match(key):
keys_to_del.append(key)
for key in keys_to_del:
del d[key]
class LApplyPreDict(LOperators):
identifier = "apply_pre_dict"
def set_operands(self, name, value):
# pylint: disable=W0201
self.name = name
# pylint: disable=W0201
self.value = value
return self
def apply_to_dict(self, d):
d.update(self.value)
def __str__(self):
return "Apply_pre_dict: %s" % self.value
def __repr__(self):
return "Apply_pre_dict: %s" % self.value
spec_iden = "_-"
spec_oper = "+<?"
tokens_map = {"-": LVariant,
".": LDot,
":": LColon,
"@": LDefault,
",": LComa,
"[": LLBracket,
"]": LRBracket,
"(": LLRBracket,
")": LRRBracket,
"!": LNotCond}
tokens_oper = {"": LSet,
"+": LAppend,
"<": LPrepend,
"?": LRegExpSet,
"?+": LRegExpAppend,
"?<": LRegExpPrepend,
}
tokens_oper_re = [r"\=", r"\+\=", r"\<\=", r"\?\=", r"\?\+\=", r"\?\<\="]
_ops_exp = re.compile(r"|".join(tokens_oper_re))
class Lexer(object):
def __init__(self, reader):
self.reader = reader
self.filename = reader.filename
self.line = None
self.linenum = 0
self.ignore_white = False
self.rest_as_string = False
self.match_func_index = 0
self.generator = self.get_lexer()
self.prev_indent = 0
self.fast = False
def set_prev_indent(self, prev_indent):
self.prev_indent = prev_indent
def set_fast(self):
self.fast = True
def set_strict(self):
self.fast = False
def match(self, line, pos):
l0 = line[0]
chars = ""
m = None
cind = 0
if l0 == "v":
if line.startswith("variants:"):
yield LVariants()
yield LColon()
pos = 9
elif line.startswith("variants "):
yield LVariants()
pos = 8
elif l0 == "-":
yield LVariant()
pos = 1
elif l0 == "o":
if line.startswith("only "):
yield LOnly()
pos = 4
while line[pos].isspace():
pos += 1
elif l0 == "n":
if line.startswith("no "):
yield LNo()
pos = 2
while line[pos].isspace():
pos += 1
elif l0 == "i":
if line.startswith("include "):
yield LInclude()
pos = 7
elif l0 == "d":
if line.startswith("del "):
yield LDel()
pos = 3
while line[pos].isspace():
pos += 1
if self.fast and pos == 0: # due to refexp
cind = line[pos:].find(":")
m = _ops_exp.search(line[pos:])
oper = ""
token = None
if self.rest_as_string:
self.rest_as_string = False
yield LString(line[pos:].lstrip())
elif self.fast and m and (cind < 0 or cind > m.end()):
chars = ""
yield LIdentifier(line[:m.start()].rstrip())
yield tokens_oper[m.group()[:-1]]()
yield LString(line[m.end():].lstrip())
else:
li = enum(line[pos:], pos)
for pos, char in li:
if char.isalnum() or char in spec_iden: # alfanum+_-