ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
Defer Statements

Block-scoped cleanup statements for C, Objective-C, and C++.

Block-scoped cleanup statements for C, Objective-C, and C++.

Defer Statements

Include <recast/defer.h> and place Defer Statements; in a compound statement. The action runs when execution leaves that block. A block action can be written as Defer Statements({ statements; });. C++11 and later, including Objective-C++, use a native scope guard rather than build-time rewriting. Its cleanup runs on exception unwinding as well as normal block exit; cleanup must not throw because the guard destructor is noexcept. Both backends accept C++ source files and preserve them for native C++ compilation. C++ scopes follow the language's normal object lifetime rules. On Windows, including the defer header makes Clang reject Microsoft-extension goto jumps that bypass a local variable's initialization, because bypassing a defer guard would leave its cleanup state uninitialized. Objective-C (.m) is transformed using @try/@finally, so registered actions also run while Objective-C exceptions unwind. This works in C functions, Objective-C methods, and block literals.

FILE *file = fopen(path, "r");
if (!file) return ERROR;
defer(fclose(file));
// Use file; fclose runs when this block exits.

SAFE_MALLOC_DEFER_FREE(name, size, pointer_type) and SAFE_CALLOC_DEFER_FREE(name, count, size, pointer_type) declare a tracked allocation and register SAFE_FREE(name) for the enclosing block. Include <ascii-chat/common.h> as well as the defer header. Like other deferred actions, cleanup reads the current pointer value at exit; after transferring ownership, set the local pointer to NULL.

SAFE_CALLOC_DEFER_FREE(items, count, sizeof(*items), item_t *);
if (!populate(items, count)) return ERROR;
#define SAFE_CALLOC_DEFER_FREE(name, count, size, cast)

In C, ordinary macros may wrap Defer Statements through multiple levels. The transformer expands those wrappers before analyzing cleanup. Wrapper definitions that use stringification, token pasting, __VA_OPT__, _Pragma, or __COUNTER__ are rejected, as are multiline invocations and arguments containing non-defer macros (use a local value instead). The expanded defer must still be a direct statement in a block. CMake discovers wrappers declared in project headers; set DEFER_WRAPPER_HEADER_DIRS to a semicolon-separated list of additional header directories when wrappers are declared outside the project.

Reaching a defer registers it. Actions run in reverse registration order, with inner blocks cleaned up first. They evaluate their expressions at exit, using the current values of referenced variables. They run on fallthrough, return, break, continue, and goto that leaves the block. A return expression is evaluated and converted to the function return type before cleanup. Nonlocal transfers such as longjmp and process termination do not run deferred actions.

defer_named(handle, action); registers a cancellable action, and defer_cancel(handle); cancels it. The handle is a lexical name, not a C variable: it cannot be copied, stored, or passed to another function. It is visible after registration in its block and nested blocks. Names of active handles must be unique. Canceling an already canceled handle is harmless; leaving and re-entering a loop body registers a fresh action.

defer_named(release_buffer, free(buffer));
if (hand_off(buffer) == SUCCESS)
defer_cancel(release_buffer);

Defer is supported in project .c and .m files and supported inline function bodies in included headers. Each defer must be a direct statement of a { ... } block. Add braces around an if or loop body before using defer there. Put a defer inside braces under a switch case; a defer directly in a switch body is rejected. Inline assembly in a function containing defer is rejected because its control flow may be opaque, including asm goto. Computed goto, jumps into a block containing defer, backward jumps that can register the same defer repeatedly, and unnamed non-builtin, non-pointer or variably modified parameters in non-void defer functions are rejected. Cleanup actions may not contain return, goto, break, continue, another defer, or __COUNTER__. The transformer also rejects source-level line directives, token-pasting macros in cleanup, preprocessor changes that can alter cleanup, and exits where an action identifier may bind to a different local declaration. These restrictions make unsupported control flow a build error rather than silently losing cleanup.

CMake uses the standalone C++ transformer by default. It writes generated sources below build/defer_transformed/; original source files are unchanged. The deps/recast submodule supplies the CMake integration. CMake downloads a release for the build host and verifies its checksum; DEFER_NATIVE_BINARY can point to an existing host executable instead. The native build does not require Python or LLVM development libraries for defer. The tool reads each translation unit's flags and include paths from compile_commands.json. The native tool transforms batch files concurrently using available CPU threads. Pass --jobs=N when invoking it directly to set a smaller limit. During incremental native builds, the batch reuses transformations whose source, recorded included files, and build context are unchanged; it reports how many files it transformed. A file is reprocessed when its own compiler arguments, dependencies, libclang version, or the tool binary change. DEFER_SHARED_CACHE optionally sets a shared cache directory, such as ASCIICHAT_DEPS_CACHE_ROOT/defer. It can reuse results across build directories for the same source tree, after checking dependency contents and the current include graph. Files using time-dependent macros or __has_include are transformed normally instead of being shared. It is disabled by default because checking a cache can cost more than a fresh transformation. Direct tool users can select the cache with --shared-cache together with --incremental. --preamble enables experimental Clang preamble reuse for direct tool invocations; it is not enabled by CMake because measurements may be slower. Each generated translation unit has its own directory, and the original source directory remains on Clang's quoted-include search path. Relative includes therefore resolve from the original source tree, including nested includes; included files are tracked as build dependencies. Per-source dependency stamps cause only affected objects to rebuild when an included file changes, even if the transformed C text itself stays unchanged. With Ninja, a lightweight eligibility scan runs on each build. Editing an ordinary source does not reconfigure CMake; adding or removing its first defer call changes the source set and automatically regenerates the build graph before compilation. Unix Makefiles use conservative reconfiguration on C source changes to ensure the same correctness.

