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)  2002-2021, University of Amsterdam
    7                              VU University 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_main,
   38          [ main/0,
   39            argv_options/3,             % +Argv, -RestArgv, -Options
   40            cli_parse_debug_options/2,  % +OptionsIn, -Options
   41            cli_enable_development_system/0
   42          ]).   43% use autoload/1 to avoid checking these files at load time.
   44:- autoload(library(debug)).   45:- autoload(library(threadutil)).   46
   47:- dynamic
   48    interactive/0.

Provide entry point for scripts

This library is intended for supporting PrologScript on Unix using the #! magic sequence for scripts using commandline options. The entry point main/0 calls the user-supplied predicate main/1 passing a list of commandline options. Below is a simle echo implementation in Prolog.

#!/usr/bin/env swipl

:- initialization(main, main).

main(Argv) :-
    echo(Argv).

echo([]) :- nl.
echo([Last]) :- !,
    write(Last), nl.
echo([H|T]) :-
    write(H), write(' '),
    echo(T).
See also
- library(optparse) for comprehensive option parsing.
- library(prolog_stack) to force backtraces in case of an uncaught exception.
- XPCE users should have a look at library(pce_main), which starts the GUI and processes events until all windows have gone. */
   80:- module_transparent
   81    main/0.
 main
Call main/1 using the passed command-line arguments. Before calling main/1 this predicate installs a signal handler for SIGINT (Control-C) that terminates the process with status 1.
   89main :-
   90    context_module(M),
   91    set_signals,
   92    current_prolog_flag(argv, Av),
   93    catch_with_backtrace(M:main(Av), Error, throw(Error)),
   94    (   interactive
   95    ->  cli_enable_development_system
   96    ;   true
   97    ).
   98
   99set_signals :-
  100    on_signal(int, _, interrupt).
 interrupt(+Signal)
We received an interrupt. This handler is installed using on_signal/3.
  107interrupt(_Sig) :-
  108    halt(1).
 argv_options(+Argv, -RestArgv, -Options) is det
Generic transformation of long commandline arguments to options. Each --Name=Value is mapped to Name(Value). Each plain name is mapped to Name(true), unless Name starts with no-, in which case the option is mapped to Name(false). Numeric option values are mapped to Prolog numbers.
See also
- library(optparse) provides a more involved option library, providing both short and long options, help and error handling. This predicate is more for quick-and-dirty scripts.
  122argv_options([], [], []).
  123argv_options([H0|T0], R, [H|T]) :-
  124    sub_atom(H0, 0, _, _, --),
  125    !,
  126    (   sub_atom(H0, B, _, A, =)
  127    ->  B2 is B-2,
  128        sub_atom(H0, 2, B2, _, Name),
  129        sub_string(H0, _, A,  0, Value0),
  130        convert_option(Name, Value0, Value)
  131    ;   sub_atom(H0, 2, _, 0, Name0),
  132        (   sub_atom(Name0, 0, _, _, 'no-')
  133        ->  sub_atom(Name0, 3, _, 0, Name),
  134            Value = false
  135        ;   Name = Name0,
  136            Value = true
  137        )
  138    ),
  139    canonical_name(Name, PlName),
  140    H =.. [PlName,Value],
  141    argv_options(T0, R, T).
  142argv_options([H|T0], [H|R], T) :-
  143    argv_options(T0, R, T).
  144
  145convert_option(password, String, String) :- !.
  146convert_option(_, String, Number) :-
  147    number_string(Number, String),
  148    !.
  149convert_option(_, String, Atom) :-
  150    atom_string(Atom, String).
  151
  152canonical_name(Name, PlName) :-
  153    split_string(Name, "-_", "", Parts),
  154    atomic_list_concat(Parts, '_', PlName).
 cli_parse_debug_options(+OptionsIn, -Options) is det
Parse certain commandline options for debugging and development purposes. Options processed are below. Note that the option argument is an atom such that these options may be activated as e.g., --debug='http(_)'.
debug(Topic)
Call debug(Topic). See debug/1 and debug/3.
spy Predicate
Place a spy-point on Predicate.
gspy(Predicate)
As spy using the graphical debugger. See tspy/1.
interactive(true)
Start the Prolog toplevel after main/1 completes.
  172cli_parse_debug_options([], []).
  173cli_parse_debug_options([H|T0], Opts) :-
  174    debug_option(H),
  175    !,
  176    cli_parse_debug_options(T0, Opts).
  177cli_parse_debug_options([H|T0], [H|T]) :-
  178    cli_parse_debug_options(T0, T).
  179
  180debug_option(interactive(true)) :-
  181    asserta(interactive).
  182debug_option(debug(TopicS)) :-
  183    term_string(Topic, TopicS),
  184    debug(Topic).
  185debug_option(spy(Atom)) :-
  186    atom_pi(Atom, PI),
  187    spy(PI).
  188debug_option(gspy(Atom)) :-
  189    atom_pi(Atom, PI),
  190    tspy(PI).
  191
  192atom_pi(Atom, Module:PI) :-
  193    split(Atom, :, Module, PiAtom),
  194    !,
  195    atom_pi(PiAtom, PI).
  196atom_pi(Atom, Name//Arity) :-
  197    split(Atom, //, Name, Arity),
  198    !.
  199atom_pi(Atom, Name/Arity) :-
  200    split(Atom, /, Name, Arity),
  201    !.
  202atom_pi(Atom, _) :-
  203    format(user_error, 'Invalid predicate indicator: "~w"~n', [Atom]),
  204    halt(1).
  205
  206split(Atom, Sep, Before, After) :-
  207    sub_atom(Atom, BL, _, AL, Sep),
  208    !,
  209    sub_atom(Atom, 0, BL, _, Before),
  210    sub_atom(Atom, _, AL, 0, AfterAtom),
  211    (   atom_number(AfterAtom, After)
  212    ->  true
  213    ;   After = AfterAtom
  214    ).
 cli_enable_development_system
Re-enable the development environment. Currently re-enables xpce if this was loaded, but not initialised and causes the interactive toplevel to be re-enabled.

This predicate may be called from main/1 to enter the Prolog toplevel rather than terminating the application after main/1 completes.

  227cli_enable_development_system :-
  228    on_signal(int, _, debug),
  229    set_prolog_flag(xpce_threaded, true),
  230    set_prolog_flag(message_ide, true),
  231    (   current_prolog_flag(xpce_version, _)
  232    ->  use_module(library(pce_dispatch)),
  233        memberchk(Goal, [pce_dispatch([])]),
  234        call(Goal)
  235    ;   true
  236    ),
  237    set_prolog_flag(toplevel_goal, prolog).
  238
  239
  240		 /*******************************
  241		 *          IDE SUPPORT		*
  242		 *******************************/
  243
  244:- multifile
  245    prolog:called_by/2.  246
  247prolog:called_by(main, [main(_)])