\input texinfo  @c -*-texinfo-*-
@include version.texi
@settitle Nana: improved support for assertions and logging in C and C++
@setfilename nana.info
@c send all the index entries to the concept index
@syncodeindex fn cp
@syncodeindex vr cp
@syncodeindex ky cp
@syncodeindex pg cp
@syncodeindex tp cp

@iftex 
@c Select A4 Paper (remove for imperialist letter paper)
@afourpaper
@end iftex

@ifinfo
@format
START-INFO-DIR-ENTRY
* Nana: (nana).          The Nana library (assertions, logging, forall,etc)
END-INFO-DIR-ENTRY
@end format
@end ifinfo

@ifinfo
This file documents the features and implementation of the GNU Nana library.

Copyright (C) 1996, 1997, 1998, 1999 P.J.Maker, Quoll Systems Pty Ltd.

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies. 

@ignore
Permission is granted to process this file through @TeX{} and print the
results, provided the printed document carries copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).

@end ignore
@end ifinfo

@iftex
@finalout
@c @smallbook
@c @cropmarks
@end iftex

@setchapternewpage odd

@titlepage
@title Nana
@subtitle Improved support for assertions and logging in C and C++
@subtitle last updated @value{UPDATED} for version @value{VERSION}
@author P.J.Maker (pjm@@gnu.org)
@page
@vskip 0pt plus 1filll
Copyright @copyright{} 1996, 1997, 1998, 1999 P.J.Maker, Quoll Systems Pty Ltd.

Permission is granted to make and distribute verbatim copies of
this manual provided the copyright notice and this permission notice
are preserved on all copies.
@end titlepage

@ifinfo
@node Top, Introduction, (dir), (dir)

This manual documents how to install and use the Nana library which
provides improved support for assertion checking and logging in C and C++.

@end ifinfo

@menu
* Introduction::                Overview
* Installation::                Installing nana
* Invoking::                    Compiling, linking and generating gdb commands
* Interface::                   Interface to nana library functions
* Shortform::                   Nana shortform generation
* Performance::                 
* Tracing::                     
* Usage::                       Some examples
* FAQ::                         Frequently Asked Questions
* Future::                      Future work/projects
* Index::                       

@detailmenu
 --- The Detailed Node Listing ---

Introduction

* Related work::                
* Assert::                      
* Scope::                       

Installing the Nana library

* Required Software::           
* Optional Software ::          
* Configure::                   
* Variables::                   
* Supported Platforms::         
* Supported Debuggers::         
* Known Problems::              
* Bug Reports::                 
* New Versions::                

Interface

* nana.h::                      
* WITHOUT_NANA::                
* I.h::                         
* DI.h::                        
* L.h::                         
* L_buffer.h::                  
* L_times.h::                   
* DL.h::                        
* GDB.h::                       
* Q.h::                         
* Qstl.h::                      
* now.h::                       
* cycles.h::                    
* eiffel.h::                    
* assert.h::                    
* calls.h::                     

cycles.h: access to CPU cycle counting registers.

* RDTSC::                       

eiffel.h: eiffel type assertions

* EIFFEL_CHECK::                
* DOEND::                       
* REQUIRE...::                  

Tracing tools

* Statement::                   
* Library::                     

Using Nana

* Simplest::                    
* Syslog::                      
* GNU::                         
* Embedded Systems::            
* Realtime::                    
* A database::                  
* Visualisation::               

@end detailmenu
@end menu

@node Introduction, Installation, Top, Top
@chapter Introduction

Nana is a library that provides support for assertion checking
and logging in a space and time efficient manner. The aim is to put
common good practice@footnote{Which is unfortunately quite uncommon in
the authors experience.} into a library that can be reused rather than
writing this stuff every time you begin a new project.

In addition assertion checking and logging code can be implemented using
a debugger rather than as inline code with a large saving in code space.

Nana aims to solve the following problems:

@enumerate
@item Avoid the two executables problem (one with asserts in and another 
without any).

The code space and time costs of having assertion checking and detailed
logging code in a program can be high. Normally people construct two
versions of the program, one with checking code for testing and one
without checking code for production use.

With nana one version of the executable can be
built for both testing and release since debugger based checking has 
negligible space and time impact.

@item Configurable: the nana library is designed to be reconfigured by
the user according to their needs. For example we can:
@itemize @bullet
@item Modify the behavior on assertion failure, e.g. to attempt
a system restart rather than just shutting down.
@item Selectively enable and disable assertion checking and
logging both at compile and run time.
@item Send the logging information off to various locations, e.g.
@itemize @minus
@item Users terminal
@item A file for later checking.
@item Another process, e.g. a plotting program or a
program that verifies that the system is behaving itself.
@item A circular buffer in memory. 

This is an old embedded systems trick and is very useful
for production systems. The time cost of logging into 
memory is not large and when your production system in
the field has problems you can then see what was happening 
in the minutes before its unfortunate demise rather than
asking some user what was happening before it died.
@end itemize
@end itemize

@item Time and space efficient.

For example the obvious @samp{assert.h} implementation uses 53 bytes for 
@samp{assert(i>=0)} on a i386. The nana version using the i386 @samp{stp}
instruction on assert fail uses 10 bytes. If you're willing to accept the
time penalty this can be reduced to 0 or 1 byte by using debugger based
assertions.

@item Support for formal methods.

