/* GOSUB support */

#include "fb.h"
#include <setjmp.h>

#if defined( _WIN32 ) && defined( __aarch64__ )
void __mingw_longjmp( jmp_buf buf, int value );
#endif

/* slow but easy to manage dynamic GOSUB call-stack */
typedef struct gosubnode {
	jmp_buf buf;
	struct gosubnode *next;
} GOSUBNODE;

/* the gosub context allocated in auto-local storage by the compiler */
typedef struct {
	GOSUBNODE *top;
} GOSUBCTX;

/*
	NOTES:
		On the compiler side, GOSUBCTX is an ANY PTR.  To extend 
		GOSUBCTX, the compiler must allocate additional	space for 
		the GOSUBCTX pseudo-object.

		GOSUBCTX does not have a constructor, but it is expected that
		the compiler will initialize the variable to zero.

		See ast-gosub.bas::astGosubAddInit()
*/


/*:::::*/
FBCALL void * fb_GosubPush( GOSUBCTX * ctx )
{
	GOSUBNODE *node = malloc( sizeof( GOSUBNODE ) );
	if( node == NULL )
		return NULL;
	node->next = ctx->top;
	ctx->top = node;

	/* returns address of ctx->top->buf	*/
	return &(ctx->top->buf);
}

/*:::::*/
FBCALL int fb_GosubPop( GOSUBCTX * ctx )
{
	if( ctx && ctx->top )
	{
		GOSUBNODE *node = ctx->top->next;
		free(ctx->top);
		ctx->top = node;

		/* return success */
		return fb_ErrorSetNum( FB_RTERROR_OK );
	}

	/* don't know where to go next so return an error */
	return fb_ErrorSetNum( FB_RTERROR_RETURNWITHOUTGOSUB );
}

/*:::::*/
FBCALL int fb_GosubReturn( GOSUBCTX * ctx )
{
	if( ctx && ctx->top )
	{
		GOSUBNODE *node = ctx->top->next;
		
		/* TODO: with a different stack allocation strategy, this
		 * temporary copy won't be needed */
		jmp_buf buf;
		memset( &buf, 0, sizeof( buf ) );
		memcpy( buf, ctx->top->buf, sizeof( buf ) );

		free(ctx->top);
		ctx->top = node;

#if defined( _WIN32 ) && defined( __aarch64__ )
		__mingw_longjmp( buf, -1 );
#else
		longjmp( buf, -1 );
#endif
	}

	/* don't know where to go next so return an error */
	return fb_ErrorSetNum( FB_RTERROR_RETURNWITHOUTGOSUB );
}

/*:::::*/
FBCALL void fb_GosubExit( GOSUBCTX * ctx )
{
	if( ctx )
	{
		while( ctx->top )
		{
			GOSUBNODE *node = ctx->top->next;
			free(ctx->top);
			ctx->top = node;
		}
	}
}
