-
Notifications
You must be signed in to change notification settings - Fork 97
/
parse.py
executable file
·1770 lines (1573 loc) · 55.3 KB
/
parse.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
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parser of Logica."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import os
import re
import string
import sys
from typing import Dict, Iterator, List, Optional, Tuple
if '.' not in __package__:
from common import color
else:
from ..common import color
CLOSE_TO_OPEN = {
')': '(',
'}': '{',
']': '['
}
CLOSING_PARENTHESIS = list(CLOSE_TO_OPEN.keys())
OPENING_PARENTHESIS = list(CLOSE_TO_OPEN.values())
VARIABLE_CHARS_SET = set(string.ascii_lowercase) | set('_') | set(string.digits)
TOO_MUCH = 'too much'
class HeritageAwareString(str):
"""A string that remembers who's substring it is."""
def __new__(cls, content) -> 'HeritageAwareString':
if isinstance(content, str):
return str.__new__(cls, content)
assert isinstance(content, bytes), 'Unexpected content: %s' % repr(content)
return str.__new__(cls, content.decode('utf-8'))
def __init__(self, unused_content):
self.start = 0
self.stop = len(self)
self.heritage = str(self)
def __getitem__(self, slice_or_index) -> 'HeritageAwareString':
if isinstance(slice_or_index, int):
return HeritageAwareString(str.__getitem__(self, slice_or_index))
else:
assert isinstance(slice_or_index, slice)
start = slice_or_index.start or 0
stop = (
slice_or_index.stop if slice_or_index.stop is not None else len(self))
return self.GetSlice(start, stop)
def GetSlice(self, start, stop) -> 'HeritageAwareString':
substring = HeritageAwareString(str(self)[start:stop])
if stop > len(self):
stop = len(self)
if stop < 0:
stop = len(self) + stop
substring.start = self.start + start
substring.stop = self.start + stop
substring.heritage = self.heritage
return substring
def Pieces(self):
return (self.heritage[:self.start],
self.heritage[self.start:self.stop],
self.heritage[self.stop:])
def Display(self):
a, b, c = self.Pieces()
if not b:
b = '<EMPTY>'
return color.Format(
'{before}{warning}{error_text}{end}{after}',
dict(before=a, error_text=b, after=c))
class ParsingException(Exception):
"""Exception thrown by parsing."""
def __init__(self, message, location):
# TODO: Unify coloring approach between parsing and compiling.
message = message.replace(
'>>', color.Color('warning')).replace('<<', color.Color('end'))
super(ParsingException, self).__init__(message)
self.location = location
def ShowMessage(self, stream=sys.stderr):
"""Printing error message."""
print(color.Format('{underline}Parsing{end}:'), file=stream)
before, error, after = self.location.Pieces()
if len(before) > 300:
before = before[-300:]
if len(after) > 300:
after = after[:300]
if not error:
error = '<EMPTY>'
print(color.Format('{before}{warning}{error_text}{end}{after}',
dict(before=before,
error_text=error,
after=after)), file=stream)
print(
color.Format('\n[ {error}Error{end} ] ') + str(self), file=stream)
def EnactIncantations(main_code):
"""Enabling experimental syntax features."""
global TOO_MUCH
if 'Signa inter verba conjugo, symbolum infixus evoco!' in main_code:
TOO_MUCH = 'fun'
def FunctorSyntaxErrorMessage():
return (
'Incorrect syntax for functor call. '
'Functor call to be made as\n'
' R := F(A: V, ...)\n'
'or\n'
' @Make(R, F, {A: V, ...})\n'
'Where R, F, A\'s and V\'s are all '
'predicate names.')
def Traverse(s):
"""Traversing the string, yielding indices with the state of parentheses.
Args:
s: Logica.
Yields:
(index in the string,
state of how many parenthesis do we have open,
status 'OK' or 'Unmatched <something>')
If 'Unmatched' status is yielded the program has a syntax error and compiler
should inform the user. Yielding 'Unmatched' terminates the iterator.
"""
state = ''
def State():
if not state:
return ''
return state[-1]
idx = -1
while idx + 1 < len(s):
idx += 1
c = s[idx]
c2 = s[idx:(idx + 2)] # For /*, */.
c3 = s[idx:(idx + 3)] # For """.
# Deal with strings (without escape).
# TODO: Deal with string escaping.
track_parenthesis = True
# First see if we are in a comment or a string.
if State() == '#':
track_parenthesis = False
if c == '\n':
state = state[:-1]
else:
# Comments are invisible to compiler.
continue
elif State() == '"':
track_parenthesis = False
if c == '\n':
yield (idx, None, 'EOL in string')
if c == '"':
state = state[:-1]
elif State() == '`':
track_parenthesis = False
if c == '`':
state = state[:-1]
elif State() == '3':
track_parenthesis = False
if c3 == '"""':
state = state[:-1]
yield (idx, state, 'OK')
idx += 1
yield (idx, state, 'OK')
idx += 1
elif State() == '/':
track_parenthesis = False
if c2 == '*/':
state = state[:-1]
idx += 1
# Comments are invisible to compiler.
continue
else:
# We are neither in comment nor in string.
if c == '#':
state += '#'
# Comments are invisible to compiler.
continue
elif c3 == '"""':
state += '3'
yield (idx, state, 'OK')
idx += 1
yield (idx, state, 'OK')
idx += 1
elif c == '"':
state += '"'
elif c == '`':
state += '`'
elif c2 == '/*':
state += '/'
idx += 1
# Comments are invisible to compiler.
continue
if track_parenthesis:
if c in OPENING_PARENTHESIS:
state += c
elif c in CLOSING_PARENTHESIS:
if state and state[-1] == CLOSE_TO_OPEN[c]:
state = state[:-1]
else:
yield (idx, None, 'Unmatched')
break
yield (idx, state, 'OK')
def RemoveComments(s):
chars = []
for idx, unused_state, status in Traverse(s):
if status == 'Unmatched':
raise ParsingException('Parenthesis matches nothing.', s[idx:idx+1])
elif status == 'EOL in string':
raise ParsingException('End of line in string.', s[idx:idx])
assert status == 'OK'
chars.append(s[idx])
return ''.join(chars)
def IsWhole(s):
"""String is 'whole' if all parenthesis match."""
status = 'OK'
for (_, _, status) in Traverse(s):
pass
return status == 'OK'
def ShowTraverse(s):
"""Showing states of traverse.
A debugging tool.
Args:
s: string with Logica.
"""
for idx, state, status in Traverse(s):
print('-----')
print(s)
print(' ' * idx + '^ ~%s~/%s' % (state, status))
def Strip(s):
"""Removing outer parenthesis and spaces."""
while True:
s = StripSpaces(s)
if (len(s) >= 2 and s[0] == '(' and s[-1] == ')' and
IsWhole(s[1:-1])):
s = s[1:-1]
else:
return s
def StripSpaces(s):
left_idx = 0
right_idx = len(s) - 1
while left_idx < len(s) and s[left_idx].isspace():
left_idx += 1
while right_idx > left_idx and s[right_idx].isspace():
right_idx -= 1
return s[left_idx:right_idx + 1]
def SplitRaw(s, separator):
"""Splits the string on separator, respecting parenthesis.
This is cornerstone of parsing.
Example: Split("[a,b],[c,d]", ",") == ["[a,b]", "[c,d]"].
Args:
s: String with Logica.
separator: Separator to split on.
Returns:
A list of parts of the string.
Raises:
ParsingException: When parenthesis don't match.
"""
parts = []
l = len(separator)
traverse = Traverse(s)
part_start = 0
for idx, state, status in traverse:
# TODO: This should be thrown by Traverse.
if status != 'OK':
raise ParsingException('Parenthesis matches nothing.', s[idx:idx+1])
# TODO: This a terrible hack to avoid parsing || as two |. Maybe
# we should tokenize at some point.
if not state and s[idx:(idx + l)] == separator and (
len(s) == idx + l or s[idx + l] != '|') and (
idx == 0 or s[idx - 1] != '|'):
# TODO: Treat tuples properly.
parts.append(s[part_start:idx])
for _ in range(l - 1):
idx, state, status = next(traverse)
part_start = idx + 1
parts.append(s[part_start:])
return parts
def Split(s, separator):
parts = SplitRaw(s, separator)
return [Strip(p) for p in parts]
def SplitInTwo(s, separator):
"""Splits the string in two or dies. Makes python typing happy."""
parts = Split(s, separator)
if len(parts) != 2:
raise ParsingException(
'I expected string to be split by >>%s<< in two.' % separator, s)
return (parts[0], parts[1])
def SplitInOneOrTwo(s, separator):
"""Splits the string in one or two. Makes python typing happy."""
parts = Split(s, separator)
if len(parts) == 1:
return ((parts[0],), None)
elif len(parts) == 2:
return (None, (parts[0], parts[1]))
else:
raise ParsingException(
'String should have been split by >>%s<< in 1 or 2 pieces.' % (
separator), s)
def SplitMany(ss: List[HeritageAwareString],
separator: str) -> List[HeritageAwareString]:
"""Splits the list of strings by the separator, flattening the result."""
result = []
for s in ss:
result.extend(Split(s, separator))
return result
def SplitOnWhitespace(s: HeritageAwareString) -> List[HeritageAwareString]:
"""Split the string by whitespace.
Like Split, does not split inside quoted strings and parentheses. Only return
non-empty parts.
"""
ss = [s]
for separator in ' \n\t':
ss = SplitMany(ss, separator)
return [chunk for chunk in ss if chunk]
############################################
#
# Parsing functions.
#
def ParseRecord(s):
s = Strip(s)
if (len(s) >= 2 and
s[0] == '{' and
s[-1] == '}' and
IsWhole(s[1:-1])):
return ParseRecordInternals(s[1:-1], is_record_literal=True)
def ParseRecordInternals(s,
is_record_literal = False,
is_aggregation_allowed=False):
"""Parsing internals of a record."""
s = Strip(s)
if len(Split(s, ':-')) > 1:
raise ParsingException(
'Unexpected >>:-<< in record internals. '
'If you apply a function to a >>combine<< statement, place it in '
'auxiliary variable first.', location=s)
if not s:
return {'field_value': []}
result = []
if IsWhole(s):
field_values = Split(s, ',')
had_restof = False
positional_ok = True
observed_fields = []
for idx, field_value in enumerate(field_values):
if had_restof:
raise ParsingException('Field >>..<rest_of><< must go last.',
field_value)
if field_value.startswith('..'):
if is_record_literal:
raise ParsingException('Field >>..<rest_of> in record literals<< '
'is not currently suppported .', field_value)
item = {
'field': '*',
'value': {'expression': ParseExpression(field_value[2:])}
}
if observed_fields:
item['except'] = observed_fields
result.append(item)
had_restof = True
positional_ok = False
continue
(_, colon_split) = SplitInOneOrTwo(field_value, ':')
if colon_split:
positional_ok = False
field, value = colon_split
observed_field = field
if not value:
value = field
if field and field[0] in string.ascii_uppercase:
raise ParsingException('Record fields may not start with capital '
'letter, as it is reserved for predicate '
'literals.\nBacktick the field name if '
'you need it capitalized. '
'E.g. "Q(`A`: 1)".',
field)
if field and field[0] == '`':
raise ParsingException('Backticks in variable names are '
'disallowed. Please give an explicit '
'variable for the value of the column.',
field)
result.append({
'field': field,
'value': {
'expression': ParseExpression(value)
}
})
else:
(_, question_split) = SplitInOneOrTwo(field_value, '?')
if question_split:
if not is_aggregation_allowed:
raise ParsingException('Aggregation of fields is only allowed in the head '
'of a rule.',
field_value)
positional_ok = False
field, value = question_split
observed_field = field
if not field:
raise ParsingException('Aggregated fields have to be named.',
field_value)
operator, expression = SplitInTwo(value, '=')
operator = Strip(operator)
result.append(
{
'field': field,
'value': {
'aggregation': {
'operator': operator,
'argument': ParseExpression(expression),
'expression_heritage': value
}
}
})
else:
if positional_ok:
result.append(
{
'field': idx,
'value': {
'expression': ParseExpression(field_value)
}
})
# It's not ideal that we hardcode 'col%d' logic here.
observed_field = 'col%d' % idx
else:
raise ParsingException(
'Positional argument can not go after non-positional '
'arguments.', field_value)
observed_fields.append(observed_field)
return {'field_value': result}
def ParseVariable(s: HeritageAwareString):
if (s and s[0] in set(string.ascii_lowercase) | set('_') and
set(s) <= VARIABLE_CHARS_SET):
if s.startswith('x_'):
raise ParsingException('Variables starting with >>x_<< are reserved '
'to be Logica compiler internal. Please use '
'a different name.', s)
return {'var_name': s}
def ParseNumber(s: HeritageAwareString):
if s[-1:] == 'u':
s = s[:-1]
# Parsing infinity as -1 for recursion depth.
if s == '∞':
return {'number': '-1'}
try:
float(s)
except ValueError:
return None
return {'number': s}
# TODO: Do this right, i.e. account for escaping and quotes in between.
def ParseString(s):
if (len(s) >= 2 and
s[0] == '"' and
s[-1] == '"' and
'"' not in s[1:-1]):
return {'the_string': s[1:-1]}
if (len(s) >= 6 and
s[:3] == '"""' and
s[-3:] == '"""' and
'"""' not in s[3:-3]):
return {'the_string': s[3:-3]}
def ParseBoolean(s):
if s in ['true', 'false']:
return {'the_bool': s}
def ParseNull(s):
if s == 'null':
return {'the_null': s}
def ParseList(s):
"""Parsing List literal."""
if len(s) >= 2 and s[0] == '[' and s[-1] == ']' and IsWhole(s[1:-1]):
inside = Strip(s[1:-1])
if not inside:
elements = []
else:
elements_str = Split(inside, ',')
elements = [ParseExpression(e) for e in elements_str]
return {'element': elements}
else:
return None
def ParsePredicateLiteral(s):
if (s == '++?' or
s == 'nil' or
s and
set(s) <=
set(string.ascii_letters) | set(string.digits) | set(['_']) and
s[0] in string.ascii_uppercase):
return {'predicate_name': s}
def ParseLiteral(s):
"""Parses a literal."""
v = ParseNumber(s)
if v:
return {'the_number': v}
v = ParseString(s)
if v:
return {'the_string': v}
v = ParseList(s)
if v:
return {'the_list': v}
v = ParseBoolean(s)
if v:
return {'the_bool': v}
v = ParseNull(s)
if v:
return {'the_null': v}
v = ParsePredicateLiteral(s)
if v:
return {'the_predicate': v}
def ParseInfix(s, operators=None, disallow_operators=None):
"""Parses an infix operator expression."""
if TOO_MUCH == 'fun':
user_defined_operators = ['---', '-+-', '-*-', '-/-', '-%-', '-^-',
'\u25C7', '\u25CB', '\u2661']
else:
user_defined_operators = []
operators = operators or (user_defined_operators + [
'||', '&&', '->', '==', '<=', '>=', '<', '>', '!=', '=', '~',
' in ', ' is not ', ' is ', '++?', '++', '+', '-', '*', '/', '%',
'^', '!'])
# We disallow ~ in expressions.
disallow_operators = disallow_operators or []
unary_operators = ['-', '!']
for op in operators:
if op in disallow_operators:
continue
parts = SplitRaw(s, op)
if len(parts) > 1:
# Right is the rightmost operand and left are all the other operands.
# This way we parse as follows:
# a / b / c -> (a / b) / c
left, right = (
s[:parts[-2].stop - s.start], s[parts[-1].start - s.start:])
# Prefer doing specialcasing to introducing unary `!~`.
if op == '~' and len(left) > 0 and left[-1] =='!':
# This is !~.
continue
left = Strip(left)
right = Strip(right)
if op in unary_operators and not left:
return {
'predicate_name': op,
'record': ParseRecordInternals(right)
}
if op == '~' and not left:
return None # Negation is special.
left_expr = ParseExpression(left)
right_expr = ParseExpression(right)
return {
'predicate_name': op.strip(),
'record': {
'field_value': [
{
'field': 'left',
'value': {'expression': left_expr}
},
{
'field': 'right',
'value': {'expression': right_expr}
}
]
}
}
def BuildTreeForCombine(parsed_expression, operator, parsed_body, full_text):
"""Construct a tree for a combine expression from the parsed components."""
aggregated_field_value = {
'field': 'logica_value',
'value': {
'aggregation': {
'operator': operator,
'argument': parsed_expression,
'expression_heritage': full_text
}
}
}
result = {
'head': {
'predicate_name': 'Combine',
'record': {
'field_value': [aggregated_field_value]
}
},
'distinct_denoted': True,
'full_text': full_text
}
if parsed_body:
result['body'] = {'conjunction': parsed_body}
return result
def ParseCombine(s: HeritageAwareString):
"""Parsing 'combine' expression."""
if s.startswith('combine '):
s = s[len('combine '):]
_, value_body = SplitInOneOrTwo(s, ':-')
if value_body:
value, body = value_body
else:
value = s
body = None
operator, expression = SplitInTwo(value, '=')
operator = Strip(operator)
parsed_expression = ParseExpression(expression)
parsed_body = ParseConjunction(body, allow_singleton=True) if body else None
return BuildTreeForCombine(parsed_expression, operator, parsed_body, s)
def ParseConciseCombine(s: HeritageAwareString):
"""Parses a concise 'combine' expression.
A concise combine expression consists is of the form 'x Op= expr' or 'x Op=
expr :- body', where x must be a variable. It is equivalent to 'x == (combine
Op= expr)' or 'x == (combine Op= expr :- body)' respectively.
"""
parts = Split(s, '=')
if len(parts) == 2:
lhs_and_op, combine = parts
left_parts = SplitOnWhitespace(lhs_and_op)
if len(left_parts) > 1:
lhs = s[:left_parts[-2].stop - s.start]
operator = left_parts[-1]
# These operators actually arise from comparison expressions; if we get
# them here, we should bail out.
prohibited_operators = ['!', '<', '>']
if operator in prohibited_operators:
return None
# Lowercase operators are not allowed and it would most likely mean
# that user forgot comma before assignment.
if operator[0].islower():
return None
left_expr = ParseExpression(lhs)
_, expression_body = SplitInOneOrTwo(combine, ':-')
if expression_body:
expression, body = expression_body
else:
expression = combine
body = None
parsed_expression = ParseExpression(expression)
parsed_body = ParseConjunction(
body, allow_singleton=True) if body else None
right_expr = BuildTreeForCombine(parsed_expression, operator, parsed_body,
s)
return {
'left_hand_side': left_expr,
'right_hand_side': {
'combine': right_expr,
'expression_heritage': s
}
}
def ParseImplication(s):
"""Parses implication expression."""
if s.startswith('if ') or s.startswith('if\n'):
inner = s[3:]
if_thens = Split(inner, 'else if')
(last_if_then, last_else) = SplitInTwo(if_thens[-1], 'else')
if_thens[-1] = last_if_then
result_if_thens = []
for condition_concequence in if_thens:
condition, consequence = SplitInTwo(condition_concequence, 'then')
result_if_thens.append({
'condition': ParseExpression(condition),
'consequence': ParseExpression(consequence)
})
last_else_parsed = ParseExpression(last_else)
return {'if_then': result_if_thens, 'otherwise': last_else_parsed}
def ParseUltraConciseCombine(s):
aggregation_call = ParseGenericCall(s, '{', '}')
if aggregation_call:
aggregating_function, multiset_rule_str = aggregation_call
_, value_body = SplitInOneOrTwo(multiset_rule_str, ':-')
if value_body:
value, body = value_body
else:
value = multiset_rule_str
body = None
parsed_expression = ParseExpression(value)
parsed_body = ParseConjunction(body, allow_singleton=True) if body else None
return BuildTreeForCombine(parsed_expression, aggregating_function, parsed_body, s)
def ParseExpression(s):
e = ActuallyParseExpression(s)
e['expression_heritage'] = s
return e
def ActuallyParseExpression(s):
"""Parsing logica.Expression."""
v = ParseCombine(s)
if v:
return {'combine': v}
v = ParseImplication(s)
if v:
return {'implication': v}
v = ParseLiteral(s)
if v:
return {'literal': v}
v = ParseVariable(s)
if v:
return {'variable': v}
v = ParseRecord(s)
if v:
return {'record': v}
v = ParseCall(s, is_aggregation_allowed=False)
if v:
return {'call': v}
v = ParseUltraConciseCombine(s)
if v:
return {'combine': v}
v = ParseInfix(s, disallow_operators='~')
if v:
return {'call': v}
v = ParseSubscript(s)
if v:
return {'subscript': v}
v = ParseNegationExpression(s)
if v:
return v # ParseNegationExpression returns an expression.
v = ParseArraySub(s)
if v:
return {'call': v}
raise ParsingException('Could not parse expression of a value.', s)
def ParseInclusion(s):
element_list_str = Split(s, ' in ')
if len(element_list_str) == 2:
return {'list': ParseExpression(element_list_str[1]),
'element': ParseExpression(element_list_str[0])}
def ParseGenericCall(s, opening, closing):
"""Parsing predicate call or array subscript."""
s = Strip(s)
predicate = ''
idx = 0
if not s:
return None
# Specialcasing -> operator for definition.
if s.startswith('->'):
idx = 2
predicate = '->'
else:
for (idx, state, status) in Traverse(s):
assert status == 'OK'
if state == opening:
good_chars = (
set(string.ascii_letters) |
set(['@', '_', '.', '$', '{', '}', '+', '-', '`']) |
set(string.digits))
if TOO_MUCH == 'fun':
good_chars |= set(['*', '^', '%', '/', '\u25C7', '\u25CB', '\u2661'])
if ((idx > 0 and set(s[:idx]) <= good_chars) or
s[:idx] == '!' or
s[:idx] == '++?' or
idx >= 2 and s[0] == '`' and s[idx - 1] == '`'):
predicate = s[:idx]
break
else:
return None
if state and state != '{' and state[0] != '`':
return None
else:
return None
if (s[idx] == opening and
s[-1] == closing and
IsWhole(s[idx + 1:-1])):
# Specialcasing `=` assignment operator for definition.
if predicate == '`=`':
predicate = '='
# Specialcasing `~` type equality operator for definition.
if predicate == '`~`':
predicate = '~'
return predicate, s[idx + 1: -1]
def ParseCall(s, is_aggregation_allowed):
"""Parsing logica.PredicateCall."""
generic_parse = ParseGenericCall(s, '(', ')')
if generic_parse is None:
return None
caller, args_str = generic_parse
args = ParseRecordInternals(
args_str,
is_aggregation_allowed=is_aggregation_allowed)
return {'predicate_name': caller,
'record': args}
def ParseArraySub(s):
"""Parsing array subscription into a call to Element function."""
generic_parse = ParseGenericCall(s, '[', ']')
if generic_parse is None:
return None
caller, args_str = generic_parse
args = ParseRecordInternals(
args_str,
is_aggregation_allowed=False)
array = ParseExpression(caller)
return NestedElement(s, array, args)
def NestedElement(s, array, args):
"""Nested Element function calls on the array with args as indexes."""
result = None
for i, fv in enumerate(args['field_value']):
fv = fv.copy()
if (fv['field'] != i):
raise ParsingException(
'Array subscription must only have positional arguments. '
'Non positional argument: >>%s<<' % fv['field'] , s)
fv['field'] = 1
if result is None:
first_argument = array
else:
first_argument = {'call': result}
element_args = {
'field_value': [
{'field': 0, 'value': {'expression': first_argument}},
fv]
}
result = {
'predicate_name': 'Element',
'record': element_args
}
return result
def ParseUnification(s):
parts = Split(s, '==')
if len(parts) == 2:
left, right = (parts[0], parts[1])
left_expr = ParseExpression(left)
right_expr = ParseExpression(right)
return {'left_hand_side': left_expr,
'right_hand_side': right_expr}
def ParseProposition(s):
"""Parsing logica.ExistentialFormula."""
c = ParseDisjunction(s)
if c:
return {'disjunction': c}
str_conjuncts = Split(s, ',')
c = ParseConjunction(s, allow_singleton=False)
if len(str_conjuncts) > 1:
return {'conjunction': c}
if TOO_MUCH == 'fun':
c = ParsePropositionalEquivalence(s)
if c:
return {'conjunction': {'conjunct': [c]}}
c = ParsePropositionalImplication(s)
if c:
return {'conjunction': {'conjunct': [c]}}
c = ParseImplication(s)
if c:
raise ParsingException('If-then-else clause is only supported as an '
'expression, not as a proposition.', s)
c = ParseCall(s, is_aggregation_allowed=False)
if c:
return {'predicate': c}
c = ParseInfix(s, operators=['&&', '||'])
if c:
return {'predicate': c}
c = ParseUnification(s)
if c:
return {'unification': c}
c = ParseInclusion(s)
if c:
return {'inclusion': c}
c = ParseConciseCombine(s)
if c:
return {'unification': c} # x f= (...) parses to x == (combine f= ...)
c = ParseInfix(s)
if c:
return {'predicate': c}
c = ParseNegation(s)
if c:
return c # ParseNegation returns a proposition.
raise ParsingException('Could not parse proposition.', s)
def ParseConjunction(s, allow_singleton=False):
str_conjuncts = Split(s, ',')
if len(str_conjuncts) == 1 and not allow_singleton:
return None
conjuncts = []
for c in str_conjuncts:
c = ParseProposition(c)
conjuncts.append(c)
return {'conjunct': conjuncts}
def ParseDisjunction(s):
str_disjuncts = Split(s, '|')
if len(str_disjuncts) == 1:
return None
disjuncts = []
for d in str_disjuncts:
d = ParseProposition(d)
disjuncts.append(d)
return {'disjunct': disjuncts}
def ParsePropositionalImplication(s):
str_implicants = Split(s, '=>')