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