Skip to content

Latest commit

 

History

History
783 lines (582 loc) · 22.9 KB

codestyle.md

File metadata and controls

783 lines (582 loc) · 22.9 KB

Aloe C++ Code Style Guide

This document covers styling decisions beyond .clang-format configuration.

Attributes

[[nodiscard]]

Apply to:

  • All const getters and query methods (is_*, has_*, supports_*)
  • Factory methods and builders
  • Methods returning std::expected<T, E> or other result types
  • Any function where ignoring the return value is likely a bug
[[nodiscard]] constexpr bool is_success() const noexcept;
[[nodiscard]] static std::shared_ptr<Table> make_ptr(std::string name);
[[nodiscard]] std::expected<ResultBlock, ErrorContext> execute(std::string_view query);

[[maybe_unused]]

Apply to:

  • Caught exceptions when only type matters
  • Lambda parameters documenting intent but unused
  • Values read for side effects (benchmarks, volatile access)
} catch ([[maybe_unused]] std::out_of_range& e) {
    log_error("Index out of range");
}

server.on_request([]([[maybe_unused]] const Request& req) {
    handle_default();
});

Naming Conventions

Element Convention Example
Classes/Structs PascalCase QueryCompiler, ErrorCode
Functions/Methods snake_case is_success(), to_string()
Variables snake_case table_name, result_count
Member variables snake_case + trailing _ table_name_, distinct_
Template type params PascalCase T, ValueType, ColumnsTp
Namespaces lowercase aloe::tcp
Enum values PascalCase LogLevel::Warning
Macros SCREAMING_SNAKE ENABLE_LOGGING
Files snake_case query_compiler.hpp

Getters

Prefer member-name style without get_ prefix for simple accessors:

constexpr const std::string& table_name() const noexcept;  // Good
constexpr const std::string& get_table_name() const noexcept;  // Avoid

Use get_ for complex lookups or operations:

[[nodiscard]] const FieldSchema* get_field_schema(std::string_view name) const;

Also use get_ for atomic, volatile, or memory-barrier reads — the access isn't a plain field load and the prefix signals that to the caller:

[[nodiscard]] int64_t get_sequence() const noexcept;   // atomic load
[[nodiscard]] int64_t get_volatile() const noexcept;   // volatile read

Template Parameters

template <typename T>                    // Simple generic
template <typename ValueType>            // Descriptive when needed
template <typename ColumnsTp>            // Tp suffix for forwarding refs
template <typename Self>                 // Self for deducing this
template <typename... Args>              // Pack names
template <IsFieldDef FieldT>             // Constrained parameters

Initialization

Class Member Defaults

Use = syntax for default member initialization:

class Query {
private:
    bool distinct_  = false;
    int limit_      = -1;
    std::string alias_ = "";
};

Local Variables and Object Construction

Prefer {} over () for construction outside class definitions:

void process() {
    User user{1, "name", true};           // Aggregate/constructor
    auto table = Table{"users"};          // Single argument
    std::vector<int> ids = {1, 2, 3};     // Container initialization

    // Not:
    // User user(1, "name", true);
    // auto table = Table("users");
}

Constructor Initializer Lists

Use {} for member initialization:

class Connection {
public:
    Connection(std::string host, int port)
        : host_{std::move(host)}
        , port_{port}
        , connected_{false} {
    }

private:
    std::string host_;
    int port_;
    bool connected_;
};

Builder Pattern

When a type has more than a handful of configuration fields, expose construction through a nested Builder class. The Builder keeps the configured value-type simple and lets callers set only the fields they care about.

Contract:

  1. Setters use deducing this, named after the field (no with_ or set_ prefix):
template <typename Self>
constexpr auto&& ring_buffer_size(this Self&& self, std::size_t value) noexcept {
    self.config_.ring_buffer_size_ = value;
    return std::forward<Self>(self);
}
  1. Terminal method is finalize() &&. It runs validation and moves the built object out. The rvalue-ref qualifier prevents reuse of a spent Builder:
