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