cpp-checked.h.pre 2.56 KB

#include <stdio.h>
#include <stdlib.h>

#include <functional>
#include <string>

namespace isl {
namespace checked {

#define ISLPP_STRINGIZE_(X) #X
#define ISLPP_STRINGIZE(X) ISLPP_STRINGIZE_(X)

#define ISLPP_ASSERT(test, message)                          \
  do {                                                       \
    if (test)                                                \
      break;                                                 \
    fputs("Assertion \"" #test "\" failed at " __FILE__      \
      ":" ISLPP_STRINGIZE(__LINE__) "\n  " message "\n",     \
      stderr);                                               \
    abort();                                                 \
  } while (0)

class boolean {
private:
  mutable bool checked = false;
  isl_bool val;

  friend boolean manage(isl_bool val);
  boolean(isl_bool val): val(val) {}
public:
  boolean()
      : val(isl_bool_error) {}
  ~boolean() {
    ISLPP_ASSERT(checked, "IMPLEMENTATION ERROR: Unchecked state");
  }

  /* implicit */ boolean(bool val)
      : val(val ? isl_bool_true : isl_bool_false) {}

  bool is_error() const { checked = true; return val == isl_bool_error; }
  bool is_false() const { checked = true; return val == isl_bool_false; }
  bool is_true() const { checked = true; return val == isl_bool_true; }

  explicit operator bool() const {
    ISLPP_ASSERT(checked, "IMPLEMENTATION ERROR: Unchecked error state");
    ISLPP_ASSERT(!is_error(), "IMPLEMENTATION ERROR: Unhandled error state");
    return is_true();
  }

  boolean operator!() const {
    if (is_error())
      return *this;
    return !is_true();
  }
};

inline boolean manage(isl_bool val) {
  return boolean(val);
}

class ctx {
  isl_ctx *ptr;
public:
  /* implicit */ ctx(isl_ctx *ctx)
      : ptr(ctx) {}
  isl_ctx *release() {
    auto tmp = ptr;
    ptr = nullptr;
    return tmp;
  }
  isl_ctx *get() {
    return ptr;
  }
};

/* Class encapsulating an isl_stat value.
 */
class stat {
private:
	mutable bool checked = false;
	isl_stat val;

	friend stat manage(isl_stat val);
	constexpr stat(isl_stat val) : val(val) {}
public:
	static stat ok() {
		return stat(isl_stat_ok);
	}
	static stat error() {
		return stat(isl_stat_error);
	}
	stat() : val(isl_stat_error) {}
	~stat() {
		ISLPP_ASSERT(checked, "IMPLEMENTATION ERROR: Unchecked state");
	}

	isl_stat release() {
		checked = true;
		return val;
	}

	bool is_error() const {
		checked = true;
		return val == isl_stat_error;
	}
	bool is_ok() const {
		checked = true;
		return val == isl_stat_ok;
	}
};

inline stat manage(isl_stat val)
{
	return stat(val);
}

}
} // namespace isl