#if !defined (__ASSERTION_HPP)
#define __ASSERTION_HPP

/*
  CoreLinux++ 
  Copyright (C) 1999 CoreLinux Consortium
  
   The CoreLinux++ Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.

   The CoreLinux++ Library Library is distributed in the hope that it will 
   be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.

   You should have received a copy of the GNU Library General Public
   License along with the GNU C Library; see the file COPYING.LIB.  If not,
   write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.  
*/   


/*
Assertion is the exception created when an assertion fails.  It contains
type information so that clients may filter the types of assertion
violations that they catch.  There are several types of assertion:

     ASSERT( bool )   Enabled by #define ALL_ASSERTIONS.  It is only used
                      inside the INVARIANT clause of a class declaration.

     REQUIRE( bool )  Enabled by #define ALL_ASSERTIONS or
                      #define ASSERT_REQUIRE.  This macro is used to
                      check precondtions for a function.  If disabled
                      the macro is compiled away.

     ENSURE( bool )   Enabled by #define ALL_ASSERTIONS or
                      #define ASSERT_ENSURE.  This macro is used to check
                      postconditions.  If disabled the macro is compiled
                      away.

     CHECK( bool )    Enabled by #define ALL_ASSERTIONS or
                      #define ASSERT_CHECK.  This macro is used to check
                      assumptions or to check calls to external functions
                      in the OS.  Unlike REQUIRE and ENSURE when disabled
                      this macro expands to:  if( !( exp )) {;} else
                      This expansion allows calls such as:
                         CHECK( DosSubAllocMem( ... ) == 0 );
                      to not be compiled away.

     CHECK_INVARIANT  Enabled by #define ALL_ASSERTIONS.  This macro is
                      used to validate that the class INVARIANT still
                      holds.  The INVARIANT must hold after construction
                      and at the end of any public member function.  In
                      order to use this assertion the class must have an
                      INVARIANT ... END_INVARIANT section in the class
                      definition.  If ALL_ASSERTIONS is not defined then
                      this macro expands to nothing.

     NEVER_GET_HERE   This macro is always enabled and throws an assertion
                      if it is ever executed.  It should be used to make
                      explicit to the reader that all cases have been
                      accounted for in a switch or if ... else if ... else
                      block.

Typically the programmer defines ALL_ASSERTIONS during development and
reduces assertion levels to ASSERT_REQUIRE at beta and even into release.

In addition to the assertions there are several helper macros that allow
for class INVARIANTs and the logic predicates "for all" and "there exists".
There is also the USES_OLD macro which allows changes in a class to be
checked against the original version of the class.

BASE_INVARIANT( BaseClass ) Can only be used in the INVARIANT clause
                      of a class definition.  This expands to call the
                      INVARIANT of one of the base classes in the
                      current class.  Expands to:  BaseClass::INVARIANT()

INVARIANT             Can only be used inside a class definition.  This
                      should be the last thing in the class and should
                      state the conditions that hold when the class is
                      correct.  The only statements allowed in the
                      INVARIANT are BASE_INVARIANT and ASSERT.
                      For example an ordered array class may
                      look like:

                         class OrderedArray<T> : public Vector
                         {
                         public:
                                  Array( int size ) :
                                      Vector(),
                                      theSize( size ),
                                      theArray( new T[ size ] );
                                  {
                                       orderTheArray();

                                       CHECK_INVARIANT;
                                  }

                                  virtual !Array();

                                  // other operations.

                         private:
                                 int theSize;
                                 T * theArray;

                         INVARIANT
                             BASE_INVARIANT( Vector );

                             // Array is sorted in ascending order.
                             ASSERT( FORALL(( int i = 1; i < theSize; i++ ),
                                         theArray[i-1] <= theArray[i] ));
                         END_INVARIANT
                         };  // end class OrderedArray<T>


END_INVARIANT         Used to terminate the INVARIANT clause in a class
                      definition.

USES_OLD( Type )      Creates a copy of the current object called old
                      which can then be used in assertions to check
                      those attributes between the new object and old.
                      Any function which needs old must declare this
                      at the start of the function.  The object must
                      be able to copy itself deeply for this to work
                      correctly.  Only creates old if ALL_ASSERTIONS or
                      ASSERT_ENSURE is defined.
                      WARNING:  old should only be used by the ENSURE
                      macro.

 old                  variable created by the USES_OLD macro.  A typical
                      use would be:

                            void List::addItem( item )
                            {
                                ...
                                ENSURE( size() == old.size() + 1 );
                            }

bool FORALL(( for-specification ), condition )

                 Only expands if ALL_ASSERITONS is defined, and can only
                 be used in assertions.  If ALL_ASSERTIONS is not defined
                 it becomes the value True.  If expanded it becomes
                 equivalent to:

                 REQUIRE( FORALL(( int i = 0; i < 10; i++ ), x[i] <= x[0] ));

                 REQUIRE( tempForAll() );

                 bool tempForAll()
                 {
                     bool result = True;
                     for( int i = 0; i < 10; i++ )
                         if( !( x[i] <= x[0] ))
                            {
                            result = False;
                            break;
                            }
                     return result;
                 }

                 Be very carefull using this macro since errors
                 in the for specification or condition can be very difficult
                 to find.  Also note that the condition can be another
                 FORALL or an EXISTS.

bool EXISTS((for-specification), condition )

                 Only expands if ALL_ASSERTIONS is defined,  otherwise
                 becomes the value True.  Returns True as soon as the
                 condition is met.  If all iterations fail then the
                 macro fails.  When expanded it becomes equivalent to:

                 ENSURE( EXISTS((int i = 0; i<10; i++), x[i] == old.x[i] ));
                 ENSURE( tempExists() );

                 bool tempExists()
                 {
                     bool result;
                     for( int i = 0; i < 10; i++ )
                        if( x[i] == old.x[i] )
                            {
                            result = True;
                            break;
                            }
                      return result;
                 }


The assertion mechanism also supports two functions;  assertionFailed()
and assertLoopDebugFunction().  The first is called when an assertion
fails and after the assertion exception has been built.  The second
one is called if FORALL or EXISTS fail.  These functions are a handy
place to set breakpoints during debugging.  They are implemented in
Assertion.cpp

               See also:  Object Oriented Software Construction
                          Bertrand Meyer.
                          Prentice Hall, Englewood Cliffs NJ., 1988.

                          C/C++ Users Journal October 1994 pages 21 - 37

*/