@itemize @bullet
@item Before and after state (e.g. x,x' in the Z notation).

Specifications are often written in terms of the state of
variables before and after an operation. For example the
@samp{isempty} operation on a stack should leave the stack
unchanged. To verify this in nana we could use:
      
@example
bool isempty()@{ /* true iff stack is empty */
  DS($s = s); /* copy s into $s in the debugger */
  ...; /* code to do the operation */
  DI($s == s); /* verify that s hasn't been changed */
@}
@end example
        
These @samp{$..} variables are called convenience variables 
and are implemented by gdb. They have a global scope and are 
dynamically typed and initialised automatically to 0.

In addition a C only version of before and after state is provided.
For example:

@example
bool isempty() @{ /* true iff stack is empty */
  ID(int olds); /* declare variable to hold old value */
  IS(olds = s); /* copy s into $s in the debugger */
  ...; /* code to do the operation */
  I(olds == s); /* verify that s hasn't been changed */
@}
@end example

@item Support for Predicate Calculus.

Nana provides some support for universal (forall) and
existential  (exists one or more) quantification. For example to specify
that the string v contains only lower case letters we could use:

@example
  I(A(char *p = v, *p != '\0', p++, islower(*p)));
@end example

These macros can be nested and used as normal boolean values in
control constructs as well as assertions. Unfortunately they
depend on the GNU CC statement value extensions and so are not 
portable. The following macros are defined in @samp{Q.h}:

@ftable @code
@item A
For all values the expression must be true.
@item E
There exists one or more values for which the expression is
true.
@item E1
There exists a single value for which the expression is true.
@item C
Returns the number of times the expression is true.
@item S
Returns the sum of the expressions.
@item P 
Returns the product of the expressions.
@end ftable

@item A C/C++ based shortform generator similar to Eiffel which 
can produce a HTML summary of your code. 

The shortform of a program consists of the function headers 
together with their preconditions@footnote{Precondition: 
a boolean expression which must be true if the operation is to
succeed. For example the @samp{sort(int *v, int n)} might have 
have precondition that @samp{v != NULL && n >= 0}.}
and postconditions@footnote{Postcondition: a boolean expression that 
must be true if the operation is correct (and the precondition
was true on entry).}

@item Performance measurement.

A small package which measures the time and space overhead of
code fragments is provided. This is used to analyse the space/time 
requirements of the nana library and could be used for other types
of measurement.

@item Verifying timing.

As well as using nana to verify timings with assertions using a
hardware supported timer you can also a simulator (e.g. the
PSIM power pc simulator by Cagney) with gdb. These simulators can
model time and provide a register called @samp{$cycles} which
represents the current cycle count of the program. This can be 
used to check that timing constraints are being meet.

@example
void process_events() @{
  for(;;)@{ 
    DS($start = $cycles); 
    switch(get_event())@{
      case TOO_HOT:
        ...;
        DI($cycles - $start <= 120);
        break;
      case TOO_COLD:
        ...;
        DI($cycles - $start <= 240);
        break;
    @}
  @}
@}
@end example
@end itemize
@end enumerate

The intended audience for Nana includes:

@itemize @bullet
@item Software Engineers.
@item Formal methods community.
@item Real time programmers.
@item System testers.
@item People teaching programming.
@end itemize

@menu
* Related work::                
* Assert::                      
* Scope::                       
@end menu

@node Related work, Assert, Introduction, Introduction
@section Related work
The Nana project was inspired by some other projects, in particular:

@itemize @bullet
@item Anna - Anna stands for "Annotated Ada" where the programmer inserts
various assertions into the code which can be automatically validated. 
To quote from the WWW Virtual Library entry on Anna:

@quotation
Anna is a language for formally specifying the intended behaviour of Ada
programs. It extends Ada with various different kinds of specification
constructs from ones as simple as assertions, to as complex as algebraic
specifications. A tool set has been implemented at Stanford for
Anna, including: 

@enumerate
@item standard DIANA extension packages, parsers, pretty-printers; 
@item a semantic checker; 
@item a specification analyser; 
@item an annotation transformer; and 
@item a special debugger that allows program debugging based on formal specifications 
@end enumerate

All tools have been developed in Ada and are therefore extremely
portable. Anna has thus been ported to many platforms. For more
information send e-mail to "anna-request@@anna.stanford.edu". Before
down loading the huge Anna release, you may wish to copy and read some
Anna LaTeX reports.

@end quotation 

Anna is available from: @code{ftp://anna.stanford.edu/pub/anna}

@item Eiffel - the Eiffel programming language provides support in the language
flexible assertion checking. To quote from the Eiffel page in WWW
Virtual library:

@quotation

Eiffel is a pure object-oriented language featuring multiple
inheritance, polymorphism, static typing and dynamic binding, genericity
(constrained and unconstrained), a disciplined exception mechanism,
systematic use of assertions to promote programming by contract, and
deferred classes for high-level design and analysis.
@end quotation

@item APP - Annotation PreProcessor.
The APP was written by David S. Rosenblum and provides assertion checking
functions for C and C++. It is implemented using a preprocessor wrapper
around the C preprocessor and supports quantifiers and before/after state.
 
See "A Practical Approach to Programming with Assertions" in
Vol 21, No. 1, January 1995 of IEEE Transactions on Software Engineering
for an interesting paper describing APP@. Unfortunately the APP tool
doesn't seem to be freely available (I'm willing to be corrected on this). 
Note that any similarity between my examples and David's are due
to morphic resonance.

@item ADL - the Assertion Definition Language.

To quote from @code{http://www.sunlabs.com/research/adl/}:

@quotation 
ADL (Assertion Definition Language) is a specification
language for programming interfaces. It can be used to describe the
programmer's interface to any C-callable function, library or system
call.

The Practical Specification Language.

ADL is the world's most practical specification language because: 

@itemize @bullet
@item Even partial specifications are useful 
@item Test programs can be automatically generated from ADL specifications 
@item Specifications are external to the implementation of the interface, so that they are vendor-independent.
@end itemize

An Automated Test Generator.

An ADL specification is not just a paper document. It can be compiled
by ADLT (the ADL translator). ADLT generates:

@itemize @bullet
@item Header files, that can be used in an implementation
@item Test programs, that ensure that any implementation meets the
specification
@item Natural-language documentation, derived directly from the specification 
@end itemize

ADLT can be used: 

As a test generator, to create tests for existing software or for
existing standards As a development tool, to ensure that
documentation, software, and tests are aligned, and to
enable concurrent work on all three aspects of software production.
@end quotation
@end itemize

Nana is essentially a poor mans implementation of some of these ideas
which works for C and C++. Ideally in the best of all possible worlds
you might want to look at Eiffel or in the military world Ada and Anna.
If you use TCL/TK you might also be interested in Jon Cook's 
@samp{AsserTCL} package.

@node Assert, Scope, Related work, Introduction
@section Assert.h considered harmful
Most C programmers become familiar with assertions from the the
@code{assert.h} header. As such its a very good thing and has a nice
simple implementation. However it is also inefficient and leads some
people to the conclusion that assertion checking is an expensive luxury.

The implementation of @code{assert.h} as distributed with @code{gcc}
looks like the following (after a bit of editing):

@example
# ifndef NDEBUG
# define _assert(ex)	@{if (!(ex)) \
                         @{(void)fprintf(stderr, \
                           "Assertion failed: file \"%s\", line %d\n", \
                           __FILE__, __LINE__);exit(1);@}@}
# define assert(ex)	_assert(ex)
# else
# define _assert(ex)
# define assert(ex)
# endif
@end example

There are are two main problems with this:

@enumerate
@item Code space overhead: each call to @samp{assert} generates 2 function
calls with 4 and 1 arguments plus strings for error messages. 
If @code{assert.h} had library code support we could make the implementation
much more space efficient, e.g. by calling a single function on error
detection.   
@item The default behaviour simply prints a message and dies, ideally
you like to be able to use a debugger to determine why the assertion
failed. Even if you run this under the debugger you can't observe the
failures of variables are an assert failure because the process exits
rather than aborting back to the debugger.
@end enumerate

Of course everyone merely rewrites their own @samp{assert} macro so
these are not significant objections. The only problem is if the author
uses the libraries without modification.

@node Scope,  , Assert, Introduction
@section Scope of this document
This document aims to both describe the library and provide a tutorial
in its use. Further work is required, particularly on the tutorial sections. 
If anyone has any suggestions please send them to me.

@node Installation, Invoking, Introduction, Top
@chapter Installing the Nana library
Nana uses the normal GNU install method in the same way as @samp{gcc}
and @samp{gdb}. To install nana in the default location
@samp{/usr/local/@{bin,lib,include@}} you would use:

@example
% gzcat nana-1.10.tar.gz | tar xvf -
% cd nana-1.10
% ./configure 
% make
% make install
% make check
% make check-mail
% make subscribe 
@end example

If you wish to produce space and time efficient code then replace
the @samp{./configure} with:

@example
% I_DEFAULT=fast ./configure
@end example

If you are using a Pentium compatiable CPU which supports the
@samp{RDTSC} instruction you may wish to enable cycle level timing
in @samp{cycles.h} by using:

@example
% ./configure --enable-rdtsc
@end example

The @var{check-mail} and @var{subscribe} targets both send e-mail. If
you need to change the mailer used try something like:

@example
% make MAILER=elm subscribe
@end example

@strong{Note:} we need to install nana before running the @samp{make check} 
target. The @samp{check-mail} target sends the test report
via e-mail to the @samp{gnuware@@cs.ntu.edu.au}.

Of course things are never that simple.  If you want to install Nana in
a different location or change the behaviour on error detection see @ref{Configure}.

Each of the sub-directories nana can be compiled and installed
separately, e.g. if you don't need the documentation you can just
compile and install from the @samp{src} sub-directory after doing the
configure statement.

Note that some of the subdirectories contain code that you may 
wish to install, improve or inspect. In particular:

@itemize @bullet
@item @samp{emacs} -- a protype emacs mode for browsing log files.
@item @samp{examples} -- some small examples.
@item @samp{gdb} -- some tools for use with gdb, in particular a statement
        level trace utility and some gdb patches.
@item @samp{perf} -- a tool for measuring space/time of code fragments.
@item @samp{shortform} -- a shortform generator which produces a HTML
summary of your codes interface.
@item @samp{tcl} -- a prototype TCL driver. We actually have a few more
TCL tools in the works so if you're interested contact the author.
@end itemize

@menu
* Required Software::           
* Optional Software ::          
* Configure::                   
* Variables::                   
* Supported Platforms::         
* Supported Debuggers::         
* Known Problems::              
* Bug Reports::                 
* New Versions::                
@end menu

@node  Required Software, Optional Software , Installation, Installation
@section Required Software
The following software is possibly required to run nana.

@ftable @code
@item gcc-2.7.2
Nana makes use of two GNU extensions in its library so you really should
be using @samp{gcc}. Some of the code can be used with any C compiler,
though it may not be worth the bother. The dependencies on gcc are in 
@samp{Q.h} which uses the statement value extension and in @samp{L.h}
which uses the variable number of arguments extension to @samp{cpp}.
@item gdb-4.16+
A recent version of @samp{gdb} is worthwhile, some early 4.?? versions
had problems setting a large number of breakpoints. Note that 
@samp{gdb-4.17} is available and has a few improvement which are useful
for some parts of this package including the tools in @samp{gdb}.
@item gmake
The @samp{configure} script and @samp{Makefiles} are generated using the
@samp{automake} and @samp{autoconf} programs. They should be reasonably
portable but if you have problems try using GNU make. For example on
some old DEC boxes we have had strange behaviour using the system make.
@end ftable

For a listing of porting results including software versions see:

@center @samp{http://www.cs.ntu.edu.au/homepages/pjm/nana-bug/}

@node Optional Software , Configure, Required Software, Installation
@section Optional Software

In addition to the required software you might also be interested
in:

@itemize @bullet
@item @samp{http://www.cs.tu-bs.de/softech/ddd/} -- a smart frontend for
gdb which can display dynamic data structures such as linked lists, etc.
@item @samp{ftp://ftp.ci.com.au/pub/psim/} -- a cycle level simulator
for the PowerPC@. A fine piece of work.
@end itemize

@node Configure, Variables, Optional Software , Installation
@comment  node-name,  next,  previous,  up
@section Configure
Nana uses a standard GNU @code{autoconf} generated @code{configure}
script. The @code{configure} script checks the setup on your machine and
then generates the appropriate Makefiles. Some of the things checked by
configure include:

@enumerate
@item Which compiler, compiler flags and libraries to use, e.g. you
might need to include a @code{-lposix} flag to the linker to build programs
on your machine.
@item Which header (.h) files are available on this machine, e.g. is
 @code{unistd.h} available on this machine.
@item Where to install programs, header file, man pages, etc.
@end enumerate

In addition @samp{configure} uses the host architecture and operating system
to generate the @samp{nana-config.h} file. This file contains some macro
definitions which define how nana works on particular operating systems
and hardware architectures. 

For example on @samp{i386} machines we would use the @samp{asm("hlt")}
instruction whenever an assertion fails, on a @samp{sparc} we would use
@samp{asm("unimp")}. Otherwise we would default to a plain C call to
@samp{abort()} If @samp{configure} does not recognise your machine it
uses plain C code.

You may wish to change these defaults on installation, one method is to edit 
a local copy of the @samp{nana-config.h} file. Alternately you can define 
the code yourself in the call to @samp{configure}. For example
to redefine the action we take when an error is detected by the @code{I}
macro we can use: 

@example
I_DEFAULT_HANDLER="restart_system()" ./configure
@end example

As well as simple calls to routines various other bits of information
are passed off to the @samp{I_DEFAULT_HANDLER} such as the expression
that failure and a failure code. For example:

@example
% I_DEFAULT_HANDLER="restart(line,file,param)" ./configure
@end example

The default for @samp{I_DEFAULT_HANDLER} calls a function which prints a
message and then dumps core.  Different behaviour on failure can be
organised by setting the @samp{I_DEFAULT} to @samp{fast}, i.e. plain
core dump or @samp{verbose} which prints an error messsage and then does
the core dump.

@example
% I_DEFAULT=fast ./configure   
@end example
 
For nana the following examples may be useful:

@enumerate
@item @code{./configure} 

Accept the default values for everything. In particular the files will
be installed in:


@center @samp{/usr/local/@{bin,include,lib,man,info@}}

@item @code{./configure --prefix=~project/tools}

Install the files into:

@center @samp{~project/tools/@{bin,include,lib,man,info@}}

@item @code{./configure --bindir=~project/bin --libdir=~/project/lib \@*
--includedir=~/project/headers --infodir=/usr/local/info \@*
--mandir=~/project/doc}

The install directory for program (@samp{bin}), etc can all be set with
command line arguments to @samp{configure}.

@item @code{CC=xacc LIBS=-lposix ./configure sun3}

If the defaults chosen by @samp{configure} are not correct you can
override them by setting variables such as @code{CC} before calling
 @samp{configure}. The @samp{sun3} argument is used to identify the
machine we are running on and may be necessary on some machines.

@item @code{./configure --help}

And of course when in doubt ask for help.
@end enumerate 

For even more details see the file @samp{INSTALL.con} which contains the
generic instructions for use with @samp{autoconf} generated
@samp{configure} scripts.

@node Variables, Supported Platforms, Configure, Installation
@section Variables for ./configure
The configure program uses the following shell variables to change
various defaults.  Another method is simply to edit the 
@samp{nana-config.h} file. Most of these values should be auto detected,
so you can ignore this section until your need to save a few 
bytes of store by using @samp{asm("hlt")} instead of a call to 
@samp{abort()}. 

@ftable @code
@item DI_MAKE_VALID_BREAKPOINT
This text is inserted when the @samp{DI.h} library needs to set a
breakpoint in the generated code. It should ideally update all
variables which being kept in registers etc so that gdb gets the
correct values for each variable.

Possible values include:

@enumerate
@item @samp{asm("nop")} -- a single @samp{nop} instruction to set the
breakpoint at.

This is the default.

@item @samp{_vi = 0} -- where @samp{_vi} is a global volatile int.
@item @samp{_vi = (exprn)} -- where @var{exprn} is the expression
we are checking for this assertion.
@item @samp{/* nothing */} -- nothing at all, this means the breakpoint
will be set at the start of the next statement which works most of the
time. However for some examples this will do the wrong thing.
@end enumerate
@item DL_MAKE_VALID_BREAKPOINT
Used for the same purpose as @samp{DI_MAKE_VALID_BREAKPOINT} for
@samp{DL.h}. It also defaults to @samp{asm("nop")}.
@item I_DEFAULT_HANDLER
The code called when @samp{I.h} detects an error.
@ftable @code
@item asm("hlt") 
Some machines use a @samp{hlt} instruction.
@item asm("unimp")
And other machines use a @samp{unimp} instruction.
@item abort()
Or we could use a call to @samp{abort} which is at least standard C@. On
some machines this is significantly larger than a single @samp{hlt}
instruction. 
@item restart()
Or a call to a function which attempts to restart the system.
@end ftable
@item ALWAYS_INCLUDE_MALLOC
This is a dodgey for some versions of Linux which don't seem to include 
@samp{malloc} when you include @samp{stdio.h} and use @samp{print}. This
causes problems for @samp{gdb} since it uses @samp{malloc} in the
executable to implement parts of its functionality. 

This kludge should be removed!
@item GDB 
This is the pathname of the version of GDB you wish to use.
For example on my FreeBSD box we have gdb-4.16 installed in @samp{/usr/bin}
and gdb-4.17 in @samp{/usr/local/bin/} to optimise confusion. If you
wish nana to use 4.17 try something like:

@example
GDB=/usr/local/bin/gdb ./configure
@end example
@end ftable

@node Supported Platforms, Supported Debuggers, Variables, Installation
@comment  node-name,  next,  previous,  up
@section Supported Platforms
Nana has been tested on the following platforms:

@enumerate
@item i386-unknown-linux, gcc-2.7.0, gdb-4.16 
@item sparc-sun-sunos4.1.4, gcc-2.7.2.f.1, gdb-4.16 
@item sparc-sun-solaris2.3, gcc-2.7.2, gdb-4.16 
@item alpha-dec-osf3.2, gcc-2.7.2, gdb-4.16 
@item mips-sgi-irix5.3, gcc-2.7.0, gdb-4.16 
@item powerpc-ibm-aix3.2.5, gcc-2.6.3, gdb-4.16 
@end enumerate

The @samp{alpha-dec-osf3.2}, @samp{mips-sgi-irix5.3} and
@samp{powerpc-ibm-aix3.2.5} implementations have problems when you
compile with @samp{-O2} or @samp{-O3} optimisation. This causes some
errors in the the debugger based assertion and logging code since
variables can be removed or changed by optimisation. At @samp{-O}
everything passes. Regardless of optimisation the C based checking code
passes all tests on these platforms.

If you use nana on a new platform please send the report file
to me via the @samp{make check-mail}
command. A machine generated list of this information is available 
at:

@center @samp{http://www.cs.ntu.edu.au/homepages/gnuware/nana}

(Warning this page is out of date and may be fixed shortly)

@node Supported Debuggers, Known Problems, Supported Platforms, Installation
@comment  node-name,  next,  previous,  up
@section Supported Debuggers

Currently Nana works with the GNU GDB debugger which is available on a
wide range of platforms including embedded systems and even provides
support for remote debugging. 
Porting to any reasonable debugger with conditional
breakpoints and commands is not very difficult. 

As an example of an unreasonable debugger, Nana has been ported to
work with the Microsoft CodeView debugger. The port is small (60 lines of
code) but suffers from a problem with variable scoping in CodeView. If
a breakpoint is set at a point in the code the expressions are not
evaluated from that particular scope. For example setting a breakpoint
in the function @code{f} cannot access a variable local to @code{f}
directly. CodeView has a unique (expletive deleted) scope operator
which you must use to set the scope @samp{@{...@}}.  This makes the
interface somewhat less than beautiful.

Another good thing about CodeView is to try a debug command which prints a
message which contains a single open @samp{@{}. This of course causes it
to hang and was the main problem during the porting to CodeView which
took a whole day.@footnote{And about 60 reset cycles where the machine
went off into hyperspace.} 

If anyone is interested I may release the CodeView implementation,
please contact me if you are interested. Of course a better bet is probably 
to move to the @samp{gdbserver} system. I think @samp{gdb} has been released
as a native even for some Microsoft operating systems.

Other debuggers like DBX don't seem to be worth the trouble since gdb
works on those machines. A redesign of the nana internals may also be useful
if we decide portability between debuggers is actually useful.

@node Known Problems, Bug Reports, Supported Debuggers, Installation
@comment  node-name,  next,  previous,  up
@section Known Problems
Nana has the following known features (or perhaps problems):

@enumerate
@item Nana macros which use the debugger 
such as @code{DI} or @code{DL} should be on lines by themselves. If you
mix code and nana macros on the same line you will get errors, e.g:

@example
main()@{
   int x;
   x = 5; x--; DI(x == 4); 
@}
@end example

This doesn't work since breakpoints are set at line boundaries rather
than statement ones. Of course anyone who writes code like this deserves
whatever happens to them.

@item Optimisation can remove variables so that debugger based
assertions (@samp{DI.h}) do not work correctly. As usual the
interaction between the debugger and the compiler is rather
complicated. This may not be a problem if the appropriate compile-time
flags are selected, e.g. @samp{-O0 and -O1} work on most platforms.

@item The @samp{Q.h} macros depend on the statement value extension to 
GNU CC so if you wish to use them you must use GCC@. This can be fixed
for C++ in a possibly useful manner, I can't see any solution for C@.

@item The logging macros depend on the Var Args extension provided by the
GNU C Preprocessor.@footnote{This allows a variable number of arguments to
C preprocessor macros.} We could (probably will) implement a fix for this 
based on the tricks in the C FAQ@. Unfortunately these tricks are not pretty.
For now interested users could simply replace their CPP with the GNU CPP
if they wished to stay with non-standard compilers. 

@item The @samp{Q.h} macros do not work in the debugger since @samp{gdb}
does support the statement expression extension.

@item Multiline expressions do not work as expected in the debugger since
you need to use a blackslash as an escape at the end of the line. 
For example:

@example
	 DI(x +
            10 > 30);
@end example
A few backslashes may solve this particular problem.

@item Problems with the @samp{configure} script.

The @samp{configure} script automatically detects the target operating
system and architecture and then generates @samp{nana-config.h}. If the
options selected in @samp{nana-config.h} are incorrect they can be
edited by hand and installed in the usual include directory. The easiest
method is simply to delete all macros in @samp{nana-config.h} since the
system defaults to more portable (and less efficient)
implementations. If you wish to do this from the configure script you 
can try giving a unsupported machine type, e.g.

@example
% ./configure pdp11-dec-ultrix
@end example

@item Some users have reported problems with the @code{configure}
script detecting @code{vsnprintf}. If @code{configure} doesn't find it
and it does exist then simply define it in @samp{nana-config.h} as per
the previous question. 

If @code{vsnprintf} really doesn't exist then get a new C library,
possibly the GNU libc.

@item The use of @code{vsprintf} opens a security hole since no 
bounds checking is done by it. Nana attempts to use @code{vsnprintf}
which is safe when it exists but it will resort to @code{vsprintf}
if it can't find @code{vsnprintf}. All careful people should make
sure that they have a library with @code{vsnprintf}.

@item @code{Qstl.h} doesn't work since the STL library has not
  been installed along with C++. This can of course be fixed by installing
  STL@. See: 

@center @samp{http://www.stl.org}

@item @code{STL} header file errors due to nana.

The C++ @code{STL} header files for version 3.0 at least must
be included before the @code{Q.h} file. 

The problem is caused by the STL files using @code{S} as a template
argument. Of course @code{Q.h} uses @code{S} for summing a
series. As usual namespace pollution strikes again.

(Thanks to Han Holl for this particular problem).

@item If you try to use the debugger based macros
such as @code{DI.h} or @code{DL.h} on code that has not 
been compiled with @code{-g} then misery follows.

(Thanks to Eugen Dedu for this one)
@end enumerate

@node Bug Reports, New Versions, Known Problems, Installation
@comment  node-name,  next,  previous,  up
@section Bug Reports

If you think you have found a bug in the Nana library, please
investigate it and report it.  

@itemize @bullet
@item Please make sure that the bug is really in the Nana library.
@item You have to send us a test case that makes it possible for us to
reproduce the bug.
@item You also have to explain what is wrong; if you get a crash, or if the
results printed are not good and in that case, in what way.
Make sure that the bug report includes all information you would
need to fix this kind of bug for someone else.  
@end itemize

If your bug report is good, we will do our best to help you to get a
corrected version of the library; if the bug report is poor, we won't do
anything about it (apart from asking you to send better bug reports).

Send your bug report to:

@center @samp{nana-bug@@cs.ntu.edu.au}

Copies of bug reports will be kept at:

@center @samp{http://www.cs.ntu.edu.au/homepages/pjm/nana-bug/}

@node New Versions,  , Bug Reports, Installation
@comment  node-name,  next,  previous,  up
@section New Versions
New versions of nana will be made available at:

@center @samp{ftp://ftp.cs.ntu.edu.au/pub/nana/} 

If you wish to be informed about new
releases of nana then subscribe to the nana mailing list. 
Send a message containing @samp{subscribe} <your e-mail address> to:

@center @samp{mailto:nana-request@@it.ntu.edu.au}. 

A hypermail archive of this list is kept at:

@center @samp{http://www.cs.ntu.edu.au/hypermail/nana-archive}

If you wish to send a message to the list send it to
@samp{mailto:nana@@it.ntu.edu.au}.

@node Invoking, Interface, Installation, Top
@chapter Invoking Nana
The functions defined by Nana are implemented either as pure C code or
as a set of commands which are generated for the debugger. 
To use the C based support for assertion checking you would use
something like:

@example 
#include <nana.h> /* this file includes the other nana .h files */

int floor_sqrt(int i) @{ /* returns floor(sqrt(i) */ 
  int answer;
  I(i >= 0); /* assert(i >= 0) if i -ve then exit */
  ...; /* code to calculate sqrt(i) */
  L("floor_sqrt(%d) == %d\n", 
        i, answer);  /* logs a printf style message */
@}
@end example

To compile and link the previous code you may need to use the @samp{-Ipath}
or @samp{-lnana} flags with the compiler. For example:

@example
% gcc toy.c -lnana
@end example

If the nana headers have been installed in a strange location you may
need to do something like:

@example
% gcc -I<strange location>/include toy.c -L<strange location>/lib -lnana
@end example

The next example uses the debugger versions of @samp{L} and @samp{I}.
If the code is run under the debugger these checks will occur, otherwise
they take up a negligible amount of space and time.

@example 
#include <nana.h> /* this includes the other nana .h files */

int floor_sqrt(int i)@{
  int answer;
  DI(i >= 0); /* assert(i >= 0) if i -ve then exit */
  ...; /* code to calculate sqrt(i) */
  DL("floor_sqrt(%d) == %d\n", i, answer);  /* logs a printf style message */
@}
@end example

To generate the debugger commands from the C source we just run the
@samp{nana} filter over the program and then execute the commands
under gdb using the @samp{source} command. You also need to compile
the program with the @samp{-g} option so the debugger works. So
something like:

@example
% gcc -g sqrt.c
% nana sqrt.c >sqrt.gdb
% gdb a.out
(gdb) source sqrt.gdb
breakpoint insert: ...
(gdb) run
...
(gdb) quit
@end example

Note that any C preprocessor flags which you use must be passed off to 
the @samp{nana} command. The best way to do this of course is in a
Makefile. Something like the following works for GNU Make:

@example
%.nana: %.c 
        nana $(CFLAGS) $< >$@@
@end example

The @samp{nana} filter can also be run over multiple source files in a
single run if thats more convenient. 

For convenience a number of other simple scripts are provided, in
particular to: 

@ftable @code
@item nana-run
Run a program under the debugger without prompting, etc.
For example:

@example
% nana-run a.out -x main.gdb
output from program
@end example

@item nana-clg
Compiles the program, generates the debugger commands and the runs the
program using @samp{nana-run}. For example:

@example
% nana-clg -O3 main.c
output from program
@end example

You can change the compiler invoked by @samp{nana-clg} by redefining 
the @samp{NANACC} environment variable. For example:

@example
% NANACC=g++ nana-clg -O3 main.cc
@end example

The installation also @samp{nana-c++lg} which compiles your code
using a GNU C++ compiler.

@item nana-trace
Generates a line by line trace of the execution of a program 
using GDB@. For example:

@example
% nana-trace a.out
54           printf("main()\n");
55           x = distance(5,-5);
distance (i=5, j=-5) at test.c:47
47           i = -i;
48           j = -j;
...
@end example

The arguments to @samp{nana-trace} are passed directly to GDB@. If you
wish display variables or call procedures on each line then could use
something like:

@example
% nana-trace -x mycommands.gdb a.out
@end example

Where the @samp{mycommands.gdb} contains the GDB commands such as 
@samp{display x} which causes @samp{x} to be printed every time the
debugger gets control of the program.

@end ftable

@node Interface, Shortform, Invoking, Top
@chapter Interface
This section describes the details of the interface to nana library.

All of the files can be included multiple times without
ill--effect since they use the C preprocessor to make sure the header
declarations are only seen the first by the compiler.
Each of the files can also be included individually.

@menu
* nana.h::                      
* WITHOUT_NANA::                
* I.h::                         
* DI.h::                        
* L.h::                         
* L_buffer.h::                  
* L_times.h::                   
* DL.h::                        
* GDB.h::                       
* Q.h::                         
* Qstl.h::                      
* now.h::                       
* cycles.h::                    
* eiffel.h::                    
* assert.h::                    
* calls.h::                     
@end menu

If any of the following routines have an internal problem (e.g. malloc
fails due to lack of memory) they will call the @samp{nana_error} function
defined in @samp{nana_error.c}. By default this function prints a message
and dumps core using @samp{abort}. If you wish to override this behaviour
you should define your own handler before linking in the nana library.

@node nana.h, WITHOUT_NANA, Interface, Interface
@section nana.h: the main header file
The @samp{nana.h} file includes most of the other files in the
library. In particular it @samp{#include's} the following
files:

@ftable @code
@item I.h
@item DI.h
@item L.h
@item DL.h
@item Q.h
@item GDB.h
@end ftable

@node WITHOUT_NANA, I.h, nana.h, Interface
@section WITHOUT_NANA: disabling all nana code for portability.
If you wish to disable all nana code you can @samp{#define} the
@samp{WITHOUT_NANA} macro. This selects versions of the 
macros defined in @samp{I.h},@samp{L.h}, etc which map to 
@samp{/* empty */}. 

So if you are using nana for your development but don't wish to 
force  your customers to use it you can add an option to your
@samp{configure} script to define/undefine @samp{WITHOUT_NANA}. 
In addition you will need to distribute copies of the nana header
files with your package to get the stubs.

Note that the @samp{L.h} and @samp{DL.h} macros use the 
macro variable number of arguments extension provided by 
GNU C@. If you wish your code to be portable you should use
the macros @samp{VL((..))}, etc rather than @samp{L(..)} to
avoid problems with non GNU C preprocessors which only take a fixed
number of arguments.

@node I.h, DI.h, WITHOUT_NANA, Interface
@comment  node-name,  next,  previous,  up
@section I.h: C based invariant checking
This implements the C based invariant checking code and is a
replacement for @samp{assert.h}. The first two macros are the normal
user interface; the remainder are used for configuring the behaviour on
failure, etc. 

@deftypefn Macro void I (bool @var{exprn})
The @var{exprn} should always be true if the program is correct.  If the
@var{exprn} is false a message will be printed, followed by core
dump.@footnote{If you don't want a core dump then look at stopping the core
dumps with @code{ulimit} rather than changing the handler.}

Checking can be enabled and disabled by using the @var{I_LEVEL}
and @var{I_DEFAULT_GUARD} macros. See the definitions below for these
macros for further details.

Note that @var{exprn} should have no side-effects@footnote{Side-effects
include such operations as input/output or assignments, e.g. @samp{x++}.}
since disabling checking shouldn't change your programs behaviour.

@example
  I(z != 0); 
  x = y / z;
@end example
@end deftypefn

@deftypefn Macro void N (bool @var{exprn})
The opposite of @samp{I}, i.e. the expression must never ever be true if
the program is working properly. It is equivelant to @code{I(!(e))} and
exists as a piece of syntactic sugar which may be helpful for complicated
boolean expressions.

@example
char* strdup(char *s) @{
  N(s == NULL);
  ...;
@}
@end example
@end deftypefn

@deftypefn Macro int I_LEVEL 
The @samp{I_LEVEL} macro is used to globally enable and disable
checking by the macros in this file. It can take on one of three values:

@ftable @code
@item 0
Disable all checking. Regardless of anything else no code will be
generated for @code{I}, @code{N}, etc.
@item 1 
Enable checking only if the corresponding guard condition is true. The
guard condition can be used to enable and disable checking at compile
and run time.
@item 2
Enable all checking regardless of guard conditions.
@end ftable

@code{I_LEVEL} defaults to @code{1}. 
@end deftypefn

@deftypefn Macro bool I_DEFAULT_GUARD
The @code{I_DEFAULT_GUARD} is used to selectively enable or disable
checking at compile or run time. 

@code{I_DEFAULT_GUARD} defaults to @code{TRUE}, i.e. always enabled.

A user would typically define @code{I_DEFAULT_GUARD} to be global or local
variable which is used to turn checking on or off at run--time. For
example:

@example
#define I_DEFAULT_GUARD i_guard > 0

extern int i_guard;
@end example
@end deftypefn

@deftypefn Macro text I_DEFAULT_PARAMS
This is passed off to the @code{I_DEFAULT_HANDLER} and defaults to
nothing, it is just some text and is intended to pass failure codes
(e.g. @code{IEH303}) or requests (e.g. @code{HW_DEAD}) information off
to the handler.

@code{I_DEFAULT_PARAMS} defaults to nothing.
@end deftypefn

@deftypefn Macro void I_DEFAULT_HANDLER (char *@var{exprn}, char *@var{file}, int @var{line}, @var{param})

When an error is detected the @code{I_DEFAULT_HANDLER} will be called to
handle the error. The arguments are:

@ftable @code
@item exprn
A string representation of the expression that has failed, e.g. @code{"I(i>=0)"}.
@item file
The file that this error occurred in, i.e. @code{__FILE__}.
@item line
The line number for the error, i.e. @code{__LINE__}.
@item param
An optional parameter which can be passed across which defaults to
@code{I_DEFAULT_PARAMS}. This can be used to pass failure codes or other
information from the checking code to the handler.
@end ftable
@end deftypefn

All of the remaining macros are used to individually override the
default values defined above. Normally these macros would be used in a
system wide header file to define macros appropriate for the
application. For example you might use @samp{IH} to define 
different checking macros for hardware and software faults.

@deftypefn Macro void  I (bool @var{e})
@deftypefnx Macro void  IG (bool @var{e}, bool @var{g}) 
@deftypefnx Macro void  IH (bool @var{e}, Macro @var{h}) 
@deftypefnx Macro void IP (bool @var{e}, Text @var{p}) 
@deftypefnx Macro void IGH (bool @var{e}, bool @var{g}, Macro @var{h}) 
@deftypefnx Macro void IGP (bool @var{e}, bool @var{g}, Text @var{p}) 
@deftypefnx Macro void IHP (bool @var{e}, Macro @var{h}, Text @var{p}) 
@deftypefnx Macro void IGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 
@deftypefnx Macro void N (bool @var{e}) 
@deftypefnx Macro void NG (bool @var{e}, bool @var{g}) 
@deftypefnx Macro void NH (bool @var{e}, Macro @var{h}) 
@deftypefnx Macro void NP (bool @var{e}, Text @var{p}) 
@deftypefnx Macro void NGH (bool @var{e}, bool @var{g}, Macro @var{h}) 
@deftypefnx Macro void NGP (bool @var{e}, bool @var{g}, Text @var{p}) 
@deftypefnx Macro void NHP (bool @var{e}, Macro @var{h}, Text @var{p}) 
@deftypefnx Macro void NGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 
@end deftypefn

We also provide support for referring to previous values of variables in 
postconditions. The @code{ID} macro is used to create variables to 
save the old state in. The @code{IS} and @code{ISG} macros are to 
set these values. 

@deftypefn Macro void ID (Text @var{decln}) 
@deftypefnx Macro void IS (Text @var{assignment})
@deftypefnx Macro void ISG (Text @var{decln}, bool @var{g})
@end deftypefn

For example:
@example
void ex(int &r) @{
  ID(int oldr = r); /* save parameter */
  g(r);
  I(oldr == r); /* check r is unchanged */
  while(more()) @{
    IS(oldr = r); /* assign r to oldr */
    h(r);
    I(oldr == r * r);
  @}
@}
@end example

@node DI.h, L.h, I.h, Interface
@comment  node-name,  next,  previous,  up
@section DI.h: debugger based invariant checking
This implements the debugger based invariant checking code.
The first two macros are the normal
user interface; the remainder are used for configuring the behaviour on
failure, etc. Note that these macros have no effect unless you run your 
program under the debugger and read in the commands generated by the
@samp{nana} command. You also need to compile the program with 
the @samp{-g} option.

@deftypefn Macro void DI (bool @var{exprn})
The @var{exprn} should always be true if the program is working. 
If it is true then nothing happens otherwise the code given by
@samp{DI_DEFAULT_HANDLER} will be called which by default prints 
a message and dies just like @samp{assert.h}.  

The checking using @var{DI} can be enabled and disabled by using the
@var{DI_LEVEL} and @var{DI_DEFAULT_GUARD} macros. See the definitions
below for these macros for further details.

Note that @var{exprn} should have no side-effects@footnote{Side-effects
include operations like input/output or assignments.} since 
disabling the checking shouldn't change your programs behaviour.
@end deftypefn

@deftypefn Macro void DN (bool @var{exprn})
The opposite of @samp{DI}, i.e. the expression must never ever be true if
the program is working properly. It is equivelant to @code{I(!(e))} and
exists as piece of syntactic sugar which is helpful for complicated
boolean expressions.
@end deftypefn

@deftypefn Macro int DI_LEVEL 
The @samp{DI_LEVEL} macro is used to globally enable and disable
checking, in particular it can take on one of three values:

@ftable @code
@item 0
Disable all checking. Regardless of anything else no code will be
generated for @code{DI}, @code{DN}, etc.
@item 1 
Enable checking only if the corresponding guard condition is true. The
guard condition can be used to enable and disable checking at compile
and run time.
@item 2
Enable all checking regardless of guard conditions, etc.
@end ftable

@code{DI_LEVEL} defaults to @code{1}. 
@end deftypefn

@deftypefn Macro bool DI_DEFAULT_GUARD
The @code{DI_DEFAULT_GUARD} is used to selectively enable or disable
checking at compile or run time. 

@code{DI_DEFAULT_GUARD} defaults to @code{TRUE}, i.e. always enabled.

A user would typically define @code{DI_DEFAULT_GUARD} to be global or local
variable which is used to turn checking on or off at run--time. For
example:

@example
#define DI_DEFAULT_GUARD (i_guard)

extern int i_guard;
@end example
@end deftypefn

@deftypefn Macro text DI_DEFAULT_PARAMS
This is passed off to the @code{DI_DEFAULT_HANDLER} and defaults to
nothing, it is just some text and is intended to pass failure codes
(e.g. @code{IEH303}) or requests (e.g. @code{HW_DEAD}) information off
to the handler.

@code{DI_DEFAULT_PARAMS} defaults to nothing.
@end deftypefn

@deftypefn Macro void DI_DEFAULT_HANDLER (char *@var{exprn}, char *@var{file}, int @var{line}, @var{param})

When an error is detected the @code{DI_DEFAULT_HANDLER} will be called to
handle the error. The arguments are:

@ftable @code
@item exprn
A string representation of the expression that has failed, e.g. @code{"I(i>=0)"}.
@item file
The file that this error occurred in, i.e. @code{__FILE__}.
@item line
The line number for the error, i.e. @code{__LINE__}.
@item param
An optional parameter which can be passed across which defaults to
@code{DI_DEFAULT_PARAMS}. This can be used to pass failure codes or other
information from the checking code to the handler.
@end ftable
@end deftypefn

@deftypefn Macro void DI_MAKE_VALID_BREAKPOINT (exprn @var{e})
This macro is used to ensure that a breakpoint can be set at the
location we are checking using @code{DI}, etc. It defaults to
@code{asm("nop")} and can be redefined by the user.
@end deftypefn

@deftypefn Macro void DI (bool @var{e})
@deftypefnx Macro void DIG (bool @var{e}, bool @var{g}) 
@deftypefnx Macro void DIH (bool @var{e}, Macro @var{h}) 
@deftypefnx Macro void DIP (bool @var{e}, Text @var{p}) 
@deftypefnx Macro void DIGH (bool @var{e}, bool @var{g}, Macro @var{h}) 
@deftypefnx Macro void DIGP (bool @var{e}, bool @var{g}, Text @var{p}) 
@deftypefnx Macro void DIHP (bool @var{e}, Macro @var{h}, Text @var{p}) 
@deftypefnx Macro void DIGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 
@deftypefnx Macro void DN (bool @var{e}) 
@deftypefnx Macro void DNG (bool @var{e}, bool @var{g}) 
@deftypefnx Macro void DNH (bool @var{e}, Macro @var{h}) 
@deftypefnx Macro void DNP (bool @var{e}, Text @var{p}) 
@deftypefnx Macro void DNGH (bool @var{e}, bool @var{g}, Macro @var{h}) 
@deftypefnx Macro void DNGP (bool @var{e}, bool @var{g}, Text @var{p}) 
@deftypefnx Macro void DNHP (bool @var{e}, Macro @var{h}, Text @var{p}) 
@deftypefnx Macro void DNGHP (bool @var{e}, bool @var{g}, Macro @var{h}, Text @var{p}) 

All of these macros are used to individually override the
default values defined above. Normally these macros
would be used in a system wide header file to define macros appropriate 
for the application.
@end deftypefn

@deftypefn Macro void DS (@var{e})
@deftypefnx Macro void DSG (@var{e}, @var{g})
These macros are used to assign values to convenience variables in the
debugger. Convenience variables are dynamically typed, global in scope
and initialised to 0. They start with a single @code{$} and can be used be
used for saving the state of program or for counting events. The
@samp{DS} macro executes @var{e} under the same rules as @code{DI}.
The @samp{DSG} macro executes @var{e} only if the the expression
@var{g} is true.

Note that @samp{DS} and @samp{DSG} can also be used for modifying
C variables and calling functions.
@end deftypefn

@node L.h, L_buffer.h, DI.h, Interface
@section L.h: support for printf style logging
These routines are used to provide logging functions. Messages can be
divided into classes and separately enabled and disabled.

@deftypefn Macro void L (@var{args}...) 
Used to log a message in a similar way to printf.

Defaults to a using @code{fprintf} on @code{stderr}.
@end deftypefn

@deftypefn Macro void LG (bool @var{guard}, @var{args}...) 
@deftypefnx Macro void LH (function @var{handler}, @var{args}...) 
@deftypefnx Macro void LP (text @var{param}, @var{args}...) 
@deftypefnx Macro void LGP (bool @var{guard}, text @var{param}, @var{args}...) 
@deftypefnx Macro void LHP (function @var{handler}, text @var{param}, @var{args}...) 
@deftypefnx Macro void LGHP (bool @var{guard}, function @var{handler}, text @var{param}, @var{args}...) 
And all of the special functions.

@end deftypefn

The macros such as @samp{L} depend on the GNU CC variable number of arguments 
to macros extension. If you wish to compile your code on other systems
you might wish to use the following variations on @samp{L}, etc.

@deftypefn Macro void VL ((@var{args}...)) 
@deftypefnx Macro void VLG ((bool @var{guard}, @var{args}...)) 
@deftypefnx Macro void VLH ((function @var{handler}, @var{args}...)) 
@deftypefnx Macro void VLP ((text @var{param}, @var{args}...)) 
@deftypefnx Macro void VLGP ((bool @var{guard}, @var{text param}, @var{args}...)) 
@deftypefnx Macro void VLHP ((function @var{handler}, text @var{param}, @var{args}...)) 
@deftypefnx Macro void VLGHP ((bool @var{guard}, function @var{handler}, text @var{param}, @var{args}...))
Each of these macros calls the corresponding function from the previous
group, i.e. by default @samp{VLG} is the same as a call to @samp{LG}.
If you define @samp{WITHOUT_NANA} all these macros are translated
to @samp{/* empty */}. 

Thus you can have nana under GCC whilst the code is still portable
to other compilers. However debugging information will not be available
on other platforms.

@strong{Note:} the argument list is surrounded by @strong{two} sets of 
brackets. For example:

@example
   VL(("haze in darwin = %d\n", 3.4));
@end example
@end deftypefn

@deftypefn Macro void L_LEVEL
Used to enable and disable logging independently of guard expressions.

@ftable @code
@item 2
Always print message
@item 1 
Print message only if the guard expression is true.
@item 0
Never print any messages.
@end ftable

Defaults to @code{1}.
@end deftypefn

@deftypefn Macro text L_DEFAULT_HANDLER
The default handler for printing which is simply the name of the
logging function or macro.

Defaults to @code{fprintf}
@end deftypefn

@deftypefn Macro bool L_DEFAULT_GUARD
The default guard condition for logging. 

Defaults to @code{TRUE}.
@end deftypefn

@deftypefn Macro text L_DEFAULT_PARAMS
The default parameter passed off to the logging function or macro.

Defaults to @code{stderr}
@end deftypefn

@deftypefn Macro void L_SHOW_TIME
If defined then display the time in front of each message.
@end deftypefn

@deftypefn Macro char* L_SHOW_TIME_FORMAT 
A format string for the time stamp in the log. By default it prints the
time out in seconds.
@end deftypefn 

@deftypefn Macro value L_SHOW_TIME_NOW
The name of a function that returns the time for the time stamp. This
defaults to the @samp{now} function from @samp{now.h}.
@end deftypefn 

@node L_buffer.h, L_times.h, L.h, Interface
@section L_buffer.h: a circular buffer for logging.
A traditional embedded systems trick is to log messages to a circular
buffer in core. This has the following benefits:

@enumerate
@item Speed -- writing to a in core buffer is much faster than spitting
out messages to a file on disk. It is often fast enough to leave at least
most of the messages in the final product.
@item Field debugging -- what the ... was the user doing before the
system crashed. Oh lets ask them, I'm sure they'll give us a good
problem report. 
@end enumerate

@deftypefn Type struct L_BUFFER 
Used to define buffer variables, it is similar to @samp{FILE*} type in 
@samp{stdio.h}. To create an instance use @samp{L_buffer_create}.
@end deftypefn

@deftypefn Function L_BUFFER* L_buffer_create (size_t @var{size})
@deftypefnx Function L_BUFFER* L_buffer_delete (L_BUFFER @var{*b})
These are used to create or delete a buffer which can contain @var{size}
characters. 

@example
  L_BUFFER *lbuffer;

  lbuffer = L_buffer_create(32*1024); /* create a 32K buffer */
  ...;
  L_buffer_delete(lbuffer); /* and delete it after use */
@end example
@end deftypefn

@deftypefn Function void L_buffer_wraparound (L_BUFFER @var{*b}, int @var{w})
A buffer created by @samp{L_buffer_create} is set up so that the new
messages will overwrite the older messages in the buffer. If you wish 
to disable this overwriting, e.g. to keep the first 32K bytes
of your system startup messages you should use @samp{L_buffer_wraparound}.
For example:

@example
  L_BUFFER *lb = L_buffer_create(32*1024);
  L_buffer_wraparound(lb, 0); /* disable wraparound */
@end example
@end deftypefn

@deftypefn Function void L_buffer_printf (L_BUFFER @var{*b}, const char @var{*fmt}, ...)
@deftypefnx Function void L_buffer_puts (L_BUFFER @var{*b}, const char @var{*str})
@deftypefnx Function void L_buffer_putchar (L_BUFFER @var{*b}, char @var{ch})
These are the routines which do that actual printing to the buffer.

@example
  L_buffer_printf(lbuffer, "U: user input %c\n", c);
  L_buffer_puts(lbuffer, "warning: its too hot");
  L_buffer_putchar(lbuffer, '*');
@end example

Note: a null pointer passed to the @samp{L_buffer_puts} function prints
as @samp{(null)}. @footnote{This was suggested by Phil Blecker.}
@end deftypefn

@deftypefn Function void L_buffer_clear (L_BUFFER @var{*b})
Clear the log, i.e. remove all messages and start again.
@end deftypefn 

@deftypefn Function void L_buffer_dump (L_BUFFER @var{*b}, FILE *@var{fp})
Dump the contents of the log @var{*b} to the file descriptor @var{*fp}. 
Typically @var{*fp} would be @samp{stderr}. 

Note that this does not change the contents of the buffer.  This is
important since we may have a hardware or software problem part of the
way through the dump operation and you don't want to loose anything.

To reset the buffer after a successful dump use @samp{L_buffer_clear}.

The output of @samp{L_buffer_dump} consists of a starting message
followed by the contents of the log. If a character in the log is not
printable we print it out in hex on a line by itself.

@example
* L_buffer_dump =
log message
and another
* non-printable character 0x1
more log messages
* end of dump
@end example
@end deftypefn 

You also need to be able to integrate these functions into your
design. See @samp{examples/ott.c} for a complicated example. Here we
will provide a simplified version which implements a new logging macro
called @samp{LFAST} which does a @samp{printf} to the @samp{log_buffer}.
If you want to have all messages going to a @samp{L_BUFFER} then you can
redefine @samp{L_DEFAULT_HANDLER}.

@example
/* project.h - the project wide include file */

#include <nana.h>
#include <L_buffer.h>

/* LFAST(char *, ...) - log a message to the log_buffer */
/*     ##f translates as the rest of the arguments to LFAST */

#define LFAST(f...) LHP(L_buffer_printf,log_buffer,##f)

extern L_BUFFER *log_buffer; /* the log buffer */
@end example

The main program merely creates the @var{log_buffer} and eventually
calls @samp{L_buffer_dump} to print out the buffer when the system dies.
@example
/* main.c - initialise the system and start things */

#include <project.h>

L_BUFFER *log_buffer;

main() @{
  log_buffer = L_buffer_create(16000); 
  if(log_buffer == NULL) @{ /* not enough store */
    ...
  @}
  LFAST("system starting at %f\n", now());
  ...;
@}

void fatal_error() @{ /* called on fatal errors */
  FILE *f = fopen("project.errors","w");
  L_buffer_dump(b, stderr); /* print log to stderr */
  L_buffer_dump(b, f); /* print log to file */
@}
@end example

@node L_times.h, DL.h, L_buffer.h, Interface
@section L_times.h: recording events and times.
This component is used to record events and times with a lower time 
and space overhead than the @samp{L_buffer.h} component. Instead
of using a @samp{printf} style string we simply record the time
and a pointer to a string identifying the event in a circular buffer.

@strong{Note 0:} the string arguments should not be modified after
a call since we record pointers to the strings rather
than the strings themselves.

@strong{Note 1:} there is no @var{printf} style formatting, e.g.
@samp{%d} in this package.

@deftypefn Type struct L_TIMES
Used to define buffers, it is similar to @samp{FILE*} type in 
@samp{stdio.h}. To create an instance use @samp{L_times_create}.
@end deftypefn

@deftypefn Function L_TIMES* L_times_create (int @var{size})
@deftypefnx Function L_TIMES* L_times_delete (L_BUFFER @var{*b})
These are used to create or delete a buffer which can contain @var{size}
messages.
@end deftypefn

@deftypefn Function void L_times_wraparound (L_TIMES @var{*b}, int @var{w})
A buffer created by @samp{L_times_create} is set up so that the new
messages will overwrite the oldest messages in the buffer. If you wish 
to disable this overwriting, e.g. to keep the first few messages
messages you could use @samp{L_times_wraparound(b,0)}.
@end deftypefn

@deftypefn Function void L_times_add (L_BUFFER @var{*b}, char @var{*m}, NANA_TIME @var{t})
Add an event identified by message @var{m} at time @var{t} to @var{b}.  
The type @var{NANA_TIME} defaults to @samp{double}. 
@end deftypefn

@deftypefn Function void L_times_dump (L_TIMES @var{*b}, FILE @var{*fd})
Dump the contents of the buffer out.
@end deftypefn

@deftypefn Function void L_times_clear (L_TIMES @var{*b})
Clear all the messages from @var{b}.
@end deftypefn

@node DL.h, GDB.h, L_times.h, Interface
@section DL.h: support for printf style logging
These routines are used to provide logging functions. Messages can be
divided into classes and separately enabled and disabled.
Note that these macros have no effect unless you run your 
program under the debugger and read in the commands generated by the
@samp{nana} command. You also need to compile the program with 
the @samp{-g} option.

@deftypefn Macro void DL (@var{args}...) 
Used to log a message.

Defaults to a using @code{fprintf} on @code{stderr}.
@end deftypefn

@deftypefn Macro void DLG (bool @var{guard}, @var{args}...) 
@deftypefnx Macro void DLH (function @var{handler}, @var{args}...) 
@deftypefnx Macro void DLP (text @var{param}, @var{args}...) 
@deftypefnx Macro void DLGP (bool @var{guard}, text @var{param}, @var{args}...) 
@deftypefnx Macro void DLHP (function @var{handler}, @var{args}...) 
@deftypefnx Macro void DLGHP (bool @var{guard}, function @var{handler}, @var{args}...) 
And all of the special functions.

@end deftypefn

The macros such as @samp{DL} depend on the GNU CC variable number of arguments 
to macros extension. If you wish to compile your code on other systems
you might wish to use the following variations on @samp{DL}, etc.

@deftypefn Macro void VDL ((@var{args}...)) 
@deftypefnx Macro void VDLG ((bool @var{guard}, @var{args}...)) 
@deftypefnx Macro void VDLH ((function @var{handler}, @var{args}...)) 
@deftypefnx Macro void VDLP ((text @var{param}, @var{args}...)) 
@deftypefnx Macro void VDLGP ((bool @var{guard}, @var{text param}, @var{args}...)) 
@deftypefnx Macro void VDLHP ((function @var{handler}, @var{args}...)) 
@deftypefnx Macro void VDLGHP ((bool @var{guard}, function @var{handler}, @var{args}...))
Each of these macros calls the corresponding function from the previous
group, i.e. by default @samp{VDL} is equivelant to a call to @samp{DL}.
If @samp{WITHOUT_NANA} is defined then the call too @samp{VDL} is 
equivelant to @samp{/* empty */}.

Thus you can have debugging under GCC whilst the code is still portable
to other compilers. However debugging information will not be available
on other platforms.

@strong{Note:} the argument list is surrounded by @strong{two} sets of 
brackets. For example:

@example
   VDL(("haze in darwin = %d\n", 3.4));
@end example
@end deftypefn

@deftypefn Macro int DL_LEVEL
Used to enable and disable logging independently of guard expressions.

@ftable @code
@item 2
Always print message
@item 1 
Print message only if the guard expression is true.
@item 0
Never print any messages.
@end ftable

Defaults to @code{1}.
@end deftypefn

@deftypefn Macro text DL_DEFAULT_HANDLER
The default handler for printing which is simply the name of the
printing function. 

Defaults to @code{printf}
@end deftypefn

@deftypefn Macro bool DL_DEFAULT_GUARD

Defaults to @code{TRUE}.
@end deftypefn

@deftypefn Macro text DL_DEFAULT_PARAMS
Defaults to @code{stderr}
@end deftypefn

@deftypefn Macro flag DL_SHOW_TIME
Each message can be given an individual time stamp by defining 
@code{DL_SHOW_TIME}. This causes the @code{_L_gettime} routine to be
called before each message which generates the timestamp. A default
version is provided by the nana library.
@end deftypefn

@node GDB.h, Q.h, DL.h, Interface
@section GDB.h: sending plain gdb commands to the debugger
@samp{GDB.h} provides macros for generating user specified commands in
the output of the @samp{nana} command.
They are not included by default in the @samp{nana.h} file.
Note that these macros have no effect unless you run your 
program under the debugger and read in the commands generated by the
@samp{nana} command. You also need to compile the program with 
the @samp{-g} option.

@deftypefn Macro void GDB (@var{command})
Emit a single line command when running this file through @samp{nana}. 
Note that each line must be passed off separately to the @samp{GDB}
macro. 

This could be used to set debugger options or to define procedures
inside @samp{gdb}, e.g.

@example
  GDB(define checkstack);
  GDB(  if 0 <= n && n <= 10);
  GDB(    print "stack ok");
  GDB(  else);
  GDB(    print "stack corrupted");
  GDB(  end);
  GDB(end);
@end example
@end deftypefn

@deftypefn Macro void GDBCALL (@var{command})
Causes a single gdb @var{command} to be executed whenever control
passes through this line of code. After the user's command is executed
control automatically returns to the program.

@example
  GDBCALL(set memory_check = 1)
@end example
@end deftypefn

These macros could used for instrumenting code or setting up test
harnesses, e.g.

@example

GDB(set $siocall = 0);
GDB(set $sioerr = 0);

void sio_driver() @{
  GDBCALL(set $siocall++)
  if(SIO_REQ & 0x010) @{
    GDBCALL(set $sioerr++); 
    ...
  @}
@}
@end example

@node Q.h, Qstl.h, GDB.h, Interface
@section Q.h: support for quantifiers
@samp{Q.h} provides support for the quantifiers of predicate logic.  For
example to check that all elements in a data structure have some
property we would use universal (forall, upside down A) quantification.
To check that one or more values in a data structure have some property
we would use existential (exists, back the front E) quantification.  For
example:

@example
  /* all values in a[] must be between 0 and 10 */
  I(A(int i = 0, i < n_array, i++, 0 <= a[i] && a[i] <= 10));

  /* there exists a value in linked list l which is smaller than 10 */
  I(E(node *p = l, p != NULL, p = p->next, p->data <= 10));
@end example

The first three arguments to @samp{A} and @samp{E} are similar 
to a C @samp{for} loop which iterates over the values we wish to
check. The final argument is the expression that must be true.

The only minor difference from the C @samp{for} loop is that variables
may be declared at the start of the loop, even if you are using C rather
than C++ which already supports this.@footnote{ANSI C does not allow
variable declarations at the beginning of loops unlike C++. The
 @samp{Q.h} macros get around this by starting each loop with a new
scope.}

The @samp{Q.h} macros can also be nested and used anywhere a boolean 
value is required. For example:

@example
  if(A(int i = 0, i < MAXX, i++,
       A(int j = 0, j < MAXY, j++,
         m[i][j] == (i == j ? 1 : 0)))) @{ 
        /* identity matrix, i.e. all 0's except for 1's on */
        /* the diagonal */
        ...
  @} else @{
        /* not an identity matrix */
        ...
  @}
@end example

The results from these 
macros can also be combined using boolean operations, e.g.

@example
  /* the values in a[i]  are either ALL positive or ALL negative */
  I(A(int i = 0, i < MAX, i++, a[i] >= 0)
    ||
    A(int i = 0, i < MAX, i++, a[i] < 0));
@end example

@strong{Portability:} note the macros in this file require the GNU
CC/C++ statement expression extension of GCC to work. If you're not using GNU CC
then for now you are out of luck. At some time in the future we may
implement a method which will work for standard C++, standard C is a bit of
a challenge.

@strong{Portability:} unfortunately these macros do not work for the 
@samp{DI} and @samp{DL} macros since the statement expression extension has 
not been implemented in GDB@.

@deftypefn Macro bool A (@var{init},@var{condition},@var{next},@var{exprn})
For all values generated by
 @samp{for(@var{int};@var{condition};@var{next})} the @var{exprn} must be
true. 
@example
  I(A(int i = 0, i < MAX, i++, a[i] >= 0)); /* all a[i] are +ve */
@end example
@end deftypefn

@deftypefn Macro bool E (@var{init},@var{condition},@var{next},@var{exprn})
There exists at least one value for @var{exprn} generated by
 @samp{for (@var{int};@var{condition};@var{next})} which is true.

@example
  /* one or more a[i] >= 0 */
  I(E(int i = 0, i < MAX, i++, a[i] >= 0));
@end example
@end deftypefn

@deftypefn Macro long C (@var{init},@var{condition},@var{next},@var{exprn})
Returns the number of times the @var{exprn} is true over the values
generated by @samp{for(@var{int};@var{condition};@var{next})}.

@example
  /* 3 elements of a[] are +ve */
  I(C(int i = 0, i < MAX, i++, a[i] >= 0) == 3); 
@end example
@end deftypefn

@deftypefn Macro bool E1 (@var{init},@var{condition},@var{next},@var{exprn})
There exists only one value generated by 
 @samp{for(@var{int};@var{condition};@var{next})} for which the @var{exprn}
is true.

@example
  /* a single elements of a[] is +ve */
  I(E1(int i = 0, i < MAX, i++, a[i] >= 0)); 
@end example
@end deftypefn

@deftypefn Macro typeof(@var{exprn}) S (@var{init},@var{condition},@var{next},@var{exprn})
Sum the values generated by @var{exprn} for all values given by
 @samp{for(@var{int};@var{condition};@var{next})}. The type of the value
returned  is given by the type of the @var{exprn}.@footnote{This uses yet
another GNU CC extension, however since we are already using statement 
expressions we might as well use @samp{typeof} as well.}

@example
  /* sum of a[] is 10 */
  I(S(int i = 0, i < MAX, i++, a[i]) == 10);

  /* sum of all +ve numbers in a[] is 10 */
  I(S(int i = 0, i < MAX, i++, a[i] >= 0 ? a[i] : 0) == 10);
@end example
@end deftypefn

@deftypefn Macro typeof(@var{exprn}) P (@var{init},@var{condition},@var{next},@var{exprn})
Returns the product of the 
values generated by @var{exprn} for all values given by
 @samp{for(@var{int};@var{condition};@var{next})}.
The type returned is the type of the expression.

@example
  /* product of all the values in a[] is 10 */
  I(P(int i = 0, i < MAX, i++, a[i]) == 10); 

  /* a = x^y i.e. x*x..*x y times */
  I(P(int i = 0, i < y, i++, x) == a);
@end example
@end deftypefn

@node Qstl.h, now.h, Q.h, Interface
@section Qstl.h: quantifiers for STL containers.
The Standard Template Library (STL) is a library for C++ that makes
extensive use of templates to implement the standard container
classes and much more. Each of the container classes provides an
interface to iterate over all the objects in the container, e.g.

@example
// MAP is an associate array from location(lat,long) onto the name.
typedef map<location,string,locationlt> MAP;

void print_map_names(MAP& m) @{ // print out all the names in the map
  for(MAP::iterator i = m.begin(); i != m.end(); ++i) @{
    cout << (*i).second << "\n";
  @}
@}
@end example

@samp{Qstl.h} provides the same facilities as @samp{Q.h} but uses the
standard STL iterator protocol shown above. The names in @samp{Qstl.h}
are generated by appending a @samp{O} (O not zero!) to the names in
@samp{Q.h}. In particular:

@deftypefn Macro bool AO (@var{name},@var{container},@var{predicate})
For all values in the @var{container} class the @var{predicate} must
be true. The @var{predicate} refers to individual values using
@var{name}. See the STL documentation for more details. 
Another way of putting this is forall @var{name} in
@var{container} the @var{predicate} must be true. 

@example
  map<int,char *,ltint> m;
  // all keys (or indexes) into m are positive	
  I(AO(i, m, (*i).first >= 0)); 
@end example
@end deftypefn

@deftypefn Macro bool EO (@var{name},@var{container},@var{predicate})
There exists one or more values in the @var{container} class for which
the @var{predicate} is true. 

@example
  map<int,char,ltint> m;

  // one or more characters in m are '$'
  I(EO(i, m, (*i).second == '$')); 
@end example
@end deftypefn

@deftypefn Macro bool E1O (@var{name},@var{container},@var{predicate})
There exists one value in the @var{container} for which
the @var{predicate} is true. 

@example
  map<int,char,ltint> m;

  // one characters in m is a '$'
  I(E1O(i, m, (*i).second == '$')); 
@end example
@end deftypefn

@deftypefn Macro int CO (@var{name},@var{container},@var{predicate})
Returns the number of times the @var{predicate} was true for all
values in the @var{container}.

@example
  map<int,char,ltint> m;
  int nalpha; 
  // count the number of alphabetic chars in the map
  nalpha = CO(i, m, isalpha((*i).second)); 
@end example
@end deftypefn

@deftypefn Macro typeof(@var{exprn}) SO (@var{name},@var{container},@var{exprn})
Sum the @var{exprn} for all values in the @var{container}.

@example
  map<int,float,ltint> m;
  float sum;
  // sum all the values in m
  sum = SO(i, m, (*i).second); 
@end example
@end deftypefn

@deftypefn Macro typeof(@var{exprn}) PO (@var{name},@var{container},@var{exprn})
Take the product of the @var{exprn} for all values in the @var{container}.

@example
  map<int,float,ltint> m;
  float product;
  // multiply all the values in m
  product = PO(i, m, (*i).second); 
@end example
@end deftypefn

@node now.h, cycles.h, Qstl.h, Interface
@section now.h: measuring time
The @samp{now.h} file provides some simple time measurement routines.
It is @emph{not} included in @samp{nana.h} so you must include this file 
separately.  

It uses the @samp{gettimeofday} system call and has an accuracy of
between 1us and 10ms depending on the operating system and hardware
configuration.

See the IPM package if you require better measurement tools.@footnote{In
the fullness of time, we may integrate these routines in here.}

@deftypefn Function double now ()
Returns the time in seconds since the beginning of time as defined by
your system. If you call @samp{now_reset} the time will start again at
0.
@end deftypefn

@deftypefn Function double now_reset ()
Reset the times returned by @samp{now} to 0.
@end deftypefn

@deftypefn Function double now_delta (double *@var{dp})
Returns the elapsed time between @var{*dp} and @var{now()}. It then sets
@var{*dp} to @var{now}, thus giving a delta time between particular
events. 

@example
  t = now();
  for(;;) @{
    ...; /* code that must finish in 50ms */
    I(now_delta(&t) <= 0.050);
  @}
@end example
@end deftypefn

@node cycles.h, eiffel.h, now.h, Interface
@section cycles.h: access to CPU cycle counting registers.
Some modern CPU's provide user accessible registers or special intstructions
which can access a counter driven directly by the CPU clock. 
The @samp{cycles.h} library provides access to these instructions
together with some calibration and utility routines. 

Currently we only provide support for Pentium/Cyrix machines using the
@samp{RDTSC} instruction. If you want to use these routines you 
need to run the @samp{configure} script with the @samp{--enable-rdtsc}
option. Other machine architectures will be supported as time goes on.

@deftp typedef CYCLES long long
The CPU cycle measurement type, typically a 64 bit unsigned integer.
@end deftp

@deftypefn Macro CYCLES cycles ()
Returns the current value for the cycle counter.
@end deftypefn

@deftypefn Function CYCLES cycles_per_second (double @var{t}, int @var{n})
Returns an estimate of the number of cycles per second using the 
@samp{now.h} library. The measurement is taken @var{n} times using 
a measurement period of @var{t} seconds for each measurement. 
The minimum and maximum values for the measurement are set by
each call to @samp{cycles_per_second} and are available from the
next two functions.
@end deftypefn

@deftypefn Function CYCLES cycles_per_second_min ()
@deftypefnx Function CYCLES cycles_per_second_max ()
Return the minimum or maximum of the measurements carried out
by the previous call to @samp{cycles_per_second}.
@end deftypefn

@deftypefn Function double cycles_diff (CYCLES @var{start}, CYCLES @var{stop})
Returns the time difference between @var{start} and @var{stop} cycles
in seconds as a double. As usual there are a few requirements:

@itemize @bullet
@item @samp{cycles_per_second} must be called before hand to calibrate
the cycle time with the real time clock.
@item @var{start} must be less than or equal to @var{stop}.
Note we do not handle wraparound currently since the counters start at 0
and are 64 bits long and so will not overflow in a reasonable period.
@footnote{Famous last words I know but: (2^64)/(1e9*60*60*24*365) = 584 yrs.}

@item The difference between the @var{start} and @var{stop} times should be
able to be represented in a @samp{double}, lest overflow and misery follow.
@item CPU clocks tend to vary a bit with temperature etc, trust this and 
die. 
@end itemize
@end deftypefn

@menu
* RDTSC::                       
@end menu

@node RDTSC,  , cycles.h, cycles.h
@subsection RDTSC: cycle timing for Pentium, Cyrix, etc

The @var{RDTSC} instruction is used for cycle timing on Pentiums and
other compatible CPUs such as the Cyrix chip set. Note that this
instruction does @emph{not} exist on earlier CPUs in the series.

We could of course try to discover the CPU type at compile or
run time and then use the appropriate instruction. This has 
all sorts of problems, e.g. if we compile on a i586 does that mean
it will be run on the same CPU (no of course not....). 

For now we use the @samp{--enable-rdtsc} option for @samp{./configure}.

@node eiffel.h, assert.h, cycles.h, Interface
@section eiffel.h: eiffel type assertions
Eiffel is a very nice language which provides the assertion checking
facilities of nana inside the language itself.  The @samp{eiffel.h}
library is intended to provide a similar setup to Eiffel in the C++
language.

@menu
* EIFFEL_CHECK::                
* DOEND::                       
* REQUIRE...::                  
@end menu

@node EIFFEL_CHECK, DOEND, eiffel.h, eiffel.h
@subsection EIFFEL_CHECK: enabling and disabling checking.

Assertion checking is controlled by the @var{EIFFEL_CHECK} 
macro which can take on any of the following values:

@ftable @code
@item CHECK_NO
Disable all checking.
@item CHECK_REQUIRE
Check the preconditions for each method.
@item CHECK_ENSURE
And also check the postconditions.
@item CHECK_INVARIANT
And also check the class invariant before and after each method is
called. The programmer should provide a class method called
@samp{invariant} which returns @samp{true} if the object is consistent, 
@samp{false} otherwise.
@item CHECK_LOOP
And also check the loop invariants.
@item CHECK_ALL
And also check any assertions using the @samp{CHECK} instruction.
@end ftable

Note that the default value for @code{EIFFEL_CHECK} is
@code{CHECK_REQUIRE}, i.e. check preconditions only. 

A typical compile flag to the compile might be:

@example
% g++ -c -DEIFFEL_CHECK=CHECK_ALL play.cc
@end example

@node DOEND, REQUIRE..., EIFFEL_CHECK, eiffel.h
@subsection DOEND: adding DO ... END
At the suggestion of Bertrand Meyer (Eiffel's author) the @code{DO} and
@code{END} macros have been added to @samp{eiffel.h}.  Note that these
are only available if you define the @code{EIFFEL_DOEND} macro. To use
these macros each of your methods should use @code{DO} ... @code{END} as
their outermost brackets. For example:

@example
// compiled with EIFFEL_DOEND defined
void Stack::push(int n) 
DO  // checks the class invariant + @{
   ... 
END // check the class invariant + @}
@end example

If you do @emph{not} define the @code{EIFFEL_DOEND} macro then @samp{eiffel.h}
reverts to its old behaviour where @samp{REQUIRE} and @samp{ENSURE} also
check the class invariant. Thus to check the class invariant when you 
are not using @code{DO} and @code{END} you would need to call
@code{REQUIRE} and @code{ENSURE}, for example:

@example
// compile with EIFFEL_DOEND undefined (i.e. old behaviour)
void Stack::push(int n) 
@{
  REQUIRE(true); // checks the invariant as well as the precondition

  ENSURE(true); // checks the invariant as well as the postcondition
@}
@end example

As for which one to option to pick, Bertrand Meyer is in favour of the
@code{DO} ... @code{END} solution.  

@node REQUIRE...,  , DOEND, eiffel.h
@subsection REQUIRE, ENSURE, CHECK, etc.
Here are the individual checking macros:

@deftypefn Macro void REQUIRE (@var{exprn})
Called at the beginning of each method to check its
precondition (requirements). For example:

@example
void Stack::push(int n) @{
  REQUIRE(!full()); // stack has space for push
  ...
@}
@end example

If @code{EIFFEL_DOEND} is not defined this also checks
the class invariant.
@end deftypefn 

@deftypefn Macro void ENSURE (@var{exprn})
Called at the end of each method.
This checks the postcondition for a method and the class invariant.

@example
void Stack::push(int n) @{
  ...
  ENSURE(!empty()); // it can't be empty after a push!
@}
@end example

If @code{EIFFEL_DOEND} is not defined this also checks
the class invariant.
@end deftypefn 

@deftypefn Macro void INVARIANT (@var{exprn})
Used to check a loop invariant.
@end deftypefn

@deftypefn Macro void CHECK (@var{exprn})
Used for any other inline assertions. For example:

@example
  CHECK(z != 0);
  x = y / z;
@end example
@end deftypefn

And finally a small example:

@example
#include <eiffel.h>

class example @{
  int nobjects;
  map<location,string,locationlt> layer;
public:
  bool invariant(); // is this object consistent
  void changeit(location l);
@};

bool example::invariant() @{
  return AO(i,layer,valid_location((*i).first)) && 
         nobjects >= 0;
@}

void example::changeit(string n, location l) @{
  REQUIRE(E1O(i,layer,(*i).second == n));
  ...;
  while(..) @{
    INVARIANT(...);
    ...
    INVARIANT(...);
  @}
  ...
  CHECK(x == 5);
  ...
  ENSURE(layer[l] == n);
@}
@end example

Note that the invariant checking macro @samp{example::invariant}
is called automatically on function entry/exit using the 
@samp{REQUIRE} and @samp{ENSURE} macros if @samp{EIFFEL_CHECK} is
not defined.

@node assert.h, calls.h, eiffel.h, Interface
@section assert.h: a drop in replacement for assert.h
A drop in replacement for @samp{assert.h} is provided in the @samp{src}
directory. It is @strong{not} installed by default. If you wish to use
it then you need to copy it to your include directory by hand.

This might be of use if you are already using @samp{assert.h} and
wish to save some code space since the nana implementation is more 
space efficient. 

Calls to @samp{assert} are translated to calls to @samp{I} and 
can be disabled by defining @samp{NDEBUG}.

@node calls.h,  , assert.h, Interface
@section calls.h: checking/printing many objects/facts.
The @samp{calls} module implements a simple list of functions which can be 
modified and executed at run-time. It is similar in spirit to the 
ANSI C @samp{atexit} function. It is intended to be used for: 

@itemize @bullet
@item Checking the consistency of the components in your system. 

For example each module could register a self checking function which
uses the rest of the nana library. All of these functions would then be
called using @samp{calls.h} to check that the entire system is consistent.

@item Printing out the state of your program in a readable format.
@end itemize

@deftp Type typedef FUNC 
A pointer to a @samp{void} function which takes a single @samp{void*}
argument. The @samp{void *} argument is intended to be used to pass
information such as arguments or pointers to objects (e.g. @samp{this}
in C++). All of the checking/printing functions must be of this type, e.g.

@example
void print_object(void *f) @{
  ...;
@}
@end example
@end deftp

@deftp Type struct CALL 
This structure represents a single call to a function, i.e. a function 
pointer (@samp{FUNC}) and the @samp{void*} argument. 

@example
	CALL *head = 0;
@end example
@end deftp

@deftypefn Function void calls_add (CALL **head, FUNC fp, *arg)
Adds a call to function @samp{fp} with argument @samp{arg} to
the list pointed to by @samp{head}. 

@example
	CALL *global_checks = 0;

	calls_add(&global_checks,complex_ok,(void *)x); 
@end example
@end deftypefn

@deftypefn Function void calls_exec (CALL **head, FUNC fp, void *arg)
Execute all/some of the calls in the list given by @samp{head}.
The arguments @samp{fp} and @samp{arg} must both
match for each individual call. The null pointer (@samp{0}) matches 
anything whilst any other value requires an exact match between
the @samp{CALL} and the arguments to @samp{calls_exec}. 
For example:

@example
calls_exec(&l,0,0); /* execute all functions in l  */
calls_exec(&l,complex_print,0); /* calls complex_print(*) in l */
calls_exec(&l,0,(void*) &b); /* calls *(&b) in l */
calls_exec(&l,f,(void*) &b); /* calls f(&b) in l */
@end example
@end deftypefn

@deftypefn Function void calls_delete (CALL **head, FUNC fp, void *arg)
Delete all/some of the calls in the list given by @samp{head}.
The arguments @samp{fp} and @samp{arg} must both
match for each individual call. The null pointer (@samp{0}) matches 
anything whilst any other value requires an exact match between
the @samp{CALL} and the arguments to @samp{calls_delete}. 
For example:

@example
calls_delete(&l,0,0); /* delete all functions in l  */
calls_delete(&l,complex_print,0); /* delete complex_print(*) in l */
calls_delete(&l,0,(void*) &b); /* delete *(&b) in l */
calls_delete(&l,f,(void*) &b); /* delete f(&b) in l */
@end example
@end deftypefn

@strong{Note:} that calls are added to the head of the list rather than the 
tail. This means that the most recently added call will be 
executed first (as in a stack).


@node Shortform, Performance, Interface, Top
@chapter Nana Shortform Generator.
The Eiffel language provides a shortform of a class which consists of 
the exported methods and their pre and post conditions. The private
part of the class such as the code is hidden in this form leaving only:

@enumerate
@item Arguments and return values for methods.
@item @samp{REQUIRE} and @samp{ENSURE} calls which specify 
the precondition and postconditions of each method. 
@end enumerate

This is useful to provide a summary of what the code does and
how to use it rather than how it works. 

Nana provides a similar service which can be used to generated a HTML
version of the short form of your program automatically.  The code for
this is kept in @samp{shortform}. Do a @samp{make example} to build
an example document.@footnote{Note you need to install the GLOBAL package
first. This is installed by default on FreeBSD systems. If you do not
have the GLOBAL package read on.}

Consider the following program:

@example
/* smallex.c - a small example */

#include <stdio.h>
#include <math.h>
#include <eiffel.h>

void sort(int *v, int n) @{
  int i;
  REQUIRE(v != NULL && 
    0 <= n);

  for(i = 0; < n; i++) @{ /* at last, an O(n) sort! */
    v[i] = i;
  @}
  /* And no, this isn't what most people think of as sorting */

  ENSURE(A(int i = 0, i < n - 1, i++, 
      v[i] <= v[i+1]));
@}
@end example

Its short form can be generated by using the @samp{nana-sfg}@footnote{The
name @samp{nana-sfg} stands for either Nana Short Form Generator or
Nana Science Fiction Generator. Personally I prefer the later derivation.}
program which generates:

@example
% nana-sfg smallex.c
...
#include <stdio.h>
#include <math.h>
#include <eiffel.h>
...
void sort(int *v, int n) @{
  ...
  REQUIRE(v != NULL && 
    n >= 0);
  ...
  ENSURE(A(int i = 0, i < n, i++, 
      v[i] <= v[i+1]));
@}
% 
@end example

The @samp{nana-sfg} program is a small AWK program which processes its
arguments into shortform and always writes to the standard output. If it
is passed no arguments it works as a normal UNIX filter reading from the
standard input.

It is suggested that a copy of @samp{nana-sfg} be kept in each projects
@samp{bin} directory so that it can be modified for local taste. The
user will probably wish to modify the rules for short form generation.
For example you might add rules such as:
 
@example
/^\/\//           @{ emit(); @} # print out C++ comments in column 1
/^\/\*\+/,/\*\//  @{ emit(); @} # print out multi-line /*+ ... */ comments
@end example

Of course for a real project you need to run @samp{nana-sfg} over the
entire source tree. To do this you can use the @samp{nana-sfdir}
program.

@example 
% nana-sfdir
@end example

This command simply creates a copy of the source tree in the current
directory under @samp{NANASF} using the @samp{nana-sfg} program. You can
then run a source code to HTML translator over the @samp{NANASF}
directory. Currently we are using the GLOBAL package which was written
by Shigio Yamaguchi which available from:

@itemize @bullet
@item @samp{http://wafu.netgate.net/tama/unix/global.html} -- the GLOBAL 
   homepage. 
@item @samp{ftp://ftp.cs.ntu.edu/pub/nana/global-2.24.tar.gz} -- a local 
   (well for Darwin at least) copy of the GLOBAL package.
@end itemize

The alert reader will perhaps be asking themselves why we did not simply
modify GLOBAL@. Well that was the original idea, however after a bit
of thinking it seemed better to separate the generation of the short
form of the code from the generation of the HTML@. This gives us the
ability to use other translators and other tools. It also simplifies the
interaction between nana and GLOBAL@. 
For information on other translators see:

@itemize @bullet
@item @samp{http://www.zib.de/Visual/software/doc++/index.html} -- DOC++
        homepage.
@item @samp{http://www.webnz.com/webnz/robert/cpp_site.html#Documentation} --
        an index of other translation tools (e.g. to LaTeX).
@end itemize

@node Performance, Tracing, Shortform, Top
@chapter Nana Performance Measurement
A tool is provided for measuring code/time requirements for arbitrary
code fragments. This is kept in the @samp{perf} directory and is @strong{not}
built by default. If you wish to use this tool use the following targets:

@example
% cd perf
% make perf
@end example

The output is @samp{perf.tex}, @samp{perf.dvi} and @samp{perf/index.html}.

Note that the measurement requires the following:

@itemize @bullet
@item GNU CC -- it uses the GNU address of label extension to calculate
        the size in bytes of a code fragment.
@item Time is measured using the nana @samp{now()} function.
@item LaTeX -- to generate the document from @samp{perf.tex}.
@item LaTeX2HTML -- to generate a HTML version of @samp{perf.tex}.
@end itemize

As an indication of the values you can expect here is part of the
results for @samp{make perf} on a 200Mhz Cyrix MMX (i386) chip which runs
at about 200 BogoMips under FreeBSD 2.2.6 with @samp{-O}.

@samp{assert(i >= 2);} 28 bytes, 19ns.

@samp{TRAD_assert(i >= 2);} 47 bytes, 20ns.@footnote{This is the traditional assert which
uses @samp{fprintf} and @samp{exit} in a macro. The BSD @samp{assert}
macro used in FreeBSD is a bit smarter and calls a function to do the 
message printing and exiting. Note that the real cost of this function
is even higher since we are only measuring the code space requirements, 
not the space required for the message strings.}

@samp{I(i >= 2);} 9 bytes, 18ns.

@samp{DI(i >= 2);} 1 byte, 147.4us.

@samp{I(A(int i=0, i!=10, i++, a[i]>=0));} 28 bytes, 287ns.

@samp{d = now();} 8 bytes, 3.1us.

@samp{printf("helloworld\n");} 13 bytes, 9.1us. 

@samp{L("helloworld\n");} 18 bytes, 8.9us.

@samp{DL("helloworld\n");} 1 byte, 26.4us.

Note that these measurements were on a system that was configured
with @samp{I_DEFAULT=fast ./configure}. The default output of 
@samp{./configure} produces nice error messages at the cost of increased 
code space.

@node Tracing, Usage, Performance, Top
@chapter Tracing tools
A few tools for execution tracing and logging are available in the
@samp{gdb} directory and are installed by default. They are simple shell
scripts and may be of some use in testing/development.  Note that
@samp{gdb-4.17} may be required on some machines for this stuff to work
properly.

@menu
* Statement::                   
* Library::                     
@end menu

@node Statement, Library, Tracing, Tracing
@section Statement level tracing
The @samp{nana-trace} executes a program and generates a message 
for each line of code executed (a statement trace). The statement 
level trace is useful for things such as:

@itemize @bullet
@item Understanding code.
@item Measuring test coverage.
@item Comparing runs of the code when regression testing, e.g.
verifying that change X only changes the behaviour of
program P for test case Z@.
@end itemize

For example the @samp{make ex-trace} command in @samp{gdb} generates:

@example
% make ex-trace
gcc -g test.c
sh ./nana-trace a.out
47           setbuf(stdout, NULL); /* disable buffering */
49           printf("** main()\n");
** main()
50           printf("** 1: %d\n", distance(1,-5));
distance (i=1, j=-5) at test.c:43
43           return abs(i - j);
abs (i=6) at test.c:35
35           if(i >= 0) @{
36                return i;
40      @}
distance (i=1, j=-5) at test.c:44
44      @}
** 1: 6
main () at test.c:51
51           printf("** 2: %d\n", distance(twice(1),-5));
twice (i=1) at test.c:29
29           i = i * 2;
31           return i ;
32      @}
distance (i=2, j=-5) at test.c:43
43           return abs(i - j);
abs (i=7) at test.c:35
35           if(i >= 0) @{
36                return i;
40      @}
distance (i=2, j=-5) at test.c:44
44      @}
** 2: 7
main () at test.c:52
52           printf("** 3: %d\n", distance(3,-5));
distance (i=3, j=-5) at test.c:43
43           return abs(i - j);
abs (i=8) at test.c:35
35           if(i >= 0) @{
36                return i;
40      @}
distance (i=3, j=-5) at test.c:44
44      @}
** 3: 8
main () at test.c:53
53      @}
@end example

@node Library,  , Statement, Tracing
@section Library tracing
On most UNIX machines there exists a tool for tracing the system
calls executed by a program. If you haven't used one of these
tools (e.g. ktrace) then now is a good time to learn. Being able
to trace the User/Kernel interface is an excellent way to understand 
complex applications. 

The @samp{nana-libtrace} facility generalises this idea to provide a GDB
based function call tracer for all functions in which are defined in a
particular library.  For example the @samp{make ex-libtrace} command in
the @samp{gdb} directory produces a trace of all calls to @samp{libc}.


@itemize @bullet
@item @samp{nana-libtrace a.out} -- reads a list of function names one per line
from the standard input and writes the corresponding gdb(1) script to
the standard output. Note that all functions specified in the input must
exist in the executable for them to be passed through to the
output. This may require compilation of your program with @samp{-static}
linking.@footnote{If possible we should replace the call to @samp{nm}
with a call to something which can print all the symbols for a
dynamically linked library. Unfortunately GDB gets upset if you try to
set a breakpoint for a function that does not exist. I suppose we could
use gdb to print the symbol list out.}  For example:

@example
% gcc -g -static test.c -lm
% ./nana-libtrace a.out >test.gdb
printf
write
% cat test.gdb
break printf
command $bpnum
silent
where 1
cont
end
break write
command $bpnum
silent
where 1
cont
end
% nana-run a.out -x test.gdb
Breakpoint 1 at 0x1483: file /usr/.../libc/stdio/printf.c, line 65.
Breakpoint 2 at 0x8c78
#0  printf (fmt=0x1116 "** main()\n")
    at /usr/src/lib/libc/../libc/stdio/printf.c:65
#0  0x8c78 in write ()
** main()
#0  printf (fmt=0x1121 "** 1: %d\n")
    at /usr/src/lib/libc/../libc/stdio/printf.c:65
#0  0x8c78 in write ()
** 1: 6
#0  printf (fmt=0x112b "** 2: %d\n")
    at /usr/src/lib/libc/../libc/stdio/printf.c:65
#0  0x8c78 in write ()
** 2: 7
#0  printf (fmt=0x1135 "** 3: %d\n")
    at /usr/src/lib/libc/../libc/stdio/printf.c:65
#0  0x8c78 in write ()
** 3: 8

Program exited with code 010.
@end example

@item @samp{nana-libtrace a.out /usr/lib/libc.a} -- trace all calls to 
@samp{libc} from @samp{a.out}. A subset of the output is given below:

@example
#0  printf (fmt=0x1135 "** 3: %d\n")
    at /usr/src/lib/libc/../libc/stdio/printf.c:65
#0  vfprintf (fp=0xa1d4, fmt0=0x1135 "** 3: %d\n", ap=0xefbfd888 "\b")
    at /usr/src/lib/libc/../libc/stdio/vfprintf.c:428
#0  vfprintf (fp=0xefbfd5b8, fmt0=0x1135 "** 3: %d\n", ap=0xefbfd888 "\b")
    at /usr/src/lib/libc/../libc/stdio/vfprintf.c:428
#0  __sfvwrite (fp=0xefbfd5b8, uio=0xefbfd184)
    at /usr/src/lib/libc/../libc/stdio/fvwrite.c:68
#0  0x8ff8 in memcpy ()
#0  0x8ff8 in memcpy ()
#0  __sfvwrite (fp=0xefbfd5b8, uio=0xefbfd184)
    at /usr/src/lib/libc/../libc/stdio/fvwrite.c:68
#0  0x8ff8 in memcpy ()
#0  fflush (fp=0xefbfd5b8) at /usr/src/lib/libc/../libc/stdio/fflush.c:60
#0  __sflush (fp=0xefbfd5b8) at /usr/src/lib/libc/../libc/stdio/fflush.c:84
#0  __swrite (cookie=0xa1d4, buf=0xefbfd1b8 "** 3: 8\nain()\n", n=8)
    at /usr/src/lib/libc/../libc/stdio/stdio.c:78
#0  0x8c78 in write ()
** 3: 8
@end example

Note that your library code must be compiled with @samp{-g} to put
in the debugging information if you wish to have the arguments displayed
symbolically. This is fairly easy on most systems, e.g on FreeBSD
you edit the global compile options @samp{/etc/make.conf} and rebuild/install
the entire system.

Ideally we would also like to be able to trace only entry calls and 
not internal calls to libc. This can be done by inserting a counter
which is incremented on call and decremented on return. We print 
the trace messages iff the counter is 1. This extension (perhaps
to GNU libc) may be written if people are interested.
@end itemize

@node Usage, FAQ, Tracing, Top
@chapter Using Nana
This chapter is intended to provide some hopefully useful examples of
Nana. If any of the users of this library would be so kind as
to contribute a section on their usage I would be obliged. 

@strong{This section is under development}

@menu
* Simplest::                    
* Syslog::                      
* GNU::                         
* Embedded Systems::            
* Realtime::                    
* A database::                  
* Visualisation::               
@end menu

@node Simplest, Syslog, Usage, Usage
@section Simplest example
As a nice simple, indeed trivial example consider the following:

@enumerate
@item Include @samp{nana.h} in your project wide include file.
@item Use @samp{I} to check invariants in your code. In particular
all functions or methods should be required to check their pre and post
conditions.
@item Use @samp{DL} to print debugging messages in your code. This means
that debugging messages only occur when you run the program under the
debugger.@footnote{Of course you also need to use the gdb commands
generated by the @samp{nana} command, perhaps using @samp{nana-clg}.}
@end enumerate

@node Syslog, GNU, Simplest, Usage
@section Syslog
@samp{syslog} is a comprehensive logging system written by Eric Allman
which is available on most UNIX systems. It provides facilities for
sorting messages by source or severity and mechanisms for sending
messages off to files, terminals or other machines. See chapter 12 of
the "UNIX System Administration Handbook (2nd Edition)" 
by Nemeth, Snyder, Seebass and Hein for an excellent tutorial on
@samp{syslog}.

The rules used by @samp{syslog} are normally defined in
@samp{/etc/syslog.conf}. Each line specifies the destination for
messages with particular sources and priorities.  For example:

@example
# log mail messages at priority info to mailinfo
mail.info /var/log/mailinfo
# log all ftp information to syslog on a remote machine
ftp.* @@remote-machine.cs.ntu.edu.au
# all critical errors to console
*.crit   /dev/console
@end example

To use @samp{syslog} we merely redefine the default handlers and
parameter values for @samp{nana}. For example:

@example
#include <syslog.h>
#define L_DEFAULT_HANDLER syslog /* replaces fprintf(3) by syslog(3) */
#define L_DEFAULT_PARAMS LOG_USER /* default priority for syslog info */
#include <nana.h>

int main() @{
     openlog("nana", /* identifier for these log messages */
        LOG_PID, /* also log the process id */
        LOG_DAEMON /* facility */
     );

     L("temperature is falling to %d", 35); /* logged at LOG_USER priority */
     LP(LOG_CRIT, "the snow is falling in Darwin"); /* LOG_CRIT message */
        
     closelog();
     return 0;
@}
@end example

This program results in the following addition to @samp{/var/adm/messages}:

@example
Jun 12 16:04:46 chingiz nana[2671]: the temperature is falling to 35
Jun 12 16:04:46 chingiz nana[2671]: the snow is falling in Darwin
@end example

In addition the @samp{LOG_CRIT} message about snow falling in Darwin is
sent to the console for immediate action. 

@strong{Note:} @samp{syslog} normally uses @samp{UDP} for its network
communications and that @samp{UDP} does not guarantee delivery. 

@node GNU, Embedded Systems, Syslog, Usage
@section GNU Programs: how to avoid nana sometimes
Imagine you@footnote{Gordon Matzigkeit contributed some of the 
ideas presented here and raised this problem.} are building a GNU program.
Ideally it should run on systems without any other software including
GCC, GDB and even Nana. 

To achieve this noble goal you can provide your configure script
with a @samp{--without-nana}@footnote{Or add a @samp{--with-nana} flag
to configure that does the opposite.} flag which then @samp{#define's}
@samp{WITHOUT_NANA}. You should also use the @samp{VL} macro rather than
@samp{L} macro since @samp{L} takes a variable number of arguments and
will break non GNU C preprocessors. 

@example
int half(int n) @{
  /* Don't use L(...) since it takes a variable number of args! */
  VL(("hello world = %d\n", 10)); /* Note the doubled (( */
  ...;
@}
@end example

@node Embedded Systems, Realtime, GNU, Usage
@section Embedded Systems: testing non-deterministic systems.
One of the uses (in fact the original use) for nana is in the 
testing of non-deterministic systems. These systems behave in a 
different way each time they are run because of timing or measurement
noise. Thus you can't just @samp{diff} the results against a known good run
since they run differently each time. 

Instead you can use a series of programs which execute over a 
the results of the program and check that the behaviour meets the
specification automatically. 

@node Realtime, A database, Embedded Systems, Usage
@section Realtime Systems 
Assertions for the timing behaviour of you system can be done in nana
nicely. You might also consider using an instruction level simulator
such as PSIM and use the @samp{cycles} variable to test realtime
constraints.

@node A database, Visualisation, Realtime, Usage
@section A database
Ah databases, business boffins using assertions. It would nice
to get a real example for this one! 

@node Visualisation,  , A database, Usage
@section Program Visualisation: pretty pictures
One nice way to use @samp{L}, @samp{DL}, etc is to punt off the messages
off to a program which displays the information. You would use the
@samp{L_DEFAULT_PARAM} argument to send commands off to a pipe with
gnuplot or TCL/TK interpreter running at the end. 

For a small example of this, see @samp{tcl/status.c}. 

@node FAQ, Future, Usage, Top
@chapter FAQ
This chapter is intended to answer some general questions about the
usage of Nana. Most of the material (perhaps) has been presented elsewhere,
my apologies for repeating myself.

@enumerate
@item Can I use GNU Nana in a commercial product?

See the license details in the file @samp{COPYING}. In summary GNU Nana
is Free software which has been released under a license that allows
commercial use provided the copyright is maintained. It is not under
the GPL@. 

@item How do you completely disable assertion checking?

Set the @samp{I_LEVEL} command to @samp{0} using @samp{-D} or 
@samp{#define} before including @samp{nana.h}. 

@item How do I find out about future releases?

Subscribe to the nana mailing list by using the @samp{make subscribe}
target in the nana root directory. 

@item Where do I send bug reports, suggestions, etc?

@samp{nana-bug@@it.ntu.edu.au} -- bug archive

@samp{nana@@it.ntu.edu.au} -- mailing list

@samp{pjm@@gnu.org} -- the author

@end enumerate

@node Future, Index, FAQ, Top
@chapter Future work
As usual, there is more work to be done than time to do it in.
Workers or test pilots are invited to apply for the following
tasks which may get down in the fullness of time minister. 
I'm particularly interested in which projects people think 
are worthwhile (or rubbish).

@enumerate
@item Ada support - pre 1.00 versions of nana provided support for
        Ada. Adding a full version of nana into the GNATS compiler 
        would probably be useful, particularly the real time part.
@item FORTRAN support.
@item Message browsing (@samp{emacs/fess.el}) - a very prototypical mode for 
browsing message logs is distributed with nana. Features include hiding/showing
lines by regular expression or predicate. If someone who knows what they
are doing rewrites this that would be a good thing. Or perhaps a modified
version of @samp{less} would be useful.
@item Program Visualisation (@samp{tcl/status.c}) - another prototype 
which uses a small TCL/TK library and nana logging to generate some 
nice pictures showing the behaviour of the program. For example
the history of variables over time can be recorded, graphs drawn and
long message logs kept. A new version of this has been created
and may be released shortly. 
@item Automated Testing - combine nana logs with a workbench
that lets you verify properties of the logs using programs @samp{gawk}
or the @samp{PRECC} (LL infinity version of YACC). This technique has
been used on industrial strength products quite successfully. 
@item GNU standards - perhaps it would be worthwhile to set up 
a prototype for checking and logging in GNU tools. 
@item Extend GDB(1) so that we can support @samp{Q.h} style quantifiers
in @samp{DI.h} expressions. Basically we need to add a restricted form 
of the statement value expression to GDB@.
@item Support for other (particularly ANSI only) compilers.
@end enumerate

@node Index,  , Future, Top
@appendix Index
@printindex cp

@summarycontents
@contents
@bye
