List modules importing predicate(s)

List modules importing predicate(s)

predicate_imported_from(M1,Name,Arity,(M1:Name/Arity,Imported_by_set)) :-
    var(Imported_by_set), !,
    setof(M2,imported_predicate_generator(M2,Name,Arity,M1),Imported_by_set).

imported_predicate_generator(M1,Name,Arity,M2) :-
    current_predicate(M1:Name/Arity),
    imported_predicate(M1:Name/Arity,M2).

imported_predicate(M1:Name/Arity,M2) :-
    compound_name_arity(Head,Name,Arity),
    predicate_property(M1:Head,imported_from(M2)).

Example usage:
NB If a module is not loaded then this will not see the import.

Note: This example loads the GUI tracer to load many modules so that the output is interesting.

?- gtrace.
% The graphical front-end will be used for subsequent tracing
true.

[trace]  ?- nodebug.
true.

?- predicate_imported_from(M,append,3,Imported_by).
M = lists,
Imported_by =  (lists:append/3, [ansi_term, arithmetic, pce_expansion, pce_global, pce_goal_expansion, pce_messages, pce_prolog_tracer, predicate_options, prolog_clause, prolog_debug, prolog_gui, prolog_stack, start_emacs, win_menu]).

?- predicate_imported_from(M,append,Arity,Imported_by).
M = lists,
Arity = 2,
Imported_by =  (lists:append/2, [pce_prolog_tracer, prolog_gui]) ;
M = lists,
Arity = 3,
Imported_by =  (lists:append/3, [ansi_term, arithmetic, pce_expansion, pce_global, pce_goal_expansion, pce_messages, pce_prolog_tracer, predicate_options, prolog_clause, prolog_debug, prolog_gui, prolog_stack, start_emacs, win_menu]).

A nice use for this is in finding example code for a predicate, e.g.

?- predicate_imported_from(aggregate,Name,Arity,Imported_by).
false.

?- gxref.
true.

?- predicate_imported_from(aggregate,Name,Arity,Imported_by).
Name = aggregate_all,
Arity = 3,
Imported_by =  (aggregate:aggregate_all/3, [http_open]).

I made this a Discourse Wiki topic so that anyone with a proper trust level can edit this. If you want to improve the code, add some documentation, or other, feel free.

There will probably be a few more topics in this category related to Prolog code analysis that I might pull together into a Wiki, but for now having the code in a more prominent place is better than being buried in a Wiki discussion topic.


Also see: List the properties for predicate(s)