]> git.proxmox.com Git - mirror_ovs.git/blame - CodingStyle
ofp-parse: Mark ofp_fatal() as never returning.
[mirror_ovs.git] / CodingStyle
CommitLineData
064af421
BP
1 Open vSwitch Coding Style
2 =========================
3
4This file describes the coding style used in most C files in the Open
5vSwitch distribution. However, Linux kernel code datapath directory
6follows the Linux kernel's established coding conventions.
7
8BASICS
9
10 Limit lines to 79 characters.
11
12 Use form feeds (control+L) to divide long source files into logical
13pieces. A form feed should appear as the only character on a line.
14
15 Do not use tabs for indentation.
16
17 Avoid trailing spaces on lines.
18
19
20NAMING
21
22 Use names that explain the purpose of a function or object.
23
24 Use underscores to separate words in an identifier: multi_word_name.
25
26 Use lowercase for most names. Use uppercase for macros, macro
27parameters, and members of enumerations.
28
29 Give arrays names that are plural.
30
31 Pick a unique name prefix (ending with an underscore) for each
32module, and apply that prefix to all of that module's externally
33visible names. Names of macro parameters, struct and union members,
34and parameters in function prototypes are not considered externally
35visible for this purpose.
36
37 Do not use names that begin with _. If you need a name for
38"internal use only", use __ as a suffix instead of a prefix.
39
40 Avoid negative names: "found" is a better name than "not_found".
41
42 In names, a "size" is a count of bytes, a "length" is a count of
43characters. A buffer has size, but a string has length. The length
44of a string does not include the null terminator, but the size of the
45buffer that contains the string does.
46
47
48COMMENTS
49
50 Comments should be written as full sentences that start with a
51capital letter and end with a period. Put two spaces between
52sentences.
53
54 Write block comments as shown below. You may put the /* and */ on
55the same line as comment text if you prefer.
56
57 /*
58 * We redirect stderr to /dev/null because we often want to remove all
59 * traffic control configuration on a port so its in a known state. If
60 * this done when there is no such configuration, tc complains, so we just
61 * always ignore it.
62 */
63
64 Each function and each variable declared outside a function, and
65each struct, union, and typedef declaration should be preceded by a
66comment. See FUNCTION DEFINITIONS below for function comment
67guidelines.
68
69 Each struct and union member should each have an inline comment that
70explains its meaning. structs and unions with many members should be
71additionally divided into logical groups of members by block comments,
72e.g.:
73
74 /* An event that will wake the following call to poll_block(). */
75 struct poll_waiter {
76 /* Set when the waiter is created. */
77 struct list node; /* Element in global waiters list. */
78 int fd; /* File descriptor. */
79 short int events; /* Events to wait for (POLLIN, POLLOUT). */
80 poll_fd_func *function; /* Callback function, if any, or null. */
81 void *aux; /* Argument to callback function. */
82 struct backtrace *backtrace; /* Event that created waiter, or null. */
83
84 /* Set only when poll_block() is called. */
85 struct pollfd *pollfd; /* Pointer to element of the pollfds array
86 (null if added from a callback). */
87 };
88
89 Use XXX or FIXME comments to mark code that needs work.
90
91 Don't use // comments.
92
93 Don't comment out or #if 0 out code. Just remove it. The code that
94was there will still be in version control history.
95
96
97FUNCTIONS
98
99 Put the return type, function name, and the braces that surround the
100function's code on separate lines, all starting in column 0.
101
102 Before each function definition, write a comment that describes the
103function's purpose, including each parameter, the return value, and
104side effects. References to argument names should be given in
105single-quotes, e.g. 'arg'. The comment should not include the
106function name, nor need it follow any formal structure. The comment
107does not need to describe how a function does its work, unless this
108information is needed to use the function correctly (this is often
109better done with comments *inside* the function).
110
111 Simple static functions do not need a comment.
112
113 Within a file, non-static functions should come first, in the order
114that they are declared in the header file, followed by static
115functions. Static functions should be in one or more separate pages
116(separated by form feed characters) in logical groups. A commonly
117useful way to divide groups is by "level", with high-level functions
118first, followed by groups of progressively lower-level functions.
119This makes it easy for the program's reader to see the top-down
120structure by reading from top to bottom.
121
122 All function declarations and definitions should include a
123prototype. Empty parentheses, e.g. "int foo();", do not include a
124prototype (they state that the function's parameters are unknown);
125write "void" in parentheses instead, e.g. "int foo(void);".
126
127 Prototypes for static functions should either all go at the top of
128the file, separated into groups by blank lines, or they should appear
129at the top of each page of functions. Don't comment individual
130prototypes, but a comment on each group of prototypes is often
131appropriate.
132
133 In the absence of good reasons for another order, the following
134parameter order is preferred. One notable exception is that data
135parameters and their corresponding size parameters should be paired.
136
137 1. The primary object being manipulated, if any (equivalent to the
138 "this" pointer in C++).
139 2. Input-only parameters.
140 3. Input/output parameters.
141 4. Output-only parameters.
142 5. Status parameter.
143
144 Example:
145
146 /* Stores the features supported by 'netdev' into each of '*current',
147 * '*advertised', '*supported', and '*peer' that are non-null. Each value
148 * is a bitmap of "enum ofp_port_features" bits, in host byte order.
149 * Returns 0 if successful, otherwise a positive errno value. On failure,
150 * all of the passed-in values are set to 0. */
151 int
152 netdev_get_features(struct netdev *netdev,
153 uint32_t *current, uint32_t *advertised,
154 uint32_t *supported, uint32_t *peer)
155 {
156 ...
157 }
158
b93e6983
BP
159Functions that destroy an instance of a dynamically-allocated type
160should accept and ignore a null pointer argument. Code that calls
161such a function (including the C standard library function free())
162should omit a null-pointer check. We find that this usually makes
163code easier to read.
164
064af421
BP
165
166FUNCTION PROTOTYPES
167
168 Put the return type and function name on the same line in a function
169prototype:
170
171 static const struct option_class *get_option_class(int code);
172
173
174 Omit parameter names from function prototypes when the names do not
175give useful information, e.g.:
176
3d222126 177 int netdev_get_mtu(const struct netdev *, int *mtup);
064af421
BP
178
179
180STATEMENTS
181
182 Indent each level of code with 4 spaces. Use BSD-style brace
183placement:
184
185 if (a()) {
186 b();
187 d();
188 }
189
190 Put a space between "if", "while", "for", etc. and the expressions
191that follow them.
192
193 Enclose single statements in braces:
194
195 if (a > b) {
196 return a;
197 } else {
198 return b;
199 }
200
201 Use comments and blank lines to divide long functions into logical
202groups of statements.
203
204 Avoid assignments inside "if" and "while" conditions.
205
206 Do not put gratuitous parentheses around the expression in a return
207statement, that is, write "return 0;" and not "return(0);"
208
209 Write only one statement per line.
210
211 Indent "switch" statements like this:
212
213 switch (conn->state) {
214 case S_RECV:
215 error = run_connection_input(conn);
216 break;
217
218 case S_PROCESS:
219 error = 0;
220 break;
221
222 case S_SEND:
223 error = run_connection_output(conn);
224 break;
225
226 default:
227 NOT_REACHED();
228 }
229
230 "switch" statements with very short, uniform cases may use an
231abbreviated style:
232
233 switch (code) {
234 case 200: return "OK";
235 case 201: return "Created";
236 case 202: return "Accepted";
237 case 204: return "No Content";
238 default: return "Unknown";
239 }
240
241 Use "for (;;)" to write an infinite loop.
242
243 In an if/else construct where one branch is the "normal" or "common"
244case and the other branch is the "uncommon" or "error" case, put the
245common case after the "if", not the "else". This is a form of
246documentation. It also places the most important code in sequential
247order without forcing the reader to visually skip past less important
248details. (Some compilers also assume that the "if" branch is the more
249common case, so this can be a real form of optimization as well.)
250
251
252MACROS
253
254 Don't define an object-like macro if an enum can be used instead.
255
256 Don't define a function-like macro if a "static inline" function
257can be used instead.
258
259 If a macro's definition contains multiple statements, enclose them
260with "do { ... } while (0)" to allow them to work properly in all
261syntactic circumstances.
262
263 Do use macros to eliminate the need to update different parts of a
264single file in parallel, e.g. a list of enums and an array that gives
265the name of each enum. For example:
266
267 /* Logging importance levels. */
268 #define VLOG_LEVELS \
269 VLOG_LEVEL(EMER, LOG_ALERT) \
270 VLOG_LEVEL(ERR, LOG_ERR) \
271 VLOG_LEVEL(WARN, LOG_WARNING) \
272 VLOG_LEVEL(INFO, LOG_NOTICE) \
273 VLOG_LEVEL(DBG, LOG_DEBUG)
274 enum vlog_level {
275 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) VLL_##NAME,
276 VLOG_LEVELS
277 #undef VLOG_LEVEL
278 VLL_N_LEVELS
279 };
280
281 /* Name for each logging level. */
282 static const char *level_names[VLL_N_LEVELS] = {
283 #define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
284 VLOG_LEVELS
285 #undef VLOG_LEVEL
286 };
287
288
289SOURCE FILES
290
291 Each source file should state its license in a comment at the very
292top, followed by a comment explaining the purpose of the code that is
293in that file. The comment should explain how the code in the file
294relates to code in other files. The goal is to allow a programmer to
295quickly figure out where a given module fits into the larger system.
296
297 The first non-comment line in a .c source file should be:
298
299 #include <config.h>
300
301#include directives should appear in the following order:
302
303 1. #include <config.h>
304
305 2. The module's own headers, if any. Including this before any
306 other header (besides <config.h>) ensures that the module's
307 header file is self-contained (see HEADER FILES) below.
308
309 3. Standard C library headers and other system headers, preferably
310 in alphabetical order. (Occasionally one encounters a set of
311 system headers that must be included in a particular order, in
312 which case that order must take precedence.)
313
314 4. Open vSwitch headers, in alphabetical order. Use "", not <>,
315 to specify Open vSwitch header names.
316
317
318HEADER FILES
319
320 Each header file should start with its license, as described under
321SOURCE FILES above, followed by a "header guard" to make the header
322file idempotent, like so:
323
324 #ifndef NETDEV_H
325 #define NETDEV_H 1
326
327 ...
328
329 #endif /* netdev.h */
330
331 Header files should be self-contained; that is, they should #include
332whatever additional headers are required, without requiring the client
333to #include them for it.
334
335 Don't define the members of a struct or union in a header file,
336unless client code is actually intended to access them directly or if
337the definition is otherwise actually needed (e.g. inline functions
338defined in the header need them).
339
340 Similarly, don't #include a header file just for the declaration of
341a struct or union tag (e.g. just for "struct <name>;"). Just declare
342the tag yourself. This reduces the number of header file
343dependencies.
344
345
346TYPES
347
348 Use typedefs sparingly. Code is clearer if the actual type is
349visible at the point of declaration. Do not, in general, declare a
350typedef for a struct, union, or enum. Do not declare a typedef for a
351pointer type, because this can be very confusing to the reader.
352
353 A function type is a good use for a typedef because it can clarify
354code. The type should be a function type, not a pointer-to-function
355type. That way, the typedef name can be used to declare function
356prototypes. (It cannot be used for function definitions, because that
357is explicitly prohibited by C89 and C99.)
358
359 You may assume that "char" is exactly 8 bits and that "int" and
360"long" are at least 32 bits.
361
362 Don't assume that "long" is big enough to hold a pointer. If you
363need to cast a pointer to an integer, use "intptr_t" or "uintptr_t"
364from <stdint.h>.
365
366 Use the int<N>_t and uint<N>_t types from <stdint.h> for exact-width
367integer types. Use the PRId<N>, PRIu<N>, and PRIx<N> macros from
368<inttypes.h> for formatting them with printf() and related functions.
369
370 Use %zu to format size_t with printf().
371
372 Use bit-fields sparingly. Do not use bit-fields for layout of
373network protocol fields or in other circumstances where the exact
374format is important.
375
376 Declare bit-fields to be type "unsigned int" or "signed int". Do
377*not* declare bit-fields of type "int": C89 allows these to be either
378signed or unsigned according to the compiler's whim. (A 1-bit
379bit-field of type "int" may have a range of -1...0!) Do not declare
380bit-fields of type _Bool or enum or any other type, because these are
381not portable.
382
383 Try to order structure members such that they pack well on a system
384with 2-byte "short", 4-byte "int", and 4- or 8-byte "long" and pointer
385types. Prefer clear organization over size optimization unless you
386are convinced there is a size or speed benefit.
387
388 Pointer declarators bind to the variable name, not the type name.
389Write "int *x", not "int* x" and definitely not "int * x".
390
391
392EXPRESSIONS
393
394 Put one space on each side of infix binary and ternary operators:
395
396 * / %
397 + -
398 << >>
399 < <= > >=
400 == !=
401 &
402 ^
403 |
404 &&
405 ||
406 ?:
407 = += -= *= /= %= &= ^= |= <<= >>=
408
409 Avoid comma operators.
410
411 Do not put any white space around postfix, prefix, or grouping
412operators:
413
414 () [] -> .
415 ! ~ ++ -- + - * &
416
417Exception 1: Put a space after (but not before) the "sizeof" keyword.
418Exception 2: Put a space between the () used in a cast and the
419expression whose type is cast: (void *) 0.
420
ede81843
BP
421 Break long lines before the ternary operators ? and :, rather than
422after them, e.g.
064af421
BP
423
424 return (out_port != VIGP_CONTROL_PATH
425 ? alpheus_output_port(dp, skb, out_port)
426 : alpheus_output_control(dp, skb, fwd_save_skb(skb),
427 VIGR_ACTION));
428
429
430 Do not parenthesize the operands of && and || unless operator
431precedence makes it necessary, or unless the operands are themselves
432expressions that use && and ||. Thus:
433
be2c418b
JP
434 if (!isdigit((unsigned char)s[0])
435 || !isdigit((unsigned char)s[1])
436 || !isdigit((unsigned char)s[2])) {
064af421
BP
437 printf("string %s does not start with 3-digit code\n", s);
438 }
439
440but
441
442 if (rule && (!best || rule->priority > best->priority)) {
443 best = rule;
444 }
445
446 Do parenthesize a subexpression that must be split across more than
447one line, e.g.:
448
449 *idxp = ((l1_idx << PORT_ARRAY_L1_SHIFT)
450 | (l2_idx << PORT_ARRAY_L2_SHIFT)
451 | (l3_idx << PORT_ARRAY_L3_SHIFT));
452
453 Try to avoid casts. Don't cast the return value of malloc().
454
455 The "sizeof" operator is unique among C operators in that it accepts
456two very different kinds of operands: an expression or a type. In
457general, prefer to specify an expression, e.g. "int *x =
458xmalloc(sizeof *x);". When the operand of sizeof is an expression,
459there is no need to parenthesize that operand, and please don't.
460
461 Use the ARRAY_SIZE macro from lib/util.h to calculate the number of
462elements in an array.
463
464 When using a relational operator like "<" or "==", put an expression
465or variable argument on the left and a constant argument on the
466right, e.g. "x == 0", *not* "0 == x".
467
468
469BLANK LINES
470
471 Put one blank line between top-level definitions of functions and
472global variables.
473
474
475C DIALECT
476
c214278b
BP
477 Some C99 features are OK because they are widely implemented even in
478older compilers:
064af421
BP
479
480 * Flexible array members (e.g. struct { int foo[]; }).
481
482 * "static inline" functions (but no other forms of "inline", for
483 which GCC and C99 have differing interpretations).
484
485 * "long long"
486
487 * <stdint.h> and <inttypes.h>.
488
489 * bool and <stdbool.h>, but don't assume that bool or _Bool can
490 only take on the values 0 or 1, because this behavior can't be
491 simulated on C89 compilers.
492
c214278b
BP
493 Don't use other C99 features that are not widely implemented in
494older compilers:
064af421
BP
495
496 * Don't use designated initializers (e.g. don't write "struct foo
497 foo = {.a = 1};" or "int a[] = {[2] = 5};").
498
499 * Don't mix declarations and code within a block.
500
501 * Don't use declarations in iteration statements (e.g. don't write
502 "for (int i = 0; i < 10; i++)").
503
504 * Don't put a trailing comma in an enum declaration (e.g. don't
505 write "enum { x = 1, };").
c214278b
BP
506
507 As a matter of style, avoid // comments.
508
509 Avoid using GCC extensions unless you also add a fallback for
510non-GCC compilers. You can, however, use GCC extensions and C99
511features in code that compiles only on GNU/Linux (such as
512lib/netdev-linux.c), because GCC is the system compiler there.