/* Part of SWI-Prolog Author: Jan Wielemaker E-mail: jan@swi-prolog.org WWW: http://www.swi-prolog.org Copyright (c) 2026, SWI-Prolog Solutions b.v. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ :- module(prolog_call_cycles, [ call_graph/2, % -Graph, +Options call_graph_sccs/2, % -SCCs, +Options call_graph_sccs/3, % +Graph, -SCCs, +Options left_recursion/2, % -LeftRecursion, +Options left_recursion/3 % +SCCs, -LeftRecursion, +Options ]). :- use_module(library(prolog_codewalk), [prolog_walk_code/1]). :- use_module(library(apply), [maplist/2, maplist/3, foldl/4, include/3, exclude/3]). :- use_module(library(assoc), [ empty_assoc/1, get_assoc/3, put_assoc/4, list_to_assoc/2, assoc_to_keys/2 ]). :- use_module(library(lists), [ member/2, append/3, append/2, list_to_set/2, reverse/2 ]). :- use_module(library(option), [option/2, option/3, meta_options/3]). :- use_module(library(pairs), [pairs_keys/2, pairs_values/2, group_pairs_by_key/2]). :- use_module(library(ugraphs), [vertices_edges_to_ugraph/3]). :- use_module(library(error), [must_be/2, domain_error/2]). :- use_module(library(ordsets), [ord_intersection/3]). :- autoload(library(dif), [dif/2]). :- meta_predicate call_graph(-, :), call_graph_sccs(-, :), left_recursion(-, :). /** Find recursion in the static call graph This library builds the static call graph of loaded Prolog code using library(prolog_codewalk) and finds the _recursion_ in it: the strongly connected components (SCCs) of the graph and, within these, the _left recursion_. A call is in _left_ position if, on some execution path through the clause body, no call to a non-built-in predicate precedes it, no built-in predicate with side effects such as reading input precedes it and no argument of the call is guaranteed to differ from the head argument it is derived from. Such arguments are proper subterms of a head argument, either directly or obtained using arg/3 or =../2, values computed from a head argument using an arithmetic operation that cannot return its input, such as `N-1`, and values that are tested to differ from a head argument, e.g., using `\==/2`. A call that is not left cannot be a variant of the calling goal. It may still recurse forever, but tabling does not help in that case. Left recursion is a _loop_ of calls in left position through which a goal may call a variant of itself. Such a loop runs forever under Prolog's SLD resolution. Loops are found by unfolding: starting from a call in left position, the goal of each call is unified with the head of a clause that has a call in left position, until we obtain a goal for the predicate we started with that unifies with the head we started with. Unification uses the occurs check and takes type tests such as atom/1 or var/1 into account. Clauses are skipped if an earlier clause that commits by a cut directly after the head or using single sided unification (=>) applies. Thus, `p(count) :- p(sum(1))` or `p(X) :- atom(X), !, p([X])` are not left recursive, while `p(a) :- p(b)` together with `p(b) :- p(a)` is. The subterm condition makes recursion that consumes input, such as grammar rules that start with a terminal, not left recursive. Unifications (=/2) are taken into account, which is needed for the code produced by the DCG translation. Unifications inside a branch of a disjunction only affect the calls in that branch, where the unifications in the condition of an if-then-else also hold in its then-branch. If a closure is called on the elements of a list, as in maplist/2, the elements of a list that is derived from the head are subterms. For example, the recursive call in the first rule below is not in left position, while it is in the second: ``` ws --> [C], { code_type(C, space) }, !, ws. lr --> lr, "a". ``` Each call edge inside an SCC is annotated with the clause and source location of the call and with an abstraction of the call's arguments. This information is used by library(prolog_auto_table) to decide which predicates to table, but is also useful for program analysis tools. The scope of the analysis is defined by the options below. Only calls _between_ predicates in scope become edges of the graph: - goal(:Goal) Analyse the predicates that are reachable from Goal. If files or module are given as well, these restrict the reachable predicates to those defined in the given files or modules. Predicates in modules of class `system` are never included. - files(+FileOrFiles) Analyse the predicates that have clauses in the given file(s), the dynamic predicates declared there and the foreign predicates of the modules they define. Files included using include/1 are part of the file that includes them: clauses in an included file belong to the file that loads it, and an included file given as FileOrFiles stands for the file(s) that load it. - module(+ModuleOrModules) Analyse the predicates defined in Module. A list of modules is allowed. - predicates(+PIs) Analyse the given (qualified) predicate indicators. - external(+Boolean) If `true` (default `false`), also return the edges from predicates in scope to predicates outside the scope in the `external` key of the graph. Other options are passed to prolog_walk_code/1, notably autoload(Bool), walk_meta_predicates(Bool) and infer_meta_predicates(Bool). */ :- predicate_options(call_graph/2, 2, [ goal(callable), files(any), module(any), predicates(list), external(boolean), pass_to(prolog_codewalk:prolog_walk_code/1, 1) ]). %! call_graph(-Graph:dict, +Options) is det. % % Compute the static call graph for the predicates selected by % Options. Graph is a dict with the keys below. Predicates are % represented by qualified predicate indicators, `M:Name/Arity`. % % - vertices % Sorted list of predicates in scope. For files(Files), these % are the predicates with clauses in Files and the dynamic % predicates declared in Files, including the files they % include. % - ugraph % The graph as a library(ugraphs) graph. % - edges % List of edges between predicates in scope. Each edge is a % dict `edge{from:PI, to:PI, clause:ClauseRef, location:Dict}`, % where `Location` is the location dict of prolog_walk_code/1 % (option `on_edge`). If a predicate calls another one multiple % times, there is an edge for each call. % - external % List of edges from predicates in scope to other predicates. % Only filled if the option external(true) is given. call_graph(Graph, Options0) :- meta_options(is_meta, Options0, Options), walk_options(Options, WalkOptions), scope(Options, WalkOptions, Vertices, Clauses), list_to_assoc_set(Vertices, VSet), option(external(External), Options, false), State = state([], []), ( Clauses == [] -> true ; prolog_walk_code([ clauses(Clauses), trace_reference(_), on_edge(collect_edge(VSet, External, State)) | WalkOptions ]) ), arg(1, State, RevEdges), arg(2, State, RevExt), reverse(RevEdges, Edges), reverse(RevExt, Ext), maplist(edge_pair, Edges, Pairs), vertices_edges_to_ugraph(Vertices, Pairs, UGraph), Graph = call_graph{vertices:Vertices, ugraph:UGraph, edges:Edges, external:Ext}. is_meta(goal). edge_pair(Edge, Edge.from-Edge.to). :- public collect_edge/6. collect_edge(VSet, External, State, Callee, Caller, Location) :- callee_pi(Callee, ToPI), goal_pi(Caller, FromPI), ( get_assoc(ToPI, VSet, _) -> E = edge{from:FromPI, to:ToPI, clause:Clause, location:Location}, clause_of_location(Location, Clause), arg(1, State, L0), nb_setarg(1, State, [E|L0]) ; External == true -> E = edge{from:FromPI, to:ToPI, clause:Clause, location:Location, goal:Callee}, clause_of_location(Location, Clause), arg(2, State, L0), nb_setarg(2, State, [E|L0]) ; true ). clause_of_location(Location, Clause) :- ( get_dict(clause, Location, Clause0) -> Clause = Clause0 ; Clause = (-) ). callee_pi(M:Goal, PI) :- callable(Goal), ( predicate_property(M:Goal, imported_from(IM)) -> true ; IM = M ), goal_pi(IM:Goal, PI). goal_pi(M:Goal, M:Name/Arity) :- callable(Goal), !, functor(Goal, Name, Arity). goal_pi(Goal, Goal). walk_options(Options, WalkOptions) :- exclude(own_option, Options, WalkOptions0), ( option(source(_), WalkOptions0) -> WalkOptions = WalkOptions0 ; WalkOptions = [source(false)|WalkOptions0] ). own_option(goal(_)). own_option(files(_)). own_option(module(_)). own_option(predicates(_)). own_option(external(_)). own_option(clauses(_)). own_option(trace_reference(_)). own_option(on_edge(_)). own_option(on_trace(_)). own_option(locations(_)). %! scope(+Options, +WalkOptions, -Vertices, -Clauses) is det. % % Determine the predicates (Vertices) in scope and the clauses we % must walk. scope(Options, WalkOptions, Vertices, Clauses) :- option(goal(Goal), Options), !, goal_scope(Goal, Options, WalkOptions, Vertices, Clauses). scope(Options, _, Vertices, Clauses) :- option(files(Files), Options), !, abs_files(Files, AbsFiles), findall(PI-Ref, ( member(File, AbsFiles), source_file_clause(File, PI, Ref) ), Pairs0), findall(PI-(-), ( member(File, AbsFiles), ( source_file_dynamic(File, PI) ; source_file_foreign(File, PI) ) ), DynPairs), append(Pairs0, DynPairs, Pairs), scope_from_pairs(Pairs, Vertices, Clauses). scope(Options, _, Vertices, Clauses) :- option(module(Modules), Options), !, modules(Modules, Ms), findall(M:Name/Arity, ( member(M, Ms), current_predicate(M:Name/Arity), functor(Head, Name, Arity), \+ predicate_property(M:Head, imported_from(_)) ), PIs), pis_scope(PIs, Vertices, Clauses). scope(Options, _, Vertices, Clauses) :- option(predicates(PIs), Options), !, must_be(list, PIs), pis_scope(PIs, Vertices, Clauses). scope(_, _, _, _) :- domain_error(call_graph_scope, none). abs_files(Files0, AbsFiles) :- ( is_list(Files0) -> Files = Files0 ; Files = [Files0] ), maplist(absolute_source_file, Files, AbsFiles0), findall(AbsFile, ( member(File, AbsFiles0), loading_file(File, AbsFile) ), AbsFiles1), sort(AbsFiles1, AbsFiles). modules(Modules, Ms) :- ( is_list(Modules) -> Ms = Modules ; Ms = [Modules] ), must_be(list(atom), Ms). %! goal_scope(:Goal, +Options, +WalkOptions, -Vertices, -Clauses) % % The scope consists of all predicates reachable from Goal that % satisfy the filter defined by the files and module options. goal_scope(Goal, Options, WalkOptions, Vertices, Clauses) :- goal_filter(Options, Filter), goal_roots(Goal, WalkOptions, Roots0), include(in_goal_scope(Filter), Roots0, Roots), list_to_assoc_set(Roots, Seen0), reachable(Roots, Filter, WalkOptions, Seen0, Seen), assoc_to_keys(Seen, Vertices), findall(Ref, ( member(PI, Vertices), pi_clause(PI, Ref) ), Clauses). goal_filter(Options, filter(Files, Modules)) :- ( option(files(Files0), Options) -> abs_files(Files0, Files) ; Files = (-) ), ( option(module(Modules0), Options) -> modules(Modules0, Modules) ; Modules = (-) ). in_goal_scope(filter(Files, Modules), PI) :- PI = M:Name/Arity, \+ module_property(M, class(system)), ( Modules == (-) -> true ; memberchk(M, Modules) ), functor(Head, Name, Arity), \+ predicate_property(M:Head, foreign), \+ predicate_property(M:Head, imported_from(_)), predicate_property(M:Head, number_of_clauses(N)), N > 0, ( Files == (-) -> true ; source_file(M:Head, File), memberchk(File, Files) -> true ). :- dynamic goal_clause/0. %! goal_roots(:Goal, +WalkOptions, -Roots) is det. % % Roots is the set of predicates called by Goal. Goal is walked % as the body of a temporary clause, such that prolog_walk_code/1 % deals with control structures and meta-predicates. goal_roots(Goal, WalkOptions, Roots) :- setup_call_cleanup( assertz((goal_clause :- Goal), Ref), callees([Ref], WalkOptions, Roots), erase(Ref)). %! reachable(+Frontier, +Filter, +WalkOptions, +Seen0, -Seen) is det. % % Seen is Seen0 extended with all predicates in scope that are % reachable from the predicates in Frontier. reachable([], _, _, Seen, Seen) :- !. reachable(Frontier, Filter, WalkOptions, Seen0, Seen) :- findall(Ref, ( member(PI, Frontier), pi_clause(PI, Ref) ), Refs), callees(Refs, WalkOptions, Callees), include(new_in_scope(Filter, Seen0), Callees, New), foldl(add_seen, New, Seen0, Seen1), reachable(New, Filter, WalkOptions, Seen1, Seen). new_in_scope(Filter, Seen, PI) :- \+ get_assoc(PI, Seen, _), in_goal_scope(Filter, PI). add_seen(PI, Seen0, Seen) :- put_assoc(PI, Seen0, true, Seen). %! callees(+Clauses, +WalkOptions, -PIs) is det. % % PIs is the sorted set of predicates called by Clauses. callees([], _, []) :- !. callees(Clauses, WalkOptions, PIs) :- State = callees([]), prolog_walk_code([ clauses(Clauses), trace_reference(_), on_edge(collect_callee(State)) | WalkOptions ]), arg(1, State, PIs0), sort(PIs0, PIs). :- public collect_callee/4. collect_callee(State, Callee, _Caller, _Location) :- ( callee_pi(Callee, PI) -> arg(1, State, L0), nb_setarg(1, State, [PI|L0]) ; true ). pis_scope(PIs, Vertices, Clauses) :- findall(PI-Ref, ( member(PI, PIs), pi_clause(PI, Ref) ), Pairs0), findall(PI-(-), member(PI, PIs), NoClause), append(Pairs0, NoClause, Pairs), scope_from_pairs(Pairs, Vertices, Clauses). scope_from_pairs(Pairs, Vertices, Clauses) :- pairs_keys(Pairs, PIs), sort(PIs, Vertices), pairs_values(Pairs, Refs0), exclude(==(-), Refs0, Refs1), list_to_set(Refs1, Clauses). absolute_source_file(Spec, File) :- ( atom(Spec), is_absolute_file_name(Spec), loaded_or_included(Spec) -> File = Spec ; absolute_file_name(Spec, File, [ file_type(prolog), access(read) ]), loaded_or_included(File) -> true ; existence_error(source_file, Spec) ). loaded_or_included(File) :- ( source_file(File) -> true ; source_file_property(File, included_in(_, _)) -> true ). % loading_file(+File, -LoadedFile) is nondet. % % LoadedFile is File if File is loaded, and else the loaded file % that (indirectly) includes File. loading_file(File, File) :- source_file(File), !. loading_file(File, Loaded) :- loading_file(File, [File], Loaded). loading_file(File, Visited, Loaded) :- source_file_property(File, included_in(Parent, _)), \+ memberchk(Parent, Visited), ( source_file(Parent) -> Loaded = Parent ; loading_file(Parent, [Parent|Visited], Loaded) ). source_file_clause(File, M:Name/Arity, Ref) :- source_file(M:Head, File), M \== system, % '$load_context_module'/3, etc. \+ predicate_property(M:Head, imported_from(_)), functor(Head, Name, Arity), \+ predicate_property(M:Head, foreign), catch(clause(M:Head, _, Ref), _, fail), clause_property(Ref, source(File)). % source_file_dynamic(+File, -PI) is nondet. % % PI is a dynamic predicate declared in File. It is in scope even if % File has no clauses for it. source_file_dynamic(File, M:Name/Arity) :- source_file(M:Head, File), M \== system, \+ predicate_property(M:Head, imported_from(_)), predicate_property(M:Head, dynamic), functor(Head, Name, Arity). % source_file_foreign(+File, -PI) is nondet. % % PI is a foreign predicate of the module defined in File, e.g., % loaded by use_foreign_library/1 or load_foreign_resource/1 of % library(qpforeign). Foreign predicates have no source file, but % the code of File calls them as local predicates. source_file_foreign(File, M:Name/Arity) :- current_module(M), module_property(M, file(File)), M \== system, current_predicate(M:Name/Arity), functor(Head, Name, Arity), predicate_property(M:Head, foreign), \+ predicate_property(M:Head, imported_from(_)). pi_clause(PI, Ref) :- PI = M:Name/Arity, functor(Head, Name, Arity), \+ predicate_property(M:Head, foreign), catch(clause(M:Head, _, Ref), _, fail). list_to_assoc_set(List, Assoc) :- findall(K-true, member(K, List), Pairs), list_to_assoc(Pairs, Assoc). existence_error(Type, Obj) :- throw(error(existence_error(Type, Obj), _)). /******************************* * SCC * *******************************/ %! call_graph_sccs(-SCCs:list(dict), +Options) is det. %! call_graph_sccs(+Graph, -SCCs:list(dict), +Options) is det. % % Compute the strongly connected components of the call graph that % contain at least one cycle, i.e., that have more than one member % or a single member that calls itself. Each SCC is a dict with the % keys below. The first form computes the graph using call_graph/2 % from Options. % % - members % Sorted list of predicate indicators in the SCC. % - edges % List of edges between members of the SCC. Each edge is a % dict as described with call_graph/2, extended with the keys % below. % - left % `true` if the call is in left position and may take part in % a loop (see module header). Note that a call with a % `subterm`, `computed` or `distinct` argument is never in % left position. % - args % List of argument abstractions for the call. Each element is % one of `fresh` (a variable that does not appear earlier in % the clause), `pass` (a variable from the head), % `bound_earlier` (a variable that appears in an earlier % goal of the body), `ground` (a ground term), `subterm` % (a proper subterm of a head argument, also if obtained % using arg/3 or =../2), `computed` (the result of an % arithmetic operation on a head argument that differs from % its input, such as `N-1`), `distinct` (a value that is % tested to differ from a head argument, e.g., using `X \== Y`) % or `constructed` (a term with % variables that is not a subterm of a head argument, e.g., % an accumulator). If the call could not be analysed, this % is `unknown`. % - decreasing % `true` if this is a call to the same predicate and some % argument is a proper subterm of the same argument in the head. % - pruned % `true` if a cut can prune the call: a cut after the call in % its clause, the cut of the if-then-else whose condition holds % the call, \+/1, once/1, ignore/1 or forall/2. If the % callee is tabled and part of the same SCC, such a cut raises % a permission error. % - barrier % `none` or the predicate through whose goal argument the call % is made if that is a barrier for shift/1: findall/3 and the % other predicates that collect all solutions, aggregate_all/3, % foldall/4 and predicates defined in C. A tabled goal cannot % suspend through a barrier to wait for an incomplete table. % % If the option locations(true) is given (default), the location of % the edges in the SCCs is refined by walking the involved clauses % with source information. call_graph_sccs(SCCs, Options0) :- meta_options(is_meta, Options0, Options), call_graph(Graph, Options), call_graph_sccs(Graph, SCCs, Options). call_graph_sccs(Graph, SCCs, Options) :- ugraph_sccs(Graph.ugraph, Components), include(cyclic_component(Graph.ugraph), Components, Cyclic), maplist(component_scc(Graph, Options), Cyclic, SCCs). cyclic_component(_, [_,_|_]) :- !. cyclic_component(UGraph, [V]) :- memberchk(V-Ns, UGraph), memberchk(V, Ns). component_scc(Graph, Options, Members0, scc{members:Members, edges:Edges}) :- sort(Members0, Members), list_to_assoc_set(Members, MSet), include(internal_edge(MSet), Graph.edges, Edges0), refine_locations(Edges0, Edges1, Options), annotate_edges(Edges1, Edges). internal_edge(MSet, Edge) :- get_assoc(Edge.from, MSet, _), get_assoc(Edge.to, MSet, _). %! ugraph_sccs(+UGraph, -SCCs:list(list)) is det. % % Tarjan's algorithm for finding the strongly connected components. % SCCs is a list of lists of vertices, in reverse topological order % (a component appears before the components that call it). ugraph_sccs(UGraph, SCCs) :- empty_assoc(Index0), foldl(scc_vertex(UGraph), UGraph, t(0, Index0, [], []), t(_, _, _, RevSCCs)), reverse(RevSCCs, SCCs). scc_vertex(UGraph, V-_, S0, S) :- S0 = t(_, Index, _, _), ( get_assoc(V, Index, _) -> S = S0 ; strongconnect(V, UGraph, S0, S, _) ). % S is t(Counter, Index, Stack, SCCs). Index maps a vertex to % i(Index, LowLink, OnStack). strongconnect(V, UGraph, t(N0, Index0, Stack0, SCCs0), S, Low) :- put_assoc(V, Index0, i(N0, N0, true), Index1), N1 is N0+1, memberchk(V-Succs, UGraph), foldl(scc_succ(V, UGraph), Succs, t(N1, Index1, [V|Stack0], SCCs0)-N0, t(N2, Index2, Stack2, SCCs2)-Low), ( Low =:= N0 -> pop_scc(V, Stack2, Stack3, Component, Index2, Index3), S = t(N2, Index3, Stack3, [Component|SCCs2]) ; get_assoc(V, Index2, i(I, _, OS)), put_assoc(V, Index2, i(I, Low, OS), Index3), S = t(N2, Index3, Stack2, SCCs2) ). scc_succ(_V, UGraph, W, S0-Low0, S-Low) :- S0 = t(_, Index, _, _), ( get_assoc(W, Index, i(WI, _, OnStack)) -> S = S0, ( OnStack == true -> Low is min(Low0, WI) ; Low = Low0 ) ; strongconnect(W, UGraph, S0, S, WLow), Low is min(Low0, WLow) ). pop_scc(V, [W|Stack0], Stack, [W|Component], Index0, Index) :- get_assoc(W, Index0, i(I, L, _)), put_assoc(W, Index0, i(I, L, false), Index1), ( W == V -> Stack = Stack0, Component = [], Index = Index1 ; pop_scc(V, Stack0, Stack, Component, Index1, Index) ). /******************************* * LOCATIONS * *******************************/ %! refine_locations(+Edges0, -Edges, +Options) is det. % % Walk the clauses holding Edges0 again with source(true) to obtain % the exact location of each call. The walk generates the edges in % the same order, so we match on the clause, the callee and the % number of the call to the callee in the clause. refine_locations(Edges0, Edges, Options) :- option(locations(true), Options, true), \+ option(source(true), Options), findall(Ref, (member(E, Edges0), Ref = E.clause, Ref \== (-)), Refs0), Refs0 \== [], !, sort(Refs0, Refs), walk_options(Options, WalkOptions0), exclude(source_option, WalkOptions0, WalkOptions), State = state([]), catch(prolog_walk_code([ clauses(Refs), trace_reference(_), source(true), on_edge(collect_location(State)) | WalkOptions ]), _, true), arg(1, State, RevLocs), reverse(RevLocs, Locs), number_calls(Locs, NLocs), number_edge_calls(Edges0, NEdges), maplist(refined_edge(NLocs), NEdges, Edges). refine_locations(Edges, Edges, _). source_option(source(_)). :- public collect_location/4. collect_location(State, Callee, _Caller, Location) :- ( get_dict(clause, Location, Clause), callee_pi(Callee, PI) -> arg(1, State, L0), nb_setarg(1, State, [loc(Clause, PI, Location)|L0]) ; true ). % The calls to a callee in a clause are numbered from the _end_ of % the clause. When prolog_walk_code/1 finds a meta-call it cannot % resolve, it restarts the walk of the clause body, reporting the % calls before it twice. Numbering from the end makes the real % calls of the clause match, while the duplicates get a number that % is higher than the number of calls to the callee. number_calls(Locs, Numbered) :- maplist(loc_key, Locs, Keyed), number_from_end(Keyed, Numbered). loc_key(loc(Clause, PI, Location), (Clause-PI)-Location). number_edge_calls(Edges, Numbered) :- maplist(edge_key, Edges, Keyed), number_from_end(Keyed, Numbered). edge_key(Edge, (Edge.clause-Edge.to)-Edge). %! number_from_end(+Keyed:list(pair), -Numbered:list(pair)) is det. % % Numbered contains `(Key-N)-Value` for each `Key-Value` in Keyed, % where N is the number of elements with the same Key from the end % of the list, starting at 1. number_from_end(Keyed, Numbered) :- reverse(Keyed, RevKeyed), empty_assoc(C0), foldl(number_keyed, RevKeyed, RevNumbered, C0, _), reverse(RevNumbered, Numbered). number_keyed(Key-Value, (Key-N)-Value, C0, C) :- ( get_assoc(Key, C0, N0) -> true ; N0 = 0 ), N is N0+1, put_assoc(Key, C0, N, C). refined_edge(NLocs, Key-Edge0, Edge) :- ( memberchk(Key-Location, NLocs) -> Edge = Edge0.put(location, Location) ; Edge = Edge0 ). /******************************* * ANNOTATION * *******************************/ %! annotate_edges(+Edges0, -Edges) is det. % % Add the keys `left`, `args` and `decreasing` to the edges. We % analyse the clause of each edge, generating the calls in the same % order as prolog_walk_code/1 and match them on the callee and the % number of the call to the callee in the clause. If the match % fails, we use the conservative annotation (left, unknown args). annotate_edges(Edges0, Edges) :- number_edge_calls(Edges0, NEdges), findall(Ref, (member(E, Edges0), Ref = E.clause), Refs0), sort(Refs0, Refs), commit_heads(Refs, Commits), maplist(clause_calls(Commits), Refs, CallLists), append(CallLists, Calls), foldl(annotated_edge(Calls), NEdges, Edges1, []), loop_keys(Edges1, LoopKeys), maplist(final_edge(LoopKeys), Edges1, Edges). annotated_edge(Calls, Key-Edge0, Edges0, Edges) :- ( memberchk(Key-call(Left, Args, Decreasing, T, Pruned, Barrier), Calls) -> Edges0 = [Key-T-Edge|Edges], Edge = Edge0.put(#{left:Left, args:Args, decreasing:Decreasing, pruned:Pruned, barrier:Barrier}) ; Key = (Clause-PI)-_, memberchk((Clause-PI)-_-_, Calls) -> Edges0 = Edges % duplicate from a restarted walk ; Edges0 = [Key-T-Edge|Edges], general_transition(Edge0, T), Edge = Edge0.put(#{left:true, args:unknown, decreasing:false, pruned:false, barrier:none}) ). final_edge(LoopKeys, Key-_-Edge0, Edge) :- ( Edge0.left == true, \+ get_assoc(Key, LoopKeys, _) -> Edge = Edge0.put(left, false) ; Edge = Edge0 ). %! commit_heads(+ClauseRefs, -Commits) is det. % % Commits is an assoc that maps each clause in ClauseRefs to the % heads of the clauses of its predicate before it that commit % unconditionally to their clause. A call that is an instance of % one of these heads never reaches the clause. Clauses commit % unconditionally if their body starts with a cut or, for % predicates defined using single sided unification (=>), if they % have no guard. commit_heads(Refs, Commits) :- findall(PI, ( member(Ref, Refs), Ref \== (-), catch(clause_property(Ref, predicate(PI)), _, fail) ), PIs0), sort(PIs0, PIs), foldl(pred_commit_heads, PIs, Pairs, []), list_to_assoc(Pairs, Commits). pred_commit_heads(M:Name/Arity, Pairs0, Pairs) :- functor(Head, Name, Arity), ( predicate_property(M:Head, ssu) -> SSU = true ; SSU = false ), findall(Ref-c(Head, Body), catch(clause(M:Head, Body, Ref), _, fail), Clauses), clause_commits(Clauses, SSU, [], Pairs0, Pairs). clause_commits([], _, _, Pairs, Pairs). clause_commits([Ref-c(Head, Body)|T], SSU, Earlier, [Ref-Earlier|Pairs0], Pairs) :- ( committing(SSU, Body) -> Earlier1 = [Head|Earlier] ; Earlier1 = Earlier ), clause_commits(T, SSU, Earlier1, Pairs0, Pairs). committing(true, Body) :- \+ top_cut(Body). committing(false, Body) :- ( Body == ! -> true ; nonvar(Body), Body = (First,_), First == ! ). top_cut(Body) :- Body == !, !. top_cut(Body) :- nonvar(Body), Body = (A,B), ( top_cut(A) -> true ; top_cut(B) ). %! clause_calls(+Commits, +ClauseRef, -Calls) is det. % % Calls is a list of `(Clause-PI-N)-call(Left, Args, Decreasing, % Transition, Pruned, Barrier)` for all calls in the body of % ClauseRef, where N numbers the calls to PI from the end of the % clause (see number_from_end/2), Transition is used by loop_keys/2, % Pruned is `true` if a cut can prune the call (see prune_open/2) % and Barrier is the predicate through which the call is made that % is a barrier for suspending a tabled goal or `none` (see % shift_barrier/2). clause_calls(_, -, []) :- !. clause_calls(Commits, Ref, Calls) :- ( catch(clause(CHead, Body, Ref), _, fail) -> strip_module(CHead, M, Head), ( get_assoc(Ref, Commits, Earlier) -> true ; Earlier = [] ), term_variables(Head, HVars), State = s([], Earlier, [], [], 0, []), catch(ignore(body_calls(Body, M, Ref, Head, HVars, true, _, [], _, State)), _, true), arg(1, State, RevCalls), arg(3, State, Pruned), arg(6, State, Barriers), reverse(RevCalls, Calls0), maplist(pruned_call(Pruned, Barriers), Calls0, Calls1), number_from_end(Calls1, Calls) ; Calls = [] ). pruned_call(Pruned, Barriers, Key-call(L, A, D, T, I), Key-call(L, A, D, T, P, B)) :- ( memberchk(I, Pruned) -> P = true ; P = false ), ( memberchk(I-B0, Barriers) -> B = B0 ; B = none ). % The state of walking a clause body is a term s(Calls, Earlier, % Pruned, Open, Count, Barriers). Calls is the list of recorded % calls, Earlier the list of heads used by the loop check (see % commit_heads/2), Pruned the list of indices of calls that can be % pruned by a cut, Open the list of indices of the calls on the % current execution path that a clause-level cut prunes, Count the % number of calls recorded and Barriers a list Index-PI of the calls % made through a shift barrier PI (see shift_barrier/2). Open is updated using the % backtrackable setarg/3, such that isolated/4 restores it. %! prune_open(+State, +Open0) is det. % % Mark the calls that were opened since Open0 as pruned. With % Open0 = [], this marks all open calls. prune_open(St, Open0) :- arg(4, St, Open), append(New, Open0, Open), !, arg(3, St, Pruned0), append(New, Pruned0, Pruned), nb_setarg(3, St, Pruned). prune_open(_, _). %! merge_open(+State, +Open0, +Opens) is det. % % Set the open calls after a disjunction to Open0 plus the calls % opened by its branches, where each element of Opens is Open0 % extended with the calls of a branch. merge_open(St, Open0, Opens) :- foldl(branch_open(Open0), Opens, New, []), append(New, Open0, Open), setarg(4, St, Open). branch_open(Open0, Open, New0, New) :- ( append(Branch, Open0, Open) -> append(Branch, New, New0) ; New0 = New ). %! body_calls(+Body, +Module, +Ref, +Head, +HeadVars, %! +Left0, -Left, +Seen0, -Seen, +State) is det. % % Walk Body in the same order as prolog_walk_code/1. Left0 is % `true` if no call to a non-built-in predicate precedes Body on some % execution path. Seen0 is a list of variables that appear in % goals of the body before Body. % % Unifications (=/2) are executed, such that the classification of % later calls takes aliasing into account. Alternative branches, % negation and the goals of meta-calls are walked in isolation (see % isolated/4): their bindings and the marks they create (see % derive/4) are undone afterwards. The unifications in the % condition of an if-then-else hold in its then-branch. body_calls(Var, _, _, _, _, L, L, S, S, _) :- var(Var), !. body_calls(M:G, _, Ref, H, HV, L0, L, S0, S, St) :- !, ( atom(M) -> body_calls(G, M, Ref, H, HV, L0, L, S0, S, St) ; L = L0, S = S0 ). body_calls((A,B), M, Ref, H, HV, L0, L, S0, S, St) :- !, body_calls(A, M, Ref, H, HV, L0, L1, S0, S1, St), body_calls(B, M, Ref, H, HV, L1, L, S1, S, St). body_calls(!, _, _, _, _, L, L, S, S, St) :- !, prune_open(St, []). body_calls((A->B), M, Ref, H, HV, L0, L, S0, S, St) :- !, arg(4, St, Open0), body_calls(A, M, Ref, H, HV, L0, L1, S0, S1, St), prune_open(St, Open0), body_calls(B, M, Ref, H, HV, L1, L, S1, S, St). body_calls((A*->B), M, Ref, H, HV, L0, L, S0, S, St) :- !, body_calls(A, M, Ref, H, HV, L0, L1, S0, S1, St), body_calls(B, M, Ref, H, HV, L1, L, S1, S, St). body_calls(\+(A), M, Ref, H, HV, L0, L, S0, S, St) :- !, arg(4, St, Open0), isolated(( body_calls(A, M, Ref, H, HV, L0, LA, S0, _, St), prune_open(St, Open0) ), LA, L0, L), seen(A, S0, S). body_calls((A;B), M, Ref, H, HV, L0, L, S0, S, St) :- !, arg(4, St, Open0), ( if_then(A, C, T) -> isolated(( body_calls(C, M, Ref, H, HV, L0, LC0, S0, SC, St), ( A = (_->_) -> prune_open(St, Open0) ; true ), body_calls(T, M, Ref, H, HV, LC0, LT0, SC, _, St), arg(4, St, OpenT0) ), LC0-LT0-OpenT0, L0-L0-Open0, LC-LT-OpenT), seen(C, S0, SC1), isolated(( body_calls(B, M, Ref, H, HV, LC, LE0, SC1, _, St), arg(4, St, OpenE0) ), LE0-OpenE0, LC-Open0, LE-OpenE) ; isolated(( body_calls(A, M, Ref, H, HV, L0, LT0, S0, _, St), arg(4, St, OpenT0) ), LT0-OpenT0, L0-Open0, LT-OpenT), isolated(( body_calls(B, M, Ref, H, HV, L0, LE0, S0, _, St), arg(4, St, OpenE0) ), LE0-OpenE0, L0-Open0, LE-OpenE) ), or(LT, LE, L), merge_open(St, Open0, [OpenT, OpenE]), seen((A;B), S0, S). body_calls(Goal, M, Ref, H, HV, L0, L, S0, S, St) :- callable(Goal), !, ( predicate_property(M:Goal, imported_from(IM)) -> true ; IM = M ), functor(Goal, Name, Arity), PI = IM:Name/Arity, record_call(PI, Goal, Ref, H, HV, L0, S0, St), ( predicate_property(M:Goal, meta_predicate(Spec)), \+ control_goal(Goal) -> Goal =.. [_|Args], Spec =.. [_|Specs], foldl(meta_arg_calls(Goal, M, Ref, H, HV, St, S0), Specs, Args, L0, LM) ; LM = L0, derive(Goal, H, HV, S0) ), seen(Goal, S0, S), ( Goal = (A=B) -> ( unify_with_occurs_check(A, B) -> true ; true ) ; true ), ( progress_goal(M:Goal) -> L = false ; L = LM ). body_calls(_, _, _, _, _, L, L, S, S, _). if_then(A, C, T) :- nonvar(A), ( A = (C->T) -> true ; A = (C*->T) ). %! seen(+Goal, +Seen0, -Seen) is det. % % Add the variables of Goal to the list of variables seen. seen(Goal, S0, S) :- term_variables(Goal, GVars), append(GVars, S0, S). %! isolated(:Walk, ?Template, +Default, -Result) is det. % % Run Walk and unify Result with a copy of Template after Walk % completed. Bindings and attributes created by Walk are undone. % If Walk fails, Result is unified with Default. Calls recorded by % Walk are kept because record_call/8 stores them using nb_setarg/3. isolated(Walk, Template, Default, Result) :- Box = box(Default), ( call(Walk), nb_setarg(1, Box, Template), fail ; arg(1, Box, Result) ). control_goal(call(_)). /******************************* * DERIVED VALUES * *******************************/ % Variables that are derived from the head such that they are % guaranteed to differ from the head argument they are derived from % are marked using an attribute: subterm(I) if the variable is bound % to a proper subterm of head argument I and computed(I) if the % variable holds the result of an arithmetic operation on head % argument I that cannot be equal to its input. Marks made inside a % control structure are undone afterwards (see isolated/4), such % that they do not affect alternative branches. % The attribute value is a(Mark, Kinds), where Mark is `-`, % subterm(I) or computed(I) and Kinds is `any` or an ordered set of % the term kinds the variable may be bound to (see term_kind/2), % derived from type tests such as atom/1. Kinds is used by the loop % check (see loop_keys/2). attr_unify_hook(a(_, Kinds), Other) :- ( Kinds == any -> true ; var(Other) -> restrict_kinds(Other, Kinds) ; term_kind(Other, Kind), memberchk(Kind, Kinds) ). var_mark(V, Mark) :- get_attr(V, prolog_call_cycles, a(Mark, _)), Mark \== (-). set_mark(V, Mark) :- ( get_attr(V, prolog_call_cycles, a(_, Kinds)) -> true ; Kinds = any ), put_attr(V, prolog_call_cycles, a(Mark, Kinds)). %! restrict_kinds(+Var, +Kinds) is semidet. % % Restrict the kinds of terms Var may be bound to. Fails if no kind % remains. restrict_kinds(V, Kinds) :- ( get_attr(V, prolog_call_cycles, a(Mark, Kinds0)) -> true ; Mark = (-), Kinds0 = any ), kinds_meet(Kinds0, Kinds, Kinds1), put_attr(V, prolog_call_cycles, a(Mark, Kinds1)). kinds_meet(any, K, K) :- !. kinds_meet(K, any, K) :- !. kinds_meet(K1, K2, K) :- ord_intersection(K1, K2, K), K \== []. term_kind(T, Kind) :- ( var(T) -> Kind = var ; atom(T) -> Kind = atom ; T == [] -> Kind = nil ; integer(T) -> Kind = integer ; number(T) -> Kind = float ; string(T) -> Kind = string ; compound(T) -> Kind = compound ; Kind = blob ). %! type_kinds(?Test, ?Kinds) is nondet. % % Kinds is the ordered set of term kinds for which the type test % Test/1 succeeds. type_kinds(var, [var]). type_kinds(nonvar, [atom,blob,compound,float,integer,nil,string]). type_kinds(atom, [atom]). type_kinds(atomic, [atom,blob,float,integer,nil,string]). type_kinds(number, [float,integer]). type_kinds(integer, [integer]). type_kinds(float, [float]). type_kinds(string, [string]). type_kinds(compound, [compound]). type_kinds(callable, [atom,compound]). type_kinds(is_list, [compound,nil]). type_kinds(is_dict, [compound]). %! differ(?A, ?B) is det. % % Constrain A and B to be different, if this is consistent. differ(A, B) :- ( dif(A, B) -> true ; true ). %! derive(+Goal, +Head, +HeadVars, +Seen) is det. % % Mark the variables that are derived from Head by Goal. derive(Test, _, _, _) :- compound(Test), compound_name_arguments(Test, Name, [X]), var(X), type_kinds(Name, Kinds), !, ( restrict_kinds(X, Kinds) -> true ; true ). derive(Test, H, HV, _) :- compound(Test), compound_name_arguments(Test, Name, [A,B]), disequality(Name), !, ( head_value(B, H, I) -> mark_fresh(A, distinct(I), HV, []) % the tested value has been seen ; head_value(A, H, I) -> mark_fresh(B, distinct(I), HV, []) ; true ), differ(A, B). derive(arg(_, T, A), H, HV, S) :- head_part(T, H, I), !, mark_fresh(A, subterm(I), HV, S). derive(T =.. L, H, HV, S) :- nonvar(L), L = [_|As], head_part(T, H, I), !, list_elements(As, Elems), % the open tail is not a subterm mark_fresh(Elems, subterm(I), HV, S). derive(D is Expr, H, HV, S) :- nonvar(Expr), differs(Expr, X), head_value(X, H, I), !, mark_fresh(D, computed(I), HV, S). derive(succ(X, D), H, HV, S) :- head_value(X, H, I), !, mark_fresh(D, computed(I), HV, S). derive(succ(D, X), H, HV, S) :- head_value(X, H, I), !, mark_fresh(D, computed(I), HV, S). derive(plus(X, K, D), H, HV, S) :- nonzero(K), head_value(X, H, I), !, mark_fresh(D, computed(I), HV, S). derive(plus(K, X, D), H, HV, S) :- nonzero(K), head_value(X, H, I), !, mark_fresh(D, computed(I), HV, S). derive(_, _, _, _). % Built-in predicates that only succeed if their arguments differ. disequality(\==). disequality(\=). disequality(dif). disequality(=\=). disequality(<). disequality(>). list_elements(L, []) :- var(L), !. list_elements([H|T0], [H|T]) :- !, list_elements(T0, T). list_elements(_, []). %! differs(+Expr, -X) is semidet. % % True if the value of Expr always differs from the value of X. differs(X+K, X) :- nonzero(K). differs(K+X, X) :- nonzero(K). differs(X-K, X) :- nonzero(K). nonzero(K) :- integer(K), K =\= 0. %! head_part(@T, +Head, -I) is semidet. % % True if T is head argument I, a proper subterm of it or a variable % marked as subterm(I). The arguments of T are thus proper subterms % of head argument I. head_part(T, _H, I) :- var(T), var_mark(T, subterm(I)), !. head_part(T, H, I) :- arg(I, H, HA), ( T == HA -> true ; proper_subterm(T, HA) ), !. %! head_value(@X, +Head, -I) is semidet. % % True if X is a variable that holds head argument I or a proper % subterm thereof. An arithmetic result that differs from X is % also different from head argument I. head_value(X, H, I) :- var(X), head_part(X, H, I). %! mark_fresh(+Term, +Mark, +HeadVars, +Seen) is det. % % Mark the variables of Term that do not appear in the head and % were not seen before. mark_fresh(Term, Mark, HV, S) :- term_variables(Term, Vs), mark_vars(Vs, Mark, HV, S). mark_vars([], _, _, _). mark_vars([V|Vs], Mark, HV, S) :- ( \+ var_memberchk(V, HV), \+ var_memberchk(V, S), \+ var_mark(V, _) -> set_mark(V, Mark) ; true ), mark_vars(Vs, Mark, HV, S). %! meta_arg_calls(+Goal, +Module, +Ref, +Head, +HeadVars, +State, %! +Seen, +Spec, +Arg, +Left0, -Left) is det. % % Walk the meta-argument Arg of Goal in isolation. The extra % arguments of a closure that is called on the elements of a list % (see closure_elements/3) are marked as subterms if the list is % derived from the head. meta_arg_calls(Goal, M, Ref, H, HV, St, S0, Spec0, Arg, L0, L) :- meta_spec_extra(Spec0, Spec), arg(5, St, Count0), ( integer(Spec) -> ( callable(Arg) -> length(Extra, Spec), extend_goal(Arg, Extra, MGoal), arg(4, St, Open0), isolated(( setarg(4, St, []), mark_elements(Goal, Extra, H, HV, S0), body_calls(MGoal, M, Ref, H, HV, L0, L1, S0, _, St), prune_meta(Goal, St), arg(4, St, OpenM0) ), L1-OpenM0, L0-[], L-OpenM), reopen_meta(Goal, St, Open0, OpenM) ; L = L0 ) ; Spec == (^) -> strip_quantifier(Arg, MGoal), isolated(( setarg(4, St, []), body_calls(MGoal, M, Ref, H, HV, L0, L1, S0, _, St) ), L1, L0, L) ; L = L0 ), barrier_calls(M:Goal, St, Count0). %! barrier_calls(:Goal, +State, +Count0) is det. % % If Goal is a shift barrier (see shift_barrier/2), record that the % calls after Count0 are made through it. The calls in a nested % barrier keep the inner one. barrier_calls(Goal, St, Count0) :- arg(5, St, Count), Count > Count0, shift_barrier(Goal, PI), !, arg(6, St, Barriers0), First is Count0+1, findall(I-PI, ( between(First, Count, I), \+ memberchk(I-_, Barriers0) ), New), append(New, Barriers0, Barriers), nb_setarg(6, St, Barriers). barrier_calls(_, _, _). %! shift_barrier(:Goal, -PI) is semidet. % % True if the goal arguments of Goal are called through a barrier % for shift/1, so a tabled goal in them cannot suspend to wait for a % table that was started outside Goal. This is the case for % findall/3 and the other predicates that collect all solutions, the % failure driven loops aggregate_all/3 and foldall/4 and meta % predicates defined in C (see the predicate_property/2 property % `shift_barrier`). PI is the predicate indicator of Goal, qualified % unless Goal is defined in a system or library module. shift_barrier(M:Goal, PI) :- ( predicate_property(M:Goal, implementation_module(IM)) -> true ; IM = M ), functor(Goal, Name, Arity), predicate_property(IM:Goal, shift_barrier), ( module_property(IM, class(Class)), memberchk(Class, [system, library]) -> PI = Name/Arity ; PI = IM:Name/Arity ). % The calls in the goal of a meta-call that can leave choice points % remain open: a cut after the meta-call prunes them. This is not % the case for predicates that collect all solutions or prune their % goal. reopen_meta(Goal, St, Open0, OpenM) :- ( ( pruning_meta(Goal) ; collecting_meta(Goal) ) -> true ; append(OpenM, Open0, Open), setarg(4, St, Open) ). collecting_meta(findall(_,_,_)). collecting_meta(findall(_,_,_,_)). collecting_meta(bagof(_,_,_)). collecting_meta(setof(_,_,_)). collecting_meta(aggregate_all(_,_,_)). collecting_meta(aggregate_all(_,_,_,_)). % A grammar body (//) is called with two extra arguments. meta_spec_extra(//, 2) :- !. meta_spec_extra(Spec, Spec). % A cut inside a meta-argument is local to it. The goals of once/1, % ignore/1 and forall/2 are pruned after their first solution. prune_meta(Goal, St) :- ( pruning_meta(Goal) -> prune_open(St, []) ; true ). pruning_meta(once(_)). pruning_meta(ignore(_)). pruning_meta(forall(_,_)). %! mark_elements(+Goal, +Extra, +Head, +HeadVars, +Seen) is det. % % If Goal calls its closure on the elements of lists, mark the extra % arguments that receive the elements of a list derived from Head. mark_elements(Goal, Extra, H, HV, S) :- closure_elements(Goal, Lists, Extra), !, maplist(mark_element(H, HV, S), Lists, Extra). mark_elements(_, _, _, _, _). mark_element(H, HV, S, List, Elem) :- ( List \== (-), head_part(List, H, I) -> mark_fresh(Elem, subterm(I), HV, S) ; true ). %! closure_elements(+Goal, -Lists, ?Extra) is semidet. % % True if Goal calls its closure with the elements of Lists as the % leading extra arguments. Lists has the same length as Extra, % using `-` for extra arguments that are not list elements. closure_elements(Goal, Lists, Extra) :- compound(Goal), compound_name_arguments(Goal, Name, [_|Args]), closure_elements(Name, Args, Lists, Extra). closure_elements(maplist, Lists, Lists, _). closure_elements(foldl, Args, Lists, _) :- append(Lists0, [_,_], Args), append(Lists0, [-,-], Lists). closure_elements(include, [L,_], [L], _). closure_elements(exclude, [L,_], [L], _). closure_elements(partition, [L,_,_], [L], _). closure_elements(partition, [L,_,_,_], [L,-], _). extend_goal(M:G, Extra, M:GE) :- !, extend_goal(G, Extra, GE). extend_goal(G, [], G) :- !. extend_goal(G, Extra, GE) :- callable(G), G =.. L0, append(L0, Extra, L), GE =.. L. strip_quantifier(G, G) :- var(G), !. strip_quantifier(_^G0, G) :- !, strip_quantifier(G0, G). strip_quantifier(G, G). or(true, _, true) :- !. or(_, true, true) :- !. or(_, _, false). %! progress_goal(:Goal) is semidet. % % True if executing Goal ends left position. This is the case for % all goals that are not built-in predicates, except for library % predicates that are known not to bind arguments or fail, such as % debug/3 (see left_transparent/1), and for built-in predicates with % side effects (see side_effect/1). progress_goal(M:Goal) :- predicate_property(M:Goal, built_in), !, functor(Goal, Name, Arity), side_effect(Name/Arity). progress_goal(M:Goal) :- ( predicate_property(M:Goal, imported_from(IM)) -> true ; IM = M ), \+ left_transparent(IM:Goal). %! side_effect(?PI) is nondet. % % True if the built-in predicate PI has side effects. A recursive % call that follows such a goal is not a pure loop: input goals make % progress by consuming input and tabling a predicate that performs % output or modifies the database changes its meaning. Goals that % only inspect a stream, such as peek_char/2, are not included. side_effect(PI) :- side_effect_list(PIs), member(PI, PIs). side_effect_list( [ % input read/1, read/2, read_term/2, read_term/3, read_clause/3, read_term_with_history/2, get_char/1, get_char/2, get_code/1, get_code/2, get_byte/1, get_byte/2, get0/1, get0/2, get/1, get/2, get_single_char/1, skip/1, skip/2, read_pending_codes/3, read_pending_chars/3, read_string/3, read_string/5, % output write/1, write/2, writeln/1, writeln/2, print/1, print/2, writeq/1, writeq/2, write_canonical/1, write_canonical/2, write_term/2, write_term/3, format/1, format/2, format/3, nl/0, nl/1, put_char/1, put_char/2, put_code/1, put_code/2, put_byte/1, put_byte/2, tab/1, tab/2, flush_output/0, flush_output/1, print_message/2, print_message_lines/3, % streams open/3, open/4, close/1, close/2, see/1, seen/0, tell/1, append/1, told/0, set_input/1, set_output/1, set_stream/2, set_stream_position/2, seek/4, % database assert/1, assert/2, asserta/1, asserta/2, assertz/1, assertz/2, retract/1, retractall/1, erase/1, recorda/2, recorda/3, recordz/2, recordz/3, flag/3, abolish/1, abolish/2, % global state nb_setval/2, b_setval/2, setarg/3, nb_setarg/3, nb_linkarg/3, nb_linkval/2, % threads and the environment thread_get_message/1, thread_get_message/2, thread_get_message/3, thread_send_message/2, thread_send_message/3, thread_create/2, thread_create/3, thread_join/1, thread_join/2, sleep/1, shell/1, shell/2, halt/0, halt/1, get_time/1 ]). :- multifile left_transparent/1. %! left_transparent(:Goal) is semidet. % % Multifile hook that is true if a call to Goal does not end the % left position of the calls that follow it. This is intended for % non built-in predicates that do not bind arguments and do not fail, % such as debug/3. left_transparent(prolog_debug:debug(_,_,_)). left_transparent(prolog_debug:debug(_)). left_transparent(prolog_debug:assertion(_)). left_transparent(error:must_be(_,_)). %! record_call(+PI, +Goal, +Ref, +Head, +HeadVars, +Left0, +Seen, %! +State) is det. % % Record the annotation of a call. A call that passes a proper % subterm of a head argument or a value computed from a head % argument that differs from it is not in left position: it cannot % be a variant of the calling goal, so tabling does not help. record_call(PI, Goal, Ref, Head, HVars, Left0, Seen, State) :- call_args(Goal, Head, HVars, Seen, Args), ( ( memberchk(subterm, Args) ; memberchk(computed, Args) ; memberchk(distinct, Args) ) -> Left = false ; Left = Left0 ), decreasing(Goal, Head, Decreasing), arg(2, State, Earlier), fresh_vars(Goal, HVars, Seen, Fresh), arg(5, State, I0), I is I0+1, nb_setarg(5, State, I), arg(4, State, Open), setarg(4, State, [I|Open]), arg(1, State, L0), copy_term((Ref-PI)-call(Left, Args, Decreasing, t(Head, Goal, Earlier, Fresh), I), Rec), nb_setarg(1, State, [Rec|L0]). % Fresh is the list of unmarked variables of Goal that do not appear % in the head or earlier in the body. These are unbound when Goal % is called. fresh_vars(Goal, HVars, Seen, Fresh) :- term_variables(Goal, GVars), include(fresh_var(HVars, Seen), GVars, Fresh). fresh_var(HVars, Seen, V) :- \+ var_memberchk(V, HVars), \+ var_memberchk(V, Seen), \+ var_mark(V, _). call_args(Goal, Head, HVars, Seen, Args) :- Goal =.. [_|GArgs], Head =.. [_|HArgs], maplist(arg_class(HArgs, HVars, Seen), GArgs, Args). arg_class(HArgs, HVars, Seen, A, Class) :- ( var(A) -> ( var_mark(A, Mark) -> functor(Mark, Class, 1) ; proper_subterm_of_any(A, HArgs) -> Class = subterm ; var_memberchk(A, HVars) -> Class = pass ; var_memberchk(A, Seen) -> Class = bound_earlier ; Class = fresh ) ; ground(A) -> Class = ground ; proper_subterm_of_any(A, HArgs) -> Class = subterm ; Class = constructed ). proper_subterm_of_any(A, HArgs) :- member(HA, HArgs), proper_subterm(A, HA), !. proper_subterm(Sub, Term) :- compound(Term), arg(_, Term, Arg), ( Sub == Arg -> true ; proper_subterm(Sub, Arg) ), !. var_memberchk(V, [H|T]) :- ( V == H -> true ; var_memberchk(V, T) ). decreasing(Goal, Head, Decreasing) :- ( functor(Goal, Name, Arity), functor(Head, Name, Arity), arg(I, Goal, GA), ( var(GA), var_mark(GA, subterm(I)) -> true ; arg(I, Head, HA), proper_subterm(GA, HA) ) -> Decreasing = true ; Decreasing = false ). /******************************* * LOOP CHECK * *******************************/ %! loop_keys(+Edges, -LoopKeys) is det. % % LoopKeys is an assoc holding the keys of the edges in left position % that take part in a _loop_: a sequence of calls in left position % through which a goal may call a variant of itself. Edges is a % list of `Key-Transition-Edge`, where Transition is a term % t(Head, Goal, Earlier, Fresh) that describes the call Goal in the % clause with head Head. Earlier is a list of heads of the clauses % before it that commit unconditionally (see commit_heads/2) and % Fresh is the list of variables of Goal that are unbound when Goal % is called. % % For each transition, we search for a sequence of transitions, % unifying the goal of each with the head of the next, that ends in % a goal for the predicate we started with that unifies with the % head we started with. Unification uses the occurs check and % respects the constraints added by derive/4: dif/2 for values that % differ from their source and the term kinds derived from type % tests, where the fresh variables of the final goal are unbound. % Thus, a goal for which the clause passes a proper subterm, % a term that contains the argument, a term with a different % principal functor, an arithmetic result that differs from the % argument or a value that is tested to differ from the argument % cannot be a variant. A sequence is pruned if a head is an % instance of a head in its Earlier list. The search depth is % limited to the number of transitions plus one, at most 10. If the % search takes too many steps, all edges in left position are % considered part of a loop. loop_keys(Edges, LoopKeys) :- findall(tr(Key, From, To, T), ( member(Key-T-E, Edges), E.left == true, From = E.from, To = E.to ), Trs), empty_assoc(K0), ( Trs == [] -> LoopKeys = K0 ; length(Trs, N), MaxDepth is min(10, N+1), index_transitions(Trs, Index), Budget = budget(20000), catch(foldl(start_loop(Index, MaxDepth, Budget), Trs, K0, LoopKeys), loop_budget, foldl(add_tr_key, Trs, K0, LoopKeys)) ). index_transitions(Trs, Index) :- findall(From-Tr, (member(Tr, Trs), Tr = tr(_, From, _, _)), Pairs0), keysort(Pairs0, Pairs), group_pairs_by_key(Pairs, Grouped), list_to_assoc(Grouped, Index). add_tr_key(tr(Key, _, _, _), K0, K) :- put_assoc(Key, K0, true, K). add_key(Key, K0, K) :- put_assoc(Key, K0, true, K). start_loop(Index, MaxDepth, Budget, tr(Key, From, To, T), K0, K) :- copy_term(T, t(H0, G0, E0, F0)), ( loop_from(Index, MaxDepth, Budget, From-H0-E0, To, G0-F0, [Key], 1, Keys) -> foldl(add_key, Keys, K0, K) ; K = K0 ). loop_from(Index, MaxDepth, Budget, Start, To, G-F, Keys0, D, Keys) :- Start = From-H0-E0, ( To == From, possible_variant(H0, E0, G, F) -> Keys = Keys0 ; D < MaxDepth, get_assoc(To, Index, Trs), member(tr(Key, To, To2, T), Trs), step(Budget), copy_term(T, t(H1, G1, E1, F1)), unify_with_occurs_check(G, H1), \+ violated(E1, H1), D1 is D+1, loop_from(Index, MaxDepth, Budget, Start, To2, G1-F1, [Key|Keys0], D1, Keys) ). possible_variant(H0, E0, G, Fresh) :- \+ \+ ( maplist(unbound, Fresh), unify_with_occurs_check(H0, G), \+ violated(E0, H0) ). unbound(V) :- ( var(V) -> restrict_kinds(V, [var]) ; true ). violated(Earlier, Head) :- member(E, Earlier), subsumes_term(E, Head), !. step(Budget) :- arg(1, Budget, N0), ( N0 > 0 -> N is N0-1, nb_setarg(1, Budget, N) ; throw(loop_budget) ). %! general_transition(+Edge, -Transition) is det. % % Transition for an edge whose call could not be analysed: a call % with fresh arguments from a clause with a general head. general_transition(Edge, t(Head, Goal, [], [])) :- pi_head(Edge.from, Head), pi_head(Edge.to, Goal). pi_head(_:Name/Arity, Head) :- functor(Head, Name, Arity). /******************************* * LEFT RECURSION * *******************************/ %! left_recursion(-LeftRecursion:dict, +Options) is nondet. %! left_recursion(+SCCs, -LeftRecursion:dict, +Options) is nondet. % % Enumerate the left recursion in the call graph. For each set of % predicates that are mutually recursive through calls in left % position (see module header), LeftRecursion is a dict with the % keys below. The first form computes the SCCs using % call_graph_sccs/2 from Options. % % - members % Sorted list of predicate indicators involved. % - cycle % List of edges (see call_graph_sccs/2) that form a shortest % cycle through the first member. % - edges % All left edges between the members. left_recursion(LeftRec, Options0) :- meta_options(is_meta, Options0, Options), call_graph_sccs(SCCs, Options), left_recursion(SCCs, LeftRec, Options). left_recursion(SCCs, LeftRec, _Options) :- member(SCC, SCCs), include(left_edge, SCC.edges, LeftEdges), LeftEdges \== [], maplist(edge_pair, LeftEdges, Pairs), pairs_keys(Pairs, Fs), pairs_values(Pairs, Ts), append(Fs, Ts, Vs0), sort(Vs0, Vs), vertices_edges_to_ugraph(Vs, Pairs, UGraph), ugraph_sccs(UGraph, Components), include(cyclic_component(UGraph), Components, Cyclic), member(Members0, Cyclic), sort(Members0, Members), list_to_assoc_set(Members, MSet), include(internal_edge(MSet), LeftEdges, Edges), Members = [Start|_], shortest_cycle(Start, Edges, Cycle), LeftRec = left_recursion{members:Members, cycle:Cycle, edges:Edges}. left_edge(Edge) :- Edge.left == true. %! shortest_cycle(+Start, +Edges, -Cycle) is det. % % Breadth-first search for the shortest path from Start back to % Start over Edges. shortest_cycle(Start, Edges, Cycle) :- ( member(E, Edges), E.from == Start, E.to == Start -> Cycle = [E] ; empty_assoc(Visited0), put_assoc(Start, Visited0, -, Visited), bfs([Start-[]], Start, Edges, Visited, RevCycle), reverse(RevCycle, Cycle) ). bfs([V-Path|Queue], Start, Edges, Visited, Cycle) :- findall(E, (member(E, Edges), E.from == V), Out), ( member(E, Out), E.to == Start -> Cycle = [E|Path] ; foldl(bfs_next(Path), Out, Queue-Visited, Queue1-Visited1), bfs(Queue1, Start, Edges, Visited1, Cycle) ). bfs_next(Path, E, Q0-V0, Q-V) :- To = E.to, ( get_assoc(To, V0, _) -> Q = Q0, V = V0 ; put_assoc(To, V0, -, V), append(Q0, [To-[E|Path]], Q) ).