www.delorie.com/gnu/docs/gforth/gforth_186.html   search  
 
Buy GNU books!


Gforth Manual

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

5.22.4 Assertions

It is a good idea to make your programs self-checking, especially if you make an assumption that may become invalid during maintenance (for example, that a certain field of a data structure is never zero). Gforth supports assertions for this purpose. They are used like this:

 
assert( flag )

The code between assert( and ) should compute a flag, that should be true if everything is alright and false otherwise. It should not change anything else on the stack. The overall stack effect of the assertion is ( -- ). E.g.

 
assert( 1 1 + 2 = ) \ what we learn in school
assert( dup 0<> ) \ assert that the top of stack is not zero
assert( false ) \ this code should not be reached

The need for assertions is different at different times. During debugging, we want more checking, in production we sometimes care more for speed. Therefore, assertions can be turned off, i.e., the assertion becomes a comment. Depending on the importance of an assertion and the time it takes to check it, you may want to turn off some assertions and keep others turned on. Gforth provides several levels of assertions for this purpose:

doc-assert0( doc-assert1( doc-assert2( doc-assert3( doc-assert( doc-)

The variable assert-level specifies the highest assertions that are turned on. I.e., at the default assert-level of one, assert0( and assert1( assertions perform checking, while assert2( and assert3( assertions are treated as comments.

The value of assert-level is evaluated at compile-time, not at run-time. Therefore you cannot turn assertions on or off at run-time; you have to set the assert-level appropriately before compiling a piece of code. You can compile different pieces of code at different assert-levels (e.g., a trusted library at level 1 and newly-written code at level 3).

doc-assert-level

If an assertion fails, a message compatible with Emacs' compilation mode is produced and the execution is aborted (currently with ABORT". If there is interest, we will introduce a special throw code. But if you intend to catch a specific condition, using throw is probably more appropriate than an assertion).

Definitions in ANS Forth for these assertion words are provided in `compat/assert.fs'.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

  webmaster     delorie software   privacy  
  Copyright 2003   by The Free Software Foundation     Updated Jun 2003