Style Guide#
Tip
Pigweed runs pw format
as part of pw presubmit
to perform some code
formatting checks. To speed up the review process, consider adding pw
presubmit
as a git push hook using the following command:
pw presubmit --install
C++ style#
The Pigweed C++ style guide is closely based on Google’s external C++ Style Guide, which is found on the web at https://google.github.io/styleguide/cppguide.html. The Google C++ Style Guide applies to Pigweed except as described in this document.
The Pigweed style guide only applies to Pigweed itself. It does not apply to projects that use Pigweed or to the third-party code included with Pigweed. Non-Pigweed code is free to use features restricted by Pigweed, such as dynamic memory allocation and the entirety of the C++ Standard Library.
Recommendations in the Embedded C++ Guide are considered part of the Pigweed style guide, but are separated out since it covers more general embedded development beyond just C++ style.
C++ standard#
Pigweed AI summary: All Pigweed C++ code must be compiled with -std=c++17 in Clang and GCC, and C++20 features may be used as long as the code still compiles unmodified with C++17. Macros are provided in pw_polyfill/language_feature_macros.h to provide C++20 features when supported. Compiler extensions should not be used unless wrapped in a macro or properly guarded in the preprocessor, and macros that wrap compiler-specific features can be found in pw_processor/compiler.h.
All Pigweed C++ code must compile with -std=c++17
in Clang and GCC. C++20
features may be used as long as the code still compiles unmodified with C++17.
See pw_polyfill/language_feature_macros.h
for macros that provide C++20
features when supported.
Compiler extensions should not be used unless wrapped in a macro or properly
guarded in the preprocessor. See pw_processor/compiler.h
for macros that
wrap compiler-specific features.
Automatic formatting#
Pigweed AI summary: Pigweed uses clang-format to automatically format its source code, and a .clang-format configuration is provided with the repository. All code in Pigweed is expected to be formatted with clang-format prior to submission, and existing code may be reformatted at any time. If clang-format formats code in an undesirable or incorrect way, it can be disabled for the affected lines by adding // clang-format off, and then re-enabled with a // clang-format on comment.
Pigweed uses clang-format to
automatically format Pigweed source code. A .clang-format
configuration is
provided with the Pigweed repository.
Automatic formatting is essential to facilitate large-scale, automated changes
in Pigweed. Therefore, all code in Pigweed is expected to be formatted with
clang-format
prior to submission. Existing code may be reformatted at any
time.
If clang-format
formats code in an undesirable or incorrect way, it can be
disabled for the affected lines by adding // clang-format off
.
clang-format
must then be re-enabled with a // clang-format on
comment.
// clang-format off
constexpr int kMyMatrix[] = {
100, 23, 0,
0, 542, 38,
1, 2, 201,
};
// clang-format on
C Standard Library#
Pigweed AI summary: This section provides guidelines for using the C Standard Library in C++ code. It recommends using the C++ versions of headers and C functions from the std namespace. It also advises against using C standard library functions that allocate memory within core Pigweed, except in cases where dynamic allocation is enabled and the functionality is optional.
In C++ headers, always use the C++ versions of C Standard Library headers (e.g.
<cstdlib>
instead of <stdlib.h>
). If the header is used by both C and
C++ code, only the C header should be used.
In C++ code, it is preferred to use C functions from the std
namespace. For
example, use std::memcpy
instead of memcpy
. The C++ standard does not
require the global namespace versions of the functions to be provided. Using
std::
is more consistent with the C++ Standard Library and makes it easier
to distinguish Pigweed functions from library functions.
Within core Pigweed, do not use C standard library functions that allocate
memory, such as std::malloc
. There are exceptions to this for when dynamic
allocation is enabled for a system; Pigweed modules are allowed to add extra
functionality when a heap is present; but this must be optional.
C++ Standard Library#
Pigweed AI summary: The C++ Standard Library is not ideal for embedded software due to its classes and functions not being designed with microcontroller constraints in mind. However, a limited set of standard C++ libraries can still be used effectively. Pigweed only permits a subset of the C++ Standard Library to keep it small, flexible, and portable. Certain headers are always permitted, while others can be used with caution or should never be used. Third-party code and projects using Pigweed are not subject to these restrictions.
Much of the C++ Standard Library is not a good fit for embedded software. Many
of the classes and functions were not designed with the RAM, flash, and
performance constraints of a microcontroller in mind. For example, simply
adding the line #include <iostream>
can increase the binary size by 150 KB!
This is larger than many microcontrollers’ entire internal storage.
However, with appropriate caution, a limited set of standard C++ libraries can be used to great effect. Developers can leverage familiar, well-tested abstractions instead of writing their own. C++ library algorithms and classes can give equivalent or better performance than hand-written C code.
A limited subset of the C++ Standard Library is permitted in Pigweed. To keep Pigweed small, flexible, and portable, functions that allocate dynamic memory must be avoided. Care must be exercised when using multiple instantiations of a template function, which can lead to code bloat.
Permitted Headers#
Pigweed AI summary: This text outlines which C++ Standard Library headers are permitted, which should be used with caution, and which should never be used. It also suggests alternative headers to use in some cases. The restrictions listed do not apply to third-party code or projects that use Pigweed.
The following C++ Standard Library headers are always permitted:
<array>
<complex>
<initializer_list>
<iterator>
<limits>
<optional>
<random>
<ratio>
<string_view>
<tuple>
<type_traits>
<utility>
<variant>
C Standard Library headers (
<c*>
)
With caution, parts of the following headers can be used:
<algorithm>
– be wary of potential memory allocation<atomic>
– not all MCUs natively support atomic operations<bitset>
– conversions to or from strings are disallowed<functional>
– do not usestd::function
; use pw_function<mutex>
– can usestd::lock_guard
, use pw_sync for mutexes<new>
– for placement new<numeric>
– be wary of code size with multiple template instantiations
Never use any of these headers:
Dynamic containers (
<list>
,<map>
,<set>
,<vector>
, etc.)Streams (
<iostream>
,<ostream>
,<fstream>
,<sstream>
etc.) – in some cases pw_stream can work instead<span>
– use pw_span instead. Downstream projects may want to directly usestd::span
if it is available, but upstream must use thepw::span
version for compatability<string>
– can use pw_string<thread>
– can use pw_thread<future>
– eventually pw_async will offer this<exception>
,<stdexcept>
– no exceptions<memory>
,<scoped_allocator>
– no allocations<regex>
<valarray>
Headers not listed here should be carefully evaluated before they are used.
These restrictions do not apply to third party code or to projects that use Pigweed.
Combining C and C++#
Pigweed AI summary: This section discusses how to combine C and C++ code. It recommends using "extern 'C'" for symbols that must have C linkage and defining these functions within C++ namespaces. It also notes that C++ functions with no parameters do not include "void" in the parameter list, while C functions with no parameters must include it. The example code provided demonstrates how to use "extern 'C'" in a C++ namespace.
Prefer to write C++ code over C code, using extern "C"
for symbols that must
have C linkage. extern "C"
functions should be defined within C++
namespaces to simplify referring to other code.
C++ functions with no parameters do not include void
in the parameter list.
C functions with no parameters must include void
.
namespace pw {
bool ThisIsACppFunction() { return true; }
extern "C" int pw_ThisIsACFunction(void) { return -1; }
extern "C" {
int pw_ThisIsAlsoACFunction(void) {
return ThisIsACppFunction() ? 100 : 0;
}
} // extern "C"
} // namespace pw
Control statements#
Pigweed AI summary: The document provides guidelines for control statements in programming. It emphasizes the use of braces and separate lines for loops and conditional statements. The syntax "while (true)" is preferred over "for (;;)" for infinite loops. The document also recommends early exits with "return" and "continue" to simplify code and improve readability. It suggests keeping the main handling at the bottom and de-dentend for both functions and loops. The document advises against using unnecessary "else" blocks after blocks that terminate with a
Loops and conditionals#
Pigweed AI summary: This section provides guidelines for using loops and conditional statements in programming. It emphasizes the importance of using braces and placing them on their own line for all loops and conditionals. It also recommends using the syntax "while (true)" instead of "for (;;)" for infinite loops. The section includes examples of correct and incorrect usage of braces and syntax for loops and conditionals.
All loops and conditional statements must use braces, and be on their own line.
Yes: Always use braces for line conditionals and loops:
while (SomeCondition()) {
x += 2;
}
if (OtherCondition()) {
DoTheThing();
}
No: Missing braces
while (SomeCondition())
x += 2;
if (OtherCondition())
DoTheThing();
No: Statement on same line as condition
while (SomeCondition()) { x += 2; }
if (OtherCondition()) { DoTheThing(); }
The syntax while (true)
is preferred over for (;;)
for infinite loops.
Yes:
while (true) {
DoSomethingForever();
}
No:
for (;;) {
DoSomethingForever();
}
Prefer early exit with return
and continue
#
Pigweed AI summary: The article recommends exiting early from functions and loops to simplify code, following the same conventions as LLVM. This approach makes the code easier to follow visually, separates the main business from edge case handling, and simplifies code reviews. The guidance applies to function early exit and loop early exit, with examples provided. The article warns against burying the main body of the function or loop inside nested conditionals, which makes it harder to understand the code's main purpose. However, there are cases where this structure
Prefer to exit early from functions and loops to simplify code. This is the same same conventions as LLVM. We find this approach is superior to the “one return per function” style for a multitude of reasons:
Visually, the code is easier to follow, and takes less horizontal screen space.
It makes it clear what part of the code is the “main business” versus “edge case handling”.
For functions, parameter checking is in its own section at the top of the function, rather than scattered around in the fuction body.
For loops, element checking is in its own section at the top of the loop, rather than scattered around in the loop body.
Commit deltas are simpler to follow in code reviews; since adding a new parameter check or loop element condition doesn’t cause an indentation change in the rest of the function.
The guidance applies in two cases:
Function early exit - Early exits are for function parameter checking and edge case checking at the top. The main functionality follows.
Loop early exit - Early exits in loops are for skipping an iteration due to some edge case with an item getting iterated over. Loops may also contain function exits, which should be structured the same way (see example below).
Yes: Exit early from functions; keeping the main handling at the bottom and de-dentend.
Status DoSomething(Parameter parameter) {
// Parameter validation first; detecting incoming use errors.
PW_CHECK_INT_EQ(parameter.property(), 3, "Programmer error: frobnitz");
// Error case: Not in correct state.
if (parameter.other() == MyEnum::kBrokenState) {
LOG_ERROR("Device in strange state: %s", parametr.state_str());
return Status::InvalidPrecondition();
}
// Error case: Not in low power mode; shouldn't do anything.
if (parameter.power() != MyEnum::kLowPower) {
LOG_ERROR("Not in low power mode");
return Status::InvalidPrecondition();
}
// Main business for the function here.
MainBody();
MoreMainBodyStuff();
}
No: Main body of function is buried and right creeping. Even though this is shorter than the version preferred by Pigweed due to factoring the return statement, the logical structure is less obvious. A function in Pigweed containing nested conditionals indicates that something complicated is happening with the flow; otherwise it would have the early bail structure; so pay close attention.
Status DoSomething(Parameter parameter) {
// Parameter validation first; detecting incoming use errors.
PW_CHECK_INT_EQ(parameter.property(), 3, "Programmer error: frobnitz");
// Error case: Not in correct state.
if (parameter.other() != MyEnum::kBrokenState) {
// Error case: Not in low power mode; shouldn't do anything.
if (parameter.power() == MyEnum::kLowPower) {
// Main business for the function here.
MainBody();
MoreMainBodyStuff();
} else {
LOG_ERROR("Not in low power mode");
}
} else {
LOG_ERROR("Device in strange state: %s", parametr.state_str());
}
return Status::InvalidPrecondition();
}
Yes: Bail early from loops; keeping the main handling at the bottom and de-dentend.
for (int i = 0; i < LoopSize(); ++i) {
// Early skip of item based on edge condition.
if (!CommonCase()) {
continue;
}
// Early exit of function based on error case.
int my_measurement = GetSomeMeasurement();
if (my_measurement < 10) {
LOG_ERROR("Found something strange; bailing");
return Status::Unknown();
}
// Main body of the loop.
ProcessItem(my_items[i], my_measurement);
ProcessItemMore(my_items[i], my_measurement, other_details);
...
}
No: Right-creeping code with the main body buried inside some nested conditional. This makes it harder to understand what is the main purpose of the loop versus what is edge case handling.
for (int i = 0; i < LoopSize(); ++i) {
if (CommonCase()) {
int my_measurement = GetSomeMeasurement();
if (my_measurement >= 10) {
// Main body of the loop.
ProcessItem(my_items[i], my_measurement);
ProcessItemMore(my_items[i], my_measurement, other_details);
...
} else {
LOG_ERROR("Found something strange; bailing");
return Status::Unknown();
}
}
}
There are cases where this structure doesn’t work, and in those cases, it is fine to structure the code differently.
No else
after return
or continue
#
Pigweed AI summary: This section advises against putting unnecessary "else" blocks after "return" or "continue" statements, as it can cause indentation issues and code duplication. The recommended approach is to use early exits instead. The section provides an example of code that follows this guidance and another example that violates it.
Do not put unnecessary } else {
blocks after blocks that terminate with a
return, since this causes unnecessary rightward indentation creep. This
guidance pairs with the preference for early exits to reduce code duplication
and standardize loop/function structure.
Yes: No else after return or continue
// Note lack of else block due to return.
if (Failure()) {
DoTheThing();
return Status::ResourceExausted();
}
// Note lack of else block due to continue.
while (MyCondition()) {
if (SomeEarlyBail()) {
continue;
}
// Main handling of item
...
}
DoOtherThing();
return OkStatus();
No: Else after return needlessly creeps right
if (Failure()) {
DoTheThing();
return Status::ResourceExausted();
} else {
while (MyCondition()) {
if (SomeEarlyBail()) {
continue;
} else {
// Main handling of item
...
}
}
DoOtherThing();
return OkStatus();
}
Include guards#
Pigweed AI summary: This paragraph provides guidelines for including header files in Pigweed. It states that the first non-comment line of every header file must be "#pragma once" and traditional macro include guards should not be used. The "#pragma once" should come directly after the Pigweed copyright block, with no blank line, followed by a blank. A sample code block is provided as an example.
The first non-comment line of every header file must be #pragma once
. Do
not use traditional macro include guards. The #pragma once
should come
directly after the Pigweed copyright block, with no blank line, followed by a
blank, like this:
// Copyright 2021 The Pigweed Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
#pragma once
// Header file-level comment goes here...
Memory allocation#
Pigweed AI summary: Dynamic memory allocation can cause problems such as occupying valuable CPU cycles and resulting in a system crash without a clear cause. To ensure portability, Pigweed code is not allowed to dynamically allocate memory and must use automatic or static storage duration. Projects using Pigweed can use dynamic allocation if their target enables the heap.
Dynamic memory allocation can be problematic. Heap allocations and deallocations occupy valuable CPU cycles. Memory usage becomes nondeterministic, which can result in a system crashing without a clear culprit.
To keep Pigweed portable, core Pigweed code is not permitted to dynamically
(heap) allocate memory, such as with malloc
or new
. All memory should be
allocated with automatic (stack) or static (global) storage duration. Pigweed
must not use C++ libraries that use dynamic allocation.
Projects that use Pigweed are free to use dynamic allocation, provided they have selected a target that enables the heap.
Naming#
Pigweed AI summary: This section outlines the naming conventions for entities in Pigweed, with additional requirements beyond the Google style guide. For C++ code, all code must be in the "pw" namespace, with private code in a source file or a namespace nested under "pw". Template arguments for non-type names should follow the "kCamelCase" naming convention. Trivial member accessors should be named with "snake_case()". Abstract base classes should be named generically, with derived types named specifically. For
Entities shall be named according to the Google style guide, with the following additional requirements.
C++ code#
Pigweed AI summary: This section provides guidelines for writing C++ code in the Pigweed namespace. All code must be in the "pw" namespace, with modules nested under it. Private code should be in a source file and placed in an anonymous namespace nested under "pw". If private code must be exposed in a header file, it must be in a namespace nested under "pw". Template arguments for non-type names should follow the "kCamelCase" naming convention. Trivial member accessors should be named with
All Pigweed C++ code must be in the
pw
namespace. Namespaces for modules should be nested underpw
. For example,pw::string::Format()
.Whenever possible, private code should be in a source (.cc) file and placed in anonymous namespace nested under
pw
.If private code must be exposed in a header file, it must be in a namespace nested under
pw
. The namespace may be named for its subsystem or use a name that designates it as private, such asinternal
.Template arguments for non-type names (e.g.
template <int kFooBar>
) should follow the constexpr and const variable Google naming convention, which means k prefixed camel case (e.g.kCamelCase
). This matches the Google C++ style for variable naming, however the wording in the official style guide isn’t explicit for template arguments and could be interpreted to usefoo_bar
style naming. For consistency with other variables whose value is always fixed for the duration of the program, the naming convention iskCamelCase
, and so that is the style we use in Pigweed.Trivial membor accessors should be named with
snake_case()
. The Google C++ style allows eithersnake_case()
orCapsCase()
, but Pigweed always usessnake_case()
.Abstract base classes should be named generically, with derived types named specifically. For example,
Stream
is an abstract base, andSocketStream
andStdioStream
are an implementations of that interface. Any prefix or postfix indicating whether something is abstract or concrete is not permitted; for example,IStream
orSocketStreamImpl
are both not permitted. These pre-/post-fixes add additional visual noise and are irrelevant to consumers of these interfaces.
C code#
Pigweed AI summary: This section provides guidelines for naming conventions in C code within Pigweed. C symbols should be prefixed with the module name or "pw" if not associated with a module. Public names used by C code must be prefixed with the module name, while private names must be prefixed with an underscore followed by the module name. C source files should be avoided in Pigweed, and instead, C++ code with C linkage using "extern C" should be used. The C prefix rules apply to functions, variables
In general, C symbols should be prefixed with the module name. If the symbol is
not associated with a module, use just pw
as the module name. Facade
backends may chose to prefix symbols with the facade’s name to help reduce the
length of the prefix.
Public names used by C code must be prefixed with the module name (e.g.
pw_tokenizer_*
).If private code must be exposed in a header, private names used by C code must be prefixed with an underscore followed by the module name (e.g.
_pw_assert_*
).Avoid writing C source (.c) files in Pigweed. Prefer to write C++ code with C linkage using
extern "C"
. Within C source, private C functions and variables must be named with the_pw_my_module_*
prefix and should be declaredstatic
whenever possible; for example,_pw_my_module_MyPrivateFunction
.The C prefix rules apply to
C functions (
int pw_foo_FunctionName(void);
),variables used by C code (
int pw_foo_variable_name;
),constant variables used by C code (
const int pw_foo_kConstantName;
),structs used by C code (
typedef struct {} pw_foo_StructName;
), andall of the above for
extern "C"
names in C++ code.
The prefix does not apply to struct members, which use normal Google style.
Preprocessor macros#
Pigweed AI summary: This section discusses the naming conventions for preprocessor macros in Pigweed. Public macros must be prefixed with the module name, while private macros must be prefixed with an underscore followed by the module name. The example provided shows how to use these naming conventions in C++ and C code. For more details on macro usage, refer to the Preprocessor macros section in the Pigweed style guide.
Public Pigweed macros must be prefixed with the module name (e.g.
PW_MY_MODULE_*
).Private Pigweed macros must be prefixed with an underscore followed by the module name (e.g.
_PW_MY_MODULE_*
). (This style may change, see b/234886184).
Example
namespace pw::my_module {
namespace nested_namespace {
// C++ names (types, variables, functions) must be in the pw namespace.
// They are named according to the Google style guide.
constexpr int kGlobalConstant = 123;
// Prefer using functions over extern global variables.
extern int global_variable;
class Class {};
void Function();
extern "C" {
// Public Pigweed code used from C must be prefixed with pw_.
extern const int pw_my_module_kGlobalConstant;
extern int pw_my_module_global_variable;
void pw_my_module_Function(void);
typedef struct {
int member_variable;
} pw_my_module_Struct;
// Private Pigweed code used from C must be prefixed with _pw_.
extern const int _pw_my_module_kPrivateGlobalConstant;
extern int _pw_my_module_private_global_variable;
void _pw_my_module_PrivateFunction(void);
typedef struct {
int member_variable;
} _pw_my_module_PrivateStruct;
} // extern "C"
// Public macros must be prefixed with PW_.
#define PW_MY_MODULE_PUBLIC_MACRO(arg) arg
// Private macros must be prefixed with _PW_.
#define _PW_MY_MODULE_PRIVATE_MACRO(arg) arg
} // namespace nested_namespace
} // namespace pw::my_module
See Preprocessor macros for details about macro usage.
Namespace scope formatting#
Pigweed AI summary: This section outlines the formatting rules for namespace scope in C++ code. Non-indented blocks such as namespaces, "extern C" blocks, and preprocessor conditionals must have a comment on their closing line with the contents of the starting line. Nested namespaces should be declared together with no blank lines between them. An example code snippet is provided to illustrate these rules.
All non-indented blocks (namespaces, extern "C"
blocks, and preprocessor
conditionals) must have a comment on their closing line with the
contents of the starting line.
All nested namespaces should be declared together with no blank lines between them.
#include "some/header.h"
namespace pw::nested {
namespace {
constexpr int kAnonConstantGoesHere = 0;
} // namespace
namespace other {
const char* SomeClass::yes = "no";
bool ThisIsAFunction() {
#if PW_CONFIG_IS_SET
return true;
#else
return false;
#endif // PW_CONFIG_IS_SET
}
extern "C" {
const int pw_kSomeConstant = 10;
int pw_some_global_variable = 600;
void pw_CFunction() { ... }
} // extern "C"
} // namespace
} // namespace pw::nested
Using directives for literals#
Pigweed AI summary: Using directives for literals, such as "std::chrono_literals" or "pw::bytes::unit_literals," are only allowed in implementation files and cannot contain any symbols other than literals. This guidance does not affect using-declarations. The rationale behind this is that literals improve code readability by making units clearer at the point of definition. An example of an allowed using directive is "using namespace std::literals::chrono_literals."
Using-directives (e.g.
using namespace ...
) are permitted in implementation files only for the
purposes of importing literals such as std::chrono_literals
or
pw::bytes::unit_literals
. Namespaces that contain any symbols other than
literals are not permitted in a using-directive. This guidance also has no
impact on using-declarations
(e.g. using foo::Bar;
).
Rationale: Literals improve code readability, making units clearer at the point of definition.
using namespace std::chrono; // Not allowed
using namespace std::literals::chrono_literals; // Allowed
constexpr std::chrono::duration delay = 250ms;
Pointers and references#
Pigweed AI summary: This section discusses pointers and references in programming. It advises placing the asterisk or ampersand next to the type for pointer and reference types. It also recommends using references over pointers whenever possible, unless the pointer may change its target or be null. Examples of pointer and reference usage are provided in the code block.
For pointer and reference types, place the asterisk or ampersand next to the type.
int* const number = &that_thing;
constexpr const char* kString = "theory!"
bool FindTheOneRing(const Region& where_to_look) { ... }
Prefer storing references over storing pointers. Pointers are required when the
pointer can change its target or may be nullptr
. Otherwise, a reference or
const reference should be used.
Preprocessor macros#
Pigweed AI summary: This document provides guidelines for using preprocessor macros in C++ code. Macros should only be used when they improve code readability, robustness, safety, or provide features not possible with standard C++. When macros are needed, they should be accompanied by extensive tests to ensure they are hard to use wrong. Standalone statement macros must require the caller to terminate the macro invocation with a semicolon. Private macros in public headers must be prefixed with "_PW_" to prevent collisions with downstream users. Macros within .
Macros should only be used when they significantly improve upon the C++ code they replace. Macros should make code more readable, robust, and safe, or provide features not possible with standard C++, such as stringification, line number capturing, or conditional compilation. When possible, use C++ constructs like constexpr variables in place of macros. Never use macros as constants, except when a string literal is needed or the value must be used by C code.
When macros are needed, the macros should be accompanied with extensive tests to ensure the macros are hard to use wrong.
Stand-alone statement macros#
Pigweed AI summary: This section discusses the proper way to use stand-alone statement macros in Pigweed's macro style. Macros that are standalone statements must require the caller to terminate the macro invocation with a semicolon. The section provides examples of bad and good macro styles and suggests using a do-while loop or a static_assert declaration statement to ensure the macro is terminated with a semicolon.
Macros that are standalone statements must require the caller to terminate the macro invocation with a semicolon (see Swalling the Semicolon). For example, the following does not conform to Pigweed’s macro style:
// BAD! Definition has built-in semicolon.
#define PW_LOG_IF_BAD(mj) \
CallSomeFunction(mj);
// BAD! Compiles without error; semicolon is missing.
PW_LOG_IF_BAD("foo")
Here’s how to do this instead:
// GOOD; requires semicolon to compile.
#define PW_LOG_IF_BAD(mj) \
CallSomeFunction(mj)
// GOOD; fails to compile due to lacking semicolon.
PW_LOG_IF_BAD("foo")
For macros in function scope that do not already require a semicolon, the
contents can be placed in a do { ... } while (0)
loop.
#define PW_LOG_IF_BAD(mj) \
do { \
if (mj.Bad()) { \
Log(#mj " is bad") \
} \
} while (0)
Standalone macros at global scope that do not already require a semicolon can
add a static_assert
declaration statement as their last line.
#define PW_NEAT_THING(thing) \
bool IsNeat_##thing() { return true; } \
static_assert(true, "Macros must be terminated with a semicolon")
Private macros in public headers#
Pigweed AI summary: This section discusses the use of private macros in public headers and the importance of prefixing them with "_PW_" to prevent collisions with downstream users, even if they are undefined after use. An example is provided to illustrate this concept.
Private macros in public headers must be prefixed with _PW_
, even if they
are undefined after use; this prevents collisions with downstream users. For
example:
#define _PW_MY_SPECIAL_MACRO(op) ...
...
// Code that uses _PW_MY_SPECIAL_MACRO()
...
#undef _PW_MY_SPECIAL_MACRO
Macros in private implementation files (.cc)#
Pigweed AI summary: This section discusses the use of macros in private implementation files (.cc) and suggests that macros that are only used within one file should be undefined after their last use. It provides an example of a macro for defining operators and includes a static assertion to ensure that macros are terminated with a semicolon. The section concludes by showing how to undefine the macro.
Macros within .cc files that should only be used within one file should be undefined after their last use; for example:
#define DEFINE_OPERATOR(op) \
T operator ## op(T x, T y) { return x op y; } \
static_assert(true, "Macros must be terminated with a semicolon") \
DEFINE_OPERATOR(+);
DEFINE_OPERATOR(-);
DEFINE_OPERATOR(/);
DEFINE_OPERATOR(*);
#undef DEFINE_OPERATOR
Preprocessor conditional statements#
Pigweed AI summary: This section discusses the use of preprocessor conditional statements in C++ programming. It recommends using #if over #ifdef for conditional compilation with macros, as #if checks the value of the macro rather than just whether it exists. The section also explains how #if handles undefined macros and evaluates false for macros defined as 0, while #ifdef evaluates true. Macros defined using compiler flags have a default value of 1 in GCC and Clang, so they work equivalently for #if and #ifdef
When using macros for conditional compilation, prefer to use #if
over
#ifdef
. This checks the value of the macro rather than whether it exists.
#if
handles undefined macros equivalently to#ifdef
. Undefined macros expand to 0 in preprocessor conditional statements.#if
evaluates false for macros defined as 0, while#ifdef
evaluates true.Macros defined using compiler flags have a default value of 1 in GCC and Clang, so they work equivalently for
#if
and#ifdef
.Macros defined to an empty statement cause compile-time errors in
#if
statements, which avoids ambiguity about how the macro should be used.
All #endif
statements should be commented with the expression from their
corresponding #if
. Do not indent within preprocessor conditional statements.
#if USE_64_BIT_WORD
using Word = uint64_t;
#else
using Word = uint32_t;
#endif // USE_64_BIT_WORD
Unsigned integers#
Pigweed AI summary: Pigweed allows the use of unsigned integers, but it is important to maintain consistency with existing code and the C++ Standard Library. Mixing signed and unsigned integers should be done with caution.
Unsigned integers are permitted in Pigweed. Aim for consistency with existing code and the C++ Standard Library. Be very careful mixing signed and unsigned integers.
Features not in the C++ standard#
Pigweed AI summary: The article advises avoiding features not available in standard C++, including compiler extensions and features from other standards like POSIX. It suggests using standard alternatives like ptrdiff_t instead of POSIX's ssize_t, and avoiding POSIX functions with suitable standard or Pigweed alternatives.
Avoid features not available in standard C++. This includes compiler extensions and features from other standards like POSIX.
For example, use ptrdiff_t
instead of POSIX’s ssize_t
, unless
interacting with a POSIX API in intentionally non-portable code. Never use
POSIX functions with suitable standard or Pigweed alternatives, such as
strnlen
(use pw::string::NullTerminatedLength
instead).
Code Owners (OWNERS)#
Pigweed AI summary: The Pigweed tool can help enforce consistent styling and detect errors in files hosted on Gerrit with the code-owners plug-in enabled. The tool follows specific rules for grouping and sorting content, and it will act upon any file named "OWNERS" by default.
If you use Gerrit for source code hosting and have the code-owners plug-in enabled Pigweed can help you enforce consistent styling on those files and also detects some errors.
The styling follows these rules.
Content is grouped by type of line (Access grant, include, etc).
Each grouping is sorted alphabetically.
Groups are placed the following order with a blank line separating each grouping.
“set noparent” line
“include” lines
“file:” lines
user grants (some examples: “*”, “foo@example.com”)
“per-file:” lines
This plugin will, by default, act upon any file named “OWNERS”.
Python style#
Pigweed AI summary: Pigweed follows the standard Python style, PEP8, and all Python code should pass "pw format" which uses "black" with specific options. Pigweed officially supports a few Python versions and all upstream code must support those versions, with the exception of pw_env_setup which must also support Python 2 and 3.6.
Pigweed uses the standard Python style: PEP8, which is available on the web at
https://www.python.org/dev/peps/pep-0008/. All Pigweed Python code should pass
pw format
, which invokes black
with a couple options.
Python versions#
Pigweed AI summary: Pigweed supports a few Python versions and all upstream code must also support those versions, except for pw_env_setup which must also support Python 2 and 3.6.
Pigweed officially supports a few Python versions. Upstream Pigweed code must support those Python versions. The only exception is pw_env_setup, which must also support Python 2 and 3.6.
Build files: GN#
Pigweed AI summary: This section discusses the GN build files required for each Pigweed source module, which encapsulate build targets and specify their sources and dependencies. The format of GN build files is similar to Bazel's BUILD files, and C/C++ build targets include fields such as public header files, source files, and dependencies. Assets within each field must be listed in alphabetical order. The section provides an example of a GN build file and its components.
Each Pigweed source module requires a GN build file named BUILD.gn. This encapsulates the build targets and specifies their sources and dependencies. GN build files use a format similar to Bazel’s BUILD files (see the Bazel style guide).
C/C++ build targets include a list of fields. The primary fields are:
<public>
– public header files<sources>
– source files and private header files<public_configs>
– public build configuration<configs>
– private build configuration<public_deps>
– public dependencies<deps>
– private dependencies
Assets within each field must be listed in alphabetical order.
# Here is a brief example of a GN build file.
import("$dir_pw_unit_test/test.gni")
config("public_include_path") {
include_dirs = [ "public" ]
visibility = [":*"]
}
pw_source_set("pw_sample_module") {
public = [ "public/pw_sample_module/sample_module.h" ]
sources = [
"public/pw_sample_module/internal/secret_header.h",
"sample_module.cc",
"used_by_sample_module.cc",
]
public_configs = [ ":public_include_path" ]
public_deps = [ dir_pw_status ]
deps = [ dir_pw_varint ]
}
pw_test_group("tests") {
tests = [ ":sample_module_test" ]
}
pw_test("sample_module_test") {
sources = [ "sample_module_test.cc" ]
deps = [ ":sample_module" ]
}
pw_doc_group("docs") {
sources = [ "docs.rst" ]
}
Build files: Bazel#
Pigweed AI summary: Build files for the Bazel build system must be named BUILD.bazel to avoid ambiguity with other build systems or tooling. Pigweed's Bazel files follow the Bazel style guide.
Build files for the Bazel build system must be named BUILD.bazel
. Bazel can
interpret files named just BUILD
, but Pigweed uses BUILD.bazel
to avoid
ambiguity with other build systems or tooling.
Pigweed’s Bazel files follow the Bazel style guide.
Documentation#
Pigweed AI summary: Pigweed's documentation is written using the reStructuredText markup language and processed by Sphinx. They use the Furo theme along with the sphinx-design extension. The documentation style guide is not yet fully implemented, so when updating the docs, they should be updated to match the style guide. The documentation includes guidelines for headings, directives, tables, code snippets, generating API documentation from source, Doxygen syntax, cross-references, and status codes in Doxygen comments.
Note
Pigweed’s documentation style guide came after much of the documentation was written, so Pigweed’s docs don’t yet 100% conform to this style guide. When updating docs, please update them to match the style guide.
Pigweed documentation is written using the reStructuredText markup language and processed by Sphinx. We use the Furo theme along with the sphinx-design extension.
Syntax Reference Links#
Pigweed AI summary: The article discusses the syntax reference links for reStructuredText (ReST), a flexible markup language used for creating structured documents. The links provided include the ReST Primer, ReST Directives, Furo Reference, and Sphinx-design Reference. The article also mentions the restrictions imposed by Pigweed to ensure consistency in documentation.
ReST is flexible, supporting formatting the same logical document in a few ways (for example headings, blank lines). Pigweed has the following restrictions to make our documentation consistent.
Headings#
Pigweed AI summary: This text provides guidelines for using headings in ReST syntax, including the hierarchy of headings and the characters to use for each level. It also emphasizes the importance of not putting blank lines after headings and not putting multiple blank lines before a heading. Examples are provided for correct and incorrect usage.
Use headings according to the following hierarchy, with the shown characters for the ReST heading syntax.
==================================
Document Title: Two Bars of Equals
==================================
Document titles use equals ("====="), above and below. Capitalize the words
in the title, except for 'a', 'of', and 'the'.
---------------------------
Major Sections Within a Doc
---------------------------
Major sections use hyphens ("----"), above and below. Capitalize the words in
the title, except for 'a', 'of', and 'the'.
Heading 1 - For Sections Within a Doc
=====================================
These should be title cased. Use a single equals bar ("====").
Heading 2 - for subsections
---------------------------
Subsections use hyphens ("----"). In many cases, these headings may be
sentence-like. In those cases, only the first letter should be capitalized.
For example, FAQ subsections would have a title with "Why does the X do the
Y?"; note the sentence capitalization (but not title capitalization).
Heading 3 - for subsubsections
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Use the caret symbol ("^^^^") for subsubsections.
Note: Generally don't go beyond heading 3.
Heading 4 - for subsubsubsections
.................................
Don't use this heading level, but if you must, use period characters
("....") for the heading.
Do not put blank lines after headings.#
Pigweed AI summary: This section provides guidelines on not putting blank lines after headings in plain text paragraphs. It includes examples of correct and incorrect formatting, with admonitions highlighting the importance of avoiding unnecessary blank lines.
Yes: No blank after heading
Here is a heading
-----------------
Note that there is no blank line after the heading separator!
No: Unnecessary blank line
Here is a heading
-----------------
There is a totally unnecessary blank line above this one. Don't do this.
Do not put multiple blank lines before a heading.#
Pigweed AI summary: This section provides guidelines on how to format headings in plain text documents. It advises against using multiple blank lines before a heading and recommends using just one blank line after the section content before the next heading. The section includes examples of correct and incorrect formatting.
Yes: Just one blank after section content before the next heading
There is some text here in the section before the next. It's just here to
illustrate the spacing standard. Note that there is just one blank line
after this paragraph.
Just one blank!
---------------
There is just one blank line before the heading.
No: Extra blank lines
There is some text here in the section before the next. It's just here to
illustrate the spacing standard. Note that there are too many blank lines
after this paragraph; there should be just one.
Too many blanks
---------------
There are too many blanks before the heading for this section.
Directives#
Pigweed AI summary: This section provides guidelines for formatting directives in plain text. Directives should be indented three spaces and have a blank line between the directive and its content to align the content with the directive name. Nested directives should also follow this indentation. The section also includes examples of incorrect formatting, such as using one, two, or four spaces for indentation or omitting the blank line between the directive and content.
Indent directives 3 spaces; and put a blank line between the directive and the content. This aligns the directive content with the directive name.
Yes: Three space indent for directives; and nested
Here is a paragraph that has some content. After this content is a
directive.
.. my_directive::
Note that this line's start aligns with the "m" above. The 3-space
alignment accounts for the ".. " prefix for directives, to vertically
align the directive name with the content.
This indentation must continue for nested directives.
.. nested_directive::
Here is some nested directive content.
No: One space, two spaces, four spaces, or other indents for directives
Here is a paragraph with some content.
.. my_directive::
The indentation here is incorrect! It's one space short; doesn't align
with the directive name above.
.. nested_directive::
This isn't indented correctly either; it's too much (4 spaces).
No: Missing blank between directive and content.
Here is a paragraph with some content.
.. my_directive::
Note the lack of blank line above here.
Tables#
Pigweed AI summary: The article suggests using the <literal>.. list-table::</literal> syntax for complex tables as it is more maintainable and easier to edit.
Consider using .. list-table::
syntax, which is more maintainable and
easier to edit for complex tables (details).
Code Snippets#
Pigweed AI summary: This section provides guidance on using code blocks from actual source code files in Sphinx documentation to keep it fresh and avoid duplicate code examples. The literalinclude directive is recommended for creating code blocks from source files, with options to include entire files or subsections. An example is provided with the source file and rendered output.
Use code blocks from actual source code files wherever possible. This helps keep documentation fresh and removes duplicate code examples. There are a few ways to do this with Sphinx.
The literalinclude directive creates a code blocks from source files. Entire
files can be included or a just a subsection. The best way to do this is with
the :start-after:
and :end-before:
options.
Example:
Documentation Source (.rst
file)
.. literalinclude:: run_doxygen.py
:start-after: [doxygen-environment-variables]
:end-before: [doxygen-environment-variables]
Source File
# DOCSTAG: [doxygen-environment-variables]
env = os.environ.copy()
env['PW_DOXYGEN_OUTPUT_DIRECTORY'] = str(output_dir.resolve())
env['PW_DOXYGEN_INPUT'] = ' '.join(pw_module_list)
env['PW_DOXYGEN_PROJECT_NAME'] = 'Pigweed'
# DOCSTAG: [doxygen-environment-variables]
Rendered Output
env = os.environ.copy()
env['PW_DOXYGEN_OUTPUT_DIRECTORY'] = str(output_dir.resolve())
env['PW_DOXYGEN_INPUT'] = ' '.join(pw_module_list)
env['PW_DOXYGEN_PROJECT_NAME'] = 'Pigweed'
Generating API documentation from source#
Pigweed AI summary: The paragraph discusses the importance of documenting APIs in the source code and using Sphinx to generate documentation. It provides examples of how to include Python API documentation and argparse command line help using autodoc directives and argparse directive. It also mentions the use of Doxygen comments in C, C++, and Java and how to bring them into Sphinx using Breathe. The paragraph also explains the syntax and usage of Doxygen commands and cross-references in Doxygen comments. Finally, it provides guidance on how to
Whenever possible, document APIs in the source code and use Sphinx to generate documentation for them. This keeps the documentation in sync with the code and reduces duplication.
Python#
Pigweed AI summary: This section provides instructions on how to include Python API documentation and argparse command line help in Sphinx documentation using autodoc directives and the argparse directive respectively. It includes examples of how to use these directives in literal blocks.
Include Python API documentation from docstrings with autodoc directives. Example:
.. automodule:: pw_cli.log
:members:
.. automodule:: pw_console.embed
:members: PwConsoleEmbed
:undoc-members:
:show-inheritance:
.. autoclass:: pw_console.log_store.LogStore
:members: __init__
:undoc-members:
:show-inheritance:
Include argparse command line help with the argparse directive. Example:
.. argparse::
:module: pw_watch.watch
:func: get_parser
:prog: pw watch
:nodefaultconst:
:nodescription:
:noepilog:
Doxygen#
Pigweed AI summary: Doxygen comments in C, C++, and Java can be surfaced in Sphinx using Breathe. To process source files with Doxygen comment blocks, they must be added to the `_doxygen_input_files` list in `//docs/BUILD.gn`. Breathe provides various directives for bringing Doxygen comments into Sphinx, such as `doxygenfile`, `doxygenclass`, `doxygentypedef`, `doxygenfunction`, and `doxygendefine`.
Doxygen comments in C, C++, and Java are surfaced in Sphinx using Breathe.
Note
Sources with doxygen comment blocks must be added to the
_doxygen_input_files
list in //docs/BUILD.gn
to be processed.
Breathe provides various directives for bringing Doxygen comments into Sphinx. These include the following:
doxygenfile – Documents a source file. May limit to specific types of symbols with
:sections:
... doxygenfile:: pw_rpc/internal/config.h :sections: define, func
doxygenclass – Documents a class and optionally its members.
.. doxygenclass:: pw::sync::BinarySemaphore :members:
doxygentypedef – Documents an alias (
typedef
orusing
statement)... doxygentypedef:: pw::Function
doxygenfunction – Documents a source file. Can be filtered to limit to specific types of symbols.
.. doxygenfunction:: pw::tokenizer::EncodeArgs
doxygendefine – Documents a preprocessor macro.
.. doxygendefine:: PW_TOKENIZE_STRING
Example Doxygen Comment Block#
Pigweed AI summary: This paragraph is an example of a Doxygen comment block. It provides documentation for the `PW_LOCK_RETURNED()` macro and describes how to use it. The comment block includes various features such as cross-references to other symbols, parameter descriptions, return value explanations, reStructuredText blocks, warning admonitions, and code examples. The comment block also includes a macro definition for `PW_LOCK_RETURNED()`, which is used to attribute a lock returned by a function.
Start a Doxygen comment block using ///
(three forward slashes).
/// This is the documentation comment for the `PW_LOCK_RETURNED()` macro. It
/// describes how to use the macro.
///
/// Doxygen comments can refer to other symbols using Sphinx cross
/// references. For example, @cpp_class{pw::InlineBasicString}, which is
/// shorthand for @crossref{cpp,class,pw::InlineBasicString}, links to a C++
/// class. @crossref{py,func,pw_tokenizer.proto.detokenize_fields} links to a
/// Python function.
///
/// @param[out] dest The memory area to copy to.
/// @param[in] src The memory area to copy from.
/// @param[in] n The number of bytes to copy
///
/// @retval OK KVS successfully initialized.
/// @retval DATA_LOSS KVS initialized and is usable, but contains corrupt data.
/// @retval UNKNOWN Unknown error. KVS is not initialized.
///
/// @rst
/// The ``@rst`` and ``@endrst`` commands form a block block of
/// reStructuredText that is rendered in Sphinx.
///
/// .. warning::
/// this is a warning admonition
///
/// .. code-block:: cpp
///
/// void release(ptrdiff_t update = 1);
/// @endrst
///
/// Example code block using Doxygen markup below. To override the language
/// use `@code{.cpp}`
///
/// @code
/// class Foo {
/// public:
/// Mutex* mu() PW_LOCK_RETURNED(mu) { return μ }
///
/// private:
/// Mutex mu;
/// };
/// @endcode
///
/// @b The first word in this sentence is bold (The).
///
#define PW_LOCK_RETURNED(x) __attribute__((lock_returned(x)))
Doxygen Syntax#
Pigweed AI summary: This section provides information on Doxygen syntax and commands that may be needed when RST cannot be used. It lists common Doxygen commands for use within a comment block, including @rst, @code, @param, @pre, @post, @return, @retval, and @note. It also explains when to use structural commands and provides an example of grouping multiple symbols into a single comment block. A reference to all Doxygen commands is also included.
Pigweed prefers to use RST wherever possible, but there are a few Doxygen syntatic elements that may be needed.
Common Doxygen commands for use within a comment block:
@rst
To start a reStructuredText block. This is a custom alias for\verbatim embed:rst:leading-asterisk
.@code Start a code block.
@param Document parameters, this may be repeated.
@pre Starts a paragraph where the precondition of an entity can be described.
@post Starts a paragraph where the postcondition of an entity can be described.
@return Single paragraph to describe return value(s).
@retval Document return values by name. This is rendered as a definition list.
@note Add a note admonition to the end of documentation.
@b To bold one word.
Doxygen provides structural commands that associate a
comment block with a particular symbol. Example of these include @class
,
@struct
, @def
, @fn
, and @file
. Do not use these unless
necessary, since they are redundant with the declarations themselves.
One case where structural commands are necessary is when a single comment block describes multiple symbols. To group multiple symbols into a single comment block, include a structural commands for each symbol on its own line. For example, the following comment documents two macros:
/// @def PW_ASSERT_EXCLUSIVE_LOCK
/// @def PW_ASSERT_SHARED_LOCK
///
/// Documents functions that dynamically check to see if a lock is held, and
/// fail if it is not held.
See also
Cross-references#
Pigweed AI summary: Pigweed provides Doxygen aliases for creating Sphinx cross references within Doxygen comments. These aliases should be used when referring to other symbols, such as functions, classes, or macros. The basic alias is "@crossref", which supports any Sphinx domain. For readability, aliases for commonly used types are provided. There are also advantages to using Sphinx cross references over Doxygen references, such as consistent formatting and the ability to refer to symbols that have not yet been documented. Cross reference links can be created
Pigweed provides Doxygen aliases for creating Sphinx cross references within Doxygen comments. These should be used when referring to other symbols, such as functions, classes, or macros.
The basic alias is @crossref
, which supports any Sphinx domain.
For readability, aliases for commonnly used types are provided.
@crossref{domain,type,identifier}
Inserts a cross reference of any type in any Sphinx domain. For example,@crossref{c,func,foo}
is equivalent to:c:func:`foo`
and links to the documentation for the C functionfoo
, if it exists.@c_macro{identifier}
Equivalent to:c:macro:`identifier`
.@cpp_func{identifier}
Equivalent to:cpp:func:`identifier`
.@cpp_class{identifier}
Equivalent to:cpp:class:`identifier`
.@cpp_type{identifier}
Equivalent to:cpp:type:`identifier`
.
Note
Use the @ aliases described above for all cross references. Doxygen provides other methods for cross references, but Sphinx cross references offer several advantages:
Sphinx cross references work for all identifiers known to Sphinx, including those documented with e.g.
.. cpp:class::
or extracted from Python. Doxygen references can only refer to identifiers known to Doxygen.Sphinx cross references always use consistent formatting. Doxygen cross references sometimes render as plain text instead of code-style monospace, or include
()
in macros that shouldn’t have them.Sphinx cross references can refer to symbols that have not yet been documented. They will be formatted correctly and become links once the symbols are documented.
Using Sphinx cross references in Doxygen comments makes cross reference syntax more consistent within Doxygen comments and between RST and Doxygen.
Create cross reference links elsewhere in the document to symbols documented
with Doxygen using standard Sphinx cross references, such as :cpp:class:
and
:cpp:func:
.
- :cpp:class:`pw::sync::BinarySemaphore::BinarySemaphore`
- :cpp:func:`pw::sync::BinarySemaphore::try_acquire`
Status codes in Doxygen comments#
Pigweed AI summary: When writing Doxygen comments in C++ header files, use the syntax "@pw_status{YOUR_STATUS_CODE_HERE}" to refer to pw_status codes. Replace "YOUR_STATUS_CODE_HERE" with a valid pw_status code. This syntax ensures that Doxygen links back to the status code's reference documentation in pw_status.
Use the following syntax when referring to pw_status
codes in Doxygen
comments:
@pw_status{YOUR_STATUS_CODE_HERE}
Replace YOUR_STATUS_CODE_HERE
with a valid pw_status
code.
This syntax ensures that Doxygen links back to the status code’s reference documentation in pw_status.
Note
The guidance in this section only applies to Doxygen comments in C++ header files.
Commit message#
Pigweed AI summary: The given text is a set of guidelines for writing commit messages in the Pigweed project. It provides recommendations on the length, format, and content of commit messages. It also includes examples of well-formed and poorly-formed commit messages. Additionally, the text explains the use of footers and the copy-to-clipboard feature on code blocks. It also introduces the use of tabs to group related content together.
Pigweed commit message bodies and summaries are limited to 72 characters wide to improve readability. Commit summaries should also be prefixed with the name of the module that the commit is affecting. Examples of well and ill-formed commit messages are provided below.
Consider the following when writing a commit message:
Documentation and comments are better - Consider whether the commit message contents would be better expressed in the documentation or code comments. Docs and code comments are durable and readable later; commit messages are rarely read after the change lands.
Include why the change is made, not just what the change is - It is important to include a “why” component in most commits. Sometimes, why is evident - for example, reducing memory usage, or optimizing. But it is often not. Err on the side of over-explaining why, not under-explaining why.
Pigweed commit messages should conform to the following style:
Yes:
pw_some_module: Short capitalized description
Details about the change here. Include a summary of the what, and a clear
description of why the change is needed for future maintainers.
Consider what parts of the commit message are better suited for
documentation.
Yes: Small number of modules affected; use {} syntax.
pw_{foo, bar, baz}: Change something in a few places
When changes cross a few modules, include them with the syntax shown
above.
Yes: Targets are effectively modules, even though they’re
nested, so they get a /
character.
targets/xyz123: Tweak support for XYZ's PQR
Yes: Uses imperative style for subject and text.
pw_something: Add foo and bar functions
This commit correctly uses imperative present-tense style.
No: Uses non-imperative style for subject and text.
pw_something: Adds more things
Use present tense imperative style for subjects and commit. The above
subject has a plural "Adds" which is incorrect; should be "Add".
Yes: Use bulleted lists when multiple changes are in a single CL. Prefer smaller CLs, but larger CLs are a practical reality.
pw_complicated_module: Pre-work for refactor
Prepare for a bigger refactor by reworking some arguments before the larger
change. This change must land in downstream projects before the refactor to
enable a smooth transition to the new API.
- Add arguments to MyImportantClass::MyFunction
- Update MyImportantClass to handle precondition Y
- Add stub functions to be used during the transition
No: Run on paragraph instead of bulleted list
pw_foo: Many things in a giant BWOT
This CL does A, B, and C. The commit message is a Big Wall Of Text
(BWOT), which we try to discourage in Pigweed. Also changes X and Y,
because Z and Q. Furthermore, in some cases, adds a new Foo (with Bar,
because we want to). Also refactors qux and quz.
No: Doesn’t capitalize the subject
pw_foo: do a thing
Above subject is incorrect, since it is a sentence style subject.
Yes: Doesn’t capitalize the subject when subject’s first word is a lowercase identifier.
pw_foo: std::unique_lock cleanup
This commit message demonstrates the subject when the subject has an
identifier for the first word. In that case, follow the identifier casing
instead of capitalizing.
However, imperative style subjects often have the identifier elsewhere in the subject; for example:
pw_foo: Improve use of std::unique_lock
No: Uses a non-standard []
to indicate module:
[pw_foo]: Do a thing
No: Has a period at the end of the subject
pw_bar: Do something great.
No: Puts extra stuff after the module which isn’t a module.
pw_bar/byte_builder: Add more stuff to builder
Copy-to-clipboard feature on code blocks#
Pigweed AI summary: The copy-to-clipboard feature on code blocks is made possible by sphinx-copybutton, which automatically removes the input prompt symbol "$". While there is currently no implemented workflow for manually removing the copy-to-clipboard button for a specific code block, instructions can be found in the "Remove copybuttons using a CSS selector" section of the sphinx-copybutton documentation.
The copy-to-clipboard feature on code blocks is powered by sphinx-copybutton.
sphinx-copybutton
recognizes $
as an input prompt and automatically
removes it.
There is a workflow for manually removing the copy-to-clipboard button for a particular code block but it has not been implemented yet. See Remove copybuttons using a CSS selector.
Comments#
Pigweed AI summary: The article recommends using C++-style comments over C-style comments, except for inline comments. Code in comments should be indented with two additional spaces, and all code blocks must begin and end with an empty comment line. An example of code in comments is provided.
Prefer C++-style (
//
) comments over C-style comments (/* */
). C-style comments should only be used for inline comments.Indent code in comments with two additional spaces, making a total of three spaces after the
//
. All code blocks must begin and end with an empty comment line, even if the blank comment line is the last line in the block.