/**
** @file mruby/error.h - Exception class
**
** See Copyright Notice in mruby.h
*/

#ifndef MRUBY_ERROR_H
#define MRUBY_ERROR_H

#include "common.h"
#include <string.h>

/**
 * mruby error handling.
 */
MRB_BEGIN_DECL

struct RException {
  MRB_OBJECT_HEADER;
  struct iv_tbl *iv;
  struct RBasic *mesg;         // NULL or probably RString
  struct RBasic *backtrace;    // NULL, RArray or RData
};

/* error that should terminate execution */
#define MRB_EXC_EXIT 65536
#define MRB_EXC_EXIT_P(e) ((e)->flags & MRB_EXC_EXIT)
/* retrieve status value from exc; need <mruby/variable.h> and <mruby/presym.h> */
#define MRB_EXC_EXIT_STATUS(mrb,e) ((int)mrb_as_int((mrb),mrb_obj_iv_get((mrb),(e),MRB_SYM(status))))
/* exit with SystemExit status */
#define MRB_EXC_CHECK_EXIT(mrb,e) do {if (MRB_EXC_EXIT_P(e)) exit(MRB_EXC_EXIT_STATUS((mrb),(e)));} while (0)

#define mrb_exc_ptr(v) ((struct RException*)mrb_ptr(v))

MRB_API mrb_noreturn void mrb_sys_fail(mrb_state *mrb, const char *mesg);
MRB_API mrb_value mrb_exc_new_str(mrb_state *mrb, struct RClass* c, mrb_value str);
#define mrb_exc_new_lit(mrb, c, lit) mrb_exc_new_str(mrb, c, mrb_str_new_lit(mrb, lit))
MRB_API mrb_noreturn void mrb_no_method_error(mrb_state *mrb, mrb_sym id, mrb_value args, const char *fmt, ...);

#if defined(MRB_NAN_BOXING) || defined(MRB_WORD_BOXING) || defined(MRB_64BIT)
#undef MRB_USE_RBREAK_VALUE_UNION
#else
#define MRB_USE_RBREAK_VALUE_UNION 1
#endif

/*
 *  flags:
 *      0..7:   enum mrb_vtype (only when defined MRB_USE_RBREAK_VALUE_UNION)
 *      8..10:  RBREAK_TAGs in src/vm.c (otherwise, set to 0)
 */
struct RBreak {
  MRB_OBJECT_HEADER;
  uintptr_t ci_break_index; // The top-level ci index to break. One before the return destination.
#ifndef MRB_USE_RBREAK_VALUE_UNION
  mrb_value val;
#else
  /* Store value as uint32_t words instead of union mrb_value_union
     to avoid 8-byte alignment of int64_t/double on 32-bit platforms
     (e.g., ARM, MIPS, PowerPC) which would inflate struct size beyond
     the 5-word RVALUE limit due to padding. */
  uint32_t value[sizeof(union mrb_value_union) / sizeof(uint32_t)];
#endif
};

#ifndef MRB_USE_RBREAK_VALUE_UNION
#define mrb_break_value_get(brk) ((brk)->val)
#define mrb_break_value_set(brk, v) ((brk)->val = v)
#else
#define RBREAK_VALUE_TT_MASK ((1 << 8) - 1)
static inline mrb_value
mrb_break_value_get(struct RBreak *brk)
{
  mrb_value val;
  memcpy(&val.value, brk->value, sizeof(val.value));
  val.tt = (enum mrb_vtype)(brk->flags & RBREAK_VALUE_TT_MASK);
  return val;
}
static inline void
mrb_break_value_set(struct RBreak *brk, mrb_value val)
{
  memcpy(brk->value, &val.value, sizeof(val.value));
  brk->flags &= ~RBREAK_VALUE_TT_MASK;
  brk->flags |= val.tt;
}
#endif  /* MRB_USE_RBREAK_VALUE_UNION */

/**
 * Error check
 *
 */
/* clear error status in the mrb_state structure */
MRB_API void mrb_clear_error(mrb_state *mrb);
/* returns TRUE if error in the previous call; internally calls mrb_clear_error() */
MRB_API mrb_bool mrb_check_error(mrb_state *mrb);

/**
 * Protect
 *
 */
typedef mrb_value mrb_protect_error_func(mrb_state *mrb, void *userdata);
MRB_API mrb_value mrb_protect_error(mrb_state *mrb, mrb_protect_error_func *body, void *userdata, mrb_bool *error);

/**
 * Protect (takes mrb_value for body argument)
 *
 * Implemented in the mruby-error mrbgem
 */
MRB_API mrb_value mrb_protect(mrb_state *mrb, mrb_func_t body, mrb_value data, mrb_bool *state);

/**
 * Ensure
 *
 * Implemented in the mruby-error mrbgem
 */
MRB_API mrb_value mrb_ensure(mrb_state *mrb, mrb_func_t body, mrb_value b_data,
                             mrb_func_t ensure, mrb_value e_data);

/**
 * Rescue
 *
 * Implemented in the mruby-error mrbgem
 */
MRB_API mrb_value mrb_rescue(mrb_state *mrb, mrb_func_t body, mrb_value b_data,
                             mrb_func_t rescue, mrb_value r_data);

/**
 * Rescue exception
 *
 * Implemented in the mruby-error mrbgem
 */
MRB_API mrb_value mrb_rescue_exceptions(mrb_state *mrb, mrb_func_t body, mrb_value b_data,
                                        mrb_func_t rescue, mrb_value r_data,
                                        mrb_int len, struct RClass **classes);

/**
 *  Calls `func` via `mrb_protect_error()` and then always executes the user block exactly once.
 *  Even if a global jump (similar to a Ruby exception) occurs within `func`, the block will be executed,
 *  and after the block's completion, the global jump will be re-thrown.
 *
 *  By checking `mrb->exc != NULL` within the block, you can determine if a global jump occurred in `func`.
 *
 *  If you want to suppress the global jump and continue processing, use `mrb_clear_error(mrb); break;`.
 *
 *  - `mrb`: The mruby state reference
 *  - `result_var`: Pre-defined mrb_value type variable (to receive `func`'s return value)
 *  - `func`: Function to call (compatible with `mrb_protect_error_func`)
 *  - `data`: User data to pass to `func`
 *
 *  Example:
 *
 *      mrb_value result;
 *      MRB_ENSURE(mrb, result, body_func, userdata) {
 *        // This block is always executed (equivalent to Ruby's ensure)
 *
 *        if (mrb->exc) {
 *          // Post-processing when an exception occurs
 *        }
 *
 *        // To ignore the global jump, use `mrb_clear_error(mrb); break;` here
 *      }
 */
#define MRB_ENSURE(mrb, result_var, func, data) \
        for (mrb_bool MRB_UNIQNAME(_break_) = FALSE; \
             !MRB_UNIQNAME(_break_) && \
                (((result_var) = mrb_protect_error(mrb, func, data, &MRB_UNIQNAME(_break_))), \
                 ((mrb)->exc = (MRB_UNIQNAME(_break_) ? mrb_obj_ptr((result_var)) : NULL)), \
                 TRUE); \
             (void)(MRB_UNIQNAME(_break_) && (mrb)->jmp && (mrb_exc_raise(mrb, result_var), TRUE)), \
                MRB_UNIQNAME(_break_) = TRUE)

MRB_END_DECL

#endif  /* MRUBY_ERROR_H */
