// -*- mode: C++; indent-tabs-mode: nil; c-basic-offset: 4 -*-

/*
 * Various assert macros based on C++ exceptions and their support code.
 */

/*
 * (c) 2006-2016 Petr Ročkai <code@fixp.eu>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <exception>
#include <string>
#include <sstream>
#include <cstdint>

#ifndef TEST
#define TEST(n)         void n()
#define TEST_FAILING(n) void n()
#endif

#ifndef NDEBUG

#define BRICK_SHARP_FIRST(x, ...) #x
#define ASSERT(...) ::brick::_assert::assert_fn(         \
        BRICK_LOCWRAP( BRICK_LOCATION( BRICK_SHARP_FIRST( __VA_ARGS__, ignored ) ) ), __VA_ARGS__ )
#define ASSERT_PRED(p, x) ::brick::_assert::assert_pred_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( #p "( " #x " )" ) ), x, p( x ) )
#define ASSERT_EQ(x, y) ::brick::_assert::assert_eq_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( #x " == " #y ) ), x, y )
#define ASSERT_LT(x, y) ::brick::_assert::assert_lt_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( #x " < " #y ) ), x, y )
#define ASSERT_LEQ(x, y) ::brick::_assert::assert_leq_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( #x " <= " #y ) ), x, y )
#define ASSERT_NEQ(x, y) ::brick::_assert::assert_neq_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( #x " != " #y ) ), x, y )
#define ASSERT_EQ_IDX(i, x, y) ::brick::_assert::assert_eq_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION_I( #x " == " #y, i ) ), x, y )

#else

#define ASSERT(...) static_cast< decltype(__VA_ARGS__, void(0)) >(0)
#define ASSERT_PRED(p, x) static_cast< decltype(p, x, void(0)) >(0)
#define ASSERT_EQ(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_LEQ(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_LT(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_NEQ(x, y) static_cast< decltype(x, y, void(0)) >(0)
#define ASSERT_EQ_IDX(i, x, y) static_cast< decltype(i, x, y, void(0)) >(0)
#endif

/* you must #include <brick-string> to use ASSERT_UNREACHABLE_F */
#define UNREACHABLE_F(...) ::brick::_assert::assert_die_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( brick::string::fmtf(__VA_ARGS__) ) ) )
#define UNREACHABLE(...) ::brick::_assert::assert_die_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( ::brick::_assert::fmt( __VA_ARGS__ ) ) ) )
#define UNREACHABLE_() ::brick::_assert::assert_die_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( "an unreachable location" ) ) )
#define NOT_IMPLEMENTED() ::brick::_assert::assert_die_fn( \
        BRICK_LOCWRAP( BRICK_LOCATION( "a missing implementation" ) ) )

#ifdef _MSC_VER
#define UNUSED
#define noexcept
#else
#define UNUSED __attribute__((unused))
#endif

#ifndef BRICK_ASSERT_H
#define BRICK_ASSERT_H

namespace brick {
namespace _assert {

/* discard any number of parameters, taken as const references */
template< typename... X >
void unused( const X&... ) { }

struct Location {
    int line, iteration;
    std::string file, stmt;
    Location( const char *f, int l, std::string st, int iter = -1 )
        : line( l ), iteration( iter ), file( f ), stmt( st )
    {
        int slashes = 0;
        for ( int i = 0; i < int( file.size() ); ++i )
            if ( file[i] == '/' )
                ++ slashes;

        while ( slashes >= 3 )
        {
            file = std::string( file, file.find( "/" ) + 1, std::string::npos );
            -- slashes;
        }
        if ( f != file )
            file = ".../" + file;
    }
};

#define BRICK_LOCATION(stmt) ::brick::_assert::Location( __FILE__, __LINE__, stmt )
#define BRICK_LOCATION_I(stmt, i) ::brick::_assert::Location( __FILE__, __LINE__, stmt, i )

// lazy location construction in C++11
#if __cplusplus >= 201103L
#define BRICK_LOCWRAP(x) [&]{ return (x); }
#define BRICK_LOCUNWRAP(x) (x)()
#else
#define BRICK_LOCWRAP(x) (x)
#define BRICK_LOCUNWRAP(x) (x)
#endif

struct AssertFailed : std::exception
{
    std::string str;

    template< typename X >
    friend inline AssertFailed &operator<<( AssertFailed &f, X x )
    {
        std::stringstream str;
        str << x;
        f.str += str.str();
        return f;
    }

    AssertFailed( Location l, const char *expected = "expected" )
    {
        (*this) << l.file << ": " << l.line;
        if ( l.iteration != -1 )
            (*this) << " (iteration " << l.iteration << ")";
        (*this) << ":\n  " << expected << " " << l.stmt;
    }

    const char *what() const noexcept override { return str.c_str(); }
};

static inline void format( AssertFailed & ) {}

template< typename X, typename... Y >
void format( AssertFailed &f, X x, Y... y )
{
    f << x;
    format( f, y... );
}

template< typename Location, typename X, typename... Y >
void assert_fn( Location l, X x, Y... y  )
{
    if ( x )
        return;
    AssertFailed f( BRICK_LOCUNWRAP( l ) );
    format( f, y... );
    throw f;
}

template< typename Location >
inline void assert_die_fn( Location l ) __attribute__((noreturn));

template< typename Location >
inline void assert_die_fn( Location l )
{
    throw AssertFailed( BRICK_LOCUNWRAP( l ), "encountered" );
}

#define ASSERT_FN(name, op, inv)                                    \
    template< typename Location >                                   \
    void assert_ ## name ## _fn( Location l, int64_t x, int64_t y ) \
    {                                                               \
        if ( !( x op y ) ) {                                        \
            AssertFailed f( BRICK_LOCUNWRAP( l ) );                 \
            f << "\n   but got "                                    \
              << x << " " #inv " " << y << "\n";                    \
            throw f;                                                \
        }                                                           \
    }                                                               \
                                                                    \
    template< typename Location, typename X, typename Y >           \
    auto assert_ ## name ## _fn( Location l, X x, Y y )             \
        -> typename std::enable_if<                                 \
        !std::is_integral< X >::value ||                            \
        !std::is_integral< Y >::value >::type                       \
    {                                                               \
        if ( !( x op y ) ) {                                        \
            AssertFailed f( BRICK_LOCUNWRAP( l ) );                 \
            f << "\n   but got "                                    \
              << x << " " #inv " " << y << "\n";                    \
            throw f;                                                \
        }                                                           \
    }

ASSERT_FN(eq, ==, !=)
ASSERT_FN(leq, <=, >)
ASSERT_FN(lt, <, >=)

template< typename Location, typename X >
void assert_pred_fn( Location l, X x, bool p )
{
    if ( !p ) {
        AssertFailed f( BRICK_LOCUNWRAP( l ) );
        f << "\n   but got x = " << x << "\n";
        throw f;
    }
}

template< typename Location, typename X, typename Y >
void assert_neq_fn( Location l, X x, Y y )
{
    if ( x != y )
        return;
    AssertFailed f( BRICK_LOCUNWRAP( l ) );
    f << "\n   but got "
      << x << " == " << y << "\n";
    throw f;
}

inline std::string fmt( const char *str ) { return str; }
inline std::string fmt( std::string str ) { return str; }
// another overload of fmt is exported by brick-string and it allows more complex formating

}
}

#endif

// vim: syntax=cpp tabstop=4 shiftwidth=4 expandtab
