]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - share/man/man9/style.9
Add $Id$, to make it simpler for members of the translation teams to
[FreeBSD/FreeBSD.git] / share / man / man9 / style.9
1 .\" Copyright (c) 1995 FreeBSD Inc. 
2 .\" All rights reserved.
3 .\"
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
6 .\" are met:
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\"    notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\"    notice, this list of conditions and the following disclaimer in the
11 .\"    documentation and/or other materials provided with the distribution.
12 .\"
13 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 .\" ARE DISCLAIMED.  IN NO EVENT SHALL [your name] OR CONTRIBUTORS BE LIABLE
17 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 .\" SUCH DAMAGE.
24 .\"
25 .\"     $Id: style.9,v 1.23 1999/01/30 04:17:14 julian Exp $
26 .\"
27 .Dd December 14, 1995
28 .Dt STYLE 9
29 .Os FreeBSD
30 .Sh NAME
31 .Nm style
32 .Nd "Kernel source file style guide"
33 .Sh DESCRIPTION
34 This file specifies the preferred style for kernel source files in the
35 .Tn FreeBSD
36 source tree.  It is also a guide for preferred user land code style.
37 .Bd -literal -offset 0i
38 /*
39  * Style guide for the FreeBSD KNF (Kernel Normal Form).
40  */
41
42 /*
43  * VERY important single-line comments look like this.
44  */
45
46 /* Most single-line comments look like this. */
47
48 /*
49  * Multi-line comments look like this.  Make them real sentences.  Fill
50  * them so they look like real paragraphs.
51  */
52 .Ed
53 .Pp
54 Kernel include files (i.e. sys/*.h) come first; normally, you'll need
55 <sys/types.h>
56 OR <sys/param.h>, but not both!  <sys/types.h> includes <sys/cdefs.h>,
57 and it's okay to depend on that.
58 .Bd -literal -offset 0i
59 #include <sys/types.h>          /* Non-local includes in brackets. */
60 .Ed
61 .Pp
62 If it's a network program, put the network include files next.
63 .Bd -literal -offset 0i
64 #include <net/if.h>
65 #include <net/if_dl.h>
66 #include <net/route.h>
67 #include <netinet/in.h>
68 #include <protocols/rwhod.h>
69 .Ed
70 .Pp
71 Then there's a blank line, followed by the /usr include files.
72 The /usr include files should be sorted!
73 .Bd -literal -offset 0i
74 #include <stdio.h>
75 .Ed
76 .Pp
77 Global pathnames are defined in /usr/include/paths.h.  Pathnames local
78 to the program go in pathnames.h in the local directory.
79 .Bd -literal -offset 0i
80 #include <paths.h>
81 .Ed
82 .Pp
83 Then, there's a blank line, and the user include files.
84 .Bd -literal -offset 0i
85 #include "pathnames.h"          /* Local includes in double quotes. */
86 .Ed
87 .Pp
88 Macros are capitalized, parenthesized, and should avoid side-effects.
89 If they are an inline expansion of a function, the function is defined
90 all in lowercase, the macro has the same name all in uppercase. If the
91 macro needs more than a single line, use braces.  Right-justify the
92 backslashes, it makes it easier to read.
93 If the macro encapsulates a compound statement, enclose it in a
94 .Dq Li do
95 loop,
96 so that it can safely be used in 
97 .Dq Li if
98 statements.
99 Any final statement-terminating semicolon should be
100 supplied by the macro invocation rather than the macro, to make parsing easier
101 for pretty-printers and editors.
102 .Bd -literal -offset 0i
103 #define MACRO(x, y) do {                                                \e
104         variable = (x) + (y);                                           \e
105         (y) += 2;                                                       \e
106 } while(0)
107 .Ed
108 .Pp
109 Enumeration values are all uppercase.
110 .Bd -literal -offset 0i
111 enum enumtype { ONE, TWO } et;
112 .Ed
113 .Pp
114 When declaring variables in structures, declare them sorted by use, then
115 by size, and then by alphabetical order.  The first category normally
116 doesn't apply, but there are exceptions.  Each one gets its own line.
117 Put a tab after the first word, i.e. use
118 .Ql int^Ix;
119 and
120 .Ql struct^Ifoo *x; .
121 .Pp
122 Major structures should be declared at the top of the file in which they
123 are used, or in separate header files, if they are used in multiple
124 source files.  Use of the structures should be by separate declarations
125 and should be "extern" if they are declared in a header file.
126 .Bd -literal -offset 0i
127 struct foo {
128         struct  foo *next;      /* List of active foo */
129         struct  mumble amumble; /* Comment for mumble */
130         int     bar;
131 };
132 struct foo *foohead;            /* Head of global foo list */
133 .Ed
134 .Pp
135 Use
136 .Xr queue 3
137 macros rather than rolling your own lists, whenever possible.  Thus,
138 the previous example would be better written:
139 .Bd -literal -offset 0i
140 #include <sys/queue.h>
141 struct  foo {
142         LIST_ENTRY(foo) link;   /* Queue macro glue for foo lists */
143         struct  mumble amumble; /* Comment for mumble */
144         int     bar;
145 };
146 LIST_HEAD(, foo) foohead;       /* Head of global foo list */
147 .Ed
148 .Pp
149 Avoid using typedefs for structure types.  This makes it impossible
150 for applications to use pointers to such a structure opaquely, which
151 is both possible and beneficial when using an ordinary struct tag.
152 When convention requires a typedef, make its name match the struct
153 tag.  Avoid typedefs ending in
154 .Dq Li \&_t ,
155 except as specified in Standard C or by
156 .Tn POSIX .
157 .Bd -literal -offset 0i
158 /* Make the structure name match the typedef. */
159 typedef struct _bar {
160         int     level;
161 } BAR;
162 .Ed
163 .Pp
164 All functions are prototyped somewhere.
165 .Pp
166 Function prototypes for private functions (i.e. functions not used
167 elsewhere) go at the top of the first source module.  Functions
168 local to one source module should be declared
169 .Ql static .
170 .Pp
171 Functions used from other parts of the kernel are prototyped in the
172 relevant include file.
173 .Pp
174 Functions that are used locally in more than one module go into a
175 separate header file, e.g.
176 .Pa extern.h .
177 .Pp
178 Only use the __P macro from the include file <sys/cdefs.h> if the source
179 file in general is (to be) compilable with a K&R Old testament compiler.
180 Use of the __P macro in new code is discouraged, although modifications
181 to existing files should be consistent with that file's conventions.
182 .Pp
183 In general code can be considered
184 .Dq new code
185 when it makes up about 50% or more of the file[s] involved.  This is enough
186 to break precedents in the existing code and use the current style guidelines.
187 .Pp
188 The kernel has a name associated with parameter types, e.g., in the kernel
189 use:
190 .Bd -literal -offset 0i
191 void    function(int fd);
192 .Ed
193 .Pp
194 In header files visible to user land applications, prototypes that are
195 visible must use either protected names or no names with the types.  It
196 is preferable to use protected names.
197 e.g., use:
198 .Bd -literal -offset 0i
199 void    function(int);
200 .Ed
201 .Pp
202 or:
203 .Bd -literal -offset 0i
204 void    function(int _fd);
205 .Ed
206 .Pp
207 Prototypes may have an extra space after a tab to enable function names
208 to line up:
209 .Bd -literal -offset 0i
210 static char     *function(int _arg, const char *_arg2, struct foo *_arg3,
211                           struct bar *_arg4);
212 static void      usage(void);
213
214 /*
215  * All major routines should have a comment briefly describing what
216  * they do.  The comment before the "main" routine should describe
217  * what the program does.
218  */
219 int
220 main(int argc, char *argv[])
221 {
222         long num;
223         int ch;
224         char *ep;
225
226 .Ed
227 .Pp
228 For consistency, getopt should be used to parse options.  Options
229 should be sorted in the getopt call and the switch statement, unless
230 parts of the switch cascade.  Elements in a switch statement that
231 cascade should have a FALLTHROUGH comment.  Numerical arguments
232 should be checked for accuracy.  Code that cannot be reached should
233 have a NOTREACHED comment.
234 .Bd -literal -offset 0i
235         while ((ch = getopt(argc, argv, "abn")) != -1)
236                 switch (ch) {           /* Indent the switch. */
237                 case 'a':               /* Don't indent the case. */
238                         aflag = 1;
239                         /* FALLTHROUGH */
240                 case 'b':
241                         bflag = 1;
242                         break;
243                 case 'n':
244                         num = strtol(optarg, &ep, 10);
245                         if (num <= 0 || *ep != '\e0')
246                                 err("illegal number -- %s", optarg);
247                         break;
248                 case '?':
249                 default:
250                         usage();
251                         /* NOTREACHED */
252                 }
253         argc -= optind;
254         argv += optind;
255
256 .Ed
257 .Pp
258 Space after keywords (if, while, for, return, switch).  No braces are
259 used for control statements with zero or only a single statement unless that
260 statement is more than a single line in which case they are permitted.
261 Forever loops are done with for's, not while's.
262 .Bd -literal -offset 0i
263         for (p = buf; *p != '\e0'; ++p)
264                 ;       /* nothing */
265         for (;;)
266                 stmt;
267         for (;;) {
268                 z = a + really + long + statement + that + needs +
269                     two lines + gets + indented + four + spaces +
270                     on + the + second + and + subsequent + lines;
271         }
272         for (;;) {
273                 if (cond)
274                         stmt;
275         }
276         if (val != NULL)
277                 val = realloc(val, newsize);
278 .Ed
279 .Pp
280 Parts of a for loop may be left empty.  Don't put declarations
281 inside blocks unless the routine is unusually complicated.
282 .Bd -literal -offset 0i
283         for (; cnt < 15; cnt++) {
284                 stmt1;
285                 stmt2;
286         }
287 .Ed
288 .Pp
289 Indentation is an 8 character tab.
290 Second level indents are four spaces.
291 .Bd -literal -offset 0i
292         while (cnt < 20)
293                 z = a + really + long + statement + that + needs +
294                     two lines + gets + indented + four + spaces +
295                     on + the + second + and + subsequent + lines.
296 .Ed
297 .Pp
298 Do not add whitespace at the end of a line, and only use tabs then spaces
299 to form the indentation.  Do not use more spaces than a tab will produce
300 and do not use spaces in front of tabs.
301 .Pp
302 Closing and opening braces go on the same line as the else.
303 Braces that aren't necessary may be left out.
304 .Bd -literal -offset 0i
305         if (test)
306                 stmt;
307         else if (bar) {
308                 stmt;
309                 stmt;
310         } else
311                 stmt;
312 .Ed
313 .Pp
314 No spaces after function names.  Commas have a space after them.  No spaces
315 after
316 .Sq \&(
317 or
318 .Sq \&[
319 or preceding
320 .Sq \&]
321 or
322 .Sq \&)
323 characters.
324 .Bd -literal -offset 0i
325         if (error = function(a1, a2))
326                 exit(error);
327 .Ed
328 .Pp
329 Unary operators don't require spaces, binary operators do. Don't
330 use parentheses unless they're required for precedence, or the
331 statement is confusing without them. Remember that other people may
332 confuse easier then you. Do YOU understand the following?
333 .Bd -literal -offset 0i
334         a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
335         k = !(l & FLAGS);
336 .Ed
337 .Pp
338 Exits should be 0 on success, or according to the predefined
339 values in
340 .Xr sysexits 3 .
341 .Bd -literal -offset 0i
342         exit(EX_OK);    /*
343                          * Avoid obvious comments such as
344                          * "Exit 0 on success."
345                          */
346 }
347 .Ed
348 .Pp
349 The function type should be on a line by itself
350 preceding the function.
351 .Bd -literal -offset 0i
352 static char *
353 function(int a1, int a2, float fl, int a4)
354 {
355 .Ed
356 .Pp
357 When declaring variables in functions declare them sorted by size,
358 then in alphabetical order; multiple ones per line are okay.
359 Declaring functions inside functions is not recommendable, since their
360 linkage scope is always global.  If a line overflows reuse the type
361 keyword.
362 .Pp
363 Be careful to not obfuscate the code by initializing variables in
364 the declarations.  Use this feature only thoughtfully.
365 DO NOT use function calls in initializers!
366 .Bd -literal -offset 0i
367         struct foo one, *two;
368         double three;
369         int *four, five;
370         char *six, seven, eight, nine, ten, eleven, twelve;
371
372         four = myfunction();
373 .Ed
374 .Pp
375 Do not declare functions inside other functions; ANSI C says that
376 such declarations have file scope regardless of the nesting of the
377 declaration.  Hiding file declarations in what appears to be a local
378 scope is undesirable and will elicit complaints from a good compiler.
379 .Pp
380 Casts and sizeof's are not followed by a space.  Note that
381 .Xr indent 1
382 does not understand this rule.
383 .Pp
384 NULL is the preferred null pointer constant.  Use NULL instead of 
385 (type *)0 or (type *)NULL in contexts where the compiler knows the
386 type, e.g., in assignments.  Use (type *)NULL in other contexts,
387 in particular for all function args.  (Casting is essential for
388 varadic args and is necessary for other args if the function prototype
389 might not be in scope.)
390 Test pointers
391 against NULL, e.g., use:
392 .Bd -literal -offset 0i
393 (p = f()) == NULL
394 .Ed
395 .Pp
396 not:
397 .Bd -literal -offset 0i
398 !(p = f())
399 .Ed
400 .Pp
401 Don't use '!' for tests unless it's a boolean, e.g. use
402 .Bd -literal -offset 0i
403 if (*p == '\e0')
404 .Ed
405 .Pp
406 not
407 .Bd -literal -offset 0i
408 if (!*p)
409 .Ed
410 .Pp
411 Routines returning void * should not have their return values cast
412 to any pointer type.
413 .Pp
414 Use
415 .Xr err 3
416 or
417 .Xr warn 3 ,
418 don't roll your own!
419 .Bd -literal -offset 0i
420         if ((four = malloc(sizeof(struct foo))) == NULL)
421                 err(1, (char *)NULL);
422         if ((six = (int *)overflow()) == NULL)
423                 errx(1, "Number overflowed.");
424         return (eight);
425 }
426 .Ed
427 .Pp
428 Old-style function declarations look like this:
429 .Bd -literal -offset 0i
430 static char *
431 function(a1, a2, fl, a4)
432         int a1, a2;     /* Declare ints, too, don't default them. */
433         float fl;       /* Beware double vs. float prototype differences. */
434         int a4;         /* List in order declared. */
435 {
436 .Ed
437 .Pp
438 Use ANSI function declarations unless you explicitly need K&R compatibility.
439 .Pp
440 Variable numbers of arguments should look like this.
441 .Bd -literal -offset 0i
442 #include <stdarg.h>
443
444 void
445 vaf(const char *fmt, ...)
446 {
447         va_list ap;
448
449         va_start(ap, fmt);
450         STUFF;
451         va_end(ap);
452         /* No return needed for void functions. */
453 }
454
455 static void
456 usage()
457 {
458         /* Insert an empty line if the function has no local variables. */
459 .Ed
460 .Pp
461 Use
462 .Xr printf 3 ,
463 not fputs/puts/putchar/whatever, it's faster and usually cleaner, not
464 to mention avoiding stupid bugs.
465 .Pp
466 Usage statements should look like the manual pages.  Options w/o
467 operands come first, in alphabetical order inside a single set of
468 braces.  Followed by options with operands, in alphabetical order,
469 each in braces.  Followed by required arguments in the order they
470 are specified, followed by optional arguments in the order they
471 are specified.  A bar
472 .Pq Sq \&|
473 separates either/or options/arguments,
474 and multiple options/arguments which are specified together are
475 placed in a single set of braces.
476 .Pp
477 .Bd -ragged -offset 0.3i
478 "usage: f [-ade] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
479 "usage: f [-a | -b] [-c [-de] [-n number]]\en"
480 .Ed
481 .Bd -literal -offset 0i
482         (void)fprintf(stderr, "usage: f [-ab]\en");
483         exit(1);
484 }
485 .Ed
486 .Pp
487 New core kernel code should be reasonably compliant with the style guides.
488 The guidelines for third-party maintained modules and device drivers are more
489 relaxed but at a minimum should be internally consistent with their style.
490 .Pp
491 Stylistic changes (including whitespace changes) are hard on the source
492 repository and are to be avoided without good reason.  Code that is
493 approximately KNF compliant in the repository must not diverge from
494 compliance.
495 .Pp
496 Whenever possible, code should be run through a code checker
497 (e.g., "gcc -Wall" or xlint(1)) and produce minimal warnings.
498
499 .Sh SEE ALSO
500 .Xr indent 1 ,
501 .Xr err 3 ,
502 .Xr sysexits 3 ,
503 .Xr warn 3
504 .Sh HISTORY
505 This man page is largely based on the src/admin/style/style file from
506 the 
507 .Tn BSD 
508 4.4-Lite2 release, with updates to reflect the current practice and
509 desire of the
510 .Tn FreeBSD
511 project.