[[nodiscard]] Config finalize() && {
    config_.validate();
    return std::move(config_);
}
  1. Constructors accept existing configs for edit-one-field workflows:
Builder() = default;
explicit Builder(const Config& existing) : config_{existing} {}
explicit Builder(Config&& existing)      : config_{std::move(existing)} {}

Constexpr and Consteval

Constexpr

Use constexpr for anything that can possibly be evaluated at compile time, including features coming in C++26. Only omit when runtime-only evaluation is explicitly intended:

// Use constexpr liberally
constexpr bool is_valid() const noexcept;
constexpr auto transform(auto&& value);
static constexpr std::string_view name = "table";

// Omit only when runtime-only is intended
std::string generate_uuid();  // Inherently runtime
void write_to_file(std::string_view path);  // Side effects

Consteval

Use consteval only for functions that must execute at compile time:

consteval std::size_t hash_type_name(std::string_view name) {
    return compute_hash(name);
}

consteval auto make_field_index(auto... fields) {
    return std::array{fields...};
}

Explicit Specifier

Single-Argument Constructors

Always use explicit for single-argument constructors:

class TableColumn {
public:
    explicit TableColumn(std::string name);
};

When implicit conversion is intentionally desired, use explicit(false) to indicate awareness:

class StringView {
public:
    explicit(false) StringView(const char* str);  // Intentional implicit conversion
};

Conditional Explicit

Use for template constructors:

template <typename U>
constexpr explicit(!std::is_convertible_v<U, T>) Box(U&& value);

Ref-Qualifiers

Use ref-qualifiers to prevent dangling references and optimize for value category:

class Builder {
public:
    // Lvalue: return reference, caller keeps builder
    [[nodiscard]] const Config& config() const& noexcept {
        return config_;
    }

    // Rvalue: return by value, builder is being discarded
    [[nodiscard]] Config config() && noexcept {
        return std::move(config_);
    }

    // Method chaining with proper forwarding
    template <typename Self>
    constexpr auto&& with_name(this Self&& self, std::string name) {
        self.name_ = std::move(name);
        return std::forward<Self>(self);
    }

private:
    Config config_;
};

Getters and Setters

Prefer noexcept for data access:

[[nodiscard]] constexpr const std::string& name() const& noexcept;
[[nodiscard]] constexpr std::string name() && noexcept;
constexpr void set_name(std::string value) noexcept;

Noexcept

Mark noexcept when function truly cannot throw:

constexpr bool is_success() const noexcept;
constexpr uint16_t value() const noexcept;

Use conditional noexcept for templates:

constexpr Box() noexcept(std::is_nothrow_constructible_v<T>)
    requires std::default_initializable<T>;

Parameters

In a definition, qualify by-value parameters const: scalars, addresses, read-only spans. The body then cannot reassign them, and the reader knows it does not.

void Packet::trim_front(const std::size_t count) noexcept {
    begin_ += std::min(count, size());
}

[[nodiscard]] constexpr std::uint16_t load_be16(const std::span<const std::byte> bytes) noexcept {
    return static_cast<std::uint16_t>((std::to_integer<unsigned>(bytes[0]) << 8U) | std::to_integer<unsigned>(bytes[1]));
}

Two exceptions:

  • A declaration without a body carries no const. It is not part of the signature, and clang-tidy's readability-avoid-const-params-in-decls rejects it there.
  • A span the function writes through, std::span<std::byte> or std::span<Packet>, stays unqualified: the const would say nothing about the elements, and the parameter is the function's output.

Members That Refer to Other Objects

The member's type says who owns the object and whether it can be absent:

The member Type
owns heap memory std::unique_ptr<T>
is set by the constructor, never null, never changed; the class is not assignable T&
is the same, but the class must stay copy- or move-assignable std::reference_wrapper<T>
can be null or is set later: an empty packet, a moved-from handle, a list link T*
// Good: the queue cannot exist without its device, and nothing reassigns it
class ShardQueue {
public:
    ShardQueue(Device& owner, std::uint16_t index, std::size_t ring_capacity, ShardQueueCounters& counters)
        : device_{owner}, counters_{counters} { /* ... */ }

private:
    Device& device_;
    ShardQueueCounters& counters_;
};

