-
Notifications
You must be signed in to change notification settings - Fork 390
/
transformer.py
2765 lines (2163 loc) · 108 KB
/
transformer.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
##
# Copyright (c) 2008-2012 MagicStack Inc.
# All rights reserved.
#
# See LICENSE for details.
##
import collections
import itertools
from edgedb.lang.ir import ast as irast
from edgedb.lang.ir import utils as irutils
from edgedb.lang.ir.utils import LinearPath
from edgedb.lang.schema import atoms as s_atoms
from edgedb.lang.schema import concepts as s_concepts
from edgedb.lang.schema import expr as s_expr
from edgedb.lang.schema import hooks as s_hooks
from edgedb.lang.schema import links as s_links
from edgedb.lang.schema import lproperties as s_lprops
from edgedb.lang.schema import name as sn
from edgedb.lang.schema import objects as s_obj
from edgedb.lang.schema import pointers as s_pointers
from edgedb.lang.schema import types as s_types
from edgedb.lang.common import exceptions as edgedb_error
from edgedb.lang.common.algos import boolean
from edgedb.lang.common import datastructures, ast, debug, markup
from edgedb.lang.common.datastructures import Void
from edgedb.lang.common.functional import checktypes
class PathIndex(dict):
"""
Graph path mapping path identifiers to AST nodes
"""
def update(self, other):
for k, v in other.items():
if k in self:
super().__getitem__(k).update(v)
else:
self[k] = v
def __setitem__(self, key, value):
if not isinstance(key, (LinearPath, str)):
raise TypeError('Invalid key type for PathIndex: %s' % key)
if not isinstance(value, set):
value = {value}
super().__setitem__(key, value)
"""
def __getitem__(self, key):
result = set()
for k, v in self.items():
if k == key:
result.update(v)
if not result:
raise KeyError
return result
"""
"""
def __contains__(self, key):
for k in self.keys():
if k == key:
return True
return False
"""
class TreeError(edgedb_error.EdgeDBError):
pass
@checktypes
class TreeTransformer:
def extract_prefixes(self, expr, prefixes=None):
prefixes = prefixes if prefixes is not None else PathIndex()
if isinstance(expr, irast.PathCombination):
for path in expr.paths:
self.extract_prefixes(path, prefixes)
elif isinstance(expr, (irast.EntitySet, irast.AtomicRefSimple)):
key = expr.get_id()
if key:
# XXX AtomicRefs with PathCombinations in ref don't have an id
if key not in prefixes:
prefixes[key] = {expr}
else:
prefixes[key].add(expr)
if isinstance(expr, irast.EntitySet) and expr.rlink:
self.extract_prefixes(expr.rlink.source, prefixes)
elif isinstance(expr, irast.AtomicRefSimple):
self.extract_prefixes(expr.ref, prefixes)
elif isinstance(expr, irast.EntityLink):
self.extract_prefixes(expr.target or expr.source, prefixes)
elif isinstance(expr, irast.LinkPropRefSimple):
self.extract_prefixes(expr.ref, prefixes)
elif isinstance(expr, irast.BinOp):
self.extract_prefixes(expr.left, prefixes)
self.extract_prefixes(expr.right, prefixes)
elif isinstance(expr, irast.UnaryOp):
self.extract_prefixes(expr.expr, prefixes)
elif isinstance(expr, irast.ExistPred):
self.extract_prefixes(expr.expr, prefixes)
elif isinstance(expr, (irast.InlineFilter, irast.InlinePropFilter)):
self.extract_prefixes(expr.ref, prefixes)
self.extract_prefixes(expr.expr, prefixes)
elif isinstance(expr, (irast.AtomicRefExpr, irast.LinkPropRefExpr)):
self.extract_prefixes(expr.expr, prefixes)
elif isinstance(expr, irast.FunctionCall):
for arg in expr.args:
self.extract_prefixes(arg, prefixes)
for sortexpr in expr.agg_sort:
self.extract_prefixes(sortexpr.expr, prefixes)
if expr.agg_filter:
self.extract_prefixes(expr.agg_filter, prefixes)
for partition_expr in expr.partition:
self.extract_prefixes(partition_expr, prefixes)
elif isinstance(expr, irast.TypeCast):
self.extract_prefixes(expr.expr, prefixes)
elif isinstance(expr, irast.NoneTest):
self.extract_prefixes(expr.expr, prefixes)
elif isinstance(expr, (irast.Sequence, irast.Record)):
for path in expr.elements:
self.extract_prefixes(path, prefixes)
elif isinstance(expr, irast.Constant):
pass
elif isinstance(expr, irast.GraphExpr):
pass
"""
if expr.generator:
self.extract_prefixes(expr.generator)
if expr.selector:
for e in expr.selector:
self.extract_prefixes(e.expr, prefixes)
if expr.grouper:
for e in expr.grouper:
self.extract_prefixes(e, prefixes)
if expr.sorter:
for e in expr.sorter:
self.extract_prefixes(e, prefixes)
"""
elif isinstance(expr, irast.SubgraphRef):
self.extract_prefixes(expr.ref, prefixes)
else:
assert False, 'unexpected node: "%r"' % expr
return prefixes
def apply_fixups(self, expr):
"""A rather dumb pass that attempts to fixup potential brokenness of a fully processed tree.
"""
if isinstance(expr, irast.PathCombination):
for path in expr.paths:
self.apply_fixups(path)
elif isinstance(expr, irast.AtomicRefSimple):
self.apply_fixups(expr.ref)
elif isinstance(expr, irast.EntitySet):
if expr.rlink:
self.apply_fixups(expr.rlink.source)
if expr.conjunction.paths:
# Move non-filtering paths out of a conjunction into a disjunction where
# it belongs.
cpaths = set()
dpaths = set()
for path in expr.conjunction.paths:
if isinstance(path, irast.EntitySet):
if 'generator' not in path.users:
dpaths.add(path)
else:
cpaths.add(path)
elif isinstance(path, irast.EntityLink):
if path.target and 'generator' not in path.target.users \
and 'generator' not in path.users:
dpaths.add(path)
else:
cpaths.add(path)
expr.conjunction.paths = frozenset(cpaths)
if dpaths:
expr.disjunction.paths = expr.disjunction.paths | dpaths
elif isinstance(expr, irast.EntityLink):
if expr.source is not None:
self.apply_fixups(expr.source)
elif isinstance(expr, irast.LinkPropRefSimple):
self.apply_fixups(expr.ref)
elif isinstance(expr, irast.BinOp):
self.apply_fixups(expr.left)
self.apply_fixups(expr.right)
elif isinstance(expr, irast.UnaryOp):
self.apply_fixups(expr.expr)
elif isinstance(expr, irast.ExistPred):
self.apply_fixups(expr.expr)
elif isinstance(expr, (irast.InlineFilter, irast.InlinePropFilter)):
self.apply_fixups(expr.ref)
self.apply_fixups(expr.expr)
elif isinstance(expr, (irast.AtomicRefExpr, irast.LinkPropRefExpr)):
self.apply_fixups(expr.expr)
elif isinstance(expr, irast.FunctionCall):
for arg in expr.args:
self.apply_fixups(arg)
for sortexpr in expr.agg_sort:
self.apply_fixups(sortexpr.expr)
if expr.agg_filter:
self.apply_fixups(expr.agg_filter)
for partition_expr in expr.partition:
self.apply_fixups(partition_expr)
elif isinstance(expr, irast.TypeCast):
self.apply_fixups(expr.expr)
elif isinstance(expr, irast.NoneTest):
self.apply_fixups(expr.expr)
elif isinstance(expr, (irast.Sequence, irast.Record)):
for path in expr.elements:
self.apply_fixups(path)
elif isinstance(expr, irast.Constant):
pass
elif isinstance(expr, irast.GraphExpr):
if expr.generator:
self.apply_fixups(expr.generator)
if expr.selector:
for e in expr.selector:
self.apply_fixups(e.expr)
if expr.grouper:
for e in expr.grouper:
self.apply_fixups(e)
if expr.sorter:
for e in expr.sorter:
self.apply_fixups(e)
if expr.set_op:
self.apply_fixups(expr.set_op_larg)
self.apply_fixups(expr.set_op_rarg)
elif isinstance(expr, irast.SortExpr):
self.apply_fixups(expr.expr)
elif isinstance(expr, irast.SubgraphRef):
self.apply_fixups(expr.ref)
else:
assert False, 'unexpected node: "%r"' % expr
def _apply_rewrite_hooks(self, expr, type):
sources = []
ln = None
if isinstance(expr, irast.EntitySet):
sources = [expr.concept]
elif isinstance(expr, irast.EntityLink):
ln = expr.link_proto.normal_name()
if expr.source.concept.is_virtual:
schema = self.context.current.proto_schema
for c in expr.source.concept.children(schema):
if ln in c.pointers:
sources.append(c)
else:
sources = [expr.source.concept]
else:
raise TypeError('unexpected node to _apply_rewrite_hooks: {!r}'.format(expr))
for source in sources:
mro = source.get_mro()
mro = [cls for cls in mro if isinstance(cls, s_obj.ProtoObject)]
for proto in mro:
if ln:
key = (proto.name, ln)
else:
key = proto.name
try:
hooks = s_hooks._rewrite_hooks[key, 'read', type]
except KeyError:
pass
else:
for hook in hooks:
result = hook(self.context.current.graph, expr,
self.context.current.context_vars)
if result:
self.apply_rewrites(result)
break
else:
continue
break
else:
if isinstance(expr, irast.EntityLink):
if type == 'computable' and expr.link_proto.is_pure_computable():
deflt = expr.link_proto.default[0]
if isinstance(deflt, s_expr.ExpressionText):
edgeql_expr = deflt
else:
edgeql_expr = "'" + str(deflt).replace("'", "''") + "'"
target_type = expr.link_proto.target.name
edgeql_expr = 'CAST ({} AS [{}])'.format(edgeql_expr, target_type)
anchors = {'self': expr.source.concept}
self._rewrite_with_edgeql_expr(expr, edgeql_expr, anchors)
def _rewrite_with_edgeql_expr(self, expr, edgeql_expr, anchors):
from edgedb.lang import edgeql
schema = self.context.current.proto_schema
ir = edgeql.compile_fragment_to_ir(edgeql_expr, schema,
anchors=anchors)
node = expr.source
rewrite_target = expr.target
path_id = LinearPath([node.concept])
nodes = ast.find_children(ir,
lambda n: isinstance(n, irast.EntitySet) and n.id == path_id)
for expr_node in nodes:
expr_node.reference = node
ptrname = expr.link_proto.normal_name()
expr_ref = irast.SubgraphRef(name=ptrname, force_inline=True, rlink=expr,
is_rewrite_product=True, rewrite_original=rewrite_target)
self.context.current.graph.replace_refs([rewrite_target], expr_ref, deep=True)
if not isinstance(ir, irast.GraphExpr):
ir = irast.GraphExpr(
selector = [
irast.SelectorExpr(expr=ir, name=ptrname)
]
)
ir.referrers.append('exists')
ir.referrers.append('generator')
self.context.current.graph.subgraphs.add(ir)
expr_ref.ref = ir
def apply_rewrites(self, expr):
"""Apply rewrites from policies
"""
if isinstance(expr, irast.PathCombination):
for path in expr.paths:
self.apply_rewrites(path)
elif isinstance(expr, irast.AtomicRefSimple):
if expr.rlink is not None:
self.apply_rewrites(expr.rlink)
self.apply_rewrites(expr.ref)
elif isinstance(expr, irast.EntitySet):
if expr.rlink:
self.apply_rewrites(expr.rlink)
if ('access_rewrite' not in expr.rewrite_flags and expr.reference is None
and expr.origin is None
and getattr(self.context.current, 'apply_access_control_rewrite', False)):
self._apply_rewrite_hooks(expr, 'filter')
expr.rewrite_flags.add('access_rewrite')
elif isinstance(expr, irast.EntityLink):
if expr.source is not None:
self.apply_rewrites(expr.source)
if 'lang_rewrite' not in expr.rewrite_flags:
schema = self.context.current.proto_schema
localizable = schema.get('std.localizable', default=None)
link_proto = expr.link_proto
if localizable is not None and link_proto.issubclass(localizable):
cvars = self.context.current.context_vars
lang = irast.Constant(index='__context_lang',
type=schema.get('std.str'))
cvars['lang'] = 'en-US'
propn = sn.Name('std.lang')
for langprop in expr.proprefs:
if langprop.name == propn:
break
else:
lprop_proto = link_proto.pointers[propn]
langprop = irast.LinkPropRefSimple(name=propn, ref=expr,
ptr_proto=lprop_proto)
expr.proprefs.add(langprop)
eq_lang = irast.BinOp(left=langprop, right=lang, op=ast.ops.EQ)
lang_none = irast.NoneTest(expr=lang)
# Test for property emptiness is for LEFT JOIN cases
prop_none = irast.NoneTest(expr=langprop)
lang_prop_none = irast.BinOp(left=lang_none, right=prop_none, op=ast.ops.OR)
lang_test = irast.BinOp(left=lang_prop_none, right=eq_lang, op=ast.ops.OR,
strong=True)
expr.propfilter = self.extend_binop(expr.propfilter, lang_test)
expr.rewrite_flags.add('lang_rewrite')
if ('access_rewrite' not in expr.rewrite_flags and expr.source is not None
# An optimization to avoid applying filtering rewrite unnecessarily.
and expr.source.reference is None
and expr.source.origin is None
and getattr(self.context.current, 'apply_access_control_rewrite', False)):
self._apply_rewrite_hooks(expr, 'filter')
expr.rewrite_flags.add('access_rewrite')
if 'computable_rewrite' not in expr.rewrite_flags and expr.source is not None:
self._apply_rewrite_hooks(expr, 'computable')
expr.rewrite_flags.add('computable_rewrite')
elif isinstance(expr, irast.LinkPropRefSimple):
self.apply_rewrites(expr.ref)
elif isinstance(expr, irast.BinOp):
self.apply_rewrites(expr.left)
self.apply_rewrites(expr.right)
elif isinstance(expr, irast.UnaryOp):
self.apply_rewrites(expr.expr)
elif isinstance(expr, irast.ExistPred):
self.apply_rewrites(expr.expr)
elif isinstance(expr, (irast.InlineFilter, irast.InlinePropFilter)):
self.apply_rewrites(expr.ref)
self.apply_rewrites(expr.expr)
elif isinstance(expr, (irast.AtomicRefExpr, irast.LinkPropRefExpr)):
self.apply_rewrites(expr.expr)
elif isinstance(expr, irast.FunctionCall):
for arg in expr.args:
self.apply_rewrites(arg)
for sortexpr in expr.agg_sort:
self.apply_rewrites(sortexpr.expr)
if expr.agg_filter:
self.apply_rewrites(expr.agg_filter)
for partition_expr in expr.partition:
self.apply_rewrites(partition_expr)
elif isinstance(expr, irast.TypeCast):
self.apply_rewrites(expr.expr)
elif isinstance(expr, irast.NoneTest):
self.apply_rewrites(expr.expr)
elif isinstance(expr, (irast.Sequence, irast.Record)):
for path in expr.elements:
self.apply_rewrites(path)
elif isinstance(expr, irast.Constant):
pass
elif isinstance(expr, irast.GraphExpr):
if expr.generator:
self.apply_rewrites(expr.generator)
if expr.selector:
for e in expr.selector:
self.apply_rewrites(e.expr)
if expr.grouper:
for e in expr.grouper:
self.apply_rewrites(e)
if expr.sorter:
for e in expr.sorter:
self.apply_rewrites(e)
if expr.set_op:
self.apply_rewrites(expr.set_op_larg)
self.apply_rewrites(expr.set_op_rarg)
elif isinstance(expr, irast.SortExpr):
self.apply_rewrites(expr.expr)
elif isinstance(expr, irast.SubgraphRef):
self.apply_rewrites(expr.ref)
else:
assert False, 'unexpected node: "%r"' % expr
def add_path_user(self, path, user):
while path:
path.users.add(user)
if isinstance(path, irast.EntitySet):
rlink = path.rlink
else:
rlink = path
if rlink:
rlink.users.add(user)
path = rlink.source
else:
path = None
return path
def entityref_to_record(self, expr, schema, *, pathspec=None,
prefixes=None, select_linkprops=False,
_visited_records=None, _recurse=True):
"""Convert an EntitySet node into an Record referencing eager-pointers of EntitySet concept
"""
if not isinstance(expr, irast.PathCombination):
expr = irast.Conjunction(paths=frozenset((expr,)))
p = next(iter(expr.paths))
if not isinstance(p, irast.EntitySet):
return expr
path_rlink = None
if _visited_records is None:
_visited_records = {}
if p.rlink is not None:
path_rlink = p.rlink
recurse_links = None
recurse_metarefs = ['id', 'name']
concepts = {c.concept for c in expr.paths}
assert len(concepts) == 1
elements = []
atomrefs = []
concept = p.concept
ref = p if len(expr.paths) == 1 else expr
rec = irast.Record(elements=elements, concept=concept, rlink=p.rlink)
_new_visited_records = _visited_records.copy()
if isinstance(concept, s_concepts.Concept):
_new_visited_records[concept] = rec
if concept.is_virtual:
ptrs = concept.get_children_common_pointers(schema)
ptrs = {ptr.normal_name(): ptr for ptr in ptrs}
ptrs.update(concept.pointers)
else:
ptrs = concept.pointers
if pathspec is not None:
must_have_links = (
sn.Name('std.id'),
sn.Name('std.mtime'),
sn.Name('std.ctime')
)
recurse_links = {(l, s_pointers.PointerDirection.Outbound):
irast.PtrPathSpec(ptr_proto=ptrs[l]) for l in must_have_links}
for ps in pathspec:
if isinstance(ps.ptr_proto, s_links.Link):
recurse_links[ps.ptr_proto.normal_name(), ps.ptr_direction] = ps
elif isinstance(ps.ptr_proto, s_lprops.TypeProperty):
# metaref
recurse_metarefs.append(ps.ptr_proto.normal_name().name)
if recurse_links is None:
recurse_links = {(pn, s_pointers.PointerDirection.Outbound):
irast.PtrPathSpec(ptr_proto=p)
for pn, p in ptrs.items()
if p.get_loading_behaviour() == s_pointers.PointerLoading.Eager and
p.target not in _visited_records}
for (link_name, link_direction), recurse_spec in recurse_links.items():
el = None
link = recurse_spec.ptr_proto
link_direction = recurse_spec.ptr_direction or s_pointers.PointerDirection.Outbound
root_link_proto = schema.get(link_name)
link_proto = link
if link_direction == s_pointers.PointerDirection.Outbound:
link_target_proto = link.target
link_singular = \
link.mapping in {s_links.LinkMapping.OneToOne,
s_links.LinkMapping.ManyToOne}
else:
link_target_proto = link.source
link_singular = \
link.mapping in {s_links.LinkMapping.OneToOne,
s_links.LinkMapping.OneToMany}
if recurse_spec.target_proto is not None:
target_proto = recurse_spec.target_proto
else:
target_proto = link_target_proto
recurse_link = recurse_spec.recurse if recurse_spec is not None else None
full_path_id = LinearPath(ref.id)
full_path_id.add(link_proto, link_direction, target_proto)
if not link_singular or recurse_link is not None:
lref = self.copy_path(ref, connect_to_origin=True)
lref.reference = ref
else:
lref = ref
if recurse_link is not None:
lref.rlink = None
if prefixes and full_path_id in prefixes and lref is ref:
targetstep = prefixes[full_path_id]
targetstep = next(iter(targetstep))
link_node = targetstep.rlink
reusing_target = True
else:
targetstep = irast.EntitySet(conjunction=irast.Conjunction(),
disjunction=irast.Disjunction(),
users={self.context.current.location},
concept=target_proto, id=full_path_id)
link_node = irast.EntityLink(source=lref, target=targetstep,
link_proto=link_proto,
direction=link_direction,
users={'selector'})
targetstep.rlink = link_node
reusing_target = False
if recurse_spec.trigger is not None:
link_node.pathspec_trigger = recurse_spec.trigger
if not link.atomic():
lref.conjunction.update(link_node)
filter_generator = None
sorter = []
newstep = targetstep
if recurse_link is not None:
newstep = lref
if recurse_spec.generator is not None:
filter_generator = recurse_spec.generator
if recurse_spec.sorter:
sort_source = newstep
for sortexpr in recurse_spec.sorter:
sortpath = sortexpr.expr
sort_target = self.copy_path(sortpath)
if isinstance(sortpath, irast.LinkPropRef):
if sortpath.ref.link_proto.normal_name() == link_node.link_proto.normal_name():
sort_target.ref = link_node
link_node.proprefs.add(sort_target)
else:
raise ValueError('Cannot sort by property ref of link other than self')
else:
sortpath_link = sortpath.rlink
sort_target.ref = sort_source
sort_link = irast.EntityLink(source=sort_source,
target=sort_target,
link_proto=sortpath_link.link_proto,
direction=sortpath_link.direction,
users=sortpath_link.users.copy())
sort_target.rlink = sort_link
sort_source.atomrefs.add(sort_target)
sorter.append(irast.SortExpr(expr=sort_target,
direction=sortexpr.direction,
nones_order=sortexpr.nones_order))
if isinstance(target_proto, s_atoms.Atom):
if link_singular:
if not reusing_target:
newstep = irast.AtomicRefSimple(ref=lref, name=link_name,
id=full_path_id,
ptr_proto=link_proto,
rlink=link_node,
users=link_node.users.copy())
link_node.target = newstep
atomrefs.append(newstep)
else:
ptr_name = sn.Name('std.target')
prop_id = LinearPath(ref.id)
prop_id.add(root_link_proto, s_pointers.PointerDirection.Outbound, None)
prop_proto = link.pointers[ptr_name]
newstep = irast.LinkPropRefSimple(name=ptr_name, id=full_path_id,
ptr_proto=prop_proto)
el = newstep
else:
if _recurse:
_memo = _new_visited_records
if recurse_spec is not None and recurse_spec.recurse is not None:
_memo = {}
new_recurse = True
elif isinstance(recurse_spec.trigger, irast.ExplicitPathSpecTrigger):
new_recurse = True
elif newstep.concept not in _visited_records:
new_recurse = True
else:
new_recurse = False
recurse_pathspec = recurse_spec.pathspec if recurse_spec is not None \
else None
el = self.entityref_to_record(newstep, schema,
pathspec=recurse_pathspec,
_visited_records=_memo,
_recurse=new_recurse)
prop_elements = []
if link.has_user_defined_properties():
if recurse_spec.pathspec is not None:
must_have_props = (
sn.Name('std.linkid'),
)
recurse_props = {propn: irast.PtrPathSpec(ptr_proto=link.pointers[propn])
for propn in must_have_props}
for ps in recurse_spec.pathspec:
if (isinstance(ps.ptr_proto, s_lprops.LinkProperty)
and not ps.ptr_proto.is_endpoint_pointer()):
recurse_props[ps.ptr_proto.normal_name()] = ps
else:
recurse_props = {pn: irast.PtrPathSpec(ptr_proto=p)
for pn, p in link.pointers.items()
if p.get_loading_behaviour() == s_pointers.PointerLoading.Eager
and not p.is_endpoint_pointer()}
proprec = irast.Record(elements=prop_elements, concept=root_link_proto)
for prop_name, prop_proto in link.pointers.items():
if prop_name not in recurse_props:
continue
prop_id = LinearPath(ref.id)
prop_id.add(root_link_proto, s_pointers.PointerDirection.Outbound, None)
prop_ref = irast.LinkPropRefSimple(name=prop_name, id=full_path_id,
ptr_proto=prop_proto,
ref=link_node)
prop_elements.append(prop_ref)
link_node.proprefs.add(prop_ref)
if prop_elements:
xvalue_elements = [el, proprec]
if isinstance(link_node.target, irast.AtomicRefSimple):
ln = link_node.link_proto.normal_name()
concept = link_node.source.concept.pointers[ln]
else:
concept = link_node.target.concept
el = irast.Record(elements=xvalue_elements,
concept=concept,
rlink=link_node, linkprop_xvalue=True)
if not link.atomic() or prop_elements:
lref.conjunction.update(link_node)
if isinstance(newstep, irast.LinkPropRefSimple):
newstep.ref = link_node
lref.disjunction.update(link_node)
if (not link_singular or recurse_spec.recurse is not None) and el is not None:
if link.atomic():
link_node.proprefs.add(newstep)
generator = irast.Conjunction(paths=frozenset((targetstep,)))
if filter_generator is not None:
ref_gen = irast.Conjunction(paths=frozenset((targetstep,)))
generator.paths = frozenset(generator.paths | {filter_generator})
generator = self.merge_paths(generator)
# merge_paths fails to update all refs, because
# some nodes that need to be updated are behind
# non-traversable rlink attribute. Do the
# proper update manually. Also, make sure
# aggregate_result below gets a correct ref.
#
new_targetstep = next(iter(ref_gen.paths))
if new_targetstep != targetstep:
el.replace_refs([targetstep], new_targetstep,
deep=True)
for elem in el.elements:
try:
rlink = elem.rlink
except AttributeError:
pass
else:
if rlink:
rlink.replace_refs([targetstep],
new_targetstep,
deep=True)
targetstep = new_targetstep
subgraph = irast.GraphExpr()
subgraph.generator = generator
subgraph.aggregate_result = irast.FunctionCall(name=('agg', 'list'),
aggregates=True,
args=[targetstep])
if sorter:
subgraph.sorter = sorter
subgraph.offset = recurse_spec.offset
subgraph.limit = recurse_spec.limit
if recurse_spec.recurse is not None:
subgraph.recurse_link = link_node
subgraph.recurse_depth = recurse_spec.recurse
selexpr = irast.SelectorExpr(expr=el, name=link_name)
subgraph.selector.append(selexpr)
el = irast.SubgraphRef(ref=subgraph, name=link_name, rlink=link_node)
# Record element may be none if link target is non-atomic and
# recursion has been prohibited on this level to prevent infinite looping.
if el is not None:
elements.append(el)
metarefs = []
for metaref in recurse_metarefs:
metarefs.append(irast.MetaRef(name=metaref, ref=ref))
for p in expr.paths:
p.atomrefs.update(atomrefs)
p.metarefs.update(metarefs)
elements.extend(metarefs)
expr = rec
if path_rlink is not None and select_linkprops:
# Linked selector paths must fetch links pointing to it
link_node = path_rlink
link = path_rlink.link_proto
root_link_proto = schema.get(link.normal_name())
recurse_props = {pn: irast.PtrPathSpec(ptr_proto=p)
for pn, p in link.pointers.items()
if p.get_loading_behaviour() == s_pointers.PointerLoading.Eager
and not p.is_endpoint_pointer()}
prop_elements = []
proprec = irast.Record(elements=prop_elements,
concept=root_link_proto)
for prop_name, prop_proto in link.pointers.items():
if prop_name not in recurse_props:
continue
prop_id = LinearPath(ref.id)
prop_id.add(root_link_proto, s_pointers.PointerDirection.Outbound, None)
prop_ref = irast.LinkPropRefSimple(name=prop_name,
id=p.id,
ptr_proto=prop_proto,
ref=link_node)
prop_elements.append(prop_ref)
link_node.proprefs.add(prop_ref)
xvalue_elements = [expr, proprec]
if isinstance(link_node.target, irast.AtomicRefSimple):
ln = link_node.link_proto.normal_name()
concept = link_node.source.concept.pointers[ln]
else:
concept = link_node.target.concept
expr = irast.Record(elements=xvalue_elements,
concept=concept,
rlink=link_node, linkprop_xvalue=True)
return expr
def entityref_to_idref(self, expr, schema):
p = next(iter(expr.paths))
if isinstance(p, irast.EntitySet):
concepts = {c.concept for c in expr.paths}
assert len(concepts) == 1
ref = p if len(expr.paths) == 1 else expr
link_name = sn.Name('std.id')
link_proto = schema.get(link_name)
target_proto = link_proto.target
id = LinearPath(ref.id)
id.add(link_proto, s_pointers.PointerDirection.Outbound, target_proto)
expr = irast.AtomicRefSimple(ref=ref, name=link_name, id=id, ptr_proto=link_proto)
return expr
def _normalize_pathspec_recursion(self, pathspec, source, proto_schema):
for ptrspec in pathspec:
if ptrspec.recurse is not None:
# Push the looping spec one step down so that the loop starts on the first
# pointer target, not the source.
#
if ptrspec.pathspec is None:
ptrspec.pathspec = []
for ptr in ptrspec.target_proto.pointers.values():
if ptr.get_loading_behaviour() == s_pointers.PointerLoading.Eager:
ptrspec.pathspec.append(irast.PtrPathSpec(ptr_proto=ptr))
recspec = irast.PtrPathSpec(ptr_proto=ptrspec.ptr_proto,
ptr_direction=ptrspec.ptr_direction,
recurse=ptrspec.recurse,
target_proto=ptrspec.target_proto,
generator=ptrspec.generator,
sorter=ptrspec.sorter,
limit=ptrspec.limit,
offset=ptrspec.offset,
pathspec=ptrspec.pathspec[:])
for i, subptrspec in enumerate(ptrspec.pathspec):
if subptrspec.ptr_proto.normal_name() == ptrspec.ptr_proto.normal_name():
ptrspec.pathspec[i] = recspec
break
else:
ptrspec.pathspec.append(recspec)
ptrspec.recurse = None
ptrspec.sorter = []
def _merge_pathspecs(self, pathspec1, pathspec2, target_most_generic=True):
merged_right = set()
if not pathspec1:
return pathspec2
if not pathspec2:
return pathspec1
result = []
for item1 in pathspec1:
item1_subspec = item1.pathspec
item1_lname = item1.ptr_proto.normal_name()
item1_ldir = item1.ptr_direction
for i, item2 in enumerate(pathspec2):
if i in merged_right:
continue