
prolog_call_cycles.pl -- 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:
system are never included.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.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).
call_graph(-Graph:dict, +Options) is detM:Name/Arity.
files(Files), these
are the predicates with clauses in Files and the dynamic
predicates declared in Files, including the files they
include.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(true) is given.
scope(+Options, +WalkOptions, -Vertices, -Clauses) is det[private]
goal_scope(:Goal, +Options, +WalkOptions, -Vertices, -Clauses)[private]
goal_roots(:Goal, +WalkOptions, -Roots) is det[private]
reachable(+Frontier, +Filter, +WalkOptions, +Seen0, -Seen) is det[private]
callees(+Clauses, +WalkOptions, -PIs) is det[private]
call_graph_sccs(-SCCs:list(dict), +Options) is det
call_graph_sccs(+Graph, -SCCs:list(dict), +Options) is dettrue 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.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.true if this is a call to the same predicate and some
argument is a proper subterm of the same argument in the head.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.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.
ugraph_sccs(+UGraph, -SCCs:list(list)) is det[private]
refine_locations(+Edges0, -Edges, +Options) is det[private]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.
number_from_end(+Keyed:list(pair), -Numbered:list(pair)) is det[private](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.
annotate_edges(+Edges0, -Edges) is det[private]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).
commit_heads(+ClauseRefs, -Commits) is det[private]
clause_calls(+Commits, +ClauseRef, -Calls) is det[private](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).
prune_open(+State, +Open0) is det[private]
merge_open(+State, +Open0, +Opens) is det[private]
body_calls(+Body, +Module, +Ref, +Head, +HeadVars, +Left0, -Left, +Seen0, -Seen, +State) is det[private]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.
seen(+Goal, +Seen0, -Seen) is det[private]
isolated(:Walk, ?Template, +Default, -Result) is det[private]
restrict_kinds(+Var, +Kinds) is semidet[private]
type_kinds(?Test, ?Kinds) is nondet[private]
differ(?A, ?B) is det[private]
derive(+Goal, +Head, +HeadVars, +Seen) is det[private]
differs(+Expr, -X) is semidet[private]
head_part(@T, +Head, -I) is semidet[private]subterm(I). The arguments of T are thus proper subterms
of head argument I.
head_value(@X, +Head, -I) is semidet[private]
mark_fresh(+Term, +Mark, +HeadVars, +Seen) is det[private]
meta_arg_calls(+Goal, +Module, +Ref, +Head, +HeadVars, +State, +Seen, +Spec, +Arg, +Left0, -Left) is det[private]
barrier_calls(:Goal, +State, +Count0) is det[private]
shift_barrier(:Goal, -PI) is semidet[private]shift_barrier). PI is the predicate indicator of Goal, qualified
unless Goal is defined in a system or library module.
mark_elements(+Goal, +Extra, +Head, +HeadVars, +Seen) is det[private]
closure_elements(+Goal, -Lists, ?Extra) is semidet[private]- for extra arguments that are not list elements.
progress_goal(:Goal) is semidet[private]
side_effect(?PI) is nondet[private]
left_transparent(:Goal) is semidet[multifile]
record_call(+PI, +Goal, +Ref, +Head, +HeadVars, +Left0, +Seen, +State) is det[private]
loop_keys(+Edges, -LoopKeys) is det[private]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.
general_transition(+Edge, -Transition) is det[private]
left_recursion(-LeftRecursion:dict, +Options) is nondet
left_recursion(+SCCs, -LeftRecursion:dict, +Options) is nondet
shortest_cycle(+Start, +Edges, -Cycle) is det[private]