-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodingStyle.txt
597 lines (437 loc) · 21.1 KB
/
CodingStyle.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
OVS NFP coding style
====================
This file describes the coding style used in most C files in the OVS
NFP project. Linux kernel code follows the Linux Kernel's established
coding conventions (Documentation/CodingStyle). Python code largely
follows Python coding conventions (PEP-8) and can be checked with
pylint.
BASICS
Limit lines to 79 characters.
You may use form feeds (control+L) to divide long source files into logical
pieces. A form feed should appear as the only character on a line.
Do not use tabs for indentation.
Avoid trailing spaces on lines.
NAMING
Use names that explain the purpose of a function or object.
Use underscores to separate words in an identifier: multi_word_name.
Use lowercase for most names. Use uppercase for macros, and members
of enumerations.
Give arrays names that are plural.
Pick a unique name prefix (ending with an underscore) for each
module, and apply that prefix to all of that module's externally
visible names. Names of macro parameters, struct and union members,
and parameters in function prototypes are not considered externally
visible for this purpose.
For some modules it may also be advisable to use a (potentially
shorter) unique prefix for names which are not exernally visible, in
particular for names which are very generic. This can make it easier
to debug and read the code."
Do not use names that begin with _. If you need a name for
"internal use only", use __ as a suffix instead of a prefix.
Avoid negative names: "found" is a better name than "not_found".
In names, a "size" is a count of bytes, a "length" is a count of
characters. A buffer has size, but a string has length. The length
of a string does not include the null terminator, but the size of the
buffer that contains the string does.
COMMENTS
Comments should be written as full sentences that start with a
capital letter and end with a period. Put two spaces between
sentences.
Comments which document an interface Doxygen style comments are
preferred but not required.
Write block comments as shown below. You may put the /* and */ on
the same line as comment text if you prefer.
/*
* We redirect stderr to /dev/null because we often want to remove all
* traffic control configuration on a port so its in a known state. If
* this done when there is no such configuration, tc complains, so we just
* always ignore it.
*/
Each function and each variable declared outside a function, and
each struct, union, and typedef declaration should be preceded by a
comment. See FUNCTION DEFINITIONS below for function comment
guidelines.
Each struct and union member should each have an inline comment that
explains its meaning. structs and unions with many members should be
additionally divided into logical groups of members by block comments,
e.g.:
/* An event that will wake the following call to poll_block(). */
struct poll_waiter {
/* Set when the waiter is created. */
struct list node; /* Element in global waiters list. */
int fd; /* File descriptor. */
short int events; /* Events to wait for (POLLIN, POLLOUT). */
poll_fd_func *function; /* Callback function, if any, or null. */
void *aux; /* Argument to callback function. */
struct backtrace *backtrace; /* Event that created waiter, or null. */
/* Set only when poll_block() is called. */
struct pollfd *pollfd; /* Pointer to element of the pollfds array
(null if added from a callback). */
};
Use XXX or FIXME comments to mark code that needs work.
Don't use // comments.
Don't comment out or #if 0 out code. Just remove it. The code that
was there will still be in version control history.
FUNCTIONS
Put the return type, function name, and the braces that surround the
function's code on separate lines, all starting in column 0.
Before each function definition, write a comment that describes the
function's purpose, including each parameter, the return value, and
side effects. References to argument names should be given in
single-quotes, e.g. 'arg', or when used to document public functions
as @arg. The comment should not include the function name, nor need
it follow any formal structure. The comment does not need to describe
how a function does its work, unless this information is needed to use
the function correctly (this is often better done with comments
*inside* the function).
Simple static functions do not need a comment.
Within a file, public functions should appear in the order they are
declared in the header file. Static functions should either be
defined before they are used or after all public functions with
prototypes defined at the top. Don't mix these alternatives unless
you have a good reason.
All function declarations and definitions should include a
prototype. Empty parentheses, e.g. "int foo();", do not include a
prototype (they state that the function's parameters are unknown);
write "void" in parentheses instead, e.g. "int foo(void);".
Prototypes for static functions should all go at the top of the
file, separated into groups by blank lines. Don't comment individual
prototypes, but a comment on each group of prototypes is often
appropriate.
In the absence of good reasons for another order, the following
parameter order is preferred. One notable exception is that data
parameters and their corresponding size parameters should be paired.
1. The primary object being manipulated, if any (equivalent to the
"this" pointer in C++).
2. Input-only parameters.
3. Input/output parameters.
4. Output-only parameters.
5. Status/Flag parameters.
Example:
/* Stores the features supported by 'netdev' into each of '*current',
* '*advertised', '*supported', and '*peer' that are non-null. Each value
* is a bitmap of "enum ofp_port_features" bits, in host byte order.
* Returns 0 if successful, otherwise a positive errno value. On failure,
* all of the passed-in values are set to 0. */
int
netdev_get_features(struct netdev *netdev,
uint32_t *current, uint32_t *advertised,
uint32_t *supported, uint32_t *peer)
{
...
}
Functions that destroy an instance of a dynamically-allocated type
should accept and ignore a null pointer argument. Code that calls
such a function (including the C standard library function free())
should omit a null-pointer check. We find that this usually makes
code easier to read.
FUNCTION PROTOTYPES
Put the return type and function name on the same line in a function
prototype:
static const struct option_class *get_option_class(int code);
Omit parameter names from function prototypes when the names do not
give useful information, e.g.:
int netdev_get_mtu(const struct netdev *, int *mtup);
STATEMENTS
Indent each level of code with 4 spaces. Use BSD-style brace
placement:
if (a()) {
b();
d();
}
Put a space between "if", "while", "for", etc. and the expressions
that follow them.
You nay enclose single statements in braces if it improves readability:
if (a > b) {
return a;
} else {
return b;
}
Use comments and blank lines to divide long functions into logical
groups of statements.
Avoid assignments inside "if" and "while" conditions.
Do not put gratuitous parentheses around the expression in a return
statement, that is, write "return 0;" and not "return(0);"
Write only one statement per line.
Indent "switch" statements like this:
switch (conn->state) {
case S_RECV:
error = run_connection_input(conn);
break;
case S_PROCESS:
error = 0;
break;
case S_SEND:
error = run_connection_output(conn);
break;
default:
NOT_REACHED();
}
"switch" statements with very short, uniform cases may use an
abbreviated style:
switch (code) {
case 200: return "OK";
case 201: return "Created";
case 202: return "Accepted";
case 204: return "No Content";
default: return "Unknown";
}
Use "for (;;)" to write an infinite loop.
In an if/else construct where one branch is the "normal" or "common"
case and the other branch is the "uncommon" or "error" case, put the
common case after the "if", not the "else". This is a form of
documentation. It also places the most important code in sequential
order without forcing the reader to visually skip past less important
details. (Some compilers also assume that the "if" branch is the more
common case, so this can be a real form of optimization as well.)
MACROS
Don't define an object-like macro if an enum can be used instead.
Don't define a function-like macro if a "static inline" function
can be used instead.
If a macro's definition contains multiple statements, enclose them
with "do { ... } while (0)" to allow them to work properly in all
syntactic circumstances.
Protect macro arguments by placing () around them when used.
Do use macros to eliminate the need to update different parts of a
single file in parallel, e.g. a list of enums and an array that gives
the name of each enum. For example:
/* Logging importance levels. */
#define VLOG_LEVELS \
VLOG_LEVEL(EMER, LOG_ALERT) \
VLOG_LEVEL(ERR, LOG_ERR) \
VLOG_LEVEL(WARN, LOG_WARNING) \
VLOG_LEVEL(INFO, LOG_NOTICE) \
VLOG_LEVEL(DBG, LOG_DEBUG)
enum vlog_level {
#define VLOG_LEVEL(NAME, SYSLOG_LEVEL) VLL_##NAME,
VLOG_LEVELS
#undef VLOG_LEVEL
VLL_N_LEVELS
};
/* Name for each logging level. */
static const char *level_names[VLL_N_LEVELS] = {
#define VLOG_LEVEL(NAME, SYSLOG_LEVEL) #NAME,
VLOG_LEVELS
#undef VLOG_LEVEL
};
SOURCE FILES
Each source file should state its license in a comment at the very
top, followed by a comment explaining the purpose of the code that is
in that file. The comment should explain how the code in the file
relates to code in other files. The goal is to allow a programmer to
quickly figure out where a given module fits into the larger system.
#include directives should appear in the following order:
1. Standard C header files
2. The module's own headers, if any.
3. Other modules headers.
A module may not rely on other module's headers to include header
files it requires, i.e. each module must explicitly include all header
files it depends on.
HEADER FILES
Each header file should start with its license, as described under
SOURCE FILES above, followed by a "header guard" to make the header
file idempotent, like so:
#ifndef NETDEV_H
#define NETDEV_H 1
...
#endif /* NETDEV_H */
Header files should be self-contained; that is, they should #include
whatever additional headers are required, without requiring the client
to #include them for it.
Don't define the members of a struct or union in a header file,
unless client code is actually intended to access them directly or if
the definition is otherwise actually needed (e.g. inline functions
defined in the header need them).
Similarly, don't #include a header file just for the declaration of
a struct or union tag (e.g. just for "struct <name>;"). Just declare
the tag yourself. This reduces the number of header file
dependencies.
TYPES
Use typedefs sparingly. Code is clearer if the actual type is
visible at the point of declaration. Do not, in general, declare a
typedef for a struct, union, or enum. Do not declare a typedef for a
pointer type, because this can be very confusing to the reader.
A function type is a good use for a typedef because it can clarify
code. The type should be a function type, not a pointer-to-function
type. That way, the typedef name can be used to declare function
prototypes. (It cannot be used for function definitions, because that
is explicitly prohibited by C89 and C99.)
You may assume that "char" is exactly 8 bits and that "int" and
"long" are at least 32 bits.
Don't assume that "long" is big enough to hold a pointer. If you
need to cast a pointer to an integer, use "intptr_t" or "uintptr_t"
from <stdint.h>.
Use the int<N>_t and uint<N>_t types from <stdint.h> for exact-width
integer types. Use the PRId<N>, PRIu<N>, and PRIx<N> macros from
<inttypes.h> for formatting them with printf() and related functions.
Use %zu to format size_t with printf().
Use bit-fields sparingly. Do not use bit-fields for layout of
network protocol fields or in other circumstances where the exact
format is important.
Declare bit-fields to be type "unsigned int" or "signed int". Do
*not* declare bit-fields of type "int": C89 allows these to be either
signed or unsigned according to the compiler's whim. (A 1-bit
bit-field of type "int" may have a range of -1...0!) Do not declare
bit-fields of type _Bool or enum or any other type, because these are
not portable.
Try to order structure members such that they pack well on a system
with 2-byte "short", 4-byte "int", and 4- or 8-byte "long" and pointer
types. Prefer clear organization over size optimization unless you
are convinced there is a size or speed benefit.
If 1-bit bit-fields are used for holding flags, do try and keep all
such structure members grouped together.
Pointer declarators bind to the variable name, not the type name.
Write "int *x", not "int* x" and definitely not "int * x".
EXPRESSIONS
Put one space on each side of infix binary and ternary operators:
* / %
+ -
<< >>
< <= > >=
== !=
&
^
|
&&
||
?:
= += -= *= /= %= &= ^= |= <<= >>=
Avoid comma operators.
Do not put any white space around postfix, prefix, or grouping
operators:
() [] -> .
! ~ ++ -- + - * &
Exception: Put a space between the () used in a cast and the
expression whose type is cast: (void *) 0.
Break long lines before the ternary operators ? and :, rather than
after them, e.g.
return (out_port != VIGP_CONTROL_PATH
? alpheus_output_port(dp, skb, out_port)
: alpheus_output_control(dp, skb, fwd_save_skb(skb),
VIGR_ACTION));
Do not parenthesize the operands of && and || unless operator
precedence makes it necessary, or unless the operands are themselves
expressions that use && and ||. Thus:
if (!isdigit((unsigned char)s[0])
|| !isdigit((unsigned char)s[1])
|| !isdigit((unsigned char)s[2])) {
printf("string %s does not start with 3-digit code\n", s);
}
but
if (rule && (!best || rule->priority > best->priority)) {
best = rule;
}
Do parenthesize a subexpression that must be split across more than
one line, e.g.:
*idxp = ((l1_idx << PORT_ARRAY_L1_SHIFT)
| (l2_idx << PORT_ARRAY_L2_SHIFT)
| (l3_idx << PORT_ARRAY_L3_SHIFT));
Try to avoid casts. Don't cast the return value of malloc().
The "sizeof" operator is unique among C operators in that it accepts
two very different kinds of operands: an expression or a type. In
general, prefer to specify an expression, e.g. "int *x =
xmalloc(sizeof *x);". When the operand of sizeof is an expression,
there is no need to parenthesize that operand, and please don't.
Use the ARRAY_SIZE macro to calculate the number of elements in an
array if available.
When using a relational operator like "<" or "==", put an expression
or variable argument on the left and a constant argument on the
right, e.g. "x == 0", *not* "0 == x".
BLANK LINES
Put one blank line between top-level definitions of functions and
global variables.
C DIALECT
Some C99 features are OK because they are widely implemented even in
older compilers:
* Flexible array members (e.g. struct { int foo[]; }).
* "static inline" functions (but no other forms of "inline", for
which GCC and C99 have differing interpretations).
* "long long"
* <stdint.h> and <inttypes.h>.
* bool and <stdbool.h>, but don't assume that bool or _Bool can
only take on the values 0 or 1, because this behavior can't be
simulated on C89 compilers.
Don't use other C99 features that are not widely implemented in
older compilers:
* Don't use designated initializers (e.g. don't write "struct foo
foo = {.a = 1};" or "int a[] = {[2] = 5};").
* Don't mix declarations and code within a block.
* Don't use declarations in iteration statements (e.g. don't write
"for (int i = 0; i < 10; i++)").
As a matter of style, avoid // comments.
Avoid using GCC extensions unless you also add a fallback for
non-GCC compilers. You can, however, use GCC extensions and C99
features in code that compiles only on GNU/Linux (such as
lib/netdev-linux.c), because GCC is the system compiler there.
MICRO C
The microC language is not quite the same as the C programming
language and there are some sharp corners that one should avoid when
writing in microC. There are also a few coding conventions that a
flowenv contribution should stick to to maintain consistency with other
flowenv code.
Never use implicit I/O operations in flowenv microC code. This could
occur by assigning to or from a variable that is declared with an
external storage qualifier such as __dram, __mem, __cls, __ctm, __imem,
__emem or the like. Although allowed by the compiler, this hides
expensive I/O operations and prevents the program from being confident
that it is updating ME-local state atomically since it may end up
unexpectedly yielding to other threads. (Note that passing around
_pointers_ to variables in these locations is perfectly fine.)
We highly recommend that you compile with the flag -Qspill=7. This
prevents any variable spilling, especially to non-local memories which
might lead to the situation mentioned above but in an even more subtle
way as the compiler puts the variable in an external memory without an
explicit declaration.
For functions that perform I/O operations, observe the following
conventions. If the function will block until all I/O is complete give
it a regular function name and do NOT pass it any parameters of type
sync_t, SIGNAL, SIGNAL_PAIR or pointers thereto. If the function will
start an I/O operation or a series of I/O operations, and will return
with one or more of them in flight, then the name of the function must
start with two underscores (i.e. "__") and the last parameters of
the function should be of type sync_t followed by one or more "SIGNAL *"
or "SIGNAL_PAIR *". The behavior of this function should depend on the
value of the sync_t variable:
* If the sync_t parameter is 'sig_done' the function should return
before the last I/O operation(s) complete leaving the caller to
wait on the "SIGNAL *" or "SIGNAL_PAIR *" parameters to complete
the I/O.
* If the sync_t parameter is 'ctx_swap' then the function should
block until all I/O operations are complete.
* If the sync_t parameter is 'sig_none' then the signal parameters
should all be NULL and the function should return immediately
leaving the last I/O operations in flight. Software would use
this option when it could infer the completion of the current
operation from the completion of subsequent operations.
A function need not support all three of sync_t values. It should
always use ctassert() to ensure that it only gets invoked with the
sync_t values that it supports.
If library code contains an I/O function starting with "__" it must
also contain the blocking variant that simply invokes the "__" variant
with a sync_t value of 'ctx_swap' and supplies an appropriate SIGNAL or
SIGNAL_PAIR parameter to that function.
When creating I/O functions also observe all of the following
conventions:
* Verify the correctness of all sync_t parameters with compile
time assertions.
* Specify sizes of I/O transfers in bytes.
* If the size of a transfer must be a compile-time constant, use
ctassert() to verify the correctness of the specified length.
* If the size of a transfer is not compile-time constant, use
try_ctassert() to attempt to verify any size parameter in case
it is a compile-time constant.
Be careful when using the '/' or '%' operators. While the compiler
will generate correct code for these operations, the run-time of such an
operator can rival or exceed that of an I/O operation in the system. In
particular, if the right hand side of the '/' or '%' operator is a
variable expression, you should expect that this code will be very slow.
This might well be fine if the code isn't in the fast path. But it is
something to be aware of.
The (char *) type is not the useful universal pointer type that it
normally is in C code. When it refers to ME local memory values, it can
produce very inefficient code. It should almost never be used to refer
to variables declared as __gpr, __read or __write. It is ok to use
(char *) for pointer arithmetic on variables stored in memory external
to the ME.
Do not use any of the functions from the ANSI standard C libraries.
They do not behave in the way that the programmer usually expects.