gprolog: Getting a stacktrace after an exception

吃可爱长大的小学妹 提交于 2019-11-26 16:45:29

@gusbro's answer (s(X)) shows you how you somewhat solve this with GNU's debugger. However, if you cannot afford to see all the printing going on, or it is much too slow, you might consider the following "debugger".

I personally do not use debuggers offered by Prolog systems for the simple reason that most of them print much too much, are often buggy themselves, and have their own specific ever changing conventions, I can't afford to learn.

:- op(900, fx, [@,$,$-]).

$-(G_0) :-
   catch(G_0, Ex, ( portray_clause(exception:Ex:G_0), throw(Ex) ) ).

$(G_0) :-
   portray_clause(call:G_0),
   $-G_0,
   portray_clause(exit:G_0).

@(G_0) :-
   (   $-G_0
   *-> true
   ;   portray_clause(badfail:G_0),
       throw(goal_failed(G_0))
   ).

:- op(950, fy, *).
*(_).

To use it, simply add $-, $, or @ in front of a specific goal.

$- means: only signal exceptions going through this goal

$ additionally show call and exit

@ assures that there is at least one answer, and if not, it is reported and an exception is thrown.

Use above annotations sparingly!

* removes the goal. This is for generalizing a program doing program modification/slicing in a pure monotonic program. For examples how to use it, see the following answers/debugging sessions 1, 2, 3, 4, 5, 6, 7, 8.

_/*term*/ replaces a term by an anonymous variable. This generalizes a program even further than * alone. Example sessions: 1, 2, 3, 4, 5, 6, 7, 8.

In this manner you can reduce the information you watch significantly.

In other systems supporting meta_predicate directives like SICStus, YAP and SWI, add in front the following directive:

:- meta_predicate(( $-(0), $(0), @(0) )).

You may trace/0 and leash/1 only the exception port, e.g:

?- trace.
?- leash([exception]).

Then you run your program and it will print a trace on screen but only stop when an exception occurs. There you can see the "stack trace" (ancestors) by pressing letter g.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!