View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2004-2021, University of Amsterdam
    7                              VU University Amsterdam
    8                              SWI-Prolog Solutions b.v.
    9    All rights reserved.
   10
   11    Redistribution and use in source and binary forms, with or without
   12    modification, are permitted provided that the following conditions
   13    are met:
   14
   15    1. Redistributions of source code must retain the above copyright
   16       notice, this list of conditions and the following disclaimer.
   17
   18    2. Redistributions in binary form must reproduce the above copyright
   19       notice, this list of conditions and the following disclaimer in
   20       the documentation and/or other materials provided with the
   21       distribution.
   22
   23    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   24    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   25    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   26    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   27    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   28    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   29    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   30    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   31    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   32    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   33    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   34    POSSIBILITY OF SUCH DAMAGE.
   35*/
   36
   37:- module(prolog_stack,
   38          [ get_prolog_backtrace/2,     % +MaxDepth, -Stack
   39            get_prolog_backtrace/3,     % +MaxDepth, -Stack, +Options
   40            prolog_stack_frame_property/2, % +Frame, ?Property
   41            print_prolog_backtrace/2,   % +Stream, +Stack
   42            print_prolog_backtrace/3,   % +Stream, +Stack, +Options
   43            backtrace/1,                % +MaxDepth
   44            print_last_choicepoint/0,
   45            print_last_choicepoint/2    % +Choice, +Options
   46          ]).   47:- autoload(library(debug),[debug/3]).   48:- autoload(library(error),[must_be/2]).   49:- autoload(library(lists),[nth1/3,append/3]).   50:- autoload(library(option),[option/2,option/3,merge_options/3]).   51:- autoload(library(prolog_clause),
   52	    [clause_name/2,predicate_name/2,clause_info/4]).   53
   54
   55:- dynamic stack_guard/1.   56:- multifile stack_guard/1.   57
   58:- predicate_options(print_prolog_backtrace/3, 3,
   59                     [ subgoal_positions(boolean)
   60                     ]).   61
   62/** <module> Examine the Prolog stack
   63
   64This module defines  high-level  primitives   for  examining  the Prolog
   65stack,  primarily  intended  to  support   debugging.  It  provides  the
   66following functionality:
   67
   68    * get_prolog_backtrace/2 gets a Prolog representation of the
   69    Prolog stack.  This can be used for printing, but also to enrich
   70    exceptions using prolog_exception_hook/4.  Decorating exceptions
   71    is provided by this library and controlled by the hook
   72    stack_guard/1.
   73
   74    * print_prolog_backtrace/2 prints a backtrace as returned by
   75    get_prolog_backtrace/2
   76
   77    * The shorthand backtrace/1 fetches and prints a backtrace.
   78
   79This library may be enabled by default to improve interactive debugging,
   80for example by adding the lines   below  to your ``<config>/init.pl`` to
   81decorate uncaught exceptions:
   82
   83  ==
   84  :- use_module(library(prolog_stack)).
   85  ==
   86
   87@bug    Use of this library may negatively impact performance of
   88        applications that process (error-)exceptions frequently
   89        as part of their normal processing.
   90*/
   91
   92:- create_prolog_flag(backtrace,            true, [type(boolean), keep(true)]).   93:- create_prolog_flag(backtrace_depth,      20,   [type(integer), keep(true)]).   94:- create_prolog_flag(backtrace_goal_depth, 3,    [type(integer), keep(true)]).   95:- create_prolog_flag(backtrace_show_lines, true, [type(boolean), keep(true)]).   96
   97%!  get_prolog_backtrace(+MaxDepth, -Backtrace) is det.
   98%!  get_prolog_backtrace(+MaxDepth, -Backtrace, +Options) is det.
   99%
  100%   Obtain a backtrace from the current location. The backtrace is a
  101%   list of frames. Each  frame  is  an   opaque  term  that  can be
  102%   inspected using the predicate  prolog_stack_frame_property/2 can
  103%   be used to extract  information  from   these  frames.  Most use
  104%   scenarios will pass the stack   to print_prolog_backtrace/2. The
  105%   following options are provided:
  106%
  107%     * frame(+Frame)
  108%     Start at Frame instead of the current frame.
  109%     * goal_term_depth(+Depth)
  110%     If Depth > 0, include a shallow copy of the goal arguments
  111%     into the stack.  Default is set by the Prolog flag
  112%     `backtrace_goal_depth`, set to `3` initially, showing the
  113%     goal and toplevel of any argument.
  114%     * guard(+Guard)
  115%     Do not show stack frames above Guard.  See stack_guard/1.
  116%     * clause_references(+Bool)
  117%     Report locations as `Clause+PC` or as a location term that
  118%     does not use clause references, allowing the exception to
  119%     be printed safely in a different context.
  120%
  121%   @param Frame is the frame to start from. See prolog_current_frame/1.
  122%   @param MaxDepth defines the maximum number of frames returned.
  123%   @compat get_prolog_backtrace/3 used to have the parameters
  124%   +Frame, +MaxDepth, -Backtrace. A call that matches this
  125%   signature is mapped to get_prolog_backtrace(MaxDepth, Backtrace,
  126%   [frame(Frame)]).
  127
  128get_prolog_backtrace(MaxDepth, Stack) :-
  129    get_prolog_backtrace(MaxDepth, Stack, []).
  130
  131get_prolog_backtrace(Fr, MaxDepth, Stack) :-
  132    integer(Fr), integer(MaxDepth), var(Stack),
  133    !,
  134    get_prolog_backtrace_lc(MaxDepth, Stack, [frame(Fr)]),
  135    nlc.
  136get_prolog_backtrace(MaxDepth, Stack, Options) :-
  137    get_prolog_backtrace_lc(MaxDepth, Stack, Options),
  138    nlc.            % avoid last-call-optimization, such that
  139                        % the top of the stack is always a nice Prolog
  140                        % frame
  141
  142nlc.
  143
  144get_prolog_backtrace_lc(MaxDepth, Stack, Options) :-
  145    (   option(frame(Fr), Options)
  146    ->  PC = call
  147    ;   prolog_current_frame(Fr0),
  148        prolog_frame_attribute(Fr0, pc, PC),
  149        prolog_frame_attribute(Fr0, parent, Fr)
  150    ),
  151    (   option(goal_term_depth(GoalDepth), Options)
  152    ->  true
  153    ;   current_prolog_flag(backtrace_goal_depth, GoalDepth)
  154    ),
  155    option(guard(Guard), Options, none),
  156    (   def_no_clause_refs(Guard)
  157    ->  DefClauseRefs = false
  158    ;   DefClauseRefs = true
  159    ),
  160    option(clause_references(ClauseRefs), Options, DefClauseRefs),
  161    must_be(nonneg, GoalDepth),
  162    backtrace(MaxDepth, Fr, PC, GoalDepth, Guard, ClauseRefs, Stack, Options).
  163
  164def_no_clause_refs(system:catch_with_backtrace/3).
  165
  166backtrace(0, _, _, _, _, _, [], _) :- !.
  167backtrace(MaxDepth, Fr, PC, GoalDepth, Guard, ClauseRefs,
  168          [frame(Level, Where, Goal)|Stack], Options) :-
  169    prolog_frame_attribute(Fr, level, Level),
  170    (   PC == foreign
  171    ->  prolog_frame_attribute(Fr, predicate_indicator, Pred),
  172        Where = foreign(Pred)
  173    ;   PC == call
  174    ->  prolog_frame_attribute(Fr, predicate_indicator, Pred),
  175        Where = call(Pred)
  176    ;   prolog_frame_attribute(Fr, clause, Clause)
  177    ->  clause_where(ClauseRefs, Clause, PC, Where, Options)
  178    ;   Where = meta_call
  179    ),
  180    (   Where == meta_call
  181    ->  Goal = 0
  182    ;   copy_goal(GoalDepth, Fr, Goal)
  183    ),
  184    (   prolog_frame_attribute(Fr, pc, PC2)
  185    ->  true
  186    ;   PC2 = foreign
  187    ),
  188    (   prolog_frame_attribute(Fr, parent, Parent),
  189        prolog_frame_attribute(Parent, predicate_indicator, PI),
  190        PI == Guard                             % last frame
  191    ->  backtrace(1, Parent, PC2, GoalDepth, Guard, ClauseRefs, Stack, Options)
  192    ;   prolog_frame_attribute(Fr, parent, Parent),
  193        more_stack(Parent)
  194    ->  D2 is MaxDepth - 1,
  195        backtrace(D2, Parent, PC2, GoalDepth, Guard, ClauseRefs, Stack, Options)
  196    ;   Stack = []
  197    ).
  198
  199more_stack(Parent) :-
  200    prolog_frame_attribute(Parent, predicate_indicator, PI),
  201    \+ (   PI = ('$toplevel':G),
  202           G \== (toplevel_call/1)
  203       ),
  204    !.
  205more_stack(_) :-
  206    current_prolog_flag(break_level, Break),
  207    Break >= 1.
  208
  209%!  clause_where(+UseClauseRef, +Clause, +PC, -Where, +Options) is det.
  210%
  211%   Get a description of the frame source   location from Clause and the
  212%   PC inside clause. If UseClauseRef is  `true`,   this  is  the a term
  213%   clause(Clause,PC),  providing  all  abvailable  information  to  the
  214%   caller at low time overhead. If  however   the  exception need to be
  215%   printed in an environment where the   clause  references may differ,
  216%   for example because the program is not   loaded,  it is printed in a
  217%   different thread and contains references to dynamic predicates, etc,
  218%   it is better to use the information inside the clause here.
  219
  220clause_where(true, Clause, PC, clause(Clause, PC), _).
  221clause_where(false, Clause, PC, pred_line(PredName, File:Line), Options) :-
  222    option(subgoal_positions(true), Options, true),
  223    subgoal_position(Clause, PC, File, CharA, _CharZ),
  224    File \= @(_),                 % XPCE Object reference
  225    lineno(File, CharA, Line),
  226    clause_predicate_name(Clause, PredName),
  227    !.
  228clause_where(false, Clause, _PC, pred_line(PredName, File:Line), _Options) :-
  229    clause_property(Clause, file(File)),
  230    clause_property(Clause, line_count(Line)),
  231    clause_predicate_name(Clause, PredName),
  232    !.
  233clause_where(false, Clause, _PC, clause_name(ClauseName), _Options) :-
  234    clause_name(Clause, ClauseName).
  235
  236%!  copy_goal(+TermDepth, +Frame, -Goal) is det.
  237%
  238%   Create a shallow copy of the frame's  goal to help debugging. In
  239%   addition to shallow copying, high-arity   terms  are represented
  240%   as below.  Currently the 16 first arguments are hardcoded.
  241%
  242%     ==
  243%     name(A1, ..., A16, <skipped Skipped of Arity>, An)
  244%     ==
  245
  246copy_goal(0, _, 0) :- !.                        % 0 is not a valid goal
  247copy_goal(D, Fr, Goal) :-
  248    prolog_frame_attribute(Fr, goal, Goal0),
  249    (   Goal0 = Module:Goal1
  250    ->  copy_term_limit(D, Goal1, Goal2),
  251        (   hidden_module(Module)
  252        ->  Goal = Goal2
  253        ;   Goal = Module:Goal2
  254        )
  255    ;   copy_term_limit(D, Goal0, Goal)
  256    ).
  257
  258hidden_module(system).
  259hidden_module(user).
  260
  261copy_term_limit(0, In, '...') :-
  262    compound(In),
  263    !.
  264copy_term_limit(N, In, Out) :-
  265    is_dict(In),
  266    !,
  267    dict_pairs(In, Tag, PairsIn),
  268    N2 is N - 1,
  269    MaxArity = 16,
  270    copy_pairs(PairsIn, N2, MaxArity, PairsOut),
  271    dict_pairs(Out, Tag, PairsOut).
  272copy_term_limit(N, In, Out) :-
  273    compound(In),
  274    !,
  275    compound_name_arity(In, Functor, Arity),
  276    N2 is N - 1,
  277    MaxArity = 16,
  278    (   Arity =< MaxArity
  279    ->  compound_name_arity(Out, Functor, Arity),
  280        copy_term_args(0, Arity, N2, In, Out)
  281    ;   OutArity is MaxArity+2,
  282        compound_name_arity(Out, Functor, OutArity),
  283        copy_term_args(0, MaxArity, N2, In, Out),
  284        SkipArg is MaxArity+1,
  285        Skipped is Arity - MaxArity - 1,
  286        format(atom(Msg), '<skipped ~D of ~D>', [Skipped, Arity]),
  287        arg(SkipArg, Out, Msg),
  288        arg(Arity, In, InA),
  289        arg(OutArity, Out, OutA),
  290        copy_term_limit(N2, InA, OutA)
  291    ).
  292copy_term_limit(_, In, Out) :-
  293    copy_term_nat(In, Out).
  294
  295copy_term_args(I, Arity, Depth, In, Out) :-
  296    I < Arity,
  297    !,
  298    I2 is I + 1,
  299    arg(I2, In, InA),
  300    arg(I2, Out, OutA),
  301    copy_term_limit(Depth, InA, OutA),
  302    copy_term_args(I2, Arity, Depth, In, Out).
  303copy_term_args(_, _, _, _, _).
  304
  305copy_pairs([], _, _, []) :- !.
  306copy_pairs(Pairs, _, 0, ['<skipped>'-Skipped]) :-
  307    !,
  308    length(Pairs, Skipped).
  309copy_pairs([K-V0|T0], N, MaxArity, [K-V|T]) :-
  310    copy_term_limit(N, V0, V),
  311    MaxArity1 is MaxArity - 1,
  312    copy_pairs(T0, N, MaxArity1, T).
  313
  314
  315%!  prolog_stack_frame_property(+Frame, ?Property) is nondet.
  316%
  317%   True when Property is a property of   Frame. Frame is an element
  318%   of a stack-trace as produced by get_prolog_backtrace/2.  Defined
  319%   properties are:
  320%
  321%     * level(Level)
  322%     * predicate(PI)
  323%     * location(File:Line)
  324
  325prolog_stack_frame_property(frame(Level,_,_), level(Level)).
  326prolog_stack_frame_property(frame(_,Where,_), predicate(PI)) :-
  327    frame_predicate(Where, PI).
  328prolog_stack_frame_property(frame(_,clause(Clause,PC),_), location(File:Line)) :-
  329    subgoal_position(Clause, PC, File, CharA, _CharZ),
  330    File \= @(_),                   % XPCE Object reference
  331    lineno(File, CharA, Line).
  332prolog_stack_frame_property(frame(_,_,_,Goal), goal(Goal)) :-
  333    Goal \== 0.
  334
  335
  336frame_predicate(foreign(PI), PI).
  337frame_predicate(call(PI), PI).
  338frame_predicate(clause(Clause, _PC), PI) :-
  339    clause_property(Clause, PI).
  340
  341default_backtrace_options(Options) :-
  342    (   current_prolog_flag(backtrace_show_lines, true)
  343    ->  Options = []
  344    ;   Options = [subgoal_positions(false)]
  345    ).
  346
  347%!  print_prolog_backtrace(+Stream, +Backtrace) is det.
  348%!  print_prolog_backtrace(+Stream, +Backtrace, +Options) is det.
  349%
  350%   Print a stacktrace in human readable form to Stream.
  351%   Options is an option list that accepts:
  352%
  353%       * subgoal_positions(+Boolean)
  354%       If =true=, print subgoal line numbers.  The default depends
  355%       on the Prolog flag =backtrace_show_lines=.
  356%
  357%   @arg Backtrace is a list of frame(Depth,Location,Goal) terms.
  358
  359print_prolog_backtrace(Stream, Backtrace) :-
  360    print_prolog_backtrace(Stream, Backtrace, []).
  361
  362print_prolog_backtrace(Stream, Backtrace, Options) :-
  363    default_backtrace_options(DefOptions),
  364    merge_options(Options, DefOptions, FinalOptions),
  365    phrase(message(Backtrace, FinalOptions), Lines),
  366    print_message_lines(Stream, '', Lines).
  367
  368:- public                               % Called from some handlers
  369    message//1.  370
  371message(Backtrace) -->
  372    {default_backtrace_options(Options)},
  373    message(Backtrace, Options).
  374
  375message(Backtrace, Options) -->
  376    message_frames(Backtrace, Options),
  377    warn_nodebug(Backtrace).
  378
  379message_frames([], _) -->
  380    [].
  381message_frames([H|T], Options) -->
  382    message_frames(H, Options),
  383    (   {T == []}
  384    ->  []
  385    ;   [nl],
  386        message_frames(T, Options)
  387    ).
  388
  389message_frames(frame(Level, Where, 0), Options) -->
  390    !,
  391    level(Level),
  392    where_no_goal(Where, Options).
  393message_frames(frame(Level, _Where, '$toplevel':toplevel_call(_)), _) -->
  394    !,
  395    level(Level),
  396    [ '<user>'-[] ].
  397message_frames(frame(Level, Where, Goal), Options) -->
  398    level(Level),
  399    [ ansi(code, '~p', [Goal]) ],
  400    where_goal(Where, Options).
  401
  402where_no_goal(foreign(PI), _) -->
  403    [ '~w <foreign>'-[PI] ].
  404where_no_goal(call(PI), _) -->
  405    [ '~w'-[PI] ].
  406where_no_goal(pred_line(PredName, File:Line), _) -->
  407    !,
  408    [ '~w at '-[PredName], url(File:Line) ].
  409where_no_goal(clause_name(ClauseName), _) -->
  410    !,
  411    [ '~w <no source>'-[ClauseName] ].
  412where_no_goal(clause(Clause, PC), Options) -->
  413    { nonvar(Clause),
  414      !,
  415      clause_where(false, Clause, PC, Where, Options)
  416    },
  417    where_no_goal(Where, Options).
  418where_no_goal(meta_call, _) -->
  419    [ '<meta call>' ].
  420
  421where_goal(foreign(_), _) -->
  422    [ ' <foreign>'-[] ],
  423    !.
  424where_goal(pred_line(_PredName, File:Line), _) -->
  425    !,
  426    [ ' at ', url(File:Line) ].
  427where_goal(clause_name(ClauseName), _) -->
  428    !,
  429    [ '~w <no source>'-[ClauseName] ].
  430where_goal(clause(Clause, PC), Options) -->
  431    { nonvar(Clause),
  432      !,
  433      clause_where(false, Clause, PC, Where, Options)
  434    },
  435    where_goal(Where, Options).
  436where_goal(clause(Clause, _PC), _) -->
  437    { clause_property(Clause, file(File)),
  438      clause_property(Clause, line_count(Line))
  439    },
  440    !,
  441    [ ' at ', url(File:Line) ].
  442where_goal(clause(Clause, _PC), _) -->
  443    { clause_name(Clause, ClauseName)
  444    },
  445    !,
  446    [ ' ~w <no source>'-[ClauseName] ].
  447where_goal(_, _) -->
  448    [].
  449
  450level(Level) -->
  451    [ '~|~t[~D]~6+ '-[Level] ].
  452
  453warn_nodebug(Backtrace) -->
  454    { contiguous(Backtrace) },
  455    !.
  456warn_nodebug(_Backtrace) -->
  457    [ nl,nl,
  458      'Note: some frames are missing due to last-call optimization.'-[], nl,
  459      'Re-run your program in debug mode (:- debug.) to get more detail.'-[]
  460    ].
  461
  462contiguous([frame(D0,_,_)|Frames]) :-
  463    contiguous(Frames, D0).
  464
  465contiguous([], _).
  466contiguous([frame(D1,_,_)|Frames], D0) :-
  467    D1 =:= D0-1,
  468    contiguous(Frames, D1).
  469
  470
  471%!  clause_predicate_name(+ClauseRef, -Predname) is det.
  472%
  473%   Produce a name (typically  Functor/Arity)   for  a  predicate to
  474%   which Clause belongs.
  475
  476clause_predicate_name(Clause, PredName) :-
  477    user:prolog_clause_name(Clause, PredName),
  478    !.
  479clause_predicate_name(Clause, PredName) :-
  480    nth_clause(Head, _N, Clause),
  481    !,
  482    predicate_name(user:Head, PredName).
  483
  484
  485%!  backtrace(+MaxDepth)
  486%
  487%   Get and print a stacktrace to the user_error stream.
  488
  489backtrace(MaxDepth) :-
  490    get_prolog_backtrace_lc(MaxDepth, Stack, []),
  491    print_prolog_backtrace(user_error, Stack).
  492
  493
  494subgoal_position(ClauseRef, PC, File, CharA, CharZ) :-
  495    debug(backtrace, 'Term-position in ~p at PC=~w:', [ClauseRef, PC]),
  496    clause_info(ClauseRef, File, TPos, _),
  497    '$clause_term_position'(ClauseRef, PC, List),
  498    debug(backtrace, '\t~p~n', [List]),
  499    find_subgoal(List, TPos, PosTerm),
  500    arg(1, PosTerm, CharA),
  501    arg(2, PosTerm, CharZ).
  502
  503%!  find_subgoal(+PosList, +TermPos, -SubGoalPos).
  504%
  505%   @see Same as find_subgoal/3 in trace.pl from the GUI tracer.
  506
  507find_subgoal(_, Pos, Pos) :-
  508    var(Pos),
  509    !.
  510find_subgoal([A|T], term_position(_, _, _, _, PosL), SPos) :-
  511    nth1(A, PosL, Pos),
  512    !,
  513    find_subgoal(T, Pos, SPos).
  514find_subgoal([1|T], brace_term_position(_,_,Pos), SPos) :-
  515    !,
  516    find_subgoal(T, Pos, SPos).
  517find_subgoal(List, parentheses_term_position(_,_,Pos), SPos) :-
  518    !,
  519    find_subgoal(List, Pos, SPos).
  520find_subgoal(_, Pos, Pos).
  521
  522
  523%!  lineno(+File, +Char, -Line)
  524%
  525%   Translate a character location to  a   line-number.  Note  that this
  526%   calls prolog_clause:try_open_source/2, but this is  always loaded as
  527%   we would not have clause info without.
  528
  529lineno(File, Char, Line) :-
  530    setup_call_cleanup(
  531        ( prolog_clause:try_open_source(File, Fd),
  532          set_stream(Fd, newline(detect))
  533        ),
  534        lineno_(Fd, Char, Line),
  535        close(Fd)).
  536
  537lineno_(Fd, Char, L) :-
  538    stream_property(Fd, position(Pos)),
  539    stream_position_data(char_count, Pos, C),
  540    C > Char,
  541    !,
  542    stream_position_data(line_count, Pos, L0),
  543    L is L0-1.
  544lineno_(Fd, Char, L) :-
  545    skip(Fd, 0'\n),
  546    lineno_(Fd, Char, L).
  547
  548
  549		 /*******************************
  550		 *          CHOICEPOINTS	*
  551		 *******************************/
  552
  553%!  print_last_choicepoint is det.
  554%
  555%   Print details on the last open choice point.
  556
  557print_last_choicepoint :-
  558    prolog_current_choice(ChI0),         % Choice in print_last_choicepoint/0
  559    prolog_choice_attribute(ChI0, parent, ChI1),
  560    print_last_choicepoint(ChI1, []).
  561print_last_choicepoint.
  562
  563%!  print_last_choicepoint(+ChoiceRef, +Options) is det.
  564
  565print_last_choicepoint(ChI1, Options) :-
  566    real_choice(ChI1, ChI),
  567    prolog_choice_attribute(ChI, frame, F),
  568    prolog_frame_attribute(F, goal, Goal),
  569    Goal \= '$execute_goal2'(_,_,_),     % Toplevel REPL choicepoint
  570    !,
  571    option(message_level(Level), Options, warning),
  572    get_prolog_backtrace(2, [_|Stack], [frame(F)]),
  573    (   predicate_property(Goal, foreign)
  574    ->  print_message(Level, choicepoint(foreign(Goal), Stack))
  575    ;   prolog_frame_attribute(F, clause, Clause),
  576        (   prolog_choice_attribute(ChI, pc, PC)
  577        ->  Ctx = jump(PC)
  578        ;   prolog_choice_attribute(ChI, clause, Next)
  579        ->  Ctx = clause(Next)
  580        ),
  581        print_message(Level, choicepoint(clause(Goal, Clause, Ctx), Stack))
  582    ).
  583print_last_choicepoint(_, _).
  584
  585real_choice(Ch0, Ch) :-
  586    prolog_choice_attribute(Ch0, type, Type),
  587    dummy_type(Type),
  588    !,
  589    prolog_choice_attribute(Ch0, parent, Ch1),
  590    real_choice(Ch1, Ch).
  591real_choice(Ch, Ch).
  592
  593dummy_type(debug).
  594dummy_type(none).
  595
  596prolog:message(choicepoint(Choice, Stack)) -->
  597    choice(Choice),
  598    [ nl, 'Called from', nl ],
  599    message(Stack).
  600
  601choice(foreign(Goal)) -->
  602    success_goal(Goal, 'a foreign choice point').
  603choice(clause(Goal, ClauseRef, clause(Next))) -->
  604    success_goal(Goal, 'a choice point in alternate clause'),
  605    [ nl ],
  606    [ '  ' ], clause_descr(ClauseRef), [': clause succeeded', nl],
  607    [ '  ' ], clause_descr(Next),      [': next candidate clause' ].
  608choice(clause(Goal, ClauseRef, jump(PC))) -->
  609    { clause_where(false, ClauseRef, PC, Where,
  610                   [subgoal_positions(true)])
  611    },
  612    success_goal(Goal, 'an in-clause choice point'),
  613    [ nl, '  ' ],
  614    where_no_goal(Where).
  615
  616success_goal(Goal, Reason) -->
  617    [ ansi(code, '~p', [Goal]),
  618      ' left ~w (after success)'-[Reason]
  619    ].
  620
  621where_no_goal(pred_line(_PredName, File:Line)) -->
  622    !,
  623    [ url(File:Line) ].
  624where_no_goal(clause_name(ClauseName)) -->
  625    !,
  626    [ '~w <no source>'-[ClauseName] ].
  627
  628clause_descr(ClauseRef) -->
  629    { clause_property(ClauseRef, file(File)),
  630      clause_property(ClauseRef, line_count(Line))
  631    },
  632    !,
  633    [ url(File:Line) ].
  634clause_descr(ClauseRef) -->
  635    { clause_name(ClauseRef, Name)
  636    },
  637    [ '~w'-[Name] ].
  638
  639
  640                 /*******************************
  641                 *        DECORATE ERRORS       *
  642                 *******************************/
  643
  644%!  prolog_stack:stack_guard(+PI) is semidet.
  645%
  646%   Dynamic multifile hook that is normally not defined. The hook is
  647%   called with PI equal to =none= if   the  exception is not caught
  648%   and with a fully qualified   (e.g., Module:Name/Arity) predicate
  649%   indicator of the predicate that called  catch/3 if the exception
  650%   is caught.
  651%
  652%   The exception is of the form error(Formal, ImplDef) and this
  653%   hook succeeds, ImplDef is unified to a term
  654%   context(prolog_stack(StackData), Message).  This context
  655%   information is used by the message printing system to print a
  656%   human readable representation of the stack when the exception
  657%   was raised.
  658%
  659%   For example, using a clause   stack_guard(none)  prints contexts
  660%   for uncaught exceptions only.  Using   a  clause  stack_guard(_)
  661%   prints a full  stack-trace  for  any   error  exception  if  the
  662%   exception   is   given    to     print_message/2.    See    also
  663%   library(http/http_error), which limits printing of exceptions to
  664%   exceptions in user-code called from the HTTP server library.
  665%
  666%   Details of the exception decoration is  controlled by two Prolog
  667%   flags:
  668%
  669%       * backtrace_depth
  670%       Integer that controls the maximum number of frames
  671%       collected.  Default is 20.  If a guard is specified, callers
  672%       of the guard are removed from the stack-trace.
  673%
  674%       * backtrace_show_lines
  675%       Boolean that indicates whether the library tries to find
  676%       line numbers for the calls.  Default is =true=.
  677
  678:- multifile
  679    user:prolog_exception_hook/4.  680:- dynamic
  681    user:prolog_exception_hook/4.  682
  683user:prolog_exception_hook(error(E, context(Ctx0,Msg)),
  684                           error(E, context(prolog_stack(Stack),Msg)),
  685                           Fr, GuardSpec) :-
  686    current_prolog_flag(backtrace, true),
  687    \+ is_stack(Ctx0, _Frames),
  688    (   atom(GuardSpec)
  689    ->  debug(backtrace, 'Got uncaught (guard = ~q) exception ~p (Ctx0=~p)',
  690              [GuardSpec, E, Ctx0]),
  691        stack_guard(GuardSpec),
  692        Guard = GuardSpec
  693    ;   prolog_frame_attribute(GuardSpec, predicate_indicator, Guard),
  694        debug(backtrace, 'Got exception ~p (Ctx0=~p, Catcher=~p)',
  695              [E, Ctx0, Guard]),
  696        stack_guard(Guard)
  697    ),
  698    (   current_prolog_flag(backtrace_depth, Depth)
  699    ->  Depth > 0
  700    ;   Depth = 20                  % Thread created before lib was loaded
  701    ),
  702    get_prolog_backtrace(Depth, Stack0,
  703                         [ frame(Fr),
  704                           guard(Guard)
  705                         ]),
  706    debug(backtrace, 'Stack = ~p', [Stack0]),
  707    clean_stack(Stack0, Stack1),
  708    join_stacks(Ctx0, Stack1, Stack).
  709
  710clean_stack(List, List) :-
  711    stack_guard(X), var(X),
  712    !.      % Do not stop if we catch all
  713clean_stack(List, Clean) :-
  714    clean_stack2(List, Clean).
  715
  716clean_stack2([], []).
  717clean_stack2([H|_], [H]) :-
  718    guard_frame(H),
  719    !.
  720clean_stack2([H|T0], [H|T]) :-
  721    clean_stack2(T0, T).
  722
  723guard_frame(frame(_,clause(ClauseRef, _, _))) :-
  724    nth_clause(M:Head, _, ClauseRef),
  725    functor(Head, Name, Arity),
  726    stack_guard(M:Name/Arity).
  727
  728join_stacks(Ctx0, Stack1, Stack) :-
  729    nonvar(Ctx0),
  730    Ctx0 = prolog_stack(Stack0),
  731    is_list(Stack0), !,
  732    append(Stack0, Stack1, Stack).
  733join_stacks(_, Stack, Stack).
  734
  735
  736%!  stack_guard(+Reason) is semidet.
  737%
  738%   Dynamic multifile predicate. It is called  with `none`, `'C'` or
  739%   the predicate indicator of the   _guard_,  the predicate calling
  740%   catch/3. The exception must be of   _compatible_  with the shape
  741%   error(Formal, context(Stack, Msg)). The  default   is  to  catch
  742%   `none`, uncaught exceptions. `'C'`  implies   that  the callback
  743%   from C will handle the exception.
  744
  745stack_guard(none).
  746stack_guard(system:catch_with_backtrace/3).
  747
  748
  749                 /*******************************
  750                 *           MESSAGES           *
  751                 *******************************/
  752
  753:- multifile
  754    prolog:message//1.  755
  756prolog:message(error(Error, context(Stack, Message))) -->
  757    { Message \== 'DWIM could not correct goal',
  758      is_stack(Stack, Frames)
  759    },
  760    !,
  761    '$messages':translate_message(error(Error, context(_, Message))),
  762    [ nl, 'In:', nl ],
  763    (   {is_list(Frames)}
  764    ->  message(Frames)
  765    ;   ['~w'-[Frames]]
  766    ).
  767
  768is_stack(Stack, Frames) :-
  769    nonvar(Stack),
  770    Stack = prolog_stack(Frames)