Rearrange navigation buttons in the HTML header
[krb5.git] / doc / coding-style
1 WRITING C CODE
2 ==============
3
4 The code in the krb5 source tree largely follows BSD KNF
5 (/usr/share/misc/style on NetBSD) except that it uses a four column
6 basic offset.  The style described here is a synthesis of BSD KNF and
7 the GNU coding standards for the C language.  The formatting described
8 in the "Formatting Your Source Code" section of the GNU coding
9 standards is mostly what we want, except we use BSD brace style and
10 BSD-ish conventions for the spacing around operators.
11
12 Formatting style for C code
13 ---------------------------
14
15 In general, use a four column basic offset, tab stops at eight
16 columns.  Indents should be tabified, i.e. continuous tabs followed by
17 spaces if necessary if the indent isn't a multiple of eight columns.
18 The "bsd" style in emacs cc-mode mostly does the right thing.  You can
19 use "M-x c-set-style" "bsd" to get this.  Alternatively, you can use
20 the "krb5" style that is included here.
21
22 Labels, including case labels, are outdented by four columns.
23 Continuations of statements are indented by an additional four
24 columns.  When continuing expressions this way, split the expression
25 so that the newline goes before a binary operator rather than after
26 it.
27
28 Continuations of argument lists or parenthesized expressions should
29 line up with the column after the opening parenthesis.  Note that this
30 may create width problems if you call a fuction deep in a bunch of
31 nested control flow statements.  Regardless, any expression split
32 between lines should stil be split so that the newline goes before a
33 binary operator rather than after it.
34
35 The maximum width should be 79 columns.  If you need more than this,
36 consider rewriting the code so that it fits in 79 columns, since
37 control flow that is nested deeply enough to require excessive width
38 is also likely to be difficult to understand if not broken up.
39 Exceptions may be made for long strings, though ANSI C string
40 concatenation should work around that as well.
41
42 Function names for definitions should start on column zero, on the
43 line following their return type name, e.g.
44
45         char *
46         foo(int a)
47         {
48             /* ... */
49         }
50
51 [just pretend that's really at column zero]
52
53 The opening brace of a function definition should also be on column
54 zero.
55
56 Braces that open substatements, such as those following "if", "else",
57 "while", "for", "do", and "switch", should be on the same line as the
58 begining of the statement.  This is sometimes called "hanging" braces.
59 The corresponding closing brace should be at the same indentation
60 level as the beginning of the statement.
61
62 The "while" keyword in a do-while construct should sit on the same
63 line as the closing brace of the substatement following "do":
64
65         do {
66             foo();
67         } while (0);
68
69 If there is an "if" statement immediately following an "else" keyword,
70 it should go on the same line immediately after the "else":
71
72         if (x) {
73             foo();
74         } else if (y) {
75             bar();
76         }
77
78 Comments to the right of code start in column 32.  Comments not to the
79 right of code are indented at the prevailing indent for the
80 surrounding code.  Make the comments complete sentences.  If you need
81 more than one line, make them into block comments, like this:
82
83         /*
84          * This is a block comment.  It should consist of complete
85          * sentences.
86          *
87          * Paragraphs should be separated by blank lines so that emacs
88          * fill commands will work properly.
89          */
90
91 Really important single-line comments should also be done in block
92 form:
93
94         /*
95          * This is a really important one-line comment.
96          */
97
98 In order to get the start and end delimiters for block comments to
99 stay when you use emacs to fill paragraphs in the comments, set both
100 the c-hanging-comment-starter-p and the c-hanging-comment-ender-p
101 variables to nil.  This will be done by the tentative "krb5" style for
102 the emacs cc-mode.
103
104 Since we are mostly aiming for C '89 compatibility, don't use "//"
105 comments.
106
107 Spaces go after keywords, but not after function names.  Do not,
108 however, put a space after sizeof.  Don't put a space after a cast
109 operator, either.  Spaces also do not go before parentheses that are
110 argument lists for function calls even if the function call is through
111 a pointer.  Spaces go after commas in argument lists, as well as
112 commas that are comma operators.  Spaces also go between parts in a
113 for loop, except for "forever" type loops.  Use for statements rather
114 than while statements to create forever loops.
115
116         if (x) {
117             p = calloc(1024, sizeof(int));
118         }
119         cp = (*elem->fp)(1024);
120         for (i = 0; i < 10; i++);
121         for (;;) {
122             /* ... */
123         }
124
125 Binary operators get spaces, unary ones do not.  Prefix and postfix
126 operators also do not get spaces.  The structure member operators "."
127 and "->" count as postfix operators syntactically, not as binary
128 operators.
129
130         x = --a + b / c - d++;
131         y = p->z.v[x];
132
133 Put spaces around the "?" and ":" in a conditional expression.
134
135         x = y ? f() : g();
136
137 In general, do not parenthesize the argument of "return".
138
139 Coding practices for C
140 ----------------------
141
142 Assume, for most purposes, working ANSI/ISO C ('89, not '99) support,
143 both for internal use and for applications compiling against Kerberos
144 header files and libraries.  Some exceptions are noted below.
145
146 Do not use assignments as truth values.  Rather than this:
147
148         /* bad style */
149         if ((retval = krb5_foo()))
150             /* ... */;
151
152 do this:
153
154         /* better style */
155         retval = krb5_foo();
156         if (retval)
157             /* ... */;
158
159 This makes the code easier to read, and also makes it easier to use
160 debuggers.  It may be excusable to put assignments into the
161 conditional espression of a "while" statement, though, like:
162
163         while ((ch = getopt(argc, argv, "abn")) != -1)
164             /* ... */;
165
166 Using assignments as truth values in conditional expressions may make
167 code particularly impenetrable.
168
169 There are at least three types of "zero" known to C.  These are the
170 integer zero (0), the null pointer constant (NULL), and the character
171 constant zero ('\0').  Yes, these are usually all technically the
172 integer zero.  Use them in their correct contexts.  (Purists will
173 point out that 0 is a valid null pointer constant; still, do not use 0
174 to specify a null pointer constant.  For further unconfusion, read the
175 section on null pointer constants in the C FAQ.)  Do not use a lone
176 variable as a truth value unless it's of integer type.  Thus:
177
178         int i;
179         char *cp;
180         /* ... */
181         if (i)
182             /* ... */;
183         if (cp != NULL) {
184             while (*cp != '\0')
185                 /* ... */;
186         }
187
188 Do not cast uses of NULL unless you're calling a function with a
189 variable number of arguments, in which case you should cast it to to
190 the appropriate pointer type.  Likewise, do not cast the return value
191 from malloc() and friends; the prototype should declare them properly
192 as returning a void * and thus shouldn't require an explicit cast.
193
194 Do not assume that realloc(NULL, size) will do the right thing, or
195 that free(NULL) will do the right thing.  ANSI guarantees that it
196 will, but some old libraries (hopefully becoming obsolete) don't.
197 Also, don't assume that malloc(0) will return a non-NULL pointer.
198 Typically, though, the output of malloc(0) will be safe to pass to
199 realloc() and free().
200
201 In any case, reading the section in the C FAQ on null pointers is
202 highly recommended to remove confusion regarding null pointers in C,
203 since this is a subject of much confusion to even experienced
204 programmers.  In particular, if you do not understand why using
205 calloc() to allocate a struct that contains pointer members or why
206 calling memset() to initialize such a struct to all-bytes-zero is
207 wrong, reread that section again.  (Note that there are *lots* of
208 examples of code in the krb5 source tree that erroneously calls
209 memset() to zero a struct, and we should fix these somehow
210 eventually.)
211
212 Control flow statements that have a single statement as their body
213 should nevertheless have braces around their bodies if the body is
214 more than one line long, especially in the case of stacked multiple
215 if-else clauses; use:
216
217         if (x) {
218             if (y)
219                 foo();
220             else
221                 bar();
222         }
223
224 instead of:
225
226         /* bad style */
227         if (x)
228             if (y)
229                 foo();
230             else
231                 bar();
232
233 which, while legible to the compiler, may confuse human readers and
234 make the code less maintainable, especially if new branches get added
235 to any of the clauses.
236
237 Also, you should almost never intersperse conditional compilation
238 directives with control flow statements, as some combination of
239 #define'd symbols may result in statements getting eaten by dangling
240 bits of control flow statements.  When it is not possible to avoid
241 this questionable practice (you really should rewrite the relevant
242 code section), make use of redundant braces to ensure that a compiler
243 error will result in preference to incorrect runtime behavior (such as
244 inadvertantly providing someone with a root shell).
245
246 Do not intersperse conditional compilation directives with control
247 flow statements in such a way that confuses emacs cc-mode.  Not only
248 does emacs get confused, but the code becomes more difficult to read
249 and maintain.  Therefore, avoid code like this:
250
251             /* bad style */
252             if (x) {
253                 f();
254             }
255         #ifdef FOO
256             else if (y) {
257         #else
258             else {
259         #endif
260                 g();
261             }
262
263 Put comments after conditional compilation directives such as "#else"
264 and "#endif".  Make them correspond to the sense of the value that
265 controls the compilation of the section they are closing, i.e.
266
267         #ifdef FOO
268         /* ... */
269         #else /* !FOO */
270         /* ... */
271         #endif /* !FOO */
272
273 Also, in the case of more complex conditional compilation directives,
274 write the comments like this:
275
276         #if defined(FOO) || defined(BAR)
277         /* ... */
278         #else /* !(defined(FOO) || defined(BAR)) */
279         /* ... */
280         #endif /* !(defined(FOO) || defined(BAR)) */
281
282 If you are writing a do-while loop that has only one statement in its
283 body, put braces around it anyway, since the while clause may be
284 mistaken for a while loop with an empty body.  Don't do this:
285
286         /* bad style */
287         do
288             foo();
289         while (x);
290
291 Instead, write this:
292
293         /* better style */
294         do {
295             foo();
296         } while (x);
297
298 While it is syntactically correct to call through a function pointer
299 without applying a dereference operator to it, do not write code that
300 does this.  It is easier to see that the function call is actually
301 taking place through a function pointer if you write an explicit
302 dereference.  However, do not explicitly take the address of a
303 function in order to assign it to a function pointer, since a function
304 name degrades into a pointer.  Thus:
305
306         int (*fp)(void);
307         int foofunc(void);
308         fp = foofunc;
309         x = (*fp)();
310
311 In general, do not take the address of an array.  It does not return a
312 pointer to the first element; it returns a pointer to the array
313 itself.  These are often identical when cast to an integral type, but
314 they are inherently of different types themselves.  Functions that
315 take array types or pointers to array types as arguments can be
316 particularly trouble-prone.
317
318 If a function is declared to return a value, do not call "return"
319 without an argument or allow the flow of control to fall off the end
320 of the function.
321
322 Always declare the return type of a function, even if it returns int.
323 Yes, this means declaring main() to return int, since main() is
324 required to return int by the standard.  If a function is not supposed
325 to return a value, declare it as returning void rather than omitting
326 the return type, which will default the return type to int.
327
328 Try to use ANSI C prototype-style function definitions in preference
329 to K&R style definitions.  When using K&R style function definitions,
330 declare all the argument types, even those that are int, but beware of
331 any narrow types in the argument list.
332
333 Do not declare variables in an inner scope, e.g. inside the compound
334 substatement of an if statement, unless the complexity of the code
335 really demands that the variables be declared that way.  In such
336 situations, the function could probably stand to be broken up into
337 smaller chunks anyway.  Do not declare variables in an inner scope
338 that shadow ones in an outer scope, since this leads to confusion.
339 Also, some debugging environments, such as gdb under Solaris, can't
340 see variables declared in an inner scope, so declaring such variables
341 will make maintenance more difficult as well.
342
343 Parenthesize expressions that may be confusing, particularly where C's
344 precedences are broken.  For example, the shift operators have lower
345 precedence than the +, -, *, /, and % operators.  Perhaps the most
346 familiar C precedence quirk is that equality and relational operators
347 are of higher precedence than assignment operators.  Less well known
348 is that the bitwise operators are of a lower precedence than equality
349 and relational operators.
350
351 The sizeof operator takes either a unary expression or a parenthesized
352 type name.  It is not necessary to parenthesize the operand of sizeof
353 if it is applied to a unary expression, but still, always parenthesize
354 the operand of the sizeof operator.  The sizeof operator does not
355 evaluate its operand if it is a unary expression, so usages such as
356
357         s = sizeof(++foo);
358
359 should be avoided for the sake of sanity and readability.
360
361 Don't pass around structures except by address.  We may relax this
362 restriction for non-API function, though.
363
364 For new functions, input parameters should go before output parameters
365 in the call signature.  There are exceptions, such as a context-like
366 parameter.
367
368 Every function should have block comment preceding it describing
369 briefly in complete sentences what it does, what inputs and outputs it
370 has, and what error codes it can return.  It should also describe any
371 unsual aspects of the function.  At some point we will want to put
372 some of this information into a machine-parsable form.
373
374 Macros should have all-uppercase names.  If it is necessary to use
375 multiple statements, use braces, and wrap the whole thing in a
376 do-while(0) construct, such as
377
378         #define FOOMACRO(x, y) do {                     \
379             foo = (x) + (y);                            \
380             f(y);                                       \
381         } while (0)
382
383 Leave off the semicolon at the end of a function-like macro, so that
384 it can be mostly used like a call to a function without a return
385 value.  Line up the backslashes to make it more readable.  Use M-x
386 c-backslash-region in emacs to do neat lined-up backslashes.
387 Parenthesize uses of arguments in the replacement text of a macro in
388 order to prevent weird interactions.
389
390 Strive to make your code capable of compiling using "gcc -Wall
391 -Wmissing-prototypes -Wtraditional -Wcast-qual -Wcast-align
392 -Wconversion -Waggregate-return -pedantic" [XXX need to rethink this
393 somewhat] without generating any errors or warnings.  Do not, however,
394 compile using the "-ansi" flag to gcc, since that can result in odd
395 behavior with header files on some systems, causing some necessary
396 symbols to not be defined.
397
398 Namespaces
399 ----------
400
401 The C standard reserves a bunch of namespaces for the implementation.
402 Don't stomp on them.  For practical purposes, any identifier with a
403 leading underscore should not be used.  (Technically, ^_[a-z].* are
404 reserved only for file scope, so should be safe for things smaller
405 than file scope, but it's better to be paranoid in this case.)
406
407 POSIX reserves typedef names ending with _t as well.
408
409 Recall that errno is a reserved identifier, and is permitted to be a
410 macro.  Therefore, do not use errno as the name of a structure member,
411 etc.
412
413 Reserved namespaces are somewhat more restricted than this; read the
414 appropriate section of the C standard if you have questions.
415
416 If you're writing new library code, pick a short prefix and stick with
417 it for any identifier with external linkage.  If for some reason a
418 library needs to have external symbols that should not be visible to
419 the application, pick another (related) prefix to use for the internal
420 globals.  This applies to typedef names, tag names, and preprocessor
421 identifiers as well.
422
423 For the krb5 library, the prefix for public global symbols is "krb5_".
424 Use "krb5int_" as a prefix for library internal globals.  Avoid using
425 "__" in symbol names, as it may confuse C++ implementations.  There
426 are admittedly a number of places where we leak thing into the
427 namespace; we should try to fix these.
428
429 Header files should also not leak symbols.  Usually using the upcased
430 version of the prefix you've picked will suffice, e.g. "KRB5_" as a
431 CPP symbol prefix corresponding to "krb5_".  In general, do not define
432 macros that are lowercase, in order to avoid confusion and to prevent
433 namespace collisions.
434
435 The C standard only guarantees six case-insensitive characters to be
436 significant in external identifiers; this is largely regarded as
437 obsolescent even in 1989 and we will ignore it.  It does, however,
438 only guarantee 31 case-sensitive characters to be signficant in
439 internal identifiers, so do not use identifiers that differ beyond the
440 31st character.  This is unlikely to be a problem, though.
441
442 Aspects of C style in GNU coding std but not here
443 -------------------------------------------------
444
445 * redundant parens to force extra indent of operators of different
446   precedences
447
448 * redundant parens to force general extra indent of expressions that
449   are broken between lines
450
451 * use of ^L characters to break up source files into pages
452
453 * nitpicking about capitalization in comments of variable names when
454   their values are meant
455
456 * commenting usages of static variables
457
458 * casts to void
459
460 * separation of word in names with underscores vs case change
461
462 * enum vs #define'd integer constants 
463
464 * 14 char filename limits, MS-DOS filename limits
465
466 * portability
467
468 * system library function quirks
469
470 * internationalization
471
472 * mmap()
473
474 Aspects of C style in BSD KNF but not here
475 ------------------------------------------
476
477 * sorting of header files
478
479 * sorting of struct members
480
481 * separating struct tag decl and struct typedef
482
483 * sorting of var decl
484
485 * lining up var names in decls
486
487 * newline after decls
488
489 * usage of __P
490
491 * usage of getopt
492
493 * not initializing vars in decls
494
495 * stdarg/varargs handling
496
497 Emacs cc-mode style
498 -------------------
499
500 Putting the following code in your .emacs file will result in mostly
501 the right thing happening with respect to formatting style.  Note that
502 you may want to turn on auto-newline feature of cc-mode, though that
503 seems to have some bugs with brace-elseif-brace handling at least in
504 the version of cc-mode that comes with emacs 20.3.
505
506         (defconst krb5-c-style
507           '("bsd" 
508             (c-cleanup-list
509              brace-elseif-brace brace-else-brace defun-close-semi)
510             (c-comment-continuation-stars . "* ")
511             (c-electric-pound-behavior alignleft)
512             (c-hanging-braces-alist
513              (brace-list-open)
514              (class-open after)
515              (substatement-open after)
516              (block-close . c-snug-do-while)
517              (extern-lang-open after))
518             (c-hanging-colons-alist
519              (case-label after)
520              (label after))
521             (c-hanging-comment-starter-p)
522             (c-hanging-comment-ender-p)
523             (c-indent-comments-syntactically-p . t)
524             (c-label-minimum-indentation . 0)
525             (c-special-indent-hook)))
526         (defun krb5-c-hook ()
527           (c-add-style "krb5" krb5-c-style t))
528         (add-hook 'c-mode-common-hook 'krb5-c-hook)
529
530 indent.pro settings
531 -------------------
532
533 The following settings for the indent program should produce a
534 reasonable approximation to the C coding style described here, though
535 some manual cleanup may be necessary.  Note that the gindent installed
536 in the gnu locker does not currently handle -psl correctly though.
537
538 -bap
539 -br
540 -ce
541 -ci4
542 -cli0
543 -d0
544 -di8
545 -i4
546 -ip4
547 -l79
548 -nbc
549 -ncdb
550 -ndj
551 -nfc1
552 -lp
553 -npcs
554 -psl
555 -sc
556 -sob
557
558 MAKEFILES
559 =========
560
561 [XXX needs to be written]
562
563 TEST SUITES
564 ===========
565
566 [XXX needs to be written]