blob: 285ded8b906c20c794123779b3f66d1afe5b4a09 [file] [log] [blame]
Keir Mierle2c1e56b2019-11-15 16:32:11 -08001.. _chapter-style:
2
3.. default-domain:: cpp
4
5.. highlight:: sh
6
7===========================
8Style Guide and Conventions
9===========================
10
Armando Montanezf2bbb752020-03-03 09:50:37 -080011.. tip::
12 Pigweed runs ``pw format`` as part of ``pw presubmit`` to perform some code
13 formatting checks. To speed up the review process, consider adding ``pw
14 presubmit`` as a git push hook using the following command:
15 ``pw presubmit --install``
16
Keir Mierle2c1e56b2019-11-15 16:32:11 -080017---------
18C++ style
19---------
20
21The Pigweed C++ style guide is closely based on Google's external C++ Style
22Guide, which is found on the web at
23https://google.github.io/styleguide/cppguide.html. The Google C++ Style Guide
24applies to Pigweed except as described in this document.
25
26The Pigweed style guide only applies to Pigweed itself. It does not apply to
Alexei Frolov44d54732020-01-10 14:45:43 -080027projects that use Pigweed or to the third-party code included with Pigweed.
Keir Mierle2c1e56b2019-11-15 16:32:11 -080028Non-Pigweed code is free to use features restricted by Pigweed, such as dynamic
29memory allocation and the entirety of the C++ Standard Library.
30
31Recommendations in the :doc:`embedded_cpp_guide` are considered part of the
32Pigweed style guide, but are separated out since it covers more general
33embedded development beyond just C++ style.
34
35Automatic formatting
36====================
37Pigweed uses `clang-format <https://clang.llvm.org/docs/ClangFormat.html>`_ to
38automatically format Pigweed source code. A ``.clang-format`` configuration is
39provided with the Pigweed repository.
40
41Automatic formatting is essential to facilitate large-scale, automated changes
42in Pigweed. Therefore, all code in Pigweed is expected to be formatted with
43``clang-format`` prior to submission. Existing code may be reformatted at any
44time.
45
46If ``clang-format`` formats code in an undesirable or incorrect way, it can be
47disabled for the affected lines by adding ``// clang-format off``.
48``clang-format`` must then be re-enabled with a ``// clang-format on`` comment.
49
50.. code-block:: cpp
51
52 // clang-format off
Alexei Frolov44d54732020-01-10 14:45:43 -080053 constexpr int kMyMatrix[] = {
Keir Mierle2c1e56b2019-11-15 16:32:11 -080054 100, 23, 0,
55 0, 542, 38,
56 1, 2, 201,
57 };
58 // clang-format on
59
60C Standard Library
61==================
62In C++ headers, always use the C++ versions of C Standard Library headers (e.g.
63``<cstdlib>`` instead of ``<stdlib.h>``). If the header is used by both C and
64C++ code, only the C header should be used.
65
66In C++ code, it is preferred to use C functions from the ``std`` namespace. For
67example, use ``std::memcpy`` instead of ``memcpy``. The C++ standard does not
68require the global namespace versions of the functions to be provided. Using
69``std::`` is more consistent with the C++ Standard Library and makes it easier
70to distinguish Pigweed functions from library functions.
71
72Within core Pigweed, do not use C standard library functions that allocate
73memory, such as ``std::malloc``. There are exceptions to this for when dynamic
74allocation is enabled for a system; Pigweed modules are allowed to add extra
75functionality when a heap is present; but this must be optional.
76
77C++ Standard Library
78====================
79Much of the C++ Standard Library is not a good fit for embedded software. Many
80of the classes and functions were not designed with the RAM, flash, and
81performance constraints of a microcontroller in mind. For example, simply
82adding the line ``#include <iostream>`` can increase the binary size by 150 KB!
Alexei Frolov44d54732020-01-10 14:45:43 -080083This is larger than many microcontrollers' entire internal storage.
Keir Mierle2c1e56b2019-11-15 16:32:11 -080084
85However, with appropriate caution, a limited set of standard C++ libraries can
86be used to great effect. Developers can leverage familiar, well-tested
87abstractions instead of writing their own. C++ library algorithms and classes
88can give equivalent or better performance than hand-written C code.
89
90A limited subset of the C++ Standard Library is permitted in Pigweed. To keep
91Pigweed small, flexible, and portable, functions that allocate dynamic memory
92must be avoided. Care must be exercised when using multiple instantiations of a
93template function, which can lead to code bloat.
94
95The following C++ Standard Library headers are always permitted:
96
97 * ``<array>``
98 * ``<complex>``
99 * ``<initializer_list>``
100 * ``<iterator>``
101 * ``<limits>``
102 * ``<optional>``
103 * ``<random>``
104 * ``<ratio>``
105 * ``<span>``
106 * ``<string_view>``
107 * ``<tuple>``
108 * ``<type_traits>``
109 * ``<utility>``
110 * ``<variant>``
111 * C Standard Library headers (``<c*>``)
112
113With caution, parts of the following headers can be used:
114
115 * ``<algorithm>`` -- be wary of potential memory allocation
116 * ``<atomic>`` -- not all MCUs natively support atomic operations
117 * ``<bitset>`` -- conversions to or from strings are disallowed
118 * ``<functional>`` -- do **not** use ``std::function``
119 * ``<new>`` -- for placement new
120 * ``<numeric>`` -- be wary of code size with multiple template instantiations
121
122Never use any of these headers:
123
124 * Dynamic containers (``<list>``, ``<map>``, ``<set>``, ``<vector>``, etc.)
125 * Streams (``<iostream>``, ``<ostream>``, ``<fstream>``, etc.)
126 * ``<exception>``
127 * ``<future>``, ``<mutex>``, ``<thread>``
128 * ``<memory>``
129 * ``<regex>``
130 * ``<scoped_allocator>``
131 * ``<sstream>``
132 * ``<stdexcept>``
133 * ``<string>``
134 * ``<valarray>``
135
136Headers not listed here should be carefully evaluated before they are used.
137
138These restrictions do not apply to third party code or to projects that use
139Pigweed.
140
141Combining C and C++
142===================
143Prefer to write C++ code over C code, using ``extern "C"`` for symbols that must
144have C linkage. ``extern "C"`` functions should be defined within C++
145namespaces to simplify referring to other code.
146
147C++ functions with no parameters do not include ``void`` in the parameter list.
148C functions with no parameters must include ``void``.
149
150.. code-block:: cpp
151
152 namespace pw {
153
154 bool ThisIsACppFunction() { return true; }
155
156 extern "C" int pw_ThisIsACFunction(void) { return -1; }
157
158 extern "C" {
159
160 int pw_ThisIsAlsoACFunction(void) {
161 return ThisIsACppFunction() ? 100 : 0;
162 }
163
164 } // extern "C"
165
166 } // namespace pw
167
168Comments
169========
170Prefer C++-style (``//``) comments over C-style commments (``/* */``). C-style
171comments should only be used for inline comments.
172
173.. code-block:: cpp
174
175 // Use C++-style comments, except where C-style comments are necessary.
176 // This returns a random number using an algorithm I found on the internet.
177 #define RANDOM_NUMBER() [] { \
178 return 4; /* chosen by fair dice roll */ \
179 }()
180
181Indent code in comments with two additional spaces, making a total of three
182spaces after the ``//``. All code blocks must begin and end with an empty
Alexei Frolov44d54732020-01-10 14:45:43 -0800183comment line, even if the blank comment line is the last line in the block.
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800184
185.. code-block:: cpp
186
187 // Here is an example of code in comments.
188 //
189 // int indentation_spaces = 2;
190 // int total_spaces = 3;
191 //
192 // engine_1.thrust = RANDOM_NUMBER() * indentation_spaces + total_spaces;
193 //
194 bool SomeFunction();
195
196Control statements
197==================
198All loops and conditional statements must use braces.
199
200The syntax ``while (true)`` if preferred over ``for (;;)`` for infinite loops.
201
202Include guards
203==============
204The first non-comment line of every header file must be ``#pragma once``. Do
205not use traditional macro include guards. The ``#pragma once`` should come
206directly after the Pigweed copyright block, with no blank line, followed by a
207blank, like this:
208
209.. code-block:: cpp
210
211 // Copyright 2019 The Pigweed Authors
212 //
213 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
Wyatt Hepler1a960942019-11-26 14:13:38 -0800214 // use this file except in compliance with the License. You may obtain a copy of
215 // the License at
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800216 //
217 // https://www.apache.org/licenses/LICENSE-2.0
218 //
219 // Unless required by applicable law or agreed to in writing, software
220 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
221 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
Wyatt Hepler1a960942019-11-26 14:13:38 -0800222 // License for the specific language governing permissions and limitations under
223 // the License.
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800224 #pragma once
225
226 // Header file-level comment goes here...
227
228Memory allocation
229=================
230Dynamic memory allocation can be problematic. Heap allocations and deallocations
231occupy valuable CPU cycles. Memory usage becomes nondeterministic, which can
232result in a system crashing without a clear culprit.
233
234To keep Pigweed portable, core Pigweed code is not permitted to dynamically
235(heap) allocate memory, such as with ``malloc`` or ``new``. All memory should be
236allocated with automatic (stack) or static (global) storage duration. Pigweed
237must not use C++ libraries that use dynamic allocation.
238
239Projects that use Pigweed are free to use dynamic allocation, provided they
240have selected a target that enables the heap.
241
242Naming
243======
244Entities shall be named according to the `Google style guide
245<https://google.github.io/styleguide/cppguide.html>`_, with the following
246additional requirements.
247
248**C++ code**
249 * All Pigweed C++ code must be in the ``pw`` namespace. Namespaces for
250 modules should be nested under ``pw``. For example,
251 ``pw::string::Format()``.
252 * Whenever possible, private code should be in a source (.cc) file and placed
253 in anonymous namespace nested under ``pw``.
254 * If private code must be exposed in a header file, it must be in a namespace
255 nested under ``pw``. The namespace may be named for its subsystem or use a
256 name that designates it as private, such as ``internal``.
257
258**C code**
259 * Public names used by C code must be prefixed with ``pw_``.
260 * If private code must be exposed in a header, private names used by C code
261 must be prefixed with ``_pw_``.
262 * Avoid writing C source (.c) files in Pigweed. Prefer to write C++ code with
263 C linkage using ``extern "C"``. Within C source, private C functions and
264 variables must be named with the ``_pw_`` prefix and should be declared
265 ``static`` whenever possible; for example, ``_pw__MyPrivateFunction``.
266 * The C prefix rules apply to
267
268 * C functions (``int pw_FunctionName(void);``),
269 * variables used by C code (``int pw_variable_name;``),
270 * constant variables used by C code (``int pw_kConstantName;``), and
271 * structs used by C code (``typedef struct {} pw_StructName;``).
272
273 The prefix does not apply to struct members, which use normal Google style.
274
275**Preprocessor macros**
276 * Public Pigweed macros must be prefixed with ``PW_``.
277 * Private Pigweed macros must be prefixed with ``_PW_``.
278
279**Example**
280
281.. code-block:: cpp
282
283 namespace pw {
284 namespace nested_namespace {
285
286 // C++ names (types, variables, functions) must be in the pw namespace.
287 // They are named according to the Google style guide.
288 constexpr int kGlobalConstant = 123;
289
290 // Prefer using functions over extern global variables.
291 extern int global_variable;
292
293 class Class {};
294
295 void Function();
296
297 extern "C" {
298
299 // Public Pigweed code used from C must be prefixed with pw_.
300 extern const int pw_kGlobalConstant;
301
302 extern int pw_global_variable;
303
304 void pw_Function(void);
305
306 typedef struct {
307 int member_variable;
308 } pw_Struct;
309
310 // Private Pigweed code used from C must be prefixed with _pw_.
311 extern const int _pw_kPrivateGlobalConstant;
312
313 extern int _pw_private_global_variable;
314
315 void _pw_PrivateFunction(void);
316
317 typedef struct {
318 int member_variable;
319 } _pw_PrivateStruct;
320
321 } // extern "C"
322
323 // Public macros must be prefixed with PW_.
324 #define PW_PUBLIC_MACRO(arg) arg
325
326 // Private macros must be prefixed with _PW_.
327 #define _PW_PRIVATE_MACRO(arg) arg
328
329 } // namespace nested_namespace
330 } // namespace pw
331
332Namespace scope formatting
333==========================
334All non-indented blocks (namespaces, ``extern "C"`` blocks, and preprocessor
335conditionals) must have a comment on their closing line with the
336contents of the starting line.
337
338All nested namespaces should be declared together with no blank lines between
339them.
340
341.. code-block:: cpp
342
343 #include "some/header.h"
344
345 namespace pw::nested {
346 namespace {
347
348 constexpr int kAnonConstantGoesHere = 0;
349
350 } // namespace
351
352 namespace other {
353
354 const char* SomeClass::yes = "no";
355
356 bool ThisIsAFunction() {
357 #if PW_CONFIG_IS_SET
358 return true;
359 #else
360 return false;
361 #endif // PW_CONFIG_IS_SET
362 }
363
364 extern "C" {
365
366 const int pw_kSomeConstant = 10;
367 int pw_some_global_variable = 600;
368
369 void pw_CFunction() { ... }
370
371 } // extern "C"
372
373 } // namespace
374 } // namespace pw::nested
375
376Pointers and references
377=======================
378For pointer and reference types, place the asterisk or ampersand next to the
379type.
380
381.. code-block:: cpp
382
383 int* const number = &that_thing;
384 constexpr const char* kString = "theory!"
385
386 bool FindTheOneRing(const Region& where_to_look) { ... }
387
388Prefer storing references over storing pointers. Pointers are required when the
389pointer can change its target or may be ``nullptr``. Otherwise, a reference or
390const reference should be used. In accordance with the Google C++ style guide,
391only const references are permitted as function arguments; pointers must be used
392in place of mutable references when passed as function arguments.
393
394Preprocessor macros
395===================
396Macros should only be used when they significantly improve upon the C++ code
397they replace. Macros should make code more readable, robust, and safe, or
398provide features not possible with standard C++, such as stringification, line
399number capturing, or conditional compilation. When possible, use C++ constructs
400like constexpr variables in place of macros. Never use macros as constants,
401except when a string literal is needed or the value must be used by C code.
402
403When macros are needed, the macros should be accompanied with extensive tests
404to ensure the macros are hard to use wrong.
405
406Stand-alone statement macros
407----------------------------
408Macros that are standalone statements must require the caller to terminate the
Alexei Frolov44d54732020-01-10 14:45:43 -0800409macro invocation with a semicolon. For example, the following does *not* conform
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800410to Pigweed's macro style:
411
412.. code-block:: cpp
413
414 // BAD! Definition has built-in semicolon.
415 #define PW_LOG_IF_BAD(mj) \
416 CallSomeFunction(mj);
417
418 // BAD! Compiles without error; semicolon is missing.
Alexei Frolov44d54732020-01-10 14:45:43 -0800419 PW_LOG_IF_BAD("foo")
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800420
421Here's how to do this instead:
422
423.. code-block:: cpp
424
425 // GOOD; requires semicolon to compile.
426 #define PW_LOG_IF_BAD(mj) \
427 CallSomeFunction(mj)
428
429 // GOOD; fails to compile due to lacking semicolon.
Alexei Frolov44d54732020-01-10 14:45:43 -0800430 PW_LOG_IF_BAD("foo")
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800431
432For macros in function scope that do not already require a semicolon, the
433contents can be placed in a ``do { ... } while (0)`` loop.
434
435.. code-block:: cpp
436
437 #define PW_LOG_IF_BAD(mj) \
438 do { \
439 if (mj.Bad()) { \
440 Log(#mj " is bad") \
441 } \
442 } while (0)
443
444Standalone macros at global scope that do not already require a semicolon can
445add a ``static_assert`` or throwaway struct declaration statement as their
446last line.
447
448.. code-block:: cpp
449
450 #define PW_NEAT_THING(thing) \
451 bool IsNeat_##thing() { return true; } \
452 static_assert(true, "Macros must be terminated with a semicolon")
453
454Private macros in public headers
455--------------------------------
456Private macros in public headers must be prefixed with ``_PW_``, even if they
457are undefined after use; this prevents collisions with downstream users. For
458example:
459
460.. code-block:: cpp
461
462 #define _PW_MY_SPECIAL_MACRO(op) ...
463 ...
464 // Code that uses _PW_MY_SPECIAL_MACRO()
465 ...
466 #undef _PW_MY_SPECIAL_MACRO
467
468Macros in private implementation files (.cc)
469--------------------------------------------
470Macros within .cc files that should only used within one file should be
471undefined after their last use; for example:
472
473.. code-block:: cpp
474
475 #define DEFINE_OPERATOR(op) \
476 T operator ## op(T x, T y) { return x op y; } \
477 static_assert(true, "Macros must be terminated with a semicolon") \
478
479 DEFINE_OPERATOR(+);
480 DEFINE_OPERATOR(-);
481 DEFINE_OPERATOR(/);
482 DEFINE_OPERATOR(*);
483
484 #undef DEFINE_OPERATOR
485
486Preprocessor conditional statements
487===================================
488When using macros for conditional compilation, prefer to use ``#if`` over
489``#ifdef``. This checks the value of the macro rather than whether it exists.
490
491 * ``#if`` handles undefined macros equivalently to ``#ifdef``. Undefined
492 macros expand to 0 in preprocessor conditional statements.
493 * ``#if`` evaluates false for macros defined as 0, while ``#ifdef`` evaluates
494 true.
495 * Macros defined using compiler flags have a default value of 1 in GCC and
496 Clang, so they work equivalently for ``#if`` and ``#ifdef``.
497 * Macros defined to an empty statement cause compile-time errors in ``#if``
498 statements, which avoids ambiguity about how the macro should be used.
499
500All ``#endif`` statements should be commented with the expression from their
501corresponding ``#if``. Do not indent within preprocessor conditional statements.
502
503.. code-block:: cpp
504
505 #if USE_64_BIT_WORD
506 using Word = uint64_t;
507 #else
508 using Word = uint32_t;
509 #endif // USE_64_BIT_WORD
510
511Unsigned integers
512=================
513Unsigned integers are permitted in Pigweed. Aim for consistency with existing
514code and the C++ Standard Library. Be very careful mixing signed and unsigned
515integers.
516
517------------
518Python style
519------------
520Pigweed uses the standard Python style: PEP8, which is available on the web at
521https://www.python.org/dev/peps/pep-0008/. All Pigweed Python code should pass
522``yapf`` when configured for PEP8 style.
523
Wyatt Heplerab4eb7a2020-01-08 18:04:31 -0800524Python 3
525========
526Pigweed uses Python 3. Some modules may offer limited support for Python 2, but
527Python 3.6 or newer is required for most Pigweed code.