View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2017-2025, VU University Amsterdam
    7			      CWI Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(prolog_jiti,
   38          [ jiti_list/0,
   39            jiti_list/1,                % +Spec
   40            jiti_index_columns/2,       % +Index, -Columns
   41            jiti_suggest_modes/1,       % :Spec
   42            jiti_suggest_modes/0
   43          ]).   44:- autoload(library(apply), [maplist/2, foldl/4, convlist/3]).   45:- autoload(library(dcg/basics), [number//1]).   46:- autoload(library(ansi_term), [ansi_format/3, ansi_hyperlink/3]).   47:- autoload(library(prolog_code), [pi_head/2, most_general_goal/2]).   48:- autoload(library(listing), [portray_clause/1]).   49:- autoload(library(lists), [append/2]).   50:- autoload(library(ordsets), [ord_subtract/3]).   51
   52
   53:- meta_predicate
   54    jiti_list(:),
   55    jiti_suggest_modes(:).

Just In Time Indexing (JITI) utilities

This module provides utilities to examine just-in-time indexes created by the system and can help diagnosing space and performance issues.

To be done
- Use print_message/2 and dynamically figure out the column width.
 jiti_list is det
 jiti_list(:Spec) is det
List the JITI (Just In Time Indexes) of selected predicates. The predicate jiti_list/0 list all just-in-time indexed predicates. The predicate jiti_list/1 takes one of the patterns below. All parts except for Name can be variables. The last pattern takes an arbitrary number of arguments.

The columns use the following notation:

   98jiti_list :-
   99    jiti_list(_:_).
  100
  101jiti_list(Spec) :-
  102    spec_head(Spec, Head),
  103    !,
  104    jiti_list(Head).
  105jiti_list(Head) :-
  106    tty_width(TTYW),
  107    findall(PI-Indexed,
  108            (   predicate_property(Head, indexed(Indexed)),
  109                \+ predicate_property(Head, imported_from(_)),
  110                pi_head(PI, Head)
  111            ), Pairs0),
  112    sort(Pairs0, Pairs),
  113    PredColW is TTYW-47,
  114    TableWidth is TTYW-1,
  115    ansi_format(bold, 'Predicate~*|~w ~t~10+~w ~t~w~14+ ~t~w~9+ ~t~w~6+ ~t~w~6+~n',
  116                [PredColW, '#Clauses', 'Index','Buckets','Speedup','Coll','Flags']),
  117    format('~`\u2015t~*|~n', [TableWidth]),
  118    maplist(print_indexes(PredColW), Pairs).
  119
  120print_indexes(PredColW, PI-List) :-
  121    foldl(print_index(PredColW, PI), List, 1, _).
  122
  123:- det(print_index/5).  124print_index(PredColW, PI0, Dict, N, N1) :-
  125    pi_head(PI0, Head),
  126    head_pi(Head, PI),                  % Create DCG PI
  127    N1 is N+1,
  128    jiti_index_columns(Dict, Columns),
  129    _{index:ArgsS, buckets:Buckets, speedup:Speedup,
  130      collisions:Collisions, flags:Flags, realised:R} :< Columns,
  131    predicate_property(Head, number_of_clauses(CCount)),
  132    istyle(R, Style),
  133    CCountColZ is PredColW+8,
  134    (   N == 1
  135    ->  format_pi(PI),
  136        format(' ~t~D~*|  ', [CCount, CCountColZ])
  137    ;   format(' ~t~*|  ', [CCountColZ])
  138    ),
  139    ansi_format(Style, '~|~s ~t~D~14+ ~t~1f~9+ ~t~w~6+ ~s~n',
  140                [ArgsS,Buckets,Speedup,Collisions,Flags]).
 jiti_index_columns(+Index:dict, -Columns:dict) is det
Columns holds what jiti_list/1 shows of Index, an element of the list of the predicate property indexed/1. This allows other tools to present indexes the same way. The keys are
index
String describing the indexed arguments, e.g., "1/2:2+3".
buckets
Number of buckets of the hash table.
speedup
Selectivity of the index (float).
collisions
Number of collisions or - if this is not applicable.
flags
String holding the flags (L, V).
realised
true if the index is materialized, false if it is virtual.
  161:- det(jiti_index_columns/2).  162jiti_index_columns(Dict, Columns) :-
  163    _{arguments:Args, position:Pos,
  164      buckets:Buckets, speedup:Speedup, list:List, realised:R,
  165      collisions:Collisions0} :< Dict,
  166    phrase(iarg_spec(Pos, Args), ArgsCodes),
  167    phrase(iflags(List, R), FlagCodes),
  168    string_codes(ArgsS, ArgsCodes),
  169    string_codes(Flags, FlagCodes),
  170    icoll(R, List, Collisions0, Collisions),
  171    Columns = _{index:ArgsS, buckets:Buckets, speedup:Speedup,
  172                collisions:Collisions, flags:Flags, realised:R}.
  173
  174format_pi(PI) :-
  175    pi_head(PI, Head),
  176    predicate_property(Head, file(File)),
  177    predicate_property(Head, line_count(Line)),
  178    !,
  179    format(string(Label), '~q', [PI]),
  180    ansi_hyperlink(user_output, File:Line, Label).
  181format_pi(PI) :-
  182    format('~q', [PI]).
 iarg_spec(+Position, +Args)//
  186iarg_spec([], [N]) ==>
  187    number(N).
  188iarg_spec([], List) ==>
  189    plus_list(List).
  190iarg_spec(Deep, Args) ==>
  191    deep_list(Deep),
  192    iarg_spec([], Args).
  193
  194plus_list([H|T]) -->
  195    number(H),
  196    (   {T==[]}
  197    ->  []
  198    ;   "+",
  199        plus_list(T)
  200    ).
  201
  202deep_list([Last]) -->
  203    !,
  204    number(Last),
  205    ":".
  206deep_list([H|T]) -->
  207    number(H),
  208    "/",
  209    deep_list(T).
  210
  211
  212iflags(true, R)  ==> "L", irealised(R).
  213iflags(false, R) ==> "", irealised(R).
  214
  215irealised(false) ==> "V".
  216irealised(true)  ==> "".
  217
  218istyle(true, code).
  219istyle(false, comment).
  220
  221icoll(true,  false, Collisions0, Collisions) =>
  222    Collisions = Collisions0.
  223icoll(_, _, _, Collisions) =>
  224    Collisions = '-'.
  225
  226head_pi(Head, PI) :-
  227    predicate_property(Head, non_terminal),
  228    !,
  229    pi_head(PI0, Head),
  230    dcg_pi(PI0, PI).
  231head_pi(Head, PI) :-
  232    pi_head(PI, Head).
  233
  234dcg_pi(M:Name/Arity, DCG) =>
  235    Arity2 is Arity-2,
  236    DCG = M:Name//Arity2.
  237dcg_pi(Name/Arity, DCG) =>
  238    Arity2 is Arity-2,
  239    DCG = Name//Arity2.
  240
  241
  242                /*******************************
  243                *            MODES             *
  244                *******************************/
 jiti_suggest_modes is det
 jiti_suggest_modes(:Spec) is det
Propose modes for the predicates referenced by Spec. This utility may be executed after a clean load of your program and after running the program. It searches for static predicates that have been called and (thus) have been examined for candidate indexes. If candidate indexes have not been materialized this implies that the predicate was never called with a nonvar value for the corresponding argument. Adding a mode/1 declaration may be used to inform the system thereof. The system will never examine arguments for indexing that have been declared as mode -.

Note: This predicate merely detects that some predicate is never called with instantiated specific arguments during this run. The user should verify whether the suggested - arguments are correct and typically complete the mode by changing ? into + (or -) where applicable. Currently, in SWI-Prolog, mode/1 declarations have no effect on the semantics of the code. In particular, a predicate that declares some argument as - may be called with this argument instantiated. This may change in the future.

Arguments:
Spec- uses the same conventions as jiti_list/1.
  270jiti_suggest_modes :-
  271    jiti_suggest_modes(_:_).
  272
  273jiti_suggest_modes(Partial) :-
  274    spec_head(Partial, Head),
  275    !,
  276    jiti_suggest_modes(Head).
  277jiti_suggest_modes(Head) :-
  278    Head = M:_,
  279    freeze(M, module_property(M, class(user))),
  280    findall(Head-Indexed,
  281            (   predicate_property(Head, indexed(Indexed)),
  282                \+ predicate_property(Head, imported_from(_))
  283            ), Pairs),
  284    convlist(suggest_mode, Pairs, Modes),
  285    (   Modes == []
  286    ->  print_message(informational, jiti(no_modes(Head)))
  287    ;   maplist(portray_clause, Modes)
  288    ).
  289
  290suggest_mode((M:Head)-Indexes, (:- mode(M:GenHead))) :-
  291    convlist(not_realised_index_arg, Indexes, FArgs),
  292    convlist(realised_index_arg, Indexes, ArgsL),
  293    append(ArgsL, Realised),
  294    sort(FArgs, Sargs),
  295    sort(Realised, RArgs),
  296    ord_subtract(Sargs, RArgs, Args),
  297    Args \== [],
  298    !,
  299    most_general_goal(Head, GenHead),
  300    make_mode(Args, GenHead).
  301
  302not_realised_index_arg(Index, Arg) :-
  303    _{ arguments:[Arg], position:[], realised:false } :< Index.
  304
  305realised_index_arg(Index, Args) :-
  306    _{ arguments:Args, position:[], realised:true } :< Index.
  307
  308make_mode([], GenHead) =>
  309    functor(GenHead, _, Arity),
  310    set_any(1, Arity, GenHead).
  311make_mode([H|T], GenHead) =>
  312    arg(H, GenHead, -),
  313    make_mode(T, GenHead).
  314
  315set_any(I, Arity, GenHead), arg(I, GenHead, Var) =>
  316    (   var(Var)
  317    ->  Var = '?'
  318    ;   true
  319    ),
  320    I2 is I+1,
  321    set_any(I2, Arity, GenHead).
  322set_any(_, _, _) =>
  323    true.
  324
  325
  326                /*******************************
  327                *      SPECIFY PREDICATES      *
  328                *******************************/
  329
  330spec_head(Module:Name/Arity, Head), atom(Name), integer(Arity) =>
  331    Head = Module:Head0,
  332    functor(Head0, Name, Arity).
  333spec_head(Module:Name/Arity, Head), atom(Name), var(Arity) =>
  334    Head = Module:Head0,
  335    freeze(Head0, functor(Head0, Name, _)).
  336spec_head(Module:Name, Head), atom(Name) =>
  337    Head = Module:Head0,
  338    freeze(Head0, functor(Head0, Name, _)).
  339spec_head(_, _) =>
  340    fail.
  341
  342                /*******************************
  343                *            OUTPUT            *
  344                *******************************/
  345
  346tty_width(W) :-
  347    catch(tty_size(_, TtyW), _, fail),
  348    !,
  349    W is max(65, TtyW).
  350tty_width(80).
  351
  352                /*******************************
  353                *           MESSAGES           *
  354                *******************************/
  355
  356:- multifile prolog:message//1.  357
  358prolog:message(jiti(no_modes(M:Head))) -->
  359    { var(Head) },
  360    [ 'No mode suggestions for predicates in module ~p'-[M] ].
  361prolog:message(jiti(no_modes(Head))) -->
  362    { numbervars(Head, 0, _, [singletons(true)]) },
  363    [ 'No mode suggestions for ~p'-[Head] ]