Did you know ... Search Documentation:
prolog_call_cycles.pl -- Find recursion in the static call graph
PublicShow source

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).

Source 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.
Source scope(+Options, +WalkOptions, -Vertices, -Clauses) is det[private]
Determine the predicates (Vertices) in scope and the clauses we must walk.
Source goal_scope(:Goal, +Options, +WalkOptions, -Vertices, -Clauses)[private]
The scope consists of all predicates reachable from Goal that satisfy the filter defined by the files and module options.
Source goal_roots(:Goal, +WalkOptions, -Roots) is det[private]
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.
Source reachable(+Frontier, +Filter, +WalkOptions, +Seen0, -Seen) is det[private]
Seen is Seen0 extended with all predicates in scope that are reachable from the predicates in Frontier.
Source callees(+Clauses, +WalkOptions, -PIs) is det[private]
PIs is the sorted set of predicates called by Clauses.
Source call_graph_sccs(-SCCs:list(dict), +Options) is det
Source 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.

Source ugraph_sccs(+UGraph, -SCCs:list(list)) is det[private]
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).
Source refine_locations(+Edges0, -Edges, +Options) is det[private]
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.
Source number_from_end(+Keyed:list(pair), -Numbered:list(pair)) is det[private]
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.
Source annotate_edges(+Edges0, -Edges) is det[private]
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).
Source commit_heads(+ClauseRefs, -Commits) is det[private]
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.
Source clause_calls(+Commits, +ClauseRef, -Calls) is det[private]
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).
Source prune_open(+State, +Open0) is det[private]
Mark the calls that were opened since Open0 as pruned. With Open0 = [], this marks all open calls.
Source merge_open(+State, +Open0, +Opens) is det[private]
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.
Source body_calls(+Body, +Module, +Ref, +Head, +HeadVars, +Left0, -Left, +Seen0, -Seen, +State) is det[private]
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.

Source seen(+Goal, +Seen0, -Seen) is det[private]
Add the variables of Goal to the list of variables seen.
Source isolated(:Walk, ?Template, +Default, -Result) is det[private]
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.
Source restrict_kinds(+Var, +Kinds) is semidet[private]
Restrict the kinds of terms Var may be bound to. Fails if no kind remains.
Source type_kinds(?Test, ?Kinds) is nondet[private]
Kinds is the ordered set of term kinds for which the type test Test/1 succeeds.
Source differ(?A, ?B) is det[private]
Constrain A and B to be different, if this is consistent.
Source derive(+Goal, +Head, +HeadVars, +Seen) is det[private]
Mark the variables that are derived from Head by Goal.
Source differs(+Expr, -X) is semidet[private]
True if the value of Expr always differs from the value of X.
Source head_part(@T, +Head, -I) is semidet[private]
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.
Source head_value(@X, +Head, -I) is semidet[private]
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.
Source mark_fresh(+Term, +Mark, +HeadVars, +Seen) is det[private]
Mark the variables of Term that do not appear in the head and were not seen before.
Source meta_arg_calls(+Goal, +Module, +Ref, +Head, +HeadVars, +State, +Seen, +Spec, +Arg, +Left0, -Left) is det[private]
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.
Source barrier_calls(:Goal, +State, +Count0) is det[private]
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.
Source shift_barrier(:Goal, -PI) is semidet[private]
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.
Source mark_elements(+Goal, +Extra, +Head, +HeadVars, +Seen) is det[private]
If Goal calls its closure on the elements of lists, mark the extra arguments that receive the elements of a list derived from Head.
Source closure_elements(+Goal, -Lists, ?Extra) is semidet[private]
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.
Source progress_goal(:Goal) is semidet[private]
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).
Source side_effect(?PI) is nondet[private]
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.
Source left_transparent(:Goal) is semidet[multifile]
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.
Source record_call(+PI, +Goal, +Ref, +Head, +HeadVars, +Left0, +Seen, +State) is det[private]
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.
Source loop_keys(+Edges, -LoopKeys) is det[private]
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.

Source general_transition(+Edge, -Transition) is det[private]
Transition for an edge whose call could not be analysed: a call with fresh arguments from a clause with a general head.
Source left_recursion(-LeftRecursion:dict, +Options) is nondet
Source 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.
Source shortest_cycle(+Start, +Edges, -Cycle) is det[private]
Breadth-first search for the shortest path from Start back to Start over Edges.

Re-exported predicates

The following predicates are exported from this file while their implementation is defined in imported modules or non-module files loaded by this module.

Source call_graph_sccs(-SCCs:list(dict), +Options) is det
Source 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.

Source left_recursion(-LeftRecursion:dict, +Options) is nondet
Source 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.