progmasoft-cpp
The C++ style guide of Progmasoft: naming, formatting, language rules, errors, ownership, ABI, testing and tooling.
Clonegit clone https://git.progmasoft.com/progmasoft-cpp
Write the first revision of Progmasoft C++ Style
- Commit
8d1fb4807edc7920fbecd0554c9c61625827e19c- Author
- Leitwolf11 ·
Changes
ADOPTING.md | 63 ++++++ CHANGELOG.md | 18 ++ CONTRIBUTING.md | 33 +++ Guide/C-INTERFACES.md | 124 +++++++++++ Guide/COMMENTS-AND-DOCUMENTATION.md | 82 +++++++ Guide/CONCURRENCY.md | 73 +++++++ Guide/ERRORS.md | 123 +++++++++++ Guide/FILES-AND-HEADERS.md | 109 ++++++++++ Guide/FORMATTING.md | 219 +++++++++++++++++++ Guide/LANGUAGE.md | 170 +++++++++++++++ Guide/NAMING.md | 94 ++++++++ Guide/OWNERSHIP-AND-MEMORY.md | 88 ++++++++ Guide/PRINCIPLES.md | 59 +++++ Guide/TESTING.md | 94 ++++++++ Guide/TOOLING.md | 161 ++++++++++++++ Guide/TYPES-AND-CLASSES.md | 137 ++++++++++++ LICENSE.md | 418 ++++++++++++++++++++++++++++++++++++ LICENSES/CC0-1.0.md | 131 +++++++++++ README.md | 61 ++++++ 19 files changed, 2257 insertions(+) diff --git a/ADOPTING.md b/ADOPTING.md new file mode 100644 index 0000000..2fc3f12 --- /dev/null +++ b/ADOPTING.md @@ -0,0 +1,63 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# Adopting the guide + +A project adopts Progmasoft C++ Style by pointing to it, copying its two tool profiles and writing down, once, where it +deviates. + +## 1. Point to the guide + +Add a short section to the project's contributing guide: + +```markdown +## C++ style + +C++ code follows [Progmasoft C++ Style](https://github.com/Progmasoft/progmasoft-cpp). +`clang-format` and `clang-tidy` enforce what they can; review covers the rest. +Deviations of this project are listed below. +``` + +Do not copy the rules into the project. A copy drifts from the guide, and two documents that disagree are worse than +one. + +## 2. Copy the profiles + +| File | From | +| --- | --- | +| `.clang-format` | [Formatting: the profile](Guide/FORMATTING.md#the-profile) | +| `.clang-tidy` | [Tooling: the clang-tidy profile](Guide/TOOLING.md#132-the-clang-tidy-profile), with the path filters set to the project's directories | +| compiler flags | [Tooling: flags](Guide/TOOLING.md#flags), in the build files of the project | + +The profiles are in the public domain (see [LICENSE.md](LICENSE.md)), so they can be copied under the project's own +license. Note the guide revision they come from in a comment at the top of each file, so a later update can be compared. + +## 3. Record the deviations + +Every project has a few rules of its own: a namespace root, an include prefix, a test framework, a component that must +use exceptions because its host does. List them in the contributing guide, each with its reason: + +```markdown +### Deviations + +- The intermediate representations use the lowercase namespaces `tala::core`, `tala::xpp` and `tala::xmm`, because + they are qualified on almost every line of the compiler (Naming, 3.4). +- Assertion failures are reported by throwing, as the Catch2 API requires; exceptions stay inside the library + (Errors, 7.1). +``` + +Within the project, its documented rule wins over the guide. An undocumented difference is not a deviation; it is code +that has not caught up yet. + +## 4. Converge gradually + +Existing code is not rewritten in one sweep. A file follows the guide where it is changed. A purely mechanical change, +such as applying `clang-format` to a directory or renaming a member convention, is its own pull request, never mixed +with a change in behavior, so that review and `git blame` stay useful. + +## Projects that follow the guide + +| Project | Deviations recorded in | +| --- | --- | +| [Progmasoft/tala](https://github.com/Progmasoft/tala) | `Documents/Contributing/STYLE-AND-LICENSING.md` | +| [Progmasoft/catch3](https://github.com/Progmasoft/catch3) | the Progmasoft-authored sources under `src/Progmasoft/`; code derived from Catch2 keeps its upstream style | diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..feefc35 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,18 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# Changelog + +A revision of the guide is named by its date. A change that requires existing code to change says so. + +## Unreleased + +## 2026-10-18 + +The first revision of Progmasoft C++ Style. It writes down the conventions of the Progmasoft C++ projects and decides +what they left open: + +- thirteen chapters, from principles to tooling, with the `.clang-format` and `.clang-tidy` profiles and the compiler + flags in full; +- guidance for adopting the guide and recording a project's deviations; +- the text under CC BY 4.0, the configuration and code examples under CC0 1.0. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b718214 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,33 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# Contributing + +Progmasoft C++ Style changes when a rule turns out to be wrong, unclear or missing. Proposals are welcome from anyone, +whether or not they work on a Progmasoft project. + +## Proposing a change + +Open an issue first for anything beyond a correction of wording, a typo or a broken link. Describe: + +- **the rule**, as it reads now or as you would write it; +- **the problem**: code that the current rule makes worse, a bug it fails to prevent, or a case it does not cover; +- **the cost of the change** for projects that already follow the guide: how much code would have to change, and whether + a tool can do it. + +A rule earns its place by preventing a real class of mistakes or by removing a choice that would otherwise be argued +about in every review. "Another style guide does it" is a starting point, not a reason. + +## Writing the change + +- Keep the shape of the guide: a rule in bold that says what to do, then the reason, then an example when it helps. +- Examples follow every rule of the guide, including formatting by the profile and the 80-column limit. +- A change to `.clang-format` or `.clang-tidy` says which clang version it was tested with and what it changes in + formatted code. +- Write in US English, in the present tense and the active voice. +- Note the change under `## Unreleased` in [CHANGELOG.md](CHANGELOG.md), saying whether existing code must change. + +## License of contributions + +By contributing you agree that your text is licensed under [CC BY 4.0](LICENSE.md) and that your configuration and code +examples are dedicated to the public domain under [CC0 1.0](LICENSES/CC0-1.0.md), like the rest of the guide. diff --git a/Guide/C-INTERFACES.md b/Guide/C-INTERFACES.md new file mode 100644 index 0000000..3fc7b60 --- /dev/null +++ b/Guide/C-INTERFACES.md @@ -0,0 +1,124 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 10. C interfaces + +A C interface is the stable binary boundary of a library: what another language, another compiler or another version of +the library links against. It is written in C11 and kept small; everything behind it is C++20. + +## 10.1 The header + +```c +// SPDX-FileCopyrightText: 2026 Example <contact@example.com> +// SPDX-License-Identifier: MPL-2.0 +#ifndef EXAMPLE_PARSER_H +#define EXAMPLE_PARSER_H + +#include <stddef.h> +#include <stdint.h> + +#ifdef __cplusplus +extern "C" { +#endif + +/// Version of this interface; bumped on every incompatible change. +#define EXAMPLE_PARSER_ABI_VERSION 3 + +/// Opaque parser state, owned by the library. +typedef struct example_parser example_parser; + +/// Result of an operation of this interface. +typedef enum example_status +{ + EXAMPLE_STATUS_OK = 0, + EXAMPLE_STATUS_INVALID_ARGUMENT = 1, + EXAMPLE_STATUS_MALFORMED_INPUT = 2, +} example_status; + +/// Create a parser. Release it with example_parser_destroy. +/// @param out Receives the parser on success; untouched on failure. +example_status +example_parser_create(example_parser **out); + +/// Release a parser created by example_parser_create. Accepts NULL. +void +example_parser_destroy(example_parser *parser); + +#ifdef __cplusplus +} +#endif + +#endif // EXAMPLE_PARSER_H +``` + +- **`.h`, C11, and include guards.** A C header may be read by a C compiler that does not know `#pragma once`, so it uses + a guard named after the file. +- **Every name has the project prefix**: functions and types `example_`, macros and enumerators `EXAMPLE_`. C has one + namespace for the whole program. +- **`extern "C"`** guards wrap the declarations, so C++ callers link against the same symbols. +- **Opaque types**: callers see a forward-declared struct and a pointer, never the layout. The layout can then change + without breaking callers. +- **Fixed-width types** (`uint32_t`, `size_t` for sizes) and no `bool` in a struct whose layout is part of the ABI; use + `uint8_t` with documented values. +- **A version macro or a version function**, so a caller can check at build time or at run time that it talks to the + interface it was written for. + +## 10.2 Ownership across the boundary + +- **Whoever allocates, frees.** A buffer the library returns is released by a function of the library, never by the + caller's `free`, because the two may not share an allocator. +- **Borrowed data is copied before the call returns** when the library needs it longer. A callback that receives a + pointer and a length may use them only until it returns; the library copies anything it keeps into memory it owns. +- **Document every pointer parameter**: may it be null, who owns it after the call, how long it must stay valid. +- **No C++ type crosses the boundary**: no `std::string`, no reference, no class with a constructor, no template. + +## 10.3 Failure across the boundary + +- **No exception crosses a C interface**, ever. With exceptions disabled this holds by construction; a project that + enables them catches everything at the boundary. +- **Every fallible function returns a status** and writes its results through out-parameters, which it leaves untouched + on failure. A function that cannot fail returns `void` or the value. +- **Detailed messages** are available through a separate call or an error object the caller owns and releases, not + through a global "last error" that breaks with threads. + +## 10.4 The C++ side + +Behind the interface, the implementation is ordinary C++20 that follows the rest of this guide: + +```cpp +extern "C" auto +example_parser_create(example_parser **out) -> example_status +{ + if (out == nullptr) + { + return EXAMPLE_STATUS_INVALID_ARGUMENT; + } + auto parser = std::make_unique<example_parser>(); + *out = parser.release(); + return EXAMPLE_STATUS_OK; +} +``` + +C++ callers wrap a C handle in an RAII type right away: + +```cpp +struct ParserDeleter final +{ + void + operator()(example_parser *parser) const noexcept + { + example_parser_destroy(parser); + } +}; + +using ParserHandle = std::unique_ptr<example_parser, ParserDeleter>; +``` + +## 10.5 Keeping it stable + +- **Record the interface in one place**: a manifest or a header that is the single source of truth for every symbol, + struct layout and magic number, checked in CI against the code. +- **Add, do not change.** A new function or a new enumerator is compatible; changing a signature, a layout or the meaning + of a value is not, and bumps the interface version. +- **Test the interface from C**: a test translation unit compiled as C11 includes the header and calls every function, + so that a C++-only construct in the header cannot slip in. diff --git a/Guide/COMMENTS-AND-DOCUMENTATION.md b/Guide/COMMENTS-AND-DOCUMENTATION.md new file mode 100644 index 0000000..7cdffb7 --- /dev/null +++ b/Guide/COMMENTS-AND-DOCUMENTATION.md @@ -0,0 +1,82 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 9. Comments and documentation + +Comments are written in US English, in full sentences that end with a period. They explain what the code cannot say for +itself: what an interface promises, why a choice was made, and what would break if someone changed it. + +## 9.1 Documentation comments + +Every public declaration in a header, meaning every type, function, enumerator, constant and data member that another +component can use, has a Doxygen comment written with `///`: + +```cpp +/// Derive the blocks that are live on entry to each block of a function. +/// The result lists blocks in ascending id order, so it is stable across +/// runs and can be compared in tests. +/// @param graph Control-flow graph of the function; must be verified. +/// @param uses Variables read by each block. +/// @return Live-in sets, or an error when the graph and the use table +/// describe different numbers of blocks. +[[nodiscard]] auto +AnalyzeLiveness(const ControlFlowGraph &graph, const UseTable &uses) + -> llvm::Expected<LivenessResult>; +``` + +- **The first sentence says what the declaration is or does**, as a summary that stands on its own in a list of + declarations. Start a function's summary with a verb in the imperative: "Derive", "Return", "Create". Start a type's + summary with a noun phrase. +- **Then the contract**: preconditions, what the result guarantees (order, ownership, lifetime of returned views), what + happens on failure, and whether the function is thread-safe when that is not obvious. +- **`@param`** for every parameter whose meaning or constraints the name does not fully convey, and **`@return`** for + every non-void function. `@pre`, `@post` and `@note` may be used where they help. +- **Do not document the implementation** in a header. A comment that says "uses a hash map internally" is wrong the day + the implementation changes, and the caller should not depend on it. +- **A longer description** may use a `/** ... */` block with `@brief`, lists and examples, as Doxygen renders them. +- **Doxygen runs in CI** with warnings as errors for the public headers, so an undocumented or misdocumented declaration + fails the build. + +## 9.2 Implementation comments + +Inside a function, comment **why**, not what: + +```cpp +// The verifier already rejected unreachable blocks, so every block here has a +// predecessor and the entry block is the only root of the dominator tree. +``` + +```cpp +// Avoid: restates the code. +// Increment the counter. +++counter; +``` + +Comment especially: + +- an invariant the code relies on and a later change could break: identity, ordering, ownership, a protocol bound; +- a workaround for a compiler, library or platform defect, with a link to the report and the condition for removing it; +- a choice that looks wrong but is deliberate, and why the obvious alternative does not work; +- the reason for every magic number that cannot be a named constant. + +Keep a comment next to the code it explains, and change it in the same commit as the code. + +## 9.3 TODOs + +A `TODO` names the issue that tracks it: `// TODO(#123): accept signed offsets once the wire format has them.` A TODO +without an issue is either done now or not written. Do not leave commented-out code; version control keeps the history. + +## 9.4 File comments + +A file starts with its license header and has no other boilerplate: no author list, no creation date, no change log. +When a file needs an overview, such as a component's main header, write it as the documentation comment of the +namespace or of the main type. + +## 9.5 Words + +- Say what a thing is for, in the vocabulary of its users, not of its implementation. +- Prefer the active voice and the present tense: "The parser stops at the first error", not "The parsing will be + stopped". +- Use the project's terms consistently. If the project calls something a "block", do not call it a "node" in one comment + and a "basic block" in another. +- Do not use comments for jokes, blame or emotions. A comment is read years later, out of context, by someone in a hurry. diff --git a/Guide/CONCURRENCY.md b/Guide/CONCURRENCY.md new file mode 100644 index 0000000..9099de3 --- /dev/null +++ b/Guide/CONCURRENCY.md @@ -0,0 +1,73 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 11. Concurrency + +Concurrent code is correct only when it is correct for every interleaving, and testing finds few of them. The rules +below make the shared state small and visible, so that a reader can check it. + +## 11.1 Share less + +- **Prefer no sharing**: give each thread its own data and combine the results at the end. A result that several + threads compute is merged in a fixed order, so the output does not depend on scheduling. +- **Immutable data may be shared freely.** An object that is fully built before the threads start and never changed + afterwards needs no lock. +- **Everything else that more than one thread touches** is protected by one mutex, or is an atomic, and the comment of + the member says which. + +## 11.2 Threads + +- **`std::jthread`**, which joins on destruction and carries a stop token, instead of `std::thread`. +- **No detached threads.** Every thread has an owner that joins it. +- **A thread pool or an executor** for many short tasks, owned by the component that needs it, not a global. +- **Name long-lived threads** when the platform allows it, so they are recognizable in a debugger and a profiler. + +## 11.3 Locks + +- **`std::scoped_lock`** to lock, and `std::unique_lock` only when a condition variable or a deferred lock needs it. + Never call `lock()` and `unlock()` by hand. +- **Hold a lock for as short as possible**, and never while calling code you do not control: a callback, a virtual + function of an unknown implementation, I/O. +- **Lock several mutexes with one `std::scoped_lock`**, which avoids deadlock, or document a lock order and keep to it. +- **A condition variable waits with a predicate**: `condition.wait(lock, [&] { return ready; })`, never a bare `wait`, + which wakes spuriously. + +## 11.4 Thread-safety annotations + +With Clang, annotate the shared state and the functions that need a lock, and build with `-Wthread-safety` as an error: + +```cpp +class Cache final +{ +public: + void + Insert(Key key, Value value) EXAMPLE_EXCLUDES(mutex_); + +private: + Mutex mutex_; + std::unordered_map<Key, Value> entries_ EXAMPLE_GUARDED_BY(mutex_); +}; +``` + +The annotation macros wrap Clang's `capability`, `guarded_by`, `requires_capability` and `locks_excluded` attributes, +and expand to nothing on other compilers. `Mutex` is a thin wrapper of `std::mutex` that carries the `capability` +attribute, because the standard type does not. + +## 11.5 Atomics + +- **An atomic is for one value**, such as a counter or a flag. Two atomics that must change together need a mutex. +- **Sequentially consistent by default**: `counter.fetch_add(1)`. A weaker memory order (`acquire`, `release`, + `relaxed`) needs a comment that names the operation it synchronizes with and why the weaker order is enough. +- **No `volatile` for synchronization.** It is for memory-mapped hardware, not for threads. + +## 11.6 Statics and globals + +- A function-local `static` that is initialized once is thread-safe in C++; use it for a lazily built constant table. + Do not use it for mutable state. +- No mutable global state. When a process-wide resource is unavoidable, such as a signal handler or a C library that + must be initialized once, wrap it in one object with a documented lifetime. + +## 11.7 Testing concurrent code + +ThreadSanitizer runs the concurrent tests in CI (see [Testing](TESTING.md#123-sanitizers)). A test that relies on +`sleep` to order threads is wrong; it uses a latch, a barrier or a condition the threads wait for. diff --git a/Guide/ERRORS.md b/Guide/ERRORS.md new file mode 100644 index 0000000..e57c790 --- /dev/null +++ b/Guide/ERRORS.md @@ -0,0 +1,123 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 7. Errors + +A failure is one of three things, and each has one way of being handled. + +| Kind | Example | Handled by | +| --- | --- | --- | +| **Recoverable failure** | a malformed input file, a missing path, a value out of range | returning `Expected<T>` or `Error` | +| **Broken invariant** | a verifier that accepted an IR it must reject, an index the caller guaranteed in range | an assertion, or a fatal error in release builds | +| **Unrecoverable environment** | out of memory, a corrupted heap | termination | + +## 7.1 No exceptions in libraries and tools + +Code is compiled with `-fno-exceptions` (`/clang:-fno-exceptions` with `clang-cl`). There is no `throw`, `try` or +`catch` in first-party code, including tests, fuzzers and benchmarks. + +The reasons are practical: an exception is invisible in a signature, so a caller cannot see that a call can fail; it +cannot cross a C interface; and its cost and its interaction with destructors are hard to reason about in code that also +runs under sanitizers and fuzzers. + +**A project may opt in** when its host model depends on exceptions, as a C++ test framework that reports a failed +assertion by throwing does. The project says so in its documentation, keeps exceptions inside its own code, and still +never lets one cross a C interface or escape a destructor. Third-party code keeps its own compiler options either way. + +## 7.2 `Expected<T>` and `Error` + +A function that produces a value or fails returns `Expected<T>`; one that only succeeds or fails returns `Error`. The guide +does not prescribe the library. `llvm::Expected<T>` and `llvm::Error` suit code that already depends on LLVM; a C++20 +backport of `std::expected` (such as `tl::expected`) or a small type of the project's own suit the rest, and C++23's +`std::expected` replaces them once a project moves to it. What matters is the discipline below: the failure is in the +signature, it cannot be ignored, and it carries a message. + +The examples use LLVM's types. + +```cpp +[[nodiscard]] auto +ParseHeader(llvm::ArrayRef<std::uint8_t> bytes) -> llvm::Expected<Header> +{ + if (bytes.size() < kHeaderSize) + { + return llvm::createStringError( + "header is %zu bytes; at least %zu are required", + bytes.size(), + kHeaderSize); + } + // ... +} + +[[nodiscard]] auto +LoadModule(const std::filesystem::path &path) -> llvm::Expected<Module> +{ + auto bytes = ReadFile(path); + if (!bytes) + { + return bytes.takeError(); + } + auto header = ParseHeader(*bytes); + if (!header) + { + // path::c_str() is wide on Windows; string() is the narrow form. + return llvm::joinErrors( + llvm::createStringError("%s: not a module", + path.string().c_str()), + header.takeError()); + } + return Module{*header, std::move(*bytes)}; +} +``` + +- **Every result is inspected exactly once.** Prefer a type that enforces this: an `llvm::Error` that is destroyed + unchecked aborts a debug build, and `[[nodiscard]]` catches the rest. Propagate the error, handle it, or consume + it with a comment saying why it may be dropped. +- **Add context on the way up**, so the final message says what was being done: the file, the record, the field. Do not + wrap an error without adding information. +- **Messages are lower-case, without a trailing period**, and name the offending value: `entry 'Demo.Main' names no + class`. They are written for the person who has to fix the input. +- **A typed error** (an error class or an error enumeration, such as a class derived from `llvm::ErrorInfo`) when a + caller needs to react to one kind differently, for example to retry. Otherwise an error with a message is enough. +- **Do not use `std::error_code` as the interface** of new code. At the boundary of an API that reports through + `std::error_code`, such as the non-throwing `std::filesystem` overloads, convert it into the project's error + type (`llvm::errorCodeToError` with LLVM). + Always call the non-throwing overload; code built without exceptions cannot catch the other one. + +## 7.3 Invariants + +An invariant is something the program's own logic guarantees. A broken invariant is a bug in the program, not in its +input, and there is no meaningful way to continue. + +- **`assert`** checks an invariant that is cheap to state, in debug builds. It never checks input, never has a side + effect, and its message is a condition a reader understands: `assert(index < blocks_.size() && "block id out of range")`. +- **An always-on check** (a project macro that prints and calls `std::abort`, or `llvm::report_fatal_error`) guards + an invariant whose + violation would corrupt memory or produce wrong output in a release build, such as a verifier disagreeing with + itself. It prints a message and terminates. +- **An unchecked unwrap** (`llvm::cantFail`, or `.value()` behind an assertion) takes the value of an `Expected` whose + success the caller has just established, such as an + operation on two sets that were created with the same size a line above. It is never a shortcut for input + validation. +- **An unreachable marker** (a project macro, `llvm_unreachable`, or C++23's `std::unreachable` behind an assertion) + follows a `switch` that handles every enumerator; it is not a way to silence a missing case. + +The line between the two first kinds is the source of the value: **anything that comes from outside the process** +(a file, the network, the command line, the environment, another component's serialized output) is validated and +reported as a recoverable failure, never asserted. + +## 7.4 Fatal defects in tests and fuzzers + +A fuzz oracle that detects a defect, such as a round trip that changes a value, terminates with a fatal error so that +the fuzzer keeps the input. A benchmark whose fixture is corrupt terminates as well; it must not time a broken +workload. A test that cannot set up its fixture fails with a message, not a crash. + +## 7.5 Destructors and cleanup + +A destructor never fails. Cleanup that can fail, such as flushing a file, is a member function that returns `Error` +and that the owner calls before the object goes away. The destructor then only releases what remains, silently. + +## 7.6 Diagnostics are not errors + +A compiler or a linter that reports problems in its input produces **diagnostics**: data with a severity, a location +and a message, collected and printed by a sink. Producing a diagnostic is normal operation and does not use +`Expected`. `Expected` is for the failure of an operation itself, such as being unable to read the input at all. diff --git a/Guide/FILES-AND-HEADERS.md b/Guide/FILES-AND-HEADERS.md new file mode 100644 index 0000000..579be87 --- /dev/null +++ b/Guide/FILES-AND-HEADERS.md @@ -0,0 +1,109 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 4. Files and headers + +## 4.1 Extensions + +| Extension | Holds | +| --- | --- | +| `.hpp` | a C++ header | +| `.cpp` | a C++ translation unit | +| `.h` | a C11 header for a [C interface](C-INTERFACES.md), and nothing else | +| `.inc` | a fragment that is included more than once on purpose, such as an X-macro table | + +A C++-only header never uses `.h`: the extension tells a reader, and a build tool, which language the file is. + +## 4.2 The layout of a header + +```cpp +// SPDX-FileCopyrightText: 2026 Example <contact@example.com> +// SPDX-License-Identifier: MPL-2.0 +#pragma once + +#include <cstdint> +#include <vector> + +#include <llvm/Support/Error.h> + +#include "Example/Graph/BlockId.hpp" + +namespace Example::Graph +{ + /// ... +} // namespace Example::Graph +``` + +1. The license header, as two SPDX comment lines, when the project uses them. +2. `#pragma once`. Every major compiler supports it, and it cannot collide the way two include guards with the same + macro name can. +3. The includes (see below). +4. One namespace block. `clang-format` adds the closing comment. + +A translation unit has the same shape without `#pragma once`. + +## 4.3 Includes + +- **Include what you use.** A file includes the header of every name it uses directly, even when another include + happens to bring it in. A header that compiles only because of what was included before it is broken. +- **Every header compiles on its own.** A build that compiles each public header in a translation unit of its own + catches a missing include before a user does. +- **Angle brackets for code you do not own, quotes for code you do.** `<vector>`, `<llvm/ADT/StringRef.h>` and the + headers of every dependency use `<>`; the project's own headers use `""`. `clang-format` then puts the two groups + in that order and sorts each. +- **Spell a project include from the root of its include path**: `"Example/Graph/BlockId.hpp"`, never a relative path + such as `"../BlockId.hpp"`. The spelling then names the same file from every directory. +- **Public headers live under a directory named for the project**, such as `Headers/Example/Graph/`, so that the + include spelling starts with the project name and cannot clash with another library's headers. +- **Forward-declare** a project class in a header that only needs its name for a pointer or reference, to keep build + dependencies small. Do not forward-declare names from the standard library or from another project; include their + header instead. +- **No `using namespace`**, in a header or a translation unit, at any scope. A `using` declaration of one name, a type + alias or a namespace alias is fine inside a function or inside the project's own namespace in a `.cpp`: + + ```cpp + namespace + { + namespace Graph = Example::Graph; + } // namespace + ``` + +## 4.4 What goes in a header + +A header declares the interface of a component: types, function declarations, constants, and the inline functions and +templates that must be visible to callers. Everything else goes in the `.cpp`. + +- A function is defined in the header only when it is a template, `constexpr`, or a one-line accessor that the type + definition reads better with. +- Helpers used by one translation unit go in an unnamed namespace in that `.cpp`, giving them internal linkage. Do not use + `static` for that purpose at namespace scope. +- A header defines no non-`inline` variable. A constant in a header is `inline constexpr`. +- A header does not depend on a macro being defined before it is included, except for the configuration macros the + project documents. + +## 4.5 The order inside a class + +Order a class by what a reader of its interface needs first: + +1. `public`, then `protected`, then `private`. +2. Within each: types and aliases, then constants, then factories and constructors, then the destructor, then the special + members, then other member functions, then data members. + +Data members are always last and always `private` in a class (see [Types and classes](TYPES-AND-CLASSES.md)). + +## 4.6 Size + +A file is at most 1500 lines; 750 or fewer is the target. The limit is not a reason to cut a coherent unit at an +arbitrary line. Split by responsibility instead, such as model, verifier, lowering, diagnostics, I/O. A file that grows +past the target is a hint that it does two things. + +A function should fit on a screen, about 60 lines. One that does not usually has steps that deserve names of their own. + +There is no `Utils.hpp`, `Common.hpp` or `Helpers.cpp`. A helper belongs with the code that uses it, or in a component +named for what the helper does. + +## 4.7 Generated and vendored code + +Generated sources are written into the build output, not into the source tree, and are never edited by hand. Vendored +code lives under one directory, such as `third_party/`, keeps its own license, formatting and style, and is excluded +from formatting and linting. A change to vendored code is made upstream, or recorded as a patch with its reason. diff --git a/Guide/FORMATTING.md b/Guide/FORMATTING.md new file mode 100644 index 0000000..80a355c --- /dev/null +++ b/Guide/FORMATTING.md @@ -0,0 +1,219 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 2. Formatting + +Formatting is mechanical, so a tool does it. Every C++ file is formatted by `clang-format` with the profile below, and +CI fails when a file is not. Nobody formats by hand, and nobody argues about a formatting choice in a review: a change +to the profile is a change to this guide. + +## The shape of the code + +```cpp +namespace Example::Geometry +{ + /// Axis-aligned rectangle with a non-negative size. + class Rectangle final + { + public: + /// Create a rectangle, or report why the size is not valid. + /// @param width Width in pixels; must not be negative. + /// @param height Height in pixels; must not be negative. + /// @return The rectangle, or an error naming the invalid side. + [[nodiscard]] static auto + Create(std::int32_t width, std::int32_t height) + -> llvm::Expected<Rectangle>; + + /// Area in square pixels. + [[nodiscard]] auto + Area() const noexcept -> std::int64_t + { + return static_cast<std::int64_t>(width_) * height_; + } + + private: + Rectangle(std::int32_t width, std::int32_t height) + : width_{width} + , height_{height} + { + } + + std::int32_t width_{}; + std::int32_t height_{}; + }; +} // namespace Example::Geometry +``` + +- Four spaces, never tabs. Lines of at most 80 columns. +- Every brace that opens a namespace, class, function or control statement stands on its own line (Allman style). +- The contents of a namespace are indented. +- A function's return type, or `auto` with a trailing return type, stands on its own line above the name. +- When the parameters or arguments do not fit on one line, each gets a line of its own. +- A binary operator that starts a continuation line leads that line. +- Constructor initializers and base classes each start a line with their comma. +- `*` and `&` stick to the name: `const Node *node`, `std::string &text`. + +## The profile + +Copy this file to `.clang-format` at the root of the project. It needs a recent clang-format; pin one exact version in +CI, because two versions can format the same file differently. + +```yaml +--- +Language: Cpp +BasedOnStyle: LLVM +Standard: c++20 + +UseTab: Never +IndentWidth: 4 +ContinuationIndentWidth: 4 +ConstructorInitializerIndentWidth: 4 +AccessModifierOffset: -4 +IndentAccessModifiers: false +ColumnLimit: 80 + +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: true + AfterClass: true + AfterControlStatement: Always + AfterEnum: true + AfterExternBlock: true + AfterFunction: true + AfterNamespace: true + AfterStruct: true + AfterUnion: true + BeforeCatch: true + BeforeElse: true + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: false + SplitEmptyRecord: false + SplitEmptyNamespace: false + +AllowShortBlocksOnASingleLine: Never +AllowShortCaseLabelsOnASingleLine: false +AllowShortEnumsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: Never +AllowShortLambdasOnASingleLine: None +AllowShortLoopsOnASingleLine: false +AllowShortNamespacesOnASingleLine: false +AllowShortRecordOnASingleLine: Never + +BreakAfterReturnType: All + +PackArguments: + BinPack: OnePerLine +PackParameters: + BinPack: OnePerLine +AllowAllArgumentsOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false + +BreakBeforeBinaryOperators: All +BreakBeforeTernaryOperators: true +AlignOperands: Align + +BreakConstructorInitializers: BeforeComma +PackConstructorInitializers: Never +BreakInheritanceList: BeforeComma + +PointerAlignment: Right +DerivePointerAlignment: false +QualifierAlignment: Leave + +SpaceBeforeParens: ControlStatements +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCtorInitializerColon: false +SpaceBeforeInheritanceColon: false +SpaceBeforeCpp11BracedList: false +SpacesInAngles: Never +SpacesInSquareBrackets: false +SpacesInParens: Never +SpaceInEmptyBraces: Never + +Cpp11BracedListStyle: Block + +SpaceAfterTemplateKeyword: false +BreakTemplateDeclarations: Yes + +IndentCaseLabels: true +IndentCaseBlocks: false + +NamespaceIndentation: All +FixNamespaceComments: true +ShortNamespaceLines: 0 +CompactNamespaces: false + +IndentPPDirectives: AfterHash +PPIndentWidth: 4 + +IncludeBlocks: Regroup +SortIncludes: CaseSensitive +IncludeIsMainRegex: '$^' +IncludeCategories: + - Regex: '^<.*>$' + Priority: 1 + SortPriority: 1 + - Regex: '^".*"$' + Priority: 2 + SortPriority: 2 + +MaxEmptyLinesToKeep: 1 +KeepEmptyLines: + AtStartOfBlock: false + +ReflowComments: true +SortUsingDeclarations: Lexicographic + +LineEnding: DeriveLF +InsertNewlineAtEOF: true +... +``` + +### Why these choices + +| Choice | Reason | +| --- | --- | +| 80 columns | Two files side by side, or a diff, fit on one screen without wrapping. | +| Four spaces | Nesting stays visible at a glance; deep nesting looks deep, which it should. | +| Braces on their own line | The opening and the closing brace of a block line up, and a block is never mistaken for a continuation. | +| Return type on its own line | Function names start at the same column, so a file can be scanned, and grepped with `^Name(`, for its functions. | +| One argument per line when they do not fit | A diff that adds an argument changes one line, and arguments are never hidden at the end of a long line. | +| No short forms on one line | Every body has the same shape, and a breakpoint can be set on any statement. | +| Leading binary operators | The operator that joins a line to the one above is the first thing a reader sees. | +| `IncludeIsMainRegex: '$^'` | No header is treated as the "main" header and moved to the top; the order is purely system, then project. | +| `DeriveLF` | A file keeps the line endings it has, so formatting never rewrites a whole file to change them. | + +## What the tool leaves to you + +`clang-format` lays out tokens; it does not decide what the code looks like at a larger scale. + +- **Always use braces** for the body of `if`, `else`, `for`, `while` and `do`, even for one statement. A line added + later then cannot fall outside the body. + + ```cpp + if (items.empty()) + { + return Error::Empty; + } + ``` + +- **One declaration per line.** `int width, height;` declares two things on a line that reads as one. +- **Blank lines separate steps.** A function that does three things in sequence shows three paragraphs. Do not open or + close a block with a blank line. +- **Keep nesting shallow.** Return early for the error and edge cases, then write the main path at the outer level. More + than three levels of nesting is a sign that a function should be split. +- **A long expression gets a name.** When a condition or a computation wraps over several lines, give its parts named + variables instead of relying on the line breaks to explain it. +- **Do not align by hand.** Extra spaces to line up `=` or comments are undone by the next rename and make a diff wider + than the change. +- **`// clang-format off`** is allowed only around a table whose layout carries meaning, such as a lookup table or a + matrix, and is always closed again with `// clang-format on` within the same screen of code. + +## Files that are not formatted + +Vendored and generated code keeps the formatting of its origin. List those paths in `.clang-format-ignore`, so the +formatting check skips them, instead of reformatting a dependency. diff --git a/Guide/LANGUAGE.md b/Guide/LANGUAGE.md new file mode 100644 index 0000000..7163472 --- /dev/null +++ b/Guide/LANGUAGE.md @@ -0,0 +1,170 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 5. Language + +The guide targets C++20 exactly: `-std=c++20`, no compiler extensions (`-Wpedantic` is on). A C++23 feature is used only +through a library that provides it for C++20, such as `llvm::Expected` in place of `std::expected`. + +## 5.1 Functions + +- **Trailing return types for functions that return a value**: `auto Size() const -> std::size_t`. Return types then + line up, and a long return type does not push the name to the right. A function that returns nothing is declared + `void`, which reads better than `auto … -> void`. +- **`[[nodiscard]]` on every function whose result matters**, and always on one that returns `Expected`, `Error`, an + owning pointer or a status. Ignoring such a result is then a compile error under `-Werror`. +- **Parameters** take an input by value when the function keeps a copy or the type is cheap to copy (scalars, + `std::string_view`, `std::span`, small trivially copyable structs); by `const &` otherwise; by `&` only for an output + or an in-out parameter, and prefer returning a value over an output parameter. +- **Default arguments** are allowed on non-virtual functions and constructors. A virtual function does not take them, + because the default would depend on the static type of the call. +- **Overloads** do the same thing for different types. When two functions do different things, give them different + names. +- **No function-style "flag" parameters** that select behavior: `Emit(module, true)` is unreadable at the call. Use an + `enum class` or two functions. +- **`noexcept`** goes on move constructors, move assignment, `swap`, destructors (implicitly) and functions that by + contract cannot fail. In exception-free code it documents that a function has no failure path; do not add it to + everything. + +## 5.2 `auto` + +Use `auto` when the type is obvious from the right side, or long and uninformative: + +```cpp +// The type is on the right. +auto parser = Parser::Create(source); +// The iterator type adds nothing. +auto iterator = blocks.find(id); +// A structured binding. +const auto &[name, value] = *entry; +``` + +Write the type when it carries information the reader needs, especially for numbers: + +```cpp +// The width and the signedness matter. +std::uint32_t offset = header.Offset(); +std::size_t count = Count(items); +``` + +Never `auto` for a variable that is meant to be a different type from the initializer, such as a proxy object +(`std::vector<bool>::reference`) or an expression template. + +## 5.3 Initialization + +- **Initialize every variable where it is declared.** An uninitialized variable is a bug waiting for a path that reads + it. Declare a variable at the point where it gets its value, in the smallest scope. +- **Brace-initialize data members** with a default: `std::uint32_t count_{};`, `bool available{};`. Every object then + starts in a defined state, and `-Wmissing-field-initializers` stays quiet for aggregate initialization that omits + trailing fields. +- **Braces for initialization, parentheses for a constructor that braces would hide.** `std::vector<int> values(3, 0)` + makes three zeros; `std::vector<int> values{3, 0}` makes the list `{3, 0}`. Use parentheses only where braces would + select an `std::initializer_list` constructor you do not want. +- **Designated initializers** name the fields of an aggregate: `Edge{.from = a, .to = b}`. Use them whenever an aggregate + has more than two fields or two fields of the same type. +- **No narrowing.** Brace initialization refuses it; with `=` and parentheses, write the conversion out. + +## 5.4 `const` and `constexpr` + +- **`const` by default.** A local that does not change is `const`; a member function that does not change the object is + `const`; a pointer or reference parameter that is only read points to `const`. +- **`constexpr` for every value known at compile time**, and for functions that can be evaluated at compile time without + contortion. `consteval` when a function must only run at compile time. +- **`inline constexpr`** for a constant in a header. `constexpr` on a static data member already implies `inline`. +- Do not `const`-qualify a by-value parameter in a declaration; it means nothing to the caller. It may be `const` in the + definition. +- **No `const_cast`** to write through a pointer that refers to a `const` object. Removing `const` is allowed only to call + a C API that takes a non-`const` pointer it is documented not to modify, with a comment saying so. + +## 5.5 Casts and conversions + +- **No C-style casts and no functional casts** for anything but constructing a value of class type. Use + `static_cast` for a value conversion, `std::bit_cast` to reinterpret the bits of a trivially copyable value, and + `reinterpret_cast` only at a byte or ABI boundary, with a comment saying why the cast is valid. +- **No implicit conversion between integer widths or signedness.** `-Wimplicit-int-conversion` and the clang-tidy + profile reject them; write the `static_cast` and make sure it cannot lose a value, or check that it cannot. +- **No implicit conversion to `bool`.** Write `pointer != nullptr`, `count != 0U`, `!text.empty()`. +- **`explicit`** on every constructor that can be called with one argument and on every conversion operator, unless the + implicit conversion is the point of the type, as it is for a view. + +## 5.6 Integers and arithmetic + +- **Sizes and indices into memory are `std::size_t`.** Counts that come from or go to a file, a protocol or an ABI use + the fixed-width types of `<cstdint>`, such as `std::uint32_t`. Do not use `long`, `unsigned long` or `short`, whose + widths differ between platforms. +- **Unsigned for bits and sizes, signed for arithmetic that can go below zero.** Do not use unsigned to say "never + negative" for a value that is computed by subtraction. +- **Integer literals carry their type**: `0U`, `1ULL << 40U`, `std::size_t{0}`. +- **Overflow of an untrusted value is checked**, before the operation, or with `__builtin_add_overflow` and its + siblings, or with a checked-arithmetic helper. Signed overflow is undefined behavior; unsigned wrap-around is defined + but almost never what a size computation means. +- **Floating point** compares with a tolerance that the code names, never with `==` on computed values. + +## 5.7 Strings and text + +- Text is UTF-8 in `std::string`. Take a read-only string parameter as `std::string_view` (or `llvm::StringRef` in code + built on LLVM). Do not use `std::wstring`, `wchar_t`, or `std::u8string` in an interface. +- Convert to a platform encoding only at the platform boundary, such as a Windows wide-character API. +- Format with `std::format`-style or `llvm::formatv`-style functions, or by streaming into a string builder; never with + `sprintf` into a fixed buffer. +- A view parameter must not be stored. A member that keeps text owns a `std::string`. + +## 5.8 Enumerations + +Every enumeration is an `enum class`. Give it an explicit underlying type when its values are stored, sent or matched +against an ABI: + +```cpp +enum class Opcode : std::uint8_t +{ + kLoad = 1, + kStore = 2, +}; +``` + +A `switch` over an enumeration lists every enumerator and has no `default`, so that `-Wswitch` reports a case that a new +enumerator needs. When a value may come from outside the program, convert it to the enumeration with a function that +validates it. + +## 5.9 Templates and concepts + +- **Constrain every template** with a concept or a `requires` clause instead of SFINAE: `template<std::integral Id>`. + The error then names the requirement, not a substitution failure deep inside. +- **Name a concept for a requirement used more than once.** Concepts are `PascalCase` nouns or adjectives: + `Hashable`, `ByteRange`. +- **Keep templates thin.** Move the part that does not depend on the template parameters into a non-template function, + to keep compile times and code size down. +- **No template metaprogramming where `constexpr` code would do.** An `if constexpr` branch or a `consteval` function is + easier to read than a recursive specialization. + +## 5.10 Lambdas + +- **Capture explicitly.** `[&]` is allowed for a lambda that does not outlive the statement it is written in, such as a + callback passed to an algorithm. A lambda that is stored, returned or run later names each capture, and captures by + value whatever it must keep. +- Never capture `this` implicitly. Write `[this]` so the lifetime dependency is visible. +- A lambda longer than a few lines, or used twice, becomes a named function. + +## 5.11 Control flow + +- **Return early** for errors and edge cases; keep the main path unindented. +- **No `goto`.** +- **Range-based `for`** whenever the index is not needed. When it is, iterate with `std::size_t`. +- **`[[fallthrough]]`** marks every intended fall-through in a `switch`; `-Wimplicit-fallthrough` rejects the rest. +- **Ranges and algorithms** where they state the intent better than a loop: `std::ranges::sort(items)`, + `std::ranges::any_of(...)`. A plain loop is better than a pipeline of five views that needs a comment to explain. +- **`[[likely]]` and `[[unlikely]]`** only where a measurement showed a difference. + +## 5.12 Features not used + +| Feature | Instead | +| --- | --- | +| C++20 modules | headers; build-tool support is not yet uniform across the supported compilers | +| Coroutines | explicit state machines or callbacks, until a project adopts a coroutine library deliberately | +| RTTI: `dynamic_cast`, `typeid` | `std::variant` and `std::visit`, a kind enumeration, or LLVM-style `isa`/`cast`/`dyn_cast` | +| Exceptions | see [Errors](ERRORS.md) | +| `std::bind` | a lambda | +| Variable-length arrays | `std::array`, `std::vector`, or a small-vector type | +| Non-`const` global and static variables | state passed explicitly, owned by an object with a clear lifetime | +| `alloca`, `setjmp`/`longjmp` | ordinary allocation and returns | +| User-defined literals | named functions or constructors, except the standard ones such as `std::chrono` suffixes | diff --git a/Guide/NAMING.md b/Guide/NAMING.md new file mode 100644 index 0000000..d575ec8 --- /dev/null +++ b/Guide/NAMING.md @@ -0,0 +1,94 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 3. Naming + +A name is the shortest documentation a thing gets, and the one a reader sees most. The casing tells the reader what kind +of thing a name is before they look it up; the words tell them what it is for. + +## 3.1 Casing + +| Kind | Style | Example | +| --- | --- | --- | +| Namespace | `PascalCase` | `Progmasoft::Tala::Analysis` | +| Class, struct, union, enum, concept, type alias | `PascalCase` | `ControlFlowGraph`, `using BlockId = std::uint32_t;` | +| Template type parameter | `PascalCase` | `template<typename Value>` | +| Function, member function, static member function | `PascalCase` | `AnalyzeLiveness`, `graph.BlockCount()`, `Rectangle::Create` | +| Local variable, parameter | `camelCase` | `blockCount`, `const Node &node` | +| Public data member of a struct | `camelCase` | `point.x`, `edge.successor` | +| Private and protected data member | `camelCase_` | `bits_`, `blocks_` | +| Constant: `constexpr`, `const` at namespace scope, static constant member | `kPascalCase` | `kMaximumDepth` | +| Enumerator | `kPascalCase` | `Color::kRed` | +| Template value parameter | `kPascalCase` | `template<std::size_t kSize>` | +| Macro | `UPPER_SNAKE_CASE` with a project prefix | `EXAMPLE_ASSERT` | +| C function and type in a C interface | `snake_case` with a project prefix | `example_parser_create` | + +The trailing underscore marks state that an object keeps for itself. A reader who sees `blocks_` inside a member +function knows it is the object's own field and not a local or a parameter, without any other prefix. + +Public data members of a struct have no underscore: a struct is a plain bundle of values that callers read and write +directly (see [Types and classes](TYPES-AND-CLASSES.md#61-struct-or-class)). + +## 3.2 Acronyms and abbreviations + +An acronym is one word and is cased as one: `HttpClient`, `ParseUtf8`, `xmlReader`, `kMaxUrlLength`. Two capital +letters in a row are allowed only for a two-letter acronym that would be unreadable otherwise: `IOError` is wrong, +`IoError` is right, but `LLVM` stays `LLVM` in a namespace that names the library (`Backend::LLVM`), because that is +the product's own spelling. + +Spell words out. `count`, `index`, `message`, `position` rather than `cnt`, `idx`, `msg`, `pos`. Abbreviations that are +more common than the word itself are fine: `id`, `url`, `utf8`, `min`, `max`, `ptr` only when it names a pointer whose +pointee is the subject. + +## 3.3 Choosing the words + +- **Types are nouns**: `Lexer`, `TokenStream`, `DiagnosticSink`. +- **Functions are verbs, or questions**: `Parse`, `EmitObject`, `IsEmpty`, `HasErrors`, `CanInline`. +- **A function that returns a property without work is named for the property**: `Size()`, `Name()`, `Entry()`. No + `Get` prefix; reserve `Get` for a lookup that can fail, such as `GetSymbol(id) -> Expected<Symbol>`. +- **A setter says what it changes**: `SetName`, `Reset`, `Assign`. +- **Booleans read as statements**: `isVisible`, `hasBody`, `shouldRetry`, `available`. Avoid negatives that cause + double negation: `isEnabled`, not `isNotDisabled`. +- **A factory that validates is `Create`**; one that reads from a source is `From…` or `Parse…`; one that converts is + `To…`. +- **Units go in the name when the type does not carry them**: `timeoutMilliseconds`, `sizeBytes`, `widthPixels`. + Prefer a type that carries the unit, such as `std::chrono::milliseconds`. +- **The scope decides the length.** A loop index over three lines may be `index`; a member that lives for the whole + program needs a name that explains itself out of context. +- **Do not repeat the context.** Inside `class Parser`, the member is `Parse`, not `ParserParse`; in namespace + `Diagnostics`, the type is `Sink`, not `DiagnosticsSink`, unless it is also used outside that namespace without a + qualifier. + +## 3.4 Namespaces + +A project's code lives under one root namespace named for the organization or the project, then one level per product +and component: `Progmasoft::Tala::Backend::LLVM`. Use C++17 nested namespace definitions: +`namespace Progmasoft::Tala::Analysis`. + +Each component owns one namespace and every name in it. Two components do not add declarations to the same namespace. + +An implementation detail that must be visible in a header, such as a helper of a template, lives in a nested `Detail` +namespace, which callers must not use. + +A project may keep a short lowercase namespace for a stable data model that is used heavily and qualified often, such +as an intermediate representation (`tala::core`, `tala::xpp`). This is a deliberate, documented exception, not a second +convention. + +## 3.5 Files + +A file is named after the main thing it declares, in the casing of that thing: `ControlFlowGraph.hpp` and +`ControlFlowGraph.cpp`. A file with several small related declarations is named after their common subject: +`Diagnostics.hpp`. A directory names a component: `Analysis/`, `Backend/`. + +Test files add `Tests`: `ControlFlowGraphTests.cpp`. A benchmark adds `Benchmark`, a fuzz target `Fuzz`. + +## 3.6 What not to name things + +- Names that differ only in case: `Value` and `value` in the same scope. +- Names starting with an underscore followed by a capital letter, or containing a double underscore anywhere: the + standard reserves them for the implementation. +- Hungarian notation and type prefixes: `pNode`, `strName`, `iCount`, `m_size`. The type is in the declaration, and + `clang-tidy` and the editor show it. +- `Manager`, `Helper`, `Util`, `Data`, `Info` and `Handler` as the whole meaning of a name. Say what the thing manages + or helps with. +- A name that lies. When the behavior of a function changes, its name changes with it. diff --git a/Guide/OWNERSHIP-AND-MEMORY.md b/Guide/OWNERSHIP-AND-MEMORY.md new file mode 100644 index 0000000..94d32da --- /dev/null +++ b/Guide/OWNERSHIP-AND-MEMORY.md @@ -0,0 +1,88 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 8. Ownership and memory + +Every object has exactly one owner, and the type says who it is. A reader should be able to tell from a declaration +alone whether a function keeps, borrows or gives away what it is handed. + +## 8.1 What owns, what borrows + +| Type | Meaning | +| --- | --- | +| `T` (a value) | owns | +| `std::unique_ptr<T>` | owns a heap object; ownership moves, never copies | +| `std::vector<T>`, `std::string`, other containers | own their elements | +| `T &`, `const T &` | borrows, never null, for the duration of the call | +| `T *`, `const T *` | borrows, may be null; never owns | +| `std::span<T>`, `std::string_view`, `llvm::ArrayRef<T>`, `llvm::StringRef` | borrows a range for the duration of the call | +| `std::shared_ptr<T>` | shared ownership; needs a reason, see below | + +- **No raw `new` or `delete`.** Create a heap object with `std::make_unique`; a container or an RAII type releases it. +- **No owning raw pointers**, not even briefly. A C API that returns an owned pointer is wrapped immediately in a + `std::unique_ptr` with a deleter (see [C interfaces](C-INTERFACES.md)). +- **`std::shared_ptr` only for genuinely shared lifetime**, where no single owner can be named, such as a cache entry + used by several threads. Shared ownership hides who keeps an object alive and makes destruction order hard to see. + Never use it to avoid deciding who the owner is. +- **Pass ownership by value**: a function that takes ownership of a `std::unique_ptr` takes it by value, and the caller + writes `std::move`. A function that only uses the object takes a reference. + +## 8.2 Views and their lifetimes + +A view does not own what it points to. It is valid only while its source lives and is not modified. + +- **A view is a parameter or a local, not a member**, unless the class documents that it is itself a view and states + what must outlive it. +- **Never return a view into a temporary or into a local**, and never keep one past a call that can reallocate the + source (`push_back`, `insert`, `resize`). +- **`llvm::Twine` is consumed in the expression that creates it.** Never store a `Twine`, never name one with `auto`. +- **A view of a `std::string` that may be modified** is taken again after the modification. + +```cpp +// Avoid: the view outlives the string it refers to. +auto +Name(const Symbol &symbol) -> std::string_view +{ + return symbol.Qualified() + ".type"; // a temporary std::string +} +``` + +## 8.3 RAII for every resource + +A file descriptor, a lock, a temporary directory, a C library handle and a registered callback are each owned by an +object whose destructor releases them. Cleanup never depends on reaching the end of a function. When a resource has no +dedicated type, use a scope guard (`llvm::make_scope_exit` or an equivalent) right after acquiring it. + +## 8.4 Containers + +- **`std::vector` is the default sequence.** Reserve when the final size is known. Do not use `std::list`; a vector of + indices is almost always faster and simpler. +- **Lookups**: a hash map when order does not matter, a sorted vector or `std::map` when it does. In code built on LLVM, + `llvm::DenseMap`, `llvm::StringMap` and `llvm::SmallVector` fit compiler-style workloads (small, dense, short-lived). + Keep them out of public, library-independent interfaces, which use standard types. +- **Never iterate a hash map to produce output or to make a decision that depends on order.** The order differs between + runs, libraries and platforms. Sort the keys first, or use an insertion-ordered map such as `llvm::MapVector`. +- **Know the sentinels of a container.** `llvm::DenseMap` reserves two key values for empty and deleted buckets; a map + whose keys come from input must use a key type that cannot collide with them. +- **Do not hold an iterator, reference or pointer to an element across an operation that may invalidate it.** + +## 8.5 Allocation + +- **Allocate less.** Prefer values and inline storage (`std::array`, a small-vector type) for small, bounded data. +- **Sizes from input are checked before allocating.** A length field in a file that claims four gigabytes is rejected, + not passed to `resize`. +- **No custom allocators** without a measurement that shows the default is the bottleneck. +- **Out-of-memory is not a recoverable failure.** Do not try to report it through `Expected`; let the allocation + terminate the process. + +## 8.6 Undefined behavior + +The code must be free of undefined behavior, not merely free of crashes. In particular: + +- no reads of uninitialized memory, no out-of-bounds access, no use after free or after move except to assign or destroy; +- no signed overflow, no shift by a negative amount or by the width of the type or more; +- no type punning through a `union` or a `reinterpret_cast`ed pointer; use `std::bit_cast` or `std::memcpy`; +- no data race (see [Concurrency](CONCURRENCY.md)). + +AddressSanitizer, UndefinedBehaviorSanitizer and ThreadSanitizer run in CI to find what review misses (see +[Testing](TESTING.md#123-sanitizers)). Passing them is necessary, not sufficient: they only see the paths the tests run. diff --git a/Guide/PRINCIPLES.md b/Guide/PRINCIPLES.md new file mode 100644 index 0000000..777de88 --- /dev/null +++ b/Guide/PRINCIPLES.md @@ -0,0 +1,59 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 1. Principles + +Every rule in this guide serves one of the principles below. When the guide says nothing about a case, decide by them, +in this order. + +## 1.1 Correct before fast, and both before clever + +Code that is wrong quickly is still wrong. Write the obvious correct version first, measure, and optimize where a +measurement says so. When an optimization makes code harder to read, the comment next to it says what it gains and how +that was measured. + +A clever construct that saves three lines but costs every later reader a minute is a bad trade. Prefer the form that +a reader new to the file understands on the first pass. + +## 1.2 The reader comes first + +Code is read far more often than it is written. Names say what a thing is for; types say who owns what; a function does +one thing that its name states. A reviewer should be able to judge a change from the diff and the code around it, +without reconstructing intent from history. + +## 1.3 Make invalid states unrepresentable + +Prefer types that cannot hold a wrong value over checks that reject one. An `enum class` instead of an `int` code, a +strong identifier type instead of a bare `std::uint32_t`, `std::optional<T>` instead of a sentinel, a factory that +validates instead of a constructor that cannot. Each check that a type makes unnecessary is a check nobody can forget. + +## 1.4 Failure is part of the interface + +A function that can fail says so in its signature: it returns `Expected<T>` or `Error`, and the caller must look at the +result. A precondition that a caller can violate is either checked and reported, or documented and asserted. Nothing +fails silently, and nothing fails by surprise. + +## 1.5 Determinism + +The same input gives the same output on every machine, every run. Output that depends on hash order, pointer values, +thread timing, the locale or the time of day is a defect unless it is the point of the program. Sort before you print; +iterate in an order you chose. + +## 1.6 Tools enforce what tools can + +Formatting, naming of members, include order and a long list of bug patterns are checked by `clang-format`, +`clang-tidy` and the compiler, with warnings as errors. A review then spends its attention on what tools cannot judge: +design, names, ownership, and whether the change does what it says. + +## 1.7 Consistency within a project beats consistency with the guide + +A project that adopts this guide over existing code converges gradually. A file follows the guide where it is touched; +a mechanical sweep is its own change, never mixed into a behavior change. Where a project deliberately deviates, it +writes the deviation down once (see [Adopting the guide](../ADOPTING.md)), and then the project's rule wins in that +project. + +## 1.8 Small, explicit dependencies + +Every dependency is a cost: build time, security surface, and a second set of conventions. Prefer the standard library, +then one well-chosen library per problem. A build target names the libraries it uses directly instead of relying on +what another target happens to bring in. diff --git a/Guide/TESTING.md b/Guide/TESTING.md new file mode 100644 index 0000000..f35013f --- /dev/null +++ b/Guide/TESTING.md @@ -0,0 +1,94 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 12. Testing + +A change that alters behavior comes with a test that fails without it. A bug fix comes with the test that reproduces the +bug. Tests are code: they follow this guide, they are reviewed, and a flaky test is a bug. + +## 12.1 Unit tests + +- **Tests live next to the component they test**, in a `Tests/` directory of that component, not in one tree for the + whole repository. The test then moves, and is found, with its code. +- **One test file per unit under test**: `ControlFlowGraphTests.cpp` for `ControlFlowGraph.hpp`. +- **A test name is a sentence that states the behavior**: `"DenseIdMap keeps zero and the maximum id as distinct keys"`. + When it fails, the name alone says what broke. +- **Arrange, act, assert**, separated by blank lines. One behavior per test; several assertions about that one behavior + are fine. +- **Test the contract, not the implementation**: inputs and observable results, boundary values (zero, one, the maximum, + one past it), the empty case, and every documented failure. +- **No shared mutable state between tests**, and no dependence on their order. A test creates what it needs, in a + temporary directory when it touches files. +- **Deterministic**: no wall clock, no unseeded random numbers, no network. Property-based tests use a fixed or a + recorded seed, so a failure can be reproduced. +- **Fast**: a unit test runs in milliseconds. A slow scenario is a separate, labeled test target. + +The guide does not prescribe a test framework. Catch2, [Catch3](https://github.com/Progmasoft/catch3), GoogleTest, +doctest and others all fit; choose one per project and use it everywhere in that project. The example below uses the +Catch2-style API: + +```cpp +TEST_CASE("BitSet union keeps the bits of both operands") +{ + auto left = llvm::cantFail(BitSet::Create(8U)); + auto right = llvm::cantFail(BitSet::Create(8U)); + left.Set(1U); + right.Set(6U); + + // errorToBool consumes the error, so a failure is reported, not leaked. + REQUIRE_FALSE(llvm::errorToBool(left.UnionWith(right))); + + CHECK(left.Test(1U)); + CHECK(left.Test(6U)); + CHECK(left.Count() == 2U); +} +``` + +Whatever the framework, use its two kinds of assertion for what they are for: one that stops a test whose further checks +would make no sense (`REQUIRE`, `ASSERT_*`), and one that reports and continues (`CHECK`, `EXPECT_*`), so one run shows +every failed expectation. + +## 12.2 Fuzzing + +Every parser of untrusted input, every decoder of a binary format and every round trip (encode, then decode) has a fuzz +target. + +- **One target per entry point**, built with AddressSanitizer and UndefinedBehaviorSanitizer. Write it against the + `LLVMFuzzerTestOneInput` entry point, which libFuzzer, AFL++ and honggfuzz all accept, so the engine can be chosen + or changed without touching the target. +- **A seed corpus** of small valid inputs checked into the repository, and a dictionary of the format's keywords and + magic numbers when it has them. +- **Bounded runs in CI** on every change, and longer campaigns on a schedule. A crash found by a fuzzer becomes a + regression test with the minimized input. +- **An oracle beyond "it did not crash"**: a round trip compares the result with the input; a verifier and a + transformation are checked against each other. + +## 12.3 Sanitizers + +CI builds and runs the tests under: + +| Sanitizer | Finds | +| --- | --- | +| AddressSanitizer | out-of-bounds access, use after free, double free, leaks (with LeakSanitizer) | +| UndefinedBehaviorSanitizer | signed overflow, invalid shifts, misaligned access, invalid enum and bool values, null dereference | +| ThreadSanitizer | data races and lock-order inversions, for every test that runs threads | + +UBSan runs with `-fno-sanitize-recover=all`, so the first finding fails the test instead of printing and continuing. +MemorySanitizer may be added where all dependencies can be built with it. + +## 12.4 Benchmarks + +Performance claims are measured. A change that is made for speed comes with a benchmark, and its pull request shows the +numbers before and after. + +- **One benchmark binary per component**, next to its tests, written with the project's benchmark library (Google + Benchmark, nanobench, the benchmarking support of the test framework, or another). +- **Benchmark realistic sizes**, and keep the setup outside the timed region. +- **Compare like with like**: the same machine, an optimized build, several repetitions, and the variance reported along + with the mean. +- A benchmark whose fixture is invalid fails; it must not time a broken workload. + +## 12.5 Coverage + +Coverage is measured in CI and reported per component. It shows what is not tested; it is not a goal in itself, and a +line that is executed is not thereby tested. Review the uncovered branches of a change rather than chasing a percentage. diff --git a/Guide/TOOLING.md b/Guide/TOOLING.md new file mode 100644 index 0000000..1a2ceaa --- /dev/null +++ b/Guide/TOOLING.md @@ -0,0 +1,161 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 13. Tooling + +The guide relies on tools for everything that can be checked mechanically. A project that adopts it turns them all on, +with warnings as errors, in CI and in the local build alike. + +## 13.1 Compiler + +The warning set below is given for Clang, and for `clang-cl` on Windows; `clang-tidy` and the thread-safety analysis +need Clang in any case. A project that also builds with GCC or MSVC enables their equivalent warnings, with warnings +as errors, in a CI job of its own. + +### Flags + +```text +-std=c++20 +-fno-exceptions +-Wall -Wextra -Wpedantic -Werror +-Wshadow +-Wformat=2 +-Wcast-align -Wcast-qual +-Wundef +-Wnull-dereference +-Wimplicit-fallthrough +-Wnon-virtual-dtor -Woverloaded-virtual +-Wextra-semi +-Wmissing-field-initializers +-Wdouble-promotion +-Wimplicit-int-conversion -Wimplicit-float-conversion +-Wdeprecated +-Wunreachable-code-aggressive +-Wvla +-Wthread-safety +-Wcomma +``` + +With `clang-cl`, each flag is passed as `/clang:<flag>`, and the language standard as `/std:c++20`. + +These flags apply to first-party code only. Third-party code is compiled with its own options; its headers are included +as system headers (`-isystem`, or the build tool's equivalent), so their warnings do not fail the build. + +### Optimized and debug builds + +Debug builds keep assertions on and use `-O0` or `-Og`. Release builds use `-O2` or `-O3` with `NDEBUG`. CI builds both, +so that code that only compiles with assertions, or only without, is caught. + +## 13.2 The clang-tidy profile + +Copy this file to `.clang-tidy` at the root of the project and adjust the two path filters at the end. Every enabled +check is an error. + +```yaml +--- +Checks: > + -*, + clang-analyzer-*, + bugprone-*, + concurrency-*, + performance-*, + portability-*, + modernize-loop-convert, + modernize-make-unique, + modernize-redundant-void-arg, + modernize-type-traits, + modernize-use-equals-delete, + modernize-use-nullptr, + modernize-use-override, + modernize-use-using, + misc-throw-by-value-catch-by-reference, + readability-duplicate-include, + readability-else-after-return, + readability-implicit-bool-conversion, + readability-inconsistent-declaration-parameter-name, + readability-make-member-function-const, + readability-misleading-indentation, + readability-redundant-access-specifiers, + readability-redundant-casting, + readability-redundant-control-flow, + readability-redundant-declaration, + readability-redundant-function-ptr-dereference, + readability-redundant-inline-specifier, + readability-redundant-smartptr-get, + readability-redundant-string-cstr, + readability-redundant-string-init, + readability-redundant-typename, + readability-simplify-boolean-expr, + readability-static-accessed-through-instance, + readability-uniqueptr-delete-release, + -bugprone-easily-swappable-parameters, + -bugprone-exception-escape, + -portability-avoid-pragma-once, + -modernize-use-auto, + -modernize-use-emplace, + -modernize-use-trailing-return-type, + -readability-braces-around-statements, + -readability-function-size, + -readability-magic-numbers, + -readability-qualified-auto, + -readability-redundant-member-init + +WarningsAsErrors: '*' +HeaderFileExtensions: + - h + - hpp +ImplementationFileExtensions: + - c + - cpp +# First-party headers only; adjust to the project's source directories. +HeaderFilterRegex: '(^|.*/)(Source|Headers|Tests)/.*' +ExcludeHeaderFilterRegex: '(^|.*/)(build|third_party|external)/.*' +SystemHeaders: false +FormatStyle: file + +CheckOptions: + readability-implicit-bool-conversion.AllowPointerConditions: false + readability-implicit-bool-conversion.AllowIntegerConditions: false + modernize-use-using.IgnoreExternC: true + modernize-use-using.IgnoreMacros: true + modernize-loop-convert.MinConfidence: reasonable +... +``` + +### Why some checks are off + +| Check | Reason | +| --- | --- | +| `bugprone-easily-swappable-parameters` | flags most functions with two parameters of one type; [strong types](TYPES-AND-CLASSES.md#67-strong-types) address the real risk | +| `bugprone-exception-escape` | meaningless when exceptions are disabled | +| `portability-avoid-pragma-once` | the guide uses `#pragma once` on purpose | +| `modernize-use-auto` | the guide writes types that carry information ([Language](LANGUAGE.md#52-auto)) | +| `modernize-use-emplace` | `push_back` of a constructed value is clearer and equally fast after a move | +| `modernize-use-trailing-return-type` | the guide uses trailing return types, but not for `void` functions, which the check would rewrite | +| `readability-braces-around-statements` | braces are required by the guide; the check's fix-its fight `clang-format` | +| `readability-function-size`, `readability-magic-numbers` | judged in review; the fixed thresholds produce more noise than findings | +| `readability-qualified-auto` | conflicts with writing `auto` for pointers returned by APIs whose type is obvious | +| `readability-redundant-member-init` | aggregate members keep an explicit `{}` so aggregate initialization that omits trailing fields stays clean under `-Wmissing-field-initializers` | + +### Naming + +Naming is checked in review, not by `readability-identifier-naming`. The check can enforce casing, but it cannot tell +a constant that deserves `kPascalCase` from an immutable local, and its exceptions for third-party callbacks grow into a +second configuration. A project may enable it once its code is consistent. + +## 13.3 Other checks + +| Tool | Checks | +| --- | --- | +| `clang-format --dry-run --Werror` | every file is formatted by the profile | +| Doxygen, warnings as errors | every public declaration is documented | +| A header self-containment build | every public header compiles on its own | +| The C interface test | each C header compiles as C11 and is called from C | +| Sanitizer and fuzzer jobs | see [Testing](TESTING.md) | +| The Clang Static Analyzer | the `clang-analyzer-*` checks over every translation unit | + +## 13.4 Versions + +Pin the exact versions of Clang, `clang-format` and `clang-tidy` that CI uses, and use the same versions locally. A +different version can format a file differently or report a check the CI version does not have. A version upgrade is +its own change: it updates the pin, reformats or fixes what the new version reports, and nothing else. diff --git a/Guide/TYPES-AND-CLASSES.md b/Guide/TYPES-AND-CLASSES.md new file mode 100644 index 0000000..d1140a7 --- /dev/null +++ b/Guide/TYPES-AND-CLASSES.md @@ -0,0 +1,137 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# 6. Types and classes + +## 6.1 Struct or class + +A **struct** is a bundle of values with no invariant: any combination of field values is valid. Its data members are +public, `camelCase`, and brace-initialized; it may have a defaulted comparison and small helpers that read its fields. + +```cpp +/// One edge of a control-flow graph. +struct Edge final +{ + /// Block the edge leaves. + BlockId from{}; + /// Block the edge enters. + BlockId to{}; + + [[nodiscard]] auto + operator==(const Edge &) const -> bool = default; +}; +``` + +A **class** keeps an invariant: some combinations of its state are invalid, and only its member functions may change it. +Its data members are `private` and end in `_`. A class has no `protected` data. + +If a struct gains an invariant, it becomes a class. Do not put an invariant into a struct with a comment asking callers +to respect it. + +## 6.2 `final` by default + +Every class and struct is `final` unless it is designed as a base class. Designing for inheritance is a decision with +consequences (a virtual destructor, a stable protected interface, documentation of what an override may do), and +`final` makes the default decision visible. + +## 6.3 Construction + +- **A constructor establishes the invariant or does not exist.** When construction can fail, the constructor is private + and a static `Create` returns `Expected<Type>`: + + ```cpp + [[nodiscard]] static auto + Create(std::size_t bitCount) -> llvm::Expected<BitSet>; + ``` + + A public constructor may still take values whose validity the caller guarantees by contract; it documents the + precondition and asserts it. + +- **`explicit`** on every single-argument constructor (see [Language](LANGUAGE.md#55-casts-and-conversions)). +- **Initialize members in the declaration** where a default exists, and in the constructor's initializer list otherwise, + in declaration order. Do not assign in the constructor body what the initializer list can set. +- **No work that can fail, and no virtual calls, in a constructor or a destructor.** +- **No two-phase initialization** (`Init()` after construction): an object that exists is ready to use. + +## 6.4 Special members: the rule of zero + +Prefer members that manage themselves (values, `std::vector`, `std::unique_ptr`, an RAII handle), so that a class +declares none of the copy and move operations or the destructor, and the defaults are right. + +When a class must manage a resource by hand, it declares all five: destructor, copy constructor, copy assignment, move +constructor and move assignment, each either implemented, `= default` or `= delete`. Move operations are `noexcept`. + +```cpp +class FileHandle final +{ +public: + explicit FileHandle(int descriptor) noexcept; + ~FileHandle(); + + FileHandle(const FileHandle &) = delete; + auto + operator=(const FileHandle &) -> FileHandle & = delete; + + FileHandle(FileHandle &&other) noexcept; + auto + operator=(FileHandle &&other) noexcept -> FileHandle &; + +private: + int descriptor_{-1}; +}; +``` + +A type that must not be copied deletes the copy operations explicitly instead of inheriting from a "noncopyable" base. + +## 6.5 Inheritance and polymorphism + +- **Prefer composition, `std::variant` or a template over inheritance** for code reuse. Inherit to model "is a", for an + interface that several unrelated implementations provide. +- **A polymorphic base** has a public virtual destructor, or a protected non-virtual one when objects are never deleted + through the base. It has no data members unless every derived class needs them. +- **`override`** on every overriding function, and never `virtual` together with `override`. `final` on an override that + must not be overridden further. +- **Public inheritance only.** Private inheritance is composition with a worse syntax. +- **No multiple inheritance of implementation.** A class may implement several pure interfaces. +- **Interfaces are small.** An interface with one implementation and no test double is not yet an interface. +- **No RTTI.** Dispatch with virtual functions, `std::visit`, or a kind tag and LLVM-style `isa`/`cast`/`dyn_cast`. + +## 6.6 Operators + +- Overload an operator only when it means what it means for built-in types: `+` adds, `==` compares for equality, `[]` + indexes. A reader must never wonder what `a << b` does to `a`. +- **Default comparisons**: `operator==` and, when there is an order, `operator<=>`, both `= default` where memberwise + comparison is right. +- Binary operators that are symmetric are hidden friends or non-members, so both operands convert the same way. +- No overloads of `&&`, `||`, `,` or unary `&`. + +## 6.7 Strong types + +Wrap a value whose meaning a bare integer or string would lose: + +```cpp +/// Identity of one block in a function; distinct from every other id kind. +struct BlockId final +{ + std::uint32_t value{}; + + [[nodiscard]] auto + operator<=>(const BlockId &) const = default; +}; +``` + +A function that takes a `BlockId` and a `SymbolId` cannot be called with the two swapped, and the compiler, not a review, +catches it. + +## 6.8 `std::optional`, `std::variant` and sentinels + +- **`std::optional<T>`** for "a value or nothing", instead of a sentinel such as `-1`, `0` or an empty string. +- **`std::variant`** for "one of several kinds", visited with `std::visit` and an overload set, so a new alternative + fails to compile where it is not handled. +- **A pointer that may be null** is fine for an optional reference to an existing object: `const Symbol *FindSymbol(...)` + says "or nothing" just as well, without a copy. + +## 6.9 Enumerations as flags + +A set of flags is an `enum class` with the bit operators defined for it, or a `std::bitset` or a set type of the project. +Do not combine plain integer constants with `|`. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..85332f3 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,418 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# License + +Copyright 2026 Progmasoft. + +The text of Progmasoft C++ Style is licensed under the +[Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/) (CC BY 4.0). +You may share and adapt it for any purpose, including commercially, as long as you give appropriate credit, link to +the license and say whether you changed it. A credit line such as this one is enough: + +> Based on [Progmasoft C++ Style](https://github.com/Progmasoft/progmasoft-cpp), CC BY 4.0. + +**Configuration and code examples are dedicated to the public domain** under +[CC0 1.0 Universal](LICENSES/CC0-1.0.md). This covers every fenced code block in this repository: the `.clang-format` +and `.clang-tidy` profiles, the compiler flags, and the C++ examples. Copy them into your own projects without credit +and under any license. + +The legal code of CC BY 4.0 follows. The legal code of CC0 is in [LICENSES/CC0-1.0.md](LICENSES/CC0-1.0.md). + +```text +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. +``` diff --git a/LICENSES/CC0-1.0.md b/LICENSES/CC0-1.0.md new file mode 100644 index 0000000..0049aa0 --- /dev/null +++ b/LICENSES/CC0-1.0.md @@ -0,0 +1,131 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC0-1.0 --> + +# CC0 1.0 Universal + +The configuration and code examples of Progmasoft C++ Style are dedicated to the public domain under this legal code; +see [LICENSE.md](../LICENSE.md). + +```text +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. +``` diff --git a/README.md b/README.md new file mode 100644 index 0000000..554d86a --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +<!-- SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> --> +<!-- SPDX-License-Identifier: CC-BY-4.0 --> + +# Progmasoft C++ Style + +Progmasoft C++ Style is a style guide for C++20. It says how code is named, laid out, structured and checked, and why, +so that a reader can move between files and projects without relearning the conventions each time. + +It is written for anyone who wants a complete, opinionated rule set to adopt. Progmasoft's own C++ projects follow it, +among them the [Tala compiler](https://github.com/Progmasoft/tala) and [Catch3](https://github.com/Progmasoft/catch3). + +## How to read it + +Each rule is short and states what to do. Most come with the reason, because a rule whose reason is known can be +applied to a case it did not foresee. Examples show the preferred form first; a form marked **Avoid** shows what the +rule replaces. + +The words follow [RFC 2119](https://www.rfc-editor.org/rfc/rfc2119) in spirit: **must** is a rule a review enforces, +**should** is the default that a good reason, written down next to the code, may override, and **may** is a choice +left to the author. + +## Contents + +| Chapter | Covers | +| --- | --- | +| [1. Principles](Guide/PRINCIPLES.md) | what the guide optimizes for, and how to decide a case it does not cover | +| [2. Formatting](Guide/FORMATTING.md) | the `.clang-format` profile, and what formatting leaves to the author | +| [3. Naming](Guide/NAMING.md) | types, functions, variables, constants, namespaces, files, macros | +| [4. Files and headers](Guide/FILES-AND-HEADERS.md) | extensions, `#pragma once`, includes, file size, the order inside a file | +| [5. Language](Guide/LANGUAGE.md) | C++20 features: `auto`, initialization, `const`, casts, integers, templates, lambdas | +| [6. Types and classes](Guide/TYPES-AND-CLASSES.md) | structs and classes, special members, inheritance, operators, enums | +| [7. Errors](Guide/ERRORS.md) | exception-free code, `Expected` and `Error`, invariants, fatal defects | +| [8. Ownership and memory](Guide/OWNERSHIP-AND-MEMORY.md) | RAII, smart pointers, views and their lifetimes, containers | +| [9. Comments and documentation](Guide/COMMENTS-AND-DOCUMENTATION.md) | Doxygen, what a comment is for, TODOs | +| [10. C interfaces](Guide/C-INTERFACES.md) | C11 headers, `extern "C"`, prefixes, ownership across the boundary | +| [11. Concurrency](Guide/CONCURRENCY.md) | threads, locks, atomics, thread-safety annotations | +| [12. Testing](Guide/TESTING.md) | unit tests, fuzzing, sanitizers, benchmarks | +| [13. Tooling](Guide/TOOLING.md) | compiler flags, the `.clang-tidy` profile, CI checks | + +[Adopting the guide](ADOPTING.md) explains how a project points to this guide, which files it copies and how it +records a deviation. [Contributing](CONTRIBUTING.md) explains how to propose a change to a rule. + +## The short version + +- C++20, formatted by the [clang-format profile](Guide/FORMATTING.md#the-profile), checked by the + [clang-tidy profile](Guide/TOOLING.md#132-the-clang-tidy-profile) with every warning an error. +- `PascalCase` for types, functions and namespaces; `camelCase` for variables and parameters; `name_` for private data + members; `kPascalCase` for constants and enumerators; `UPPER_SNAKE_CASE` for macros. +- Four spaces, braces on their own line, 80 columns, the return type on its own line. +- `.hpp` and `.cpp`; `.h` only for a C interface. `#pragma once`. Standard and third-party headers in `<>`, the + project's own in `""`. +- No `using namespace`. No exceptions in libraries and tools: recoverable failures return `Expected<T>` or `Error`. +- Ownership is visible in the type: values and `std::unique_ptr` own, references and views borrow. +- Every public declaration has a `///` comment, in US English. +- Tests sit next to the code they test; sanitizers and fuzzers run in CI. The guide prescribes no test, fuzzing or + benchmark framework, and no error library: it prescribes how they are used. + +## License + +The text is licensed under [CC BY 4.0](LICENSE.md). The configuration files and code examples are dedicated to the +public domain under [CC0 1.0](LICENSES/CC0-1.0.md), so they can be copied into any project without credit.