]> git.proxmox.com Git - ovs.git/blame - Documentation/internals/contributing/coding-style.rst
coding-style: Few visual enhancements for the document.
[ovs.git] / Documentation / internals / contributing / coding-style.rst
CommitLineData
d124a408
SF
1..
2 Licensed under the Apache License, Version 2.0 (the "License"); you may
3 not use this file except in compliance with the License. You may obtain
4 a copy of the License at
5
6 http://www.apache.org/licenses/LICENSE-2.0
7
8 Unless required by applicable law or agreed to in writing, software
9 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
10 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
11 License for the specific language governing permissions and limitations
12 under the License.
13
14 Convention for heading levels in Open vSwitch documentation:
15
16 ======= Heading 0 (reserved for the title in a document)
17 ------- Heading 1
18 ~~~~~~~ Heading 2
19 +++++++ Heading 3
20 ''''''' Heading 4
21
22 Avoid deeper levels because they do not render well.
23
24=========================
25Open vSwitch Coding Style
26=========================
27
28This file describes the coding style used in most C files in the Open vSwitch
29distribution. However, Linux kernel code datapath directory follows the Linux
30kernel's established coding conventions. For the Windows kernel datapath code,
d0e53b15 31use the coding style described in :doc:`coding-style-windows`.
d124a408
SF
32
33The following GNU indent options approximate this style.
34
35::
36
37 -npro -bad -bap -bbb -br -blf -brs -cdw -ce -fca -cli0 -npcs -i4 -l79 \
38 -lc79 -nbfda -nut -saf -sai -saw -sbi4 -sc -sob -st -ncdb -pi4 -cs -bs \
39 -di1 -lp -il0 -hnl
40
41.. _basics:
42
43Basics
44------
45
46- Limit lines to 79 characters.
47
48- Use form feeds (control+L) to divide long source files into logical pieces. A
49 form feed should appear as the only character on a line.
50
51- Do not use tabs for indentation.
52
53- Avoid trailing spaces on lines.
54
55.. _naming:
56
57Naming
58------
59
60- Use names that explain the purpose of a function or object.
61
62- Use underscores to separate words in an identifier: ``multi_word_name``.
63
64- Use lowercase for most names. Use uppercase for macros, macro parameters,
65 and members of enumerations.
66
67- Give arrays names that are plural.
68
69- Pick a unique name prefix (ending with an underscore) for each
70 module, and apply that prefix to all of that module's externally
71 visible names. Names of macro parameters, struct and union members,
72 and parameters in function prototypes are not considered externally
73 visible for this purpose.
74
75- Do not use names that begin with ``_``. If you need a name for "internal use
76 only", use ``__`` as a suffix instead of a prefix.
77
78- Avoid negative names: ``found`` is a better name than ``not_found``.
79
80- In names, a ``size`` is a count of bytes, a ``length`` is a count of
81 characters. A buffer has size, but a string has length. The length of a
82 string does not include the null terminator, but the size of the buffer that
83 contains the string does.
84
85.. _comments:
86
87Comments
88--------
89
90Comments should be written as full sentences that start with a capital letter
91and end with a period. Put two spaces between sentences.
92
93Write block comments as shown below. You may put the ``/*`` and ``*/`` on the
94same line as comment text if you prefer.
95
96::
97
98 /*
99 * We redirect stderr to /dev/null because we often want to remove all
100 * traffic control configuration on a port so its in a known state. If
101 * this done when there is no such configuration, tc complains, so we just
102 * always ignore it.
103 */
104
105Each function and each variable declared outside a function, and each struct,
106union, and typedef declaration should be preceded by a comment. See functions_
107below for function comment guidelines.
108
109Each struct and union member should each have an inline comment that explains
110its meaning. structs and unions with many members should be additionally
111divided into logical groups of members by block comments, e.g.:
112
113::
114
115 /* An event that will wake the following call to poll_block(). */
116 struct poll_waiter {
117 /* Set when the waiter is created. */
118 struct ovs_list node; /* Element in global waiters list. */
119 int fd; /* File descriptor. */
120 short int events; /* Events to wait for (POLLIN, POLLOUT). */
121 poll_fd_func *function; /* Callback function, if any, or null. */
122 void *aux; /* Argument to callback function. */
123 struct backtrace *backtrace; /* Event that created waiter, or null. */
124
125 /* Set only when poll_block() is called. */
126 struct pollfd *pollfd; /* Pointer to element of the pollfds array
127 (null if added from a callback). */
128 };
129
130Use ``XXX`` or ``FIXME`` comments to mark code that needs work.
131
132Don't use ``//`` comments.
133
b24f1e49
IM
134Don't comment out or ``#if 0`` out code. Just remove it. The code that was
135there will still be in version control history.
d124a408
SF
136
137.. _functions:
138
139Functions
140---------
141
142Put the return type, function name, and the braces that surround the function's
143code on separate lines, all starting in column 0.
144
145Before each function definition, write a comment that describes the function's
146purpose, including each parameter, the return value, and side effects.
b24f1e49
IM
147References to argument names should be given in single-quotes, e.g. ``'arg'``.
148The comment should not include the function name, nor need it follow any formal
d124a408
SF
149structure. The comment does not need to describe how a function does its work,
150unless this information is needed to use the function correctly (this is often
151better done with comments *inside* the function).
152
153Simple static functions do not need a comment.
154
155Within a file, non-static functions should come first, in the order that they
156are declared in the header file, followed by static functions. Static
157functions should be in one or more separate pages (separated by form feed
158characters) in logical groups. A commonly useful way to divide groups is by
159"level", with high-level functions first, followed by groups of progressively
160lower-level functions. This makes it easy for the program's reader to see the
161top-down structure by reading from top to bottom.
162
163All function declarations and definitions should include a prototype. Empty
164parentheses, e.g. ``int foo();``, do not include a prototype (they state that
165the function's parameters are unknown); write ``void`` in parentheses instead,
166e.g. ``int foo(void);``.
167
168Prototypes for static functions should either all go at the top of the file,
169separated into groups by blank lines, or they should appear at the top of each
170page of functions. Don't comment individual prototypes, but a comment on each
171group of prototypes is often appropriate.
172
173In the absence of good reasons for another order, the following parameter order
174is preferred. One notable exception is that data parameters and their
175corresponding size parameters should be paired.
176
b24f1e49 1771. The primary object being manipulated, if any (equivalent to the ``this``
d124a408
SF
178 pointer in C++).
179
1802. Input-only parameters.
181
1823. Input/output parameters.
183
1844. Output-only parameters.
185
1865. Status parameter.
187
188Example:
189
190::
191
192 ```
193 /* Stores the features supported by 'netdev' into each of '*current',
194 * '*advertised', '*supported', and '*peer' that are non-null. Each value
195 * is a bitmap of "enum ofp_port_features" bits, in host byte order.
196 * Returns 0 if successful, otherwise a positive errno value. On failure,
197 * all of the passed-in values are set to 0. */
198 int
199 netdev_get_features(struct netdev *netdev,
200 uint32_t *current, uint32_t *advertised,
201 uint32_t *supported, uint32_t *peer)
202 {
203 ...
204 }
205 ```
206
207Functions that destroy an instance of a dynamically-allocated type should
208accept and ignore a null pointer argument. Code that calls such a function
209(including the C standard library function ``free()``) should omit a
210null-pointer check. We find that this usually makes code easier to read.
211
212Functions in ``.c`` files should not normally be marked ``inline``, because it
064ccb0c 213does not usually help code generation and it does suppress compiler warnings
b24f1e49
IM
214about unused functions. (Functions defined in ``.h`` usually should be marked
215``inline``.)
d124a408
SF
216
217.. _function prototypes:
218
219Function Prototypes
220-------------------
221
222Put the return type and function name on the same line in a function prototype:
223
224::
225
226 static const struct option_class *get_option_class(int code);
227
228Omit parameter names from function prototypes when the names do not give useful
229information, e.g.:
230
231::
232
233 int netdev_get_mtu(const struct netdev *, int *mtup);
234
235Statements
236----------
237
238Indent each level of code with 4 spaces. Use BSD-style brace placement:
239
240::
241
242 if (a()) {
243 b();
244 d();
245 }
246
247Put a space between ``if``, ``while``, ``for``, etc. and the expressions that
248follow them.
249
250Enclose single statements in braces:
251
252::
253
254 if (a > b) {
255 return a;
256 } else {
257 return b;
258 }
259
260Use comments and blank lines to divide long functions into logical groups of
261statements.
262
263Avoid assignments inside ``if`` and ``while`` conditions.
264
265Do not put gratuitous parentheses around the expression in a return statement,
266that is, write ``return 0;`` and not ``return(0);``
267
268Write only one statement per line.
269
270Indent ``switch`` statements like this:
271
272::
273
274 switch (conn->state) {
275 case S_RECV:
276 error = run_connection_input(conn);
277 break;
278
279 case S_PROCESS:
280 error = 0;
281 break;
282
283 case S_SEND:
284 error = run_connection_output(conn);
285 break;
286
287 default:
288 OVS_NOT_REACHED();
289 }
290
291``switch`` statements with very short, uniform cases may use an abbreviated
292style:
293
294::
295
296 switch (code) {
297 case 200: return "OK";
298 case 201: return "Created";
299 case 202: return "Accepted";
300 case 204: return "No Content";
301 default: return "Unknown";
302 }
303
304Use ``for (;;)`` to write an infinite loop.
305
b24f1e49
IM
306In an ``if/else`` construct where one branch is the "normal" or "common" case
307and the other branch is the "uncommon" or "error" case, put the common case
308after the ``if``, not the ``else``. This is a form of documentation. It also
309places the most important code in sequential order without forcing the reader
310to visually skip past less important details. (Some compilers also assume that
311the ``if`` branch is the more common case, so this can be a real form of
312optimization as well.)
d124a408
SF
313
314Return Values
315-------------
316
317For functions that return a success or failure indication, prefer one of the
318following return value conventions:
319
b24f1e49
IM
320- An ``int`` where ``0`` indicates success and a positive errno value indicates
321 a reason for failure.
d124a408 322
b24f1e49 323- A ``bool`` where ``true`` indicates success and ``false`` indicates failure.
d124a408
SF
324
325Macros
326------
327
328Don't define an object-like macro if an enum can be used instead.
329
b24f1e49 330Don't define a function-like macro if a ``static inline`` function can be used
d124a408
SF
331instead.
332
b24f1e49
IM
333If a macro's definition contains multiple statements, enclose them with
334``do { ... } while (0)`` to allow them to work properly in all syntactic
d124a408
SF
335circumstances.
336
337Do use macros to eliminate the need to update different parts of a single file
338in parallel, e.g. a list of enums and an array that gives the name of each
339enum. For example:
340
341::
342
343 /* Logging importance levels. */
344 #define VLOG_LEVELS \
345 VLOG_LEVEL(EMER, LOG_ALERT) \
346 VLOG_LEVEL(ERR, LOG_ERR) \
347 VLOG_LEVEL(WARN, LOG_WARNING) \
348 VLOG_LEVEL(INFO, LOG_NOTICE) \
349 VLOG_LEVEL(DBG, LOG_DEBUG)
350 enum vlog_level {
351 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) VLL_##NAME,
352 VLOG_LEVELS
353 #undef VLOG_LEVEL
354 VLL_N_LEVELS
355 };
356
357 /* Name for each logging level. */
358 static const char *level_names[VLL_N_LEVELS] = {
359 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
360 VLOG_LEVELS
361 #undef VLOG_LEVEL
362 };
363
364Thread Safety Annotations
365-------------------------
366
367Use the macros in ``lib/compiler.h`` to annotate locking requirements. For
368example:
369
370::
371
372 static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER;
373 static struct ovs_rwlock rwlock = OVS_RWLOCK_INITIALIZER;
374
375 void function_require_plain_mutex(void) OVS_REQUIRES(mutex);
376 void function_require_rwlock(void) OVS_REQ_RDLOCK(rwlock);
377
378Pass lock objects, not their addresses, to the annotation macros. (Thus we have
379``OVS_REQUIRES(mutex)`` above, not ``OVS_REQUIRES(&mutex)``.)
380
381.. _source files:
382
383Source Files
384------------
385
386Each source file should state its license in a comment at the very top,
387followed by a comment explaining the purpose of the code that is in that file.
388The comment should explain how the code in the file relates to code in other
389files. The goal is to allow a programmer to quickly figure out where a given
390module fits into the larger system.
391
b24f1e49 392The first non-comment line in a ``.c`` source file should be:
d124a408
SF
393
394::
395
396 #include <config.h>
397
398``#include`` directives should appear in the following order:
399
4001. ``#include <config.h>``
401
4022. The module's own headers, if any. Including this before any other header
403 (besides ) ensures that the module's header file is self-contained (see
404 `header files`_ below).
405
4063. Standard C library headers and other system headers, preferably in
407 alphabetical order. (Occasionally one encounters a set of system headers
408 that must be included in a particular order, in which case that order must
409 take precedence.)
410
4114. Open vSwitch headers, in alphabetical order. Use ``""``, not ``<>``, to
412 specify Open vSwitch header names.
413
414.. _header files:
415
416Header Files
417------------
418
419Each header file should start with its license, as described under `source
420files`_ above, followed by a "header guard" to make the header file idempotent,
421like so:
422
423::
424
425 #ifndef NETDEV_H
426 #define NETDEV_H 1
427
428 ...
429
430 #endif /* netdev.h */
431
b24f1e49
IM
432Header files should be self-contained; that is, they should ``#include``
433whatever additional headers are required, without requiring the client to
434``#include`` them for it.
d124a408
SF
435
436Don't define the members of a struct or union in a header file, unless client
437code is actually intended to access them directly or if the definition is
438otherwise actually needed (e.g. inline functions defined in the header need
439them).
440
441Similarly, don't ``#include`` a header file just for the declaration of a
442struct or union tag (e.g. just for ``struct ;``). Just declare the tag
443yourself. This reduces the number of header file dependencies.
444
445Types
446-----
447
448Use typedefs sparingly. Code is clearer if the actual type is visible at the
b24f1e49
IM
449point of declaration. Do not, in general, declare a typedef for a ``struct``,
450``union``, or ``enum``. Do not declare a typedef for a pointer type, because
451this can be very confusing to the reader.
d124a408
SF
452
453A function type is a good use for a typedef because it can clarify code. The
454type should be a function type, not a pointer-to-function type. That way, the
455typedef name can be used to declare function prototypes. (It cannot be used for
456function definitions, because that is explicitly prohibited by C89 and C99.)
457
458You may assume that ``char`` is exactly 8 bits and that ``int`` and ``long``
459are at least 32 bits.
460
461Don't assume that ``long`` is big enough to hold a pointer. If you need to cast
462a pointer to an integer, use ``intptr_t`` or ``uintptr_t`` from .
463
464Use the ``int_t`` and ``uint_t`` types from for exact-width integer types. Use
465the ``PRId``, ``PRIu``, and ``PRIx`` macros from for formatting them with
466``printf()`` and related functions.
467
468For compatibility with antique ``printf()`` implementations:
469
470- Instead of ``"%zu"``, use ``"%"PRIuSIZE``.
471
472- Instead of ``"%td"``, use ``"%"PRIdPTR``.
473
474- Instead of ``"%ju"``, use ``"%"PRIuMAX``.
475
476Other variants exist for different radixes. For example, use ``"%"PRIxSIZE``
477instead of ``"%zx"`` or ``"%x"`` instead of ``"%hhx"``.
478
479Also, instead of ``"%hhd"``, use ``"%d"``. Be cautious substituting ``"%u"``,
480``"%x"``, and ``"%o"`` for the corresponding versions with ``"hh"``: cast the
481argument to unsigned char if necessary, because ``printf("%hhu", -1)`` prints
b24f1e49 482``255`` but ``printf("%u", -1)`` prints ``4294967295``.
d124a408
SF
483
484Use bit-fields sparingly. Do not use bit-fields for layout of network
485protocol fields or in other circumstances where the exact format is
486important.
487
b24f1e49
IM
488Declare bit-fields to be signed or unsigned integer types or ``_Bool`` (aka
489``bool``). Do *not* declare bit-fields of type ``int``: C99 allows these to be
d124a408 490either signed or unsigned according to the compiler's whim. (A 1-bit bit-field
b24f1e49 491of type ``int`` may have a range of ``-1...0``!)
d124a408
SF
492
493Try to order structure members such that they pack well on a system with 2-byte
494``short``, 4-byte ``int``, and 4- or 8-byte ``long`` and pointer types. Prefer
495clear organization over size optimization unless you are convinced there is a
496size or speed benefit.
497
498Pointer declarators bind to the variable name, not the type name. Write
499``int *x``, not ``int* x`` and definitely not ``int * x``.
500
501Expressions
502-----------
503
504Put one space on each side of infix binary and ternary operators:
505
506::
507
508 * / %
509 + -
510 << >>
511 < <= > >=
512 == !=
513 &
514 ^
515 |
516 &&
517 ||
518 ?:
519 = += -= *= /= %= &= ^= |= <<= >>=
520
521Avoid comma operators.
522
523Do not put any white space around postfix, prefix, or grouping operators:
524
525::
526
527 () [] -> .
528 ! ~ ++ -- + - * &
529
530Exception 1: Put a space after (but not before) the "sizeof" keyword.
531
b24f1e49
IM
532Exception 2: Put a space between the ``()`` used in a cast and the expression
533whose type is cast: ``(void *) 0``.
d124a408 534
b24f1e49
IM
535Break long lines before the ternary operators ``?`` and ``:``, rather than
536after them, e.g.
d124a408
SF
537
538::
539
540 return (out_port != VIGP_CONTROL_PATH
541 ? alpheus_output_port(dp, skb, out_port)
542 : alpheus_output_control(dp, skb, fwd_save_skb(skb),
543 VIGR_ACTION));
544
2450cdab
BP
545Parenthesize the operands of ``&&`` and ``||`` if operator precedence makes it
546necessary, or if the operands are themselves expressions that use ``&&`` and
547``||``, but not otherwise. Thus::
d124a408
SF
548
549 if (rule && (!best || rule->priority > best->priority)) {
550 best = rule;
551 }
552
2450cdab 553but::
d124a408 554
2450cdab
BP
555 if (!isdigit((unsigned char)s[0]) ||
556 !isdigit((unsigned char)s[1]) ||
557 !isdigit((unsigned char)s[2])) {
558 printf("string %s does not start with 3-digit code\n", s);
559 }
d124a408 560
2450cdab
BP
561Do parenthesize a subexpression that must be split across more than one line,
562e.g.::
563
564 *idxp = ((l1_idx << PORT_ARRAY_L1_SHIFT) |
565 (l2_idx << PORT_ARRAY_L2_SHIFT) |
566 (l3_idx << PORT_ARRAY_L3_SHIFT));
567
568Breaking a long line after a binary operator gives its operands a more
569consistent look, since each operand has the same horizontal position. This
570makes the end-of-line position a good choice when the operands naturally
571resemble each other, as in the previous two examples. On the other hand,
572breaking before a binary operator better draws the eye to the operator, which
573can help clarify code by making it more obvious what's happening, such as in
574the following example::
575
576 if (!ctx.freezing
577 && xbridge->has_in_band
578 && in_band_must_output_to_local_port(flow)
579 && !actions_output_to_local_port(&ctx)) {
580
581Thus, decide whether to break before or after a binary operator separately in
582each situation, based on which of these factors appear to be more important.
d124a408
SF
583
584Try to avoid casts. Don't cast the return value of malloc().
585
b24f1e49 586The ``sizeof`` operator is unique among C operators in that it accepts two very
d124a408 587different kinds of operands: an expression or a type. In general, prefer to
6e367a20 588specify an expression, e.g. ``int *x = xmalloc(sizeof *x);``. When the
b24f1e49 589operand of ``sizeof`` is an expression, there is no need to parenthesize that
d124a408
SF
590operand, and please don't.
591
592Use the ``ARRAY_SIZE`` macro from ``lib/util.h`` to calculate the number of
593elements in an array.
594
595When using a relational operator like ``<`` or ``==``, put an expression or
596variable argument on the left and a constant argument on the right, e.g.
597``x == 0``, *not* ``0 == x``.
598
599Blank Lines
600-----------
601
602Put one blank line between top-level definitions of functions and global
603variables.
604
605C DIALECT
606---------
607
608Most C99 features are OK because they are widely implemented:
609
610- Flexible array members (e.g. ``struct { int foo[]; }``).
611
612- ``static inline`` functions (but no other forms of ``inline``, for which GCC
613 and C99 have differing interpretations).
614
615- ``long long``
616
b24f1e49
IM
617- ``bool`` and ``<stdbool.h>``, but don't assume that ``bool`` or ``_Bool`` can
618 only take on the values ``0`` or ``1``, because this behavior can't be
619 simulated on C89 compilers.
d124a408
SF
620
621 Also, don't assume that a conversion to ``bool`` or ``_Bool`` follows C99
b24f1e49
IM
622 semantics, i.e. use ``(bool) (some_value != 0)`` rather than
623 ``(bool) some_value``. The latter might produce unexpected results on non-C99
624 environments. For example, if ``bool`` is implemented as a typedef of char
625 and ``some_value = 0x10000000``.
d124a408 626
b24f1e49
IM
627- Designated initializers (e.g. ``struct foo foo = { .a = 1 };`` and
628 ``int a[] = { [2] = 5 };``).
d124a408 629
09de8591
BP
630- Mixing of declarations and code within a block. Favor positioning that
631 allows variables to be initialized at their point of declaration.
d124a408 632
b24f1e49
IM
633- Use of declarations in iteration statements
634 (e.g. ``for (int i = 0; i < 10; i++)``).
d124a408 635
b24f1e49
IM
636- Use of a trailing comma in an enum declaration (e.g.
637 ``enum { x = 1, };``).
d124a408
SF
638
639As a matter of style, avoid ``//`` comments.
640
641Avoid using GCC or Clang extensions unless you also add a fallback for other
642compilers. You can, however, use C99 features or GCC extensions also supported
643by Clang in code that compiles only on GNU/Linux (such as
644``lib/netdev-linux.c``), because GCC is the system compiler there.
645
646Python
647------
648
649When introducing new Python code, try to follow Python's `PEP 8
34aa9cf9 650<https://www.python.org/dev/peps/pep-0008/>`__ style. Consider running the
d124a408 651``pep8`` or ``flake8`` tool against your code to find issues.
cb991590
AC
652
653Libraries
654---------
655
656When introducing a new library, follow
657:doc:`Open vSwitch Library ABI guide <libopenvswitch-abi>`