// Good: an empty packet has no pool
class Packet {
private:
    Pool* pool_ = nullptr;
};
  • No std::shared_ptr: each shard owns what it works on, and nothing in the stack shares ownership.
  • A type compared by what it points at keeps a pointer: Scheduler's defaulted operator== compares its ShardContext*, where a reference_wrapper would compare the two contexts.
  • An operation state that deletes itself when it completes (new, then delete this) stays a raw new; std::unique_ptr cannot hold an object that owns itself.

Unreachable Code

std::unreachable()

Use for code paths that should never execute:

switch (category) {
    case Category::Success: return "success";
    case Category::Error: return "error";
}
std::unreachable();

Error Handling

Hot Path: std::expected<T, E>

Use std::expected only in performance-critical, hot-path code. A function with several distinct failure modes uses std::expected<T, std::variant<E1, E2, ...>>; build failures with std::unexpected(e):

// Receive path - called for every packet
[[nodiscard]] aloe::execution::task<std::expected<Segment, ReceiveError>>
next_segment();

// Tight loop processing
[[nodiscard]] std::expected<Row, ParseError> parse_row(std::span<const std::byte> data);

Setup/Rare/Cold Path: Exceptions

Use exceptions for setup functions, constructors, rare operations, and non-hot-path code:

// Constructor - called once
Connection::Connection(const Config& config) {
    if (!config.is_valid()) {
        throw ConfigurationError{"Invalid connection config"};
    }
}

// Setup function - called at startup
void initialize_pool(const PoolConfig& config) {
    if (config.max_connections < 1) {
        throw std::invalid_argument{"Pool must have at least 1 connection"};
    }
}

// Rare operation
void migrate_schema(const Schema& target) {
    if (!can_migrate(target)) {
        throw MigrationError{"Incompatible schema versions"};
    }
}

Platform-Specific Code

Gate platform-specific code with #if defined(<PLATFORM>). Nest sub-feature checks (libc version, kernel headers) inside the platform guard. Always provide a portable #else fallback — callers should never need #ifdef at the use site.

#if defined(__linux__)
    #if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 30))
        #include <unistd.h>
    #else
        #include <sys/syscall.h>
    #endif
#endif

[[nodiscard]] inline uint64_t capture_kernel_tid() noexcept {
#if defined(__linux__)
    #if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 30))
    return static_cast<uint64_t>(::gettid());
    #else
    return static_cast<uint64_t>(::syscall(SYS_gettid));
    #endif
#else
    return std::hash<std::thread::id>{}(std::this_thread::get_id());
#endif
}

Templates and Concepts

Prefer Concepts Over SFINAE

// Good: concept constraint
template <typename T>
    requires std::invocable<T, int>
void apply(T&& fn);

// Avoid: SFINAE
template <typename T, std::enable_if_t<std::is_invocable_v<T, int>, int> = 0>
void apply(T&& fn);

Concept Definitions

template <typename T>
concept IsFieldDef = requires {
    typename T::value_type;
    { T::name() } -> std::convertible_to<std::string_view>;
};

template <typename T, typename... Args>
concept OneOf = (std::is_same_v<Args, T> || ...);

Concept Naming

Prefix Intent Example
Is* Type predicate — "T is a kind of X" IsFieldDef, IsOperator, IsQuery, IsHttpDriver
Has* Structural requirement — "T exposes members/ops" HasStaticNameMember, HasAcceptVisitor, HasToHttpResponse
no prefix Generic operator-like / variadic relation OneOf, OneOfDecayed

Concept Conformance

A class written to model a concept says so at the bottom of its header, inside its namespace, so the header fails to compile the moment the class stops modelling it:

    class Port { /* ... */ };

    static_assert(device::IsDevice<Port>);

}  // namespace aloe::fabric

