Initial import from FreeBSD RELENG_4:
[dragonfly.git] / share / man / man9 / style.9
1 .\" Copyright (c) 1995-2001 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 .\"
26 .Dd December 7, 2001
27 .Dt STYLE 9
28 .Os
29 .Sh NAME
30 .Nm style
31 .Nd "kernel source file style guide"
32 .Sh DESCRIPTION
33 This file specifies the preferred style for kernel source files in the
34 .Fx
35 source tree.
36 It is also a guide for preferred userland code style.
37 Many of the style rules are implicit in the examples.
38 Be careful to check the examples before assuming that
39 .Nm
40 is silent on an issue.
41 .Bd -literal
42 /*
43  * Style guide for FreeBSD.  Based on the CSRG's KNF (Kernel Normal Form).
44  *
45  *      @(#)style       1.14 (Berkeley) 4/28/95
46  * $FreeBSD: src/share/man/man9/style.9,v 1.32.2.19 2002/04/14 19:28:03 asmodai Exp $
47  */
48
49 /*
50  * VERY important single-line comments look like this.
51  */
52
53 /* Most single-line comments look like this. */
54
55 /*
56  * Multi-line comments look like this.  Make them real sentences.  Fill
57  * them so they look like real paragraphs.
58  */
59 .Ed
60 .Pp
61 After any copyright header, there is a blank line, and the
62 .Va rcsid
63 for source files.
64 Version control system ID tags should only exist once in a file
65 (unlike this one).
66 Non-C/C++ source files follow the example above, while C/C++ source files
67 follow the one below.
68 All VCS (version control system) revision identification from files obtained
69 from elsewhere should be maintained, including, where applicable, multiple IDs
70 showing a file's history.
71 In general, keep the IDs intact, including any
72 .So Li $ Sc Ns s .
73 There is no reason to add
74 .Qq Li "From"
75 in front of foreign VCS IDs.
76 Most
77 .No non- Ns Fx
78 VCS IDs should be indented by a tab if in a comment.
79 .Bd -literal
80 #include <sys/cdefs.h>
81 __RCSID("@(#)style      1.14 (Berkeley) 4/28/95");
82 __FBSDID("$FreeBSD: src/share/man/man9/style.9,v 1.32.2.19 2002/04/14 19:28:03 asmodai Exp $");
83 .Ed
84 .Pp
85 Leave another blank line before the header files.
86 .Pp
87 Kernel include files (i.e.\&
88 .Pa sys/*.h )
89 come first; normally, include
90 .Aq Pa sys/types.h
91 OR
92 .Aq Pa sys/param.h ,
93 but not both.
94 .Aq Pa sys/types.h
95 includes
96 .Aq Pa sys/cdefs.h ,
97 and it is okay to depend on that.
98 .Bd -literal
99 #include <sys/types.h>  /* Non-local includes in angle brackets. */
100 .Ed
101 .Pp
102 For a network program, put the network include files next.
103 .Bd -literal
104 #include <net/if.h>
105 #include <net/if_dl.h>
106 #include <net/route.h>
107 #include <netinet/in.h>
108 #include <protocols/rwhod.h>
109 .Ed
110 .Pp
111 Do not use files in
112 .Pa /usr/include
113 for files in the kernel.
114 .Pp
115 Leave a blank line before the next group, the
116 .Pa /usr
117 include files,
118 which should be sorted alphabetically by name.
119 .Bd -literal
120 #include <stdio.h>
121 .Ed
122 .Pp
123 Global pathnames are defined in
124 .Aq Pa paths.h .
125 Pathnames local
126 to the program go in
127 .Qq Pa pathnames.h
128 in the local directory.
129 .Bd -literal
130 #include <paths.h>
131 .Ed
132 .Pp
133 Leave another blank line before the user include files.
134 .Bd -literal
135 #include "pathnames.h"          /* Local includes in double quotes. */
136 .Ed
137 .Pp
138 Do not
139 .Ic #define
140 or declare names in the implementation namespace except
141 for implementing application interfaces.
142 .Pp
143 The names of
144 .Dq unsafe
145 macros (ones that have side effects), and the names of macros for
146 manifest constants, are all in uppercase.
147 The expansions of expression-like macros are either a single token
148 or have outer parentheses.
149 Put a single tab character between the
150 .Ic #define
151 and the macro name.
152 If a macro is an inline expansion of a function, the function name is
153 all in lowercase and the macro has the same name all in uppercase.
154 .\" XXX the above conflicts with ANSI style where the names are the
155 .\" same and you #undef the macro (if any) to get the function.
156 .\" It is not followed for MALLOC(), and not very common if inline
157 .\" functions are used.
158 If a
159 macro needs more than a single line, use braces
160 .Ql ( \&{
161 and
162 .Ql \&} ) .
163 Right-justify the
164 backslashes; it makes it easier to read.
165 If the macro encapsulates a compound statement, enclose it in a
166 .Ic do
167 loop,
168 so that it can safely be used in
169 .Ic if
170 statements.
171 Any final statement-terminating semicolon should be
172 supplied by the macro invocation rather than the macro, to make parsing easier
173 for pretty-printers and editors.
174 .Bd -literal
175 #define MACRO(x, y) do {                                                \e
176         variable = (x) + (y);                                           \e
177         (y) += 2;                                                       \e
178 } while(0)
179 .Ed
180 .Pp
181 Enumeration values are all uppercase.
182 .Bd -literal
183 enum enumtype { ONE, TWO } et;
184 .Ed
185 .Pp
186 When declaring variables in structures, declare them sorted by use, then
187 by size, and then in alphabetical order.
188 The first category normally does not apply, but there are exceptions.
189 Each one gets its own line.
190 Try to make the structure
191 readable by aligning the member names using either one or two tabs
192 depending upon your judgment.
193 You should use one tab if it suffices to align most of the member names.
194 Names following extremely long types
195 should be separated by a single space.
196 .Pp
197 Major structures should be declared at the top of the file in which they
198 are used, or in separate header files if they are used in multiple
199 source files.
200 Use of the structures should be by separate declarations
201 and should be
202 .Ic extern
203 if they are declared in a header file.
204 .Bd -literal
205 struct foo {
206         struct foo      *next;          /* List of active foo. */
207         struct mumble   amumble;        /* Comment for mumble. */
208         int             bar;            /* Try to align the comments. */
209         struct verylongtypename *baz;   /* Won't fit in 2 tabs. */
210 };
211 struct foo *foohead;                    /* Head of global foo list. */
212 .Ed
213 .Pp
214 Use
215 .Xr queue 3
216 macros rather than rolling your own lists, whenever possible.
217 Thus,
218 the previous example would be better written:
219 .Bd -literal
220 #include <sys/queue.h>
221
222 struct foo {
223         LIST_ENTRY(foo) link;           /* Use queue macros for foo lists. */
224         struct mumble   amumble;        /* Comment for mumble. */
225         int             bar;            /* Try to align the comments. */
226         struct verylongtypename *baz;   /* Won't fit in 2 tabs. */
227 };
228 LIST_HEAD(, foo) foohead;               /* Head of global foo list. */
229 .Ed
230 .Pp
231 Avoid using typedefs for structure types.
232 This makes it impossible
233 for applications to use pointers to such a structure opaquely, which
234 is both possible and beneficial when using an ordinary struct tag.
235 When convention requires a
236 .Ic typedef ,
237 make its name match the struct tag.
238 Avoid typedefs ending in
239 .Dq Li _t ,
240 except as specified in Standard C or by \*[Px].
241 .Bd -literal
242 /* Make the structure name match the typedef. */
243 typedef struct bar {
244         int     level;
245 } BAR;
246 typedef int             foo;            /* This is foo. */
247 typedef const long      baz;            /* This is baz. */
248 .Ed
249 .Pp
250 All functions are prototyped somewhere.
251 .Pp
252 Function prototypes for private functions (i.e. functions not used
253 elsewhere) go at the top of the first source module.
254 Functions
255 local to one source module should be declared
256 .Ic static .
257 .Pp
258 Functions used from other parts of the kernel are prototyped in the
259 relevant include file.
260 .Pp
261 Functions that are used locally in more than one module go into a
262 separate header file, e.g.\&
263 .Qq Pa extern.h .
264 .Pp
265 Only use the
266 .Dv __P
267 macro from the include file
268 .Aq Pa sys/cdefs.h
269 if the source
270 file in general is (to be) compilable with a K&R Old Testament compiler.
271 Use of the
272 .Dv __P
273 macro in new code is discouraged, although modifications
274 to existing files should be consistent with that file's conventions.
275 .Pp
276 In general code can be considered
277 .Dq "new code"
278 when it makes up about 50% or more of the file(s) involved.
279 This is enough
280 to break precedents in the existing code and use the current
281 .Nm
282 guidelines.
283 .Pp
284 The kernel has a name associated with parameter types, e.g., in the kernel
285 use:
286 .Bd -literal
287 void    function(int fd);
288 .Ed
289 .Pp
290 In header files visible to userland applications, prototypes that are
291 visible must use either
292 .Dq protected
293 names (ones beginning with an underscore)
294 or no names with the types.
295 It is preferable to use protected names.
296 E.g., use:
297 .Bd -literal
298 void    function(int);
299 .Ed
300 .Pp
301 or:
302 .Bd -literal
303 void    function(int _fd);
304 .Ed
305 .Pp
306 Prototypes may have an extra space after a tab to enable function names
307 to line up:
308 .Bd -literal
309 static char     *function(int _arg, const char *_arg2, struct foo *_arg3,
310                     struct bar *_arg4);
311 static void      usage(void);
312
313 /*
314  * All major routines should have a comment briefly describing what
315  * they do.  The comment before the "main" routine should describe
316  * what the program does.
317  */
318 int
319 main(int argc, char *argv[])
320 {
321         long num;
322         int ch;
323         char *ep;
324
325 .Ed
326 .Pp
327 For consistency,
328 .Xr getopt 3
329 should be used to parse options.
330 Options
331 should be sorted in the
332 .Xr getopt 3
333 call and the
334 .Ic switch
335 statement, unless
336 parts of the
337 .Ic switch
338 cascade.
339 Elements in a
340 .Ic switch
341 statement that cascade should have a
342 .Li FALLTHROUGH
343 comment.
344 Numerical arguments should be checked for accuracy.
345 Code that cannot be reached should have a
346 .Li NOTREACHED
347 comment.
348 .Bd -literal
349         while ((ch = getopt(argc, argv, "abn:")) != -1)
350                 switch (ch) {           /* Indent the switch. */
351                 case 'a':               /* Don't indent the case. */
352                         aflag = 1;
353                         /* FALLTHROUGH */
354                 case 'b':
355                         bflag = 1;
356                         break;
357                 case 'n':
358                         num = strtol(optarg, &ep, 10);
359                         if (num <= 0 || *ep != '\e0') {
360                                 warnx("illegal number, -n argument -- %s",
361                                     optarg);
362                                 usage();
363                         }
364                         break;
365                 case '?':
366                 default:
367                         usage();
368                         /* NOTREACHED */
369                 }
370         argc -= optind;
371         argv += optind;
372 .Ed
373 .Pp
374 Space after keywords
375 .Pq Ic if , while , for , return , switch .
376 No braces are
377 used for control statements with zero or only a single statement unless that
378 statement is more than a single line in which case they are permitted.
379 Forever loops are done with
380 .Ic for Ns 's ,
381 not
382 .Ic while Ns 's .
383 .Bd -literal
384         for (p = buf; *p != '\e0'; ++p)
385                 ;       /* nothing */
386         for (;;)
387                 stmt;
388         for (;;) {
389                 z = a + really + long + statement + that + needs +
390                     two lines + gets + indented + four + spaces +
391                     on + the + second + and + subsequent + lines;
392         }
393         for (;;) {
394                 if (cond)
395                         stmt;
396         }
397         if (val != NULL)
398                 val = realloc(val, newsize);
399 .Ed
400 .Pp
401 Parts of a
402 .Ic for
403 loop may be left empty.
404 Do not put declarations
405 inside blocks unless the routine is unusually complicated.
406 .Bd -literal
407         for (; cnt < 15; cnt++) {
408                 stmt1;
409                 stmt2;
410         }
411 .Ed
412 .Pp
413 Indentation is an 8 character tab.
414 Second level indents are four spaces.
415 If you have to wrap a long statement, put the operator at the end of the
416 line.
417 .Bd -literal
418         while (cnt < 20 && this_variable_name_is_too_long_for_its_own_good &&
419             ep != NULL)
420                 z = a + really + long + statement + that + needs +
421                     two lines + gets + indented + four + spaces +
422                     on + the + second + and + subsequent + lines;
423 .Ed
424 .Pp
425 Do not add whitespace at the end of a line, and only use tabs
426 followed by spaces
427 to form the indentation.
428 Do not use more spaces than a tab will produce
429 and do not use spaces in front of tabs.
430 .Pp
431 Closing and opening braces go on the same line as the
432 .Ic else .
433 Braces that are not necessary may be left out.
434 .Bd -literal
435         if (test)
436                 stmt;
437         else if (bar) {
438                 stmt;
439                 stmt;
440         } else
441                 stmt;
442 .Ed
443 .Pp
444 No spaces after function names.
445 Commas have a space after them.
446 No spaces
447 after
448 .Ql \&(
449 or
450 .Ql \&[
451 or preceding
452 .Ql \&]
453 or
454 .Ql \&)
455 characters.
456 .Bd -literal
457         error = function(a1, a2);
458         if (error != 0)
459                 exit(error);
460 .Ed
461 .Pp
462 Unary operators do not require spaces, binary operators do.
463 Do not use parentheses unless they are required for precedence or unless the
464 statement is confusing without them.
465 Remember that other people may
466 confuse easier than you.
467 Do YOU understand the following?
468 .Bd -literal
469         a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
470         k = !(l & FLAGS);
471 .Ed
472 .Pp
473 Exits should be 0 on success, or according to the predefined
474 values in
475 .Xr sysexits 3 .
476 .Bd -literal
477         exit(EX_OK);    /*
478                          * Avoid obvious comments such as
479                          * "Exit 0 on success."
480                          */
481 }
482 .Ed
483 .Pp
484 The function type should be on a line by itself
485 preceding the function.
486 .Bd -literal
487 static char *
488 function(int a1, int a2, float fl, int a4)
489 {
490 .Ed
491 .Pp
492 When declaring variables in functions declare them sorted by size,
493 then in alphabetical order; multiple ones per line are okay.
494 If a line overflows reuse the type keyword.
495 .Pp
496 Be careful to not obfuscate the code by initializing variables in
497 the declarations.
498 Use this feature only thoughtfully.
499 DO NOT use function calls in initializers.
500 .Bd -literal
501         struct foo one, *two;
502         double three;
503         int *four, five;
504         char *six, seven, eight, nine, ten, eleven, twelve;
505
506         four = myfunction();
507 .Ed
508 .Pp
509 Do not declare functions inside other functions; ANSI C says that
510 such declarations have file scope regardless of the nesting of the
511 declaration.
512 Hiding file declarations in what appears to be a local
513 scope is undesirable and will elicit complaints from a good compiler.
514 .Pp
515 Casts and
516 .Ic sizeof Ns 's
517 are not followed by a space.
518 Note that
519 .Xr indent 1
520 does not understand this rule.
521 .Pp
522 .Dv NULL
523 is the preferred null pointer constant.
524 Use
525 .Dv NULL
526 instead of
527 .Vt ( "type *" ) Ns 0
528 or
529 .Vt ( "type *" ) Ns Dv NULL
530 in contexts where the compiler knows the
531 type, e.g., in assignments.
532 Use
533 .Vt ( "type *" ) Ns Dv NULL
534 in other contexts,
535 in particular for all function args.
536 (Casting is essential for
537 variadic args and is necessary for other args if the function prototype
538 might not be in scope.)
539 Test pointers against
540 .Dv NULL ,
541 e.g., use:
542 .Pp
543 .Bd -literal
544 (p = f()) == NULL
545 .Ed
546 .Pp
547 not:
548 .Bd -literal
549 !(p = f())
550 .Ed
551 .Pp
552 Do not use
553 .Ic \&!
554 for tests unless it is a boolean, e.g. use
555 .Bd -literal
556 if (*p == '\e0')
557 .Ed
558 .Pp
559 not
560 .Bd -literal
561 if (!*p)
562 .Ed
563 .Pp
564 Routines returning
565 .Vt "void *"
566 should not have their return values cast
567 to any pointer type.
568 .Pp
569 Use
570 .Xr err 3
571 or
572 .Xr warn 3 ,
573 do not roll your own.
574 .Bd -literal
575         if ((four = malloc(sizeof(struct foo))) == NULL)
576                 err(1, (char *)NULL);
577         if ((six = (int *)overflow()) == NULL)
578                 errx(1, "number overflowed");
579         return (eight);
580 }
581 .Ed
582 .Pp
583 Old-style function declarations look like this:
584 .Bd -literal
585 static char *
586 function(a1, a2, fl, a4)
587         int a1, a2;     /* Declare ints, too, don't default them. */
588         float fl;       /* Beware double vs. float prototype differences. */
589         int a4;         /* List in order declared. */
590 {
591 .Ed
592 .Pp
593 Use ANSI function declarations unless you explicitly need K&R compatibility.
594 Long parameter lists are wrapped with a normal four space indent.
595 .Pp
596 Variable numbers of arguments should look like this.
597 .Bd -literal
598 #include <stdarg.h>
599
600 void
601 vaf(const char *fmt, ...)
602 {
603         va_list ap;
604
605         va_start(ap, fmt);
606         STUFF;
607         va_end(ap);
608         /* No return needed for void functions. */
609 }
610
611 static void
612 usage()
613 {
614         /* Insert an empty line if the function has no local variables. */
615 .Ed
616 .Pp
617 Use
618 .Xr printf 3 ,
619 not
620 .Xr fputs 3 ,
621 .Xr puts 3 ,
622 .Xr putchar 3 ,
623 whatever; it is faster and usually cleaner, not
624 to mention avoiding stupid bugs.
625 .Pp
626 Usage statements should look like the manual pages
627 .Sx SYNOPSIS .
628 The usage statement should be structured in the following order:
629 .Bl -enum
630 .It
631 Options without operands come first,
632 in alphabetical order,
633 inside a single set of brackets
634 .Ql ( \&[
635 and
636 .Ql \&] ) .
637 .It
638 Options with operands come next,
639 also in alphabetical order,
640 with each option and its argument inside its own pair of brackets.
641 .It
642 Required arguments
643 (if any)
644 are next,
645 listed in the order they should be specified on the command line.
646 .It
647 Finally,
648 any optional arguments should be listed,
649 listed in the order they should be specified,
650 and all inside brackets.
651 .El
652 .Pp
653 A bar
654 .Pq Ql \&|
655 separates
656 .Dq either-or
657 options/arguments,
658 and multiple options/arguments which are specified together are
659 placed in a single set of brackets.
660 .Bd -literal -offset 4n
661 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
662 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
663 .Ed
664 .Bd -literal
665         (void)fprintf(stderr, "usage: f [-ab]\en");
666         exit(EX_USAGE);
667 }
668 .Ed
669 .Pp
670 Note that the manual page options description should list the options in
671 pure alphabetical order.
672 That is, without regard to whether an option takes arguments or not.
673 The alphabetical ordering should take into account the case ordering
674 shown above.
675 .Pp
676 New core kernel code should be reasonably compliant with the
677 .Nm
678 guides.
679 The guidelines for third-party maintained modules and device drivers are more
680 relaxed but at a minimum should be internally consistent with their style.
681 .Pp
682 Stylistic changes (including whitespace changes) are hard on the source
683 repository and are to be avoided without good reason.
684 Code that is approximately
685 .Fx
686 KNF
687 .Nm
688 compliant in the repository must not diverge from compliance.
689 .Pp
690 Whenever possible, code should be run through a code checker
691 (e.g.,
692 .Xr lint 1
693 or
694 .Nm gcc Fl Wall )
695 and produce minimal warnings.
696 .Sh SEE ALSO
697 .Xr indent 1 ,
698 .Xr lint 1 ,
699 .Xr err 3 ,
700 .Xr sysexits 3 ,
701 .Xr warn 3
702 .Sh HISTORY
703 This man page is largely based on the
704 .Pa src/admin/style/style
705 file from the
706 .Bx 4.4 Lite2
707 release, with occasional updates to reflect the current practice and
708 desire of the
709 .Fx
710 project.