-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
1535 lines (1236 loc) · 50.8 KB
/
parser.py
File metadata and controls
1535 lines (1236 loc) · 50.8 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
import logging
import unicodedata
from abc import ABCMeta
from abc import abstractmethod
from collections import deque
from enum import Enum
from typing import Any
from typing import Deque
from typing import List
from typing import Optional
from typing import Set
from typing import Tuple
from typing import Type
from typing import TypeVar
import antlr4
import antlr4.error.ErrorListener
from antlr4 import CommonTokenStream
from antlr4 import InputStream
from antlr4 import ParserRuleContext
from antlr4 import ParseTreeWalker
from fcsql.FCSLexer import FCSLexer
from fcsql.FCSParser import FCSParser
from fcsql.FCSParserListener import FCSParserListener
# ---------------------------------------------------------------------------
LOGGER = logging.getLogger(__name__)
_T = TypeVar("_T", bound="QueryNode")
OCCURS_UNBOUNDED = -1
"""Atom occurrence if not bound."""
# ---------------------------------------------------------------------------
class QueryNodeType(str, Enum):
"""Node types of FCS-QL expression tree nodes."""
def __str__(self) -> str:
return self.value
QUERY_SEGMENT = "QuerySegment"
"""Segment query."""
QUERY_GROUP = "QueryGroup"
"""Group query."""
QUERY_SEQUENCE = "QuerySequence"
"""Sequence query."""
QUERY_DISJUNCTION = "QueryDisjunction"
"""Or query."""
QUERY_WITH_WITHIN = "QueryWithWithin"
"""Query with within part."""
EXPRESSION = "Expression"
"""Simple expression."""
EXPRESSION_WILDCARD = "Wildcard"
"""Wildcard expression."""
EXPRESSION_GROUP = "Group"
"""Group expression."""
EXPRESSION_OR = "Or"
"""Or expression."""
EXPRESSION_AND = "And"
"""And expression."""
EXPRESSION_NOT = "Not"
"""Not expression."""
SIMPLE_WITHIN = "SimpleWithin"
"""Simple within part."""
class Operator(str, Enum):
"""FCS-QL operators."""
def __str__(self) -> str:
return self.value
EQUALS = "Eq"
"""EQUALS operator."""
NOT_EQUALS = "Ne"
"""NOT-EQUALS operator."""
class RegexFlag(str, Enum):
"""FCS-QL expression tree regex flags."""
def __new__(cls, name: str, char: str):
obj = str.__new__(cls, name)
obj._value_ = name
obj.char = char
return obj
char: str
def __str__(self) -> str:
return self.value
CASE_INSENSITIVE = ("case-insensitive", "i")
"""Case insensitive."""
CASE_SENSITIVE = ("case-sensitive", "I")
"""Case sensitive."""
LITERAL_MATCHING = ("literal-matching", "l")
"""match exactly (= literally)"""
IGNORE_DIACRITICS = ("ignore-diacritics", "d")
"""Ignore all diacritics."""
class SimpleWithinScope(str, Enum):
"""The within scope."""
def __str__(self) -> str:
return self.value
SENTENCE = "Sentence"
"""sentence scope (small)"""
UTTERANCE = "Utterance"
"""utterance scope (small)"""
PARAGRAPH = "Paragraph"
"""paragraph scope (medium)"""
TURN = "Turn"
"""turn scope (medium)"""
TEXT = "Text"
"""text scope (large)"""
SESSION = "Session"
"""session scope (large)"""
# ---------------------------------------------------------------------------
class QueryVisitor(metaclass=ABCMeta):
"""Interface implementing a Visitor pattern for FCS-QL expression trees.
Default method implementations do nothing.
"""
def visit(self, node: "QueryNode") -> None:
"""Visit a query node. Generic handler, dispatches to visit methods
based on `QueryNodeType` if exists else do nothing::
method = "visit_" + node.node_type.value
Args:
node: the node to visit
Returns:
``None``
"""
if not node:
return None
def noop(node):
pass
# search for specific visit function based on node_type
method = getattr(self, f"visit_{node.node_type}", noop)
method(node)
# ---------------------------------------------------------------------------
class QueryNode(metaclass=ABCMeta):
"""Base class for FCS-QL expression tree nodes."""
def __init__(
self,
node_type: QueryNodeType,
children: Optional[List["QueryNode"]] = None,
child: Optional["QueryNode"] = None,
):
"""[Constructor]
Args:
node_type: the type of the node
children: the children of this node or ``None``. Defaults to None.
child: the child of this node or ``None``. Defaults to None.
"""
self.node_type = node_type
"""The node type of this node."""
self.parent: Optional[QueryNode] = None
"""The parent node of this node.
``None`` if this is the root node.
"""
if not children:
children = list()
self.children = list(children)
"""The children of this node."""
if child:
self.children.append(child)
def has_node_type(self, node_type: QueryNodeType) -> bool:
"""Check, if node if of given type.
Args:
node_type: type to check against
Returns:
bool: ``True`` if node is of given type, ``False`` otherwise
Raises:
TypeError: if node_type is ``None``
"""
if node_type is None:
raise TypeError("node_type is None")
return self.node_type == node_type
@property
def child_count(self) -> int:
"""Get the number of children of this node.
Returns:
int: the number of children of this node
"""
return len(self.children) if self.children else 0
def get_child(
self, idx: int, clazz: Optional[Type[_T]] = None
) -> Optional["QueryNode"]:
"""Get a child node of specified type by index.
When supplied with ``clazz`` parameter, only child nodes of
the requested type are counted.
Args:
idx: the index of the child node (if `clazz` provided, only consideres child nodes of requested type)
clazz: the type to nodes to be considered, optional
Returns:
QueryNode: the child node of this node or ``None`` if not child was found (e.g. type mismatch or index out of bounds)
"""
if not self.children or idx < 0 or idx > self.child_count:
return None
if not clazz:
return self.children[idx]
pos = 0
for child in self.children:
if isinstance(child, clazz):
if pos == idx:
return child
pos += 1
return None
def get_first_child(
self, clazz: Optional[Type[_T]] = None
) -> Optional["QueryNode"]:
"""Get this first child node.
Args:
clazz: the type to nodes to be considered
Returns:
QueryNode: the first child node of this node or ``None``
"""
return self.get_child(0, clazz=clazz)
def get_last_child(self, clazz: Optional[Type[_T]] = None) -> Optional["QueryNode"]:
"""Get this last child node.
Args:
clazz: the type to nodes to be considered
Returns:
QueryNode: the last child node of this node or ``None``
"""
return self.get_child(self.child_count - 1, clazz=clazz)
def __str__(self) -> str:
chs = " ".join(map(str, self.children))
return f"({self.node_type!s}{' ' + chs if chs else ''})"
@abstractmethod
def accept(self, visitor: QueryVisitor) -> None:
pass
# ---------------------------------------------------------------------------
class Expression(QueryNode):
"""A FCS-QL expression tree SIMPLE expression node."""
def __init__(
self,
qualifier: Optional[str],
identifier: str,
operator: Operator,
regex: str,
regex_flags: Optional[Set[RegexFlag]],
):
"""[Constructor]
Args:
qualifier: the layer identifier qualifier or ``None``
identifier: the layer identifier
operator: the operator
regex: the regular expression
regex_flags: the regular expression flags or ``None``
"""
super().__init__(QueryNodeType.EXPRESSION)
if not qualifier or qualifier.isspace():
qualifier = None
if not regex_flags:
regex_flags = None
else:
regex_flags = set(regex_flags)
self.qualifier = qualifier
"""The Layer Type Identifier qualifier.
``None`` if not used in this expression.
"""
self.identifier = identifier
"""The layer identifier."""
self.operator = operator
"""The operator."""
self.regex = regex
"""The regex value."""
self.regex_flags = regex_flags
"""The regex flags set.
``None`` if no flags were used in this expression.
"""
def has_layer_identifier(self, identifier: str) -> bool:
"""Check if the expression used a given **Layer Type Identifier**.
Args:
identifier: the Layer Type Identifier to check against
Returns:
bool: ``True`` if this identifier was used, ``False`` otherwise
Raises:
TypeError: if identifier is ``None``
"""
if identifier is None:
raise TypeError("identifier is None")
return self.identifier == identifier
def is_layer_qualifier_empty(self) -> bool:
"""Check if the Layer Type Identifier qualifier is empty.
Returns:
bool: ``True`` if no Layer Type Identifier qualifier was set, ``False`` otherwise
"""
# NOTE: check only `self.qualifier is None` ?
return bool(self.qualifier)
def has_layer_qualifier(self, qualifier: str) -> bool:
"""Check if the expression used a given qualifier for the Layer Type
Identifier.
Args:
qualifier: the qualifier to check against
Returns:
bool: ``True`` if this identifier was used, ``False`` otherwise
Raises:
TypeError: if qualifier is ``None``
"""
if qualifier is None:
raise TypeError("qualifier is None")
if self.is_layer_qualifier_empty():
return False
return self.qualifier == qualifier
def has_operator(self, operator: Operator) -> bool:
"""Check if expression used a given operator.
Args:
operator: the operator to check
Returns:
bool: ``True`` if the given operator was used, ``False`` otherwise
Raises:
TypeError: if operator is ``None``
"""
if operator is None:
raise TypeError("operator is None")
return self.operator == operator
def is_regex_flags_empty(self) -> bool:
"""Check if a regex flag set is empty.
Returns:
bool: ``True`` if no regex flags where set, ``False`` otherwise
"""
return bool(self.regex_flags)
def has_regex_flag(self, flag: RegexFlag) -> bool:
"""Check if a regex flag is set.
Args:
flag: the flag to be checked
Returns:
bool: ``True`` if the flag is set, ``False`` otherwise
Raises:
TypeError: if flag is ``None``
"""
if flag is None:
raise TypeError("flag is None")
if not self.regex_flags:
return False
return flag in self.regex_flags
def __str__(self) -> str:
parts = list()
parts.append(f"({self.node_type!s} ")
parts.append(f"{self.qualifier}:" if self.qualifier else "")
parts.append(f'{self.identifier} {self.operator!s} "')
parts.append(
self.regex.translate(str.maketrans({"\n": "\\n", "\r": "\\r", "\t": "\\t"})) # type: ignore
)
parts.append('"')
if self.regex_flags:
parts.append("/")
# TODO: use chars from RegexFlag enum. How to guarantee same order?
parts.append("i" if RegexFlag.CASE_INSENSITIVE in self.regex_flags else "")
parts.append("I" if RegexFlag.CASE_SENSITIVE in self.regex_flags else "")
parts.append("l" if RegexFlag.LITERAL_MATCHING in self.regex_flags else "")
parts.append("d" if RegexFlag.IGNORE_DIACRITICS in self.regex_flags else "")
return "".join(parts)
def accept(self, visitor: QueryVisitor) -> None:
visitor.visit(self)
# ---------------------------------------------------------------------------
class ExpressionWildcard(QueryNode):
"""A FCS-QL expression tree WILDCARD expression node."""
def __init__(
self,
children: Optional[List["QueryNode"]] = None,
child: Optional["QueryNode"] = None,
):
super().__init__(
QueryNodeType.EXPRESSION_WILDCARD, children=children, child=child
)
def accept(self, visitor: QueryVisitor) -> None:
visitor.visit(self)
class ExpressionGroup(QueryNode):
"""A FCS-QL expression tree GROUP expression node."""
def __init__(self, child: QueryNode):
"""[Constructor]
Args:
child: the group content
"""
super().__init__(QueryNodeType.EXPRESSION_GROUP, child=child)
def __str__(self) -> str:
return f"({self.node_type!s} {self.get_first_child()!s})"
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
# for child in self.children:
# child.accept(visitor)
self.children[0].accept(visitor)
visitor.visit(self)
class ExpressionNot(QueryNode):
"""A FCS-QL expression tree NOT expression node."""
def __init__(self, child: QueryNode):
"""[Constructor]
Args:
child: the child expression
"""
super().__init__(QueryNodeType.EXPRESSION_NOT, child=child)
def __str__(self) -> str:
return f"({self.node_type!s} {self.get_first_child()!s})"
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
# for child in self.children:
# child.accept(visitor)
self.children[0].accept(visitor)
visitor.visit(self)
class ExpressionAnd(QueryNode):
"""A FCS-QL expression tree AND expression node."""
def __init__(self, children: List[QueryNode]):
"""[Constructor]
Args:
children: child elements covered by AND expression.
"""
super().__init__(QueryNodeType.EXPRESSION_AND, children=children)
@property
def operands(self) -> List[QueryNode]:
"""Get the AND expression operands.
Returns:
List[QueryNode]: a list of expressions
"""
return self.children
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
for child in self.children:
child.accept(visitor)
visitor.visit(self)
class ExpressionOr(QueryNode):
"""A FCS-QL expression tree OR expression node."""
def __init__(self, children: List[QueryNode]):
"""[Constructor]
Args:
children: child elements covered by OR expression.
"""
super().__init__(QueryNodeType.EXPRESSION_OR, children=children)
@property
def operands(self) -> List[QueryNode]:
"""Get the OR expression operands.
Returns:
List[QueryNode]: a list of expressions
"""
return self.children
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
for child in self.children:
child.accept(visitor)
visitor.visit(self)
# ---------------------------------------------------------------------------
class QueryDisjunction(QueryNode):
"""A FCS-QL expression tree QR query."""
def __init__(self, children: List[QueryNode]):
"""[Constructor]
Args:
children: the children
"""
super().__init__(QueryNodeType.QUERY_DISJUNCTION, children=children)
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
for child in self.children:
child.accept(visitor)
visitor.visit(self)
class QuerySequence(QueryNode):
"""A FCS-QL expression tree query sequence node."""
def __init__(self, children: List[QueryNode]):
"""[Constructor]
Args:
children: the children for this node
"""
super().__init__(QueryNodeType.QUERY_SEQUENCE, children=children)
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
for child in self.children:
child.accept(visitor)
visitor.visit(self)
class QueryWithWithin(QueryNode):
"""FCS-QL expression tree QUERY-WITH-WITHIN node."""
def __init__(self, query: QueryNode, within: Optional[QueryNode]):
"""[Constructor]
Args:
query: the query node
within: the within node
"""
children = [query, within] if within else [query]
super().__init__(QueryNodeType.QUERY_WITH_WITHIN, children=children)
def get_query(self) -> QueryNode:
"""Get the query clause.
Returns:
QueryNode: the query clause
"""
return self.children[0]
def get_within(self) -> Optional[QueryNode]:
"""Get the within clause (= search context)
Returns:
QueryNode: the witin clause
"""
return self.get_child(1)
def accept(self, visitor: QueryVisitor) -> None:
self.children[0].accept(visitor)
within = self.get_child(1)
if within:
within.accept(visitor)
visitor.visit(self)
class QuerySegment(QueryNode):
"""A FCS-QL expression tree query segment node."""
def __init__(self, expression: QueryNode, min_occurs: int, max_occurs: int):
"""[Constructor]
Args:
expression: the expression
min_occurs: the minimum occurrence
max_occurs: the maximum occurrence
"""
super().__init__(QueryNodeType.QUERY_SEGMENT, child=expression)
self.min_occurs = min_occurs
"""The minimum occurrence of this segment."""
self.max_occurs = max_occurs
"""The maximum occurrence of this segment."""
def get_expression(self) -> QueryNode:
"""Get the expression for this segment.
Returns:
QueryNode: the expression
"""
return self.children[0]
def __str__(self) -> str:
ret = f"({self.node_type!s} "
if self.min_occurs != 1:
ret += f"@min={'*' if self.min_occurs == OCCURS_UNBOUNDED else self.min_occurs} "
if self.max_occurs != 1:
ret += f"@max={'*' if self.max_occurs == OCCURS_UNBOUNDED else self.max_occurs} "
ret += f"{self.children[0]!s})"
return ret
def accept(self, visitor: QueryVisitor) -> None:
self.children[0].accept(visitor)
visitor.visit(self)
class QueryGroup(QueryNode):
"""A FCS-QL expression tree GROUP query node."""
def __init__(self, child: QueryNode, min_occurs: int, max_occurs: int):
"""[Constructor]
Args:
child: the child
min_occurs: the minimum occurrence
max_occurs: the maximum occurrence
"""
super().__init__(QueryNodeType.QUERY_SEGMENT, child=child)
self.min_occurs = min_occurs
"""The minimum occurrence of group content."""
self.max_occurs = max_occurs
"""The maximum occurrence of group content."""
def get_content(self) -> QueryNode:
"""Get the group content.
Returns:
QueryNode: the content of the GROUP query
"""
return self.children[0]
def __str__(self) -> str:
ret = f"({self.node_type!s} "
if self.min_occurs != 1:
ret += f"@min={'*' if self.min_occurs == OCCURS_UNBOUNDED else self.min_occurs} "
if self.max_occurs != 1:
ret += f"@max={'*' if self.max_occurs == OCCURS_UNBOUNDED else self.max_occurs} "
ret += f"{self.children[0]!s})"
return ret
def accept(self, visitor: QueryVisitor) -> None:
if self.children:
for child in self.children:
child.accept(visitor)
visitor.visit(self)
# ---------------------------------------------------------------------------
class SimpleWithin(QueryNode):
"""A FCS-QL expression tree SIMPLE WITHIN query node."""
def __init__(self, scope: SimpleWithinScope):
super().__init__(QueryNodeType.SIMPLE_WITHIN)
self.scope = scope
"""The simple within scope."""
def __str__(self) -> str:
return f"({self.node_type!s} {self.scope!s})"
def accept(self, visitor: QueryVisitor) -> None:
visitor.visit(self)
# ---------------------------------------------------------------------------
REP_ZERO_OR_MORE = (0, OCCURS_UNBOUNDED)
REP_ONE_OR_MORE = (1, OCCURS_UNBOUNDED)
REP_ZERO_OR_ONE = (0, 1)
EMPTY_STRING = ""
DEFAULT_IDENTIFIER = "text"
DEFAULT_OPERATOR = Operator.EQUALS
DEFAULT_UNICODE_NORMALIZATION_FORM = "NFC"
"""Default unicode normalization form.
See also: `unicodedata.normalize
<https://docs.python.org/3/library/unicodedata.html#unicodedata.normalize>`_
"""
# ---------------------------------------------------------------------------
class ErrorListener(antlr4.error.ErrorListener.ErrorListener):
def __init__(self, query: str) -> None:
super().__init__()
self.query = query
self.errors: List[str] = list()
def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
# FIXME: additional information of error should not be logged but added
# to the list of errors; that list probably needs to be enhanced to
# store supplementary information Furthermore, a sophisticated
# errorlist implementation could also be used by the QueryVistor to add
# addition query error information
if LOGGER.isEnabledFor(logging.DEBUG):
if isinstance(offendingSymbol, antlr4.Token):
pos = offendingSymbol.start
if pos != -1:
LOGGER.debug("query: %s", self.query)
LOGGER.debug(" %s^- %s", " " * pos, msg)
self.errors.append(msg)
def has_errors(self) -> bool:
return bool(self.errors)
class QueryParserException(Exception):
"""Query parser exception."""
class ExpressionTreeBuilderException(Exception):
"""Error building expression tree."""
class ExpressionTreeBuilder(FCSParserListener):
def __init__(self, parser: "QueryParser") -> None:
super().__init__()
self.parser = parser
self.stack: Deque[Any] = deque()
self.stack_Query_disjunction: Deque[int] = deque()
"""for `enterQuery_disjunction`/`exitQuery_disjunction`"""
self.stack_Query_sequence: Deque[int] = deque()
"""for `enterQuery_sequence`/`exitQuery_sequence`"""
self.stack_Expression_or: Deque[int] = deque()
"""for `enterExpression_or`/`exitExpression_or`"""
self.stack_Expression_and: Deque[int] = deque()
"""for `enterExpression_and`/`exitExpression_and`"""
# ----------------------------------------------------
def enterQuery(self, ctx: FCSParser.QueryContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
return super().enterQuery(ctx)
def exitQuery(self, ctx: FCSParser.QueryContext):
w_ctx = ctx.getChild(0, FCSParser.Within_partContext)
if w_ctx is not None:
within = self.stack.pop()
query = self.stack.pop()
self.stack.append(QueryWithWithin(query, within))
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitQuery: stack=%s", self.stack)
return super().exitQuery(ctx)
def enterMain_query(self, ctx: FCSParser.Main_queryContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterMain_query: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
return super().enterMain_query(ctx)
def exitMain_query(self, ctx: FCSParser.Main_queryContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitMain_query: stack=%s", self.stack)
return super().exitMain_query(ctx)
def enterQuery_disjunction(self, ctx: FCSParser.Query_disjunctionContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery_disjunction: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
self.stack_Query_disjunction.append(len(self.stack))
return super().enterQuery_disjunction(ctx)
def exitQuery_disjunction(self, ctx: FCSParser.Query_disjunctionContext):
pos = self.stack_Query_disjunction.pop()
if len(self.stack) > pos:
items: List[QueryNode] = list()
while len(self.stack) > pos:
items.insert(0, self.stack.pop())
self.stack.append(QueryDisjunction(items))
else:
raise ExpressionTreeBuilderException("exitQuery_disjunction is empty")
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitQuery_disjunction: stack=%s", self.stack)
return super().exitQuery_disjunction(ctx)
def enterQuery_sequence(self, ctx: FCSParser.Query_sequenceContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery_sequence: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
self.stack_Query_sequence.append(len(self.stack))
return super().enterQuery_sequence(ctx)
def exitQuery_sequence(self, ctx: FCSParser.Query_sequenceContext):
pos = self.stack_Query_sequence.pop()
if len(self.stack) > pos:
items: List[QueryNode] = list()
while len(self.stack) > pos:
items.insert(0, self.stack.pop())
self.stack.append(QuerySequence(items))
else:
raise ExpressionTreeBuilderException("exitQuery_sequence is empty")
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitQuery_sequence: stack=%s", self.stack)
return super().exitQuery_sequence(ctx)
def enterQuery_group(self, ctx: FCSParser.Query_groupContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery_group: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
return super().enterQuery_group(ctx)
def exitQuery_group(self, ctx: FCSParser.Query_groupContext):
# handle repetition (if any)
min = max = 1
# fetch *first* child of type QuantifierContext, therefore idx=0
q_ctx = ctx.getChild(0, FCSParser.QualifierContext)
if q_ctx is not None:
min, max = ExpressionTreeBuilder.processRepetition(ctx)
content: QueryNode = self.stack.pop()
self.stack.append(QueryGroup(content, min, max))
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitQuery_group: stack=%s", self.stack)
return super().exitQuery_group(ctx)
def enterQuery_simple(self, ctx: FCSParser.Query_simpleContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery_simple: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
return super().enterQuery_simple(ctx)
def exitQuery_simple(self, ctx: FCSParser.Query_simpleContext):
# handle repetition (if any)
min = max = 1
# fetch *first* child of type QuantifierContext, therefore idx=0
q_ctx = ctx.getChild(0, FCSParser.QualifierContext)
if q_ctx is not None:
min, max = ExpressionTreeBuilder.processRepetition(ctx)
expression: QueryNode = self.stack.pop()
self.stack.append(QuerySegment(expression, min, max))
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitQuery_simple: stack=%s", self.stack)
return super().exitQuery_simple(ctx)
def enterQuery_implicit(self, ctx: FCSParser.Query_implicitContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery_implicit: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
self.stack.append(self.parser.default_operator)
self.stack.append(self.parser.default_identifier)
self.stack.append(EMPTY_STRING)
return super().enterQuery_implicit(ctx)
def exitQuery_implicit(self, ctx: FCSParser.Query_implicitContext):
regex_flags: Set[RegexFlag] = self.stack.pop()
regex_value: str = self.stack.pop()
qualifier: str = self.stack.pop()
identifier: str = self.stack.pop()
operator: Operator = self.stack.pop()
self.stack.append(
Expression(
qualifier=qualifier,
identifier=identifier,
operator=operator,
regex=regex_value,
regex_flags=regex_flags,
)
)
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug("exitQuery_implicit: stack=%s", self.stack)
return super().exitQuery_implicit(ctx)
# TODO: check, abortable, if also exit?
def enterQuery_segment(self, ctx: FCSParser.Query_segmentContext):
if LOGGER.isEnabledFor(logging.DEBUG):
LOGGER.debug(
"enterQuery_segment: children=%s / cnt=%s / text=%s",
ctx.children,
ctx.getChildCount(),
ctx.getText(),
)
# if the context contains only two children, they must be
# '[' and ']' thus we are dealing with a wildcard segment
if ctx.getChildCount() == 2:
self.stack.append(ExpressionWildcard())
# TODO: not exactly matching the java implementation
# do we need to block 'visitQuery_segment' call?
return super().enterQuery_segment(ctx)