// -*- C++ -*-
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#pragma once
#ifndef INCLUDEOS_EXPECTS_HEADER
#define INCLUDEOS_EXPECTS_HEADER

// LIKELY/UNLIKELY
#include <likely>
#include <cstdlib>

#undef Expects
#undef Ensures

#ifdef INCLUDEOS_SMP_ENABLE
#include <smp>
#endif

#include <os.hpp>
inline void __expect_fail(const char *expr, const char *file, int line, const char *func){
#ifndef UNITTESTS
#ifdef INCLUDEOS_SMP_ENABLE
  SMP::global_lock();
#endif
  fprintf(stderr, "%s:%i:%s %s \n",file, line, func, expr);
  fflush(NULL);
#ifdef INCLUDEOS_SMP_ENABLE
  SMP::global_unlock();
#endif
  os::panic(expr);
#else // TEST
  // throw here to allow tests to capture the error
  #include <stdexcept>
  #include <format>
  auto msg = std::format("{}:{}:{} {}",file, line, func, expr);
  throw std::runtime_error(msg);
#endif
}

#define Expects(x) ((void)((x) || (__expect_fail("Expects failed: "#x, __FILE__, __LINE__, __func__),0)))
#define Ensures(x) ((void)((x) || (__expect_fail("Ensures failed: "#x, __FILE__, __LINE__, __func__),0)))

namespace os {
// parameter for noexcept specifier when bypassing noexcept for testing
#if defined(TEST)
  constexpr bool hard_noexcept = false;
#else
  constexpr bool hard_noexcept = true;
#endif

}
#endif //< INCLUDEOS_EXPECTS_HEADER
