:- ensure_loaded(common).
cvs_id('$Id: stack.pl,v 1.3 2004/10/21 21:05:19 sandro Exp $').
/*

  Stack-Trace Stuff.

  
*/




stack_trace(Lines) :-
	prolog_current_frame(This),
	prolog_frame_attribute(This, parent, Parent),
	stack_trace(Lines, Parent).
stack_trace([trace_failed]).

stack_trace([Line|Lines], This) :-
	(   prolog_frame_attribute(This, parent, Parent)
	->  stack_trace(Lines, Parent)
	;   true
	),
	stack_frame_line(Line, This).


stack_frame_line(Line, Frame) :-
	prolog_frame_attribute(Frame, goal, Goal),
	prolog_frame_attribute(Frame, level, Level),
	(   prolog_frame_attribute(Frame, clause, Reference)
	->  clause_property(Reference, file(File)),
	    clause_property(Reference, line_count(LineNo))
	;   File='<foreign code>', LineNo=''
	),
	Line = '. frame: ~d ~a:~a ~q~n' - [Level, File, LineNo, Goal].

/*
print_stack_trace :-
	prolog_current_frame(This),
	prolog_frame_attribute(This, parent, Parent),
	print_stack_trace(Parent).

print_stack_trace(This) :-
	(   prolog_frame_attribute(This, parent, Parent)
	->  print_stack_trace(Parent)
	;   true
	),
	stack_frame_print(This).


stack_frame_print(Frame) :-
	prolog_frame_attribute(Frame, goal, Goal),
	prolog_frame_attribute(Frame, level, Level),
	(   prolog_frame_attribute(Frame, clause, Reference)
	->  clause_property(Reference, file(File)),
	    clause_property(Reference, line_count(Line))
	;   File='<foreign code>', Line=''
	),
	format('#~d ~a:~a ~q~n', [Level, File, Line, Goal]).

t1 :- t2.
t2 :- t3.
t3 :- print_stack_trace.
*/
xt1 :- xt2.
xt2 :- xt3.
xt3 :- stack_trace(Lines), print_message_lines(user_error, '', Lines).

print_stack :- stack_trace(Lines), print_message_lines(user_error, '', Lines).