A class template has no type to check there; the template that first instantiates it with its real arguments checks it in its own body, as tcp::Stack checks Connection and ReadView. Tests keep the negative checks and the fakes, not a copy of the positive ones.

Requires Clause Placement

Place after template parameters, on own line with indent:

template <typename F>
    requires std::invocable<F, T&>
constexpr auto and_then(F&& f) & -> std::invoke_result_t<F, T&>;

Deducing This (C++23)

Prefer deducing this over CRTP.

For member access in getters and decompose methods, use std::forward_like<Self>(self.member_):

template <typename Self>
[[nodiscard]] constexpr auto&& value(this Self&& self) noexcept {
    return std::forward_like<Self>(self.value_);
}

For method calls (CRTP dispatch, chaining), use std::forward<Self>(self).method():

template <typename Self>
constexpr auto&& with_name(this Self&& self, std::string name) {
    self.name_ = std::move(name);
    return std::forward<Self>(self);
}

// CRTP dispatch to derived class
template <typename Self>
constexpr auto process(this Self&& self) {
    return std::forward<Self>(self).derived().do_work();
}

Rationale: std::forward_like directly applies the value category of Self to the member without going through the object. This avoids clang-tidy bugprone-use-after-move false positives that occur with std::forward<Self>(self).member_, and is semantically cleaner for member access.

One Class, One Place

A class's member functions are defined in the class body or, for a non-template class with a source file, in that one .cpp. One class's definitions are never spread over several headers, by code path or otherwise, and no header is included after another's namespace closes, .inl or .hpp, to finish what the class above needs: headers include what they use at the top, in an order with no cycle, and the umbrella lists every one of them. The reader of a class sees every member in one place; a class too big for that is split into classes with responsibilities of their own, each in its own file.

// Good: every member of the template defined in its body, in session.hpp
template <typename Transport>
class Session {
public:
    void receive(std::span<const std::byte> bytes) noexcept { /* ... */ }
    void send(std::span<const std::byte> bytes) noexcept { /* ... */ }
};

// Bad: session_receive.hpp and session_send.hpp each defining members of Session<Transport>
template <typename Transport>
void Session<Transport>::receive(std::span<const std::byte> bytes) noexcept { /* ... */ }

Lambda Captures

Prefer explicit captures over [&] or [=]:

[this] { process(); }                            // Member access
[]() { return default_value(); }                 // Stateless
[&result](auto& val) { result = transform(val); } // Explicit ref

Commenting

File Headers

No copyright headers. Files start directly with #pragma once:

#pragma once

#include <string>

Documentation

Use Doxygen for public APIs:

/**
 * @brief Async executor with coroutine support
 *
 * Thread safety: NOT thread-safe. Owned by one shard, used only on its core.
 */
class AsyncExecutor {

Inline Comments

Brief explanations for non-obvious logic:

// Propagate error maintaining original category
std::visit([&result]<typename E>(E&& err) { ... }, value_);

TODO Format

// TODO: Issue#33 - add binary format flag
// TODO: add constexpr support

Module Layout

Each module under common/, devices/, fixtures/ or l7/ ships an umbrella header at <module>/export/aloe/<module> — a file with no extension containing only #pragma once and #include directives for every public header of the module:

// common/core/export/aloe/core
#pragma once

#include <clock.hpp>
#include <version.hpp>
// ...

Consumers include the whole module via #include <aloe/<module>>:

#include <aloe/core>

Namespaces

Which Namespace

Every module gets a namespace named after it: aloe::core, aloe::execution, aloe::log, aloe::wire, aloe::device, aloe::fabric, aloe::frames, aloe::ethdev, aloe::loop, aloe::runtime, aloe::net, aloe::stream, aloe::tcp; the benchmarks live in aloe::benchmarks. A name says which module it comes from, so aloe::execution::ex::just, aloe::wire::MacAddress and aloe::fabric::Port need no lookup to place. Nothing is declared directly in aloe.

Code in one module names another module's vocabulary through the module namespace, never through a using-directive: inside aloe::fabric, write wire::MacAddress. Inside the module itself the names stay unqualified.

Opening Style

Use the C++17 one-line nested form. Never nest with separate braces.

namespace aloe::net { ... }            // Good
namespace aloe::tcp { ... }            // Good

// Avoid:
// namespace aloe { namespace net { ... } }

Internal Implementation Details

Place implementation-only types, trait structs, and helper concepts inside a nested namespace detail { ... } — lowercase, singular (never details or impl). Anything inside detail is not part of the public API.

namespace aloe::net {
    namespace detail {
        struct SegmentHeader { ... };
        struct ReassemblyQueue { ... };
    }  // namespace detail
}  // namespace aloe::net

Include Organization

Order (separated by blank lines), which .clang-format produces itself:

