View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           https://www.swi-prolog.org
    6    Copyright (c)  1997-2026, University of Amsterdam
    7                              VU University Amsterdam
    8                              CWI, Amsterdam
    9                              SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module('$messages',
   39          [ print_message/2,            % +Kind, +Term
   40            print_message_lines/3,      % +Stream, +Prefix, +Lines
   41            message_to_string/2         % +Term, -String
   42          ]).   43
   44:- multifile
   45    prolog:message//1,              % entire message
   46    prolog:error_message//1,        % 1-st argument of error term
   47    prolog:message_context//1,      % Context of error messages
   48    prolog:deprecated//1,	    % Deprecated features
   49    prolog:message_location//1,     % (File) location of error messages
   50    prolog:message_line_element/2,  % Extend printing
   51    prolog:message_action/2.        % Side effects (broadcast)
   52:- dynamic
   53    prolog:message_action/2.        % Allow overruling
   54:- '$hide'((
   55    prolog:message//1,
   56    prolog:error_message//1,
   57    prolog:message_context//1,
   58    prolog:deprecated//1,
   59    prolog:message_location//1,
   60    prolog:message_line_element/2)).   61% Lang, Term versions
   62:- multifile
   63    prolog:message//2,              % entire message
   64    prolog:error_message//2,        % 1-st argument of error term
   65    prolog:message_context//2,      % Context of error messages
   66    prolog:message_location//2,	    % (File) location of error messages
   67    prolog:deprecated//2.	    % Deprecated features
   68:- '$hide'((
   69    prolog:message//2,
   70    prolog:error_message//2,
   71    prolog:message_context//2,
   72    prolog:deprecated//2,
   73    prolog:message_location//2)).   74
   75:- discontiguous
   76    prolog_message/3.   77
   78:- public
   79    translate_message//1,           % +Message (deprecated)
   80    prolog:translate_message//1.    % +Message
   81
   82:- create_prolog_flag(message_context, [thread], []).   83:- create_prolog_flag(debugger_goal_links, auto,
   84                      [ type(oneof([false,true,auto])),
   85                        keep(true)
   86                      ]).
 translate_message(+Term)// is det
Translate a message Term into message lines. The produced lines is a list of
nl
Emit a newline
Fmt - Args
Emit the result of format(Fmt, Args)
Fmt
Emit the result of format(Fmt)
ansi(Class, Fmt, Args)
Use ansi_format/3 for color output.
url(Location)
Emit a source location as a hyperlink. Location is File:Line:Column, File:Line, File or a URL.
url(Location, Label)
As above, but print Label rather than Location. Label is plain text, Fmt-Args or ansi(Class, Fmt, Args), the latter combining a hyperlink with a style class.
flush
Used only as last element of the list. Simply flush the output instead of producing a final newline.
at_same_line
Start the messages at the same line (instead of using ~N)
eol
End the decorated part of the last line. See print_message_lines/3.

The elements begin(Class, Ctx) and end(Ctx) that decorate the message as a whole are added by print_message_lines/3.

Use predicate_reference//1,2 to refer to a predicate rather than formatting the predicate indicator by hand.

deprecated
- Use code for message translation should call translate_message//1.
  126prolog:translate_message(Term) -->
  127    translate_message(Term).
 translate_message(+Term)// is det
Translate a message term into message lines. This version may be called from user and library definitions for message translation.
  134translate_message(Term) -->
  135    { nonvar(Term) },
  136    (   { message_lang(Lang) },
  137        prolog:message(Lang, Term)
  138    ;   prolog:message(Term)
  139    ),
  140    !.
  141translate_message(Term) -->
  142    { nonvar(Term) },
  143    translate_message2(Term),
  144    !.
  145translate_message(Term) -->
  146    { nonvar(Term),
  147      Term = error(_, _)
  148    },
  149    [ 'Unknown exception: ~p'-[Term] ].
  150translate_message(Term) -->
  151    [ 'Unknown message: ~p'-[Term] ].
  152
  153translate_message2(Term) -->
  154    prolog_message(Term).
  155translate_message2(error(resource_error(stack), Context)) -->
  156    !,
  157    out_of_stack(Context).
  158translate_message2(error(resource_error(tripwire(Wire, Context)), _)) -->
  159    !,
  160    tripwire_message(Wire, Context).
  161translate_message2(error(existence_error(reset, Ball), SWI)) -->
  162    swi_location(SWI),
  163    tabling_existence_error(Ball, SWI).
  164translate_message2(error(ISO, SWI)) -->
  165    swi_location(SWI),
  166    term_message(ISO),
  167    swi_extra(SWI).
  168translate_message2(unwind(Term)) -->
  169    unwind_message(Term).
  170translate_message2(message_lines(Lines), L, T) :- % deal with old C-warning()
  171    make_message_lines(Lines, L, T).
  172translate_message2(format(Fmt, Args)) -->
  173    [ Fmt-Args ].
 translate_exception(+Exception)//
As translate_message//1 for an exception. Exceptions may be data from elsewhere, e.g., an error received from a remote pengine, so a format(Fmt, Args) ball is only formatted if Fmt does not call goals. Other messages that hold an exception use this as well.
  182translate_exception(Ex) -->
  183    { nonvar(Ex),
  184      Ex = format(Fmt, Args)
  185    },
  186    !,
  187    format_message(Fmt, Args).
  188translate_exception(Ex) -->
  189    translate_message(Ex).
 format_message(+Fmt, +Args)//
Format Args using Fmt, unless Fmt calls goals using ~@ or ~W or is not text. In that case, print the term. Used for format(Fmt, Args) inside exceptions.
  197format_message(Fmt, Args) -->
  198    (   { format_calls_goals(Fmt) }
  199    ->  [ '~q'-[format(Fmt, Args)] ]
  200    ;   [ Fmt-Args ]
  201    ).
  202
  203format_calls_goals(Fmt) :-
  204    (   catch(text_to_string(Fmt, String), _, fail)
  205    ->  string_codes(String, Codes),
  206        fmt_goal_directive(Codes)
  207    ;   true
  208    ).
  209
  210fmt_goal_directive([0'~|T0]) :-
  211    !,
  212    fmt_skip_argument(T0, T),
  213    (   T = [C|_],
  214        ( C == 0'@ ; C == 0'W )
  215    ->  true
  216    ;   T = [_|T1],
  217        fmt_goal_directive(T1)
  218    ).
  219fmt_goal_directive([_|T]) :-
  220    fmt_goal_directive(T).
  221
  222fmt_skip_argument([0'`,_|T0], T) :-
  223    !,
  224    T = T0.
  225fmt_skip_argument([0'*|T0], T) :-
  226    !,
  227    T = T0.
  228fmt_skip_argument([D|T0], T) :-
  229    code_type(D, digit),
  230    !,
  231    fmt_skip_argument(T0, T).
  232fmt_skip_argument(T, T).
  233
  234make_message_lines([], T, T) :- !.
  235make_message_lines([Last],  ['~w'-[Last]|T], T) :- !.
  236make_message_lines([L0|LT], ['~w'-[L0],nl|T0], T) :-
  237    make_message_lines(LT, T0, T).
 term_message(+Term)//
Deal with the formal argument of error(Format, ImplDefined) exception terms. The ImplDefined argument is handled by swi_location//2.
  245:- public term_message//1.  246term_message(Term) -->
  247    {var(Term)},
  248    !,
  249    [ 'Unknown error term: ~p'-[Term] ].
  250term_message(Term) -->
  251    { message_lang(Lang) },
  252    prolog:error_message(Lang, Term),
  253    !.
  254term_message(Term) -->
  255    prolog:error_message(Term),
  256    !.
  257term_message(Term) -->
  258    iso_message(Term).
  259term_message(Term) -->
  260    swi_message(Term).
  261term_message(Term) -->
  262    [ 'Unknown error term: ~p'-[Term] ].
  263
  264iso_message(resource_error(c_stack)) -->
  265    out_of_c_stack.
  266iso_message(resource_error(Missing)) -->
  267    [ 'Not enough resources: ~w'-[Missing] ].
  268iso_message(type_error(Var, Actual)) -->
  269    { var(Var) },
  270    [ 'Type error: unbound (var) type expected, found `~p'''-[Actual] ].
  271iso_message(type_error(evaluable, Actual)) -->
  272    { callable(Actual) },
  273    [ 'Arithmetic: `~p'' is not a function'-[Actual] ].
  274iso_message(type_error(free_of_attvar, Actual)) -->
  275    [ 'Type error: `~W'' contains attributed variables'-
  276      [Actual,[portray(true), attributes(portray)]] ].
  277iso_message(type_error(Expected, Actual)) -->
  278    [ 'Type error: `~w'' expected, found `~p'''-[Expected, Actual] ],
  279    type_error_comment(Expected, Actual).
  280iso_message(domain_error(Domain, Actual)) -->
  281    [ 'Domain error: '-[] ], domain(Domain),
  282    [ ' expected, found `~p'''-[Actual] ].
  283iso_message(instantiation_error) -->
  284    [ 'Arguments are not sufficiently instantiated' ].
  285iso_message(uninstantiation_error(Var)) -->
  286    [ 'Uninstantiated argument expected, found ~p'-[Var] ].
  287iso_message(representation_error(standard_order(T1, T2))) -->
  288    [ 'Cyclic terms have no standard order: ~p and ~p'-[T1, T2] ].
  289iso_message(representation_error(What)) -->
  290    { compound(What),
  291      compound_name_arguments(What, Id, [Culprit]),
  292      !,
  293      culprit_write_options(Options)
  294    },
  295    [ 'Cannot represent ~W as `~w'''-[Culprit, Options, Id] ].
  296iso_message(representation_error(What)) -->
  297    [ 'Cannot represent due to `~w'''-[What] ].
  298iso_message(permission_error(Action, Type, Object)) -->
  299    permission_error(Action, Type, Object).
  300iso_message(evaluation_error(Which)) -->
  301    [ 'Arithmetic: evaluation error: `~p'''-[Which] ].
  302iso_message(existence_error(procedure, Proc)) -->
  303    [ 'Unknown procedure: ' ],
  304    predicate_reference(Proc),
  305    unknown_proc_msg(Proc).
  306iso_message(existence_error(answer_variable, Var)) -->
  307    [ '$~w was not bound by a previous query'-[Var] ].
  308iso_message(existence_error(matching_rule, Goal)) -->
  309    [ 'No rule matches ~p'-[Goal] ].
  310iso_message(existence_error(Type, Object)) -->
  311    [ '~w `~p'' does not exist'-[Type, Object] ].
  312iso_message(existence_error(export, PI, module(M))) --> % not ISO
  313    [ 'Module ', ansi(code, '~q', [M]), ' does not export ' ],
  314    predicate_reference(M:PI, [module(hide)]).
  315iso_message(existence_error(Type, Object, In)) --> % not ISO
  316    [ '~w `~p'' does not exist in ~p'-[Type, Object, In] ].
  317iso_message(busy(Type, Object)) -->
  318    [ '~w `~p'' is busy'-[Type, Object] ].
  319iso_message(syntax_error(swi_backslash_newline)) -->
  320    [ 'Deprecated: ... \\<newline><white>*.  Use \\c' ].
  321iso_message(syntax_error(warning_var_tag)) -->
  322    [ 'Deprecated: dict with unbound tag (_{...}).  Mapped to #{...}.' ].
  323iso_message(syntax_error(var_tag)) -->
  324    [ 'Syntax error: dict syntax with unbound tag (_{...}).' ].
  325iso_message(syntax_error(Id)) -->
  326    [ 'Syntax error: ' ],
  327    syntax_error(Id).
  328iso_message(occurs_check(Var, In)) -->
  329    [ 'Cannot unify ~p with ~p: would create an infinite tree'-[Var, In] ].
 culprit_write_options(-Options) is det
Options to print a culprit that may be large. The defaults limit the depth and length of text. The flag print_write_options may override them.
  337culprit_write_options(Options) :-
  338    current_prolog_flag(print_write_options, Options0),
  339    Options = [max_depth(10), max_text(100)|Options0].
 permission_error(Action, Type, Object)//
Translate permission errors. Most follow te pattern "No permission to Action Type Object", but some are a bit different.
  346permission_error(Action, built_in_procedure, Pred) -->
  347    [ 'No permission to ~w built-in predicate '-[Action] ],
  348    predicate_reference(Pred),
  349    (   {Action \== export}
  350    ->  [ nl,
  351          'Use :- redefine_system_predicate(+Head) if redefinition is intended'
  352        ]
  353    ;   []
  354    ).
  355permission_error(import_into(Dest), procedure, Pred) -->
  356    [ 'No permission to import ' ],
  357    predicate_reference(Pred),
  358    [ ' into ~w'-[Dest] ].
  359permission_error(Action, static_procedure, Proc) -->
  360    [ 'No permission to ~w static procedure '-[Action] ],
  361    predicate_reference(Proc),
  362    predicate_definition(Proc, 'Defined').
  363permission_error(input, stream, Stream) -->
  364    [ 'No permission to read from output stream `~p'''-[Stream] ].
  365permission_error(output, stream, Stream) -->
  366    [ 'No permission to write to input stream `~p'''-[Stream] ].
  367permission_error(input, text_stream, Stream) -->
  368    [ 'No permission to read bytes from TEXT stream `~p'''-[Stream] ].
  369permission_error(output, text_stream, Stream) -->
  370    [ 'No permission to write bytes to TEXT stream `~p'''-[Stream] ].
  371permission_error(input, binary_stream, Stream) -->
  372    [ 'No permission to read characters from binary stream `~p'''-[Stream] ].
  373permission_error(output, binary_stream, Stream) -->
  374    [ 'No permission to write characters to binary stream `~p'''-[Stream] ].
  375permission_error(open, source_sink, alias(Alias)) -->
  376    [ 'No permission to reuse alias "~p": already taken'-[Alias] ].
  377permission_error(tnot, non_tabled_procedure, Pred) -->
  378    [ 'The argument of ' ], predicate_reference(tnot/1),
  379    [ ' is not tabled: ' ], predicate_reference(Pred).
  380permission_error(assert, procedure, Pred) -->
  381    { predicate_head(Pred, Head),
  382      predicate_property(Head, ssu)
  383    },
  384    predicate_reference(Pred),
  385    [ ': an SSU (Head => Body) predicate cannot have normal Prolog clauses' ].
  386permission_error(Action, Type, Object) -->
  387    [ 'No permission to ~w ~w `~p'''-[Action, Type, Object] ].
  388
  389
  390unknown_proc_msg(_:(^)/2) -->
  391    !,
  392    unknown_proc_msg((^)/2).
  393unknown_proc_msg((^)/2) -->
  394    !,
  395    [nl, '  ^/2 can only appear as the 2nd argument of setof/3 and bagof/3'].
  396unknown_proc_msg((:-)/2) -->
  397    !,
  398    [nl, '  Rules must be loaded from a file'],
  399    faq('ToplevelMode').
  400unknown_proc_msg((=>)/2) -->
  401    !,
  402    [nl, '  Rules must be loaded from a file'],
  403    faq('ToplevelMode').
  404unknown_proc_msg((:-)/1) -->
  405    !,
  406    [nl, '  Directives must be loaded from a file'],
  407    faq('ToplevelMode').
  408unknown_proc_msg((?-)/1) -->
  409    !,
  410    [nl, '  ?- is the Prolog prompt'],
  411    faq('ToplevelMode').
  412unknown_proc_msg(Proc) -->
  413    { dwim_predicates(Proc, Dwims) },
  414    (   {Dwims \== []}
  415    ->  [nl, '  However, there are definitions for:', nl],
  416        dwim_alternatives(Dwims)
  417    ;   []
  418    ).
  419
  420dependency_error(shared(Shared), private(Private)) -->
  421    [ 'Shared table for ' ], predicate_reference(Shared),
  422    [ ' may not depend on private ' ], predicate_reference(Private).
  423dependency_error(Dep, monotonic(On)) -->
  424    [ 'Dependent ' ], predicate_reference(Dep),
  425    [ ' on monotonic predicate ' ], predicate_reference(On),
  426    [ ' is not monotonic or incremental' ].
  427
  428faq(Page) -->
  429    [nl, '  See FAQ at https://www.swi-prolog.org/FAQ/', Page, '.html' ].
  430
  431type_error_comment(_Expected, Actual) -->
  432    { type_of(Actual, Type),
  433      (   sub_atom(Type, 0, 1, _, First),
  434          memberchk(First, [a,e,i,o,u])
  435      ->  Article = an
  436      ;   Article = a
  437      )
  438    },
  439    [ ' (~w ~w)'-[Article, Type] ].
  440
  441type_of(Term, Type) :-
  442    (   attvar(Term)      -> Type = attvar
  443    ;   var(Term)         -> Type = var
  444    ;   atom(Term)        -> Type = atom
  445    ;   integer(Term)     -> Type = integer
  446    ;   string(Term)      -> Type = string
  447    ;   Term == []        -> Type = empty_list
  448    ;   blob(Term, BlobT) -> blob_type(BlobT, Type)
  449    ;   rational(Term)    -> Type = rational
  450    ;   float(Term)       -> Type = float
  451    ;   is_stream(Term)   -> Type = stream
  452    ;   is_dict(Term)     -> Type = dict
  453    ;   is_list(Term)     -> Type = list
  454    ;   Term = [_|_]      -> list_like(Term, Type)
  455    ;   cyclic_term(Term) -> Type = cyclic
  456    ;   compound(Term)    -> Type = compound
  457    ;                        Type = unknown
  458    ).
  459
  460list_like(Term, Type) :-
  461    '$skip_list'(_, Term, Tail),
  462    (   var(Tail)
  463    ->  Type = partial_list
  464    ;   Type = invalid_list                      % TBD: Better name?
  465    ).
  466
  467blob_type(BlobT, Type) :-
  468    atom_concat(BlobT, '_reference', Type).
  469
  470syntax_error(end_of_clause) -->
  471    [ 'Unexpected end of clause' ].
  472syntax_error(end_of_clause_expected) -->
  473    [ 'End of clause expected' ].
  474syntax_error(end_of_file) -->
  475    [ 'Unexpected end of file' ].
  476syntax_error(end_of_file_in_block_comment) -->
  477    [ 'End of file in /* ... */ comment' ].
  478syntax_error(end_of_file_in_quoted(Quote)) -->
  479    [ 'End of file in quoted ' ],
  480    quoted_type(Quote).
  481syntax_error(illegal_number) -->
  482    [ 'Illegal number' ].
  483syntax_error(long_atom) -->
  484    [ 'Atom too long (see style_check/1)' ].
  485syntax_error(long_string) -->
  486    [ 'String too long (see style_check/1)' ].
  487syntax_error(operator_clash) -->
  488    [ 'Operator priority clash' ].
  489syntax_error(operator_expected) -->
  490    [ 'Operator expected' ].
  491syntax_error(operator_balance) -->
  492    [ 'Unbalanced operator' ].
  493syntax_error(quoted_punctuation) -->
  494    [ 'Operand expected, unquoted comma or bar found' ].
  495syntax_error(list_rest) -->
  496    [ 'Unexpected comma or bar in rest of list' ].
  497syntax_error(cannot_start_term) -->
  498    [ 'Illegal start of term' ].
  499syntax_error(punct(Punct, End)) -->
  500    [ 'Unexpected `~w\' before `~w\''-[Punct, End] ].
  501syntax_error(undefined_char_escape(C)) -->
  502    [ 'Unknown character escape in quoted atom or string: `\\~w\''-[C] ].
  503syntax_error(void_not_allowed) -->
  504    [ 'Empty argument list "()"' ].
  505syntax_error(encoding(Message)) -->
  506    [ 'Cannot decode input: ~w'-[Message] ].
  507syntax_error(Term) -->
  508    { compound(Term),
  509      compound_name_arguments(Term, Syntax, [Text])
  510    }, !,
  511    [ '~w expected, found '-[Syntax], ansi(code, '"~w"', [Text]) ].
  512syntax_error(Message) -->
  513    [ '~w'-[Message] ].
  514
  515quoted_type('\'') --> [atom].
  516quoted_type('\"') --> { current_prolog_flag(double_quotes, Type) }, [Type-[]].
  517quoted_type('\`') --> { current_prolog_flag(back_quotes, Type) }, [Type-[]].
  518
  519domain(range(Low,High)) -->
  520    !,
  521    ['[~q..~q]'-[Low,High] ].
  522domain(Domain) -->
  523    ['`~w\''-[Domain] ].
 tabling_existence_error(+Ball, +Context)//
Called on invalid shift/1 calls. Track those that result from tabling errors.
  530tabling_existence_error(Ball, Context) -->
  531    { table_shift_ball(Ball) },
  532    [ 'Tabling dependency error' ],
  533    swi_extra(Context).
  534
  535table_shift_ball(dependency(_Head)).
  536table_shift_ball(dependency(_Skeleton, _Trie, _Mono)).
  537table_shift_ball(call_info(_Skeleton, _Status)).
  538table_shift_ball(call_info(_GenSkeleton, _Skeleton, _Status)).
 dwim_predicates(+PI, -Dwims)
Find related predicate indicators.
  544dwim_predicates(Module:Name/_Arity, Dwims) :-
  545    !,
  546    findall(Dwim, dwim_predicate(Module:Name, Dwim), Dwims).
  547dwim_predicates(Name/_Arity, Dwims) :-
  548    findall(Dwim, dwim_predicate(user:Name, Dwim), Dwims).
  549
  550dwim_alternatives([]) --> [].
  551dwim_alternatives([H|T]) -->
  552    [ '        ' ],
  553    predicate_reference(H, [tag(true)]),
  554    [ nl ],
  555    dwim_alternatives(T).
  556
  557swi_message(io_error(Op, Stream)) -->
  558    [ 'I/O error in ~w on stream ~p'-[Op, Stream] ].
  559swi_message(thread_error(TID, false)) -->
  560    [ 'Thread ~p died due to failure:'-[TID] ].
  561swi_message(thread_error(TID, exception(Error))) -->
  562    [ 'Thread ~p died abnormally:'-[TID], nl ],
  563    translate_exception(Error).
  564swi_message(dependency_error(Tabled, DependsOn)) -->
  565    dependency_error(Tabled, DependsOn).
  566swi_message(shell(execute, Cmd)) -->
  567    [ 'Could not execute `~w'''-[Cmd] ].
  568swi_message(shell(signal(Sig), Cmd)) -->
  569    [ 'Caught signal ~d on `~w'''-[Sig, Cmd] ].
  570swi_message(format(Fmt, Args)) -->
  571    format_message(Fmt, Args).
  572swi_message(signal(Name, Num)) -->
  573    [ 'Caught signal ~d (~w)'-[Num, Name] ].
  574swi_message(limit_exceeded(Limit, MaxVal)) -->
  575    [ 'Exceeded ~w limit (~w)'-[Limit, MaxVal] ].
  576swi_message(goal_failed(Goal)) -->
  577    [ 'goal unexpectedly failed: ~p'-[Goal] ].
  578swi_message(shared_object(_Action, Message)) --> % Message = dlerror()
  579    [ '~w'-[Message] ].
  580swi_message(system_error(Error)) -->
  581    [ 'error in system call: ~w'-[Error]
  582    ].
  583swi_message(system_error) -->
  584    [ 'error in system call'
  585    ].
  586swi_message(failure_error(Goal)) -->
  587    [ 'Goal failed: ~p'-[Goal] ].
  588swi_message(timeout_error(Op, Stream)) -->
  589    [ 'Timeout in ~w from ~p'-[Op, Stream] ].
  590swi_message(not_implemented(Type, What)) -->
  591    [ '~w `~p\' is not implemented in this version'-[Type, What] ].
  592swi_message(context_error(nodirective, Goal)) -->
  593    [ 'Wrong context: ' ], predicate_reference(Goal),
  594    [ ' can only be used in a directive' ].
  595swi_message(context_error(edit, no_default_file)) -->
  596    (   { current_prolog_flag(windows, true) }
  597    ->  [ 'Edit/0 can only be used after opening a \c
  598               Prolog file by double-clicking it' ]
  599    ;   [ 'Edit/0 can only be used with the "-s file" commandline option'
  600        ]
  601    ),
  602    [ nl, 'Use "?- edit(Topic)." or "?- emacs."' ].
  603swi_message(context_error(function, meta_arg(S))) -->
  604    [ 'Functions are not (yet) supported for meta-arguments of type ~q'-[S] ].
  605swi_message(format_argument_type(Fmt, Arg)) -->
  606    [ 'Illegal argument to format sequence ~~~w: ~p'-[Fmt, Arg] ].
  607swi_message(format(Msg)) -->
  608    [ 'Format error: ~w'-[Msg] ].
  609swi_message(conditional_compilation_error(unterminated, File:Line)) -->
  610    [ 'Unterminated conditional compilation from '-[], url(File:Line) ].
  611swi_message(conditional_compilation_error(no_if, What)) -->
  612    [ ':- ~w without :- if'-[What] ].
  613swi_message(duplicate_key(Key)) -->
  614    [ 'Duplicate key: ~p'-[Key] ].
  615swi_message(determinism_error(PI, det, Found, property)) -->
  616    (   { predicate_head(PI, Head),
  617          predicate_property(Head, det)
  618        }
  619    ->  [ 'Deterministic procedure ' ], predicate_reference(PI)
  620    ;   [ 'Procedure ' ], predicate_reference(PI),
  621        [ ' called from a deterministic procedure' ]
  622    ),
  623    det_error(Found).
  624swi_message(determinism_error(PI, det, fail, guard)) -->
  625    [ 'Procedure ' ], predicate_reference(PI),
  626    [ ' failed after $-guard' ].
  627swi_message(determinism_error(PI, det, fail, guard_in_caller)) -->
  628    [ 'Procedure ' ], predicate_reference(PI),
  629    [ ' failed after $-guard in caller' ].
  630swi_message(determinism_error(Goal, det, fail, goal)) -->
  631    [ 'Goal ~p failed'-[Goal] ].
  632swi_message(determinism_error(Goal, det, nondet, goal)) -->
  633    [ 'Goal ~p succeeded with a choice point'-[Goal] ].
  634swi_message(qlf_format_error(File, Message)) -->
  635    [ '~w: Invalid QLF file: ~w'-[File, Message] ].
  636swi_message(goal_expansion_error(bound, Term)) -->
  637    [ 'Goal expansion bound a variable to ~p'-[Term] ].
  638
  639det_error(nondet) -->
  640    [ ' succeeded with a choicepoint'- [] ].
  641det_error(fail) -->
  642    [ ' failed'- [] ].
 swi_location(+Term)// is det
Print location information for error(Formal, ImplDefined) from the ImplDefined term.
  650:- public swi_location//1.  651swi_location(X) -->
  652    { var(X) },
  653    !.
  654swi_location(Context) -->
  655    { message_lang(Lang) },
  656    prolog:message_location(Lang, Context),
  657    !.
  658swi_location(Context) -->
  659    prolog:message_location(Context),
  660    !.
  661swi_location(context(Caller, _Msg)) -->
  662    { ground(Caller) },
  663    !,
  664    caller(Caller).
  665swi_location(file(Path, Line, -1, _CharNo)) -->
  666    !,
  667    [ url(Path:Line), ': ' ].
  668swi_location(file(Path, Line, LinePos, _CharNo)) -->
  669    { Column is LinePos+1 },                    % line_position is 0-based
  670    [ url(Path:Line:Column), ': ' ].
  671swi_location(stream(Stream, Line, LinePos, CharNo)) -->
  672    (   { is_stream(Stream),
  673          stream_property(Stream, file_name(File))
  674        }
  675    ->  swi_location(file(File, Line, LinePos, CharNo))
  676    ;   { Column is LinePos+1 },
  677        [ 'Stream ~w:~d:~d '-[Stream, Line, Column] ]
  678    ).
  679swi_location(autoload(File:Line)) -->
  680    [ url(File:Line), ': ' ].
  681swi_location(_) -->
  682    [].
  683
  684caller(system:'$record_clause'/3) -->
  685    !,
  686    [].
  687caller(Caller) -->
  688    { predicate_indicator(Caller, _) },
  689    !,
  690    predicate_reference(Caller, [link(false)]),
  691    [ ': ' ].
  692caller(Caller) -->
  693    [ '~p: '-[Caller] ].
 swi_extra(+Term)// is det
Extract information from the second argument of an error(Formal, ImplDefined) that is printed after the core of the message.
See also
- swi_location//1 uses the same term to insert context before the core of the message.
  704swi_extra(X) -->
  705    { var(X) },
  706    !,
  707    [].
  708swi_extra(Context) -->
  709    { message_lang(Lang) },
  710    prolog:message_context(Lang, Context),
  711    !.
  712swi_extra(Context) -->
  713    prolog:message_context(Context).
  714swi_extra(context(_, Msg)) -->
  715    { nonvar(Msg),
  716      Msg \== ''
  717    },
  718    !,
  719    swi_comment(Msg).
  720swi_extra(string(String, CharPos)) -->
  721    { sub_string(String, 0, CharPos, _, Before),
  722      sub_string(String, CharPos, _, 0, After)
  723    },
  724    [ nl, '~w'-[Before], nl, '** here **', nl, '~w'-[After] ].
  725swi_extra(_) -->
  726    [].
  727
  728swi_comment(already_from(Module)) -->
  729    !,
  730    [ ' (already imported from ~q)'-[Module] ].
  731swi_comment(directory(_Dir)) -->
  732    !,
  733    [ ' (is a directory)' ].
  734swi_comment(not_a_directory(_Dir)) -->
  735    !,
  736    [ ' (is not a directory)' ].
  737swi_comment(Msg) -->
  738    [ ' (~w)'-[Msg] ].
  739
  740
  741thread_context -->
  742    { \+ current_prolog_flag(toplevel_thread, true),
  743      thread_self(Id)
  744    },
  745    !,
  746    ['[Thread ~w] '-[Id]].
  747thread_context -->
  748    [].
  749
  750		 /*******************************
  751		 *        UNWIND MESSAGES	*
  752		 *******************************/
  753
  754unwind_message(Var) -->
  755    { var(Var) }, !,
  756    [ 'Unknown unwind message: ~p'-[Var] ].
  757unwind_message(abort) -->
  758    [ 'Execution Aborted' ].
  759unwind_message(halt(_)) -->
  760    [].
  761unwind_message(thread_exit(Term)) -->
  762    [ 'Invalid thread_exit/1.  Payload: ~p'-[Term] ].
  763unwind_message(Term) -->
  764    [ 'Unknown "unwind" exception: ~p'-[Term] ].
  765
  766
  767                 /*******************************
  768                 *        NORMAL MESSAGES       *
  769                 *******************************/
  770
  771:- dynamic prolog:version_msg/1.  772:- multifile prolog:version_msg/1.  773
  774prolog_message(welcome) -->
  775    [ 'Welcome to SWI-Prolog (' ],
  776    prolog_message(threads),
  777    prolog_message(address_bits),
  778    ['version ' ],
  779    prolog_message(version),
  780    [ ')', nl ],
  781    prolog_message(copyright),
  782    [ nl ],
  783    translate_message(user_versions),
  784    [ nl ],
  785    prolog_message(documentaton),
  786    [ nl, nl ].
  787prolog_message(user_versions) -->
  788    (   { findall(Msg, prolog:version_msg(Msg), Msgs),
  789          Msgs \== []
  790        }
  791    ->  [nl],
  792        user_version_messages(Msgs)
  793    ;   []
  794    ).
  795prolog_message(deprecated(Term)) -->
  796    { nonvar(Term) },
  797    (   { message_lang(Lang) },
  798        prolog:deprecated(Lang, Term)
  799    ->  []
  800    ;   prolog:deprecated(Term)
  801    ->  []
  802    ;   deprecated(Term)
  803    ).
  804prolog_message(unhandled_exception(E)) -->
  805    { nonvar(E) },
  806    [ 'Unhandled exception: ' ],
  807    (   translate_exception(E)
  808    ->  []
  809    ;   [ '~p'-[E] ]
  810    ).
 prolog_message(+Term)//
  814prolog_message(initialization_error(_, E, File:Line)) -->
  815    !,
  816    [ url(File:Line),
  817      ': Initialization goal raised exception:', nl
  818    ],
  819    translate_exception(E).
  820prolog_message(initialization_error(Goal, E, _)) -->
  821    [ 'Initialization goal ~p raised exception:'-[Goal], nl ],
  822    translate_exception(E).
  823prolog_message(initialization_failure(_Goal, File:Line)) -->
  824    !,
  825    [ url(File:Line),
  826      ': Initialization goal failed'-[]
  827    ].
  828prolog_message(initialization_failure(Goal, _)) -->
  829    [ 'Initialization goal failed: ~p'-[Goal]
  830    ].
  831prolog_message(initialization_exception(E)) -->
  832    [ 'Prolog initialisation failed:', nl ],
  833    translate_exception(E).
  834prolog_message(initialization(halt(Status), Goal, File:Line)) -->
  835    [ url(File:Line), ': '], goal(Goal), [nl,
  836      '  Initialization goal called ', ansi(code, '~p', [halt(Status)]),
  837      '.', nl,
  838      '  The program entry point should be called using ',
  839      ansi(code, 'initialization/2', []), '.', nl,
  840      '  Consider using ', ansi(code, 'library(main)', []), '.'
  841    ].
  842prolog_message(init_goal_syntax(Error, Text)) -->
  843    !,
  844    [ '-g ~w: '-[Text] ],
  845    translate_exception(Error).
  846prolog_message(init_goal_failed(failed, @(Goal,File:Line))) -->
  847    !,
  848    [ url(File:Line), ': ~p: false'-[Goal] ].
  849prolog_message(init_goal_failed(Error, @(Goal,File:Line))) -->
  850    !,
  851    [ url(File:Line), ': ~p '-[Goal] ],
  852    translate_exception(Error).
  853prolog_message(init_goal_failed(failed, Text)) -->
  854    !,
  855    [ '-g ~w: false'-[Text] ].
  856prolog_message(init_goal_failed(Error, Text)) -->
  857    !,
  858    [ '-g ~w: '-[Text] ],
  859    translate_exception(Error).
  860prolog_message(goal_failed(Context, Goal)) -->
  861    [ 'Goal (~w) failed: ~p'-[Context, Goal] ].
  862prolog_message(no_current_module(Module)) -->
  863    [ '~w is not a current module (created)'-[Module] ].
  864prolog_message(commandline_arg_type(Flag, Arg)) -->
  865    [ 'Bad argument to commandline option -~w: ~w'-[Flag, Arg] ].
  866prolog_message(missing_feature(Name)) -->
  867    [ 'This version of SWI-Prolog does not support ~w'-[Name] ].
  868prolog_message(singletons(_Term, List)) -->
  869    [ 'Singleton variables: ~w'-[List] ].
  870prolog_message(multitons(_Term, List)) -->
  871    [ 'Singleton-marked variables appearing more than once: ~w'-[List] ].
  872prolog_message(profile_no_cpu_time) -->
  873    [ 'No CPU-time info.  Check the SWI-Prolog manual for details' ].
  874prolog_message(non_ascii(Text, Type)) -->
  875    [ 'Unquoted ~w with non-portable characters: ~w'-[Type, Text] ].
  876prolog_message(io_warning(Stream, Message)) -->
  877    { stream_property(Stream, position(Position)),
  878      !,
  879      stream_position_data(line_count, Position, LineNo),
  880      stream_position_data(line_position, Position, LinePos),
  881      Column is LinePos+1                       % line_position is 0-based
  882    },
  883    (   { stream_property(Stream, file_name(File)) }
  884    ->  [ url(File:LineNo:Column) ]
  885    ;   [ '~p:~d:~d'-[Stream, LineNo, Column] ]
  886    ),
  887    [ ': ~w'-[Message] ].
  888prolog_message(io_warning(Stream, Message)) -->
  889    [ 'stream ~p: ~w'-[Stream, Message] ].
  890prolog_message(option_usage(pldoc)) -->
  891    [ 'Usage: --pldoc[=port]' ].
  892prolog_message(interrupt(begin)) -->
  893    [ 'Action (h for help) ? ', flush ].
  894prolog_message(interrupt(end)) -->
  895    [ 'continue' ].
  896prolog_message(interrupt(trace)) -->
  897    [ 'continue (trace mode)' ].
  898prolog_message(unknown_in_module_user) -->
  899    [ 'Using a non-error value for unknown in the global module', nl,
  900      'causes most of the development environment to stop working.', nl,
  901      'Please use :- dynamic or limit usage of unknown to a module.', nl,
  902      'See https://www.swi-prolog.org/howto/database.html'
  903    ].
  904prolog_message(untable(PI)) -->
  905    [ 'Reconsult: removed tabling for ' ], predicate_reference(PI).
  906prolog_message(unknown_option(Set, Opt)) -->
  907    [ 'Unknown ~w option: ~p'-[Set, Opt] ].
  908
  909
  910                 /*******************************
  911                 *         LOADING FILES        *
  912                 *******************************/
  913
  914prolog_message(modify_active_procedure(Who, What)) -->
  915    predicate_reference(Who),
  916    [ ': modified active procedure ' ],
  917    predicate_reference(What).
  918prolog_message(load_file(failed(user:File))) -->
  919    [ 'Failed to load ~p'-[File] ].
  920prolog_message(load_file(failed(Module:File))) -->
  921    [ 'Failed to load ~p into module ~p'-[File, Module] ].
  922prolog_message(load_file(failed(File))) -->
  923    [ 'Failed to load ~p'-[File] ].
  924prolog_message(mixed_directive(Goal)) -->
  925    [ 'Cannot pre-compile mixed load/call directive: ~p'-[Goal] ].
  926prolog_message(cannot_redefine_comma) -->
  927    [ 'Full stop in clause-body?  Cannot redefine ,/2' ].
  928prolog_message(illegal_autoload_index(Dir, Term)) -->
  929    [ 'Illegal term in INDEX file of directory ~w: ~w'-[Dir, Term] ].
  930prolog_message(redefined_procedure(Type, Proc)) -->
  931    [ 'Redefined ~w procedure '-[Type] ],
  932    predicate_reference(Proc),
  933    predicate_definition(Proc, 'Previously defined').
  934prolog_message(declare_module(Module, abolish(Predicates))) -->
  935    [ 'Loading module ~w abolished:'-[Module], nl ],
  936    predicate_list(Predicates).
  937prolog_message(import_private(Module, Private)) -->
  938    [ 'import/1: ' ], predicate_reference(Private),
  939    [ ' is not exported (still imported into ~q)'-[Module] ].
  940prolog_message(ignored_weak_import(Into, From:PI)) -->
  941    [ 'Local definition of ' ],
  942    predicate_reference(Into:PI, [module(show)]),
  943    [ ' overrides weak import from ~q'-[From] ].
  944prolog_message(undefined_export(Module, PI)) -->
  945    [ 'Exported procedure ' ],
  946    predicate_reference(Module:PI, [module(show)]),
  947    [ ' is not defined' ].
  948prolog_message(no_exported_op(Module, Op)) -->
  949    [ 'Operator ~q:~q is not exported (still defined)'-[Module, Op] ].
  950prolog_message(discontiguous((-)/2,_)) -->
  951    prolog_message(minus_in_identifier).
  952prolog_message(discontiguous(Proc,Current)) -->
  953    [ 'Clauses of ' ], predicate_reference(Proc),
  954    [ ' are not together in the source-file' ],
  955    predicate_definition(Proc, 'Earlier definition'),
  956    [ nl, 'Current predicate: ' ], predicate_reference(Current),
  957    [ nl, 'Use ', ansi(code, ':- discontiguous ~p.', [Proc]),
  958      ' to suppress this message'
  959    ].
  960prolog_message(decl_no_effect(Goal)) -->
  961    [ 'Deprecated declaration has no effect: ~p'-[Goal] ].
  962prolog_message(load_file(start(Level, File))) -->
  963    [ '~|~t~*+Loading '-[Level] ],
  964    load_file(File),
  965    [ ' ...' ].
  966prolog_message(include_file(start(Level, File))) -->
  967    [ '~|~t~*+include '-[Level] ],
  968    load_file(File),
  969    [ ' ...' ].
  970prolog_message(include_file(done(Level, File))) -->
  971    [ '~|~t~*+included '-[Level] ],
  972    load_file(File).
  973prolog_message(load_file(done(Level, File, Action, Module, Time, Clauses))) -->
  974    [ '~|~t~*+'-[Level] ],
  975    load_file(File),
  976    [ ' ~w'-[Action] ],
  977    load_module(Module),
  978    [ ' ~2f sec, ~D clauses'-[Time, Clauses] ].
  979prolog_message(dwim_undefined(Goal, Alternatives)) -->
  980    [ 'Unknown procedure: ' ],
  981    predicate_reference(Goal),
  982    [ nl, '    However, there are definitions for:', nl ],
  983    dwim_alternatives(Alternatives).
  984prolog_message(dwim_correct(Into)) -->
  985    [ ansi(warning, 'Correct to: ', []), ansi(code, '~q', [Into]),
  986      ansi(warning, '? ', []), flush
  987    ].
  988prolog_message(error(loop_error(Spec), file_search(Used))) -->
  989    [ 'File search: too many levels of indirections on: ~p'-[Spec], nl,
  990      '    Used alias expansions:', nl
  991    ],
  992    used_search(Used).
  993prolog_message(minus_in_identifier) -->
  994    [ 'The "-" character should not be used to separate words in an', nl,
  995      'identifier.  Check the SWI-Prolog FAQ for details.'
  996    ].
  997prolog_message(qlf(removed_after_error(File))) -->
  998    [ 'Removed incomplete QLF file ~w'-[File] ].
  999prolog_message(qlf(recompile(Spec,_Pl,_Qlf,Reason))) -->
 1000    [ '~p: recompiling QLF file'-[Spec] ],
 1001    qlf_recompile_reason(Reason).
 1002prolog_message(qlf(can_not_recompile(Spec,QlfFile,_Reason))) -->
 1003    [ '~p: can not recompile "~w" (access denied)'-[Spec, QlfFile], nl,
 1004      '\tLoading from source'-[]
 1005    ].
 1006prolog_message(qlf(system_lib_out_of_date(Spec,QlfFile))) -->
 1007    [ '~p: can not recompile "~w" (access denied)'-[Spec, QlfFile], nl,
 1008      '\tLoading QlfFile'-[]
 1009    ].
 1010prolog_message(redefine_module(Module, OldFile, File)) -->
 1011    [ 'Module "~q" already loaded from ~w.'-[Module, OldFile], nl,
 1012      'Wipe and reload from ~w? '-[File], flush
 1013    ].
 1014prolog_message(redefine_module_reply) -->
 1015    [ 'Please answer y(es), n(o) or a(bort)' ].
 1016prolog_message(reloaded_in_module(Absolute, OldContext, LM)) -->
 1017    [ '~w was previously loaded in module ~w'-[Absolute, OldContext], nl,
 1018      '\tnow it is reloaded into module ~w'-[LM] ].
 1019prolog_message(expected_layout(Expected, Pos)) -->
 1020    [ 'Layout data: expected ~w, found: ~p'-[Expected, Pos] ].
 1021
 1022used_search([]) -->
 1023    [].
 1024used_search([Alias=Expanded|T]) -->
 1025    [ '        file_search_path(~p, ~p)'-[Alias, Expanded], nl ],
 1026    used_search(T).
 1027
 1028load_file(file(Spec, _Path)) -->
 1029    (   {atomic(Spec)}
 1030    ->  [ '~w'-[Spec] ]
 1031    ;   [ '~p'-[Spec] ]
 1032    ).
 1033%load_file(file(_, Path)) -->
 1034%       [ '~w'-[Path] ].
 1035
 1036load_module(user) --> !.
 1037load_module(system) --> !.
 1038load_module(Module) -->
 1039    [ ' into ~w'-[Module] ].
 user_predicate_indicator(+QPI, -PI) is det
Remove the module qualification from QPI if it does not add information for the user. This is the single module hiding policy of this file. See also predicate_reference//2.
 1047user_predicate_indicator(Module:PI, PI) :-
 1048    hidden_module(Module),
 1049    !.
 1050user_predicate_indicator(PI, PI).
 1051
 1052hidden_module(user) :- !.
 1053hidden_module(system) :- !.
 1054hidden_module(M) :-
 1055    sub_atom(M, 0, _, _, $).
 1056
 1057qlf_recompile_reason(old) -->
 1058    !,
 1059    [ ' (out of date)'-[] ].
 1060qlf_recompile_reason(_) -->
 1061    [ ' (incompatible with current Prolog version)'-[] ].
 1062
 1063prolog_message(file_search(cache(Spec, _Cond), Path)) -->
 1064    [ 'File search: ~p --> ~p (cache)'-[Spec, Path] ].
 1065prolog_message(file_search(found(Spec, Cond), Path)) -->
 1066    [ 'File search: ~p --> ~p OK ~p'-[Spec, Path, Cond] ].
 1067prolog_message(file_search(tried(Spec, Cond), Path)) -->
 1068    [ 'File search: ~p --> ~p NO ~p'-[Spec, Path, Cond] ].
 1069
 1070                 /*******************************
 1071                 *              GC              *
 1072                 *******************************/
 1073
 1074prolog_message(gc(done(GGained, TGained, Time, GUsed, TUsed, GFree, TFree))) -->
 1075    thread_context,
 1076    [ 'GC: gained (g+t) ~D+~D in ~3f sec; used ~D+~D; free ~D+~D'-
 1077      [GGained, TGained, Time, GUsed, TUsed, GFree, TFree]
 1078    ].
 1079prolog_message(gc(minor(GGained, TGained, Time, GUsed, TUsed, GFree, TFree))) -->
 1080    thread_context,
 1081    [ 'GC (minor): gained (g+t) ~D+~D in ~3f sec; used ~D+~D; free ~D+~D'-
 1082      [GGained, TGained, Time, GUsed, TUsed, GFree, TFree]
 1083    ].
 1084prolog_message(gc(dropped(Count))) -->
 1085    thread_context,
 1086    [ 'GC: ~D more GC and stack shift reports were dropped'-[Count] ].
 1087prolog_message(shift(done(Local, Global, Trail, Time))) -->
 1088    thread_context,
 1089    [ 'SHIFT: l+g+t = ~D+~D+~D (~3f sec)'-[Local, Global, Trail, Time] ].
 1090prolog_message(agc(start)) -->
 1091    thread_context,
 1092    [ 'AGC: ', flush ].
 1093prolog_message(agc(done(Collected, Remaining, Time))) -->
 1094    [ at_same_line,
 1095      'reclaimed ~D atoms in ~3f sec. (remaining: ~D)'-
 1096      [Collected, Time, Remaining]
 1097    ].
 1098prolog_message(cgc(start)) -->
 1099    thread_context,
 1100    [ 'CGC: ', flush ].
 1101prolog_message(cgc(done(CollectedClauses, _CollectedBytes,
 1102                        RemainingBytes, Time))) -->
 1103    [ at_same_line,
 1104      'reclaimed ~D clauses in ~3f sec. (pending: ~D bytes)'-
 1105      [CollectedClauses, Time, RemainingBytes]
 1106    ].
 1107
 1108		 /*******************************
 1109		 *        STACK OVERFLOW	*
 1110		 *******************************/
 1111
 1112out_of_stack(Context) -->
 1113    { human_stack_size(Context.localused,   Local),
 1114      human_stack_size(Context.globalused,  Global),
 1115      human_stack_size(Context.trailused,   Trail),
 1116      human_stack_size(Context.stack_limit, Limit),
 1117      LCO is (100*(Context.depth - Context.environments))/Context.depth
 1118    },
 1119    [ 'Stack limit (~s) exceeded'-[Limit], nl,
 1120      '  Stack sizes: local: ~s, global: ~s, trail: ~s'-[Local,Global,Trail], nl,
 1121      '  Stack depth: ~D, last-call: ~0f%, Choice points: ~D'-
 1122         [Context.depth, LCO, Context.choicepoints], nl
 1123    ],
 1124    overflow_reason(Context, Resolve),
 1125    resolve_overflow(Resolve).
 1126
 1127human_stack_size(Size, String) :-
 1128    Size < 100,
 1129    format(string(String), '~dKb', [Size]).
 1130human_stack_size(Size, String) :-
 1131    Size < 100 000,
 1132    Value is Size / 1024,
 1133    format(string(String), '~1fMb', [Value]).
 1134human_stack_size(Size, String) :-
 1135    Value is Size / (1024*1024),
 1136    format(string(String), '~1fGb', [Value]).
 1137
 1138overflow_reason(Context, fix) -->
 1139    show_non_termination(Context),
 1140    !.
 1141overflow_reason(Context, enlarge) -->
 1142    { Stack = Context.get(stack) },
 1143    !,
 1144    [ '  In:'-[], nl ],
 1145    stack(Stack).
 1146overflow_reason(_Context, enlarge) -->
 1147    [ '  Insufficient global stack'-[] ].
 1148
 1149show_non_termination(Context) -->
 1150    (   { Stack = Context.get(cycle) }
 1151    ->  [ '  Probable infinite recursion (cycle):'-[], nl ]
 1152    ;   { Stack = Context.get(non_terminating) }
 1153    ->  [ '  Possible non-terminating recursion:'-[], nl ]
 1154    ),
 1155    stack(Stack).
 1156
 1157stack([]) --> [].
 1158stack([frame(Depth, M:Goal, _)|T]) -->
 1159    [ '    [~D] ~q:'-[Depth, M] ],
 1160    stack_goal(Goal),
 1161    [ nl ],
 1162    stack(T).
 1163
 1164stack_goal(Goal) -->
 1165    { compound(Goal),
 1166      !,
 1167      compound_name_arity(Goal, Name, Arity)
 1168    },
 1169    [ '~q('-[Name] ],
 1170    stack_goal_args(1, Arity, Goal),
 1171    [ ')'-[] ].
 1172stack_goal(Goal) -->
 1173    [ '~q'-[Goal] ].
 1174
 1175stack_goal_args(I, Arity, Goal) -->
 1176    { I =< Arity,
 1177      !,
 1178      arg(I, Goal, A),
 1179      I2 is I + 1
 1180    },
 1181    stack_goal_arg(A),
 1182    (   { I2 =< Arity }
 1183    ->  [ ', '-[] ],
 1184        stack_goal_args(I2, Arity, Goal)
 1185    ;   []
 1186    ).
 1187stack_goal_args(_, _, _) -->
 1188    [].
 1189
 1190stack_goal_arg(A) -->
 1191    { nonvar(A),
 1192      A = [Len|T],
 1193      !
 1194    },
 1195    (   {Len == cyclic_term}
 1196    ->  [ '[cyclic list]'-[] ]
 1197    ;   {T == []}
 1198    ->  [ '[length:~D]'-[Len] ]
 1199    ;   [ '[length:~D|~p]'-[Len, T] ]
 1200    ).
 1201stack_goal_arg(A) -->
 1202    { nonvar(A),
 1203      A = _/_,
 1204      !
 1205    },
 1206    [ '<compound ~p>'-[A] ].
 1207stack_goal_arg(A) -->
 1208    [ '~p'-[A] ].
 1209
 1210resolve_overflow(fix) -->
 1211    [].
 1212resolve_overflow(enlarge) -->
 1213    { current_prolog_flag(stack_limit, LimitBytes),
 1214      NewLimit is LimitBytes * 2
 1215    },
 1216    [ nl,
 1217      'Use the --stack_limit=size[KMG] command line option or'-[], nl,
 1218      '?- set_prolog_flag(stack_limit, ~I). to double the limit.'-[NewLimit]
 1219    ].
 out_of_c_stack
The thread's C-stack limit was exceeded. Give some advice on how to resolve this.
 1226out_of_c_stack -->
 1227    { statistics(c_stack, Limit), Limit > 0 },
 1228    !,
 1229    [ 'C-stack limit (~D bytes) exceeded.'-[Limit], nl ],
 1230    resolve_c_stack_overflow(Limit).
 1231out_of_c_stack -->
 1232    { statistics(c_stack, Limit), Limit > 0 },
 1233    [ 'C-stack limit exceeded.'-[Limit], nl ],
 1234    resolve_c_stack_overflow(Limit).
 1235
 1236resolve_c_stack_overflow(_Limit) -->
 1237    { thread_self(main) },
 1238    [ 'Use the shell command ' ], code('~w', 'ulimit -s size'),
 1239    [ ' to enlarge the limit.' ].
 1240resolve_c_stack_overflow(_Limit) -->
 1241    [ 'Use the ' ], code('~w', 'c_stack(KBytes)'),
 1242    [ ' option of '], code(thread_create/3), [' to enlarge the limit.' ].
 1243
 1244
 1245                 /*******************************
 1246                 *        MAKE/AUTOLOAD         *
 1247                 *******************************/
 1248
 1249prolog_message(make(reload(Files))) -->
 1250    { length(Files, N)
 1251    },
 1252    [ 'Make: reloading ~D files'-[N] ].
 1253prolog_message(make(done(_Files))) -->
 1254    [ 'Make: finished' ].
 1255prolog_message(make(library_index(Dir))) -->
 1256    [ 'Updating index for library ~w'-[Dir] ].
 1257prolog_message(autoload(Pred, File)) -->
 1258    thread_context,
 1259    [ 'autoloading ' ], predicate_reference(Pred, [link(false)]),
 1260    [ ' from ~w'-[File] ].
 1261prolog_message(autoload(read_index(Dir))) -->
 1262    [ 'Loading autoload index for ~w'-[Dir] ].
 1263prolog_message(autoload(disabled(Loaded))) -->
 1264    [ 'Disabled autoloading (loaded ~D files)'-[Loaded] ].
 1265prolog_message(autoload(already_defined(PI, From))) -->
 1266    predicate_reference(PI),
 1267    (   { predicate_head(PI, Head),
 1268          predicate_property(Head, built_in)
 1269        }
 1270    ->  [' is a built-in predicate']
 1271    ;   [ ' is already imported from module ' ],
 1272        code(From)
 1273    ).
 1274
 1275swi_message(autoload(Msg)) -->
 1276    [ nl, '  ' ],
 1277    autoload_message(Msg).
 1278
 1279autoload_message(not_exported(PI, Spec, _FullFile, _Exports)) -->
 1280    [ ansi(code, '~w', [Spec]),
 1281      ' does not export '
 1282    ],
 1283    predicate_reference(PI, [link(false)]).
 1284autoload_message(no_file(Spec)) -->
 1285    [ ansi(code, '~p', [Spec]), ': No such file' ].
 1286
 1287
 1288                 /*******************************
 1289                 *       COMPILER WARNINGS      *
 1290                 *******************************/
 1291
 1292% print warnings about dubious code raised by the compiler.
 1293% TBD: pass in PC to produce exact error locations.
 1294
 1295prolog_message(compiler_warnings(Clause, Warnings0)) -->
 1296    {   print_goal_options(DefOptions),
 1297        (   prolog_load_context(variable_names, VarNames)
 1298        ->  warnings_with_named_vars(Warnings0, VarNames, Warnings),
 1299            Options = [variable_names(VarNames)|DefOptions]
 1300        ;   Options = DefOptions,
 1301            Warnings = Warnings0
 1302        )
 1303    },
 1304    compiler_warnings(Warnings, Clause, Options).
 1305
 1306warnings_with_named_vars([], _, []).
 1307warnings_with_named_vars([H|T0], VarNames, [H|T]) :-
 1308    term_variables(H, Vars),
 1309    '$member'(V1, Vars),
 1310    '$member'(_=V2, VarNames),
 1311    V1 == V2,
 1312    !,
 1313    warnings_with_named_vars(T0, VarNames, T).
 1314warnings_with_named_vars([_|T0], VarNames, T) :-
 1315    warnings_with_named_vars(T0, VarNames, T).
 1316
 1317
 1318compiler_warnings([], _, _) --> [].
 1319compiler_warnings([H|T], Clause, Options) -->
 1320    (   compiler_warning(H, Clause, Options)
 1321    ->  []
 1322    ;   [ 'Unknown compiler warning: ~W'-[H,Options] ]
 1323    ),
 1324    (   {T==[]}
 1325    ->  []
 1326    ;   [nl]
 1327    ),
 1328    compiler_warnings(T, Clause, Options).
 1329
 1330compiler_warning(eq_vv(A,B), _Clause, Options) -->
 1331    (   { A == B }
 1332    ->  [ 'Test is always true: ~W'-[A==B, Options] ]
 1333    ;   [ 'Test is always false: ~W'-[A==B, Options] ]
 1334    ).
 1335compiler_warning(eq_singleton(A,B), _Clause, Options) -->
 1336    [ 'Test is always false: ~W'-[A==B, Options] ].
 1337compiler_warning(neq_vv(A,B), _Clause, Options) -->
 1338    (   { A \== B }
 1339    ->  [ 'Test is always true: ~W'-[A\==B, Options] ]
 1340    ;   [ 'Test is always false: ~W'-[A\==B, Options] ]
 1341    ).
 1342compiler_warning(neq_singleton(A,B), _Clause, Options) -->
 1343    [ 'Test is always true: ~W'-[A\==B, Options] ].
 1344compiler_warning(unify_singleton(A,B), _Clause, Options) -->
 1345    [ 'Unified variable is not used: ~W'-[A=B, Options] ].
 1346compiler_warning(always(Bool, Pred, Arg), _Clause, Options) -->
 1347    { Goal =.. [Pred,Arg] },
 1348    [ 'Test is always ~w: ~W'-[Bool, Goal, Options] ].
 1349compiler_warning(unbalanced_var(V), _Clause, Options) -->
 1350    [ 'Variable not introduced in all branches: ~W'-[V, Options] ].
 1351compiler_warning(branch_singleton(V), _Clause, Options) -->
 1352    [ 'Singleton variable in branch: ~W'-[V, Options] ].
 1353compiler_warning(negation_singleton(V), _Clause, Options) -->
 1354    [ 'Singleton variable in \\+: ~W'-[V, Options] ].
 1355compiler_warning(multiton(V), _Clause, Options) -->
 1356    [ 'Singleton-marked variable appears more than once: ~W'-[V, Options] ].
 1357
 1358print_goal_options(
 1359    [ quoted(true),
 1360      portray(true)
 1361    ]).
 1362
 1363
 1364                 /*******************************
 1365                 *      TOPLEVEL MESSAGES       *
 1366                 *******************************/
 1367
 1368prolog_message(version) -->
 1369    { current_prolog_flag(version_git, Version) },
 1370    !,
 1371    [ '~w'-[Version] ].
 1372prolog_message(version) -->
 1373    { current_prolog_flag(version_data, swi(Major,Minor,Patch,Options))
 1374    },
 1375    (   { '$option'(tag(Tag), Options) }
 1376    ->  [ '~w.~w.~w-~w'-[Major, Minor, Patch, Tag] ]
 1377    ;   [ '~w.~w.~w'-[Major, Minor, Patch] ]
 1378    ).
 1379prolog_message(address_bits) -->
 1380    { current_prolog_flag(address_bits, Bits)
 1381    },
 1382    !,
 1383    [ '~d bits, '-[Bits] ].
 1384prolog_message(threads) -->
 1385    { current_prolog_flag(threads, true)
 1386    },
 1387    !,
 1388    [ 'threaded, ' ].
 1389prolog_message(threads) -->
 1390    [].
 1391prolog_message(copyright) -->
 1392    [ 'SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software.', nl,
 1393      'Please run ', ansi(code, '?- license.', []), ' for legal details.'
 1394    ].
 1395prolog_message(documentaton) -->
 1396    [ 'For online help and background, visit ', url('https://www.swi-prolog.org') ],
 1397    (   { exists_source(library(help)) }
 1398    ->  [ nl,
 1399          'For built-in help, use ', ansi(code, '?- help(Topic).', []),
 1400          ' or ', ansi(code, '?- apropos(Word).', [])
 1401        ]
 1402    ;   []
 1403    ).
 1404prolog_message(about) -->
 1405    [ 'SWI-Prolog version (' ],
 1406    prolog_message(threads),
 1407    prolog_message(address_bits),
 1408    ['version ' ],
 1409    prolog_message(version),
 1410    [ ')', nl ],
 1411    prolog_message(copyright).
 1412prolog_message(halt) -->
 1413    [ 'halt' ].
 1414prolog_message(break(begin, Level)) -->
 1415    [ 'Break level ~d'-[Level] ].
 1416prolog_message(break(end, Level)) -->
 1417    [ 'Exit break level ~d'-[Level] ].
 1418prolog_message(var_query(_)) -->
 1419    [ '... 1,000,000 ............ 10,000,000 years later', nl, nl,
 1420      '~t~8|>> 42 << (last release gives the question)'
 1421    ].
 1422prolog_message(close_on_abort(Stream)) -->
 1423    [ 'Abort: closed stream ~p'-[Stream] ].
 1424prolog_message(cancel_halt(Reason)) -->
 1425    [ 'Halt cancelled: ~p'-[Reason] ].
 1426prolog_message(on_error(halt(Status))) -->
 1427    { statistics(errors, Errors),
 1428      statistics(warnings, Warnings)
 1429    },
 1430    [ 'Halting with status ~w due to ~D errors and ~D warnings'-
 1431      [Status, Errors, Warnings] ].
 1432
 1433prolog_message(query(QueryResult)) -->
 1434    query_result(QueryResult).
 1435
 1436query_result(no) -->            % failure
 1437    [ ansi(truth(false), 'false.', []) ],
 1438    extra_line.
 1439query_result(yes(true, [])) -->      % prompt_alternatives_on: groundness
 1440    !,
 1441    [ ansi(truth(true), 'true.', []) ],
 1442    extra_line.
 1443query_result(yes(Delays, Residuals)) -->
 1444    result([], Delays, Residuals),
 1445    extra_line.
 1446query_result(done) -->          % user typed <CR>
 1447    extra_line.
 1448query_result(yes(Bindings, Delays, Residuals)) -->
 1449    result(Bindings, Delays, Residuals),
 1450    prompt(yes, Bindings, Delays, Residuals).
 1451query_result(more(Bindings, Delays, Residuals)) -->
 1452    result(Bindings, Delays, Residuals),
 1453    prompt(more, Bindings, Delays, Residuals).
 1454:- if(current_prolog_flag(emscripten, true)). 1455query_result(help) -->
 1456    [ ansi(bold, '  Possible actions:', []), nl,
 1457      '  ; (n,r,space): redo              | t:       trace&redo'-[], nl,
 1458      '  *:             show choicepoint  | . (c,a): stop'-[], nl,
 1459      '  w:             write             | p:       print'-[], nl,
 1460      '  +:             max_depth*5       | -:       max_depth//5'-[], nl,
 1461      '  h (?):         help'-[],
 1462      nl, nl
 1463    ].
 1464:- else. 1465query_result(help) -->
 1466    [ ansi(bold, '  Possible actions:', []), nl,
 1467      '  ; (n,r,space,TAB): redo              | t:           trace&redo'-[], nl,
 1468      '  *:                 show choicepoint  | . (c,a,RET): stop'-[], nl,
 1469      '  w:                 write             | p:           print'-[], nl,
 1470      '  +:                 max_depth*5       | -:           max_depth//5'-[], nl,
 1471      '  b:                 break             | h (?):       help'-[],
 1472      nl, nl
 1473    ].
 1474:- endif. 1475query_result(action) -->
 1476    [ 'Action? '-[], flush ].
 1477query_result(confirm) -->
 1478    [ 'Please answer \'y\' or \'n\'? '-[], flush ].
 1479query_result(eof) -->
 1480    [ nl ].
 1481query_result(toplevel_open_line) -->
 1482    [].
 1483
 1484prompt(Answer, [], true, []-[]) -->
 1485    !,
 1486    prompt(Answer, empty).
 1487prompt(Answer, _, _, _) -->
 1488    !,
 1489    prompt(Answer, non_empty).
 1490
 1491prompt(yes, empty) -->
 1492    !,
 1493    [ ansi(truth(true), 'true.', []) ],
 1494    extra_line.
 1495prompt(yes, _) -->
 1496    !,
 1497    [ full_stop ],
 1498    extra_line.
 1499prompt(more, empty) -->
 1500    !,
 1501    [ ansi(truth(true), 'true ', []), flush ].
 1502prompt(more, _) -->
 1503    !,
 1504    [ ' '-[], flush ].
 1505
 1506result(Bindings, Delays, Residuals) -->
 1507    { current_prolog_flag(answer_write_options, Options0),
 1508      Options = [partial(true)|Options0],
 1509      GOptions = [priority(999)|Options0]
 1510    },
 1511    wfs_residual_program(Delays, GOptions),
 1512    bindings(Bindings, [priority(699)|Options]),
 1513    (   {Residuals == []-[]}
 1514    ->  bind_delays_sep(Bindings, Delays),
 1515        delays(Delays, GOptions)
 1516    ;   bind_res_sep(Bindings, Residuals),
 1517        residuals(Residuals, GOptions),
 1518        (   {Delays == true}
 1519        ->  []
 1520        ;   [','-[], nl],
 1521            delays(Delays, GOptions)
 1522        )
 1523    ).
 1524
 1525bindings([], _) -->
 1526    [].
 1527bindings([binding(Names,Skel,Subst)|T], Options) -->
 1528    { '$last'(Names, Name) },
 1529    var_names(Names), value(Name, Skel, Subst, Options),
 1530    (   { T \== [] }
 1531    ->  [ ','-[], nl ],
 1532        bindings(T, Options)
 1533    ;   []
 1534    ).
 1535
 1536var_names([Name]) -->
 1537    !,
 1538    [ ansi(binding(name), '~w', [Name]), ' = '-[] ].
 1539var_names([Name1,Name2|T]) -->
 1540    !,
 1541    [ ansi(binding(name), '~w', [Name1]), ' = '-[],
 1542      ansi(binding(name), '~w', [Name2]), ', '-[]
 1543    ],
 1544    var_names([Name2|T]).
 1545
 1546
 1547value(Name, Skel, Subst, Options) -->
 1548    (   { var(Skel), Subst = [Skel=S] }
 1549    ->  { Skel = '$VAR'(Name) },
 1550        [ '~W'-[S, Options] ]
 1551    ;   [ '~W'-[Skel, Options] ],
 1552        substitution(Subst, Options)
 1553    ).
 1554
 1555substitution([], _) --> !.
 1556substitution([N=V|T], Options) -->
 1557    [ ', ', ansi(comment, '% where', []), nl,
 1558      '    ~w = ~W'-[N,V,Options] ],
 1559    substitutions(T, Options).
 1560
 1561substitutions([], _) --> [].
 1562substitutions([N=V|T], Options) -->
 1563    [ ','-[], nl, '    ~w = ~W'-[N,V,Options] ],
 1564    substitutions(T, Options).
 1565
 1566
 1567residuals(Normal-Hidden, Options) -->
 1568    residuals1(Normal, Options),
 1569    bind_res_sep(Normal, Hidden),
 1570    (   {Hidden == []}
 1571    ->  []
 1572    ;   [ansi(comment, '% with pending residual goals', []), nl]
 1573    ),
 1574    residuals1(Hidden, Options).
 1575
 1576residuals1([], _) -->
 1577    [].
 1578residuals1([G|Gs], Options) -->
 1579    (   { Gs \== [] }
 1580    ->  [ '~W,'-[G, Options], nl ],
 1581        residuals1(Gs, Options)
 1582    ;   [ '~W'-[G, Options] ]
 1583    ).
 1584
 1585wfs_residual_program(true, _Options) -->
 1586    !.
 1587wfs_residual_program(Goal, _Options) -->
 1588    { current_prolog_flag(toplevel_list_wfs_residual_program, true),
 1589      '$current_typein_module'(TypeIn),
 1590      (   current_predicate(delays_residual_program/2)
 1591      ->  true
 1592      ;   use_module(library(wfs), [delays_residual_program/2])
 1593      ),
 1594      delays_residual_program(TypeIn:Goal, TypeIn:Program),
 1595      Program \== []
 1596    },
 1597    !,
 1598    [ ansi(comment, '% WFS residual program', []), nl ],
 1599    [ ansi(wfs(residual_program), '~@', ['$messages':list_clauses(Program)]) ].
 1600wfs_residual_program(_, _) --> [].
 1601
 1602delays(true, _Options) -->
 1603    !.
 1604delays(Goal, Options) -->
 1605    { current_prolog_flag(toplevel_list_wfs_residual_program, true)
 1606    },
 1607    !,
 1608    [ ansi(truth(undefined), '~W', [Goal, Options]) ].
 1609delays(_, _Options) -->
 1610    [ ansi(truth(undefined), undefined, []) ].
 1611
 1612:- public list_clauses/1. 1613
 1614list_clauses([]).
 1615list_clauses([H|T]) :-
 1616    (   system_undefined(H)
 1617    ->  true
 1618    ;   portray_clause(user_output, H, [indent(4)])
 1619    ),
 1620    list_clauses(T).
 1621
 1622system_undefined((undefined :- tnot(undefined))).
 1623system_undefined((answer_count_restraint :- tnot(answer_count_restraint))).
 1624system_undefined((radial_restraint :- tnot(radial_restraint))).
 1625
 1626bind_res_sep(_, []) --> !.
 1627bind_res_sep(_, []-[]) --> !.
 1628bind_res_sep([], _) --> !.
 1629bind_res_sep(_, _) --> [','-[], nl].
 1630
 1631bind_delays_sep([], _) --> !.
 1632bind_delays_sep(_, true) --> !.
 1633bind_delays_sep(_, _) --> [','-[], nl].
 extra_line// is det
End the answer and, if toplevel_extra_white_line is true, add an empty line. The ~N cannot be replaced by nl because the answer is not always left at a non-empty line. The eol element paints the remainder of the line if the message has a background colour, which ~N cannot do as it is written using format/3.

Note that eol ends the last line of the answer. The empty line that separates the answer from the next query is not part of the answer and keeps the default background.

 1647extra_line -->
 1648    { current_prolog_flag(toplevel_extra_white_line, true) },
 1649    !,
 1650    [eol, '~N'-[]].
 1651extra_line -->
 1652    [eol].
 1653
 1654prolog_message(if_tty(Message)) -->
 1655    (   {current_prolog_flag(tty_control, true)}
 1656    ->  [ at_same_line ], list(Message)
 1657    ;   []
 1658    ).
 1659prolog_message(halt(Reason)) -->
 1660    [ '~w: halt'-[Reason] ].
 1661prolog_message(no_action(Char)) -->
 1662    [ 'Unknown action: ~c (h for help)'-[Char], nl ].
 1663
 1664prolog_message(history(help(Show, Help))) -->
 1665    [ 'History Commands:', nl,
 1666      '    !!.              Repeat last query', nl,
 1667      '    !nr.             Repeat query numbered <nr>', nl,
 1668      '    !str.            Repeat last query starting with <str>', nl,
 1669      '    !?str.           Repeat last query holding <str>', nl,
 1670      '    ^old^new.        Substitute <old> into <new> of last query', nl,
 1671      '    !nr^old^new.     Substitute in query numbered <nr>', nl,
 1672      '    !str^old^new.    Substitute in query starting with <str>', nl,
 1673      '    !?str^old^new.   Substitute in query holding <str>', nl,
 1674      '    ~w.~21|Show history list'-[Show], nl,
 1675      '    ~w.~21|Show this list'-[Help], nl, nl
 1676    ].
 1677prolog_message(history(no_event)) -->
 1678    [ '! No such event' ].
 1679prolog_message(history(bad_substitution)) -->
 1680    [ '! Bad substitution' ].
 1681prolog_message(history(expanded(Event))) -->
 1682    [ '~w.'-[Event] ].
 1683prolog_message(history(history(Events))) -->
 1684    history_events(Events).
 1685prolog_message(history(no_history)) -->
 1686    [ '! event history not supported in this version' ].
 1687
 1688history_events([]) -->
 1689    [].
 1690history_events([Nr-Event|T]) -->
 1691    [ ansi(comment, '%', []),
 1692      ansi(bold, '~t~w ~6|', [Nr]),
 1693      ansi(code, '~s', [Event]),
 1694      nl
 1695    ],
 1696    history_events(T).
 user_version_messages(+Terms)//
Helper for the welcome message to print information registered using version/1.
 1704user_version_messages([]) --> [].
 1705user_version_messages([H|T]) -->
 1706    user_version_message(H),
 1707    user_version_messages(T).
 user_version_message(+Term)
 1711user_version_message(Term) -->
 1712    translate_message(Term), !, [nl].
 1713user_version_message(Atom) -->
 1714    [ '~w'-[Atom], nl ].
 1715
 1716
 1717                 /*******************************
 1718                 *       DEBUGGER MESSAGES      *
 1719                 *******************************/
 1720
 1721prolog_message(spy(Head)) -->
 1722    [ 'New spy point on ' ],
 1723    predicate_reference(Head).
 1724prolog_message(already_spying(Head)) -->
 1725    [ 'Already spying ' ],
 1726    predicate_reference(Head).
 1727prolog_message(nospy(Head)) -->
 1728    [ 'Removed spy point from ' ],
 1729    predicate_reference(Head).
 1730prolog_message(trace_mode(OnOff)) -->
 1731    [ 'Trace mode switched to ~w'-[OnOff] ].
 1732prolog_message(debug_mode(OnOff)) -->
 1733    [ 'Debug mode switched to ~w'-[OnOff] ].
 1734prolog_message(debugging(OnOff, Threads)) -->
 1735    [ 'Debug mode is ~w'-[OnOff] ],
 1736    debugging_threads(Threads).
 1737prolog_message(spying([])) -->
 1738    !,
 1739    [ 'No spy points' ].
 1740prolog_message(spying(Heads)) -->
 1741    [ 'Spy points (see spy/1) on:', nl ],
 1742    predicate_list(Heads).
 1743prolog_message(trace(Head, [])) -->
 1744    !,
 1745    [ '    ' ], predicate_reference(Head, [tag(true)]),
 1746    [ ' Not tracing'-[], nl].
 1747prolog_message(trace(Head, Ports)) -->
 1748    { '$member'(Port, Ports), compound(Port),
 1749      !,
 1750      numbervars(Head+Ports, 0, _, [singletons(true)])
 1751    },
 1752    [ '    ~p: ~p'-[Head,Ports] ].
 1753prolog_message(trace(Head, Ports)) -->
 1754    [ '    ' ], predicate_reference(Head, [tag(true)]),
 1755    [ ': ~w'-[Ports], nl].
 1756prolog_message(tracing([])) -->
 1757    !,
 1758    [ 'No traced predicates (see trace/1,2)' ].
 1759prolog_message(tracing(Heads)) -->
 1760    [ 'Trace points (see trace/1,2) on:', nl ],
 1761    tracing_list(Heads).
 predicate_list(+Specs)// is det
Emit a list of predicates, one per line, each tagged with its kind. See predicate_reference//2.
 1768predicate_list([]) -->
 1769    [].
 1770predicate_list([H|T]) -->
 1771    [ '    ' ], predicate_reference(H, [tag(true)]), [nl],
 1772    predicate_list(T).
 1773
 1774tracing_list([]) -->
 1775    [].
 1776tracing_list([trace(Head, Ports)|T]) -->
 1777    translate_message(trace(Head, Ports)),
 1778    tracing_list(T).
 1779
 1780debugging_threads([]) -->
 1781    [].
 1782debugging_threads(ThreadsByClass) -->
 1783    [ nl, 'Threads in the following classes run in debug mode:', nl],
 1784    list_threads_by_class(ThreadsByClass).
 1785
 1786list_threads_by_class([]) -->
 1787    [].
 1788list_threads_by_class([H|T]) -->
 1789    list_thread_class(H),
 1790    list_threads_by_class(T).
 1791
 1792list_thread_class(Class-Threads) -->
 1793    { length(Threads, Count) },
 1794    [ '    Class ', ansi(code, '~p', [Class]), ': ~D threads'-[Count] ].
 1795
 1796% frame(+Frame, +Choice, +Port, +PC) - Print for the debugger.
 1797prolog_message(frame(Frame, _Choice, backtrace, _PC)) -->
 1798    !,
 1799    { prolog_frame_attribute(Frame, level, Level)
 1800    },
 1801    [ ansi(frame(level), '~t[~D] ~10|', [Level]) ],
 1802    frame_context(Frame),
 1803    frame_goal(Frame, backtrace).
 1804prolog_message(frame(Frame, Choice, choice, PC)) -->
 1805    !,
 1806    prolog_message(frame(Frame, Choice, backtrace, PC)).
 1807prolog_message(frame(_, _Choice, cut_call(_PC), _)) --> !.
 1808prolog_message(frame(Frame, _Choice, Port, _PC)) -->
 1809    frame_flags(Frame),
 1810    port(Port),
 1811    frame_level(Frame),
 1812    frame_context(Frame),
 1813    frame_depth_limit(Port, Frame),
 1814    frame_goal(Frame, Port),
 1815    [ flush ].
 1816
 1817% frame(:Goal, +Trace)		- Print for trace/2
 1818prolog_message(frame(Goal, trace(Port))) -->
 1819    !,
 1820    thread_context,
 1821    [ ' T ' ],
 1822    port(Port),
 1823    predicate_goal(Goal, Port).
 1824prolog_message(frame(Goal, trace(Port, Id))) -->
 1825    !,
 1826    thread_context,
 1827    [ ' T ' ],
 1828    port(Port, Id),
 1829    predicate_goal(Goal, Port).
 goal_style(+Port, -Style) is det
Style is the colour class used for the goal of a frame that is being reported for Port. It is a term goal(Port, Parity), which allows themes to decorate the goal depending on the port, on the parity of the step count (striping, which separates the steps of a trace visually) or both. See also '$answer_class'/1, which does the same for the answers of the interactive toplevel.
 1840goal_style(Port0, goal(Port, Parity)) :-
 1841    functor(Port0, Port, _),
 1842    trace_parity(Parity).
 1843
 1844trace_parity(Parity) :-
 1845    (   nb_current('$trace_step', C0)
 1846    ->  true
 1847    ;   C0 = 0
 1848    ),
 1849    C is C0+1,
 1850    nb_setval('$trace_step', C),
 1851    (   C mod 2 =:= 0
 1852    ->  Parity = even
 1853    ;   Parity = odd
 1854    ).
 1855
 1856frame_goal(Frame, Port) -->
 1857    { prolog_frame_attribute(Frame, goal, Goal),
 1858      goal_style(Port, Style)
 1859    },
 1860    (   { frame_location(Frame, Location) }
 1861    ->  goal(Goal, Style, Location)
 1862    ;   goal(Goal, Style)
 1863    ).
 predicate_goal(+Goal, +Port)// is det
Emit Goal, linking it to the definition of its predicate. Used if we have no frame, i.e., for the messages of library(prolog_trace).
 1870predicate_goal(Goal, Port) -->
 1871    { goal_style(Port, Style)
 1872    },
 1873    (   { goal_links,
 1874          predicate_location(Goal, Location)
 1875        }
 1876    ->  goal(Goal, Style, Location)
 1877    ;   goal(Goal, Style)
 1878    ).
 1879
 1880goal(Goal0, Style) -->
 1881    { goal_format(Goal0, Goal, Options)
 1882    },
 1883    [ ansi(Style, '~W', [Goal, Options]) ].
 1884
 1885goal(Goal0, Style, Location) -->
 1886    { goal_format(Goal0, Goal, Options)
 1887    },
 1888    [ url(Location, ansi(Style, '~W', [Goal, Options])) ].
 1889
 1890goal_format(Goal0, Goal, Options) :-
 1891    clean_goal(Goal0, Goal),
 1892    current_prolog_flag(debugger_write_options, Options).
 frame_location(+Frame, -Location) is semidet
Location is File:Line for the call site of Frame, i.e., the place in the clause of the parent frame from which Frame was called. This is the position the user is at while tracing. If we cannot find it, fall back to the clause that runs in Frame and finally to the file that defines the predicate.

Resolving the call site uses library(prolog_stack), which has to run the decompiler and read the source file. This is affordable for an interactive tracer, but we only do it if the location can actually be used, i.e., if hyperlinks are rendered. See goal_links/0.

 1907frame_location(Frame, Location) :-
 1908    goal_links,
 1909    catch(frame_location_(Frame, Location), _, fail).
 1910
 1911frame_location_(Frame, File:Line) :-
 1912    prolog_frame_attribute(Frame, pc, PC),
 1913    prolog_frame_attribute(Frame, parent, Parent),
 1914    prolog_frame_attribute(Parent, clause, Clause),
 1915    prolog_stack_frame_property(frame(_,clause(Clause,PC),_),
 1916                                location(File:Line)),
 1917    !.
 1918frame_location_(Frame, File:Line) :-
 1919    prolog_frame_attribute(Frame, clause, Clause),
 1920    clause_property(Clause, file(File)),
 1921    clause_property(Clause, line_count(Line)),
 1922    !.
 1923frame_location_(Frame, Location) :-
 1924    prolog_frame_attribute(Frame, goal, Goal),
 1925    predicate_location(Goal, Location).
 goal_links is semidet
True when goals printed by the debugger should be linked to their source location. Controlled by the flag debugger_goal_links, which is one of true, false or auto. Using auto (default) we create the links if the console can render them.
 1934goal_links :-
 1935    current_prolog_flag(debugger_goal_links, Links),
 1936    goal_links(Links).
 1937
 1938goal_links(true).                       % note: no clause for `false`
 1939goal_links(auto) :-
 1940    (   current_prolog_flag(hyperlink_term, true)
 1941    ->  true
 1942    ;   predicate_property(ansi_term:hyperlink(_,_), number_of_clauses(N)),
 1943        N > 0
 1944    ).
 1945
 1946frame_level(Frame) -->
 1947    { prolog_frame_attribute(Frame, level, Level)
 1948    },
 1949    [ '(~D) '-[Level] ].
 1950
 1951frame_context(Frame) -->
 1952    (   { current_prolog_flag(debugger_show_context, true),
 1953          prolog_frame_attribute(Frame, context_module, Context)
 1954        }
 1955    ->  [ '[~w] '-[Context] ]
 1956    ;   []
 1957    ).
 1958
 1959frame_depth_limit(fail, Frame) -->
 1960    { prolog_frame_attribute(Frame, depth_limit_exceeded, true)
 1961    },
 1962    !,
 1963    [ '[depth-limit exceeded] ' ].
 1964frame_depth_limit(_, _) -->
 1965    [].
 1966
 1967frame_flags(Frame) -->
 1968    { prolog_frame_attribute(Frame, goal, Goal),
 1969      (   predicate_property(Goal, transparent)
 1970      ->  T = '^'
 1971      ;   T = ' '
 1972      ),
 1973      (   predicate_property(Goal, spying)
 1974      ->  S = '*'
 1975      ;   S = ' '
 1976      )
 1977    },
 1978    [ '~w~w '-[T, S] ].
 1979
 1980% trace/1 context handling
 1981port(Port, Dict) -->
 1982    { _{level:Level, start:Time} :< Dict
 1983    },
 1984    (   { Port \== call,
 1985          get_time(Now),
 1986          Passed is (Now - Time)*1000.0
 1987        }
 1988    ->  [ '[~d +~1fms] '-[Level, Passed] ]
 1989    ;   [ '[~d] '-[Level] ]
 1990    ),
 1991    port(Port).
 1992port(Port, _Id-Level) -->
 1993    [ '[~d] '-[Level] ],
 1994    port(Port).
 1995
 1996port(PortTerm) -->
 1997    { functor(PortTerm, Port, _),
 1998      port_name(Port, Name)
 1999    },
 2000    !,
 2001    [ ansi(port(Port), '~w: ', [Name]) ].
 2002
 2003port_name(call,      'Call').
 2004port_name(exit,      'Exit').
 2005port_name(fail,      'Fail').
 2006port_name(redo,      'Redo').
 2007port_name(unify,     'Unify').
 2008port_name(exception, 'Exception').
 2009
 2010clean_goal(M:Goal, Goal) :-
 2011    hidden_module(M),
 2012    !.
 2013clean_goal(M:Goal, Goal) :-
 2014    predicate_property(M:Goal, built_in),
 2015    !.
 2016clean_goal(Goal, Goal).
 2017
 2018
 2019                 /*******************************
 2020                 *        COMPATIBILITY         *
 2021                 *******************************/
 2022
 2023prolog_message(compatibility(renamed(Old, New))) -->
 2024    [ 'The predicate ' ], predicate_reference(Old, [link(false)]),
 2025    [ ' has been renamed to ' ], predicate_reference(New),
 2026    [ '.', nl,
 2027      'Please update your sources for compatibility with future versions.'
 2028    ].
 2029
 2030
 2031                 /*******************************
 2032                 *            THREADS           *
 2033                 *******************************/
 2034
 2035prolog_message(abnormal_thread_completion(Goal, exception(Ex))) -->
 2036    !,
 2037    [ 'Thread running "~p" died on exception: '-[Goal] ],
 2038    translate_exception(Ex).
 2039prolog_message(abnormal_thread_completion(Goal, fail)) -->
 2040    [ 'Thread running "~p" died due to failure'-[Goal] ].
 2041prolog_message(threads_not_died(Running)) -->
 2042    [ 'The following threads wouldn\'t die: ~p'-[Running] ].
 2043
 2044
 2045                 /*******************************
 2046                 *             PACKS            *
 2047                 *******************************/
 2048
 2049prolog_message(pack(attached(Pack, BaseDir))) -->
 2050    [ 'Attached package ~w at ~q'-[Pack, BaseDir] ].
 2051prolog_message(pack(duplicate(Entry, OldDir, Dir))) -->
 2052    [ 'Package ~w already attached at ~q.'-[Entry,OldDir], nl,
 2053      '\tIgnoring version from ~q'- [Dir]
 2054    ].
 2055prolog_message(pack(no_arch(Entry, Arch))) -->
 2056    [ 'Package ~w: no binary for architecture ~w'-[Entry, Arch] ].
 2057
 2058                 /*******************************
 2059                 *             MISC             *
 2060                 *******************************/
 2061
 2062prolog_message(null_byte_in_path(Component)) -->
 2063    [ '0-byte in PATH component: ~p (skipped directory)'-[Component] ].
 2064prolog_message(invalid_tmp_dir(Dir, Reason)) -->
 2065    [ 'Cannot use ~p as temporary file directory: ~w'-[Dir, Reason] ].
 2066prolog_message(ambiguous_stream_pair(Pair)) -->
 2067    [ 'Ambiguous operation on stream pair ~p'-[Pair] ].
 2068prolog_message(backcomp(init_file_moved(FoundFile))) -->
 2069    { absolute_file_name(app_config('init.pl'), InitFile,
 2070                         [ file_errors(fail)
 2071                         ])
 2072    },
 2073    [ 'The location of the config file has moved'-[], nl,
 2074      '  from "~w"'-[FoundFile], nl,
 2075      '  to   "~w"'-[InitFile], nl,
 2076      '  See https://www.swi-prolog.org/modified/config-files.html'-[]
 2077    ].
 2078prolog_message(not_accessed_flags(List)) -->
 2079    [ 'The following Prolog flags have been set but not used:', nl ],
 2080    flags(List).
 2081prolog_message(implicit_create_flag(Flag)) -->
 2082    [ 'Created unknown Prolog flag ', ansi(code, '~q', Flag),
 2083      ' (see create_prolog_flag/3)'
 2084    ].
 2085prolog_message(prolog_flag_invalid_preset(Flag, Preset, _Type, New)) -->
 2086    [ 'Prolog flag ', ansi(code, '~q', Flag), ' has been (re-)created with a type that is \c
 2087       incompatible with its value.', nl,
 2088      'Value updated from ', ansi(code, '~p', [Preset]), ' to default (',
 2089      ansi(code, '~p', [New]), ')'
 2090    ].
 2091
 2092
 2093flags([H|T]) -->
 2094    ['  ', ansi(code, '~q', [H])],
 2095    (   {T == []}
 2096    ->  []
 2097    ;   [nl],
 2098        flags(T)
 2099    ).
 2100
 2101
 2102		 /*******************************
 2103		 *          DEPRECATED		*
 2104		 *******************************/
 2105
 2106deprecated(set_prolog_stack(_Stack,limit)) -->
 2107    [ 'set_prolog_stack/2: limit(Size) sets the combined limit.'-[], nl,
 2108      'See https://www.swi-prolog.org/changes/stack-limit.html'
 2109    ].
 2110deprecated(autoload(TargetModule, File, _M:PI, expansion)) -->
 2111    !,
 2112    [ 'Auto-loading ' ], predicate_reference(PI, [link(false)]),
 2113    [ ' from ' ],
 2114    load_file(File), [ ' into ' ],
 2115    target_module(TargetModule),
 2116    [ ' is deprecated due to term- or goal-expansion' ].
 2117deprecated(source_search_working_directory(File, _FullFile)) -->
 2118    [ 'Found file ', ansi(code, '~w', [File]),
 2119      ' relative to the current working directory.', nl,
 2120      'This behaviour is deprecated but still supported by', nl,
 2121      'the Prolog flag ',
 2122      ansi(code, source_search_working_directory, []), '.', nl
 2123    ].
 2124deprecated(moved_library(Old, New)) -->
 2125    [ 'Library was moved: ~q --> ~q'-[Old, New] ].
 2126
 2127load_file(File) -->
 2128    { file_base_name(File, Base),
 2129      absolute_file_name(library(Base), File, [access(read), file_errors(fail)]),
 2130      file_name_extension(Clean, pl, Base)
 2131    },
 2132    !,
 2133    [ ansi(code, '~p', [library(Clean)]) ].
 2134load_file(File) -->
 2135    [ url(File) ].
 2136
 2137target_module(Module) -->
 2138    { module_property(Module, file(File)) },
 2139    !,
 2140    load_file(File).
 2141target_module(Module) -->
 2142    [ 'module ', ansi(code, '~p', [Module]) ].
 2143
 2144
 2145
 2146		 /*******************************
 2147		 *           TRIPWIRES		*
 2148		 *******************************/
 2149
 2150tripwire_message(max_integer_size, Bytes) -->
 2151    !,
 2152    [ 'Trapped tripwire max_integer_size: big integers and \c
 2153       rationals are limited to ~D bytes'-[Bytes] ].
 2154tripwire_message(Wire, Context) -->
 2155    [ 'Trapped tripwire ~w for '-[Wire] ],
 2156    tripwire_context(Wire, Context).
 2157
 2158tripwire_context(_, ATrie) -->
 2159    { '$is_answer_trie'(ATrie, _),
 2160      !,
 2161      '$tabling':atrie_goal(ATrie, QGoal),
 2162      clean_goal(QGoal, Goal)          % a goal, not a predicate indicator
 2163    },
 2164    [ '~p'-[Goal] ].
 2165tripwire_context(_, Ctx) -->
 2166    [ '~p'-[Ctx] ].
 2167
 2168
 2169		 /*******************************
 2170		 *     INTERNATIONALIZATION	*
 2171		 *******************************/
 2172
 2173:- create_prolog_flag(message_language, default, []).
 message_lang(-Lang) is multi
True when Lang is a language id preferred for messages. Starts with the most specific language (e.g., nl_BE) and ends with en.
 2180message_lang(Lang) :-
 2181    current_message_lang(Lang0),
 2182    (   Lang0 == en
 2183    ->  Lang = en
 2184    ;   sub_atom(Lang0, 0, _, _, en_)
 2185    ->  longest_id(Lang0, Lang)
 2186    ;   (   longest_id(Lang0, Lang)
 2187        ;   Lang = en
 2188        )
 2189    ).
 2190
 2191longest_id(Lang, Id) :-
 2192    split_string(Lang, "_-", "", [H|Components]),
 2193    longest_prefix(Components, Taken),
 2194    atomic_list_concat([H|Taken], '_', Id).
 2195
 2196longest_prefix([H|T0], [H|T]) :-
 2197    longest_prefix(T0, T).
 2198longest_prefix(_, []).
 current_message_lang(-Lang) is det
Get the current language for messages.
 2204current_message_lang(Lang) :-
 2205    (   current_prolog_flag(message_language, Lang0),
 2206        Lang0 \== default
 2207    ->  Lang = Lang0
 2208    ;   os_user_lang(Lang0)
 2209    ->  clean_encoding(Lang0, Lang1),
 2210        set_prolog_flag(message_language, Lang1),
 2211        Lang = Lang1
 2212    ;   Lang = en
 2213    ).
 2214
 2215os_user_lang(Lang) :-
 2216    current_prolog_flag(windows, true),
 2217    win_get_user_preferred_ui_languages(name, [Lang|_]).
 2218os_user_lang(Lang) :-
 2219    catch(setlocale(messages, _, ''), _, fail),
 2220    setlocale(messages, Lang, Lang).
 2221os_user_lang(Lang) :-
 2222    getenv('LANG', Lang).
 2223
 2224
 2225clean_encoding(Lang0, Lang) :-
 2226    (   sub_atom(Lang0, A, _, _, '.')
 2227    ->  sub_atom(Lang0, 0, A, _, Lang)
 2228    ;   Lang = Lang0
 2229    ).
 2230
 2231		 /*******************************
 2232		 *          PRIMITIVES		*
 2233		 *******************************/
 2234
 2235code(Term) -->
 2236    code('~p', Term).
 2237
 2238code(Format, Term) -->
 2239    [ ansi(code, Format, [Term]) ].
 2240
 2241list([]) --> [].
 2242list([H|T]) --> [H], list(T).
 2243
 2244
 2245		 /*******************************
 2246		 *     PREDICATE REFERENCES	*
 2247		 *******************************/
 predicate_indicator(+Spec, -QPI) is semidet
QPI is the fully qualified predicate indicator Module:Name/Arity or, for a non-terminal, Module:Name//Arity for Spec. Spec is one of

The module is kept here. Whether or not it is printed is left to predicate_reference//2, which uses user_predicate_indicator/2.

See also
- pi_head/2 of library(prolog_code) for the general version. This one is in the boot files and thus cannot use it.
 2264:- public
 2265    predicate_indicator/2. 2266
 2267predicate_indicator(Spec, QPI) :-
 2268    strip_module(user:Spec, Module, Spec1),
 2269    (   is_predicate_indicator(Spec1)
 2270    ->  dcg_indicator(Module, Spec1, QPI)
 2271    ;   callable(Spec1),
 2272        '$pi_head'(Module:PI, Module:Spec1),
 2273        dcg_indicator(Module, PI, QPI)
 2274    ).
 dcg_indicator(+Module, +PI, -QPI) is det
Qualify PI with Module and use the // notation if the predicate is a non-terminal.
 2281dcg_indicator(Module, Name//DCGArity, Module:Name//DCGArity) :-
 2282    !.
 2283dcg_indicator(Module, Name/Arity, QPI) :-
 2284    (   Arity >= 2,
 2285        current_predicate(Module:Name/Arity),
 2286        functor(Head, Name, Arity),
 2287        predicate_property(Module:Head, non_terminal)
 2288    ->  DCGArity is Arity-2,
 2289        QPI = Module:Name//DCGArity
 2290    ;   QPI = Module:Name/Arity
 2291    ).
 predicate_head(+Spec, -QHead) is semidet
QHead is the module qualified head for Spec, accepting the same input as predicate_indicator/2. Unqualified specs are qualified using user.
 2299predicate_head(Spec, QHead) :-
 2300    strip_module(user:Spec, Module, Spec1),
 2301    (   is_predicate_indicator(Spec1)
 2302    ->  '$pi_head'(Module:Spec1, QHead)
 2303    ;   callable(Spec1),
 2304        QHead = Module:Spec1
 2305    ).
 2306
 2307is_predicate_indicator(Name/Arity) :-
 2308    atomic(Name), integer(Arity).
 2309is_predicate_indicator(Name//Arity) :-
 2310    atomic(Name), integer(Arity).
 predicate_reference(+Spec)// is det
 predicate_reference(+Spec, +Options)// is det
Emit a reference to a predicate. Spec is a (possibly qualified) head or predicate indicator. The reference is printed using the style class code and, if the location of the predicate is known and the output is a terminal that supports it, it is a hyperlink to the definition. Options:
module(+Which)
One of auto (default), hide or show. Using auto, the module qualification is removed if hidden_module/1 holds for it.
link(+Bool)
If false, do not try to create a hyperlink. Default true.
style(+Class)
Style class for the reference. Default code.
tag(+Bool)
If true, add a tag that indicates the kind of predicate. See predicate_kind/2. Default false. Only sensible if the reference is the only thing on the line.

If Spec cannot be interpreted as a predicate it is printed using the code class and ~p, i.e., we never fail on a malformed message.

 2336:- public
 2337    predicate_reference//1,
 2338    predicate_reference//2. 2339
 2340predicate_reference(Spec) -->
 2341    predicate_reference(Spec, []).
 2342
 2343predicate_reference(Spec, Options) -->
 2344    { predicate_indicator(Spec, QPI) },
 2345    !,
 2346    { pref_option(style(Style), Options, code),
 2347      pref_option(module(Mode), Options, auto),
 2348      reference_pi(Mode, QPI, PI)
 2349    },
 2350    predicate_link(QPI, ansi(Style, '~q', [PI]), Options),
 2351    predicate_reference_tag(QPI, Options).
 2352predicate_reference(Spec, _Options) -->
 2353    [ ansi(code, '~p', [Spec]) ].
 2354
 2355reference_pi(auto, QPI, PI) :-
 2356    !,
 2357    user_predicate_indicator(QPI, PI).
 2358reference_pi(hide, _:PI, PI) :- !.
 2359reference_pi(_, QPI, QPI).
 2360
 2361predicate_link(QPI, Label, Options) -->
 2362    { pref_option(link(true), Options, true),
 2363      predicate_location(QPI, Location)
 2364    },
 2365    !,
 2366    [ url(Location, Label) ].
 2367predicate_link(_, Label, _) -->
 2368    [ Label ].
 pref_option(?Option, +Options, +Default) is semidet
Get an option from the option list of predicate_reference//2. Fails if Options holds a value for Option that does not unify. Note that this deliberately does not use library(option): boot/messages.pl must be able to print a message before the libraries are available.
 2377pref_option(Option, Options, Default) :-
 2378    functor(Option, Name, 1),
 2379    functor(General, Name, 1),
 2380    (   memberchk(General, Options)
 2381    ->  General = Option
 2382    ;   arg(1, Option, Default)
 2383    ).
 predicate_location(+Spec, -Location) is semidet
Location is File:Line for the definition of the predicate Spec. Also deals with predicates defined in C. Note that predicates that are not loaded but can be autoloaded are located from the autoload index, i.e., printing a message never loads a library.
 2392:- public
 2393    predicate_location/2. 2394
 2395predicate_location(Spec, Location) :-
 2396    predicate_head(Spec, Head),
 2397    current_predicate(_, Head),                 % do not (auto)load
 2398    '$predicate_source_location'(Head, Location).
 predicate_definition(+Spec, +Message)// is det
Emit "Message at File:Line" on a new line if the location of Spec is known and nothing at all if it is not.
 2405:- public
 2406    predicate_definition//2. 2407
 2408predicate_definition(Spec, Message) -->
 2409    { predicate_location(Spec, Location) },
 2410    !,
 2411    [ nl, '~w at '-[Message], url(Location) ].
 2412predicate_definition(_, _) -->
 2413    [].
 predicate_kind(+Spec, -Kind) is semidet
Classify a predicate for the benefit of the user who has to pick one from a list of candidates. Fails if Spec is not a predicate. Kind is one of
 2429:- public
 2430    predicate_kind/2. 2431
 2432predicate_kind(Spec, Kind) :-
 2433    predicate_head(Spec, Head),
 2434    (   current_predicate(_, Head)              % do not autoload
 2435    ->  defined_predicate_kind(Head, Kind)
 2436    ;   predicate_property(Head, autoload(File))
 2437    ->  library_name(File, Name),
 2438        Kind = library(Name)
 2439    ;   Kind = undefined
 2440    ).
 2441
 2442defined_predicate_kind(Head, Kind) :-
 2443    (   predicate_property(Head, iso)
 2444    ->  Kind = iso
 2445    ;   predicate_property(Head, built_in)
 2446    ->  (   predicate_property(Head, foreign)
 2447        ->  Kind = foreign
 2448        ;   Kind = built_in
 2449        )
 2450    ;   predicate_property(Head, imported_from(Module))
 2451    ->  module_kind(Module, Kind)
 2452    ;   predicate_property(Head, file(File)),
 2453        library_file(File)
 2454    ->  library_name(File, Name),
 2455        Kind = library(Name)
 2456    ;   Kind = user
 2457    ).
 2458
 2459module_kind(Module, Kind) :-
 2460    (   hidden_module(Module)
 2461    ->  Kind = user
 2462    ;   module_property(Module, file(File)),
 2463        library_file(File)
 2464    ->  library_name(File, Name),
 2465        Kind = library(Name)
 2466    ;   Kind = module(Module)
 2467    ).
 library_file(+File) is semidet
 library_name(+File, -Name) is det
True if File is in one of the library directories and, if so, Name is how the file is referred to as library(Name).
 2475library_file(File) :-
 2476    absolute_file_name(library(.), LibDir,
 2477                       [ file_type(directory),
 2478                         solutions(all),
 2479                         file_errors(fail)
 2480                       ]),
 2481    sub_atom(File, 0, _, _, LibDir),
 2482    !.
 2483
 2484library_name(File, Name) :-
 2485    (   file_name_extension(Base, Ext, File),
 2486        Ext \== ''
 2487    ->  true
 2488    ;   Base = File
 2489    ),
 2490    file_base_name(Base, Name).
 predicate_reference_tag(+QPI, +Options)// is det
 predicate_kind_tag(+Kind)// is det
Emit the kind of the predicate as a short tag.
 2497predicate_reference_tag(QPI, Options) -->
 2498    { pref_option(tag(true), Options, false),
 2499      predicate_kind(QPI, Kind)
 2500    },
 2501    !,
 2502    predicate_kind_tag(Kind).
 2503predicate_reference_tag(_, _) -->
 2504    [].
 2505
 2506predicate_kind_tag(Kind) -->
 2507    { predicate_kind_label(Kind, Label) },
 2508    [ ansi(predicate(Kind), ' [~w]', [Label]) ].
 2509
 2510predicate_kind_label(iso,          'ISO').
 2511predicate_kind_label(built_in,     'built-in').
 2512predicate_kind_label(foreign,      'built-in').
 2513predicate_kind_label(user,         'user').
 2514predicate_kind_label(undefined,    'undefined').
 2515predicate_kind_label(library(Name), Label) :-
 2516    format(atom(Label), 'library(~w)', [Name]).
 2517predicate_kind_label(module(Name), Name).
 2518
 2519
 2520		 /*******************************
 2521		 *        DEFAULT THEME		*
 2522		 *******************************/
 2523
 2524:- multifile
 2525    prolog:theme/1,
 2526    prolog:theme_base/2. 2527:- public
 2528    current_theme/1,
 2529    theme_ancestor/2,
 2530    default_theme/2.
 current_theme(-Theme) is det
Theme is the theme that defines the console colours (see prolog:console_color/3). This is the value of the Prolog flag theme, unless this is default or auto. In that case it is the theme of a loaded theme file, e.g., a file loaded from the init file or by library(theme/auto). If no theme file is loaded, Theme is default.
 2541current_theme(Theme) :-
 2542    current_prolog_flag(theme, Selected),
 2543    Selected \== default,
 2544    Selected \== auto,
 2545    !,
 2546    Theme = Selected.
 2547current_theme(Theme) :-
 2548    prolog:theme(Loaded),
 2549    !,
 2550    Theme = Loaded.
 2551current_theme(default).
 theme_ancestor(+Theme, -Ancestor) is nondet
Ancestor is Theme or a theme Theme is based on, nearest first. A theme is based on another theme using the multifile hook prolog:theme_base/2. A theme uses the settings of its base theme that it does not define itself.
 2560theme_ancestor(Theme, Ancestor) :-
 2561    theme_ancestor(Theme, [Theme], Ancestor).
 2562
 2563theme_ancestor(Theme, _, Theme).
 2564theme_ancestor(Theme, Seen, Ancestor) :-
 2565    prolog:theme_base(Theme, Base),
 2566    !,
 2567    \+ memberchk(Base, Seen),
 2568    theme_ancestor(Base, [Base|Seen], Ancestor).
 2569
 2570
 2571default_theme(var,                    [fg(red)]).
 2572default_theme(code,                   [fg(blue)]).
 2573default_theme(comment,                [fg(green)]).
 2574default_theme(warning,                [fg(red)]).
 2575default_theme(error,                  [bold, fg(red)]).
 2576default_theme(truth(false),           [bold, fg(red)]).
 2577default_theme(truth(true),            [bold]).
 2578default_theme(truth(undefined),       [bold, fg(cyan)]).
 2579default_theme(wfs(residual_program),  [fg(cyan)]).
 2580default_theme(frame(level),           [bold]).
 2581default_theme(goal(_,_),              []).
 2582default_theme(port(call),             [bold, fg(green)]).
 2583default_theme(port(exit),             [bold, fg(green)]).
 2584default_theme(port(fail),             [bold, fg(red)]).
 2585default_theme(port(redo),             [bold, fg(yellow)]).
 2586default_theme(port(unify),            [bold, fg(blue)]).
 2587default_theme(port(exception),        [bold, fg(magenta)]).
 2588default_theme(prompt,                 [bold]).
 2589default_theme(input,                  []).
 2590default_theme(answer(_),              []).
 2591default_theme(binding(name),          [bold]).
 2592default_theme(predicate(iso),         [italic, fg(cyan)]).
 2593default_theme(predicate(built_in),    [italic, fg(cyan)]).
 2594default_theme(predicate(foreign),     [italic, fg(cyan)]).
 2595default_theme(predicate(library(_)),  [italic, fg(green)]).
 2596default_theme(predicate(module(_)),   [italic, fg(green)]).
 2597default_theme(predicate(user),        [italic, fg(default)]).
 2598default_theme(predicate(undefined),   [italic, fg(red)]).
 2599default_theme(message(informational), [fg(green)]).
 2600default_theme(message(information),   [fg(green)]).
 2601default_theme(message(debug(_)),      [fg(blue)]).
 2602default_theme(message(Level),         Attrs) :-
 2603    nonvar(Level),
 2604    default_theme(Level, Attrs).
 2605
 2606
 2607                 /*******************************
 2608                 *      PRINTING MESSAGES       *
 2609                 *******************************/
 2610
 2611:- multifile
 2612    user:message_hook/3,
 2613    prolog:message_prefix_hook/2. 2614:- dynamic
 2615    user:message_hook/3,
 2616    prolog:message_prefix_hook/2. 2617:- thread_local
 2618    user:thread_message_hook/3. 2619:- '$notransact'((user:message_hook/3,
 2620                  prolog:message_prefix_hook/2,
 2621                  user:thread_message_hook/3)).
 print_message(+Kind, +Term)
Print an error message using a term as generated by the exception system.
 2628print_message(Level, _Term) :-
 2629    msg_property(Level, stream(S)),
 2630    stream_property(S, error(true)),
 2631    !.
 2632print_message(Level, Term) :-
 2633    setup_call_cleanup(
 2634        notrace(push_msg(Term, Stack)),
 2635        ignore(print_message_guarded(Level, Term)),
 2636        notrace(pop_msg(Stack))),
 2637    !.
 2638print_message(Level, Term) :-
 2639    (   Level \== silent
 2640    ->  format(user_error, 'Recursive ~w message: ~q~n', [Level, Term]),
 2641        autoload_call(backtrace(20))
 2642    ;   true
 2643    ).
 2644
 2645push_msg(Term, Messages) :-
 2646    nb_current('$inprint_message', Messages),
 2647    !,
 2648    \+ ( '$member'(Msg, Messages),
 2649         Msg =@= Term
 2650       ),
 2651    Stack = [Term|Messages],
 2652    b_setval('$inprint_message', Stack).
 2653push_msg(Term, []) :-
 2654    b_setval('$inprint_message', [Term]).
 2655
 2656pop_msg(Stack) :-
 2657    nb_delete('$inprint_message'),              % delete history
 2658    b_setval('$inprint_message', Stack).
 2659
 2660print_message_guarded(Level, Term) :-
 2661    (   must_print(Level, Term)
 2662    ->  (   prolog:message_action(Term, Level),
 2663            fail                                % forall/2 is cleaner, but not yet
 2664        ;   true                                % defined
 2665        ),
 2666        (   translate_message(Term, Lines, [])
 2667        ->  (   nonvar(Term),
 2668                (   notrace(user:thread_message_hook(Term, Level, Lines))
 2669                ->  true
 2670                ;   notrace(user:message_hook(Term, Level, Lines))
 2671                )
 2672            ->  true
 2673            ;   '$inc_message_count'(Level),
 2674                print_system_message(Term, Level, Lines),
 2675                maybe_halt_on_error(Level)
 2676            )
 2677        )
 2678    ;   true
 2679    ).
 2680
 2681maybe_halt_on_error(error) :-
 2682    current_prolog_flag(on_error, halt),
 2683    !,
 2684    halt(1).
 2685maybe_halt_on_error(warning) :-
 2686    current_prolog_flag(on_warning, halt),
 2687    !,
 2688    halt(1).
 2689maybe_halt_on_error(_).
 print_system_message(+Term, +Kind, +Lines)
Print the message if the user did not intecept the message. The first is used for errors and warnings that can be related to source-location. Note that syntax errors have their own source-location and should therefore not be handled this way.
 2699print_system_message(_, silent, _) :- !.
 2700print_system_message(_, informational, _) :-
 2701    current_prolog_flag(verbose, silent),
 2702    !.
 2703print_system_message(_, banner, _) :-
 2704    current_prolog_flag(verbose, silent),
 2705    !.
 2706print_system_message(_, _, []) :- !.
 2707print_system_message(Term, Kind, Lines) :-
 2708    catch(flush_output(user_output), _, true),      % may not exist
 2709    source_location(File, Line),
 2710    Term \= error(syntax_error(_), _),
 2711    msg_property(Kind, location_prefix(File:Line, LocPrefix, LinePrefix)),
 2712    !,
 2713    to_list(LocPrefix, LocPrefixL),
 2714    insert_prefix(Lines, LinePrefix, Ctx, PrefixLines),
 2715    '$append'([ [begin(Kind, Ctx)],
 2716                LocPrefixL,
 2717                [nl],
 2718                PrefixLines,
 2719                [end(Ctx)]
 2720              ],
 2721              AllLines),
 2722    msg_property(Kind, stream(Stream)),
 2723    ignore(stream_property(Stream, position(Pos))),
 2724    print_message_lines(Stream, AllLines),
 2725    (   \+ stream_property(Stream, position(Pos)),
 2726        msg_property(Kind, wait(Wait)),
 2727        Wait > 0
 2728    ->  sleep(Wait)
 2729    ;   true
 2730    ).
 2731print_system_message(_, Kind, Lines) :-
 2732    msg_property(Kind, stream(Stream)),
 2733    print_message_lines(Stream, kind(Kind), Lines).
 2734
 2735to_list(ListIn, List) :-
 2736    is_list(ListIn),
 2737    !,
 2738    List = ListIn.
 2739to_list(NonList, [NonList]).
 2740
 2741:- multifile
 2742    user:message_property/2. 2743
 2744msg_property(Kind, Property) :-
 2745    notrace(user:message_property(Kind, Property)),
 2746    !.
 2747msg_property(Kind, prefix(Prefix)) :-
 2748    msg_prefix(Kind, Prefix),
 2749    !.
 2750msg_property(_, prefix('~N')) :- !.
 2751msg_property(query, color_class(Class)) :-
 2752    !,
 2753    '$answer_class'(Class).
 2754msg_property(query, stream(user_output)) :- !.
 2755msg_property(_, stream(user_error)) :- !.
 2756msg_property(error, tag('ERROR')).
 2757msg_property(warning, tag('Warning')).
 2758msg_property(Level,
 2759             location_prefix(File:Line,
 2760                             ['~N~w: '-[Tag], url(File:Line), ':'],
 2761                             '~N~w:    '-[Tag])) :-
 2762    include_msg_location(Level),
 2763    msg_property(Level, tag(Tag)).
 2764msg_property(error,   wait(0.1)) :- !.
 2765
 2766include_msg_location(warning).
 2767include_msg_location(error).
 2768
 2769msg_prefix(debug(_), Prefix) :-
 2770    msg_context('~N% ', Prefix).
 2771msg_prefix(Level, Prefix) :-
 2772    msg_property(Level, tag(Tag)),
 2773    atomics_to_string(['~N', Tag, ': '], Prefix0),
 2774    msg_context(Prefix0, Prefix).
 2775msg_prefix(informational, '~N% ').
 2776msg_prefix(information,   '~N% ').
 msg_context(+Prefix0, -Prefix) is det
Add contextual information to a message. This uses the Prolog flag message_context. Recognised context terms are:

In addition, the hook message_prefix_hook/2 is called that allows for additional context information.

 2790msg_context(Prefix0, Prefix) :-
 2791    current_prolog_flag(message_context, Context),
 2792    is_list(Context),
 2793    !,
 2794    add_message_context(Context, Prefix0, Prefix).
 2795msg_context(Prefix, Prefix).
 2796
 2797add_message_context([], Prefix, Prefix).
 2798add_message_context([H|T], Prefix0, Prefix) :-
 2799    (   add_message_context1(H, Prefix0, Prefix1)
 2800    ->  true
 2801    ;   Prefix1 = Prefix0
 2802    ),
 2803    add_message_context(T, Prefix1, Prefix).
 2804
 2805add_message_context1(Context, Prefix0, Prefix) :-
 2806    prolog:message_prefix_hook(Context, Extra),
 2807    atomics_to_string([Prefix0, Extra, ' '], Prefix).
 2808add_message_context1(time, Prefix0, Prefix) :-
 2809    get_time(Now),
 2810    format_time(string(S), '%T.%3f ', Now),
 2811    string_concat(Prefix0, S, Prefix).
 2812add_message_context1(time(Format), Prefix0, Prefix) :-
 2813    get_time(Now),
 2814    format_time(string(S), Format, Now),
 2815    atomics_to_string([Prefix0, S, ' '], Prefix).
 2816add_message_context1(thread, Prefix0, Prefix) :-
 2817    \+ current_prolog_flag(toplevel_thread, true),
 2818    thread_self(Id0),
 2819    !,
 2820    (   atom(Id0)
 2821    ->  Id = Id0
 2822    ;   thread_property(Id0, id(Id))
 2823    ),
 2824    format(string(Prefix), '~w[Thread ~w] ', [Prefix0, Id]).
 print_message_lines(+Stream, +PrefixOrKind, +Lines)
Quintus compatibility predicate to print message lines using a prefix.

If PrefixOrKind is kind(Kind), the message as a whole may be decorated. To this end the lines are wrapped in begin(Class, Ctx) and end(Ctx), where Class is derived from Kind using msg_color_class/2. Ctx is a variable that is bound by whoever implements prolog:message_line_element/2 for begin/2 (normally library(ansi_term)) and remains unbound if the decoration is not available, e.g., because Stream is not a terminal.

The elements that need Ctx are rewritten by prefix_nl/4 to carry it. See there for the details.

 2842print_message_lines(Stream, kind(Kind), Lines) :-
 2843    !,
 2844    msg_property(Kind, prefix(Prefix)),
 2845    msg_color_class(Kind, Class),
 2846    insert_prefix(Lines, Prefix, Ctx, PrefixLines),
 2847    '$append'([ begin(Class, Ctx)
 2848              | PrefixLines
 2849              ],
 2850              [ end(Ctx)
 2851              ],
 2852              AllLines),
 2853    print_message_lines(Stream, AllLines).
 2854print_message_lines(Stream, Prefix, Lines) :-
 2855    insert_prefix(Lines, Prefix, _, PrefixLines),
 2856    print_message_lines(Stream, PrefixLines).
 msg_color_class(+Kind, -Class) is det
Colour class used to decorate an entire message of the given Kind. Defaults to Kind itself, which is mapped to message(Kind) (see level_attrs/2).
 2864msg_color_class(Kind, Class) :-
 2865    msg_property(Kind, color_class(Class0)),
 2866    !,
 2867    Class = Class0.
 2868msg_color_class(Kind, Kind).
 insert_prefix(+Lines, +Prefix, ?Ctx, -PrefixedLines) is det
Add Prefix to the start of each line of Lines. If the first element is at_same_line the message continues the line and no initial prefix is added. Ctx is the message context; see prefix_nl/4 and print_message_lines/3.
 2877insert_prefix([at_same_line|Lines0], Prefix, Ctx, Lines) :-
 2878    !,
 2879    prefix_nl(Lines0, Prefix, Ctx, Lines).
 2880insert_prefix(Lines0, Prefix, Ctx, [prefix(Prefix)|Lines]) :-
 2881    prefix_nl(Lines0, Prefix, Ctx, Lines).
 prefix_nl(+Lines, +Prefix, ?Ctx, -Lines) is det
Insert Prefix after each nl and make the message context Ctx available to the elements that need it:

The last line of a message is ended implicitly: if Lines does not end in nl or flush an nl is added. This one does not paint: what follows the message is not part of it. A message that wants its last line painted ends it using eol.

 2903prefix_nl([], _, _, [nl]).
 2904prefix_nl([nl], _, Ctx, [nl(Ctx)]) :- !.
 2905prefix_nl([flush], _, Ctx, [flush(Ctx)]) :- !.
 2906prefix_nl([nl|T0], Prefix, Ctx, [nl(Ctx), prefix(Prefix)|T]) :-
 2907    !,
 2908    prefix_nl(T0, Prefix, Ctx, T).
 2909prefix_nl([flush|T0], Prefix, Ctx, [flush(Ctx)|T]) :-
 2910    !,
 2911    prefix_nl(T0, Prefix, Ctx, T).
 2912prefix_nl([eol|T0], Prefix, Ctx, [eol(Ctx)|T]) :-
 2913    !,
 2914    prefix_nl(T0, Prefix, Ctx, T).
 2915prefix_nl([ansi(Attrs,Fmt,Args)|T0], Prefix, Ctx,
 2916          [ansi(Attrs,Fmt,Args,Ctx)|T]) :-
 2917    !,
 2918    prefix_nl(T0, Prefix, Ctx, T).
 2919prefix_nl([url(URL,ansi(Attrs,Fmt,Args))|T0], Prefix, Ctx,
 2920          [url(URL,ansi(Attrs,Fmt,Args,Ctx))|T]) :-
 2921    !,
 2922    prefix_nl(T0, Prefix, Ctx, T).
 2923prefix_nl([H|T0], Prefix, Ctx, [H|T]) :-
 2924    prefix_nl(T0, Prefix, Ctx, T).
 print_message_lines(+Stream, +Lines)
 2928print_message_lines(Stream, Lines) :-
 2929    with_output_to(
 2930        Stream,
 2931        notrace(print_message_lines_guarded(current_output, Lines))).
 2932
 2933print_message_lines_guarded(_, []) :- !.
 2934print_message_lines_guarded(S, [H|T]) :-
 2935    line_element(S, H),
 2936    print_message_lines_guarded(S, T).
 2937
 2938line_element(S, E) :-
 2939    prolog:message_line_element(S, E),
 2940    !.
 2941line_element(S, full_stop) :-
 2942    !,
 2943    '$put_token'(S, '.').           % insert space if needed.
 2944line_element(S, nl) :-
 2945    !,
 2946    nl(S).
 2947line_element(S, nl(_Ctx)) :-
 2948    !,
 2949    nl(S).
 2950line_element(S, flush(_Ctx)) :-
 2951    !,
 2952    flush_output(S).
 2953line_element(_, eol(_Ctx)) :- !.
 2954line_element(S, prefix(Fmt-Args)) :-
 2955    !,
 2956    safe_format(S, Fmt, Args).
 2957line_element(S, prefix(Fmt)) :-
 2958    !,
 2959    safe_format(S, Fmt, []).
 2960line_element(S, flush) :-
 2961    !,
 2962    flush_output(S).
 2963line_element(S, Fmt-Args) :-
 2964    !,
 2965    safe_format(S, Fmt, Args).
 2966line_element(S, ansi(_, Fmt, Args)) :-
 2967    !,
 2968    safe_format(S, Fmt, Args).
 2969line_element(S, ansi(_, Fmt, Args, _Ctx)) :-
 2970    !,
 2971    safe_format(S, Fmt, Args).
 2972line_element(S, url(URL)) :-
 2973    !,
 2974    print_link(S, URL).
 2975line_element(S, url(_URL, Label)) :-
 2976    !,
 2977    link_label(Label, Fmt, Args),
 2978    safe_format(S, Fmt, Args).
 2979line_element(_, begin(_Level, _Ctx)) :- !.
 2980line_element(_, end(_Ctx)) :- !.
 2981line_element(S, Fmt) :-
 2982    safe_format(S, Fmt, []).
 2983
 2984print_link(S, File:Line:Column) :-
 2985    !,
 2986    safe_format(S, '~w:~d:~d', [File, Line, Column]).
 2987print_link(S, File:Line) :-
 2988    !,
 2989    safe_format(S, '~w:~d', [File, Line]).
 2990print_link(S, File) :-
 2991    safe_format(S, '~w', [File]).
 link_label(+Label, -Format, -Args) is det
Decompose the label of an url/2 message element. See url/2 in print_message_lines/3. Note that a plain label is text rather than a format: it typically holds a file name, which may contain ~.
 2999:- public
 3000    link_label/3. 3001
 3002link_label(Fmt-Args, Fmt, Args) :-
 3003    atom(Fmt),
 3004    is_list(Args),
 3005    !.
 3006link_label(ansi(_Class, Fmt, Args), Fmt, Args) :- !.
 3007link_label(ansi(_Class, Fmt, Args, _Ctx), Fmt, Args) :- !.
 3008link_label(Text, '~w', [Text]).
 safe_format(+Stream, +Format, +Args) is det
 3012safe_format(S, Fmt, Args) :-
 3013    E = error(_,_),
 3014    catch(format(S,Fmt,Args), E,
 3015          format_failed(S,Fmt,Args,E)).
 3016
 3017format_failed(S, _Fmt, _Args, E) :-
 3018    stream_property(S, error(true)),
 3019    !,
 3020    throw(E).
 3021format_failed(S, Fmt, Args, error(E,_)) :-
 3022    format(S, '~N    [[ EXCEPTION while printing message ~q~n\c
 3023                        ~7|with arguments ~W:~n\c
 3024                        ~7|raised: ~W~n~4|]]~n',
 3025           [ Fmt,
 3026             Args, [quoted(true), max_depth(10)],
 3027             E, [quoted(true), max_depth(10)]
 3028           ]).
 message_to_string(+Term, -String)
Translate an error term into a string
 3034message_to_string(Term, Str) :-
 3035    translate_message(Term, Actions, []),
 3036    !,
 3037    actions_to_format(Actions, Fmt, Args),
 3038    format(string(Str), Fmt, Args).
 3039
 3040actions_to_format([], '', []) :- !.
 3041actions_to_format([nl(_)|T], Fmt, Args) :-      % see prefix_nl/4
 3042    !,
 3043    actions_to_format([nl|T], Fmt, Args).
 3044actions_to_format([nl], '', []) :- !.
 3045actions_to_format([Term, nl], Fmt, Args) :-
 3046    !,
 3047    actions_to_format([Term], Fmt, Args).
 3048actions_to_format([nl|T], Fmt, Args) :-
 3049    !,
 3050    actions_to_format(T, Fmt0, Args),
 3051    atom_concat('~n', Fmt0, Fmt).
 3052actions_to_format([ansi(_Attrs, Fmt0, Args0)|Tail], Fmt, Args) :-
 3053    !,
 3054    actions_to_format(Tail, Fmt1, Args1),
 3055    atom_concat(Fmt0, Fmt1, Fmt),
 3056    append_args(Args0, Args1, Args).
 3057actions_to_format([url(Pos)|Tail], Fmt, Args) :-
 3058    !,
 3059    actions_to_format(Tail, Fmt1, Args1),
 3060    url_actions_to_format(url(Pos), Fmt1, Args1, Fmt, Args).
 3061actions_to_format([url(URL, Label)|Tail], Fmt, Args) :-
 3062    !,
 3063    actions_to_format(Tail, Fmt1, Args1),
 3064    url_actions_to_format(url(URL, Label), Fmt1, Args1, Fmt, Args).
 3065actions_to_format([Fmt0-Args0|Tail], Fmt, Args) :-
 3066    !,
 3067    actions_to_format(Tail, Fmt1, Args1),
 3068    atom_concat(Fmt0, Fmt1, Fmt),
 3069    append_args(Args0, Args1, Args).
 3070actions_to_format([Skip|T], Fmt, Args) :-
 3071    action_skip(Skip),
 3072    !,
 3073    actions_to_format(T, Fmt, Args).
 3074actions_to_format([Term|Tail], Fmt, Args) :-
 3075    atomic(Term),
 3076    !,
 3077    actions_to_format(Tail, Fmt1, Args),
 3078    atom_concat(Term, Fmt1, Fmt).
 3079actions_to_format([Term|Tail], Fmt, Args) :-
 3080    actions_to_format(Tail, Fmt1, Args1),
 3081    atom_concat('~w', Fmt1, Fmt),
 3082    append_args([Term], Args1, Args).
 3083
 3084action_skip(at_same_line).
 3085action_skip(flush).
 3086action_skip(flush(_Ctx)).
 3087action_skip(eol).
 3088action_skip(eol(_Ctx)).
 3089action_skip(begin(_Level, _Ctx)).
 3090action_skip(end(_Ctx)).
 3091
 3092url_actions_to_format(url(File:Line:Column), Fmt1, Args1, Fmt, Args) :-
 3093    !,
 3094    atom_concat('~w:~d:~d', Fmt1, Fmt),
 3095    append_args([File,Line,Column], Args1, Args).
 3096url_actions_to_format(url(File:Line), Fmt1, Args1, Fmt, Args) :-
 3097    !,
 3098    atom_concat('~w:~d', Fmt1, Fmt),
 3099    append_args([File,Line], Args1, Args).
 3100url_actions_to_format(url(File), Fmt1, Args1, Fmt, Args) :-
 3101    !,
 3102    atom_concat('~w', Fmt1, Fmt),
 3103    append_args([File], Args1, Args).
 3104url_actions_to_format(url(_URL, Label), Fmt1, Args1, Fmt, Args) :-
 3105    !,
 3106    link_label(Label, Fmt0, Args0),
 3107    atom_concat(Fmt0, Fmt1, Fmt),
 3108    append_args(Args0, Args1, Args).
 3109
 3110
 3111append_args(M:Args0, Args1, M:Args) :-
 3112    !,
 3113    strip_module(Args1, _, A1),
 3114    to_list(Args0, Args01),
 3115    '$append'(Args01, A1, Args).
 3116append_args(Args0, Args1, Args) :-
 3117    strip_module(Args1, _, A1),
 3118    to_list(Args0, Args01),
 3119    '$append'(Args01, A1, Args).
 3120
 3121                 /*******************************
 3122                 *    MESSAGES TO PRINT ONCE    *
 3123                 *******************************/
 3124
 3125:- dynamic
 3126    printed/2.
 print_once(Message, Level)
True for messages that must be printed only once.
 3132print_once(compatibility(_), _).
 3133print_once(null_byte_in_path(_), _).
 3134print_once(deprecated(_), _).
 must_print(+Level, +Message)
True if the message must be printed.
 3140must_print(Level, Message) :-
 3141    nonvar(Message),
 3142    print_once(Message, Level),
 3143    !,
 3144    \+ printed(Message, Level),
 3145    assert(printed(Message, Level)).
 3146must_print(_, _)