1This is Info file nana.info, produced by Makeinfo version 1.68 from the 2input file nana.texi. 3 4START-INFO-DIR-ENTRY 5* Nana: (nana). The GNU Nana library (assertions, logging, forall,etc) 6END-INFO-DIR-ENTRY 7 8 This file documents the features and implementation of the GNU Nana 9library. 10 11 Copyright (C) 1996, 1997, 1998, 1999 P.J.Maker, Quoll Systems Pty 12Ltd. 13 14 Permission is granted to make and distribute verbatim copies of this 15manual provided the copyright notice and this permission notice are 16preserved on all copies. 17 18 19File: nana.info, Node: DI.h, Next: L.h, Prev: I.h, Up: Interface 20 21DI.h: debugger based invariant checking 22======================================= 23 24 This implements the debugger based invariant checking code. The 25first two macros are the normal user interface; the remainder are used 26for configuring the behaviour on failure, etc. Note that these macros 27have no effect unless you run your program under the debugger and read 28in the commands generated by the `nana' command. You also need to 29compile the program with the `-g' option. 30 31 - Macro: void DI (bool EXPRN) 32 The EXPRN should always be true if the program is working. If it 33 is true then nothing happens otherwise the code given by 34 `DI_DEFAULT_HANDLER' will be called which by default prints a 35 message and dies just like `assert.h'. 36 37 The checking using DI can be enabled and disabled by using the 38 DI_LEVEL and DI_DEFAULT_GUARD macros. See the definitions below 39 for these macros for further details. 40 41 Note that EXPRN should have no side-effects(1) since disabling the 42 checking shouldn't change your programs behaviour. 43 44 - Macro: void DN (bool EXPRN) 45 The opposite of `DI', i.e. the expression must never ever be true 46 if the program is working properly. It is equivelant to `I(!(e))' 47 and exists as piece of syntactic sugar which is helpful for 48 complicated boolean expressions. 49 50 - Macro: int DI_LEVEL 51 The `DI_LEVEL' macro is used to globally enable and disable 52 checking, in particular it can take on one of three values: 53 54 `0' 55 Disable all checking. Regardless of anything else no code 56 will be generated for `DI', `DN', etc. 57 58 `1' 59 Enable checking only if the corresponding guard condition is 60 true. The guard condition can be used to enable and disable 61 checking at compile and run time. 62 63 `2' 64 Enable all checking regardless of guard conditions, etc. 65 66 `DI_LEVEL' defaults to `1'. 67 68 - Macro: bool DI_DEFAULT_GUARD 69 The `DI_DEFAULT_GUARD' is used to selectively enable or disable 70 checking at compile or run time. 71 72 `DI_DEFAULT_GUARD' defaults to `TRUE', i.e. always enabled. 73 74 A user would typically define `DI_DEFAULT_GUARD' to be global or 75 local variable which is used to turn checking on or off at 76 run-time. For example: 77 78 #define DI_DEFAULT_GUARD (i_guard) 79 80 extern int i_guard; 81 82 - Macro: text DI_DEFAULT_PARAMS 83 This is passed off to the `DI_DEFAULT_HANDLER' and defaults to 84 nothing, it is just some text and is intended to pass failure codes 85 (e.g. `IEH303') or requests (e.g. `HW_DEAD') information off to 86 the handler. 87 88 `DI_DEFAULT_PARAMS' defaults to nothing. 89 90 - Macro: void DI_DEFAULT_HANDLER (char *EXPRN, char *FILE, int LINE, 91 PARAM) 92 When an error is detected the `DI_DEFAULT_HANDLER' will be called 93 to handle the error. The arguments are: 94 95 `exprn' 96 A string representation of the expression that has failed, 97 e.g. `"I(i>=0)"'. 98 99 `file' 100 The file that this error occurred in, i.e. `__FILE__'. 101 102 `line' 103 The line number for the error, i.e. `__LINE__'. 104 105 `param' 106 An optional parameter which can be passed across which 107 defaults to `DI_DEFAULT_PARAMS'. This can be used to pass 108 failure codes or other information from the checking code to 109 the handler. 110 111 - Macro: void DI_MAKE_VALID_BREAKPOINT (exprn E) 112 This macro is used to ensure that a breakpoint can be set at the 113 location we are checking using `DI', etc. It defaults to 114 `asm("nop")' and can be redefined by the user. 115 116 - Macro: void DI (bool E) 117 - Macro: void DIG (bool E, bool G) 118 - Macro: void DIH (bool E, Macro H) 119 - Macro: void DIP (bool E, Text P) 120 - Macro: void DIGH (bool E, bool G, Macro H) 121 - Macro: void DIGP (bool E, bool G, Text P) 122 - Macro: void DIHP (bool E, Macro H, Text P) 123 - Macro: void DIGHP (bool E, bool G, Macro H, Text P) 124 - Macro: void DN (bool E) 125 - Macro: void DNG (bool E, bool G) 126 - Macro: void DNH (bool E, Macro H) 127 - Macro: void DNP (bool E, Text P) 128 - Macro: void DNGH (bool E, bool G, Macro H) 129 - Macro: void DNGP (bool E, bool G, Text P) 130 - Macro: void DNHP (bool E, Macro H, Text P) 131 - Macro: void DNGHP (bool E, bool G, Macro H, Text P) 132 All of these macros are used to individually override the default 133 values defined above. Normally these macros would be used in a 134 system wide header file to define macros appropriate for the 135 application. 136 137 - Macro: void DS (E) 138 - Macro: void DSG (E, G) 139 These macros are used to assign values to convenience variables in 140 the debugger. Convenience variables are dynamically typed, global 141 in scope and initialised to 0. They start with a single `$' and 142 can be used be used for saving the state of program or for 143 counting events. The `DS' macro executes E under the same rules as 144 `DI'. The `DSG' macro executes E only if the the expression G is 145 true. 146 147 Note that `DS' and `DSG' can also be used for modifying C 148 variables and calling functions. 149 150 ---------- Footnotes ---------- 151 152 (1) Side-effects include operations like input/output or assignments. 153 154 155File: nana.info, Node: L.h, Next: L_buffer.h, Prev: DI.h, Up: Interface 156 157L.h: support for printf style logging 158===================================== 159 160 These routines are used to provide logging functions. Messages can be 161divided into classes and separately enabled and disabled. 162 163 - Macro: void L (ARGS...) 164 Used to log a message in a similar way to printf. 165 166 Defaults to a using `fprintf' on `stderr'. 167 168 - Macro: void LG (bool GUARD, ARGS...) 169 - Macro: void LH (function HANDLER, ARGS...) 170 - Macro: void LP (text PARAM, ARGS...) 171 - Macro: void LGP (bool GUARD, text PARAM, ARGS...) 172 - Macro: void LHP (function HANDLER, text PARAM, ARGS...) 173 - Macro: void LGHP (bool GUARD, function HANDLER, text PARAM, ARGS...) 174 And all of the special functions. 175 176 177 The macros such as `L' depend on the GNU CC variable number of 178arguments to macros extension. If you wish to compile your code on 179other systems you might wish to use the following variations on `L', 180etc. 181 182 - Macro: void VL ((ARGS...)) 183 - Macro: void VLG ((bool GUARD, ARGS...)) 184 - Macro: void VLH ((function HANDLER, ARGS...)) 185 - Macro: void VLP ((text PARAM, ARGS...)) 186 - Macro: void VLGP ((bool GUARD, TEXT PARAM, ARGS...)) 187 - Macro: void VLHP ((function HANDLER, text PARAM, ARGS...)) 188 - Macro: void VLGHP ((bool GUARD, function HANDLER, text PARAM, 189 ARGS...)) 190 Each of these macros calls the corresponding function from the 191 previous group, i.e. by default `VLG' is the same as a call to 192 `LG'. If you define `WITHOUT_NANA' all these macros are translated 193 to `/* empty */'. 194 195 Thus you can have nana under GCC whilst the code is still portable 196 to other compilers. However debugging information will not be 197 available on other platforms. 198 199 *Note:* the argument list is surrounded by *two* sets of brackets. 200 For example: 201 202 VL(("haze in darwin = %d\n", 3.4)); 203 204 - Macro: void L_LEVEL 205 Used to enable and disable logging independently of guard 206 expressions. 207 208 `2' 209 Always print message 210 211 `1' 212 Print message only if the guard expression is true. 213 214 `0' 215 Never print any messages. 216 217 Defaults to `1'. 218 219 - Macro: text L_DEFAULT_HANDLER 220 The default handler for printing which is simply the name of the 221 logging function or macro. 222 223 Defaults to `fprintf' 224 225 - Macro: bool L_DEFAULT_GUARD 226 The default guard condition for logging. 227 228 Defaults to `TRUE'. 229 230 - Macro: text L_DEFAULT_PARAMS 231 The default parameter passed off to the logging function or macro. 232 233 Defaults to `stderr' 234 235 - Macro: void L_SHOW_TIME 236 If defined then display the time in front of each message. 237 238 - Macro: char* L_SHOW_TIME_FORMAT 239 A format string for the time stamp in the log. By default it 240 prints the time out in seconds. 241 242 - Macro: value L_SHOW_TIME_NOW 243 The name of a function that returns the time for the time stamp. 244 This defaults to the `now' function from `now.h'. 245 246 247File: nana.info, Node: L_buffer.h, Next: L_times.h, Prev: L.h, Up: Interface 248 249L_buffer.h: a circular buffer for logging. 250========================================== 251 252 A traditional embedded systems trick is to log messages to a circular 253buffer in core. This has the following benefits: 254 255 1. Speed - writing to a in core buffer is much faster than spitting 256 out messages to a file on disk. It is often fast enough to leave 257 at least most of the messages in the final product. 258 259 2. Field debugging - what the ... was the user doing before the 260 system crashed. Oh lets ask them, I'm sure they'll give us a good 261 problem report. 262 263 - Type: struct L_BUFFER 264 Used to define buffer variables, it is similar to `FILE*' type in 265 `stdio.h'. To create an instance use `L_buffer_create'. 266 267 - Function: L_BUFFER* L_buffer_create (size_t SIZE) 268 - Function: L_BUFFER* L_buffer_delete (L_BUFFER *B) 269 These are used to create or delete a buffer which can contain SIZE 270 characters. 271 272 L_BUFFER *lbuffer; 273 274 lbuffer = L_buffer_create(32*1024); /* create a 32K buffer */ 275 ...; 276 L_buffer_delete(lbuffer); /* and delete it after use */ 277 278 - Function: void L_buffer_wraparound (L_BUFFER *B, int W) 279 A buffer created by `L_buffer_create' is set up so that the new 280 messages will overwrite the older messages in the buffer. If you 281 wish to disable this overwriting, e.g. to keep the first 32K bytes 282 of your system startup messages you should use 283 `L_buffer_wraparound'. For example: 284 285 L_BUFFER *lb = L_buffer_create(32*1024); 286 L_buffer_wraparound(lb, 0); /* disable wraparound */ 287 288 - Function: void L_buffer_printf (L_BUFFER *B, const char *FMT, ...) 289 - Function: void L_buffer_puts (L_BUFFER *B, const char *STR) 290 - Function: void L_buffer_putchar (L_BUFFER *B, char CH) 291 These are the routines which do that actual printing to the buffer. 292 293 L_buffer_printf(lbuffer, "U: user input %c\n", c); 294 L_buffer_puts(lbuffer, "warning: its too hot"); 295 L_buffer_putchar(lbuffer, '*'); 296 297 Note: a null pointer passed to the `L_buffer_puts' function prints 298 as `(null)'. (1) 299 300 - Function: void L_buffer_clear (L_BUFFER *B) 301 Clear the log, i.e. remove all messages and start again. 302 303 - Function: void L_buffer_dump (L_BUFFER *B, FILE *FP) 304 Dump the contents of the log *B to the file descriptor *FP. 305 Typically *FP would be `stderr'. 306 307 Note that this does not change the contents of the buffer. This is 308 important since we may have a hardware or software problem part of 309 the way through the dump operation and you don't want to loose 310 anything. 311 312 To reset the buffer after a successful dump use `L_buffer_clear'. 313 314 The output of `L_buffer_dump' consists of a starting message 315 followed by the contents of the log. If a character in the log is 316 not printable we print it out in hex on a line by itself. 317 318 * L_buffer_dump = 319 log message 320 and another 321 * non-printable character 0x1 322 more log messages 323 * end of dump 324 325 You also need to be able to integrate these functions into your 326design. See `examples/ott.c' for a complicated example. Here we will 327provide a simplified version which implements a new logging macro 328called `LFAST' which does a `printf' to the `log_buffer'. If you want 329to have all messages going to a `L_BUFFER' then you can redefine 330`L_DEFAULT_HANDLER'. 331 332 /* project.h - the project wide include file */ 333 334 #include <nana.h> 335 #include <L_buffer.h> 336 337 /* LFAST(char *, ...) - log a message to the log_buffer */ 338 /* ##f translates as the rest of the arguments to LFAST */ 339 340 #define LFAST(f...) LHP(L_buffer_printf,log_buffer,##f) 341 342 extern L_BUFFER *log_buffer; /* the log buffer */ 343 344 The main program merely creates the LOG_BUFFER and eventually calls 345`L_buffer_dump' to print out the buffer when the system dies. 346 /* main.c - initialise the system and start things */ 347 348 #include <project.h> 349 350 L_BUFFER *log_buffer; 351 352 main() { 353 log_buffer = L_buffer_create(16000); 354 if(log_buffer == NULL) { /* not enough store */ 355 ... 356 } 357 LFAST("system starting at %f\n", now()); 358 ...; 359 } 360 361 void fatal_error() { /* called on fatal errors */ 362 FILE *f = fopen("project.errors","w"); 363 L_buffer_dump(b, stderr); /* print log to stderr */ 364 L_buffer_dump(b, f); /* print log to file */ 365 } 366 367 ---------- Footnotes ---------- 368 369 (1) This was suggested by Phil Blecker. 370 371 372File: nana.info, Node: L_times.h, Next: DL.h, Prev: L_buffer.h, Up: Interface 373 374L_times.h: recording events and times. 375====================================== 376 377 This component is used to record events and times with a lower time 378and space overhead than the `L_buffer.h' component. Instead of using a 379`printf' style string we simply record the time and a pointer to a 380string identifying the event in a circular buffer. 381 382 *Note 0:* the string arguments should not be modified after a call 383since we record pointers to the strings rather than the strings 384themselves. 385 386 *Note 1:* there is no PRINTF style formatting, e.g. `%d' in this 387package. 388 389 - Type: struct L_TIMES 390 Used to define buffers, it is similar to `FILE*' type in 391 `stdio.h'. To create an instance use `L_times_create'. 392 393 - Function: L_TIMES* L_times_create (int SIZE) 394 - Function: L_TIMES* L_times_delete (L_BUFFER *B) 395 These are used to create or delete a buffer which can contain SIZE 396 messages. 397 398 - Function: void L_times_wraparound (L_TIMES *B, int W) 399 A buffer created by `L_times_create' is set up so that the new 400 messages will overwrite the oldest messages in the buffer. If you 401 wish to disable this overwriting, e.g. to keep the first few 402 messages messages you could use `L_times_wraparound(b,0)'. 403 404 - Function: void L_times_add (L_BUFFER *B, char *M, NANA_TIME T) 405 Add an event identified by message M at time T to B. The type 406 NANA_TIME defaults to `double'. 407 408 - Function: void L_times_dump (L_TIMES *B, FILE *FD) 409 Dump the contents of the buffer out. 410 411 - Function: void L_times_clear (L_TIMES *B) 412 Clear all the messages from B. 413 414 415File: nana.info, Node: DL.h, Next: GDB.h, Prev: L_times.h, Up: Interface 416 417DL.h: support for printf style logging 418====================================== 419 420 These routines are used to provide logging functions. Messages can be 421divided into classes and separately enabled and disabled. Note that 422these macros have no effect unless you run your program under the 423debugger and read in the commands generated by the `nana' command. You 424also need to compile the program with the `-g' option. 425 426 - Macro: void DL (ARGS...) 427 Used to log a message. 428 429 Defaults to a using `fprintf' on `stderr'. 430 431 - Macro: void DLG (bool GUARD, ARGS...) 432 - Macro: void DLH (function HANDLER, ARGS...) 433 - Macro: void DLP (text PARAM, ARGS...) 434 - Macro: void DLGP (bool GUARD, text PARAM, ARGS...) 435 - Macro: void DLHP (function HANDLER, ARGS...) 436 - Macro: void DLGHP (bool GUARD, function HANDLER, ARGS...) 437 And all of the special functions. 438 439 440 The macros such as `DL' depend on the GNU CC variable number of 441arguments to macros extension. If you wish to compile your code on 442other systems you might wish to use the following variations on `DL', 443etc. 444 445 - Macro: void VDL ((ARGS...)) 446 - Macro: void VDLG ((bool GUARD, ARGS...)) 447 - Macro: void VDLH ((function HANDLER, ARGS...)) 448 - Macro: void VDLP ((text PARAM, ARGS...)) 449 - Macro: void VDLGP ((bool GUARD, TEXT PARAM, ARGS...)) 450 - Macro: void VDLHP ((function HANDLER, ARGS...)) 451 - Macro: void VDLGHP ((bool GUARD, function HANDLER, ARGS...)) 452 Each of these macros calls the corresponding function from the 453 previous group, i.e. by default `VDL' is equivelant to a call to 454 `DL'. If `WITHOUT_NANA' is defined then the call too `VDL' is 455 equivelant to `/* empty */'. 456 457 Thus you can have debugging under GCC whilst the code is still 458 portable to other compilers. However debugging information will 459 not be available on other platforms. 460 461 *Note:* the argument list is surrounded by *two* sets of brackets. 462 For example: 463 464 VDL(("haze in darwin = %d\n", 3.4)); 465 466 - Macro: int DL_LEVEL 467 Used to enable and disable logging independently of guard 468 expressions. 469 470 `2' 471 Always print message 472 473 `1' 474 Print message only if the guard expression is true. 475 476 `0' 477 Never print any messages. 478 479 Defaults to `1'. 480 481 - Macro: text DL_DEFAULT_HANDLER 482 The default handler for printing which is simply the name of the 483 printing function. 484 485 Defaults to `printf' 486 487 - Macro: bool DL_DEFAULT_GUARD 488 Defaults to `TRUE'. 489 490 - Macro: text DL_DEFAULT_PARAMS 491 Defaults to `stderr' 492 493 - Macro: flag DL_SHOW_TIME 494 Each message can be given an individual time stamp by defining 495 `DL_SHOW_TIME'. This causes the `_L_gettime' routine to be called 496 before each message which generates the timestamp. A default 497 version is provided by the nana library. 498 499 500File: nana.info, Node: GDB.h, Next: Q.h, Prev: DL.h, Up: Interface 501 502GDB.h: sending plain gdb commands to the debugger 503================================================= 504 505 `GDB.h' provides macros for generating user specified commands in 506the output of the `nana' command. They are not included by default in 507the `nana.h' file. Note that these macros have no effect unless you 508run your program under the debugger and read in the commands generated 509by the `nana' command. You also need to compile the program with the 510`-g' option. 511 512 - Macro: void GDB (COMMAND) 513 Emit a single line command when running this file through `nana'. 514 Note that each line must be passed off separately to the `GDB' 515 macro. 516 517 This could be used to set debugger options or to define procedures 518 inside `gdb', e.g. 519 520 GDB(define checkstack); 521 GDB( if 0 <= n && n <= 10); 522 GDB( print "stack ok"); 523 GDB( else); 524 GDB( print "stack corrupted"); 525 GDB( end); 526 GDB(end); 527 528 - Macro: void GDBCALL (COMMAND) 529 Causes a single gdb COMMAND to be executed whenever control passes 530 through this line of code. After the user's command is executed 531 control automatically returns to the program. 532 533 GDBCALL(set memory_check = 1) 534 535 These macros could used for instrumenting code or setting up test 536harnesses, e.g. 537 538 539 GDB(set $siocall = 0); 540 GDB(set $sioerr = 0); 541 542 void sio_driver() { 543 GDBCALL(set $siocall++) 544 if(SIO_REQ & 0x010) { 545 GDBCALL(set $sioerr++); 546 ... 547 } 548 } 549 550 551File: nana.info, Node: Q.h, Next: Qstl.h, Prev: GDB.h, Up: Interface 552 553Q.h: support for quantifiers 554============================ 555 556 `Q.h' provides support for the quantifiers of predicate logic. For 557example to check that all elements in a data structure have some 558property we would use universal (forall, upside down A) quantification. 559To check that one or more values in a data structure have some property 560we would use existential (exists, back the front E) quantification. For 561example: 562 563 /* all values in a[] must be between 0 and 10 */ 564 I(A(int i = 0, i < n_array, i++, 0 <= a[i] && a[i] <= 10)); 565 566 /* there exists a value in linked list l which is smaller than 10 */ 567 I(E(node *p = l, p != NULL, p = p->next, p->data <= 10)); 568 569 The first three arguments to `A' and `E' are similar to a C `for' 570loop which iterates over the values we wish to check. The final 571argument is the expression that must be true. 572 573 The only minor difference from the C `for' loop is that variables 574may be declared at the start of the loop, even if you are using C rather 575than C++ which already supports this.(1) 576 577 The `Q.h' macros can also be nested and used anywhere a boolean 578value is required. For example: 579 580 if(A(int i = 0, i < MAXX, i++, 581 A(int j = 0, j < MAXY, j++, 582 m[i][j] == (i == j ? 1 : 0)))) { 583 /* identity matrix, i.e. all 0's except for 1's on */ 584 /* the diagonal */ 585 ... 586 } else { 587 /* not an identity matrix */ 588 ... 589 } 590 591 The results from these macros can also be combined using boolean 592operations, e.g. 593 594 /* the values in a[i] are either ALL positive or ALL negative */ 595 I(A(int i = 0, i < MAX, i++, a[i] >= 0) 596 || 597 A(int i = 0, i < MAX, i++, a[i] < 0)); 598 599 *Portability:* note the macros in this file require the GNU CC/C++ 600statement expression extension of GCC to work. If you're not using GNU 601CC then for now you are out of luck. At some time in the future we may 602implement a method which will work for standard C++, standard C is a 603bit of a challenge. 604 605 *Portability:* unfortunately these macros do not work for the `DI' 606and `DL' macros since the statement expression extension has not been 607implemented in GDB. 608 609 - Macro: bool A (INIT,CONDITION,NEXT,EXPRN) 610 For all values generated by `for(INT;CONDITION;NEXT)' the EXPRN 611 must be true. 612 I(A(int i = 0, i < MAX, i++, a[i] >= 0)); /* all a[i] are +ve */ 613 614 - Macro: bool E (INIT,CONDITION,NEXT,EXPRN) 615 There exists at least one value for EXPRN generated by `for 616 (INT;CONDITION;NEXT)' which is true. 617 618 /* one or more a[i] >= 0 */ 619 I(E(int i = 0, i < MAX, i++, a[i] >= 0)); 620 621 - Macro: long C (INIT,CONDITION,NEXT,EXPRN) 622 Returns the number of times the EXPRN is true over the values 623 generated by `for(INT;CONDITION;NEXT)'. 624 625 /* 3 elements of a[] are +ve */ 626 I(C(int i = 0, i < MAX, i++, a[i] >= 0) == 3); 627 628 - Macro: bool E1 (INIT,CONDITION,NEXT,EXPRN) 629 There exists only one value generated by 630 `for(INT;CONDITION;NEXT)' for which the EXPRN is true. 631 632 /* a single elements of a[] is +ve */ 633 I(E1(int i = 0, i < MAX, i++, a[i] >= 0)); 634 635 - Macro: typeof (EXPRN) S (INIT,CONDITION,NEXT,EXPRN) 636 Sum the values generated by EXPRN for all values given by 637 `for(INT;CONDITION;NEXT)'. The type of the value returned is 638 given by the type of the EXPRN.(2) 639 640 /* sum of a[] is 10 */ 641 I(S(int i = 0, i < MAX, i++, a[i]) == 10); 642 643 /* sum of all +ve numbers in a[] is 10 */ 644 I(S(int i = 0, i < MAX, i++, a[i] >= 0 ? a[i] : 0) == 10); 645 646 - Macro: typeof (EXPRN) P (INIT,CONDITION,NEXT,EXPRN) 647 Returns the product of the values generated by EXPRN for all 648 values given by `for(INT;CONDITION;NEXT)'. The type returned is 649 the type of the expression. 650 651 /* product of all the values in a[] is 10 */ 652 I(P(int i = 0, i < MAX, i++, a[i]) == 10); 653 654 /* a = x^y i.e. x*x..*x y times */ 655 I(P(int i = 0, i < y, i++, x) == a); 656 657 ---------- Footnotes ---------- 658 659 (1) ANSI C does not allow variable declarations at the beginning of 660loops unlike C++. The `Q.h' macros get around this by starting each 661loop with a new scope. 662 663 (2) This uses yet another GNU CC extension, however since we are 664already using statement expressions we might as well use `typeof' as 665well. 666 667 668File: nana.info, Node: Qstl.h, Next: now.h, Prev: Q.h, Up: Interface 669 670Qstl.h: quantifiers for STL containers. 671======================================= 672 673 The Standard Template Library (STL) is a library for C++ that makes 674extensive use of templates to implement the standard container classes 675and much more. Each of the container classes provides an interface to 676iterate over all the objects in the container, e.g. 677 678 // MAP is an associate array from location(lat,long) onto the name. 679 typedef map<location,string,locationlt> MAP; 680 681 void print_map_names(MAP& m) { // print out all the names in the map 682 for(MAP::iterator i = m.begin(); i != m.end(); ++i) { 683 cout << (*i).second << "\n"; 684 } 685 } 686 687 `Qstl.h' provides the same facilities as `Q.h' but uses the standard 688STL iterator protocol shown above. The names in `Qstl.h' are generated 689by appending a `O' (O not zero!) to the names in `Q.h'. In particular: 690 691 - Macro: bool AO (NAME,CONTAINER,PREDICATE) 692 For all values in the CONTAINER class the PREDICATE must be true. 693 The PREDICATE refers to individual values using NAME. See the STL 694 documentation for more details. Another way of putting this is 695 forall NAME in CONTAINER the PREDICATE must be true. 696 697 map<int,char *,ltint> m; 698 // all keys (or indexes) into m are positive 699 I(AO(i, m, (*i).first >= 0)); 700 701 - Macro: bool EO (NAME,CONTAINER,PREDICATE) 702 There exists one or more values in the CONTAINER class for which 703 the PREDICATE is true. 704 705 map<int,char,ltint> m; 706 707 // one or more characters in m are '$' 708 I(EO(i, m, (*i).second == '$')); 709 710 - Macro: bool E1O (NAME,CONTAINER,PREDICATE) 711 There exists one value in the CONTAINER for which the PREDICATE is 712 true. 713 714 map<int,char,ltint> m; 715 716 // one characters in m is a '$' 717 I(E1O(i, m, (*i).second == '$')); 718 719 - Macro: int CO (NAME,CONTAINER,PREDICATE) 720 Returns the number of times the PREDICATE was true for all values 721 in the CONTAINER. 722 723 map<int,char,ltint> m; 724 int nalpha; 725 // count the number of alphabetic chars in the map 726 nalpha = CO(i, m, isalpha((*i).second)); 727 728 - Macro: typeof (EXPRN) SO (NAME,CONTAINER,EXPRN) 729 Sum the EXPRN for all values in the CONTAINER. 730 731 map<int,float,ltint> m; 732 float sum; 733 // sum all the values in m 734 sum = SO(i, m, (*i).second); 735 736 - Macro: typeof (EXPRN) PO (NAME,CONTAINER,EXPRN) 737 Take the product of the EXPRN for all values in the CONTAINER. 738 739 map<int,float,ltint> m; 740 float product; 741 // multiply all the values in m 742 product = PO(i, m, (*i).second); 743 744 745File: nana.info, Node: now.h, Next: cycles.h, Prev: Qstl.h, Up: Interface 746 747now.h: measuring time 748===================== 749 750 The `now.h' file provides some simple time measurement routines. It 751is *not* included in `nana.h' so you must include this file separately. 752 753 It uses the `gettimeofday' system call and has an accuracy of 754between 1us and 10ms depending on the operating system and hardware 755configuration. 756 757 See the IPM package if you require better measurement tools.(1) 758 759 - Function: double now () 760 Returns the time in seconds since the beginning of time as defined 761 by your system. If you call `now_reset' the time will start again 762 at 0. 763 764 - Function: double now_reset () 765 Reset the times returned by `now' to 0. 766 767 - Function: double now_delta (double *DP) 768 Returns the elapsed time between *DP and NOW(). It then sets *DP 769 to NOW, thus giving a delta time between particular events. 770 771 t = now(); 772 for(;;) { 773 ...; /* code that must finish in 50ms */ 774 I(now_delta(&t) <= 0.050); 775 } 776 777 ---------- Footnotes ---------- 778 779 (1) In the fullness of time, we may integrate these routines in here. 780 781 782File: nana.info, Node: cycles.h, Next: eiffel.h, Prev: now.h, Up: Interface 783 784cycles.h: access to CPU cycle counting registers. 785================================================= 786 787 Some modern CPU's provide user accessible registers or special 788intstructions which can access a counter driven directly by the CPU 789clock. The `cycles.h' library provides access to these instructions 790together with some calibration and utility routines. 791 792 Currently we only provide support for Pentium/Cyrix machines using 793the `RDTSC' instruction. If you want to use these routines you need to 794run the `configure' script with the `--enable-rdtsc' option. Other 795machine architectures will be supported as time goes on. 796 797 - typedef: CYCLES long long 798 The CPU cycle measurement type, typically a 64 bit unsigned 799 integer. 800 801 - Macro: CYCLES cycles () 802 Returns the current value for the cycle counter. 803 804 - Function: CYCLES cycles_per_second (double T, int N) 805 Returns an estimate of the number of cycles per second using the 806 `now.h' library. The measurement is taken N times using a 807 measurement period of T seconds for each measurement. The minimum 808 and maximum values for the measurement are set by each call to 809 `cycles_per_second' and are available from the next two functions. 810 811 - Function: CYCLES cycles_per_second_min () 812 - Function: CYCLES cycles_per_second_max () 813 Return the minimum or maximum of the measurements carried out by 814 the previous call to `cycles_per_second'. 815 816 - Function: double cycles_diff (CYCLES START, CYCLES STOP) 817 Returns the time difference between START and STOP cycles in 818 seconds as a double. As usual there are a few requirements: 819 820 * `cycles_per_second' must be called before hand to calibrate 821 the cycle time with the real time clock. 822 823 * START must be less than or equal to STOP. Note we do not 824 handle wraparound currently since the counters start at 0 and 825 are 64 bits long and so will not overflow in a reasonable 826 period. (1) 827 828 * The difference between the START and STOP times should be 829 able to be represented in a `double', lest overflow and 830 misery follow. 831 832 * CPU clocks tend to vary a bit with temperature etc, trust 833 this and die. 834 835* Menu: 836 837* RDTSC:: 838 839 ---------- Footnotes ---------- 840 841 (1) Famous last words I know but: (2^64)/(1e9*60*60*24*365) = 584 842yrs. 843 844 845File: nana.info, Node: RDTSC, Prev: cycles.h, Up: cycles.h 846 847RDTSC: cycle timing for Pentium, Cyrix, etc 848------------------------------------------- 849 850 The RDTSC instruction is used for cycle timing on Pentiums and other 851compatible CPUs such as the Cyrix chip set. Note that this instruction 852does *not* exist on earlier CPUs in the series. 853 854 We could of course try to discover the CPU type at compile or run 855time and then use the appropriate instruction. This has all sorts of 856problems, e.g. if we compile on a i586 does that mean it will be run on 857the same CPU (no of course not....). 858 859 For now we use the `--enable-rdtsc' option for `./configure'. 860 861 862File: nana.info, Node: eiffel.h, Next: assert.h, Prev: cycles.h, Up: Interface 863 864eiffel.h: eiffel type assertions 865================================ 866 867 Eiffel is a very nice language which provides the assertion checking 868facilities of nana inside the language itself. The `eiffel.h' library 869is intended to provide a similar setup to Eiffel in the C++ language. 870 871* Menu: 872 873* EIFFEL_CHECK:: 874* DOEND:: 875* REQUIRE...:: 876 877 878File: nana.info, Node: EIFFEL_CHECK, Next: DOEND, Prev: eiffel.h, Up: eiffel.h 879 880EIFFEL_CHECK: enabling and disabling checking. 881---------------------------------------------- 882 883 Assertion checking is controlled by the EIFFEL_CHECK macro which can 884take on any of the following values: 885 886`CHECK_NO' 887 Disable all checking. 888 889`CHECK_REQUIRE' 890 Check the preconditions for each method. 891 892`CHECK_ENSURE' 893 And also check the postconditions. 894 895`CHECK_INVARIANT' 896 And also check the class invariant before and after each method is 897 called. The programmer should provide a class method called 898 `invariant' which returns `true' if the object is consistent, 899 `false' otherwise. 900 901`CHECK_LOOP' 902 And also check the loop invariants. 903 904`CHECK_ALL' 905 And also check any assertions using the `CHECK' instruction. 906 907 Note that the default value for `EIFFEL_CHECK' is `CHECK_REQUIRE', 908i.e. check preconditions only. 909 910 A typical compile flag to the compile might be: 911 912 % g++ -c -DEIFFEL_CHECK=CHECK_ALL play.cc 913 914 915File: nana.info, Node: DOEND, Next: REQUIRE..., Prev: EIFFEL_CHECK, Up: eiffel.h 916 917DOEND: adding DO ... END 918------------------------ 919 920 At the suggestion of Bertrand Meyer (Eiffel's author) the `DO' and 921`END' macros have been added to `eiffel.h'. Note that these are only 922available if you define the `EIFFEL_DOEND' macro. To use these macros 923each of your methods should use `DO' ... `END' as their outermost 924brackets. For example: 925 926 // compiled with EIFFEL_DOEND defined 927 void Stack::push(int n) 928 DO // checks the class invariant + { 929 ... 930 END // check the class invariant + } 931 932 If you do *not* define the `EIFFEL_DOEND' macro then `eiffel.h' 933reverts to its old behaviour where `REQUIRE' and `ENSURE' also check 934the class invariant. Thus to check the class invariant when you are not 935using `DO' and `END' you would need to call `REQUIRE' and `ENSURE', for 936example: 937 938 // compile with EIFFEL_DOEND undefined (i.e. old behaviour) 939 void Stack::push(int n) 940 { 941 REQUIRE(true); // checks the invariant as well as the precondition 942 943 ENSURE(true); // checks the invariant as well as the postcondition 944 } 945 946 As for which one to option to pick, Bertrand Meyer is in favour of 947the `DO' ... `END' solution. 948 949 950File: nana.info, Node: REQUIRE..., Prev: DOEND, Up: eiffel.h 951 952REQUIRE, ENSURE, CHECK, etc. 953---------------------------- 954 955 Here are the individual checking macros: 956 957 - Macro: void REQUIRE (EXPRN) 958 Called at the beginning of each method to check its precondition 959 (requirements). For example: 960 961 void Stack::push(int n) { 962 REQUIRE(!full()); // stack has space for push 963 ... 964 } 965 966 If `EIFFEL_DOEND' is not defined this also checks the class 967 invariant. 968 969 - Macro: void ENSURE (EXPRN) 970 Called at the end of each method. This checks the postcondition 971 for a method and the class invariant. 972 973 void Stack::push(int n) { 974 ... 975 ENSURE(!empty()); // it can't be empty after a push! 976 } 977 978 If `EIFFEL_DOEND' is not defined this also checks the class 979 invariant. 980 981 - Macro: void INVARIANT (EXPRN) 982 Used to check a loop invariant. 983 984 - Macro: void CHECK (EXPRN) 985 Used for any other inline assertions. For example: 986 987 CHECK(z != 0); 988 x = y / z; 989 990 And finally a small example: 991 992 #include <eiffel.h> 993 994 class example { 995 int nobjects; 996 map<location,string,locationlt> layer; 997 public: 998 bool invariant(); // is this object consistent 999 void changeit(location l); 1000 }; 1001 1002 bool example::invariant() { 1003 return AO(i,layer,valid_location((*i).first)) && 1004 nobjects >= 0; 1005 } 1006 1007 void example::changeit(string n, location l) { 1008 REQUIRE(E1O(i,layer,(*i).second == n)); 1009 ...; 1010 while(..) { 1011 INVARIANT(...); 1012 ... 1013 INVARIANT(...); 1014 } 1015 ... 1016 CHECK(x == 5); 1017 ... 1018 ENSURE(layer[l] == n); 1019 } 1020 1021 Note that the invariant checking macro `example::invariant' is 1022called automatically on function entry/exit using the `REQUIRE' and 1023`ENSURE' macros if `EIFFEL_CHECK' is not defined. 1024 1025 1026File: nana.info, Node: assert.h, Next: calls.h, Prev: eiffel.h, Up: Interface 1027 1028assert.h: a drop in replacement for assert.h 1029============================================ 1030 1031 A drop in replacement for `assert.h' is provided in the `src' 1032directory. It is *not* installed by default. If you wish to use it then 1033you need to copy it to your include directory by hand. 1034 1035 This might be of use if you are already using `assert.h' and wish to 1036save some code space since the nana implementation is more space 1037efficient. 1038 1039 Calls to `assert' are translated to calls to `I' and can be disabled 1040by defining `NDEBUG'. 1041 1042 1043File: nana.info, Node: calls.h, Prev: assert.h, Up: Interface 1044 1045calls.h: checking/printing many objects/facts. 1046============================================== 1047 1048 The `calls' module implements a simple list of functions which can be 1049modified and executed at run-time. It is similar in spirit to the ANSI 1050C `atexit' function. It is intended to be used for: 1051 1052 * Checking the consistency of the components in your system. 1053 1054 For example each module could register a self checking function 1055 which uses the rest of the nana library. All of these functions 1056 would then be called using `calls.h' to check that the entire 1057 system is consistent. 1058 1059 * Printing out the state of your program in a readable format. 1060 1061 - Type: typedef FUNC 1062 A pointer to a `void' function which takes a single `void*' 1063 argument. The `void *' argument is intended to be used to pass 1064 information such as arguments or pointers to objects (e.g. `this' 1065 in C++). All of the checking/printing functions must be of this 1066 type, e.g. 1067 1068 void print_object(void *f) { 1069 ...; 1070 } 1071 1072 - Type: struct CALL 1073 This structure represents a single call to a function, i.e. a 1074 function pointer (`FUNC') and the `void*' argument. 1075 1076 CALL *head = 0; 1077 1078 - Function: void calls_add (CALL **head, FUNC fp, *arg) 1079 Adds a call to function `fp' with argument `arg' to the list 1080 pointed to by `head'. 1081 1082 CALL *global_checks = 0; 1083 1084 calls_add(&global_checks,complex_ok,(void *)x); 1085 1086 - Function: void calls_exec (CALL **head, FUNC fp, void *arg) 1087 Execute all/some of the calls in the list given by `head'. The 1088 arguments `fp' and `arg' must both match for each individual call. 1089 The null pointer (`0') matches anything whilst any other value 1090 requires an exact match between the `CALL' and the arguments to 1091 `calls_exec'. For example: 1092 1093 calls_exec(&l,0,0); /* execute all functions in l */ 1094 calls_exec(&l,complex_print,0); /* calls complex_print(*) in l */ 1095 calls_exec(&l,0,(void*) &b); /* calls *(&b) in l */ 1096 calls_exec(&l,f,(void*) &b); /* calls f(&b) in l */ 1097 1098 - Function: void calls_delete (CALL **head, FUNC fp, void *arg) 1099 Delete all/some of the calls in the list given by `head'. The 1100 arguments `fp' and `arg' must both match for each individual call. 1101 The null pointer (`0') matches anything whilst any other value 1102 requires an exact match between the `CALL' and the arguments to 1103 `calls_delete'. For example: 1104 1105 calls_delete(&l,0,0); /* delete all functions in l */ 1106 calls_delete(&l,complex_print,0); /* delete complex_print(*) in l */ 1107 calls_delete(&l,0,(void*) &b); /* delete *(&b) in l */ 1108 calls_delete(&l,f,(void*) &b); /* delete f(&b) in l */ 1109 1110 *Note:* that calls are added to the head of the list rather than the 1111tail. This means that the most recently added call will be executed 1112first (as in a stack). 1113 1114 1115File: nana.info, Node: Shortform, Next: Performance, Prev: Interface, Up: Top 1116 1117Nana Shortform Generator. 1118************************* 1119 1120 The Eiffel language provides a shortform of a class which consists of 1121the exported methods and their pre and post conditions. The private 1122part of the class such as the code is hidden in this form leaving only: 1123 1124 1. Arguments and return values for methods. 1125 1126 2. `REQUIRE' and `ENSURE' calls which specify the precondition and 1127 postconditions of each method. 1128 1129 This is useful to provide a summary of what the code does and how to 1130use it rather than how it works. 1131 1132 Nana provides a similar service which can be used to generated a HTML 1133version of the short form of your program automatically. The code for 1134this is kept in `shortform'. Do a `make example' to build an example 1135document.(1) 1136 1137 Consider the following program: 1138 1139 /* smallex.c - a small example */ 1140 1141 #include <stdio.h> 1142 #include <math.h> 1143 #include <eiffel.h> 1144 1145 void sort(int *v, int n) { 1146 int i; 1147 REQUIRE(v != NULL && 1148 0 <= n); 1149 1150 for(i = 0; < n; i++) { /* at last, an O(n) sort! */ 1151 v[i] = i; 1152 } 1153 /* And no, this isn't what most people think of as sorting */ 1154 1155 ENSURE(A(int i = 0, i < n - 1, i++, 1156 v[i] <= v[i+1])); 1157 } 1158 1159 Its short form can be generated by using the `nana-sfg'(2) program 1160which generates: 1161 1162 % nana-sfg smallex.c 1163 ... 1164 #include <stdio.h> 1165 #include <math.h> 1166 #include <eiffel.h> 1167 ... 1168 void sort(int *v, int n) { 1169 ... 1170 REQUIRE(v != NULL && 1171 n >= 0); 1172 ... 1173 ENSURE(A(int i = 0, i < n, i++, 1174 v[i] <= v[i+1])); 1175 } 1176 % 1177 1178 The `nana-sfg' program is a small AWK program which processes its 1179arguments into shortform and always writes to the standard output. If it 1180is passed no arguments it works as a normal UNIX filter reading from the 1181standard input. 1182 1183 It is suggested that a copy of `nana-sfg' be kept in each projects 1184`bin' directory so that it can be modified for local taste. The user 1185will probably wish to modify the rules for short form generation. For 1186example you might add rules such as: 1187 1188 /^\/\// { emit(); } # print out C++ comments in column 1 1189 /^\/\*\+/,/\*\// { emit(); } # print out multi-line /*+ ... */ comments 1190 1191 Of course for a real project you need to run `nana-sfg' over the 1192entire source tree. To do this you can use the `nana-sfdir' program. 1193 1194 % nana-sfdir 1195 1196 This command simply creates a copy of the source tree in the current 1197directory under `NANASF' using the `nana-sfg' program. You can then run 1198a source code to HTML translator over the `NANASF' directory. Currently 1199we are using the GLOBAL package which was written by Shigio Yamaguchi 1200which available from: 1201 1202 * `http://wafu.netgate.net/tama/unix/global.html' - the GLOBAL 1203 homepage. 1204 1205 * `ftp://ftp.cs.ntu.edu/pub/nana/global-2.24.tar.gz' - a local 1206 (well for Darwin at least) copy of the GLOBAL package. 1207 1208 The alert reader will perhaps be asking themselves why we did not 1209simply modify GLOBAL. Well that was the original idea, however after a 1210bit of thinking it seemed better to separate the generation of the short 1211form of the code from the generation of the HTML. This gives us the 1212ability to use other translators and other tools. It also simplifies the 1213interaction between nana and GLOBAL. For information on other 1214translators see: 1215 1216 * `http://www.zib.de/Visual/software/doc++/index.html' - DOC++ 1217 homepage. 1218 1219 * `http://www.webnz.com/webnz/robert/cpp_site.html#Documentation' - 1220 an index of other translation tools (e.g. to LaTeX). 1221 1222 ---------- Footnotes ---------- 1223 1224 (1) Note you need to install the GLOBAL package first. This is 1225installed by default on FreeBSD systems. If you do not have the GLOBAL 1226package read on. 1227 1228 (2) The name `nana-sfg' stands for either Nana Short Form Generator 1229or Nana Science Fiction Generator. Personally I prefer the later 1230derivation. 1231 1232 1233File: nana.info, Node: Performance, Next: Tracing, Prev: Shortform, Up: Top 1234 1235Nana Performance Measurement 1236**************************** 1237 1238 A tool is provided for measuring code/time requirements for arbitrary 1239code fragments. This is kept in the `perf' directory and is *not* built 1240by default. If you wish to use this tool use the following targets: 1241 1242 % cd perf 1243 % make perf 1244 1245 The output is `perf.tex', `perf.dvi' and `perf/index.html'. 1246 1247 Note that the measurement requires the following: 1248 1249 * GNU CC - it uses the GNU address of label extension to calculate 1250 the size in bytes of a code fragment. 1251 1252 * Time is measured using the nana `now()' function. 1253 1254 * LaTeX - to generate the document from `perf.tex'. 1255 1256 * LaTeX2HTML - to generate a HTML version of `perf.tex'. 1257 1258 As an indication of the values you can expect here is part of the 1259results for `make perf' on a 200Mhz Cyrix MMX (i386) chip which runs at 1260about 200 BogoMips under FreeBSD 2.2.6 with `-O'. 1261 1262 `assert(i >= 2);' 28 bytes, 19ns. 1263 1264 `TRAD_assert(i >= 2);' 47 bytes, 20ns.(1) 1265 1266 `I(i >= 2);' 9 bytes, 18ns. 1267 1268 `DI(i >= 2);' 1 byte, 147.4us. 1269 1270 `I(A(int i=0, i!=10, i++, a[i]>=0));' 28 bytes, 287ns. 1271 1272 `d = now();' 8 bytes, 3.1us. 1273 1274 `printf("helloworld\n");' 13 bytes, 9.1us. 1275 1276 `L("helloworld\n");' 18 bytes, 8.9us. 1277 1278 `DL("helloworld\n");' 1 byte, 26.4us. 1279 1280 Note that these measurements were on a system that was configured 1281with `I_DEFAULT=fast ./configure'. The default output of `./configure' 1282produces nice error messages at the cost of increased code space. 1283 1284 ---------- Footnotes ---------- 1285 1286 (1) This is the traditional assert which uses `fprintf' and `exit' 1287in a macro. The BSD `assert' macro used in FreeBSD is a bit smarter and 1288calls a function to do the message printing and exiting. Note that the 1289real cost of this function is even higher since we are only measuring 1290the code space requirements, not the space required for the message 1291strings. 1292 1293 1294File: nana.info, Node: Tracing, Next: Usage, Prev: Performance, Up: Top 1295 1296Tracing tools 1297************* 1298 1299 A few tools for execution tracing and logging are available in the 1300`gdb' directory and are installed by default. They are simple shell 1301scripts and may be of some use in testing/development. Note that 1302`gdb-4.17' may be required on some machines for this stuff to work 1303properly. 1304 1305* Menu: 1306 1307* Statement:: 1308* Library:: 1309 1310 1311File: nana.info, Node: Statement, Next: Library, Prev: Tracing, Up: Tracing 1312 1313Statement level tracing 1314======================= 1315 1316 The `nana-trace' executes a program and generates a message for each 1317line of code executed (a statement trace). The statement level trace is 1318useful for things such as: 1319 1320 * Understanding code. 1321 1322 * Measuring test coverage. 1323 1324 * Comparing runs of the code when regression testing, e.g. 1325 verifying that change X only changes the behaviour of program P 1326 for test case Z. 1327 1328 For example the `make ex-trace' command in `gdb' generates: 1329 1330 % make ex-trace 1331 gcc -g test.c 1332 sh ./nana-trace a.out 1333 47 setbuf(stdout, NULL); /* disable buffering */ 1334 49 printf("** main()\n"); 1335 ** main() 1336 50 printf("** 1: %d\n", distance(1,-5)); 1337 distance (i=1, j=-5) at test.c:43 1338 43 return abs(i - j); 1339 abs (i=6) at test.c:35 1340 35 if(i >= 0) { 1341 36 return i; 1342 40 } 1343 distance (i=1, j=-5) at test.c:44 1344 44 } 1345 ** 1: 6 1346 main () at test.c:51 1347 51 printf("** 2: %d\n", distance(twice(1),-5)); 1348 twice (i=1) at test.c:29 1349 29 i = i * 2; 1350 31 return i ; 1351 32 } 1352 distance (i=2, j=-5) at test.c:43 1353 43 return abs(i - j); 1354 abs (i=7) at test.c:35 1355 35 if(i >= 0) { 1356 36 return i; 1357 40 } 1358 distance (i=2, j=-5) at test.c:44 1359 44 } 1360 ** 2: 7 1361 main () at test.c:52 1362 52 printf("** 3: %d\n", distance(3,-5)); 1363 distance (i=3, j=-5) at test.c:43 1364 43 return abs(i - j); 1365 abs (i=8) at test.c:35 1366 35 if(i >= 0) { 1367 36 return i; 1368 40 } 1369 distance (i=3, j=-5) at test.c:44 1370 44 } 1371 ** 3: 8 1372 main () at test.c:53 1373 53 } 1374 1375