About
This document defines the coding style and rules for PER-owned code in the monorepo. The rules are organized in three parts:
- Shared principles that apply to all languages
- Firmware/C rules for the embedded firmware under
firmware/
- Rust rules for the DAQ workspace under
daq/
These rules are often specific examples rather than an exhaustive list. Their underlying principles should be applied broadly, with the overarching goal of writing consistent, safe, clean, simple, understandable, and maintainable code.
The goal is to maintain a consistent and easily maintainable codebase. Following these rules reduces opportunities for hidden bugs and makes the code more readable and reviewable for others.
Shared
These rules apply to all PER-owned code in the repository, regardless of language.
Avoid nesting where possible
- Try using early returns and condition inversion
- Remember to free resources (like semaphore/mutex) before returning
- No more than 4 indentations deep
- Extract a helper function if nesting is still too deep
void nesting_example_bad() {
if (condition1) {
if (condition2) {
}
}
}
void nesting_example_better() {
if (!condition1) {
return;
}
if (!condition2) {
return;
}
}
Use descriptive names
- Try to use full words wherever possible
- Keep it to a reasonable length
- The exception to this rule is temporary variables in for loops like
i or j
- Variables with units should have their unit at the end of the name when it would otherwise be ambiguous
- Document units and conversions at API and protocol boundaries, and where possible enforce proper usage via types
- Avoid magic numbers
- Define a named constant,
enum, or macro
- Explain constants whose meaning comes from hardware, a protocol, or a physical limit
- Handle errors deliberately
- Propagate errors or report them where recovery is possible
- Do not silently discard faults or substitute misleading values
- Keep documentation in sync
- Update affected in-repository documentation in the same PR as behavior changes
- Comments should explain intent, assumptions, and constraints, not restate the code
- Generally follow the principle of least surprise
- Avoid unexpected side effects, hidden state, and non-obvious behavior
- Avoid unnecessary complexity, indirection, and abstraction
- As a rule of thumb, it is best to follow the style of existing code.
- Match naming, formatting, and structure.
Firmware C
The compiler standard for firmware is set to C23, enabling several important modern features:
bool, nullptr as standard keywords
constexpr for compile-time constants
static_assert for compile-time assertions
Targets are STM32 MCUs (G4, F4) using the arm-none-eabi-gcc toolchain. On this platform, 32 bit writes are atomic.
Firmware allocation and naming rules do not apply to Rust or Python host tools.
- Use of dynamic memory allocation is forbidden
- Absolutely no
malloc(), this will open the risk for memory fragmentation
- Instead, you must either allocate memory at compile time, or use stack-based local variables
- FreeRTOS tasks, queues, and synchronization objects must be created statically, not from the heap
Global variables
- Global variables should be prefixed with
g_
Function names
- Library functions should be prefixed with the library name in caps
void NXT_set_command();
void poll_shock_pots();
- Macros
- Use
SCREAMING_SNAKE_CASE
- Same rules as function names
- Wrap values with parenthesis to prevent expansion edge cases
Never pass side effects like i++ or hardware register reads to a macro, parenthesization does not prevent double evaluation
c // bad #define ABS(x) ((x) < 0 ? (-1 * x) : x) // good #define ABS(x) ((x) < 0 ? (-1 * (x)) : (x))
Inline functions
- Use inline functions over macros wherever possible, they offer type checking and single evaluation of arguments
- Prefer typed
static constexpr constants to macros for inherent type safety
static inline uint32_t max_u32(uint32_t a, uint32_t b) {
return a > b ? a : b;
}
Don't use brace-less control statements
if (condition)
code();
if (condition) {
code();
}
Allowed data types
float
char
bool (standard keyword in C23)
- From
<stdint.h>
int num;
short num2;
int32_t num;
int16_t num2;
Always initialize variables with a value
- global variables should explicitly be zero'd out (even though the compiler does this for you)
type_t g_global_struct = {0};
uint8_t g_global_val = 0;
struct declarations
- Always use
typedef and suffix your new type with _t
- Order your variables in descending size (this saves space from padding)
- However exceptions can be made for logical/clarity purposes
- Remember that we target 32-bit architecture for firmware (pointers are 4 bytes)
typedef struct {
uint16_t small_num;
uint32_t medium_num;
uint64_t big_num;
uint16_t small_num2;
} bad_struct_t;
typedef struct {
uint64_t big_num;
uint32_t medium_num;
uint16_t small_num;
uint16_t small_num2;
} good_struct_t;
enum declaration
- Always use
typedef and suffix your new type with _t
- Enum members should be prefixed with the name of the enum (example below)
- Always explicitly declare the base type of the enum, ESPECIALLY when it is a member of a
struct
- It is recommended to assign explicit values to each enum member
c // example enum typedef enum : uint8_t { FAULT_STATE_CLEAR = 0, FAULT_STATE_PENDING = 1, FAULT_STATE_LATCHED = 2, FAULT_STATE_RECOVERING = 3 } fault_state_t;
Check null pointers before dereferencing
- Document whether pointer arguments may be null
- A documented non-null precondition must be upheld by callers
- Silently returning from a
void function is not a substitute for an error contract, return an error or report a fault when invalid input matters
```c // bad void pass_by_reference(uint16_t *ptr) { *ptr = 10; }
// good, returns false for an invalid output pointer and the caller must handle failure bool set_value(uint16_t *value) { if (value == nullptr) { return false; } *value = 10; return true; } ```
Use apostrophes to format large numbers (C23)
```c // bad static constexpr uint32_t target_core_clock_rate_hz = 16000000;
// good static constexpr uint32_t target_core_clock_rate_hz = 16'000'000; ```
Rust
These rules apply to all repository-owned Rust, including tests and examples. Unlike the firmware C, host Rust may use heap allocation and standard collections.
- Do not use
.unwrap() or .unwrap_err()
- This includes tests and examples, a panic in an example is still a crash
- Use
Result/Option with ? or explicit matching instead
Keep production .expect() and .expect_err() exceptional
- An invariant established by the code must guarantee the required variant
- Put the justification beside the call and explain the invariant in its message
- Prefer an infallible constructor when one is available
- Tests may use descriptive
expect/expect_err calls for setup and assertions, prefer a test returning Result when ? makes the intent clearer
fn loopback_address() -> std::net::Ipv4Addr {
// This source-controlled literal is valid IPv4, independent of external input.
"127.0.0.1"
.parse()
.expect("hard-coded loopback literal should be a valid IPv4 address")
}
Handle recoverable errors with Result and Option
Result for operations that can fail, Option for expected absence
- Propagate with
? or explicit matching, preserve useful error context
- Better yet, use the type system to prevent the error from being possible in the first place
- External input, parsing user files, filesystem access, device operations, and channel communication require recoverable handling, they cannot justify an
expect simply because failure is unlikely
fn read_log(path: &std::path::Path) -> std::io::Result<String> {
let contents = std::fs::read_to_string(path)?;
Ok(contents)
}
Only use defaults when the fallback is meaningful
unwrap_or, unwrap_or_else, and unwrap_or_default are allowed when the fallback is meaningful
- Do not conceal failures with defaults,
.ok(), or ignored results
- Explain intentional best-effort behavior, including when an error can safely be ignored during cleanup
fn log_folder(configured: Option<std::path::PathBuf>) -> std::path::PathBuf {
// No configured folder means use the application's default log directory.
configured.unwrap_or_else(|| std::path::PathBuf::from("logs"))
}
- Do not replace error handling with panics
- No
panic!, unchecked extraction, or unchecked indexing of external data
- Assertions should express internal invariants
- Naming
snake_case for functions, variables, modules, and fields
UpperCamelCase for types and enum variants
SCREAMING_SNAKE_CASE for constants and statics
- Do not carry C's library prefixes,
g_ prefix, or _t suffix into Rust naming
- Prefer borrowing to unnecessary cloning
- Accept
&str, slices, or &Path when ownership is not required
- Take ownership explicitly when it is
- Use enums to express distinct states
- Instead of ambiguous combinations of flags
- Keep APIs and abstractions focused on the actual use case
- Use explicit widths for wire data
- Use
usize for collection sizes and indices
- Explain intentional lossy numeric conversions
- Use the type system
- Prevent invalid states and values and guarantee invariants
- Make ownership clear
- Prevent misuse of APIs
- Keep blocking work out of the UI
- Keep blocking I/O and expensive processing outside UI updates
- Use channels to communicate with workers and make state ownership clear
- Handle the worker lifecycle deliberately
- Check channel disconnection, cancellation, and worker shutdown
- Avoid holding locks across blocking work, review lock ordering and exit paths
- Only use safe Rust
- No
unsafe blocks