  1. Corresponding header (for .cpp files)
  2. Headers without an extension: the standard library and the umbrellas (<aloe/...>), sorted together
  3. Headers ending in .hpp or .h: third-party libraries and the same module's headers

What it cannot decide is how each one is spelled:

  • A .cpp includes its own header in quotes, #include "flow_table.hpp", first. No other include uses quotes.
  • A header of the same module is included by its basename, #include <tcp_stack.hpp>, wherever it sits in the module. A header whose names are all in detail sits in a detail/ folder inside the folder it belongs to (stack/detail/receiver.hpp beside stack/tcp_stack.hpp), never in one detail/ folder for the whole module, and is #include <detail/receiver.hpp>.
  • Anything from another module comes through its umbrella, #include <aloe/net>, never one of its headers, even when only one is needed. A module never includes its own umbrella.
  • Tests, examples and the benchmark are not modules: they include every module through its umbrella, and their own helpers by basename.
// a .cpp in tcp
#include "flow_table.hpp"

#include <algorithm>
#include <aloe/core>
#include <aloe/wire>
#include <cstdint>

#include <tcp_counters.hpp>

./scripts/check-includes.sh checks every source against these rules, in the pre-commit hook and in CI.

Type Aliases

Use _type suffix for member type aliases:

using value_type = T;
using error_type = E;
using scheduler_type = Scheduler;

Class Layout

Order within class:

  1. Public types and aliases
  2. Public static members
  3. Constructors/destructors
  4. Public methods
  5. Protected members
  6. Private types
  7. Private methods
  8. Private data members
class Table {
public:
    using column_type = TableColumn;

    static std::shared_ptr<Table> make_ptr(std::string name);

    explicit Table(std::string name);
    ~Table() = default;

    [[nodiscard]] constexpr const std::string& name() const noexcept;

private:
    std::string name_;
    std::vector<column_type> columns_;
};

Macros

Public Interface

Public headers define no macros. A macro cannot be exported from a C++ module and cannot be scoped to a namespace, so keeping the public interface free of them is what lets a module wrapper be added later without touching the code. Use constexpr values, consteval functions and concepts instead.

Prefix Convention

Macros are allowed inside implementation files and in detail headers.

Prefix Use
ALOE_* Build-wide flags set by CMake
ALOE_<MODULE>_* Macros private to one module, for example ALOE_NET_*

Feature-Flag Disabled Fallbacks

When a macro is gated behind a feature flag, the #else branch must expand to a compilable no-op so call sites never need #ifdef guards:

#ifdef ALOE_TRACE
    #define ALOE_NET_TRACE(...) ::aloe::net::detail::trace(__VA_ARGS__)
#else
    #define ALOE_NET_TRACE(...) ((void)0)
#endif

Coroutines and Senders

Name the execution facilities through <aloe/execution>: aloe::execution::ex:: for senders, receivers and schedulers, aloe::execution::task<T> for coroutine tasks. Never spell stdexec:: or exec:: outside common/execution/execution/execution.hpp. That header is the only place that changes when the standard library ships std::execution.

Do not wrap a sender in std::move when its type is trivially copyable; clang-tidy rejects it. Pass the expression directly.