Vincenzoni
Vincenzoni

Reputation: 55

How can extract the module's name in a file?

How can extract the module's name and the optional predicates present in a file?

If I have a file.pl containing the call to one or more modules, how can I extract the name of these modules and the name of the predicates in the module declaration?

Example: if my file contains the call to module

:- use_module(library(lists), [ member/2,
                                append/2 as list_concat
                              ]).
:- use_module(library(option).

I want to create an predicate extract(file.pl)

and output List=[[list,member,append],[option]]

Thanks.

Upvotes: 0

Views: 125

Answers (1)

Paulo Moura
Paulo Moura

Reputation: 18663

Assuming SWI-Prolog (as tagged). You could write something similar to what I do in the Logtalk adapter file for this Prolog compiler:

list_of_exports(File, Module, Exports) :-
    absolute_file_name(File, Path, [file_type(prolog), access(read), file_errors(fail)]),
    module_property(Module, file(Path)),    % only succeeds for loaded modules
    module_property(Module, exports(Exports)),
    !.
list_of_exports(File, Module, Exports) :-
    absolute_file_name(File, Path, [file_type(prolog), access(read), file_errors(fail)]),
    open(Path, read, In),
    (   peek_char(In, #) ->                 % deal with #! script; if not present
        skip(In, 10)                        % assume that the module declaration
    ;   true                                % is the first directive on the file
    ),
    setup_call_cleanup(true, read(In, ModuleDecl), close(In)),
    ModuleDecl = (:- module(Module, Exports)),
    (   var(Module) ->
        file_base_name(Path, Base),
        file_name_extension(Module, _, Base)
    ;   true
    ).

Note that this code doesn't deal with encoding/1 directives that might be present as the first term of the file. The code was also written long ago with the help of the SWI-Prolog author.

Upvotes: 1

Related Questions