The CMake integration requires a compilation database and a single-config Ninja or Unix Makefiles generator. The standalone defer repository also maintains a Python implementation. Directly compiling an untransformed C source containing defer fails rather than turning cleanup into a no-op. C header functions use per-translation- unit Clang VFS overlays. DEFER_HEADER_OVERLAYS=AUTO detects defer in project headers; ON forces this path and OFF disables it. Add external header roots to DEFER_WRAPPER_HEADER_DIRS, or use ON when headers are outside the scanned roots. The first activation analyzes all eligible project C and Objective-C sources and disables target precompiled headers; later builds use native per-file incremental caching. The shared cache is not used while header overlays are active. Multiple active instantiations of the same header function in one translation unit are rejected. Defer in an included C source file remains unsupported. C++ uses native scope guards directly. Objective-C and Objective-C++ require an Objective-C runtime advertising zero-cost exceptions, with exception handling enabled. CMake adds -fobjc-exceptions when transforming .m sources. Direct tool users must pass it in the actual compilation arguments and compile with the same flags. A CMake project compiling .m files must enable its OBJC language; the ascii-chat project already enables it on Apple platforms. On Linux, provide a modern GNUstep libobjc2 runtime, select it with an appropriate -fobjc-runtime=gnustep-2.0 compiler option, and link that runtime. Apple exception unwinding has been verified; the legacy GNU Objective-C runtime does not support this contract and is rejected. Objective-C jumps into a generated protected region are rejected by Clang validation. For C sources, panic instrumentation runs before defer transformation when enabled. Objective-C sources are not instrumented by the panic tool.

Both implementations can transform several files in one invocation using --batch manifest.txt. Each UTF-8 manifest line contains an input path and an output path separated by a tab. With --compilation-database, pass either the directory containing compile_commands.json or the file itself. The tool looks up the generated output first, then the original input; multiple matching commands are rejected because the correct configuration is unclear.

Without a compilation database, add a third tab-separated field containing a JSON array of Clang arguments for that file. For example, a manifest can contain the following lines, with each <TAB> replaced by an actual tab:

src/a.c<TAB>out/a.c<TAB>["-std=c17", "-DVALUE=1", "-Iinclude"]
src/b.c<TAB>out/b.c<TAB>["-std=c23", "-DVALUE=2", "-Iinclude"]
static bool size_t gotel_query_t * out
Definition queries.h:8

The arrays contain parser arguments, not the compiler executable, input, output, or shell-quoted command. Relative paths in those arguments resolve from the tool's working directory; use -working-directory when needed. A two-field row without a database uses no additional arguments. Explicit per-file arguments and a compilation database cannot be combined. Native batch mode supports --dependency-stamps --incremental with either form; changing one file's arguments invalidates that file's cached transformation.

For a single source, either implementation automatically reads redirected stdin and writes validated transformed bytes to stdout when no input/output paths or other modes are specified:

defer-tool --filename path/to/input.c -- -std=c17 -Iinclude < input.c > output.c
# Equivalent positional form:
defer-tool --filename path/to/input.c - - -- -std=c17 -Iinclude < input.c > output.c

--filename is required for stdin input. It determines the input language, source locations, and relative include lookup. It is a virtual path and is not read or overwritten. A compilation database may be used instead of explicit flags when it has an entry for that path. Diagnostics go to stderr and invalid input produces no transformed output. This mode handles one translation unit and does not support header overlays, dependency files, or batch options. The ascii-chat CMake build always uses batch mode.

To inspect an exit without writing a generated file, pass its source line and the C compilation arguments to either implementation:

defer-tool --explain src/example.c:42 -- -std=c23 -Iinclude

Actions are listed in cleanup order. Each runs only if execution actually reached its registration and has not canceled it; the output does not claim to predict branch choices. Use explicit Clang arguments for this mode. Use defer-tool --show-transformed src/example.c:42 -- -std=c23 -Iinclude to print the generated version of the function containing that line. The displayed snippet includes source mapping directives and is for inspection; it is not a standalone translation unit.

For a longer randomized check on a Unix host with Clang and libFuzzer, configure the standalone defer project with DEFER_BUILD_FUZZER=ON, build defer-fuzz, and run it with a writable copy of tests/fuzz/defer as the corpus. Successful transformations are parsed again and must remain valid C.