/* yForth? - A Forth interpreter written in ANSI C
 * Copyright (C) 2012 Luca Padovani
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * ------------------------------------------------------------------------
 * Module name:     exceptio.c
 * Abstract:        exception word set
 */

#include <malloc.h>
#include <setjmp.h>
#include "yforth.h"
#include "core.h"
#include "exceptio.h"

/**************************************************************************/
/* VARIABLES **************************************************************/
/**************************************************************************/

struct exception_frame *top_frame;  /* ptr to the top of exception stack */

/**************************************************************************/
/* WORDS ******************************************************************/
/**************************************************************************/

void _catch() {
	register struct exception_frame *frame =
		(struct exception_frame *) malloc(sizeof(struct exception_frame));
	if (frame) {
		register int ret_val;
		if ((ret_val = setjmp(frame->catch_buf)) == 0) {
            /* Executed when "catch" is invoked */
			save_input_specification();
			frame->sp = sp + 1;
			frame->rp = rp;
			frame->bp = bp;
			frame->fp = fp;
			frame->last = top_frame;
			top_frame = frame;
			exec_word((struct word_def *) *sp++);
			*--sp = 0;
		} else *--sp = ret_val;
		frame = top_frame;
		sp = frame->sp;
		rp = frame->rp;
		bp = frame->bp;
		top_frame = frame->last;
		free(frame);
		restore_input_specification();
	}
}

void _throw() {
	register Cell n = *sp++;
	if (n) {
		if (top_frame) longjmp(top_frame->catch_buf, n);
		else if (n == -1) ;
		else if (n == -2) _type();
		sp = sp_top;
		longjmp(warm_start_jump, 1);
	}
}

