| 1 | |
| 2 | # Eddy lab code conventions |
| 3 | |
| 4 | This document is aimed at indoctrinating new developers into the |
| 5 | conventions used by Eddy lab code, including HMMER, Infernal, and |
| 6 | Easel. The conventions' intent is to make it easier for our code to be |
| 7 | maintained efficiently by one busy professor for a long time. |
| 8 | |
| 9 | Not all of our code follows our own current conventions. Older code |
| 10 | often predates newer conventions. We apply our code conventions like |
| 11 | building ordinances. New construction must comply with current |
| 12 | ordinances. Older construction does not have to immediately conform |
| 13 | to the current rules, but when significant renovation happens, old |
| 14 | work needs to be brought up to current standards. |
| 15 | |
| 16 | |
| 17 | ------------------------------------ |
| 18 | |
| 19 | ## naming conventions at a glance |
| 20 | |
| 21 | | thing | example | explanation | |
| 22 | |--------------------|---------------------------|-------------| |
| 23 | | project prefix | `esl` | Externally visible functions, structures, macros, and constants are prefixed according to which of our code projects it's from. | |
| 24 | | module name | `json` | We call discrete units of our code "modules". A module name is 10 characters or fewer. | |
| 25 | | source file | `esl_json.c` | Each module has one source file, named `esl_<module>.c`... | |
| 26 | | header file | `esl_json.h` | ... and one header file, named `esl_<module>.h`... | |
| 27 | | documentation | `esl_json.md` | ... and one documentation file, named `esl_<module>.md`, in github-flavored Markdown (GFM) format. (This is aspirational. Currently they're all LaTeX `.tex` files, and I want to make them Markdown instead as we go forward.) | |
| 28 | | objects | `ESL_JSON` | Each module typically typedef's one object (C structure), named `ESL_<MODULE>`. If there's more than one object, the additional ones are named something like `ESL_<MODULE>_FOO`. | |
| 29 | | external function | `esl_json_PartialParse()` | A module defines as few externally visible functions as possible, and names them `esl_<module>_<functionname>()`. The `<functionname>` part generally uses mixed case capitalization, and follows standardized **interface** nomenclature and behavior, described below. Functions in `easel.c` omit the module name: `esl_exception()` for example.| |
| 30 | | internal function | `json_foo()` | ... usually most functions are static, not exposed outside the module. | |
| 31 | | macro | `ESL_JSON_MACRO()` | Macros follow the same naming convention as functions, but are all uppercase. | |
| 32 | | constant | `eslJSON_KEY` | `#define`'d constants are `esl<MODULE>_<CONSTNAME>`. Constants in `easel.h` omit the `<MODULE>_` part. This includes a set of defined return codes, such as `eslOK`. | |
| 33 | | configure constant | `HAVE_STDINT_H` | Constants that don't start with `esl` are almost always compile-time configuration constants defined by the autoconf `./configure` script, defined in `esl_config.h`, and following GNU naming standards. | |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | ----------------------------------- |
| 39 | |
| 40 | ## design of a module |
| 41 | |
| 42 | Each .c file is the center of an organizational unit called a |
| 43 | **_module_**. Each module has a name, 10 characters or fewer: `json`, for |
| 44 | example, for the Easel module that provides JSON data format parsing |
| 45 | capabilities. The module name is used to construct all the externally |
| 46 | visible identifiers (names of functions, structures, etc.) provided by |
| 47 | the module. |
| 48 | |
| 49 | Each module consists of three files: a .c C code file, a .h header |
| 50 | file, and a documentation file (currently .tex, but we're moving to |
| 51 | Markdown, .md). These filenames are constructed from the project |
| 52 | prefix (below) and the module name. For example, the Easel `buffer` |
| 53 | module is implemented in `esl_buffer.c`, `esl_buffer.h`, and |
| 54 | `esl_buffer.tex`. |
| 55 | |
| 56 | Our `.c` files are larger than most coding styles would |
| 57 | advocate. Our code is designed to be _read_, to be |
| 58 | _self-documenting_, to contain its own _testing methods_, and to |
| 59 | provide useful _working examples_. Thus the size of the files is a |
| 60 | little deceptive. Only about a quarter of a |
| 61 | module's `.c` file might typically be its actual module implementation. |
| 62 | Around half of the mass of a typical `.c` file is documentation, and |
| 63 | about a quarter consists of **_drivers_** for unit testing and examples. |
| 64 | |
| 65 | |
| 66 | ### dependencies between modules |
| 67 | |
| 68 | Module dependencies must follow a directed acyclic graph. You can't have |
| 69 | module foo depend on bar, bar depend on baz, and baz depend on foo. |
| 70 | |
| 71 | The main hierarchy in our graph is by project: Infernal uses HMMER and |
| 72 | Easel functions, and HMMER uses Easel functions. |
| 73 | |
| 74 | <img align="right" width="500" src="figures/easel_techtree.png"> |
| 75 | |
| 76 | Within a project, modules are organized (implicitly, if not |
| 77 | explicitly) in groups so that there's a hierarchy of groups, and a |
| 78 | hierarchy of modules within groups. The figure to the right shows the |
| 79 | current Easel "technology tree". ("Open in new tab" to embiggen.) |
| 80 | |
| 81 | |
| 82 | |
| 83 | ### the project prefix |
| 84 | |
| 85 | We have three primary software projects -- Easel, HMMER, and Infernal. |
| 86 | They stack on top of each other, with Infernal calling both HMMER and |
| 87 | Easel code, for example. When we look at our source code, we want to |
| 88 | identify at a glance where a given piece of code is from. We also want |
| 89 | to avoid name clashes with the system and with other libraries, even |
| 90 | unanticipated future ones. So each project has a unique prefix: |
| 91 | |
| 92 | | prefix | project | |
| 93 | |--------|-----------| |
| 94 | | `esl_` | Easel | |
| 95 | | `p7_` | HMMER 3.x | |
| 96 | | `h4_` | HMMER 4.x | |
| 97 | | `cm_` | Infernal | |
| 98 | |
| 99 | All externally visible identifiers use a project prefix. Static |
| 100 | identifiers (internal to one .c or .h file) do not. |
| 101 | |
| 102 | ### sections of the .c file |
| 103 | |
| 104 | A .c file is typically organized into a somewhat stereotypical set of |
| 105 | sections, to facilitate navigation: |
| 106 | |
| 107 | | section | description | |
| 108 | |------------------------|--------------| |
| 109 | | `the H4_FOOBAR object` | First section provides the API for creating and destroying any object(s) this module implements. | |
| 110 | | the rest of the API | Any other external functions follow, in one or more sections. | |
| 111 | | `debugging/dev code` | Externally visible functions for validating, dumping objects. | |
| 112 | | private functions | We aren't rigorous about where internal (static) functions go, but they often go in a separate section in the middle of the .c file, after the API and before the drivers. | |
| 113 | | optional drivers | Sections for any stats, benchmark, or regression drivers. | |
| 114 | | unit tests | `utest_*()` functions for the test driver. | |
| 115 | | test driver | All modules have an automated test driver that runs the unit tests. | |
| 116 | | examples | At least one example small program showing how to use the main features of the module. | |
| 117 | |
| 118 | The top of the .c file starts with a comment with a one-line |
| 119 | description of the module's purpose, a table of contents for its |
| 120 | sections, and possibly some other notes. |
| 121 | |
| 122 | For example, this is the top of start of `esl_json`: |
| 123 | |
| 124 | |
| 125 | /* esl_json : JSON data file parsing |
| 126 | * |
| 127 | * Inspired by Serge Zaitsev's Jasmine parser, https://github.com/zserge/jsmn |
| 128 | * |
| 129 | * Contents: |
| 130 | * 1. Full or incremental JSON parsing |
| 131 | * 2. ESL_JSON: a JSON parse tree |
| 132 | * 3. ESL_JSON_PARSER: precise state at each input byte |
| 133 | * 4. Accessing tokenized data |
| 134 | * 5. Debugging, development tools |
| 135 | * 6. Internal functions |
| 136 | * 7. Unit tests |
| 137 | * 8. Test driver |
| 138 | * 9. Example |
| 139 | * |
| 140 | * References: |
| 141 | * www.json.org |
| 142 | * tools.ietf.org/html/rfc8259 |
| 143 | */ |
| 144 | #include <esl_config.h> |
| 145 | |
| 146 | The short table of contents description lines are repeated in comments |
| 147 | at the top of each section later in the file, facilitating |
| 148 | text-searching: |
| 149 | |
| 150 | |
| 151 | /***************************************************************** |
| 152 | * 3. ESL_JSON_PARSER : precise state at each input byte |
| 153 | *****************************************************************/ |
| 154 | |
| 155 | These section headers are also parsed automatically by our `autodoc` |
| 156 | automated documentation script, when it extracts and formats a table |
| 157 | of external functions from the .c file. |
| 158 | |
| 159 | |
| 160 | |
| 161 | ### included headers |
| 162 | |
| 163 | The first include is a project-wide configuration header named |
| 164 | `<project_prefix>_config.h`. It must be included first, because it |
| 165 | may contain configuration constants that affect the behavior of other |
| 166 | headers, even including system headers. It must be included with angle |
| 167 | brackets, not double quotes, so compilation commands can control the |
| 168 | order that -I include directories are searched (build tree first, |
| 169 | source tree last), to assure that we don't erroneously use a stray |
| 170 | previous config file in the source tree when we're building in a build |
| 171 | tree. |
| 172 | |
| 173 | System headers come next, because they might contain configuration |
| 174 | that affects our headers. Finally come our headers. I tend to group |
| 175 | our headers together by project, and alphabetize them, but (aside from |
| 176 | the project-wide config.h) our headers don't depend on any particular |
| 177 | inclusion order. |
| 178 | |
| 179 | For example: |
| 180 | |
| 181 | |
| 182 | #include <h4_config.h> |
| 183 | |
| 184 | #include <stdio.h> |
| 185 | #include <stdlib.h> |
| 186 | #include <string.h> |
| 187 | |
| 188 | #include "easel.h" |
| 189 | #include "esl_alphabet.h" |
| 190 | #include "esl_random.h" |
| 191 | |
| 192 | #include "h4_hmm.h" |
| 193 | #include "h4_profile.h" |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 198 | ### the .h file |
| 199 | |
| 200 | The contents of each .h file are wrapped in a standardized `#ifndef |
| 201 | <project_prefix><MODULE>_INCLUDED` that makes sure each header is only |
| 202 | included once during compilation, regardless of the order of |
| 203 | `#include` statements; for example: |
| 204 | |
| 205 | ``` |
| 206 | #ifndef eslJSON_INCLUDED |
| 207 | #define eslJSON_INCLUDED |
| 208 | #include <esl_config.h> |
| 209 | |
| 210 | /* ...contents here... */ |
| 211 | |
| 212 | #endif /* eslJSON_INCLUDED */ |
| 213 | ``` |
| 214 | |
| 215 | The contents are typically ordered as: |
| 216 | |
| 217 | 1. Definition of constants and enums. |
| 218 | 2. Definition of typedef'd structures. ("objects"). |
| 219 | 3. External function declarations. |
| 220 | |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | ------------------------------------ |
| 226 | |
| 227 | ## writing an Easel function |
| 228 | |
| 229 | ### conventions for function names |
| 230 | |
| 231 | Externally visible function names are tripartite: `<pfx>_<module>_<funcname>`. |
| 232 | |
| 233 | The `<module>` part should be the module's full name. Some Easel |
| 234 | modules historically also have abbreviated tag names, such as `abc` |
| 235 | for the `alphabet` module, but I've decided this creates more |
| 236 | confusion than the saved typing is worth. |
| 237 | |
| 238 | Because `<pfx>` and `<module>` is also used to construct filenames, |
| 239 | the idea is that one should be able to immediately know where to find |
| 240 | the source code file for a given function, just from its name. |
| 241 | |
| 242 | There are a set of standard `<funcname>`'s that obey common behaviors, |
| 243 | called **interfaces** (see below). For example, allocation/deallocation routines |
| 244 | are called `_Create()` and `_Destroy()`. Otherwise, the name part can be anything. |
| 245 | We generally use mixed-case capitalization, as in `esl_json_DoSomething()`. |
| 246 | |
| 247 | Private (static) functions can be named anything you want (within |
| 248 | reason; be careful of namespace clashes, don't name a function |
| 249 | `strcmp()`) and do not have to follow these conventions. However, it's |
| 250 | common to just drop the `<pfx>` and have internal functions named |
| 251 | `<module>_<funcname>`. |
| 252 | |
| 253 | Sometimes essentially the same function must be provided for different |
| 254 | data types. In these cases one-letter prefixes are used to indicate |
| 255 | datatype: |
| 256 | |
| 257 | | char code | example | type | |
| 258 | |-----------|-----------------------|-------| |
| 259 | | `C` | `esl_rsq_CShuffle()` | `char` type, or a C `char *` text string | |
| 260 | | `X` | `esl_rsq_XShuffle()` | `ESL_DSQ` type, an Easel digitized sequence | |
| 261 | | `I` | `esl_vec_ISum()` | `int` integer(s) | |
| 262 | | `F` | `esl_vec_FSum()` | `float` float(s) | |
| 263 | | `D` | `esl_vec_DSum()` | `double` double(s) | |
| 264 | |
| 265 | |
| 266 | |
| 267 | ### conventions for argument names |
| 268 | |
| 269 | We have some conventions for argument names to help differentiate |
| 270 | between input versus output, and when output's memory space is |
| 271 | allocated within the function as opposed to being provided by the |
| 272 | caller. We also have a convention for optional results. These apply |
| 273 | especially to arguments that are pointers to our structures |
| 274 | (__objects__). |
| 275 | |
| 276 | Summarized: |
| 277 | |
| 278 | | argument | | |
| 279 | |-----------------|---------------------------------------------------------------| |
| 280 | | `const *foo` | `foo`'s contents are input-only, unmodified by the function. | |
| 281 | | `*foo` | `foo`'s contents are modified -- including reallocation of caller-provided space. | |
| 282 | | `*ret_foo` | `foo` is a result that's been allocated by the function. | |
| 283 | | `*opt_foo` | `foo` is an optional result allocated by the function. | |
| 284 | | `*byp_foo` | `foo` may be provided by the caller, may be allocated and returned by the function, or may be left NULL and the function will use internal defaults. | |
| 285 | |
| 286 | In more detail: |
| 287 | |
| 288 | * **const *foo, input only:** When an argument is a pointer to a |
| 289 | structure that's strictly input, unmodified by the function, we use |
| 290 | C's `const` qualifier. |
| 291 | |
| 292 | * __*foo, input/output:__ When the caller provides allocated existing |
| 293 | space, either with valid data (for an input/output argument) or |
| 294 | without. The function may modify the data, the allocation, or both. |
| 295 | We aim to minimize allocations (`malloc()` is relatively expensive) |
| 296 | so it's common to provide a previously allocated data structure that |
| 297 | might or might not be the right size to hold the function's output, |
| 298 | and have the function reallocate it only if needed. |
| 299 | |
| 300 | * __*ret_foo, allocated output:__The function allocates space for the result, |
| 301 | and passes back a pointer to it. The caller is responsible for |
| 302 | deallocation. For example: |
| 303 | |
| 304 | int |
| 305 | esl_module_Function(ESL_FOOOBJ **ret_foo) |
| 306 | { |
| 307 | ... |
| 308 | } |
| 309 | |
| 310 | is called like: |
| 311 | |
| 312 | ESL_FOOOBJ *foo = NULL; |
| 313 | esl_module_Function(&foo); |
| 314 | |
| 315 | * __*opt_foo, optional allocated output:__ As above, but for an optional |
| 316 | result. The caller can pass `NULL` instead of a pointer to a pointer |
| 317 | if it doesn't want the result. For example: |
| 318 | |
| 319 | int |
| 320 | esl_module_Function(ESL_FOOOBJ **opt_foo) |
| 321 | { |
| 322 | ... |
| 323 | } |
| 324 | |
| 325 | can either be called like the `*ret_foo` example above, or like: |
| 326 | |
| 327 | esl_module_Function(NULL); |
| 328 | |
| 329 | * __*byp_foo, input/output/default switch:__ There are a few cases |
| 330 | where there are three ways an argument is handled: |
| 331 | |
| 332 | * pointer to some needed input configuration that the caller knows; |
| 333 | * the configuration is unknown to the caller, the function will figure |
| 334 | it out, and the caller wants it back as output; |
| 335 | * the caller just wants the function to run in a default mode. |
| 336 | |
| 337 | I call this a "bypass" argument. The most common example arises in |
| 338 | handling a digital sequence alphabet, `ESL_ALPHABET`. For example, |
| 339 | to provide a known alphabet to a function: |
| 340 | |
| 341 | ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO); |
| 342 | esl_module_Function(&abc); |
| 343 | |
| 344 | to have the function figure out the alphabet and return it: |
| 345 | |
| 346 | ESL_ALPHABET *abc = NULL; |
| 347 | esl_module_Function(&abc); |
| 348 | |
| 349 | and to have the function run in default without it: |
| 350 | |
| 351 | esl_module_Function(NULL); |
| 352 | |
| 353 | The function itself would look something like: |
| 354 | |
| 355 | int |
| 356 | esl_module_Function(ESL_FOOOBJ **byp_abc) |
| 357 | { |
| 358 | ESL_ALPHABET *abc = (byp_abc == NULL || *byp_abc == NULL) ? esl_alphabet_Create(eslAMINO) : *byp_abc; |
| 359 | ... |
| 360 | if (byp_abc != NULL) *byp_abc = abc; |
| 361 | return eslOK; |
| 362 | } |
| 363 | |
| 364 | Or alternatively, because the pointer incantations are obscure and error-prone, |
| 365 | we have macros for this: |
| 366 | |
| 367 | int |
| 368 | esl_module_Function(ESL_FOOOBJ **byp_abc) |
| 369 | { |
| 370 | ESL_ALPHABET *abc = (esl_byp_IsInternal(byp_abc) || esl_byp_IsReturned(byp_abc)) ? esl_alphabet_Create(eslAMINO) : *byp_abc; |
| 371 | ... |
| 372 | if (esl_byp_IsReturned(byp_abc)) *byp_abc = abc; |
| 373 | return eslOK; |
| 374 | } |
| 375 | |
| 376 | |
| 377 | ### reentrancy and thread-safety |
| 378 | |
| 379 | All our code must expect to be called in multithreaded |
| 380 | applications. All functions must be reentrant. There should be no |
| 381 | global or static variables. |
| 382 | |
| 383 | |
| 384 | --------------------------------------------------- |
| 385 | |
| 386 | ## managing memory allocation |
| 387 | |
| 388 | We allocate memory using `ESL_ALLOC(ptr, size)`, a macro wrapper |
| 389 | around `malloc()`. Pointers are always initialized to `NULL` when they |
| 390 | are declared, before the `ESL_ALLOC()`. |
| 391 | |
| 392 | The `ESL_ALLOC()` macro depends on having an `int status` variable and |
| 393 | an `ERROR:` goto target in scope. If an allocation fails, |
| 394 | `ESL_ALLOC()` throws an `eslEMEM` exception with an error message that |
| 395 | reports the file, line number, and size of the attempted allocation. |
| 396 | If a nonfatal exception handler has been registered, when the handler |
| 397 | returns, it sets `status = eslEMEM` and jumps to `ERROR:`, our |
| 398 | idiomatic clean-up-and-return-abnormally block. |
| 399 | |
| 400 | The `int status` and `ERROR:` business is dirty, but is a price I've |
| 401 | decided to pay in return for a consistent, idiomatic handling of |
| 402 | errors with cleanup. |
| 403 | |
| 404 | For example: |
| 405 | |
| 406 | char *foo = NULL; |
| 407 | int status; |
| 408 | ... |
| 409 | ESL_ALLOC(foo, sizeof(char) * 128); |
| 410 | ... |
| 411 | return eslOK; |
| 412 | |
| 413 | ERROR: |
| 414 | return status; |
| 415 | |
| 416 | Similarly, there is an `ESL_REALLOC(ptr, newsize)` macro for |
| 417 | reallocating a pointer `ptr` to a new size in bytes `newsize`. |
| 418 | If `ptr` is `NULL`, `ESL_REALLOC()` behaves identically to |
| 419 | `ESL_ALLOC()`. |
| 420 | |
| 421 | We never make allocations of size 0. The macros treat a size of 0 as |
| 422 | an `eslEMEM` error. The result of `malloc(0)` is |
| 423 | implementation-defined according to the C99 standard; it can either be |
| 424 | `NULL`, or it can be a pointer value that must not be dereferenced. |
| 425 | We want to avoid having `NULL` as a successful result of an |
| 426 | allocation, because it confuses static analysis tools when they see |
| 427 | dereferences of possibly `NULL` pointers. |
| 428 | |
| 429 | The `size` argument is >= 0. It can be either signed or unsigned, but |
| 430 | beware of mixed constructs like `(sizeof(foo) * n)`. `sizeof()` |
| 431 | returns unsigned; (unsigned * signed) first converts the signed |
| 432 | operand to unsigned; if the signed operand is negative, the conversion |
| 433 | adds `UINT_MAX+1` modulo `UINT_MAX+1`, and a small negative signed |
| 434 | number becomes a ridiculously large unsigned one. Even when you know n |
| 435 | is positive, a `-Walloc-size-larger-than` warning in some gcc versions |
| 436 | is very aggressively looking for problems of this sort, where it may |
| 437 | assume that your n could have any value from INT_MIN to -1, generating |
| 438 | a false positive compiler warning. To suppress this warning we |
| 439 | typically use a signed cast, `(ptrdiff_t) sizeof(foo) * n`. |
| 440 | |
| 441 | |
| 442 | |
| 443 | ### resizeable objects |
| 444 | |
| 445 | ### reusable objects |
| 446 | |
| 447 | ### redlines |
| 448 | |
| 449 | |
| 450 | |
| 451 | |
| 452 | --------------------------------------------------- |
| 453 | |
| 454 | ## return codes, errors, and exceptions |
| 455 | |
| 456 | Visible functions should generally return an integer status |
| 457 | code. `eslOK` means success. Error codes are listed in |
| 458 | `easel.h`. Common ones include `eslEMEM` (memory allocation failure), |
| 459 | `eslEOF` (end-of-file), and `eslEFORMAT` (bad input format). |
| 460 | |
| 461 | A few interfaces follow a different pattern. `_Create()` functions |
| 462 | return an allocated pointer to a new object. `_Destroy()` functions |
| 463 | return `void`. `_Get*()` functions directly return some value they've |
| 464 | accessed in an object. |
| 465 | |
| 466 | We distinguish **normal errors** from **exceptions**. Anything that |
| 467 | could happen because of something the user does (including any input) |
| 468 | is a normal error. Anything that could happen because of a failure in |
| 469 | our code or unexpected system behavior (including allocation failures) |
| 470 | is an exception. |
| 471 | |
| 472 | Only a top-level application program is allowed to exit directly to |
| 473 | the shell. Following POSIX requirements, it returns status 0 (`eslOK`) |
| 474 | on success, nonzero (an Easel error code) on failure. On a normal |
| 475 | error from a command-line application, an informative user-directed |
| 476 | error message is printed on `stderr`, typically by calling `esl_fatal()`. |
| 477 | |
| 478 | In any function other than the top-level application program, |
| 479 | normal errors are reported by returning an error code, either by a |
| 480 | simple `return status`, or by using one of two Easel macros, |
| 481 | `ESL_FAIL()` or `ESL_XFAIL()`. |
| 482 | |
| 483 | Exceptions are thrown by calling the Easel exception handler, |
| 484 | generally through the Easel macros `ESL_EXCEPTION()` or |
| 485 | `ESL_XEXCEPTION()`. |
| 486 | |
| 487 | |
| 488 | |
| 489 | |
| 490 | |
| 491 | ### idiomatic function structure |
| 492 | |
| 493 | |
| 494 | |
| 495 | |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | -------------------------------- |
| 501 | ## function documentation |
| 502 | |
| 503 | Any comment that starts with |
| 504 | |
| 505 | ``` |
| 506 | /* Function: ... |
| 507 | ``` |
| 508 | |
| 509 | is recognized and parsed by our `autodoc.py` program, which assumes |
| 510 | that this starts a specially structured function documentation header. |
| 511 | |
| 512 | For information on `autodoc` and the format of our structured comment |
| 513 | headers, see [`devkit/autodoc.md`](../devkit/autodoc.md). |
| 514 | |
| 515 | |
| 516 | ----------------------------------------------- |
| 517 | |
| 518 | ## standard function interfaces |
| 519 | |
| 520 | ### creating and destroying objects |
| 521 | |
| 522 | * **_Create()** : create a new object, return ptr to it. |
| 523 | |
| 524 | ESL_FOO *esl_foo_Create() |
| 525 | |
| 526 | Takes any necessary size, initialization, configuration information |
| 527 | as arguments (if any), and returns a pointer to a newly allocated |
| 528 | object. The allocation may be just an initial guess (for a reusable |
| 529 | and resizable object). |
| 530 | |
| 531 | Throws `NULL` if an allocation fails. |
| 532 | |
| 533 | (If errors other than allocation errors can occur, use a **_Build()** |
| 534 | interface instead.) |
| 535 | |
| 536 | |
| 537 | * **_Build()** : create a new object that requires better error handling. |
| 538 | |
| 539 | int esl_foo_Build(ESL_FOO **ret_obj) |
| 540 | |
| 541 | Same as `_Create()`, but for the case when there are more ways to |
| 542 | fail than just allocation failure. Returns `eslOK` on success. |
| 543 | |
| 544 | On failure, returns an appropriate nonzero code, and `*ret_obj` is |
| 545 | returned `NULL`. |
| 546 | |
| 547 | |
| 548 | * **_Destroy()** : deallocate an object; returns `void`. |
| 549 | |
| 550 | void esl_foo_Destroy(ESL_FOO *obj) |
| 551 | |
| 552 | Must handle the case where `obj` is only partially allocated (for |
| 553 | example, when cleaning up after a failure in a `_Create()` call). |
| 554 | |
| 555 | Must also handle the case where `obj` is `NULL`, by doing nothing. |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | ### opening and closing streams |
| 561 | |
| 562 | * **_Open()** : open an input stream |
| 563 | |
| 564 | int esl_foo_Open(const char *filename, int fmtcode, ESL_FOO **ret_obj) |
| 565 | |
| 566 | Opens an input file by name for reading, or (more rarely) |
| 567 | transforms an open `FILE *` stream into a more complex object of |
| 568 | our own. Return a pointer to the open object in <*ret_obj>. |
| 569 | |
| 570 | If the file can be in different formats, there can be a `fmtcode` |
| 571 | argument, with possible format codes defined in the module header. |
| 572 | A `fmtcode` of 0 means unknown format, in which case the `_Open()` |
| 573 | call attempts to autodetect the format. This idiom allows callers |
| 574 | (thus users) to specify a format when it is known, or to let the |
| 575 | program determine the format for itself, a tradeoff of reliability |
| 576 | versus ease of use. |
| 577 | |
| 578 | If the filename is `-`, the new object is configured |
| 579 | to read from `stdin`. |
| 580 | |
| 581 | If the filename ends in a `.gz` suffix, the object is configured |
| 582 | to read from a `gzip -dc` pipe. |
| 583 | |
| 584 | On error, returns a nonzero Easel error code, including |
| 585 | `eslENOTFOUND` if file can't be found or opened for reading, or |
| 586 | `eslEFORMAT` if file isn't in expected format, or format |
| 587 | autodetection failed. |
| 588 | |
| 589 | |
| 590 | |
| 591 | * **_Close()** : close an input stream |
| 592 | |
| 593 | int esl_foo_Close(ESL_FOO *obj) |
| 594 | |
| 595 | Close the input stream `obj`. Return `eslOK` on success, or a |
| 596 | standard Easel error code. |
| 597 | |
| 598 | (There are cases where an error in an input stream is only detected |
| 599 | at closing time, such as input streams depending on |
| 600 | `popen()/pclose()`.) |
| 601 | |
| 602 | |
| 603 | |
| 604 | |
| 605 | |
| 606 | ### making copies of objects |
| 607 | |
| 608 | |
| 609 | * **_Clone()** : duplicate an object to newly allocated space |
| 610 | |
| 611 | ESL_FOO *esl_foo_Clone(const ESL_FOO *obj) |
| 612 | |
| 613 | Creates a new object, copies the contents of `obj` into it, and |
| 614 | returns a pointer to the new object. Equivalent to `_Create()` |
| 615 | followed by `_Copy()`. Caller is responsible for free'ing |
| 616 | the returned object. |
| 617 | |
| 618 | Throws `NULL` on allocation failure. |
| 619 | |
| 620 | |
| 621 | * **_Copy()** : copy an object into existing space |
| 622 | |
| 623 | int esl_foo_Copy(const ESL_FOO *src, ESL_FOO *dest) |
| 624 | |
| 625 | Copies `src` object into `dest`, where the caller has already |
| 626 | created an appropriately allocated and empty `dest` object. |
| 627 | |
| 628 | Returns `eslOK` on success. |
| 629 | |
| 630 | Throws `eslEINCOMPAT` if the objects are not compatible. |
| 631 | |
| 632 | * **_Shadow()** : create a partial dependent copy |
| 633 | |
| 634 | ESL_FOO *esl_foo_Shadow(const ESL_FOO *obj) |
| 635 | |
| 636 | Creates a partial new object that is dependent on `obj`. Some of |
| 637 | the data in `obj` is considered to be constant and shared with the |
| 638 | shadow. For constant shared data, the shadow only has pointers |
| 639 | into the original object, rather than actually copying the data. A |
| 640 | shadow must be deallocated before the primary object. The object |
| 641 | structure needs to have a flag for whether it's a shadow or not, |
| 642 | so that `_Destroy()` knows whether to deallocate the constant data |
| 643 | or not. |
| 644 | |
| 645 | Shadows arise in multithreading, when threads share some but not |
| 646 | all of an object's internal data. |
| 647 | |
| 648 | |
| 649 | ### resizing objects |
| 650 | |
| 651 | * **_Grow():** increase object's allocation, if necessary |
| 652 | |
| 653 | int esl_foo_Grow(ESL_FOO *obj) |
| 654 | |
| 655 | Check to see if `obj` can hold another element. If not, increase |
| 656 | the allocation, according to its internally stored rules on |
| 657 | reallocation strategy (often by doubling). Returns `eslOK` on |
| 658 | success. Throws `eslEMEM` on allocation failure. |
| 659 | |
| 660 | * **_GrowTo(n):** increase object's allocation to a given size, if necessary |
| 661 | |
| 662 | int esl_foo_GrowTo(ESL_FOO *obj, int n) |
| 663 | |
| 664 | Check to see if `obj` can hold `n` elements. If not, it |
| 665 | reallocates to at least that size. Returns `eslOK` on success. |
| 666 | Throws `eslEMEM` on allocation failure. |
| 667 | |
| 668 | * **_GrowFor(n):** increase object's allocation to hold at least n elements |
| 669 | |
| 670 | int esl_foo_GrowFor(ESL_FOO *obj, int n) |
| 671 | |
| 672 | Check to see if `obj` can hold `n` elements, and increase the |
| 673 | allocation if needed. If the allocation is already large enough, |
| 674 | do nothing. |
| 675 | |
| 676 | `<n>` does not include sentinels, if any. For an array of elements |
| 677 | 1..n with sentinels at 0 and n+1, for example, you pass n as |
| 678 | the argument, and the object is reallocated for at least n+2. |
| 679 | |
| 680 | A `_GrowFor()` gets used when we're building a large object |
| 681 | incrementally by appending several elements at once. **All data must |
| 682 | remain unchanged.** Only things having to do with allocation can be |
| 683 | changed. |
| 684 | |
| 685 | In general we reallocate by doubling. However, if |
| 686 | we're already very large (over redline), we don't want to pay the 2x |
| 687 | cost of a redoubling strategy. Also, it's reasonable (and harmless) |
| 688 | to guess that if the object is empty, maybe the caller is only |
| 689 | going to resize us once, not build us incrementally, so we can make |
| 690 | the first reallocation at the exactly requested size. So |
| 691 | in pseudocode: |
| 692 | ``` |
| 693 | if (n+s < redline || obj not empty): |
| 694 | reallocate by doubling until nalloc >= n+s |
| 695 | else |
| 696 | reallocate for n+s exactly |
| 697 | ``` |
| 698 | |
| 699 | When using redoubling strategies, be careful not to pathologically |
| 700 | overflow the allocation size: |
| 701 | ``` |
| 702 | if (n+s > INT32_MAX/2) ESL_XEXCEPTION(eslERANGE, "n too large"); |
| 703 | ``` |
| 704 | |
| 705 | Example: `h4_anchorset_GrowFor()` |
| 706 | [xref J14/1] |
| 707 | |
| 708 | ### reusing objects |
| 709 | |
| 710 | Memory allocation is computationally expensive. An application needs |
| 711 | to minimize `malloc()` calls in performance-critical regions. In loops |
| 712 | where one `_Destroy()`'s an old object only to `_Create()` the next |
| 713 | one, such as a sequential input loop that processes objects from a |
| 714 | file one at a time, instead we often have routines for recycling old |
| 715 | objects. |
| 716 | |
| 717 | * **_Reuse():** recycle and reinitialize an old object |
| 718 | |
| 719 | int esl_foo_Reuse(ESL_FOO *obj) |
| 720 | |
| 721 | Reinitialize `obj`, reusing as much of its previously allocated |
| 722 | memory as possible. A `_Reuse()` call is equivalent to calling |
| 723 | `_Destroy(); _Create()` but with few or no new allocations. |
| 724 | |
| 725 | If the object is arbitrarily resizable and it has a **redline** |
| 726 | control on its memory, the allocation is shrunk back to the |
| 727 | redline level. |
| 728 | |
| 729 | `_Reuse()` can either be called after we're done with an old |
| 730 | object (where a `_Destroy()` call might otherwise be used), or |
| 731 | before we're about to use a new one (where a `_Create()` call |
| 732 | might otherwise be used), depending on what makes sense in a |
| 733 | particular code context. |
| 734 | |
| 735 | |
| 736 | |
| 737 | ### accessing information in objects |
| 738 | |
| 739 | * **_Is*():** test some aspect of the state of an object |
| 740 | |
| 741 | int esl_foo_IsSomething(const ESL_FOO *obj) |
| 742 | |
| 743 | Performs some specific test of the internal state of an object, |
| 744 | and returns `TRUE` or `FALSE`. |
| 745 | |
| 746 | * **_Get*():** return a data element from an object |
| 747 | |
| 748 | value = esl_foo_GetSomething(const ESL_FOO *obj) |
| 749 | |
| 750 | Retrieves some specified data element from `obj` and return it |
| 751 | directly. Because no error code can be returned, a `_Get()` call |
| 752 | must be a simple access within the object, guaranteed to succeed. |
| 753 | `_Get()` routines can be implemented as macros. `_Read()` and |
| 754 | `Fetch()` are for more complex access methods that might fail, |
| 755 | thus requiring better error handling. |
| 756 | |
| 757 | |
| 758 | * **_Read*():** read a data object from a reader stream object |
| 759 | |
| 760 | int esl_foo_Read(ESL_FOOREADER *ffp, ESL_FOO *obj) |
| 761 | |
| 762 | Retrieves the next data object from an open input stream `ffp`, |
| 763 | and store it in `obj`, an already allocated space that the caller |
| 764 | has provided. The `_Read()` may grow the allocation of `obj` if |
| 765 | necessary. |
| 766 | |
| 767 | * **_Fetch*():** retrieve something from an object in new space |
| 768 | |
| 769 | int esl_foo_FetchSomething(const ESL_FOO *obj, <type> **ret_value) |
| 770 | |
| 771 | Retrieves something from `obj`, puts it in newly allocated space, |
| 772 | and returns a pointer to it in `*ret_value`. Caller is responsible |
| 773 | for deallocating `*ret_value`. |
| 774 | |
| 775 | * **_Set*():** set some data field(s) in an object |
| 776 | |
| 777 | int esl_foo_SetSomething(ESL_FOO *obj, const <type> value) |
| 778 | |
| 779 | Set some field in `obj` to `value`. If any memory needs to be |
| 780 | reallocated or free'd, this is done. |
| 781 | |
| 782 | * **_Format*():** set some string field in an object with printf() semantics |
| 783 | |
| 784 | int esl_foo_FormatSomething(ESL_FOO *obj, const char *fmt, ...) |
| 785 | |
| 786 | Sets some string field in `obj` using the `printf()`-style format |
| 787 | string `fmt` followed by arguments for that format. If any memory |
| 788 | needs to be reallocated or free'd, this is done. |
| 789 | |
| 790 | |
| 791 | ### debugging, testing, development |
| 792 | |
| 793 | * **_Sizeof():** return total allocated size of object, in bytes. |
| 794 | |
| 795 | size_t esl_foo_Sizeof(const ESL_FOO *obj) |
| 796 | |
| 797 | |
| 798 | * **_Validate():** verify that object contains valid data |
| 799 | |
| 800 | int esl_foo_Validate(const ESL_FOO *obj, char *errmsg) |
| 801 | |
| 802 | Checks that the contents of `obj` seem all right. Returns `eslOK` |
| 803 | if they are. If they aren't, returns `eslFAIL`, and caller |
| 804 | provides a non-`NULL` error message space `errmsg`, an informative |
| 805 | message describing the reason for the failure is formatted and |
| 806 | left in `errmsg`. If the caller provides this message buffer, it |
| 807 | must allocate it for at least `eslERRBUFSIZE` bytes. |
| 808 | |
| 809 | `_Validate()` routines can be used in production code to |
| 810 | validate user input. Therefore failures are normal |
| 811 | errors, handled by `ESL_FAIL()` (or `ESL_XFAIL()`). |
| 812 | |
| 813 | When `_Validate()` routines are used in unit tests, you can take |
| 814 | advantage of the fact that `ESL_FAIL()` and `ESL_XFAIL()` macros |
| 815 | call a stub function `esl_fail()`. You can set a debugging |
| 816 | breakpoint in `esl_fail()` to get a `_Validate()` routine to stop |
| 817 | immediately where a test failed. |
| 818 | |
| 819 | The `errmsg` can be either coarse-grained ("validation of object X |
| 820 | failed") or fine-grained ("in object X, data element Y fails test |
| 821 | Z"). A validation of user input (which we expect to fail often) |
| 822 | should be fine-grained, to return maximally useful information |
| 823 | about what the user did wrong. A validation of internal data can |
| 824 | be very coarse-grained, knowing that a developer can simply set a |
| 825 | breakpoint in `esl_fail()` to see what line the failure happens |
| 826 | on. |
| 827 | |
| 828 | * **_Compare():** compare two objects for equality |
| 829 | |
| 830 | int esl_foo_Compare(const ESL_FOO *obj1, const ESL_FOO *obj2, float r_tol, float a_tol) |
| 831 | |
| 832 | Returns `eslOK` if contents of `obj1` and `obj2` are judged to be |
| 833 | identical; returns `eslFAIL` if they differ. |
| 834 | |
| 835 | Floating point number comparisons call `esl_FCompare()` with |
| 836 | relative tolerance `r_tol` and absolute tolerance `a_tol` with the |
| 837 | `obj1` value treated as the reference |
| 838 | ($x_0$)). `esl_FCompare()` defines floating point equality as |
| 839 | $|x_0-x| < |x_0|*\mbox{r_tol} + \mbox{a_tol}$, |
| 840 | |
| 841 | (Do not use `atol` as a variable name, because it can get confused |
| 842 | with the atol() function.) |
| 843 | |
| 844 | `eslFAIL` can arise in normal use, for example when a `_Compare()` |
| 845 | routine is used to test for convergence of an iterative algorithm. |
| 846 | `_Compare()` functions are also commonly called inside |
| 847 | `_Validate()` functions. As in `_Validate()`, failures in a |
| 848 | `_Compare()` function are handled by `ESL_FAIL()` or |
| 849 | `ESL_XFAIL()`, so a debugging breakpoint can be set at |
| 850 | `esl_fail()`. |
| 851 | |
| 852 | Note that `eslOK` is 0 and error codes are nonzero, so you must do |
| 853 | `if (esl_foo_Compare(obj1, obj2) != eslOK)`, not just `if |
| 854 | (esl_foo_Compare(obj1, obj2)`. |
| 855 | |
| 856 | |
| 857 | * **_Dump():** print internals of an object compactly, for debugging |
| 858 | |
| 859 | int esl_foo_Dump(FILE *fp, const ESL_FOO *obj) |
| 860 | |
| 861 | Prints the internals of an object, often in a compact |
| 862 | human-readable tabular form. Useful during debugging and |
| 863 | development to view the entire object at a glance. Returns `eslOK` |
| 864 | on success. Unlike a more robust `_Write()` call, a `_Dump()` |
| 865 | call may assume that all its writes will succeed, and does not |
| 866 | need to check return status of `fprintf()` or other system calls, |
| 867 | because it is not intended for production use. |
| 868 | |
| 869 | |
| 870 | * **_TestSample():** generate ugly but syntactically valid object for unit tests |
| 871 | |
| 872 | int esl_foo_TestSample(ESL_RANDOMNESS *rng, ESL_FOO **ret_obj) |
| 873 | |
| 874 | Creates an object filled with randomly sampled values for all data |
| 875 | elements. The aim is to exercise syntactically valid values and |
| 876 | ranges, and presence/absence of optional information and |
| 877 | allocations, but not necessarily to obsess about data semantics. |
| 878 | For example, we use `_TestSample()` calls in testing MPI |
| 879 | send/receive communications routines, where we don't care so much |
| 880 | about the object's contents making sense, as we do about faithful |
| 881 | transmission of any object with syntactically valid contents. |
| 882 | |
| 883 | A `_TestSample()` call produces an object that is sufficiently |
| 884 | valid for use in other debugging tools, including `_Dump()`, |
| 885 | `_Compare()`, and `_Validate()`. However, because elements may be |
| 886 | randomly sampled independently, in ways that don't respect |
| 887 | interdependencies, the object may contain data inconsistencies |
| 888 | that make the object invalid for the application's real purposes. |
| 889 | Contrast `_Sample()` routines, which generate semantically and |
| 890 | syntactically valid objects, but are not as nasty about ugly edge |
| 891 | cases as a `_TestSample()`. |
| 892 | |
| 893 | |
| 894 | |
| 895 | ### miscellaneous |
| 896 | |
| 897 | * **_Write():** output to a file or stream |
| 898 | |
| 899 | int esl_foo_Write(FILE *fp, const ESL_FOO *obj) |
| 900 | |
| 901 | Write data from `obj` to an open, writable output stream |
| 902 | `fp`. Used for exporting or saving data files. `_Write()` |
| 903 | functions must be robust to system write errors, including filling |
| 904 | a filesystem or having a filesystem unexpectedly disconnect. They |
| 905 | must check return status of all system write calls, including |
| 906 | `*printf()` calls, throwing an `eslEWRITE` exception on system |
| 907 | failures. |
| 908 | |
| 909 | * **_Encode*():** convert a string representation to an internal integer code |
| 910 | |
| 911 | int code = esl_foo_EncodeSomething(const char *s) |
| 912 | |
| 913 | Given a string representation `s`, match it case-insensitively |
| 914 | against a list of possible strings and convert this human |
| 915 | representation to its internal `#define` or `enum` code. If the |
| 916 | string is unrecognized, returns a code of 0, signifying |
| 917 | "unknown". This must be a normal return error (not thrown |
| 918 | exception) because the string might come from user input, such as |
| 919 | a command line option argument. |
| 920 | |
| 921 | * **_Decode*():** convert an internal integer code to a string representation |
| 922 | |
| 923 | char *esl_foo_DecodeSomething(int code) |
| 924 | |
| 925 | Given an internal code (`enum` or `#define` constant), return a |
| 926 | pointer to its human-readable string representation, for |
| 927 | diagnostics or output. The strings are constants, so they can be |
| 928 | static. If `code` isn't recognized, throws an `eslEINVAL` |
| 929 | exception and returns `NULL` |
| 930 | |
| 931 | |
| 932 | |
| 933 | ---------------------------------------------------------------- |
| 934 | ## driver programs |
| 935 | |
| 936 | We embed several **driver programs** directly in the module's .c code. |
| 937 | Each of them is wrapped in standardized `#ifdef`'s, and our Makefiles |
| 938 | know how to compile them so that only one program and its `main()` are |
| 939 | compiled at a time. Drivers include a **unit test driver** and one or |
| 940 | more **example** program, and may also include **statistics |
| 941 | collections**, **benchmarks**, **experiments**, and special |
| 942 | **regression/comparison tests**. Having a unit test program and an |
| 943 | example program directly embedded in the .c code of a module |
| 944 | encourages throrough systematic testing, and makes the module more |
| 945 | self-documented. |
| 946 | |
| 947 | Appropriate conditional compilation is handled automatically by |
| 948 | our Makefile targets. Test drivers are compiled as part of `make check`, |
| 949 | which also runs our test suite. `make dev` compiles all the driver |
| 950 | programs. |
| 951 | |
| 952 | None of the driver programs are installed by `make install`. They're |
| 953 | only for testing and development. |
| 954 | |
| 955 | * **Unit test driver.** Each module must have exactly one `main()` that |
| 956 | runs all the **unit tests** for the module. It is enclosed by a |
| 957 | `<pfx><MODULE>_TESTDRIVE` ifdef, as in: |
| 958 | |
| 959 | #ifdef eslJSON_TESTDRIVE |
| 960 | ... |
| 961 | #endif /*eslJSON_TESTDRIVE*/ |
| 962 | |
| 963 | The unit test driver program takes no command line arguments. It |
| 964 | must generate any input files that it needs as temporary files |
| 965 | that it cleans up upon normal exit. It should complete with a few |
| 966 | seconds at most. If it succeeds, it returns 0; if it fails, it |
| 967 | calls `esl_fatal()` to issue a short error message on `stderr` and |
| 968 | returns nonzero. Our `sqc` script runs a large menu of all of a |
| 969 | project's tests, and it depends on each unit test driver having |
| 970 | these behaviors. |
| 971 | |
| 972 | It may have command line options for manual use. Common ones include: |
| 973 | |
| 974 | * `-h`: show brief help on version and usage |
| 975 | * `-s <n>`: set random number generator seed to `<n>` |
| 976 | * `-v`: produce more verbose and informative output |
| 977 | * `-x`: allow bad luck **stochastic test failures** (described later) |
| 978 | |
| 979 | It is customary for the unit test driver program to give a short |
| 980 | output that reports the program name, the random number generator |
| 981 | seed, and the exit status. |
| 982 | |
| 983 | ## esl_json_utest |
| 984 | # rng seed = 2349871 |
| 985 | # status = ok |
| 986 | |
| 987 | This output helps with finding **stochastic test failures** (described below). |
| 988 | |
| 989 | |
| 990 | * **Example driver(s).** Each module has one or more example |
| 991 | `main()` that provides a "hello world" level example of using the |
| 992 | module's API. An example may be extracted verbatim to our PDF |
| 993 | documentation, so it should be clean and short. It is enclosed |
| 994 | in a `<pfx><MODULE>_EXAMPLE` ifdef, such as `eslJSON_EXAMPLE`. |
| 995 | Additional examples have numbered ifdefs, like `eslJSON_EXAMPLE2`. |
| 996 | |
| 997 | * **Benchmark driver.** Optionally, there may be benchmark |
| 998 | performance test program(s) that collect time and/or memory statistics. They |
| 999 | may produce output for graphing. They are run on demand, manually, |
| 1000 | not by any of our automated tools. The ifdef's are |
| 1001 | `<pfx><MODULE>_BENCHMARK`. |
| 1002 | |
| 1003 | * **Statistics collection driver.** Optionally, there may be |
| 1004 | program(s) for collecting statistics used to characterize some other |
| 1005 | aspect of the module's scientific performance, such as its |
| 1006 | accuracy. Like benchmarks, these are designed to run manually. |
| 1007 | Ifdef's are `<pfx><MODULE>_STATS`. |
| 1008 | |
| 1009 | * **Experiment driver.** Optionally, there may be program(s) for |
| 1010 | running other reproducible experiments we've done on the module |
| 1011 | code, essentially the same as statistics generators. Ifdef's are |
| 1012 | `<pfx><MODULE>_EXPERIMENT`. |
| 1013 | |
| 1014 | * **Regression/comparison test driver.** Optionally, there may be |
| 1015 | program(s) that compare results of our code to either previous |
| 1016 | versions or to other standard libraries. These tests typically |
| 1017 | need to link to additional libraries, such as previous versions of |
| 1018 | our code, or libraries like LAPACK or the GNU Scientific Library. |
| 1019 | There aren't many such tests in our code at present, and they |
| 1020 | aren't well standardized. They are run (and sometimes even |
| 1021 | compiled) manually, because the requisite comparison libraries may |
| 1022 | not be present on our usual development machines. Ifdef's are |
| 1023 | `<pfx><MODULE>_REGRESSION`. |
| 1024 | |
| 1025 | The format of the conditional compilation ifdef's for all the drivers |
| 1026 | (including test and example drivers) must be obeyed. Some of our some |
| 1027 | development scripts depend on identifying these ifdef's automatically. |
| 1028 | Our Makefiles use them to systematically and automatically compile the |
| 1029 | driver programs for the module. |
| 1030 | |
| 1031 | ### summary |
| 1032 | |
| 1033 | | Driver type | ifdef flag example | program name example | notes | |
| 1034 | |--------------|-----------------------|--------------------------|---------------| |
| 1035 | | unit test | `eslJSON_TESTDRIVE` | `esl_json_utest` | output and exit status standardized for `sqc` | |
| 1036 | | example | `eslJSON_EXAMPLE` | `esl_json_example` | short and pretty, for verbatim inclusion in documentation | |
| 1037 | | benchmark | `eslJSON_BENCHMARK` | `esl_json_benchmark` | | |
| 1038 | | statistics | `eslJSON_STATS` | `esl_json_stats` | | |
| 1039 | | experiment | `eslJSON_EXPERIMENT` | `esl_json_experiment` | | |
| 1040 | | regression | `eslJSON_REGRESSION` | `esl_json_regression` | may require other installed libraries | |
| 1041 | |
| 1042 | |
| 1043 | --------------------------------------------------------------- |
| 1044 | ## writing unit tests |
| 1045 | |
| 1046 | An Easel test driver runs a set of individual unit tests one after |
| 1047 | another. Sometimes there is one unit test assigned to each exposed |
| 1048 | function in the API. Sometimes, it makes sense to test several exposed |
| 1049 | functions in a single unit test function. |
| 1050 | |
| 1051 | A unit test function is named `utest_*()`, declared static, and returns void: |
| 1052 | |
| 1053 | static void utest_something() |
| 1054 | |
| 1055 | Upon any failure, a unit test calls `esl_fatal()` with a |
| 1056 | developer-oriented error message and terminates. Don't use `abort()` |
| 1057 | or any other way to fail out of the test program. Our automated test |
| 1058 | script `sqc`, which is run by a `make check`, traps the output of |
| 1059 | `esl_fatal()` cleanly. |
| 1060 | |
| 1061 | If you write a new unit test, you just have to slot it into the list |
| 1062 | of unit tests that the test driver `main()` is calling. |
| 1063 | |
| 1064 | ### RNG seeding and dealing with expected stochastic failures |
| 1065 | |
| 1066 | Many unit tests use random sampling. Where possible, we seed the |
| 1067 | random number generator (RNG) pseudorandomly, so unit tests exercise |
| 1068 | different scenarios as we run them repeatedly. Initializing the RNG |
| 1069 | with `esl_randomness_Create(0)` selects an arbitrary pseudorandom |
| 1070 | seed. |
| 1071 | |
| 1072 | In production code packages that people install, our unit tests should |
| 1073 | never fail unless there's an actual problem. We don't want to |
| 1074 | frighten civilians, we don't want spurious "bug" reports, and we don't |
| 1075 | want to tell people "just run the test again, it's probably fine and |
| 1076 | won't happen again". However, there are cases where an RNG-dependent |
| 1077 | unit test can't guaranteed success 100% of the time for arbitrary |
| 1078 | seeds. For example, for a normally distributed numerical error, large |
| 1079 | errors may be improbable but not strictly impossible. In cases where |
| 1080 | we expect the test to succeed 99.99+% of the time for arbitrary seeds |
| 1081 | but we need 100% for production code, we define a fixed RNG seed where |
| 1082 | the test is known to work (often "42"). We call these "expected |
| 1083 | stochastic failures". |
| 1084 | |
| 1085 | During development, it might or might not be useful to allow expected |
| 1086 | stochastic failures. On the one hand, it's good to allow arbitrary |
| 1087 | seeds to find unusual problems. On the other hand, you don't want to |
| 1088 | be distracted by rare one-off glitches in code unrelated to what |
| 1089 | you're working on. Test drivers always have an option for setting the |
| 1090 | RNG seed manually (usually `-s`) so one can always do `my_utest -s 0` |
| 1091 | to override a default fixed seed. |
| 1092 | |
| 1093 | When a test does fail with an arbitrary seed, you want to know what |
| 1094 | that arbitrary seed was, so you can reproduce the problem. It isn't |
| 1095 | sufficient to know that the default seed was 0; that just means that |
| 1096 | one of $2^{32}$ possible seeds was chosen. So our tests always print |
| 1097 | the RNG seed using code like this in the test driver: |
| 1098 | |
| 1099 | ``` |
| 1100 | fprintf(stderr, "## %s\n", argv[0]); |
| 1101 | fprintf(stderr, "# rng seed = %" PRIu32 "\n", esl_randomness_GetSeed(rng)); |
| 1102 | ``` |
| 1103 | |
| 1104 | Because this output is from the `main()` of the test driver, not in |
| 1105 | individual utests, we generally create the RNG in `main()` and pass |
| 1106 | the same RNG to all individual utests, as opposed to passing them a |
| 1107 | seed that might be 0. Passing a seed to a utest isn't preferred, |
| 1108 | unless there's some other way that you're outputting the arbitrary |
| 1109 | seed that got chosen when your seed was 0. |
| 1110 | |
| 1111 | |
| 1112 | |
| 1113 | |
| 1114 | |
| 1115 | |
| 1116 | |
| 1117 | |
| 1118 | |
| 1119 | |
| 1120 | |
| 1121 | ### using temp files in unit tests |
| 1122 | |
| 1123 | |
| 1124 | |
| 1125 | |
| 1126 | ## playing nice with our other development tools |
| 1127 | |
| 1128 | ### using valgrind to find memory leaks, and more |
| 1129 | |
| 1130 | ### using gcov to measure unit test code coverage |
| 1131 | |
| 1132 | ### using gprof for performance profiling |
| 1133 | |
| 1134 | ### using the clang static analyzer, `checker` |
| 1135 | |
| 1136 | -------------------------------- |
| 1137 | |
| 1138 | > _This is the great nightmare, when you're doing something long and |
| 1139 | > hard, is you're terrified that it will be perceived as gratuitously |
| 1140 | > hard and difficult, that it is some avant-garde-for-its-own-sake kind |
| 1141 | > of exercise._ |
| 1142 | > |
| 1143 | > David Foster Wallace, speaking of _Infinite Jest_ |
| 1144 |