blob: 320aac33db18b7b05a8e744ef35f71a7b2e71bd2 [file] [log] [blame]
Wyatt Heplerf9fb90f2020-09-30 18:59:33 -07001.. _docs-pw-style:
Keir Mierle2c1e56b2019-11-15 16:32:11 -08002
3===========================
4Style Guide and Conventions
5===========================
6
Armando Montanezf2bbb752020-03-03 09:50:37 -08007.. 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
Keir Mierle2c1e56b2019-11-15 16:32:11 -080013---------
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
Alexei Frolov44d54732020-01-10 14:45:43 -080023projects that use Pigweed or to the third-party code included with Pigweed.
Keir Mierle2c1e56b2019-11-15 16:32:11 -080024Non-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
Alexei Frolov44d54732020-01-10 14:45:43 -080049 constexpr int kMyMatrix[] = {
Keir Mierle2c1e56b2019-11-15 16:32:11 -080050 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!
Alexei Frolov44d54732020-01-10 14:45:43 -080079This is larger than many microcontrollers' entire internal storage.
Keir Mierle2c1e56b2019-11-15 16:32:11 -080080
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 commments (``/* */``). 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
Alexei Frolov44d54732020-01-10 14:45:43 -0800179comment line, even if the blank comment line is the last line in the block.
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800180
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
Ewout van Bekkume072fab2020-07-17 16:34:00 -0700196The syntax ``while (true)`` is preferred over ``for (;;)`` for infinite loops.
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800197
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
Keir Mierle086ef1c2020-03-19 02:03:51 -0700207 // Copyright 2020 The Pigweed Authors
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800208 //
209 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
Wyatt Hepler1a960942019-11-26 14:13:38 -0800210 // use this file except in compliance with the License. You may obtain a copy of
211 // the License at
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800212 //
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
Wyatt Hepler1a960942019-11-26 14:13:38 -0800218 // License for the specific language governing permissions and limitations under
219 // the License.
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800220 #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``.
Keir Mierle003044a2020-04-14 10:56:20 -0700253 * Template arguments for non-type names (e.g. ``template <int foo_bar>``)
254 should follow the variable naming convention, which means snake case (e.g.
255 ``foo_bar``). This matches the Google C++ style, however the wording in the
256 official style guide isn't explicit and could be interpreted to use
257 ``kFooBar`` style naming. Wide practice establishes that the naming
258 convention is ``snake_case``, and so that is the style we use in Pigweed.
259
260 **Note:** At time of writing much of Pigweed incorrectly follows the
261 ``kCamelCase`` naming for non-type template arguments. This is a bug that
262 will be fixed eventually.
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800263
264**C code**
265 * Public names used by C code must be prefixed with ``pw_``.
266 * If private code must be exposed in a header, private names used by C code
267 must be prefixed with ``_pw_``.
268 * Avoid writing C source (.c) files in Pigweed. Prefer to write C++ code with
269 C linkage using ``extern "C"``. Within C source, private C functions and
270 variables must be named with the ``_pw_`` prefix and should be declared
271 ``static`` whenever possible; for example, ``_pw__MyPrivateFunction``.
272 * The C prefix rules apply to
273
274 * C functions (``int pw_FunctionName(void);``),
275 * variables used by C code (``int pw_variable_name;``),
276 * constant variables used by C code (``int pw_kConstantName;``), and
277 * structs used by C code (``typedef struct {} pw_StructName;``).
278
279 The prefix does not apply to struct members, which use normal Google style.
280
281**Preprocessor macros**
282 * Public Pigweed macros must be prefixed with ``PW_``.
283 * Private Pigweed macros must be prefixed with ``_PW_``.
284
285**Example**
286
287.. code-block:: cpp
288
289 namespace pw {
290 namespace nested_namespace {
291
292 // C++ names (types, variables, functions) must be in the pw namespace.
293 // They are named according to the Google style guide.
294 constexpr int kGlobalConstant = 123;
295
296 // Prefer using functions over extern global variables.
297 extern int global_variable;
298
299 class Class {};
300
301 void Function();
302
303 extern "C" {
304
305 // Public Pigweed code used from C must be prefixed with pw_.
306 extern const int pw_kGlobalConstant;
307
308 extern int pw_global_variable;
309
310 void pw_Function(void);
311
312 typedef struct {
313 int member_variable;
314 } pw_Struct;
315
316 // Private Pigweed code used from C must be prefixed with _pw_.
317 extern const int _pw_kPrivateGlobalConstant;
318
319 extern int _pw_private_global_variable;
320
321 void _pw_PrivateFunction(void);
322
323 typedef struct {
324 int member_variable;
325 } _pw_PrivateStruct;
326
327 } // extern "C"
328
329 // Public macros must be prefixed with PW_.
330 #define PW_PUBLIC_MACRO(arg) arg
331
332 // Private macros must be prefixed with _PW_.
333 #define _PW_PRIVATE_MACRO(arg) arg
334
335 } // namespace nested_namespace
336 } // namespace pw
337
338Namespace scope formatting
339==========================
340All non-indented blocks (namespaces, ``extern "C"`` blocks, and preprocessor
341conditionals) must have a comment on their closing line with the
342contents of the starting line.
343
344All nested namespaces should be declared together with no blank lines between
345them.
346
347.. code-block:: cpp
348
349 #include "some/header.h"
350
351 namespace pw::nested {
352 namespace {
353
354 constexpr int kAnonConstantGoesHere = 0;
355
356 } // namespace
357
358 namespace other {
359
360 const char* SomeClass::yes = "no";
361
362 bool ThisIsAFunction() {
363 #if PW_CONFIG_IS_SET
364 return true;
365 #else
366 return false;
367 #endif // PW_CONFIG_IS_SET
368 }
369
370 extern "C" {
371
372 const int pw_kSomeConstant = 10;
373 int pw_some_global_variable = 600;
374
375 void pw_CFunction() { ... }
376
377 } // extern "C"
378
379 } // namespace
380 } // namespace pw::nested
381
382Pointers and references
383=======================
384For pointer and reference types, place the asterisk or ampersand next to the
385type.
386
387.. code-block:: cpp
388
389 int* const number = &that_thing;
390 constexpr const char* kString = "theory!"
391
392 bool FindTheOneRing(const Region& where_to_look) { ... }
393
394Prefer storing references over storing pointers. Pointers are required when the
395pointer can change its target or may be ``nullptr``. Otherwise, a reference or
396const reference should be used. In accordance with the Google C++ style guide,
397only const references are permitted as function arguments; pointers must be used
398in place of mutable references when passed as function arguments.
399
400Preprocessor macros
401===================
402Macros should only be used when they significantly improve upon the C++ code
403they replace. Macros should make code more readable, robust, and safe, or
404provide features not possible with standard C++, such as stringification, line
405number capturing, or conditional compilation. When possible, use C++ constructs
406like constexpr variables in place of macros. Never use macros as constants,
407except when a string literal is needed or the value must be used by C code.
408
409When macros are needed, the macros should be accompanied with extensive tests
410to ensure the macros are hard to use wrong.
411
412Stand-alone statement macros
413----------------------------
414Macros that are standalone statements must require the caller to terminate the
Alexei Frolov44d54732020-01-10 14:45:43 -0800415macro invocation with a semicolon. For example, the following does *not* conform
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800416to Pigweed's macro style:
417
418.. code-block:: cpp
419
420 // BAD! Definition has built-in semicolon.
421 #define PW_LOG_IF_BAD(mj) \
422 CallSomeFunction(mj);
423
424 // BAD! Compiles without error; semicolon is missing.
Alexei Frolov44d54732020-01-10 14:45:43 -0800425 PW_LOG_IF_BAD("foo")
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800426
427Here's how to do this instead:
428
429.. code-block:: cpp
430
431 // GOOD; requires semicolon to compile.
432 #define PW_LOG_IF_BAD(mj) \
433 CallSomeFunction(mj)
434
435 // GOOD; fails to compile due to lacking semicolon.
Alexei Frolov44d54732020-01-10 14:45:43 -0800436 PW_LOG_IF_BAD("foo")
Keir Mierle2c1e56b2019-11-15 16:32:11 -0800437
438For macros in function scope that do not already require a semicolon, the
439contents can be placed in a ``do { ... } while (0)`` loop.
440
441.. code-block:: cpp
442
443 #define PW_LOG_IF_BAD(mj) \
444 do { \
445 if (mj.Bad()) { \
446 Log(#mj " is bad") \
447 } \
448 } while (0)
449
450Standalone macros at global scope that do not already require a semicolon can
451add a ``static_assert`` or throwaway struct declaration statement as their
452last line.
453
454.. code-block:: cpp
455
456 #define PW_NEAT_THING(thing) \
457 bool IsNeat_##thing() { return true; } \
458 static_assert(true, "Macros must be terminated with a semicolon")
459
460Private macros in public headers
461--------------------------------
462Private macros in public headers must be prefixed with ``_PW_``, even if they
463are undefined after use; this prevents collisions with downstream users. For
464example:
465
466.. code-block:: cpp
467
468 #define _PW_MY_SPECIAL_MACRO(op) ...
469 ...
470 // Code that uses _PW_MY_SPECIAL_MACRO()
471 ...
472 #undef _PW_MY_SPECIAL_MACRO
473
474Macros in private implementation files (.cc)
475--------------------------------------------
476Macros within .cc files that should only used within one file should be
477undefined after their last use; for example:
478
479.. code-block:: cpp
480
481 #define DEFINE_OPERATOR(op) \
482 T operator ## op(T x, T y) { return x op y; } \
483 static_assert(true, "Macros must be terminated with a semicolon") \
484
485 DEFINE_OPERATOR(+);
486 DEFINE_OPERATOR(-);
487 DEFINE_OPERATOR(/);
488 DEFINE_OPERATOR(*);
489
490 #undef DEFINE_OPERATOR
491
492Preprocessor conditional statements
493===================================
494When using macros for conditional compilation, prefer to use ``#if`` over
495``#ifdef``. This checks the value of the macro rather than whether it exists.
496
497 * ``#if`` handles undefined macros equivalently to ``#ifdef``. Undefined
498 macros expand to 0 in preprocessor conditional statements.
499 * ``#if`` evaluates false for macros defined as 0, while ``#ifdef`` evaluates
500 true.
501 * Macros defined using compiler flags have a default value of 1 in GCC and
502 Clang, so they work equivalently for ``#if`` and ``#ifdef``.
503 * Macros defined to an empty statement cause compile-time errors in ``#if``
504 statements, which avoids ambiguity about how the macro should be used.
505
506All ``#endif`` statements should be commented with the expression from their
507corresponding ``#if``. Do not indent within preprocessor conditional statements.
508
509.. code-block:: cpp
510
511 #if USE_64_BIT_WORD
512 using Word = uint64_t;
513 #else
514 using Word = uint32_t;
515 #endif // USE_64_BIT_WORD
516
517Unsigned integers
518=================
519Unsigned integers are permitted in Pigweed. Aim for consistency with existing
520code and the C++ Standard Library. Be very careful mixing signed and unsigned
521integers.
522
523------------
524Python style
525------------
526Pigweed uses the standard Python style: PEP8, which is available on the web at
527https://www.python.org/dev/peps/pep-0008/. All Pigweed Python code should pass
528``yapf`` when configured for PEP8 style.
529
Wyatt Heplerab4eb7a2020-01-08 18:04:31 -0800530Python 3
531========
532Pigweed uses Python 3. Some modules may offer limited support for Python 2, but
533Python 3.6 or newer is required for most Pigweed code.
Wayne Jacksond597e462020-06-03 15:03:12 -0700534
535---------------
536Build files: GN
537---------------
538
539Each Pigweed source module will require a build file named BUILD.gn which
540encapsulates the build targets and specifies their sources and dependencies.
541The format of this file is simlar in structure to the
542`Bazel/Blaze format <https://docs.bazel.build/versions/3.2.0/build-ref.html>`_
543(Googlers may also review `go/build-style <go/build-style>`_), but with
544nomenclature specific to Pigweed. For each target specified within the build
545file there are a list of depdency fields. Those fields, in their expected
546order, are:
547
548 * ``<public_config>`` -- external build configuration
549 * ``<public_deps>`` -- necessary public dependencies (ie: Pigweed headers)
550 * ``<public>`` -- exposed package public interface header files
551 * ``<config>`` -- package build configuration
552 * ``<sources>`` -- package source code
553 * ``<deps>`` -- package necessary local dependencies
554
555Assets within each field must be listed in alphabetical order
556
557.. code-block:: cpp
558
559 # Here is a brief example of a GN build file.
560
561 import("$dir_pw_unit_test/test.gni")
562
563 config("default_config") {
564 include_dirs = [ "public" ]
565 }
566
567 source_set("pw_sample_module") {
568 public_configs = [ ":default_config" ]
569 public_deps = [
Kevin Zeng1e10ef22020-06-09 20:47:14 -0700570 dir_pw_span,
Wayne Jacksond597e462020-06-03 15:03:12 -0700571 dir_pw_status,
572 ]
573 public = [ "public/pw_sample_module/sample_module.h" ]
574 sources = [
575 "public/pw_sample_module/internal/sample_module.h",
576 "sample_module.cc",
577 "used_by_sample_module.cc",
578 ]
579 deps = [ dir_pw_varint ]
580 }
581
582 pw_test_group("tests") {
583 tests = [ ":sample_module_test" ]
584 }
585
586 pw_test("sample_module_test") {
Wayne Jacksond597e462020-06-03 15:03:12 -0700587 sources = [ "sample_module_test.cc" ]
Kevin Zeng1e10ef22020-06-09 20:47:14 -0700588 deps = [ ":sample_module" ]
Wayne Jacksond597e462020-06-03 15:03:12 -0700589 }
590
591 pw_doc_group("docs") {
592 sources = [ "docs.rst" ]
593 }