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)  1985-2017, University of Amsterdam
    7                              VU University Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module('$toplevel',
   37          [ '$initialise'/0,            % start Prolog
   38            '$toplevel'/0,              % Prolog top-level (re-entrant)
   39            '$compile'/0,               % `-c' toplevel
   40            '$config'/0,                % --dump-runtime-variables toplevel
   41            initialize/0,               % Run program initialization
   42            version/0,                  % Write initial banner
   43            version/1,                  % Add message to the banner
   44            prolog/0,                   % user toplevel predicate
   45            '$query_loop'/0,            % toplevel predicate
   46            residual_goals/1,           % +Callable
   47            (initialization)/1,         % initialization goal (directive)
   48            '$thread_init'/0,           % initialise thread
   49            (thread_initialization)/1   % thread initialization goal
   50            ]).   51
   52
   53                 /*******************************
   54                 *       FILE_SEARCH_PATH       *
   55                 *******************************/
   56
   57:- multifile user:file_search_path/2.   58
   59user:file_search_path(app_data, PrologAppData) :-
   60    (   current_prolog_flag(windows, true)
   61    ->  catch(win_folder(appdata, AppData), _, fail),
   62        atom_concat(AppData, '/SWI-Prolog', PrologAppData),
   63        (   exists_directory(PrologAppData)
   64        ->  true
   65        ;   catch(make_directory(PrologAppData), _, fail)
   66        )
   67    ;   catch(expand_file_name('~/lib/swipl', [PrologAppData]), _, fail)
   68    ).
   69user:file_search_path(app_preferences, Preferences) :-
   70    (   current_prolog_flag(windows, true)
   71    ->  Preferences = app_data('.')
   72    ;   catch(expand_file_name(~, [UserHome]), _, fail)
   73    ->  Preferences = UserHome
   74    ).
   75user:file_search_path(user_profile, app_preferences('.')).
   76
   77
   78                 /*******************************
   79                 *         VERSION BANNER       *
   80                 *******************************/
   81
   82:- dynamic
   83    prolog:version_msg/1.
 version is det
Print the Prolog banner message and messages registered using version/1.
   90version :-
   91    print_message(banner, welcome).
 version(+Message) is det
Add message to version/0
   97:- multifile
   98    system:term_expansion/2.   99
  100system:term_expansion((:- version(Message)),
  101                      prolog:version_msg(Message)).
  102
  103version(Message) :-
  104    (   prolog:version_msg(Message)
  105    ->  true
  106    ;   assertz(prolog:version_msg(Message))
  107    ).
  108
  109
  110                /********************************
  111                *         INITIALISATION        *
  112                *********************************/
  113
  114%       note: loaded_init_file/2 is used by prolog_load_context/2 to
  115%       confirm we are loading a script.
  116
  117:- dynamic
  118    loaded_init_file/2.             % already loaded init files
  119
  120'$load_init_file'(none) :- !.
  121'$load_init_file'(Base) :-
  122    loaded_init_file(Base, _),
  123    !.
  124'$load_init_file'(InitFile) :-
  125    exists_file(InitFile),
  126    !,
  127    ensure_loaded(user:InitFile).
  128'$load_init_file'(Base) :-
  129    absolute_file_name(user_profile(Base), InitFile,
  130                       [ access(read),
  131                         file_errors(fail)
  132                       ]),
  133    asserta(loaded_init_file(Base, InitFile)),
  134    load_files(user:InitFile,
  135               [ scope_settings(false)
  136               ]).
  137'$load_init_file'(_).
  138
  139'$load_system_init_file' :-
  140    loaded_init_file(system, _),
  141    !.
  142'$load_system_init_file' :-
  143    '$cmd_option_val'(system_init_file, Base),
  144    Base \== none,
  145    current_prolog_flag(home, Home),
  146    file_name_extension(Base, rc, Name),
  147    atomic_list_concat([Home, '/', Name], File),
  148    absolute_file_name(File, Path,
  149                       [ file_type(prolog),
  150                         access(read),
  151                         file_errors(fail)
  152                       ]),
  153    asserta(loaded_init_file(system, Path)),
  154    load_files(user:Path,
  155               [ silent(true),
  156                 scope_settings(false)
  157               ]),
  158    !.
  159'$load_system_init_file'.
  160
  161'$load_script_file' :-
  162    loaded_init_file(script, _),
  163    !.
  164'$load_script_file' :-
  165    '$cmd_option_val'(script_file, OsFiles),
  166    load_script_files(OsFiles).
  167
  168load_script_files([]).
  169load_script_files([OsFile|More]) :-
  170    prolog_to_os_filename(File, OsFile),
  171    (   absolute_file_name(File, Path,
  172                           [ file_type(prolog),
  173                             access(read),
  174                             file_errors(fail)
  175                           ])
  176    ->  asserta(loaded_init_file(script, Path)),
  177        load_files(user:Path, []),
  178        load_files(More)
  179    ;   throw(error(existence_error(script_file, File), _))
  180    ).
  181
  182
  183                 /*******************************
  184                 *       AT_INITIALISATION      *
  185                 *******************************/
  186
  187:- meta_predicate
  188    initialization(0).  189
  190:- '$iso'((initialization)/1).
 initialization :Goal
Runs Goal after loading the file in which this directive appears as well as after restoring a saved state.
See also
- initialization/2
  199initialization(Goal) :-
  200    Goal = _:G,
  201    prolog:initialize_now(G, Use),
  202    !,
  203    print_message(warning, initialize_now(G, Use)),
  204    initialization(Goal, now).
  205initialization(Goal) :-
  206    initialization(Goal, after_load).
  207
  208:- multifile
  209    prolog:initialize_now/2,
  210    prolog:message//1.  211
  212prolog:initialize_now(load_foreign_library(_),
  213                      'use :- use_foreign_library/1 instead').
  214prolog:initialize_now(load_foreign_library(_,_),
  215                      'use :- use_foreign_library/2 instead').
  216
  217prolog:message(initialize_now(Goal, Use)) -->
  218    [ 'Initialization goal ~p will be executed'-[Goal],nl,
  219      'immediately for backward compatibility reasons', nl,
  220      '~w'-[Use]
  221    ].
  222
  223'$run_initialization' :-
  224    '$run_initialization'(_, []),
  225    '$thread_init'.
 initialize
Run goals registered with :- initialization(Goal, program).. Stop with an exception if a goal fails or raises an exception.
  232initialize :-
  233    forall('$init_goal'(when(program), Goal, Ctx),
  234           run_initialize(Goal, Ctx)).
  235
  236run_initialize(Goal, Ctx) :-
  237    (   catch(Goal, E, true),
  238        (   var(E)
  239        ->  true
  240        ;   throw(error(initialization_error(E, Goal, Ctx), _))
  241        )
  242    ;   throw(error(initialization_error(failed, Goal, Ctx), _))
  243    ).
  244
  245
  246                 /*******************************
  247                 *     THREAD INITIALIZATION    *
  248                 *******************************/
  249
  250:- meta_predicate
  251    thread_initialization(0).  252:- dynamic
  253    '$at_thread_initialization'/1.
 thread_initialization :Goal
Run Goal now and everytime a new thread is created.
  259thread_initialization(Goal) :-
  260    assert('$at_thread_initialization'(Goal)),
  261    call(Goal),
  262    !.
  263
  264'$thread_init' :-
  265    (   '$at_thread_initialization'(Goal),
  266        (   call(Goal)
  267        ->  fail
  268        ;   fail
  269        )
  270    ;   true
  271    ).
  272
  273
  274                 /*******************************
  275                 *     FILE SEARCH PATH (-p)    *
  276                 *******************************/
 $set_file_search_paths is det
Process -p PathSpec options.
  282'$set_file_search_paths' :-
  283    '$cmd_option_val'(search_paths, Paths),
  284    (   '$member'(Path, Paths),
  285        atom_chars(Path, Chars),
  286        (   phrase('$search_path'(Name, Aliases), Chars)
  287        ->  '$reverse'(Aliases, Aliases1),
  288            forall('$member'(Alias, Aliases1),
  289                   asserta(user:file_search_path(Name, Alias)))
  290        ;   print_message(error, commandline_arg_type(p, Path))
  291        ),
  292        fail ; true
  293    ).
  294
  295'$search_path'(Name, Aliases) -->
  296    '$string'(NameChars),
  297    [=],
  298    !,
  299    {atom_chars(Name, NameChars)},
  300    '$search_aliases'(Aliases).
  301
  302'$search_aliases'([Alias|More]) -->
  303    '$string'(AliasChars),
  304    path_sep,
  305    !,
  306    { '$make_alias'(AliasChars, Alias) },
  307    '$search_aliases'(More).
  308'$search_aliases'([Alias]) -->
  309    '$string'(AliasChars),
  310    '$eos',
  311    !,
  312    { '$make_alias'(AliasChars, Alias) }.
  313
  314path_sep -->
  315    { current_prolog_flag(windows, true)
  316    },
  317    !,
  318    [;].
  319path_sep -->
  320    [:].
  321
  322'$string'([]) --> [].
  323'$string'([H|T]) --> [H], '$string'(T).
  324
  325'$eos'([], []).
  326
  327'$make_alias'(Chars, Alias) :-
  328    catch(term_to_atom(Alias, Chars), _, fail),
  329    (   atom(Alias)
  330    ;   functor(Alias, F, 1),
  331        F \== /
  332    ),
  333    !.
  334'$make_alias'(Chars, Alias) :-
  335    atom_chars(Alias, Chars).
  336
  337
  338                 /*******************************
  339                 *   LOADING ASSIOCIATED FILES  *
  340                 *******************************/
 argv_files(-Files) is det
Update the Prolog flag argv, extracting the leading directory and files.
  347argv_files(Files) :-
  348    current_prolog_flag(argv, Argv),
  349    no_option_files(Argv, Argv1, Files),
  350    (   Argv1 \== Argv
  351    ->  set_prolog_flag(argv, Argv1)
  352    ;   true
  353    ).
  354
  355no_option_files([--|Argv], Argv, []) :- !.
  356no_option_files([OsScript|Argv], Argv, [Script]) :-
  357    prolog_to_os_filename(Script, OsScript),
  358    access_file(Script, read),
  359    catch(setup_call_cleanup(
  360              open(Script, read, In),
  361              ( get_char(In, '#'),
  362                get_char(In, '!')
  363              ),
  364              close(In)),
  365          _, fail),
  366    !.
  367no_option_files([OsFile|Argv0], Argv, [File|T]) :-
  368    file_name_extension(_, Ext, OsFile),
  369    user:prolog_file_type(Ext, prolog),
  370    !,
  371    prolog_to_os_filename(File, OsFile),
  372    no_option_files(Argv0, Argv, T).
  373no_option_files(Argv, Argv, []).
  374
  375clean_argv :-
  376    (   current_prolog_flag(argv, [--|Argv])
  377    ->  set_prolog_flag(argv, Argv)
  378    ;   true
  379    ).
 associated_files(-Files)
If SWI-Prolog is started as <exe> <file>.<ext>, where <ext> is the extension registered for associated files, set the Prolog flag associated_file, switch to the directory holding the file and -if possible- adjust the window title.
  388associated_files([]) :-
  389    current_prolog_flag(saved_program_class, runtime),
  390    !,
  391    clean_argv.
  392associated_files(Files) :-
  393    '$set_prolog_file_extension',
  394    argv_files(Files),
  395    (   Files = [File|_]
  396    ->  absolute_file_name(File, AbsFile),
  397        set_prolog_flag(associated_file, AbsFile),
  398        set_working_directory(File),
  399        set_window_title(Files)
  400    ;   true
  401    ).
 set_working_directory(+File)
When opening as a GUI application, e.g., by opening a file from the Finder/Explorer/..., we typically want to change working directory to the location of the primary file. We currently detect that we are a GUI app by the Prolog flag console_menu, which is set by swipl-win[.exe].
  411set_working_directory(File) :-
  412    current_prolog_flag(console_menu, true),
  413    access_file(File, read),
  414    !,
  415    file_directory_name(File, Dir),
  416    working_directory(_, Dir).
  417set_working_directory(_).
  418
  419set_window_title([File|More]) :-
  420    current_predicate(system:window_title/2),
  421    !,
  422    (   More == []
  423    ->  Extra = []
  424    ;   Extra = ['...']
  425    ),
  426    atomic_list_concat(['SWI-Prolog --', File | Extra], ' ', Title),
  427    system:window_title(_, Title).
  428set_window_title(_).
 start_pldoc
If the option --pldoc[=port] is given, load the PlDoc system.
  436start_pldoc :-
  437    '$cmd_option_val'(pldoc_server, Server),
  438    (   Server == ''
  439    ->  call((doc_server(_), doc_browser))
  440    ;   catch(atom_number(Server, Port), _, fail)
  441    ->  call(doc_server(Port))
  442    ;   print_message(error, option_usage(pldoc)),
  443        halt(1)
  444    ).
  445start_pldoc.
 load_associated_files(+Files)
Load Prolog files specified from the commandline.
  452load_associated_files(Files) :-
  453    (   '$member'(File, Files),
  454        load_files(user:File, [expand(false)]),
  455        fail
  456    ;   true
  457    ).
  458
  459hkey('HKEY_CURRENT_USER/Software/SWI/Prolog').
  460hkey('HKEY_LOCAL_MACHINE/Software/SWI/Prolog').
  461
  462'$set_prolog_file_extension' :-
  463    current_prolog_flag(windows, true),
  464    hkey(Key),
  465    catch(win_registry_get_value(Key, fileExtension, Ext0),
  466          _, fail),
  467    !,
  468    (   atom_concat('.', Ext, Ext0)
  469    ->  true
  470    ;   Ext = Ext0
  471    ),
  472    (   user:prolog_file_type(Ext, prolog)
  473    ->  true
  474    ;   asserta(user:prolog_file_type(Ext, prolog))
  475    ).
  476'$set_prolog_file_extension'.
  477
  478
  479                /********************************
  480                *        TOPLEVEL GOALS         *
  481                *********************************/
 $initialise is semidet
Called from PL_initialise() to do the Prolog part of the initialization. If an exception occurs, this is printed and '$initialise' fails.
  489'$initialise' :-
  490    catch(initialise_prolog, E, initialise_error(E)).
  491
  492initialise_error('$aborted') :- !.
  493initialise_error(E) :-
  494    print_message(error, initialization_exception(E)),
  495    fail.
  496
  497initialise_prolog :-
  498    '$clean_history',
  499    '$run_initialization',
  500    '$load_system_init_file',
  501    set_toplevel,
  502    '$set_file_search_paths',
  503    init_debug_flags,
  504    start_pldoc,
  505    attach_packs,
  506    '$cmd_option_val'(init_file, OsFile),
  507    prolog_to_os_filename(File, OsFile),
  508    '$load_init_file'(File),
  509    catch(setup_colors, E, print_message(warning, E)),
  510    '$load_script_file',
  511    associated_files(Files),
  512    load_associated_files(Files),
  513    '$cmd_option_val'(goals, Goals),
  514    (   Goals == [],
  515        \+ '$init_goal'(when(_), _, _)
  516    ->  version                                 % default interactive run
  517    ;   run_init_goals(Goals),
  518        (   load_only
  519        ->  version
  520        ;   run_program_init,
  521            run_main_init
  522        )
  523    ).
  524
  525set_toplevel :-
  526    '$cmd_option_val'(toplevel, TopLevelAtom),
  527    catch(term_to_atom(TopLevel, TopLevelAtom), E,
  528          (print_message(error, E),
  529           halt(1))),
  530    create_prolog_flag(toplevel_goal, TopLevel, [type(term)]).
  531
  532load_only :-
  533    current_prolog_flag(os_argv, OSArgv),
  534    memberchk('-l', OSArgv),
  535    current_prolog_flag(argv, Argv),
  536    \+ memberchk('-l', Argv).
 run_init_goals(+Goals) is det
Run registered initialization goals on order. If a goal fails, execution is halted.
  543run_init_goals([]).
  544run_init_goals([H|T]) :-
  545    run_init_goal(H),
  546    run_init_goals(T).
  547
  548run_init_goal(Text) :-
  549    catch(term_to_atom(Goal, Text), E,
  550          (   print_message(error, init_goal_syntax(E, Text)),
  551              halt(2)
  552          )),
  553    run_init_goal(Goal, Text).
 run_program_init is det
Run goals registered using
  559run_program_init :-
  560    forall('$init_goal'(when(program), Goal, Ctx),
  561           run_init_goal(Goal, @(Goal,Ctx))).
  562
  563run_main_init :-
  564    findall(Goal-Ctx, '$init_goal'(when(main), Goal, Ctx), Pairs),
  565    '$last'(Pairs, Goal-Ctx),
  566    !,
  567    (   current_prolog_flag(toplevel_goal, default)
  568    ->  set_prolog_flag(toplevel_goal, halt)
  569    ;   true
  570    ),
  571    run_init_goal(Goal, @(Goal,Ctx)).
  572run_main_init.
  573
  574run_init_goal(Goal, Ctx) :-
  575    (   catch_with_backtrace(user:Goal, E, true)
  576    ->  (   var(E)
  577        ->  true
  578        ;   print_message(error, init_goal_failed(E, Ctx)),
  579            halt(2)
  580        )
  581    ;   (   current_prolog_flag(verbose, silent)
  582        ->  Level = silent
  583        ;   Level = error
  584        ),
  585        print_message(Level, init_goal_failed(failed, Ctx)),
  586        halt(1)
  587    ).
 init_debug_flags is det
Initialize the various Prolog flags that control the debugger and toplevel.
  594init_debug_flags :-
  595    once(print_predicate(_, [print], PrintOptions)),
  596    create_prolog_flag(answer_write_options, PrintOptions, []),
  597    create_prolog_flag(prompt_alternatives_on, determinism, []),
  598    create_prolog_flag(toplevel_extra_white_line, true, []),
  599    create_prolog_flag(toplevel_print_factorized, false, []),
  600    create_prolog_flag(print_write_options,
  601                       [ portray(true), quoted(true), numbervars(true) ],
  602                       []),
  603    create_prolog_flag(toplevel_residue_vars, false, []),
  604    '$set_debugger_write_options'(print).
 setup_backtrace
Initialise printing a backtrace.
  610setup_backtrace :-
  611    (   \+ current_prolog_flag(backtrace, false),
  612        load_setup_file(library(prolog_stack))
  613    ->  true
  614    ;   true
  615    ).
 setup_colors is det
Setup interactive usage by enabling colored output.
  621setup_colors :-
  622    (   \+ current_prolog_flag(color_term, false),
  623        stream_property(user_input, tty(true)),
  624        stream_property(user_error, tty(true)),
  625        stream_property(user_output, tty(true)),
  626        \+ getenv('TERM', dumb),
  627        load_setup_file(user:library(ansi_term))
  628    ->  true
  629    ;   true
  630    ).
 setup_history
Enable per-directory persistent history.
  636setup_history :-
  637    (   \+ current_prolog_flag(save_history, false),
  638        stream_property(user_input, tty(true)),
  639        \+ current_prolog_flag(readline, false),
  640        load_setup_file(library(prolog_history))
  641    ->  prolog_history(enable)
  642    ;   true
  643    ),
  644    set_default_history,
  645    '$load_history'.
 setup_readline
Setup line editing.
  651setup_readline :-
  652    (   current_prolog_flag(readline, swipl_win)
  653    ->  true
  654    ;   stream_property(user_input, tty(true)),
  655        current_prolog_flag(tty_control, true),
  656        \+ getenv('TERM', dumb),
  657        (   current_prolog_flag(readline, ReadLine)
  658        ->  true
  659        ;   ReadLine = true
  660        ),
  661        readline_library(ReadLine, Library),
  662        load_setup_file(library(Library))
  663    ->  set_prolog_flag(readline, Library)
  664    ;   set_prolog_flag(readline, false)
  665    ).
  666
  667readline_library(true, Library) :-
  668    !,
  669    preferred_readline(Library).
  670readline_library(false, _) :-
  671    !,
  672    fail.
  673readline_library(Library, Library).
  674
  675preferred_readline(editline).
  676preferred_readline(readline).
 load_setup_file(+File) is semidet
Load a file and fail silently if the file does not exist.
  682load_setup_file(File) :-
  683    catch(load_files(File,
  684                     [ silent(true),
  685                       if(not_loaded)
  686                     ]), _, fail).
  687
  688
  689:- '$hide'('$toplevel'/0).              % avoid in the GUI stacktrace
 $toplevel
Called from PL_toplevel()
  695'$toplevel' :-
  696    '$runtoplevel',
  697    print_message(informational, halt).
 $runtoplevel
Actually run the toplevel. The values default and prolog both start the interactive toplevel, where prolog implies the user gave -t prolog.
See also
- prolog/0 is the default interactive toplevel
  707'$runtoplevel' :-
  708    current_prolog_flag(toplevel_goal, TopLevel0),
  709    toplevel_goal(TopLevel0, TopLevel),
  710    user:TopLevel.
  711
  712:- dynamic  setup_done/0.  713:- volatile setup_done/0.  714
  715toplevel_goal(default, '$query_loop') :-
  716    !,
  717    setup_interactive.
  718toplevel_goal(prolog, '$query_loop') :-
  719    !,
  720    setup_interactive.
  721toplevel_goal(Goal, Goal).
  722
  723setup_interactive :-
  724    setup_done,
  725    !.
  726setup_interactive :-
  727    asserta(setup_done),
  728    catch(setup_backtrace, E, print_message(warning, E)),
  729    catch(setup_readline,  E, print_message(warning, E)),
  730    catch(setup_history,   E, print_message(warning, E)).
 $compile
Toplevel called when invoked with -c option.
  736'$compile' :-
  737    (   catch('$compile_', E, (print_message(error, E), halt(1)))
  738    ->  true
  739    ;   print_message(error, error(goal_failed('$compile'), _)),
  740        halt(1)
  741    ).
  742
  743'$compile_' :-
  744    '$load_system_init_file',
  745    '$set_file_search_paths',
  746    init_debug_flags,
  747    '$run_initialization',
  748    attach_packs,
  749    use_module(library(qsave)),
  750    qsave:qsave_toplevel.
 $config
Toplevel when invoked with --dump-runtime-variables
  756'$config' :-
  757    '$load_system_init_file',
  758    '$set_file_search_paths',
  759    init_debug_flags,
  760    '$run_initialization',
  761    load_files(library(prolog_config)),
  762    (   catch(prolog_dump_runtime_variables, E,
  763              (print_message(error, E), halt(1)))
  764    ->  true
  765    ;   print_message(error, error(goal_failed(prolog_dump_runtime_variables),_))
  766    ).
  767
  768
  769                /********************************
  770                *    USER INTERACTIVE LOOP      *
  771                *********************************/
 prolog
Run the Prolog toplevel. This is now the same as break/0, which pretends to be in a break-level if there is a parent environment.
  779prolog :-
  780    break.
  781
  782:- create_prolog_flag(toplevel_mode, backtracking, []).
 $query_loop
Run the normal Prolog query loop. Note that the query is not protected by catch/3. Dealing with unhandled exceptions is done by the C-function query_loop(). This ensures that unhandled exceptions are really unhandled (in Prolog).
  791'$query_loop' :-
  792    current_prolog_flag(toplevel_mode, recursive),
  793    !,
  794    break_level(Level),
  795    read_expanded_query(Level, Query, Bindings),
  796    (   Query == end_of_file
  797    ->  print_message(query, query(eof))
  798    ;   '$call_no_catch'('$execute'(Query, Bindings)),
  799        (   current_prolog_flag(toplevel_mode, recursive)
  800        ->  '$query_loop'
  801        ;   '$switch_toplevel_mode'(backtracking),
  802            '$query_loop'           % Maybe throw('$switch_toplevel_mode')?
  803        )
  804    ).
  805'$query_loop' :-
  806    break_level(BreakLev),
  807    repeat,
  808        read_expanded_query(BreakLev, Query, Bindings),
  809        (   Query == end_of_file
  810        ->  !, print_message(query, query(eof))
  811        ;   '$execute'(Query, Bindings),
  812            (   current_prolog_flag(toplevel_mode, recursive)
  813            ->  !,
  814                '$switch_toplevel_mode'(recursive),
  815                '$query_loop'
  816            ;   fail
  817            )
  818        ).
  819
  820break_level(BreakLev) :-
  821    (   current_prolog_flag(break_level, BreakLev)
  822    ->  true
  823    ;   BreakLev = -1
  824    ).
  825
  826read_expanded_query(BreakLev, ExpandedQuery, ExpandedBindings) :-
  827    '$current_typein_module'(TypeIn),
  828    (   stream_property(user_input, tty(true))
  829    ->  '$system_prompt'(TypeIn, BreakLev, Prompt),
  830        prompt(Old, '|    ')
  831    ;   Prompt = '',
  832        prompt(Old, '')
  833    ),
  834    trim_stacks,
  835    repeat,
  836      read_query(Prompt, Query, Bindings),
  837      prompt(_, Old),
  838      catch(call_expand_query(Query, ExpandedQuery,
  839                              Bindings, ExpandedBindings),
  840            Error,
  841            (print_message(error, Error), fail)),
  842    !.
 read_query(+Prompt, -Goal, -Bindings) is det
Read the next query. The first clause deals with the case where !-based history is enabled. The second is used if we have command line editing.
  851read_query(Prompt, Goal, Bindings) :-
  852    current_prolog_flag(history, N),
  853    integer(N), N > 0,
  854    !,
  855    read_history(h, '!h',
  856                 [trace, end_of_file],
  857                 Prompt, Goal, Bindings).
  858read_query(Prompt, Goal, Bindings) :-
  859    remove_history_prompt(Prompt, Prompt1),
  860    repeat,                                 % over syntax errors
  861    prompt1(Prompt1),
  862    read_query_line(user_input, Line),
  863    '$save_history_line'(Line),             % save raw line (edit syntax errors)
  864    '$current_typein_module'(TypeIn),
  865    catch(read_term_from_atom(Line, Goal,
  866                              [ variable_names(Bindings),
  867                                module(TypeIn)
  868                              ]), E,
  869          (   print_message(error, E),
  870              fail
  871          )),
  872    !,
  873    '$save_history_event'(Line).            % save event (no syntax errors)
 read_query_line(+Input, -Line) is det
  877read_query_line(Input, Line) :-
  878    catch(read_term_as_atom(Input, Line), Error, true),
  879    save_debug_after_read,
  880    (   var(Error)
  881    ->  true
  882    ;   Error = error(syntax_error(_),_)
  883    ->  print_message(error, Error),
  884        fail
  885    ;   print_message(error, Error),
  886        throw(Error)
  887    ).
 read_term_as_atom(+Input, -Line)
Read the next term as an atom and skip to the newline or a non-space character.
  894read_term_as_atom(In, Line) :-
  895    '$raw_read'(In, Line),
  896    (   Line == end_of_file
  897    ->  true
  898    ;   skip_to_nl(In)
  899    ).
 skip_to_nl(+Input) is det
Read input after the term. Skips white space and %... comment until the end of the line or a non-blank character.
  906skip_to_nl(In) :-
  907    repeat,
  908    peek_char(In, C),
  909    (   C == '%'
  910    ->  skip(In, '\n')
  911    ;   char_type(C, space)
  912    ->  get_char(In, _),
  913        C == '\n'
  914    ;   true
  915    ),
  916    !.
  917
  918remove_history_prompt('', '') :- !.
  919remove_history_prompt(Prompt0, Prompt) :-
  920    atom_chars(Prompt0, Chars0),
  921    clean_history_prompt_chars(Chars0, Chars1),
  922    delete_leading_blanks(Chars1, Chars),
  923    atom_chars(Prompt, Chars).
  924
  925clean_history_prompt_chars([], []).
  926clean_history_prompt_chars(['~', !|T], T) :- !.
  927clean_history_prompt_chars([H|T0], [H|T]) :-
  928    clean_history_prompt_chars(T0, T).
  929
  930delete_leading_blanks([' '|T0], T) :-
  931    !,
  932    delete_leading_blanks(T0, T).
  933delete_leading_blanks(L, L).
 set_default_history
Enable !-based numbered command history. This is enabled by default if we are not running under GNU-emacs and we do not have our own line editing.
  942set_default_history :-
  943    current_prolog_flag(history, _),
  944    !.
  945set_default_history :-
  946    (   (   \+ current_prolog_flag(readline, false)
  947        ;   current_prolog_flag(emacs_inferior_process, true)
  948        )
  949    ->  create_prolog_flag(history, 0, [])
  950    ;   create_prolog_flag(history, 25, [])
  951    ).
  952
  953
  954                 /*******************************
  955                 *        TOPLEVEL DEBUG        *
  956                 *******************************/
 save_debug_after_read
Called right after the toplevel read to save the debug status if it was modified from the GUI thread using e.g.
thread_signal(main, gdebug)
bug
- Ideally, the prompt would change if debug mode is enabled. That is hard to realise with all the different console interfaces supported by SWI-Prolog.
  971save_debug_after_read :-
  972    current_prolog_flag(debug, true),
  973    !,
  974    save_debug.
  975save_debug_after_read.
  976
  977save_debug :-
  978    (   tracing,
  979        notrace
  980    ->  Tracing = true
  981    ;   Tracing = false
  982    ),
  983    current_prolog_flag(debug, Debugging),
  984    set_prolog_flag(debug, false),
  985    create_prolog_flag(query_debug_settings,
  986                       debug(Debugging, Tracing), []).
  987
  988restore_debug :-
  989    current_prolog_flag(query_debug_settings, debug(Debugging, Tracing)),
  990    set_prolog_flag(debug, Debugging),
  991    (   Tracing == true
  992    ->  trace
  993    ;   true
  994    ).
  995
  996:- initialization
  997    create_prolog_flag(query_debug_settings, debug(false, false), []).  998
  999
 1000                /********************************
 1001                *            PROMPTING          *
 1002                ********************************/
 1003
 1004'$system_prompt'(Module, BrekLev, Prompt) :-
 1005    current_prolog_flag(toplevel_prompt, PAtom),
 1006    atom_codes(PAtom, P0),
 1007    (    Module \== user
 1008    ->   '$substitute'('~m', [Module, ': '], P0, P1)
 1009    ;    '$substitute'('~m', [], P0, P1)
 1010    ),
 1011    (    BrekLev > 0
 1012    ->   '$substitute'('~l', ['[', BrekLev, '] '], P1, P2)
 1013    ;    '$substitute'('~l', [], P1, P2)
 1014    ),
 1015    current_prolog_flag(query_debug_settings, debug(Debugging, Tracing)),
 1016    (    Tracing == true
 1017    ->   '$substitute'('~d', ['[trace] '], P2, P3)
 1018    ;    Debugging == true
 1019    ->   '$substitute'('~d', ['[debug] '], P2, P3)
 1020    ;    '$substitute'('~d', [], P2, P3)
 1021    ),
 1022    atom_chars(Prompt, P3).
 1023
 1024'$substitute'(From, T, Old, New) :-
 1025    atom_codes(From, FromCodes),
 1026    phrase(subst_chars(T), T0),
 1027    '$append'(Pre, S0, Old),
 1028    '$append'(FromCodes, Post, S0) ->
 1029    '$append'(Pre, T0, S1),
 1030    '$append'(S1, Post, New),
 1031    !.
 1032'$substitute'(_, _, Old, Old).
 1033
 1034subst_chars([]) -->
 1035    [].
 1036subst_chars([H|T]) -->
 1037    { atomic(H),
 1038      !,
 1039      atom_codes(H, Codes)
 1040    },
 1041    Codes,
 1042    subst_chars(T).
 1043subst_chars([H|T]) -->
 1044    H,
 1045    subst_chars(T).
 1046
 1047
 1048                /********************************
 1049                *           EXECUTION           *
 1050                ********************************/
 $execute(Goal, Bindings) is det
Execute Goal using Bindings.
 1056'$execute'(Var, _) :-
 1057    var(Var),
 1058    !,
 1059    print_message(informational, var_query(Var)).
 1060'$execute'(Goal, Bindings) :-
 1061    '$current_typein_module'(TypeIn),
 1062    '$dwim_correct_goal'(TypeIn:Goal, Bindings, Corrected),
 1063    !,
 1064    setup_call_cleanup(
 1065        '$set_source_module'(M0, TypeIn),
 1066        expand_goal(Corrected, Expanded),
 1067        '$set_source_module'(M0)),
 1068    print_message(silent, toplevel_goal(Expanded, Bindings)),
 1069    '$execute_goal2'(Expanded, Bindings).
 1070'$execute'(_, _) :-
 1071    notrace,
 1072    print_message(query, query(no)).
 1073
 1074'$execute_goal2'(Goal, Bindings) :-
 1075    restore_debug,
 1076    residue_vars(Goal, Vars),
 1077    deterministic(Det),
 1078    (   save_debug
 1079    ;   restore_debug, fail
 1080    ),
 1081    flush_output(user_output),
 1082    call_expand_answer(Bindings, NewBindings),
 1083    (    \+ \+ write_bindings(NewBindings, Vars, Det)
 1084    ->   !
 1085    ).
 1086'$execute_goal2'(_, _) :-
 1087    save_debug,
 1088    print_message(query, query(no)).
 1089
 1090residue_vars(Goal, Vars) :-
 1091    current_prolog_flag(toplevel_residue_vars, true),
 1092    !,
 1093    call_residue_vars(Goal, Vars).
 1094residue_vars(Goal, []) :-
 1095    toplevel_call(Goal).
 1096
 1097toplevel_call(Goal) :-
 1098    call(Goal),
 1099    no_lco.
 1100
 1101no_lco.
 write_bindings(+Bindings, +ResidueVars, +Deterministic) is semidet
Write bindings resulting from a query. The flag prompt_alternatives_on determines whether the user is prompted for alternatives. groundness gives the classical behaviour, determinism is considered more adequate and informative.

Succeeds if the user accepts the answer and fails otherwise.

Arguments:
ResidueVars- are the residual constraints and provided if the prolog flag toplevel_residue_vars is set to project.
 1116write_bindings(Bindings, ResidueVars, Det) :-
 1117    '$current_typein_module'(TypeIn),
 1118    translate_bindings(Bindings, Bindings1, ResidueVars, TypeIn:Residuals),
 1119    write_bindings2(Bindings1, Residuals, Det).
 1120
 1121write_bindings2([], Residuals, _) :-
 1122    current_prolog_flag(prompt_alternatives_on, groundness),
 1123    !,
 1124    print_message(query, query(yes(Residuals))).
 1125write_bindings2(Bindings, Residuals, true) :-
 1126    current_prolog_flag(prompt_alternatives_on, determinism),
 1127    !,
 1128    print_message(query, query(yes(Bindings, Residuals))).
 1129write_bindings2(Bindings, Residuals, _Det) :-
 1130    repeat,
 1131        print_message(query, query(more(Bindings, Residuals))),
 1132        get_respons(Action),
 1133    (   Action == redo
 1134    ->  !, fail
 1135    ;   Action == show_again
 1136    ->  fail
 1137    ;   !,
 1138        print_message(query, query(done))
 1139    ).
 residual_goals(:NonTerminal)
Directive that registers NonTerminal as a collector for residual goals.
 1146:- multifile
 1147    residual_goal_collector/1. 1148
 1149:- meta_predicate
 1150    residual_goals(2). 1151
 1152residual_goals(NonTerminal) :-
 1153    throw(error(context_error(nodirective, residual_goals(NonTerminal)), _)).
 1154
 1155system:term_expansion((:- residual_goals(NonTerminal)),
 1156                      '$toplevel':residual_goal_collector(M2:Head)) :-
 1157    prolog_load_context(module, M),
 1158    strip_module(M:NonTerminal, M2, Head),
 1159    '$must_be'(callable, Head).
 prolog:residual_goals// is det
DCG that collects residual goals that are not associated with the answer through attributed variables.
 1166:- public prolog:residual_goals//0. 1167
 1168prolog:residual_goals -->
 1169    { findall(NT, residual_goal_collector(NT), NTL) },
 1170    collect_residual_goals(NTL).
 1171
 1172collect_residual_goals([]) --> [].
 1173collect_residual_goals([H|T]) -->
 1174    ( call(H) -> [] ; [] ),
 1175    collect_residual_goals(T).
 prolog:translate_bindings(+Bindings0, -Bindings, +ResidueVars, +ResidualGoals, -Residuals) is det
Translate the raw variable bindings resulting from successfully completing a query into a binding list and list of residual goals suitable for human consumption.
Arguments:
Bindings- is a list of binding(Vars,Value,Substitutions), where Vars is a list of variable names. E.g. binding(['A','B'],42,[])` means that both the variable A and B have the value 42. Values may contain terms '$VAR'(Name) to indicate sharing with a given variable. Value is always an acyclic term. If cycles appear in the answer, Substitutions contains a list of substitutions that restore the original term.
Residuals- is a pair of two lists representing residual goals. The first element of the pair are residuals related to the query variables and the second are related that are disconnected from the query.
 1200:- public
 1201    prolog:translate_bindings/5. 1202:- meta_predicate
 1203    prolog:translate_bindings(+, -, +, +, :). 1204
 1205prolog:translate_bindings(Bindings0, Bindings, ResVars, ResGoals, Residuals) :-
 1206    translate_bindings(Bindings0, Bindings, ResVars, ResGoals, Residuals).
 1207
 1208translate_bindings(Bindings0, Bindings, ResidueVars, Residuals) :-
 1209    prolog:residual_goals(ResidueGoals, []),
 1210    translate_bindings(Bindings0, Bindings, ResidueVars, ResidueGoals,
 1211                       Residuals).
 1212
 1213translate_bindings(Bindings0, Bindings, [], [], _:[]-[]) :-
 1214    term_attvars(Bindings0, []),
 1215    !,
 1216    join_same_bindings(Bindings0, Bindings1),
 1217    factorize_bindings(Bindings1, Bindings2),
 1218    bind_vars(Bindings2, Bindings3),
 1219    filter_bindings(Bindings3, Bindings).
 1220translate_bindings(Bindings0, Bindings, ResidueVars, ResGoals0,
 1221                   TypeIn:Residuals-HiddenResiduals) :-
 1222    project_constraints(Bindings0, ResidueVars),
 1223    hidden_residuals(ResidueVars, Bindings0, HiddenResiduals0),
 1224    omit_qualifiers(HiddenResiduals0, TypeIn, HiddenResiduals),
 1225    copy_term(Bindings0+ResGoals0, Bindings1+ResGoals1, Residuals0),
 1226    '$append'(ResGoals1, Residuals0, Residuals1),
 1227    omit_qualifiers(Residuals1, TypeIn, Residuals),
 1228    join_same_bindings(Bindings1, Bindings2),
 1229    factorize_bindings(Bindings2, Bindings3),
 1230    bind_vars(Bindings3, Bindings4),
 1231    filter_bindings(Bindings4, Bindings).
 1232
 1233hidden_residuals(ResidueVars, Bindings, Goal) :-
 1234    term_attvars(ResidueVars, Remaining),
 1235    term_attvars(Bindings, QueryVars),
 1236    subtract_vars(Remaining, QueryVars, HiddenVars),
 1237    copy_term(HiddenVars, _, Goal).
 1238
 1239subtract_vars(All, Subtract, Remaining) :-
 1240    sort(All, AllSorted),
 1241    sort(Subtract, SubtractSorted),
 1242    ord_subtract(AllSorted, SubtractSorted, Remaining).
 1243
 1244ord_subtract([], _Not, []).
 1245ord_subtract([H1|T1], L2, Diff) :-
 1246    diff21(L2, H1, T1, Diff).
 1247
 1248diff21([], H1, T1, [H1|T1]).
 1249diff21([H2|T2], H1, T1, Diff) :-
 1250    compare(Order, H1, H2),
 1251    diff3(Order, H1, T1, H2, T2, Diff).
 1252
 1253diff12([], _H2, _T2, []).
 1254diff12([H1|T1], H2, T2, Diff) :-
 1255    compare(Order, H1, H2),
 1256    diff3(Order, H1, T1, H2, T2, Diff).
 1257
 1258diff3(<,  H1, T1,  H2, T2, [H1|Diff]) :-
 1259    diff12(T1, H2, T2, Diff).
 1260diff3(=, _H1, T1, _H2, T2, Diff) :-
 1261    ord_subtract(T1, T2, Diff).
 1262diff3(>,  H1, T1, _H2, T2, Diff) :-
 1263    diff21(T2, H1, T1, Diff).
 project_constraints(+Bindings, +ResidueVars) is det
Call <module>:project_attributes/2 if the Prolog flag toplevel_residue_vars is set to project.
 1271project_constraints(Bindings, ResidueVars) :-
 1272    !,
 1273    term_attvars(Bindings, AttVars),
 1274    phrase(attribute_modules(AttVars), Modules0),
 1275    sort(Modules0, Modules),
 1276    term_variables(Bindings, QueryVars),
 1277    project_attributes(Modules, QueryVars, ResidueVars).
 1278project_constraints(_, _).
 1279
 1280project_attributes([], _, _).
 1281project_attributes([M|T], QueryVars, ResidueVars) :-
 1282    (   current_predicate(M:project_attributes/2),
 1283        catch(M:project_attributes(QueryVars, ResidueVars), E,
 1284              print_message(error, E))
 1285    ->  true
 1286    ;   true
 1287    ),
 1288    project_attributes(T, QueryVars, ResidueVars).
 1289
 1290attribute_modules([]) --> [].
 1291attribute_modules([H|T]) -->
 1292    { get_attrs(H, Attrs) },
 1293    attrs_modules(Attrs),
 1294    attribute_modules(T).
 1295
 1296attrs_modules([]) --> [].
 1297attrs_modules(att(Module, _, More)) -->
 1298    [Module],
 1299    attrs_modules(More).
 join_same_bindings(Bindings0, Bindings)
Join variables that are bound to the same value. Note that we return the last value. This is because the factorization may be different and ultimately the names will be printed as V1 = V2, ... VN = Value. Using the last, Value has the factorization of VN.
 1310join_same_bindings([], []).
 1311join_same_bindings([Name=V0|T0], [[Name|Names]=V|T]) :-
 1312    take_same_bindings(T0, V0, V, Names, T1),
 1313    join_same_bindings(T1, T).
 1314
 1315take_same_bindings([], Val, Val, [], []).
 1316take_same_bindings([Name=V1|T0], V0, V, [Name|Names], T) :-
 1317    V0 == V1,
 1318    !,
 1319    take_same_bindings(T0, V1, V, Names, T).
 1320take_same_bindings([Pair|T0], V0, V, Names, [Pair|T]) :-
 1321    take_same_bindings(T0, V0, V, Names, T).
 omit_qualifiers(+QGoals, +TypeIn, -Goals) is det
Omit unneeded module qualifiers from QGoals relative to the given module TypeIn.
 1330omit_qualifiers([], _, []).
 1331omit_qualifiers([Goal0|Goals0], TypeIn, [Goal|Goals]) :-
 1332    omit_qualifier(Goal0, TypeIn, Goal),
 1333    omit_qualifiers(Goals0, TypeIn, Goals).
 1334
 1335omit_qualifier(M:G0, TypeIn, G) :-
 1336    M == TypeIn,
 1337    !,
 1338    omit_meta_qualifiers(G0, TypeIn, G).
 1339omit_qualifier(M:G0, TypeIn, G) :-
 1340    predicate_property(TypeIn:G0, imported_from(M)),
 1341    \+ predicate_property(G0, transparent),
 1342    !,
 1343    G0 = G.
 1344omit_qualifier(_:G0, _, G) :-
 1345    predicate_property(G0, built_in),
 1346    \+ predicate_property(G0, transparent),
 1347    !,
 1348    G0 = G.
 1349omit_qualifier(M:G0, _, M:G) :-
 1350    atom(M),
 1351    !,
 1352    omit_meta_qualifiers(G0, M, G).
 1353omit_qualifier(G0, TypeIn, G) :-
 1354    omit_meta_qualifiers(G0, TypeIn, G).
 1355
 1356omit_meta_qualifiers(V, _, V) :-
 1357    var(V),
 1358    !.
 1359omit_meta_qualifiers((QA,QB), TypeIn, (A,B)) :-
 1360    !,
 1361    omit_qualifier(QA, TypeIn, A),
 1362    omit_qualifier(QB, TypeIn, B).
 1363omit_meta_qualifiers(freeze(V, QGoal), TypeIn, freeze(V, Goal)) :-
 1364    callable(QGoal),
 1365    !,
 1366    omit_qualifier(QGoal, TypeIn, Goal).
 1367omit_meta_qualifiers(when(Cond, QGoal), TypeIn, when(Cond, Goal)) :-
 1368    callable(QGoal),
 1369    !,
 1370    omit_qualifier(QGoal, TypeIn, Goal).
 1371omit_meta_qualifiers(G, _, G).
 bind_vars(+BindingsIn, -Bindings)
Bind variables to '$VAR'(Name), so they are printed by the names used in the query. Note that by binding in the reverse order, variables bound to one another come out in the natural order.
 1380bind_vars(Bindings0, Bindings) :-
 1381    bind_query_vars(Bindings0, Bindings, SNames),
 1382    bind_skel_vars(Bindings, Bindings, SNames, 1, _).
 1383
 1384bind_query_vars([], [], []).
 1385bind_query_vars([binding(Names,Var,[Var2=Cycle])|T0],
 1386                [binding(Names,Cycle,[])|T], [Name|SNames]) :-
 1387    Var == Var2,                   % also implies var(Var)
 1388    !,
 1389    '$last'(Names, Name),
 1390    Var = '$VAR'(Name),
 1391    bind_query_vars(T0, T, SNames).
 1392bind_query_vars([B|T0], [B|T], AllNames) :-
 1393    B = binding(Names,Var,Skel),
 1394    bind_query_vars(T0, T, SNames),
 1395    (   var(Var), \+ attvar(Var), Skel == []
 1396    ->  AllNames = [Name|SNames],
 1397        '$last'(Names, Name),
 1398        Var = '$VAR'(Name)
 1399    ;   AllNames = SNames
 1400    ).
 1401
 1402
 1403
 1404bind_skel_vars([], _, _, N, N).
 1405bind_skel_vars([binding(_,_,Skel)|T], Bindings, SNames, N0, N) :-
 1406    bind_one_skel_vars(Skel, Bindings, SNames, N0, N1),
 1407    bind_skel_vars(T, Bindings, SNames, N1, N).
 bind_one_skel_vars(+Subst, +Bindings, +VarName, +N0, -N)
Give names to the factorized variables that do not have a name yet. This introduces names _S<N>, avoiding duplicates. If a factorized variable shares with another binding, use the name of that variable.
To be done
- Consider the call below. We could remove either of the A = x(1). Which is best?
?- A = x(1), B = a(A,A).
A = x(1),
B = a(A, A), % where
    A = x(1).
 1426bind_one_skel_vars([], _, _, N, N).
 1427bind_one_skel_vars([Var=Value|T], Bindings, Names, N0, N) :-
 1428    (   var(Var)
 1429    ->  (   '$member'(binding(Names, VVal, []), Bindings),
 1430            same_term(Value, VVal)
 1431        ->  '$last'(Names, VName),
 1432            Var = '$VAR'(VName),
 1433            N2 = N0
 1434        ;   between(N0, infinite, N1),
 1435            atom_concat('_S', N1, Name),
 1436            \+ memberchk(Name, Names),
 1437            !,
 1438            Var = '$VAR'(Name),
 1439            N2 is N1 + 1
 1440        )
 1441    ;   N2 = N0
 1442    ),
 1443    bind_one_skel_vars(T, Bindings, Names, N2, N).
 factorize_bindings(+Bindings0, -Factorized)
Factorize cycles and sharing in the bindings.
 1450factorize_bindings([], []).
 1451factorize_bindings([Name=Value|T0], [binding(Name, Skel, Subst)|T]) :-
 1452    '$factorize_term'(Value, Skel, Subst0),
 1453    (   current_prolog_flag(toplevel_print_factorized, true)
 1454    ->  Subst = Subst0
 1455    ;   only_cycles(Subst0, Subst)
 1456    ),
 1457    factorize_bindings(T0, T).
 1458
 1459
 1460only_cycles([], []).
 1461only_cycles([B|T0], List) :-
 1462    (   B = (Var=Value),
 1463        Var = Value,
 1464        acyclic_term(Var)
 1465    ->  only_cycles(T0, List)
 1466    ;   List = [B|T],
 1467        only_cycles(T0, T)
 1468    ).
 filter_bindings(+Bindings0, -Bindings)
Remove bindings that must not be printed. There are two of them: Variables whose name start with '_' and variables that are only bound to themselves (or, unbound).
 1477filter_bindings([], []).
 1478filter_bindings([H0|T0], T) :-
 1479    hide_vars(H0, H),
 1480    (   (   arg(1, H, [])
 1481        ;   self_bounded(H)
 1482        )
 1483    ->  filter_bindings(T0, T)
 1484    ;   T = [H|T1],
 1485        filter_bindings(T0, T1)
 1486    ).
 1487
 1488hide_vars(binding(Names0, Skel, Subst), binding(Names, Skel, Subst)) :-
 1489    hide_names(Names0, Skel, Subst, Names).
 1490
 1491hide_names([], _, _, []).
 1492hide_names([Name|T0], Skel, Subst, T) :-
 1493    (   sub_atom(Name, 0, _, _, '_'),
 1494        current_prolog_flag(toplevel_print_anon, false),
 1495        sub_atom(Name, 1, 1, _, Next),
 1496        char_type(Next, prolog_var_start)
 1497    ->  true
 1498    ;   Subst == [],
 1499        Skel == '$VAR'(Name)
 1500    ),
 1501    !,
 1502    hide_names(T0, Skel, Subst, T).
 1503hide_names([Name|T0], Skel, Subst, [Name|T]) :-
 1504    hide_names(T0, Skel, Subst, T).
 1505
 1506self_bounded(binding([Name], Value, [])) :-
 1507    Value == '$VAR'(Name).
 get_respons(-Action)
Read the continuation entered by the user.
 1513get_respons(Action) :-
 1514    repeat,
 1515        flush_output(user_output),
 1516        get_single_char(Char),
 1517        answer_respons(Char, Action),
 1518        (   Action == again
 1519        ->  print_message(query, query(action)),
 1520            fail
 1521        ;   !
 1522        ).
 1523
 1524answer_respons(Char, again) :-
 1525    '$in_reply'(Char, '?h'),
 1526    !,
 1527    print_message(help, query(help)).
 1528answer_respons(Char, redo) :-
 1529    '$in_reply'(Char, ';nrNR \t'),
 1530    !,
 1531    print_message(query, if_tty([ansi(bold, ';', [])])).
 1532answer_respons(Char, redo) :-
 1533    '$in_reply'(Char, 'tT'),
 1534    !,
 1535    trace,
 1536    save_debug,
 1537    print_message(query, if_tty([ansi(bold, '; [trace]', [])])).
 1538answer_respons(Char, continue) :-
 1539    '$in_reply'(Char, 'ca\n\ryY.'),
 1540    !,
 1541    print_message(query, if_tty([ansi(bold, '.', [])])).
 1542answer_respons(0'b, show_again) :-
 1543    !,
 1544    break.
 1545answer_respons(Char, show_again) :-
 1546    print_predicate(Char, Pred, Options),
 1547    !,
 1548    print_message(query, if_tty(['~w'-[Pred]])),
 1549    set_prolog_flag(answer_write_options, Options).
 1550answer_respons(-1, show_again) :-
 1551    !,
 1552    print_message(query, halt('EOF')),
 1553    halt(0).
 1554answer_respons(Char, again) :-
 1555    print_message(query, no_action(Char)).
 1556
 1557print_predicate(0'w, [write], [ quoted(true),
 1558                                spacing(next_argument)
 1559                              ]).
 1560print_predicate(0'p, [print], [ quoted(true),
 1561                                portray(true),
 1562                                max_depth(10),
 1563                                spacing(next_argument)
 1564                              ]).
 1565
 1566
 1567                 /*******************************
 1568                 *          EXPANSION           *
 1569                 *******************************/
 1570
 1571:- user:dynamic(expand_query/4). 1572:- user:multifile(expand_query/4). 1573
 1574call_expand_query(Goal, Expanded, Bindings, ExpandedBindings) :-
 1575    user:expand_query(Goal, Expanded, Bindings, ExpandedBindings),
 1576    !.
 1577call_expand_query(Goal, Expanded, Bindings, ExpandedBindings) :-
 1578    toplevel_variables:expand_query(Goal, Expanded, Bindings, ExpandedBindings),
 1579    !.
 1580call_expand_query(Goal, Goal, Bindings, Bindings).
 1581
 1582
 1583:- user:dynamic(expand_answer/2). 1584:- user:multifile(expand_answer/2). 1585
 1586call_expand_answer(Goal, Expanded) :-
 1587    user:expand_answer(Goal, Expanded),
 1588    !.
 1589call_expand_answer(Goal, Expanded) :-
 1590    toplevel_variables:expand_answer(Goal, Expanded),
 1591    !.
 1592call_expand_answer(Goal, Goal)