View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2026, SWI-Prolog Solutions b.v.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(prolog_call_cycles,
   36          [ call_graph/2,               % -Graph, +Options
   37            call_graph_sccs/2,          % -SCCs, +Options
   38            call_graph_sccs/3,          % +Graph, -SCCs, +Options
   39            left_recursion/2,           % -LeftRecursion, +Options
   40            left_recursion/3            % +SCCs, -LeftRecursion, +Options
   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
   65/** <module> Find recursion in the static call graph
   66
   67This library builds the static call graph of loaded Prolog code using
   68library(prolog_codewalk) and finds the _recursion_ in it: the strongly
   69connected components (SCCs) of the graph and, within these, the _left
   70recursion_. A call is in _left_ position if, on some execution path
   71through the clause body, no call to a non-built-in predicate precedes
   72it, no built-in predicate with side effects such as reading input
   73precedes it and no argument of the call is guaranteed to differ from
   74the head argument it is derived from.  Such arguments are proper
   75subterms of a head argument, either directly or obtained using arg/3
   76or =../2, values computed from a head argument using an arithmetic
   77operation that cannot return its input, such as `N-1`, and values that
   78are tested to differ from a head argument, e.g., using `\==/2`.  A call
   79that is not left cannot be a variant of the calling goal.  It may
   80still recurse forever, but tabling does not help in that case.
   81
   82Left recursion is a _loop_ of calls in left position through which a
   83goal may call a variant of itself.  Such a loop runs forever under
   84Prolog's SLD resolution.  Loops are found by unfolding: starting from
   85a call in left position, the goal of each call is unified with the
   86head of a clause that has a call in left position, until we obtain a
   87goal for the predicate we started with that unifies with the head we
   88started with.  Unification uses the occurs check and takes type tests
   89such as atom/1 or var/1 into account.  Clauses are skipped if an
   90earlier clause that commits by a cut directly after the head or using
   91single sided unification (=>) applies.  Thus, `p(count) :- p(sum(1))`
   92or `p(X) :- atom(X), !, p([X])` are not left recursive, while
   93`p(a) :- p(b)` together with `p(b) :- p(a)` is.
   94
   95The subterm condition makes recursion that consumes input, such as
   96grammar rules that start with a terminal, not left recursive.
   97Unifications (=/2) are taken into account, which is needed for the
   98code produced by the DCG translation.  Unifications inside a branch of
   99a disjunction only affect the calls in that branch, where the
  100unifications in the condition of an if-then-else also hold in its
  101then-branch.  If a closure is called on the elements of a list, as in
  102maplist/2, the elements of a list that is derived from the head are
  103subterms.  For example, the recursive call in the first rule below is
  104not in left position, while it is in the second:
  105
  106```
  107ws --> [C], { code_type(C, space) }, !, ws.
  108lr --> lr, "a".
  109```
  110
  111Each call edge inside an SCC is annotated with the clause and source
  112location of the call and with an abstraction of the call's arguments.
  113This information is used by library(prolog_auto_table) to decide which
  114predicates to table, but is also useful for program analysis tools.
  115
  116The scope of the analysis is defined by the options below. Only calls
  117_between_ predicates in scope become edges of the graph:
  118
  119  - goal(:Goal)
  120    Analyse the predicates that are reachable from Goal.  If files
  121    or module are given as well, these restrict the reachable
  122    predicates to those defined in the given files or modules.
  123    Predicates in modules of class `system` are never included.
  124  - files(+FileOrFiles)
  125    Analyse the predicates that have clauses in the given file(s), the
  126    dynamic predicates declared there and the foreign predicates of the
  127    modules they define.  Files included using include/1 are part of
  128    the file that includes them: clauses in an included file belong to
  129    the file that loads it, and an included file given as FileOrFiles
  130    stands for the file(s) that load it.
  131  - module(+ModuleOrModules)
  132    Analyse the predicates defined in Module.  A list of modules is
  133    allowed.
  134  - predicates(+PIs)
  135    Analyse the given (qualified) predicate indicators.
  136  - external(+Boolean)
  137    If `true` (default `false`), also return the edges from predicates
  138    in scope to predicates outside the scope in the `external` key of
  139    the graph.
  140
  141Other options are passed to prolog_walk_code/1, notably autoload(Bool),
  142walk_meta_predicates(Bool) and infer_meta_predicates(Bool).
  143*/
  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
  154%!  call_graph(-Graph:dict, +Options) is det.
  155%
  156%   Compute the static call graph for the predicates selected by
  157%   Options.  Graph is a dict with the keys below.  Predicates are
  158%   represented by qualified predicate indicators, `M:Name/Arity`.
  159%
  160%     - vertices
  161%       Sorted list of predicates in scope.  For files(Files), these
  162%       are the predicates with clauses in Files and the dynamic
  163%       predicates declared in Files, including the files they
  164%       include.
  165%     - ugraph
  166%       The graph as a library(ugraphs) graph.
  167%     - edges
  168%       List of edges between predicates in scope.  Each edge is a
  169%       dict `edge{from:PI, to:PI, clause:ClauseRef, location:Dict}`,
  170%       where `Location` is the location dict of prolog_walk_code/1
  171%       (option `on_edge`).  If a predicate calls another one multiple
  172%       times, there is an edge for each call.
  173%     - external
  174%       List of edges from predicates in scope to other predicates.
  175%       Only filled if the option external(true) is given.
  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
  262%!  scope(+Options, +WalkOptions, -Vertices, -Clauses) is det.
  263%
  264%   Determine the predicates (Vertices) in scope and the clauses we
  265%   must walk.
  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
  319%!  goal_scope(:Goal, +Options, +WalkOptions, -Vertices, -Clauses)
  320%
  321%   The scope consists of all predicates reachable from Goal that
  322%   satisfy the filter defined by the files and module options.
  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
  368%!  goal_roots(:Goal, +WalkOptions, -Roots) is det.
  369%
  370%   Roots is the set of predicates called by Goal.  Goal is walked
  371%   as the body of a temporary clause, such that prolog_walk_code/1
  372%   deals with control structures and meta-predicates.
  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
  380%!  reachable(+Frontier, +Filter, +WalkOptions, +Seen0, -Seen) is det.
  381%
  382%   Seen is Seen0 extended with all predicates in scope that are
  383%   reachable from the predicates in Frontier.
  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
  403%!  callees(+Clauses, +WalkOptions, -PIs) is det.
  404%
  405%   PIs is the sorted set of predicates called by Clauses.
  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
  464%   loading_file(+File, -LoadedFile) is nondet.
  465%
  466%   LoadedFile is File if File is loaded, and else the loaded file
  467%   that (indirectly) includes File.
  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,                       % '$load_context_module'/3, etc.
  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
  492%   source_file_dynamic(+File, -PI) is nondet.
  493%
  494%   PI is a dynamic predicate declared in File.  It is in scope even if
  495%   File has no clauses for it.
  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
  504%   source_file_foreign(+File, -PI) is nondet.
  505%
  506%   PI is a foreign predicate of the module defined in File, e.g.,
  507%   loaded by use_foreign_library/1 or load_foreign_resource/1 of
  508%   library(qpforeign).  Foreign predicates have no source file, but
  509%   the code of File calls them as local predicates.
  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		 /*******************************
  535		 *              SCC             *
  536		 *******************************/
  537
  538%!  call_graph_sccs(-SCCs:list(dict), +Options) is det.
  539%!  call_graph_sccs(+Graph, -SCCs:list(dict), +Options) is det.
  540%
  541%   Compute the strongly connected components of the call graph that
  542%   contain at least one cycle, i.e., that have more than one member
  543%   or a single member that calls itself.  Each SCC is a dict with the
  544%   keys below.  The first form computes the graph using call_graph/2
  545%   from Options.
  546%
  547%     - members
  548%       Sorted list of predicate indicators in the SCC.
  549%     - edges
  550%       List of edges between members of the SCC.  Each edge is a
  551%       dict as described with call_graph/2, extended with the keys
  552%       below.
  553%       - left
  554%         `true` if the call is in left position and may take part in
  555%         a loop (see module header).  Note that a call with a
  556%         `subterm`, `computed` or `distinct` argument is never in
  557%         left position.
  558%       - args
  559%         List of argument abstractions for the call. Each element is
  560%         one of `fresh` (a variable that does not appear earlier in
  561%         the clause), `pass` (a variable from the head),
  562%         `bound_earlier` (a variable that appears in an earlier
  563%         goal of the body), `ground` (a ground term), `subterm`
  564%         (a proper subterm of a head argument, also if obtained
  565%         using arg/3 or =../2), `computed` (the result of an
  566%         arithmetic operation on a head argument that differs from
  567%         its input, such as `N-1`), `distinct` (a value that is
  568%         tested to differ from a head argument, e.g., using `X \== Y`)
  569%         or `constructed` (a term with
  570%         variables that is not a subterm of a head argument, e.g.,
  571%         an accumulator).  If the call could not be analysed, this
  572%         is `unknown`.
  573%       - decreasing
  574%         `true` if this is a call to the same predicate and some
  575%         argument is a proper subterm of the same argument in the head.
  576%       - pruned
  577%         `true` if a cut can prune the call: a cut after the call in
  578%         its clause, the cut of the if-then-else whose condition holds
  579%         the call, \+/1, once/1, ignore/1 or forall/2.  If the
  580%         callee is tabled and part of the same SCC, such a cut raises
  581%         a permission error.
  582%       - barrier
  583%         `none` or the predicate through whose goal argument the call
  584%         is made if that is a barrier for shift/1: findall/3 and the
  585%         other predicates that collect all solutions, aggregate_all/3,
  586%         foldall/4 and predicates defined in C.  A tabled goal cannot
  587%         suspend through a barrier to wait for an incomplete table.
  588%
  589%   If the option locations(true) is given (default), the location of
  590%   the edges in the SCCs is refined by walking the involved clauses
  591%   with source information.
  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
  619%!  ugraph_sccs(+UGraph, -SCCs:list(list)) is det.
  620%
  621%   Tarjan's algorithm for finding the strongly connected components.
  622%   SCCs is a list of lists of vertices, in reverse topological order
  623%   (a component appears before the components that call it).
  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
  638% S is t(Counter, Index, Stack, SCCs).  Index maps a vertex to
  639% i(Index, LowLink, OnStack).
  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		 /*******************************
  680		 *           LOCATIONS          *
  681		 *******************************/
  682
  683%!  refine_locations(+Edges0, -Edges, +Options) is det.
  684%
  685%   Walk the clauses holding Edges0 again with source(true) to obtain
  686%   the exact location of each call.  The walk generates the edges in
  687%   the same order, so we match on the clause, the callee and the
  688%   number of the call to the callee in the clause.
  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
  726%   The calls to a callee in a clause are numbered from the _end_ of
  727%   the clause.  When prolog_walk_code/1 finds a meta-call it cannot
  728%   resolve, it restarts the walk of the clause body, reporting the
  729%   calls before it twice.  Numbering from the end makes the real
  730%   calls of the clause match, while the duplicates get a number that
  731%   is higher than the number of calls to the callee.
  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
  745%!  number_from_end(+Keyed:list(pair), -Numbered:list(pair)) is det.
  746%
  747%   Numbered contains `(Key-N)-Value` for each `Key-Value` in Keyed,
  748%   where N is the number of elements with the same Key from the end
  749%   of the list, starting at 1.
  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		 /*******************************
  770		 *          ANNOTATION          *
  771		 *******************************/
  772
  773%!  annotate_edges(+Edges0, -Edges) is det.
  774%
  775%   Add the keys `left`, `args` and `decreasing` to the edges.  We
  776%   analyse the clause of each edge, generating the calls in the same
  777%   order as prolog_walk_code/1 and match them on the callee and the
  778%   number of the call to the callee in the clause.  If the match
  779%   fails, we use the conservative annotation (left, unknown args).
  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                  % duplicate from a restarted walk
  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
  814%!  commit_heads(+ClauseRefs, -Commits) is det.
  815%
  816%   Commits is an assoc that maps each clause in ClauseRefs to the
  817%   heads of the clauses of its predicate before it that commit
  818%   unconditionally to their clause.  A call that is an instance of
  819%   one of these heads never reaches the clause.  Clauses commit
  820%   unconditionally if their body starts with a cut or, for
  821%   predicates defined using single sided unification (=>), if they
  822%   have no guard.
  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
  874%!  clause_calls(+Commits, +ClauseRef, -Calls) is det.
  875%
  876%   Calls is a list of `(Clause-PI-N)-call(Left, Args, Decreasing,
  877%   Transition, Pruned, Barrier)` for all calls in the body of
  878%   ClauseRef, where N numbers the calls to PI from the end of the
  879%   clause (see number_from_end/2), Transition is used by loop_keys/2,
  880%   Pruned is `true` if a cut can prune the call (see prune_open/2)
  881%   and Barrier is the predicate through which the call is made that
  882%   is a barrier for suspending a tabled goal or `none` (see
  883%   shift_barrier/2).
  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
  918%   The state of walking a clause body is a term s(Calls, Earlier,
  919%   Pruned, Open, Count, Barriers).  Calls is the list of recorded
  920%   calls, Earlier the list of heads used by the loop check (see
  921%   commit_heads/2), Pruned the list of indices of calls that can be
  922%   pruned by a cut, Open the list of indices of the calls on the
  923%   current execution path that a clause-level cut prunes, Count the
  924%   number of calls recorded and Barriers a list Index-PI of the calls
  925%   made through a shift barrier PI (see shift_barrier/2).  Open is updated using the
  926%   backtrackable setarg/3, such that isolated/4 restores it.
  927
  928%!  prune_open(+State, +Open0) is det.
  929%
  930%   Mark the calls that were opened since Open0 as pruned.  With
  931%   Open0 = [], this marks all open calls.
  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
  942%!  merge_open(+State, +Open0, +Opens) is det.
  943%
  944%   Set the open calls after a disjunction to Open0 plus the calls
  945%   opened by its branches, where each element of Opens is Open0
  946%   extended with the calls of a branch.
  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
  959%!  body_calls(+Body, +Module, +Ref, +Head, +HeadVars,
  960%!             +Left0, -Left, +Seen0, -Seen, +State) is det.
  961%
  962%   Walk Body in the same order as prolog_walk_code/1.  Left0 is
  963%   `true` if no call to a non-built-in predicate precedes Body on some
  964%   execution path.  Seen0 is a list of variables that appear in
  965%   goals of the body before Body.
  966%
  967%   Unifications (=/2) are executed, such that the classification of
  968%   later calls takes aliasing into account.  Alternative branches,
  969%   negation and the goals of meta-calls are walked in isolation (see
  970%   isolated/4): their bindings and the marks they create (see
  971%   derive/4) are undone afterwards.  The unifications in the
  972%   condition of an if-then-else hold in its then-branch.
  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
 1073%!  seen(+Goal, +Seen0, -Seen) is det.
 1074%
 1075%   Add the variables of Goal to the list of variables seen.
 1076
 1077seen(Goal, S0, S) :-
 1078    term_variables(Goal, GVars),
 1079    append(GVars, S0, S).
 1080
 1081%!  isolated(:Walk, ?Template, +Default, -Result) is det.
 1082%
 1083%   Run Walk and unify Result with a copy of Template after Walk
 1084%   completed.  Bindings and attributes created by Walk are undone.
 1085%   If Walk fails, Result is unified with Default.  Calls recorded by
 1086%   Walk are kept because record_call/8 stores them using nb_setarg/3.
 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		 /*******************************
 1099		 *        DERIVED VALUES        *
 1100		 *******************************/
 1101
 1102%   Variables that are derived from the head such that they are
 1103%   guaranteed to differ from the head argument they are derived from
 1104%   are marked using an attribute: subterm(I) if the variable is bound
 1105%   to a proper subterm of head argument I and computed(I) if the
 1106%   variable holds the result of an arithmetic operation on head
 1107%   argument I that cannot be equal to its input.  Marks made inside a
 1108%   control structure are undone afterwards (see isolated/4), such
 1109%   that they do not affect alternative branches.
 1110
 1111%   The attribute value is a(Mark, Kinds), where Mark is `-`,
 1112%   subterm(I) or computed(I) and Kinds is `any` or an ordered set of
 1113%   the term kinds the variable may be bound to (see term_kind/2),
 1114%   derived from type tests such as atom/1.  Kinds is used by the loop
 1115%   check (see loop_keys/2).
 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
 1137%!  restrict_kinds(+Var, +Kinds) is semidet.
 1138%
 1139%   Restrict the kinds of terms Var may be bound to.  Fails if no kind
 1140%   remains.
 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
 1168%!  type_kinds(?Test, ?Kinds) is nondet.
 1169%
 1170%   Kinds is the ordered set of term kinds for which the type test
 1171%   Test/1 succeeds.
 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
 1186%!  differ(?A, ?B) is det.
 1187%
 1188%   Constrain A and B to be different, if this is consistent.
 1189
 1190differ(A, B) :-
 1191    (   dif(A, B)
 1192    ->  true
 1193    ;   true
 1194    ).
 1195
 1196%!  derive(+Goal, +Head, +HeadVars, +Seen) is det.
 1197%
 1198%   Mark the variables that are derived from Head by Goal.
 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, [])  % the tested value has been seen
 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),           % the open tail is not a subterm
 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
 1259%   Built-in predicates that only succeed if their arguments differ.
 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
 1276%!  differs(+Expr, -X) is semidet.
 1277%
 1278%   True if the value of Expr always differs from the value of X.
 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
 1288%!  head_part(@T, +Head, -I) is semidet.
 1289%
 1290%   True if T is head argument I, a proper subterm of it or a variable
 1291%   marked as subterm(I).  The arguments of T are thus proper subterms
 1292%   of head argument I.
 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
 1306%!  head_value(@X, +Head, -I) is semidet.
 1307%
 1308%   True if X is a variable that holds head argument I or a proper
 1309%   subterm thereof.  An arithmetic result that differs from X is
 1310%   also different from head argument I.
 1311
 1312head_value(X, H, I) :-
 1313    var(X),
 1314    head_part(X, H, I).
 1315
 1316%!  mark_fresh(+Term, +Mark, +HeadVars, +Seen) is det.
 1317%
 1318%   Mark the variables of Term that do not appear in the head and
 1319%   were not seen before.
 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
 1335%!  meta_arg_calls(+Goal, +Module, +Ref, +Head, +HeadVars, +State,
 1336%!                 +Seen, +Spec, +Arg, +Left0, -Left) is det.
 1337%
 1338%   Walk the meta-argument Arg of Goal in isolation.  The extra
 1339%   arguments of a closure that is called on the elements of a list
 1340%   (see closure_elements/3) are marked as subterms if the list is
 1341%   derived from the head.
 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
 1369%!  barrier_calls(:Goal, +State, +Count0) is det.
 1370%
 1371%   If Goal is a shift barrier (see shift_barrier/2), record that the
 1372%   calls after Count0 are made through it.  The calls in a nested
 1373%   barrier keep the inner one.
 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
 1390%!  shift_barrier(:Goal, -PI) is semidet.
 1391%
 1392%   True if the goal arguments of Goal are called through a barrier
 1393%   for shift/1, so a tabled goal in them cannot suspend to wait for a
 1394%   table that was started outside Goal.  This is the case for
 1395%   findall/3 and the other predicates that collect all solutions, the
 1396%   failure driven loops aggregate_all/3 and foldall/4 and meta
 1397%   predicates defined in C (see the predicate_property/2 property
 1398%   `shift_barrier`).  PI is the predicate indicator of Goal, qualified
 1399%   unless Goal is defined in a system or library module.
 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
 1414%   The calls in the goal of a meta-call that can leave choice points
 1415%   remain open: a cut after the meta-call prunes them.  This is not
 1416%   the case for predicates that collect all solutions or prune their
 1417%   goal.
 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
 1435%   A grammar body (//) is called with two extra arguments.
 1436
 1437meta_spec_extra(//, 2) :- !.
 1438meta_spec_extra(Spec, Spec).
 1439
 1440%   A cut inside a meta-argument is local to it.  The goals of once/1,
 1441%   ignore/1 and forall/2 are pruned after their first solution.
 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
 1453%!  mark_elements(+Goal, +Extra, +Head, +HeadVars, +Seen) is det.
 1454%
 1455%   If Goal calls its closure on the elements of lists, mark the extra
 1456%   arguments that receive the elements of a list derived from Head.
 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
 1471%!  closure_elements(+Goal, -Lists, ?Extra) is semidet.
 1472%
 1473%   True if Goal calls its closure with the elements of Lists as the
 1474%   leading extra arguments.  Lists has the same length as Extra,
 1475%   using `-` for extra arguments that are not list elements.
 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
 1513%!  progress_goal(:Goal) is semidet.
 1514%
 1515%   True if executing Goal ends left position.  This is the case for
 1516%   all goals that are not built-in predicates, except for library
 1517%   predicates that are known not to bind arguments or fail, such as
 1518%   debug/3 (see left_transparent/1), and for built-in predicates with
 1519%   side effects (see side_effect/1).
 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
 1533%!  side_effect(?PI) is nondet.
 1534%
 1535%   True if the built-in predicate PI has side effects.  A recursive
 1536%   call that follows such a goal is not a pure loop: input goals make
 1537%   progress by consuming input and tabling a predicate that performs
 1538%   output or modifies the database changes its meaning.  Goals that
 1539%   only inspect a stream, such as peek_char/2, are not included.
 1540
 1541side_effect(PI) :-
 1542    side_effect_list(PIs),
 1543    member(PI, PIs).
 1544
 1545side_effect_list(
 1546    [ % input
 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      % output
 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      % streams
 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      % database
 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      % global state
 1569      nb_setval/2, b_setval/2, setarg/3, nb_setarg/3, nb_linkarg/3,
 1570      nb_linkval/2,
 1571      % threads and the environment
 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
 1581%!  left_transparent(:Goal) is semidet.
 1582%
 1583%   Multifile hook that is true if a call to Goal does not end the
 1584%   left position of the calls that follow it.  This is intended for
 1585%   non built-in predicates that do not bind arguments and do not fail,
 1586%   such as debug/3.
 1587
 1588left_transparent(prolog_debug:debug(_,_,_)).
 1589left_transparent(prolog_debug:debug(_)).
 1590left_transparent(prolog_debug:assertion(_)).
 1591left_transparent(error:must_be(_,_)).
 1592
 1593%!  record_call(+PI, +Goal, +Ref, +Head, +HeadVars, +Left0, +Seen,
 1594%!              +State) is det.
 1595%
 1596%   Record the annotation of a call.  A call that passes a proper
 1597%   subterm of a head argument or a value computed from a head
 1598%   argument that differs from it is not in left position: it cannot
 1599%   be a variant of the calling goal, so tabling does not help.
 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
 1623%   Fresh is the list of unmarked variables of Goal that do not appear
 1624%   in the head or earlier in the body.  These are unbound when Goal
 1625%   is called.
 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		 /*******************************
 1696		 *          LOOP CHECK          *
 1697		 *******************************/
 1698
 1699%!  loop_keys(+Edges, -LoopKeys) is det.
 1700%
 1701%   LoopKeys is an assoc holding the keys of the edges in left position
 1702%   that take part in a _loop_: a sequence of calls in left position
 1703%   through which a goal may call a variant of itself.  Edges is a
 1704%   list of `Key-Transition-Edge`, where Transition is a term
 1705%   t(Head, Goal, Earlier, Fresh) that describes the call Goal in the
 1706%   clause with head Head.  Earlier is a list of heads of the clauses
 1707%   before it that commit unconditionally (see commit_heads/2) and
 1708%   Fresh is the list of variables of Goal that are unbound when Goal
 1709%   is called.
 1710%
 1711%   For each transition, we search for a sequence of transitions,
 1712%   unifying the goal of each with the head of the next, that ends in
 1713%   a goal for the predicate we started with that unifies with the
 1714%   head we started with.  Unification uses the occurs check and
 1715%   respects the constraints added by derive/4: dif/2 for values that
 1716%   differ from their source and the term kinds derived from type
 1717%   tests, where the fresh variables of the final goal are unbound.
 1718%   Thus, a goal for which the clause passes a proper subterm,
 1719%   a term that contains the argument, a term with a different
 1720%   principal functor, an arithmetic result that differs from the
 1721%   argument or a value that is tested to differ from the argument
 1722%   cannot be a variant.  A sequence is pruned if a head is an
 1723%   instance of a head in its Earlier list.  The search depth is
 1724%   limited to the number of transitions plus one, at most 10.  If the
 1725%   search takes too many steps, all edges in left position are
 1726%   considered part of a loop.
 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
 1809%!  general_transition(+Edge, -Transition) is det.
 1810%
 1811%   Transition for an edge whose call could not be analysed: a call
 1812%   with fresh arguments from a clause with a general head.
 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		 /*******************************
 1823		 *        LEFT RECURSION        *
 1824		 *******************************/
 1825
 1826%!  left_recursion(-LeftRecursion:dict, +Options) is nondet.
 1827%!  left_recursion(+SCCs, -LeftRecursion:dict, +Options) is nondet.
 1828%
 1829%   Enumerate the left recursion in the call graph.  For each set of
 1830%   predicates that are mutually recursive through calls in left
 1831%   position (see module header), LeftRecursion is a dict with the
 1832%   keys below.  The first form computes the SCCs using
 1833%   call_graph_sccs/2 from Options.
 1834%
 1835%     - members
 1836%       Sorted list of predicate indicators involved.
 1837%     - cycle
 1838%       List of edges (see call_graph_sccs/2) that form a shortest
 1839%       cycle through the first member.
 1840%     - edges
 1841%       All left edges between the members.
 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
 1869%!  shortest_cycle(+Start, +Edges, -Cycle) is det.
 1870%
 1871%   Breadth-first search for the shortest path from Start back to
 1872%   Start over Edges.
 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    )