/*
Copyright (c) 2008, Mathias Kende

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

#ifndef __LIB_CEXN_H__
#define __LIB_CEXN_H__

#include <setjmp.h>
#include <stdlib.h>

typedef void (*f_handler)(const char*,void*, const char*, const char*, int, const char*, const char*, int);
#define exn_handler(h) void h(const char* type, void* exn, const char* r_file, const char* r_fct, int r_line, const char* c_file, const char* c_fct, int c_line)

jmp_buf* __get_buf();
void __delete_buf();
void __throw_exn(int n, void* exn, const char* type, const char* file,const char* fct, int line)  __attribute__ ((__noreturn__));
void __rethrow()  __attribute__ ((__noreturn__));
void* __get_exn();
void __catchall(const char* file,const char* fct, int line);
int __register_handler(int n,f_handler handler);
int __unregister_handler(int n);
void __clear_exn();
int __check_handler_list();
int __set_return_code(int code);

#define __hash_type(s)		(			\
{							\
        int h = 0;					\
        const int b8 = 1 << 7;				\
        int i;						\
        for (i = 0; s[i] != 0; i++)			\
        {						\
                int m = s[i] + b8 * ((i / 4) % 2);	\
                m <<= ((i % 4) * 8);			\
                h ^= m;					\
        }						\
        if (h == 0)					\
                h = 0xDCB312E8;				\
        h = (h & ~(1<<31));				\
	h;						\
})

#define __cleanup {if(!__val && !__cleaned) { __cleaned = 1; __delete_buf(); } if (__val && !__cleared && __catched) { __cleared = 1; __clear_exn();} }
#define try {jmp_buf* __env = __get_buf(); int __catched = 0, __cleaned = 0, __cleared = 0, __temp; int __val = setjmp(*__env); if (!__val) for(__temp = 0; __temp < 1; ++__temp) {
#define catch(t,v) } else if (__val == __hash_type(#t)) for (__temp = 0; __temp < 1; ++__temp) { __typeof__(t) v = *(__typeof__(t)*)__get_exn(); __catched = 1;
#define finally } { __cleanup
#define rethrow } { __cleanup; if (__val && !__catched) __rethrow(); }}
#define catchall } { __cleanup; if (__val && !__catched) __catchall(__FILE__, __FUNCTION__, __LINE__); }}
#define with } { if(!__val)
#define throw(t,exn) {__typeof__(t)* __exn = malloc(sizeof(t)); *__exn = (exn); __throw_exn(__hash_type(#t),__exn, #t, __FILE__, __FUNCTION__, __LINE__); }

/*
This version of throw may support a larger set of syntaxe:
#define throw(t,exn) {__typeof__(t) __exn = exn; __typeof__(t)* __exnp = malloc(sizeof(t)); *__exnp = __exn; __throw_exn(__hash_type(#t),__exnp, #t, __FILE__, __FUNCTION__, __LINE__); }
But even if you can initialize a struct with a list of its member, such a initializer list cannot be passed as argument to a macro.

The solution is to forget about C89 and switch to C99 syntaxe with something like:
#define throw(t,...) {__typeof__(t) __exn = __VA_ARGS__; __typeof__(t)* __exnp = malloc(sizeof(t)); *__exnp = __exn; __throw_exn(__hash_type(#t),__exnp, #t, __FILE__, __FUNCTION__, __LINE__); }
There you can write things like:
struct s {int a; char* b;};
...
throw(struct s,{42; "hello world"});
You can use this version of the throw macro if you have no problem with C99.

Shorter but gcc specifics (uses compounds literals):
#define throw(t,...) {__typeof__(t)* __exnp = malloc(sizeof(t)); *__exnp = (__typeof__(t))__VA_ARGS__; __throw_exn(__hash_type(#t),__exnp, #t, __FILE__, __FUNCTION__, __LINE__); }
 */

/* The buffer allocated for an exception is freed when the next exception is thrown, or at the end of the program.
 * break and continue can be used to get out of a try block but not the goto nor the return statement.
 * any keyword can be used inside a catch or finally block, but if used in a catch, the finally
 * block will not be executed.
 *
 * This library should be tread safe on modern architecture (where gcc __thread keywork is correctly
 * handled, but thread should be started outside of any try block.
*/

/*
 * the handler get a pointer to the exception. But this pointer is no longer valid when
 * out of the handler. But the exception can be rethrown in a handler with __rethrow()
 * The restriction given below do not apply here as a finally block is executed
 * before any registered handler.
*/
#define register_handler(t,f) __register_handler(__hash_type(#t),f)
#define unregister_handler(t) __unregister_handler(__hash_type(#t))

/*
 * __rethrow() can be called inside a "catch" block to propagate an exception
 * more efficiently than by throwing it again (and the information about the
 * first location of the exception throwing is preserved.
 * But the finally block following the catch, if any, will not be executed.
 * The same thing apply if one throw an exception from a catch block.
 *
 * If one really must exit from a "try" bloc with return, break or continue, then
 * __delete_buf() must be called before.
*/

/*
  These version of throw and catch do not need the __typeof__ keyword, but
  they are less powerfull, e.g. they don't allow function pointers as exception type.
#define catch(t,v) } else if (__val == __hash_type(#t)) { t v = *(t*)__exn; __raised = 0;
#define throw(t,exn) {t* __exn = malloc(sizeof(t)); *__exn =(exn); __throw_exn(__hash_type(#t),__exn, #t, __FILE__, __FUNCTION__, __LINE__); }
*/

/*
 * Deprecated version without a finally block.
#define try {jmp_buf* __env = __get_buf(); int __raised = 0; int __val = setjmp(*__env); if (!__val) {
#define with __delete_buf();} else { void* __exn = __get_exn(); __raised = 1; if (0) 
#define catch(t,v) } else if (__val == __hash_type(#t)) { __typeof__(t) v = *(__typeof__(t)*)__exn; __raised = 0;
#define finally } {  
#define rethrow else __rethrow(); __clear_exn(); }}
#define catchall else __catchall(__FILE__, __FUNCTION__, __LINE__); __clear_exn(); }}
#define throw(t,exn) {__typeof__(t)* __exn = malloc(sizeof(t)); *__exn = (exn); __throw_exn(__hash_type(#t),__exn, #t, __FILE__, __FUNCTION__, __LINE__); }
*/


#endif