#if !defined IN_COMMON_HPP
   #error Assertion.hpp is included by Common.hpp only.
#endif

namespace   corelinux
{
   // Standard class Declarations

   DECLARE_CLASS( Assertion );

   // These macros are called when an assertion fails or a FORALL or EXISTS
   // test fails respectively.  They provide a convienent place to set a
   // breakpoint during debugging.
   //

   Long assertionFailed( AssertionCref rAssertion );
   void assertLoopDebugFunction( void );

   //
   // Static variables needed by the assertion macros.
   //

   static Long asstInvert   = 0;
   static Long asstResult   = 0;
   static Long asstEval     = 0;
   static Long asstShortCut = 0;
   static Long asstZero     = 0;

   static struct AssertCt
   {
      AssertCt( void )
      {
         asstInvert = asstResult = asstEval = asstShortCut = asstZero = 0;
      }
      // empty
   } asstCt;


   //
   // Typedefs and Macros
   //


   #define paste(a,b) a##b
   #define paste3(a,b,c) a##b##c


   #if defined  ALL_ASSERTIONS || defined ASSERT_REQUIRE
      #define REQUIRE( exp )                                               \
         IGNORE_RETURN (                                                   \
            asstResult = asstZero || exp,                                  \
            asstResult || assertionFailed( Assertion( Assertion::REQUIRE,  \
                                       TEXT( #exp ),                       \
                                      LOCATION                             \
                                      )) )

   #else
      #define REQUIRE( exp )
   #endif  // defined ALL_ASSERTIONS || ASSERT_REQUIRE

   #if defined  ALL_ASSERTIONS || defined ASSERT_ENSURE
      #define ENSURE( exp )                                                \
         IGNORE_RETURN (                                                   \
            asstResult = asstZero || exp,                                  \
            asstResult || assertionFailed( Assertion( Assertion::ENSURE,   \
                                       TEXT( #exp ),                       \
                                      LOCATION                             \
                                   )) )

   #else
      #define ENSURE( exp )
   #endif  // defined ALL_ASSERTIONS || ASSERT_ENSURE

   #if defined  ALL_ASSERTIONS || defined ASSERT_CHECK
      #define CHECK( exp )                                                 \
         IGNORE_RETURN (                                                   \
            asstResult = asstZero || exp,                                  \
            asstResult || assertionFailed( Assertion( Assertion::CHECK,    \
                                      paste3(                              \
                                             TEXT("CHECK( "),              \
                                             TEXT( #exp ),                 \
                                             TEXT(" )")                    \
                                            ),                             \
                                                 LOCATION )) )

   #else
      #define CHECK( exp )
   #endif  // defined ALL_ASSERTIONS || ASSERT_CHECK


   #define NEVER_GET_HERE                                               \
      assertionFailed( Assertion( Assertion::NEVERGETHERE,              \
                                TEXT("NEVER_GET_HERE"),                 \
                                LOCATION ))

//
// Macros that support class INVARIANTs.
//

   #if defined ALL_ASSERTIONS
      #define INVARIANT                                                 \
   protected:                                                           \
      virtual void invariant(void) const { Short executingInvariant = 1;
      #define END_INVARIANT }
      #define CHECK_INVARIANT  invariant()
   #else
      #define INVARIANT      paste(/, *)
      #define END_INVARIANT
      #define CHECK_INVARIANT
   #endif

/*                                 
                          paste3(                                       \
                                 TEXT("STDASSERT( "),                   \
                                 TEXT( #exp ),                          \
                                 TEXT(" )")                             \
                                ),                                      \
*/                                

   #if defined ALL_ASSERTIONS
      #define STDASSERT( exp )                                          \
      if( executingInvariant )                                          \
      {                                                                 \
         asstResult = asstZero || exp,                                  \
         asstResult ||                                                  \
            assertionFailed( Assertion( Assertion::ASSERT,              \
                                 TEXT( #exp ),                          \
                          LOCATION ));                                  \
      }                                                                 \
      else                                                              \
      {                                                                 \
         throw Exception(                                               \
            TEXT("STDASSERT used outside of INVARIANT"), LOCATION );    \
      }
   #else
      #define STDASSERT( exp )
   #endif  // defined ALL_ASSERTIONS

   #if defined ALL_ASSERTIONS
      #define BASE_INVARIANT( ClassType )                               \
      if( executingInvariant )                                          \
      {                                                                 \
         ClassType::invariant();                                        \
      }                                                                 \
      else                                                              \
      {                                                                 \
         throw Exception(                                               \
            TEXT("BASE_INVARIANT used outside of an INVARIANT"),        \
            LOCATION,                                                   \
            Exception::ProcessTerminate);                               \
      }

   #else
      #define BASE_INVARIANT( ClassType )
   #endif

//
// Macro that defines "old".
//

   #if defined ALL_ASSERTIONS || defined ASSERT_ENSURE
      #define USES_OLD( Type )   Type old( clself )
   #else
      #define USES_OLD( Type )
   #endif

//
// Macros for FORALL and EXISTS
//

   #define ASSERT_LOOP( asstFor, asstAll, asstCond )                    \
      anAssertCt();                                                     \
      {                                                                 \
         volatile x = 0;                                                \
         Long asstShortCut;                                             \
         if( asstDoEval( asstShortCut ))                                \
         {                                                              \
            Long asstInvert = ::asstInvert;                             \
            asstResult = asstAll;                                       \
            for asstFor                                                 \
            {                                                           \
               asstResult = x || asstCond;                              \
               if( asstResult != asstAll ) break;                       \
            }                                                           \
            if(asstInvert) asstResult = !asstResult;                    \
         }                                                              \
             ::asstShortCut = asstShortCut;                             \
             if( asstResult == 0 ) assertLoopDebugFunction();           \
      }                                                                 \
      asstResult = ::asstShortCut ? asstResult : asstResult

   #if defined ALL_ASSERTIONS
      #define FORALL(asstFor, asstCond ) ASSERT_LOOP( asstFor, 1, asstCond )
      #define EXISTS(asstFor, asstCond ) ASSERT_LOOP( asstFor, 0, asstCond )
   #else
      #define FORALL(asstFor, asstCond ) True
      #define EXISTS(asstFor, asstCond ) True
   #endif

//
// Constants
//


//
// Helper Classes (including exceptions).
//

   /**
   Assertion is-a Exception created when an assertion fails.  It contains
   type information so that clients may filter the types of assertion
   violations that they catch.  There are several types of assertion macros
   defined. Refer to the comments at the top of Assertion.hpp for details.
   */

   class Assertion : public Exception
   {
      //
      // Note that a private default constructor is not needed
      // beause Exception's default constructor is private.
      //

   public:

      /// Assertion Types enum

      enum Type
      {
         REQUIRE,       /// REQUIRE pre-condition state
         ENSURE,        /// ENSURE post-condition state
         CHECK,         /// CHECK invariant state
         ASSERT,        /// ASSERT invariant state
         NEVERGETHERE   /// NEVERGETHERE logic state
      };

   public:

      /**
      Assertion Constructor
      @param Type Specifies the state condition for the assertion
      @param Reason Text describing the assertion
      @param File The source module the assertion was thrown from
      @param Line The throw point line in the source module
      */

                  Assertion
                     ( 
                        Type aType,
                        CharPtr aReason,
                        CharPtr aFile,
                        LineNum aLine 
                     );

      /**
      Assertion copy constructor
      @param Assertion const reference
      */

                  Assertion( AssertionCref rExcept );

      /// Virtual Destructor

      virtual     ~Assertion( void );

      //
      // Operator overloads
      //

      /**
      Assignment operator overload
      @param  Assertion const reference
      @return Assertion reference to self
      */

      AssertionRef   operator=( AssertionCref );

      /**
      Comparisson operator overload
      @param Assertion const reference
      @return true if equal, false otherwise
      */

      bool           operator==( AssertionCref );

      //
      // Accessors
      //

      /**
      Accessor 
      @return The Type which caused the assertion
      */

      Assertion::Type getType( void ) const;

   private:

      Assertion::Type theType;
   };

//
// Inline Functions
//

   inline AssertCt & anAssertCt( void )
   {
      asstInvert = 0;
      asstEval   = 1;
      return asstCt;
   };

   inline Long asstDoEval( Long & asstShortCut )
   {
      Long result = asstEval;

      asstShortCut = !asstEval && asstResult;

      asstEval = 0;

      return result;
   }

   inline const AssertCt & operator !( const AssertCt & a )
   {
      asstInvert = !asstInvert;
      return a;
   }

   inline Long operator &&( Long left, const AssertCt & )
   {
      asstEval = left;
      return left;
   }

   inline Long operator ||( int left, const AssertCt & )
   {
      asstEval = !left;
      return left;
   }

}

#endif // !defined ASSERT_HPP

/*
   Common rcs information do not modify
   $Author: prudhomm $
   $Revision: 1.1 $
   $Date: 2000/04/23 20:43:13 $
   $Locker:  $
*/

