34
35:- module(prolog_call_cycles,
36 [ call_graph/2, 37 call_graph_sccs/2, 38 call_graph_sccs/3, 39 left_recursion/2, 40 left_recursion/3 41 ]). 42:- use_module(library(prolog_codewalk), [prolog_walk_code/1]). 43:- use_module(library(apply),
44 [maplist/2, maplist/3, foldl/4, include/3, exclude/3]). 45:- use_module(library(assoc),
46 [ empty_assoc/1, get_assoc/3, put_assoc/4, list_to_assoc/2,
47 assoc_to_keys/2
48 ]). 49:- use_module(library(lists),
50 [ member/2, append/3, append/2, list_to_set/2, reverse/2
51 ]). 52:- use_module(library(option), [option/2, option/3, meta_options/3]). 53:- use_module(library(pairs),
54 [pairs_keys/2, pairs_values/2, group_pairs_by_key/2]). 55:- use_module(library(ugraphs), [vertices_edges_to_ugraph/3]). 56:- use_module(library(error), [must_be/2, domain_error/2]). 57:- use_module(library(ordsets), [ord_intersection/3]). 58:- autoload(library(dif), [dif/2]). 59
60:- meta_predicate
61 call_graph(-, :),
62 call_graph_sccs(-, :),
63 left_recursion(-, :). 64
144
145:- predicate_options(call_graph/2, 2,
146 [ goal(callable),
147 files(any),
148 module(any),
149 predicates(list),
150 external(boolean),
151 pass_to(prolog_codewalk:prolog_walk_code/1, 1)
152 ]). 153
176
177call_graph(Graph, Options0) :-
178 meta_options(is_meta, Options0, Options),
179 walk_options(Options, WalkOptions),
180 scope(Options, WalkOptions, Vertices, Clauses),
181 list_to_assoc_set(Vertices, VSet),
182 option(external(External), Options, false),
183 State = state([], []),
184 ( Clauses == []
185 -> true
186 ; prolog_walk_code([ clauses(Clauses),
187 trace_reference(_),
188 on_edge(collect_edge(VSet, External, State))
189 | WalkOptions
190 ])
191 ),
192 arg(1, State, RevEdges),
193 arg(2, State, RevExt),
194 reverse(RevEdges, Edges),
195 reverse(RevExt, Ext),
196 maplist(edge_pair, Edges, Pairs),
197 vertices_edges_to_ugraph(Vertices, Pairs, UGraph),
198 Graph = call_graph{vertices:Vertices, ugraph:UGraph,
199 edges:Edges, external:Ext}.
200
201is_meta(goal).
202
203edge_pair(Edge, Edge.from-Edge.to).
204
205:- public collect_edge/6. 206
207collect_edge(VSet, External, State, Callee, Caller, Location) :-
208 callee_pi(Callee, ToPI),
209 goal_pi(Caller, FromPI),
210 ( get_assoc(ToPI, VSet, _)
211 -> E = edge{from:FromPI, to:ToPI, clause:Clause, location:Location},
212 clause_of_location(Location, Clause),
213 arg(1, State, L0),
214 nb_setarg(1, State, [E|L0])
215 ; External == true
216 -> E = edge{from:FromPI, to:ToPI, clause:Clause, location:Location,
217 goal:Callee},
218 clause_of_location(Location, Clause),
219 arg(2, State, L0),
220 nb_setarg(2, State, [E|L0])
221 ; true
222 ).
223
224clause_of_location(Location, Clause) :-
225 ( get_dict(clause, Location, Clause0)
226 -> Clause = Clause0
227 ; Clause = (-)
228 ).
229
230callee_pi(M:Goal, PI) :-
231 callable(Goal),
232 ( predicate_property(M:Goal, imported_from(IM))
233 -> true
234 ; IM = M
235 ),
236 goal_pi(IM:Goal, PI).
237
238goal_pi(M:Goal, M:Name/Arity) :-
239 callable(Goal),
240 !,
241 functor(Goal, Name, Arity).
242goal_pi(Goal, Goal).
243
244walk_options(Options, WalkOptions) :-
245 exclude(own_option, Options, WalkOptions0),
246 ( option(source(_), WalkOptions0)
247 -> WalkOptions = WalkOptions0
248 ; WalkOptions = [source(false)|WalkOptions0]
249 ).
250
251own_option(goal(_)).
252own_option(files(_)).
253own_option(module(_)).
254own_option(predicates(_)).
255own_option(external(_)).
256own_option(clauses(_)).
257own_option(trace_reference(_)).
258own_option(on_edge(_)).
259own_option(on_trace(_)).
260own_option(locations(_)).
261
266
267scope(Options, WalkOptions, Vertices, Clauses) :-
268 option(goal(Goal), Options),
269 !,
270 goal_scope(Goal, Options, WalkOptions, Vertices, Clauses).
271scope(Options, _, Vertices, Clauses) :-
272 option(files(Files), Options),
273 !,
274 abs_files(Files, AbsFiles),
275 findall(PI-Ref,
276 ( member(File, AbsFiles),
277 source_file_clause(File, PI, Ref)
278 ), Pairs0),
279 findall(PI-(-),
280 ( member(File, AbsFiles),
281 ( source_file_dynamic(File, PI)
282 ; source_file_foreign(File, PI)
283 )
284 ), DynPairs),
285 append(Pairs0, DynPairs, Pairs),
286 scope_from_pairs(Pairs, Vertices, Clauses).
287scope(Options, _, Vertices, Clauses) :-
288 option(module(Modules), Options),
289 !,
290 modules(Modules, Ms),
291 findall(M:Name/Arity,
292 ( member(M, Ms),
293 current_predicate(M:Name/Arity),
294 functor(Head, Name, Arity),
295 \+ predicate_property(M:Head, imported_from(_))
296 ), PIs),
297 pis_scope(PIs, Vertices, Clauses).
298scope(Options, _, Vertices, Clauses) :-
299 option(predicates(PIs), Options),
300 !,
301 must_be(list, PIs),
302 pis_scope(PIs, Vertices, Clauses).
303scope(_, _, _, _) :-
304 domain_error(call_graph_scope, none).
305
306abs_files(Files0, AbsFiles) :-
307 ( is_list(Files0) -> Files = Files0 ; Files = [Files0] ),
308 maplist(absolute_source_file, Files, AbsFiles0),
309 findall(AbsFile,
310 ( member(File, AbsFiles0),
311 loading_file(File, AbsFile)
312 ), AbsFiles1),
313 sort(AbsFiles1, AbsFiles).
314
315modules(Modules, Ms) :-
316 ( is_list(Modules) -> Ms = Modules ; Ms = [Modules] ),
317 must_be(list(atom), Ms).
318
323
324goal_scope(Goal, Options, WalkOptions, Vertices, Clauses) :-
325 goal_filter(Options, Filter),
326 goal_roots(Goal, WalkOptions, Roots0),
327 include(in_goal_scope(Filter), Roots0, Roots),
328 list_to_assoc_set(Roots, Seen0),
329 reachable(Roots, Filter, WalkOptions, Seen0, Seen),
330 assoc_to_keys(Seen, Vertices),
331 findall(Ref,
332 ( member(PI, Vertices),
333 pi_clause(PI, Ref)
334 ), Clauses).
335
336goal_filter(Options, filter(Files, Modules)) :-
337 ( option(files(Files0), Options)
338 -> abs_files(Files0, Files)
339 ; Files = (-)
340 ),
341 ( option(module(Modules0), Options)
342 -> modules(Modules0, Modules)
343 ; Modules = (-)
344 ).
345
346in_goal_scope(filter(Files, Modules), PI) :-
347 PI = M:Name/Arity,
348 \+ module_property(M, class(system)),
349 ( Modules == (-)
350 -> true
351 ; memberchk(M, Modules)
352 ),
353 functor(Head, Name, Arity),
354 \+ predicate_property(M:Head, foreign),
355 \+ predicate_property(M:Head, imported_from(_)),
356 predicate_property(M:Head, number_of_clauses(N)),
357 N > 0,
358 ( Files == (-)
359 -> true
360 ; source_file(M:Head, File),
361 memberchk(File, Files)
362 -> true
363 ).
364
365:- dynamic
366 goal_clause/0. 367
373
374goal_roots(Goal, WalkOptions, Roots) :-
375 setup_call_cleanup(
376 assertz((goal_clause :- Goal), Ref),
377 callees([Ref], WalkOptions, Roots),
378 erase(Ref)).
379
384
385reachable([], _, _, Seen, Seen) :- !.
386reachable(Frontier, Filter, WalkOptions, Seen0, Seen) :-
387 findall(Ref,
388 ( member(PI, Frontier),
389 pi_clause(PI, Ref)
390 ), Refs),
391 callees(Refs, WalkOptions, Callees),
392 include(new_in_scope(Filter, Seen0), Callees, New),
393 foldl(add_seen, New, Seen0, Seen1),
394 reachable(New, Filter, WalkOptions, Seen1, Seen).
395
396new_in_scope(Filter, Seen, PI) :-
397 \+ get_assoc(PI, Seen, _),
398 in_goal_scope(Filter, PI).
399
400add_seen(PI, Seen0, Seen) :-
401 put_assoc(PI, Seen0, true, Seen).
402
406
407callees([], _, []) :- !.
408callees(Clauses, WalkOptions, PIs) :-
409 State = callees([]),
410 prolog_walk_code([ clauses(Clauses),
411 trace_reference(_),
412 on_edge(collect_callee(State))
413 | WalkOptions
414 ]),
415 arg(1, State, PIs0),
416 sort(PIs0, PIs).
417
418:- public collect_callee/4. 419
420collect_callee(State, Callee, _Caller, _Location) :-
421 ( callee_pi(Callee, PI)
422 -> arg(1, State, L0),
423 nb_setarg(1, State, [PI|L0])
424 ; true
425 ).
426
427pis_scope(PIs, Vertices, Clauses) :-
428 findall(PI-Ref,
429 ( member(PI, PIs),
430 pi_clause(PI, Ref)
431 ), Pairs0),
432 findall(PI-(-), member(PI, PIs), NoClause),
433 append(Pairs0, NoClause, Pairs),
434 scope_from_pairs(Pairs, Vertices, Clauses).
435
436scope_from_pairs(Pairs, Vertices, Clauses) :-
437 pairs_keys(Pairs, PIs),
438 sort(PIs, Vertices),
439 pairs_values(Pairs, Refs0),
440 exclude(==(-), Refs0, Refs1),
441 list_to_set(Refs1, Clauses).
442
443absolute_source_file(Spec, File) :-
444 ( atom(Spec),
445 is_absolute_file_name(Spec),
446 loaded_or_included(Spec)
447 -> File = Spec
448 ; absolute_file_name(Spec, File,
449 [ file_type(prolog),
450 access(read)
451 ]),
452 loaded_or_included(File)
453 -> true
454 ; existence_error(source_file, Spec)
455 ).
456
457loaded_or_included(File) :-
458 ( source_file(File)
459 -> true
460 ; source_file_property(File, included_in(_, _))
461 -> true
462 ).
463
468
469loading_file(File, File) :-
470 source_file(File),
471 !.
472loading_file(File, Loaded) :-
473 loading_file(File, [File], Loaded).
474
475loading_file(File, Visited, Loaded) :-
476 source_file_property(File, included_in(Parent, _)),
477 \+ memberchk(Parent, Visited),
478 ( source_file(Parent)
479 -> Loaded = Parent
480 ; loading_file(Parent, [Parent|Visited], Loaded)
481 ).
482
483source_file_clause(File, M:Name/Arity, Ref) :-
484 source_file(M:Head, File),
485 M \== system, 486 \+ predicate_property(M:Head, imported_from(_)),
487 functor(Head, Name, Arity),
488 \+ predicate_property(M:Head, foreign),
489 catch(clause(M:Head, _, Ref), _, fail),
490 clause_property(Ref, source(File)).
491
496
497source_file_dynamic(File, M:Name/Arity) :-
498 source_file(M:Head, File),
499 M \== system,
500 \+ predicate_property(M:Head, imported_from(_)),
501 predicate_property(M:Head, dynamic),
502 functor(Head, Name, Arity).
503
510
511source_file_foreign(File, M:Name/Arity) :-
512 current_module(M),
513 module_property(M, file(File)),
514 M \== system,
515 current_predicate(M:Name/Arity),
516 functor(Head, Name, Arity),
517 predicate_property(M:Head, foreign),
518 \+ predicate_property(M:Head, imported_from(_)).
519
520pi_clause(PI, Ref) :-
521 PI = M:Name/Arity,
522 functor(Head, Name, Arity),
523 \+ predicate_property(M:Head, foreign),
524 catch(clause(M:Head, _, Ref), _, fail).
525
526list_to_assoc_set(List, Assoc) :-
527 findall(K-true, member(K, List), Pairs),
528 list_to_assoc(Pairs, Assoc).
529
530existence_error(Type, Obj) :-
531 throw(error(existence_error(Type, Obj), _)).
532
533
534 537
592
593call_graph_sccs(SCCs, Options0) :-
594 meta_options(is_meta, Options0, Options),
595 call_graph(Graph, Options),
596 call_graph_sccs(Graph, SCCs, Options).
597
598call_graph_sccs(Graph, SCCs, Options) :-
599 ugraph_sccs(Graph.ugraph, Components),
600 include(cyclic_component(Graph.ugraph), Components, Cyclic),
601 maplist(component_scc(Graph, Options), Cyclic, SCCs).
602
603cyclic_component(_, [_,_|_]) :- !.
604cyclic_component(UGraph, [V]) :-
605 memberchk(V-Ns, UGraph),
606 memberchk(V, Ns).
607
608component_scc(Graph, Options, Members0, scc{members:Members, edges:Edges}) :-
609 sort(Members0, Members),
610 list_to_assoc_set(Members, MSet),
611 include(internal_edge(MSet), Graph.edges, Edges0),
612 refine_locations(Edges0, Edges1, Options),
613 annotate_edges(Edges1, Edges).
614
615internal_edge(MSet, Edge) :-
616 get_assoc(Edge.from, MSet, _),
617 get_assoc(Edge.to, MSet, _).
618
624
625ugraph_sccs(UGraph, SCCs) :-
626 empty_assoc(Index0),
627 foldl(scc_vertex(UGraph), UGraph,
628 t(0, Index0, [], []), t(_, _, _, RevSCCs)),
629 reverse(RevSCCs, SCCs).
630
631scc_vertex(UGraph, V-_, S0, S) :-
632 S0 = t(_, Index, _, _),
633 ( get_assoc(V, Index, _)
634 -> S = S0
635 ; strongconnect(V, UGraph, S0, S, _)
636 ).
637
640
641strongconnect(V, UGraph, t(N0, Index0, Stack0, SCCs0), S, Low) :-
642 put_assoc(V, Index0, i(N0, N0, true), Index1),
643 N1 is N0+1,
644 memberchk(V-Succs, UGraph),
645 foldl(scc_succ(V, UGraph), Succs,
646 t(N1, Index1, [V|Stack0], SCCs0)-N0,
647 t(N2, Index2, Stack2, SCCs2)-Low),
648 ( Low =:= N0
649 -> pop_scc(V, Stack2, Stack3, Component, Index2, Index3),
650 S = t(N2, Index3, Stack3, [Component|SCCs2])
651 ; get_assoc(V, Index2, i(I, _, OS)),
652 put_assoc(V, Index2, i(I, Low, OS), Index3),
653 S = t(N2, Index3, Stack2, SCCs2)
654 ).
655
656scc_succ(_V, UGraph, W, S0-Low0, S-Low) :-
657 S0 = t(_, Index, _, _),
658 ( get_assoc(W, Index, i(WI, _, OnStack))
659 -> S = S0,
660 ( OnStack == true
661 -> Low is min(Low0, WI)
662 ; Low = Low0
663 )
664 ; strongconnect(W, UGraph, S0, S, WLow),
665 Low is min(Low0, WLow)
666 ).
667
668pop_scc(V, [W|Stack0], Stack, [W|Component], Index0, Index) :-
669 get_assoc(W, Index0, i(I, L, _)),
670 put_assoc(W, Index0, i(I, L, false), Index1),
671 ( W == V
672 -> Stack = Stack0,
673 Component = [],
674 Index = Index1
675 ; pop_scc(V, Stack0, Stack, Component, Index1, Index)
676 ).
677
678
679 682
689
690refine_locations(Edges0, Edges, Options) :-
691 option(locations(true), Options, true),
692 \+ option(source(true), Options),
693 findall(Ref, (member(E, Edges0), Ref = E.clause, Ref \== (-)), Refs0),
694 Refs0 \== [],
695 !,
696 sort(Refs0, Refs),
697 walk_options(Options, WalkOptions0),
698 exclude(source_option, WalkOptions0, WalkOptions),
699 State = state([]),
700 catch(prolog_walk_code([ clauses(Refs),
701 trace_reference(_),
702 source(true),
703 on_edge(collect_location(State))
704 | WalkOptions
705 ]),
706 _, true),
707 arg(1, State, RevLocs),
708 reverse(RevLocs, Locs),
709 number_calls(Locs, NLocs),
710 number_edge_calls(Edges0, NEdges),
711 maplist(refined_edge(NLocs), NEdges, Edges).
712refine_locations(Edges, Edges, _).
713
714source_option(source(_)).
715
716:- public collect_location/4. 717
718collect_location(State, Callee, _Caller, Location) :-
719 ( get_dict(clause, Location, Clause),
720 callee_pi(Callee, PI)
721 -> arg(1, State, L0),
722 nb_setarg(1, State, [loc(Clause, PI, Location)|L0])
723 ; true
724 ).
725
732
733number_calls(Locs, Numbered) :-
734 maplist(loc_key, Locs, Keyed),
735 number_from_end(Keyed, Numbered).
736
737loc_key(loc(Clause, PI, Location), (Clause-PI)-Location).
738
739number_edge_calls(Edges, Numbered) :-
740 maplist(edge_key, Edges, Keyed),
741 number_from_end(Keyed, Numbered).
742
743edge_key(Edge, (Edge.clause-Edge.to)-Edge).
744
750
751number_from_end(Keyed, Numbered) :-
752 reverse(Keyed, RevKeyed),
753 empty_assoc(C0),
754 foldl(number_keyed, RevKeyed, RevNumbered, C0, _),
755 reverse(RevNumbered, Numbered).
756
757number_keyed(Key-Value, (Key-N)-Value, C0, C) :-
758 ( get_assoc(Key, C0, N0) -> true ; N0 = 0 ),
759 N is N0+1,
760 put_assoc(Key, C0, N, C).
761
762refined_edge(NLocs, Key-Edge0, Edge) :-
763 ( memberchk(Key-Location, NLocs)
764 -> Edge = Edge0.put(location, Location)
765 ; Edge = Edge0
766 ).
767
768
769 772
780
781annotate_edges(Edges0, Edges) :-
782 number_edge_calls(Edges0, NEdges),
783 findall(Ref, (member(E, Edges0), Ref = E.clause), Refs0),
784 sort(Refs0, Refs),
785 commit_heads(Refs, Commits),
786 maplist(clause_calls(Commits), Refs, CallLists),
787 append(CallLists, Calls),
788 foldl(annotated_edge(Calls), NEdges, Edges1, []),
789 loop_keys(Edges1, LoopKeys),
790 maplist(final_edge(LoopKeys), Edges1, Edges).
791
792annotated_edge(Calls, Key-Edge0, Edges0, Edges) :-
793 ( memberchk(Key-call(Left, Args, Decreasing, T, Pruned, Barrier),
794 Calls)
795 -> Edges0 = [Key-T-Edge|Edges],
796 Edge = Edge0.put(#{left:Left, args:Args, decreasing:Decreasing,
797 pruned:Pruned, barrier:Barrier})
798 ; Key = (Clause-PI)-_,
799 memberchk((Clause-PI)-_-_, Calls)
800 -> Edges0 = Edges 801 ; Edges0 = [Key-T-Edge|Edges],
802 general_transition(Edge0, T),
803 Edge = Edge0.put(#{left:true, args:unknown, decreasing:false,
804 pruned:false, barrier:none})
805 ).
806
807final_edge(LoopKeys, Key-_-Edge0, Edge) :-
808 ( Edge0.left == true,
809 \+ get_assoc(Key, LoopKeys, _)
810 -> Edge = Edge0.put(left, false)
811 ; Edge = Edge0
812 ).
813
823
824commit_heads(Refs, Commits) :-
825 findall(PI,
826 ( member(Ref, Refs),
827 Ref \== (-),
828 catch(clause_property(Ref, predicate(PI)), _, fail)
829 ), PIs0),
830 sort(PIs0, PIs),
831 foldl(pred_commit_heads, PIs, Pairs, []),
832 list_to_assoc(Pairs, Commits).
833
834pred_commit_heads(M:Name/Arity, Pairs0, Pairs) :-
835 functor(Head, Name, Arity),
836 ( predicate_property(M:Head, ssu)
837 -> SSU = true
838 ; SSU = false
839 ),
840 findall(Ref-c(Head, Body), catch(clause(M:Head, Body, Ref), _, fail),
841 Clauses),
842 clause_commits(Clauses, SSU, [], Pairs0, Pairs).
843
844clause_commits([], _, _, Pairs, Pairs).
845clause_commits([Ref-c(Head, Body)|T], SSU, Earlier, [Ref-Earlier|Pairs0],
846 Pairs) :-
847 ( committing(SSU, Body)
848 -> Earlier1 = [Head|Earlier]
849 ; Earlier1 = Earlier
850 ),
851 clause_commits(T, SSU, Earlier1, Pairs0, Pairs).
852
853committing(true, Body) :-
854 \+ top_cut(Body).
855committing(false, Body) :-
856 ( Body == !
857 -> true
858 ; nonvar(Body),
859 Body = (First,_),
860 First == !
861 ).
862
863top_cut(Body) :-
864 Body == !,
865 !.
866top_cut(Body) :-
867 nonvar(Body),
868 Body = (A,B),
869 ( top_cut(A)
870 -> true
871 ; top_cut(B)
872 ).
873
884
885clause_calls(_, -, []) :- !.
886clause_calls(Commits, Ref, Calls) :-
887 ( catch(clause(CHead, Body, Ref), _, fail)
888 -> strip_module(CHead, M, Head),
889 ( get_assoc(Ref, Commits, Earlier)
890 -> true
891 ; Earlier = []
892 ),
893 term_variables(Head, HVars),
894 State = s([], Earlier, [], [], 0, []),
895 catch(ignore(body_calls(Body, M, Ref, Head, HVars,
896 true, _, [], _, State)),
897 _, true),
898 arg(1, State, RevCalls),
899 arg(3, State, Pruned),
900 arg(6, State, Barriers),
901 reverse(RevCalls, Calls0),
902 maplist(pruned_call(Pruned, Barriers), Calls0, Calls1),
903 number_from_end(Calls1, Calls)
904 ; Calls = []
905 ).
906
907pruned_call(Pruned, Barriers, Key-call(L, A, D, T, I),
908 Key-call(L, A, D, T, P, B)) :-
909 ( memberchk(I, Pruned)
910 -> P = true
911 ; P = false
912 ),
913 ( memberchk(I-B0, Barriers)
914 -> B = B0
915 ; B = none
916 ).
917
927
932
933prune_open(St, Open0) :-
934 arg(4, St, Open),
935 append(New, Open0, Open),
936 !,
937 arg(3, St, Pruned0),
938 append(New, Pruned0, Pruned),
939 nb_setarg(3, St, Pruned).
940prune_open(_, _).
941
947
948merge_open(St, Open0, Opens) :-
949 foldl(branch_open(Open0), Opens, New, []),
950 append(New, Open0, Open),
951 setarg(4, St, Open).
952
953branch_open(Open0, Open, New0, New) :-
954 ( append(Branch, Open0, Open)
955 -> append(Branch, New, New0)
956 ; New0 = New
957 ).
958
973
974body_calls(Var, _, _, _, _, L, L, S, S, _) :-
975 var(Var),
976 !.
977body_calls(M:G, _, Ref, H, HV, L0, L, S0, S, St) :-
978 !,
979 ( atom(M)
980 -> body_calls(G, M, Ref, H, HV, L0, L, S0, S, St)
981 ; L = L0, S = S0
982 ).
983body_calls((A,B), M, Ref, H, HV, L0, L, S0, S, St) :-
984 !,
985 body_calls(A, M, Ref, H, HV, L0, L1, S0, S1, St),
986 body_calls(B, M, Ref, H, HV, L1, L, S1, S, St).
987body_calls(!, _, _, _, _, L, L, S, S, St) :-
988 !,
989 prune_open(St, []).
990body_calls((A->B), M, Ref, H, HV, L0, L, S0, S, St) :-
991 !,
992 arg(4, St, Open0),
993 body_calls(A, M, Ref, H, HV, L0, L1, S0, S1, St),
994 prune_open(St, Open0),
995 body_calls(B, M, Ref, H, HV, L1, L, S1, S, St).
996body_calls((A*->B), M, Ref, H, HV, L0, L, S0, S, St) :-
997 !,
998 body_calls(A, M, Ref, H, HV, L0, L1, S0, S1, St),
999 body_calls(B, M, Ref, H, HV, L1, L, S1, S, St).
1000body_calls(\+(A), M, Ref, H, HV, L0, L, S0, S, St) :-
1001 !,
1002 arg(4, St, Open0),
1003 isolated(( body_calls(A, M, Ref, H, HV, L0, LA, S0, _, St),
1004 prune_open(St, Open0)
1005 ), LA, L0, L),
1006 seen(A, S0, S).
1007body_calls((A;B), M, Ref, H, HV, L0, L, S0, S, St) :-
1008 !,
1009 arg(4, St, Open0),
1010 ( if_then(A, C, T)
1011 -> isolated(( body_calls(C, M, Ref, H, HV, L0, LC0, S0, SC, St),
1012 ( A = (_->_)
1013 -> prune_open(St, Open0)
1014 ; true
1015 ),
1016 body_calls(T, M, Ref, H, HV, LC0, LT0, SC, _, St),
1017 arg(4, St, OpenT0)
1018 ), LC0-LT0-OpenT0, L0-L0-Open0, LC-LT-OpenT),
1019 seen(C, S0, SC1),
1020 isolated(( body_calls(B, M, Ref, H, HV, LC, LE0, SC1, _, St),
1021 arg(4, St, OpenE0)
1022 ), LE0-OpenE0, LC-Open0, LE-OpenE)
1023 ; isolated(( body_calls(A, M, Ref, H, HV, L0, LT0, S0, _, St),
1024 arg(4, St, OpenT0)
1025 ), LT0-OpenT0, L0-Open0, LT-OpenT),
1026 isolated(( body_calls(B, M, Ref, H, HV, L0, LE0, S0, _, St),
1027 arg(4, St, OpenE0)
1028 ), LE0-OpenE0, L0-Open0, LE-OpenE)
1029 ),
1030 or(LT, LE, L),
1031 merge_open(St, Open0, [OpenT, OpenE]),
1032 seen((A;B), S0, S).
1033body_calls(Goal, M, Ref, H, HV, L0, L, S0, S, St) :-
1034 callable(Goal),
1035 !,
1036 ( predicate_property(M:Goal, imported_from(IM))
1037 -> true
1038 ; IM = M
1039 ),
1040 functor(Goal, Name, Arity),
1041 PI = IM:Name/Arity,
1042 record_call(PI, Goal, Ref, H, HV, L0, S0, St),
1043 ( predicate_property(M:Goal, meta_predicate(Spec)),
1044 \+ control_goal(Goal)
1045 -> Goal =.. [_|Args],
1046 Spec =.. [_|Specs],
1047 foldl(meta_arg_calls(Goal, M, Ref, H, HV, St, S0), Specs, Args,
1048 L0, LM)
1049 ; LM = L0,
1050 derive(Goal, H, HV, S0)
1051 ),
1052 seen(Goal, S0, S),
1053 ( Goal = (A=B)
1054 -> ( unify_with_occurs_check(A, B)
1055 -> true
1056 ; true
1057 )
1058 ; true
1059 ),
1060 ( progress_goal(M:Goal)
1061 -> L = false
1062 ; L = LM
1063 ).
1064body_calls(_, _, _, _, _, L, L, S, S, _).
1065
1066if_then(A, C, T) :-
1067 nonvar(A),
1068 ( A = (C->T)
1069 -> true
1070 ; A = (C*->T)
1071 ).
1072
1076
1077seen(Goal, S0, S) :-
1078 term_variables(Goal, GVars),
1079 append(GVars, S0, S).
1080
1087
1088isolated(Walk, Template, Default, Result) :-
1089 Box = box(Default),
1090 ( call(Walk),
1091 nb_setarg(1, Box, Template),
1092 fail
1093 ; arg(1, Box, Result)
1094 ).
1095
1096control_goal(call(_)).
1097
1098 1101
1110
1116
1117attr_unify_hook(a(_, Kinds), Other) :-
1118 ( Kinds == any
1119 -> true
1120 ; var(Other)
1121 -> restrict_kinds(Other, Kinds)
1122 ; term_kind(Other, Kind),
1123 memberchk(Kind, Kinds)
1124 ).
1125
1126var_mark(V, Mark) :-
1127 get_attr(V, prolog_call_cycles, a(Mark, _)),
1128 Mark \== (-).
1129
1130set_mark(V, Mark) :-
1131 ( get_attr(V, prolog_call_cycles, a(_, Kinds))
1132 -> true
1133 ; Kinds = any
1134 ),
1135 put_attr(V, prolog_call_cycles, a(Mark, Kinds)).
1136
1141
1142restrict_kinds(V, Kinds) :-
1143 ( get_attr(V, prolog_call_cycles, a(Mark, Kinds0))
1144 -> true
1145 ; Mark = (-),
1146 Kinds0 = any
1147 ),
1148 kinds_meet(Kinds0, Kinds, Kinds1),
1149 put_attr(V, prolog_call_cycles, a(Mark, Kinds1)).
1150
1151kinds_meet(any, K, K) :- !.
1152kinds_meet(K, any, K) :- !.
1153kinds_meet(K1, K2, K) :-
1154 ord_intersection(K1, K2, K),
1155 K \== [].
1156
1157term_kind(T, Kind) :-
1158 ( var(T) -> Kind = var
1159 ; atom(T) -> Kind = atom
1160 ; T == [] -> Kind = nil
1161 ; integer(T) -> Kind = integer
1162 ; number(T) -> Kind = float
1163 ; string(T) -> Kind = string
1164 ; compound(T) -> Kind = compound
1165 ; Kind = blob
1166 ).
1167
1172
1173type_kinds(var, [var]).
1174type_kinds(nonvar, [atom,blob,compound,float,integer,nil,string]).
1175type_kinds(atom, [atom]).
1176type_kinds(atomic, [atom,blob,float,integer,nil,string]).
1177type_kinds(number, [float,integer]).
1178type_kinds(integer, [integer]).
1179type_kinds(float, [float]).
1180type_kinds(string, [string]).
1181type_kinds(compound, [compound]).
1182type_kinds(callable, [atom,compound]).
1183type_kinds(is_list, [compound,nil]).
1184type_kinds(is_dict, [compound]).
1185
1189
1190differ(A, B) :-
1191 ( dif(A, B)
1192 -> true
1193 ; true
1194 ).
1195
1199
1200derive(Test, _, _, _) :-
1201 compound(Test),
1202 compound_name_arguments(Test, Name, [X]),
1203 var(X),
1204 type_kinds(Name, Kinds),
1205 !,
1206 ( restrict_kinds(X, Kinds)
1207 -> true
1208 ; true
1209 ).
1210derive(Test, H, HV, _) :-
1211 compound(Test),
1212 compound_name_arguments(Test, Name, [A,B]),
1213 disequality(Name),
1214 !,
1215 ( head_value(B, H, I)
1216 -> mark_fresh(A, distinct(I), HV, []) 1217 ; head_value(A, H, I)
1218 -> mark_fresh(B, distinct(I), HV, [])
1219 ; true
1220 ),
1221 differ(A, B).
1222derive(arg(_, T, A), H, HV, S) :-
1223 head_part(T, H, I),
1224 !,
1225 mark_fresh(A, subterm(I), HV, S).
1226derive(T =.. L, H, HV, S) :-
1227 nonvar(L),
1228 L = [_|As],
1229 head_part(T, H, I),
1230 !,
1231 list_elements(As, Elems), 1232 mark_fresh(Elems, subterm(I), HV, S).
1233derive(D is Expr, H, HV, S) :-
1234 nonvar(Expr),
1235 differs(Expr, X),
1236 head_value(X, H, I),
1237 !,
1238 mark_fresh(D, computed(I), HV, S).
1239derive(succ(X, D), H, HV, S) :-
1240 head_value(X, H, I),
1241 !,
1242 mark_fresh(D, computed(I), HV, S).
1243derive(succ(D, X), H, HV, S) :-
1244 head_value(X, H, I),
1245 !,
1246 mark_fresh(D, computed(I), HV, S).
1247derive(plus(X, K, D), H, HV, S) :-
1248 nonzero(K),
1249 head_value(X, H, I),
1250 !,
1251 mark_fresh(D, computed(I), HV, S).
1252derive(plus(K, X, D), H, HV, S) :-
1253 nonzero(K),
1254 head_value(X, H, I),
1255 !,
1256 mark_fresh(D, computed(I), HV, S).
1257derive(_, _, _, _).
1258
1260
1261disequality(\==).
1262disequality(\=).
1263disequality(dif).
1264disequality(=\=).
1265disequality(<).
1266disequality(>).
1267
1268list_elements(L, []) :-
1269 var(L),
1270 !.
1271list_elements([H|T0], [H|T]) :-
1272 !,
1273 list_elements(T0, T).
1274list_elements(_, []).
1275
1279
1280differs(X+K, X) :- nonzero(K).
1281differs(K+X, X) :- nonzero(K).
1282differs(X-K, X) :- nonzero(K).
1283
1284nonzero(K) :-
1285 integer(K),
1286 K =\= 0.
1287
1293
1294head_part(T, _H, I) :-
1295 var(T),
1296 var_mark(T, subterm(I)),
1297 !.
1298head_part(T, H, I) :-
1299 arg(I, H, HA),
1300 ( T == HA
1301 -> true
1302 ; proper_subterm(T, HA)
1303 ),
1304 !.
1305
1311
1312head_value(X, H, I) :-
1313 var(X),
1314 head_part(X, H, I).
1315
1320
1321mark_fresh(Term, Mark, HV, S) :-
1322 term_variables(Term, Vs),
1323 mark_vars(Vs, Mark, HV, S).
1324
1325mark_vars([], _, _, _).
1326mark_vars([V|Vs], Mark, HV, S) :-
1327 ( \+ var_memberchk(V, HV),
1328 \+ var_memberchk(V, S),
1329 \+ var_mark(V, _)
1330 -> set_mark(V, Mark)
1331 ; true
1332 ),
1333 mark_vars(Vs, Mark, HV, S).
1334
1342
1343meta_arg_calls(Goal, M, Ref, H, HV, St, S0, Spec0, Arg, L0, L) :-
1344 meta_spec_extra(Spec0, Spec),
1345 arg(5, St, Count0),
1346 ( integer(Spec)
1347 -> ( callable(Arg)
1348 -> length(Extra, Spec),
1349 extend_goal(Arg, Extra, MGoal),
1350 arg(4, St, Open0),
1351 isolated(( setarg(4, St, []),
1352 mark_elements(Goal, Extra, H, HV, S0),
1353 body_calls(MGoal, M, Ref, H, HV, L0, L1, S0, _, St),
1354 prune_meta(Goal, St),
1355 arg(4, St, OpenM0)
1356 ), L1-OpenM0, L0-[], L-OpenM),
1357 reopen_meta(Goal, St, Open0, OpenM)
1358 ; L = L0
1359 )
1360 ; Spec == (^)
1361 -> strip_quantifier(Arg, MGoal),
1362 isolated(( setarg(4, St, []),
1363 body_calls(MGoal, M, Ref, H, HV, L0, L1, S0, _, St)
1364 ), L1, L0, L)
1365 ; L = L0
1366 ),
1367 barrier_calls(M:Goal, St, Count0).
1368
1374
1375barrier_calls(Goal, St, Count0) :-
1376 arg(5, St, Count),
1377 Count > Count0,
1378 shift_barrier(Goal, PI),
1379 !,
1380 arg(6, St, Barriers0),
1381 First is Count0+1,
1382 findall(I-PI,
1383 ( between(First, Count, I),
1384 \+ memberchk(I-_, Barriers0)
1385 ), New),
1386 append(New, Barriers0, Barriers),
1387 nb_setarg(6, St, Barriers).
1388barrier_calls(_, _, _).
1389
1400
1401shift_barrier(M:Goal, PI) :-
1402 ( predicate_property(M:Goal, implementation_module(IM))
1403 -> true
1404 ; IM = M
1405 ),
1406 functor(Goal, Name, Arity),
1407 predicate_property(IM:Goal, shift_barrier),
1408 ( module_property(IM, class(Class)),
1409 memberchk(Class, [system, library])
1410 -> PI = Name/Arity
1411 ; PI = IM:Name/Arity
1412 ).
1413
1418
1419reopen_meta(Goal, St, Open0, OpenM) :-
1420 ( ( pruning_meta(Goal)
1421 ; collecting_meta(Goal)
1422 )
1423 -> true
1424 ; append(OpenM, Open0, Open),
1425 setarg(4, St, Open)
1426 ).
1427
1428collecting_meta(findall(_,_,_)).
1429collecting_meta(findall(_,_,_,_)).
1430collecting_meta(bagof(_,_,_)).
1431collecting_meta(setof(_,_,_)).
1432collecting_meta(aggregate_all(_,_,_)).
1433collecting_meta(aggregate_all(_,_,_,_)).
1434
1436
(//, 2) :- !.
1438meta_spec_extra(Spec, Spec).
1439
1442
1443prune_meta(Goal, St) :-
1444 ( pruning_meta(Goal)
1445 -> prune_open(St, [])
1446 ; true
1447 ).
1448
1449pruning_meta(once(_)).
1450pruning_meta(ignore(_)).
1451pruning_meta(forall(_,_)).
1452
1457
1458mark_elements(Goal, Extra, H, HV, S) :-
1459 closure_elements(Goal, Lists, Extra),
1460 !,
1461 maplist(mark_element(H, HV, S), Lists, Extra).
1462mark_elements(_, _, _, _, _).
1463
1464mark_element(H, HV, S, List, Elem) :-
1465 ( List \== (-),
1466 head_part(List, H, I)
1467 -> mark_fresh(Elem, subterm(I), HV, S)
1468 ; true
1469 ).
1470
1476
1477closure_elements(Goal, Lists, Extra) :-
1478 compound(Goal),
1479 compound_name_arguments(Goal, Name, [_|Args]),
1480 closure_elements(Name, Args, Lists, Extra).
1481
1482closure_elements(maplist, Lists, Lists, _).
1483closure_elements(foldl, Args, Lists, _) :-
1484 append(Lists0, [_,_], Args),
1485 append(Lists0, [-,-], Lists).
1486closure_elements(include, [L,_], [L], _).
1487closure_elements(exclude, [L,_], [L], _).
1488closure_elements(partition, [L,_,_], [L], _).
1489closure_elements(partition, [L,_,_,_], [L,-], _).
1490
1491extend_goal(M:G, Extra, M:GE) :-
1492 !,
1493 extend_goal(G, Extra, GE).
1494extend_goal(G, [], G) :- !.
1495extend_goal(G, Extra, GE) :-
1496 callable(G),
1497 G =.. L0,
1498 append(L0, Extra, L),
1499 GE =.. L.
1500
1501strip_quantifier(G, G) :-
1502 var(G),
1503 !.
1504strip_quantifier(_^G0, G) :-
1505 !,
1506 strip_quantifier(G0, G).
1507strip_quantifier(G, G).
1508
1509or(true, _, true) :- !.
1510or(_, true, true) :- !.
1511or(_, _, false).
1512
1520
1521progress_goal(M:Goal) :-
1522 predicate_property(M:Goal, built_in),
1523 !,
1524 functor(Goal, Name, Arity),
1525 side_effect(Name/Arity).
1526progress_goal(M:Goal) :-
1527 ( predicate_property(M:Goal, imported_from(IM))
1528 -> true
1529 ; IM = M
1530 ),
1531 \+ left_transparent(IM:Goal).
1532
1540
1541side_effect(PI) :-
1542 side_effect_list(PIs),
1543 member(PI, PIs).
1544
1545side_effect_list(
1546 [ 1547 read/1, read/2, read_term/2, read_term/3, read_clause/3,
1548 read_term_with_history/2,
1549 get_char/1, get_char/2, get_code/1, get_code/2, get_byte/1,
1550 get_byte/2, get0/1, get0/2, get/1, get/2, get_single_char/1,
1551 skip/1, skip/2, read_pending_codes/3, read_pending_chars/3,
1552 read_string/3, read_string/5,
1553 1554 write/1, write/2, writeln/1, writeln/2, print/1, print/2,
1555 writeq/1, writeq/2, write_canonical/1, write_canonical/2,
1556 write_term/2, write_term/3, format/1, format/2, format/3,
1557 nl/0, nl/1, put_char/1, put_char/2, put_code/1, put_code/2,
1558 put_byte/1, put_byte/2, tab/1, tab/2, flush_output/0,
1559 flush_output/1, print_message/2, print_message_lines/3,
1560 1561 open/3, open/4, close/1, close/2, see/1, seen/0, tell/1,
1562 append/1, told/0, set_input/1, set_output/1, set_stream/2,
1563 set_stream_position/2, seek/4,
1564 1565 assert/1, assert/2, asserta/1, asserta/2, assertz/1, assertz/2,
1566 retract/1, retractall/1, erase/1, recorda/2, recorda/3,
1567 recordz/2, recordz/3, flag/3, abolish/1, abolish/2,
1568 1569 nb_setval/2, b_setval/2, setarg/3, nb_setarg/3, nb_linkarg/3,
1570 nb_linkval/2,
1571 1572 thread_get_message/1, thread_get_message/2, thread_get_message/3,
1573 thread_send_message/2, thread_send_message/3, thread_create/2,
1574 thread_create/3, thread_join/1, thread_join/2, sleep/1,
1575 shell/1, shell/2, halt/0, halt/1, get_time/1
1576 ]).
1577
1578:- multifile
1579 left_transparent/1. 1580
1587
1588left_transparent(prolog_debug:debug(_,_,_)).
1589left_transparent(prolog_debug:debug(_)).
1590left_transparent(prolog_debug:assertion(_)).
1591left_transparent(error:must_be(_,_)).
1592
1600
1601record_call(PI, Goal, Ref, Head, HVars, Left0, Seen, State) :-
1602 call_args(Goal, Head, HVars, Seen, Args),
1603 ( ( memberchk(subterm, Args)
1604 ; memberchk(computed, Args)
1605 ; memberchk(distinct, Args)
1606 )
1607 -> Left = false
1608 ; Left = Left0
1609 ),
1610 decreasing(Goal, Head, Decreasing),
1611 arg(2, State, Earlier),
1612 fresh_vars(Goal, HVars, Seen, Fresh),
1613 arg(5, State, I0),
1614 I is I0+1,
1615 nb_setarg(5, State, I),
1616 arg(4, State, Open),
1617 setarg(4, State, [I|Open]),
1618 arg(1, State, L0),
1619 copy_term((Ref-PI)-call(Left, Args, Decreasing,
1620 t(Head, Goal, Earlier, Fresh), I), Rec),
1621 nb_setarg(1, State, [Rec|L0]).
1622
1626
1627fresh_vars(Goal, HVars, Seen, Fresh) :-
1628 term_variables(Goal, GVars),
1629 include(fresh_var(HVars, Seen), GVars, Fresh).
1630
1631fresh_var(HVars, Seen, V) :-
1632 \+ var_memberchk(V, HVars),
1633 \+ var_memberchk(V, Seen),
1634 \+ var_mark(V, _).
1635
1636call_args(Goal, Head, HVars, Seen, Args) :-
1637 Goal =.. [_|GArgs],
1638 Head =.. [_|HArgs],
1639 maplist(arg_class(HArgs, HVars, Seen), GArgs, Args).
1640
1641arg_class(HArgs, HVars, Seen, A, Class) :-
1642 ( var(A)
1643 -> ( var_mark(A, Mark)
1644 -> functor(Mark, Class, 1)
1645 ; proper_subterm_of_any(A, HArgs)
1646 -> Class = subterm
1647 ; var_memberchk(A, HVars)
1648 -> Class = pass
1649 ; var_memberchk(A, Seen)
1650 -> Class = bound_earlier
1651 ; Class = fresh
1652 )
1653 ; ground(A)
1654 -> Class = ground
1655 ; proper_subterm_of_any(A, HArgs)
1656 -> Class = subterm
1657 ; Class = constructed
1658 ).
1659
1660proper_subterm_of_any(A, HArgs) :-
1661 member(HA, HArgs),
1662 proper_subterm(A, HA),
1663 !.
1664
1665proper_subterm(Sub, Term) :-
1666 compound(Term),
1667 arg(_, Term, Arg),
1668 ( Sub == Arg
1669 -> true
1670 ; proper_subterm(Sub, Arg)
1671 ),
1672 !.
1673
1674var_memberchk(V, [H|T]) :-
1675 ( V == H
1676 -> true
1677 ; var_memberchk(V, T)
1678 ).
1679
1680decreasing(Goal, Head, Decreasing) :-
1681 ( functor(Goal, Name, Arity),
1682 functor(Head, Name, Arity),
1683 arg(I, Goal, GA),
1684 ( var(GA),
1685 var_mark(GA, subterm(I))
1686 -> true
1687 ; arg(I, Head, HA),
1688 proper_subterm(GA, HA)
1689 )
1690 -> Decreasing = true
1691 ; Decreasing = false
1692 ).
1693
1694
1695 1698
1727
1728loop_keys(Edges, LoopKeys) :-
1729 findall(tr(Key, From, To, T),
1730 ( member(Key-T-E, Edges),
1731 E.left == true,
1732 From = E.from,
1733 To = E.to
1734 ), Trs),
1735 empty_assoc(K0),
1736 ( Trs == []
1737 -> LoopKeys = K0
1738 ; length(Trs, N),
1739 MaxDepth is min(10, N+1),
1740 index_transitions(Trs, Index),
1741 Budget = budget(20000),
1742 catch(foldl(start_loop(Index, MaxDepth, Budget), Trs, K0, LoopKeys),
1743 loop_budget,
1744 foldl(add_tr_key, Trs, K0, LoopKeys))
1745 ).
1746
1747index_transitions(Trs, Index) :-
1748 findall(From-Tr, (member(Tr, Trs), Tr = tr(_, From, _, _)), Pairs0),
1749 keysort(Pairs0, Pairs),
1750 group_pairs_by_key(Pairs, Grouped),
1751 list_to_assoc(Grouped, Index).
1752
1753add_tr_key(tr(Key, _, _, _), K0, K) :-
1754 put_assoc(Key, K0, true, K).
1755
1756add_key(Key, K0, K) :-
1757 put_assoc(Key, K0, true, K).
1758
1759start_loop(Index, MaxDepth, Budget, tr(Key, From, To, T), K0, K) :-
1760 copy_term(T, t(H0, G0, E0, F0)),
1761 ( loop_from(Index, MaxDepth, Budget, From-H0-E0, To, G0-F0, [Key], 1,
1762 Keys)
1763 -> foldl(add_key, Keys, K0, K)
1764 ; K = K0
1765 ).
1766
1767loop_from(Index, MaxDepth, Budget, Start, To, G-F, Keys0, D, Keys) :-
1768 Start = From-H0-E0,
1769 ( To == From,
1770 possible_variant(H0, E0, G, F)
1771 -> Keys = Keys0
1772 ; D < MaxDepth,
1773 get_assoc(To, Index, Trs),
1774 member(tr(Key, To, To2, T), Trs),
1775 step(Budget),
1776 copy_term(T, t(H1, G1, E1, F1)),
1777 unify_with_occurs_check(G, H1),
1778 \+ violated(E1, H1),
1779 D1 is D+1,
1780 loop_from(Index, MaxDepth, Budget, Start, To2, G1-F1, [Key|Keys0],
1781 D1, Keys)
1782 ).
1783
1784possible_variant(H0, E0, G, Fresh) :-
1785 \+ \+ ( maplist(unbound, Fresh),
1786 unify_with_occurs_check(H0, G),
1787 \+ violated(E0, H0)
1788 ).
1789
1790unbound(V) :-
1791 ( var(V)
1792 -> restrict_kinds(V, [var])
1793 ; true
1794 ).
1795
1796violated(Earlier, Head) :-
1797 member(E, Earlier),
1798 subsumes_term(E, Head),
1799 !.
1800
1801step(Budget) :-
1802 arg(1, Budget, N0),
1803 ( N0 > 0
1804 -> N is N0-1,
1805 nb_setarg(1, Budget, N)
1806 ; throw(loop_budget)
1807 ).
1808
1813
1814general_transition(Edge, t(Head, Goal, [], [])) :-
1815 pi_head(Edge.from, Head),
1816 pi_head(Edge.to, Goal).
1817
1818pi_head(_:Name/Arity, Head) :-
1819 functor(Head, Name, Arity).
1820
1821
1822 1825
1842
1843left_recursion(LeftRec, Options0) :-
1844 meta_options(is_meta, Options0, Options),
1845 call_graph_sccs(SCCs, Options),
1846 left_recursion(SCCs, LeftRec, Options).
1847
1848left_recursion(SCCs, LeftRec, _Options) :-
1849 member(SCC, SCCs),
1850 include(left_edge, SCC.edges, LeftEdges),
1851 LeftEdges \== [],
1852 maplist(edge_pair, LeftEdges, Pairs),
1853 pairs_keys(Pairs, Fs), pairs_values(Pairs, Ts),
1854 append(Fs, Ts, Vs0), sort(Vs0, Vs),
1855 vertices_edges_to_ugraph(Vs, Pairs, UGraph),
1856 ugraph_sccs(UGraph, Components),
1857 include(cyclic_component(UGraph), Components, Cyclic),
1858 member(Members0, Cyclic),
1859 sort(Members0, Members),
1860 list_to_assoc_set(Members, MSet),
1861 include(internal_edge(MSet), LeftEdges, Edges),
1862 Members = [Start|_],
1863 shortest_cycle(Start, Edges, Cycle),
1864 LeftRec = left_recursion{members:Members, cycle:Cycle, edges:Edges}.
1865
1866left_edge(Edge) :-
1867 Edge.left == true.
1868
1873
1874shortest_cycle(Start, Edges, Cycle) :-
1875 ( member(E, Edges), E.from == Start, E.to == Start
1876 -> Cycle = [E]
1877 ; empty_assoc(Visited0),
1878 put_assoc(Start, Visited0, -, Visited),
1879 bfs([Start-[]], Start, Edges, Visited, RevCycle),
1880 reverse(RevCycle, Cycle)
1881 ).
1882
1883bfs([V-Path|Queue], Start, Edges, Visited, Cycle) :-
1884 findall(E, (member(E, Edges), E.from == V), Out),
1885 ( member(E, Out), E.to == Start
1886 -> Cycle = [E|Path]
1887 ; foldl(bfs_next(Path), Out, Queue-Visited, Queue1-Visited1),
1888 bfs(Queue1, Start, Edges, Visited1, Cycle)
1889 ).
1890
1891bfs_next(Path, E, Q0-V0, Q-V) :-
1892 To = E.to,
1893 ( get_assoc(To, V0, _)
1894 -> Q = Q0, V = V0
1895 ; put_assoc(To, V0, -, V),
1896 append(Q0, [To-[E|Path]], Q)
1897 )