xref: /freebsd/share/man/man9/style.9 (revision 6e8394b8baa7d5d9153ab90de6824bcd19b3b4e1)
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.22 1997/12/07 20:25:45 wollman 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
34This file specifies the preferred style for kernel source files in the
35.Tn FreeBSD
36source 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
54Kernel include files (i.e. sys/*.h) come first; normally, you'll need
55<sys/types.h>
56OR <sys/param.h>, but not both!  <sys/types.h> includes <sys/cdefs.h>,
57and 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
62If 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
71Then there's a blank line, followed by the /usr include files.
72The /usr include files should be sorted!
73.Bd -literal -offset 0i
74#include <stdio.h>
75.Ed
76.Pp
77Global pathnames are defined in /usr/include/paths.h.  Pathnames local
78to the program go in pathnames.h in the local directory.
79.Bd -literal -offset 0i
80#include <paths.h>
81.Ed
82.Pp
83Then, 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
88Macros are capitalized, parenthesized, and should avoid side-effects.
89If they are an inline expansion of a function, the function is defined
90all in lowercase, the macro has the same name all in uppercase. If the
91macro needs more than a single line, use braces.  Right-justify the
92backslashes, it makes it easier to read.
93If the macro encapsulates a compound statement, enclose it in a
94.Dq Li do
95loop,
96so that it can safely be used in
97.Dq Li if
98statements.
99Any final statement-terminating semicolon should be
100supplied by the macro invocation rather than the macro, to make parsing easier
101for 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
109Enumeration values are all uppercase.
110.Bd -literal -offset 0i
111enum enumtype { ONE, TWO } et;
112.Ed
113.Pp
114When declaring variables in structures, declare them sorted by use, then
115by size, and then by alphabetical order.  The first category normally
116doesn't apply, but there are exceptions.  Each one gets its own line.
117Put a tab after the first word, i.e. use
118.Ql int^Ix;
119and
120.Ql struct^Ifoo *x; .
121.Pp
122Major structures should be declared at the top of the file in which they
123are used, or in separate header files, if they are used in multiple
124source files.  Use of the structures should be by separate declarations
125and should be "extern" if they are declared in a header file.
126.Bd -literal -offset 0i
127struct foo {
128	struct	foo *next;	/* List of active foo */
129	struct	mumble amumble;	/* Comment for mumble */
130	int	bar;
131};
132struct foo *foohead;		/* Head of global foo list */
133.Ed
134.Pp
135Use
136.Xr queue 3
137macros rather than rolling your own lists, whenever possible.  Thus,
138the previous example would be better written:
139.Bd -literal -offset 0i
140#include <sys/queue.h>
141struct	foo {
142	LIST_ENTRY(foo)	link;	/* Queue macro glue for foo lists */
143	struct	mumble amumble;	/* Comment for mumble */
144	int	bar;
145};
146LIST_HEAD(, foo) foohead;	/* Head of global foo list */
147.Ed
148.Pp
149Avoid using typedefs for structure types.  This makes it impossible
150for applications to use pointers to such a structure opaquely, which
151is both possible and beneficial when using an ordinary struct tag.
152When convention requires a typedef, make its name match the struct
153tag.  Avoid typedefs ending in
154.Dq Li \&_t ,
155except as specified in Standard C or by
156.Tn POSIX .
157.Bd -literal -offset 0i
158/* Make the structure name match the typedef. */
159typedef struct _bar {
160	int	level;
161} BAR;
162.Ed
163.Pp
164All functions are prototyped somewhere.
165.Pp
166Function prototypes for private functions (i.e. functions not used
167elsewhere) go at the top of the first source module.  Functions
168local to one source module should be declared
169.Ql static .
170.Pp
171Functions used from other parts of the kernel are prototyped in the
172relevant include file.
173.Pp
174Functions that are used locally in more than one module go into a
175separate header file, e.g.
176.Pa extern.h .
177.Pp
178Only use the __P macro from the include file <sys/cdefs.h> if the source
179file in general is (to be) compilable with a K&R Old testament compiler.
180Use of the __P macro in new code is discouraged, although modifications
181to existing files should be consistent with that file's conventions.
182.Pp
183In general code can be considered
184.Dq new code
185when it makes up about 50% or more of the file[s] involved.  This is enough
186to break precedents in the existing code and use the current style guidelines.
187.Pp
188The kernel has a name associated with parameter types, e.g., in the kernel
189use:
190.Bd -literal -offset 0i
191void	function(int fd);
192.Ed
193.Pp
194In header files visible to user land applications, prototypes that are
195visible must use either protected names or no names with the types.  It
196is preferable to use protected names.
197e.g., use:
198.Bd -literal -offset 0i
199void	function(int);
200.Ed
201.Pp
202or:
203.Bd -literal -offset 0i
204void	function(int _fd);
205.Ed
206.Pp
207Prototypes may have an extra space after a tab to enable function names
208to line up:
209.Bd -literal -offset 0i
210static char	*function(int _arg, const char *_arg2, struct foo *_arg3,
211			  struct bar *_arg4);
212static 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 */
219int
220main(int argc, char *argv[])
221{
222	long num;
223	int ch;
224	char *ep;
225
226.Ed
227.Pp
228For consistency, getopt should be used to parse options.  Options
229should be sorted in the getopt call and the switch statement, unless
230parts of the switch cascade.  Elements in a switch statement that
231cascade should have a FALLTHROUGH comment.  Numerical arguments
232should be checked for accuracy.  Code that cannot be reached should
233have 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
258Space after keywords (if, while, for, return, switch).  No braces are
259used for control statements with zero or only a single statement unless that
260statement is more than a single line in which case they are permitted.
261Forever 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
280Parts of a for loop may be left empty.  Don't put declarations
281inside 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
289Indentation is an 8 character tab.
290Second 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
298Do not add whitespace at the end of a line, and only use tabs then spaces
299to form the indentation.  Do not use more spaces than a tab will produce
300and do not use spaces in front of tabs.
301.Pp
302Closing and opening braces go on the same line as the else.
303Braces 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
314No spaces after function names.  Commas have a space after them.  No spaces
315after
316.Sq \&(
317or
318.Sq \&[
319or preceding
320.Sq \&]
321or
322.Sq \&)
323characters.
324.Bd -literal -offset 0i
325	if (error = function(a1, a2))
326		exit(error);
327.Ed
328.Pp
329Unary operators don't require spaces, binary operators do. Don't
330use parentheses unless they're required for precedence, or the
331statement is confusing without them. Remember that other people may
332confuse 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
338Exits should be 0 on success, or according to the predefined
339values 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
349The function type should be on a line by itself
350preceding the function.
351.Bd -literal -offset 0i
352static char *
353function(int a1, int a2, float fl, int a4)
354{
355.Ed
356.Pp
357When declaring variables in functions declare them sorted by size,
358then in alphabetical order; multiple ones per line are okay.
359Declaring functions inside functions is not recommendable, since their
360linkage scope is always global.  If a line overflows reuse the type
361keyword.
362.Pp
363Be careful to not obfuscate the code by initializing variables in
364the declarations.  Use this feature only thoughtfully.
365DO 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
375Do not declare functions inside other functions; ANSI C says that
376such declarations have file scope regardless of the nesting of the
377declaration.  Hiding file declarations in what appears to be a local
378scope is undesirable and will elicit complaints from a good compiler.
379.Pp
380Casts and sizeof's are not followed by a space.  Note that
381.Xr indent 1
382does not understand this rule.
383.Pp
384NULL is the preferred null pointer constant.  Use NULL instead of
385(type *)0 or (type *)NULL in contexts where the compiler knows the
386type, e.g., in assignments.  Use (type *)NULL in other contexts,
387in particular for all function args.  (Casting is essential for
388varadic args and is necessary for other args if the function prototype
389might not be in scope.)
390Test pointers
391against NULL, e.g., use:
392.Bd -literal -offset 0i
393(p = f()) == NULL
394.Ed
395.Pp
396not:
397.Bd -literal -offset 0i
398!(p = f())
399.Ed
400.Pp
401Don't use '!' for tests unless it's a boolean, e.g. use
402.Bd -literal -offset 0i
403if (*p == '\e0')
404.Ed
405.Pp
406not
407.Bd -literal -offset 0i
408if (!*p)
409.Ed
410.Pp
411Routines returning void * should not have their return values cast
412to any pointer type.
413.Pp
414Use
415.Xr err 3
416or
417.Xr warn 3 ,
418don'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
428Old-style function declarations look like this:
429.Bd -literal -offset 0i
430static char *
431function(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
438Use ANSI function declarations unless you explicitly need K&R compatability.
439.Pp
440Variable numbers of arguments should look like this.
441.Bd -literal -offset 0i
442#include <stdarg.h>
443
444void
445vaf(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
455static void
456usage()
457{
458	/* Insert an empty line if the function has no local variables. */
459.Ed
460.Pp
461Use
462.Xr printf 3 ,
463not fputs/puts/putchar/whatever, it's faster and usually cleaner, not
464to mention avoiding stupid bugs.
465.Pp
466Usage statements should look like the manual pages.  Options w/o
467operands come first, in alphabetical order inside a single set of
468braces.  Followed by options with operands, in alphabetical order,
469each in braces.  Followed by required arguments in the order they
470are specified, followed by optional arguments in the order they
471are specified.  A bar
472.Pq Sq \&|
473separates either/or options/arguments,
474and multiple options/arguments which are specified together are
475placed 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
487New core kernel code should be reasonably compliant with the style guides.
488The guidelines for third-party maintained modules and device drivers are more
489relaxed but at a minimum should be internally consistant with their style.
490.Pp
491Stylistic changes (including whitespace changes) are hard on the source
492repository and are to be avoided without good reason.  Code that is
493approximately KNF compliant in the repository must not diverge from
494compliance.
495.Pp
496Whenever 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
505This man page is largely based on the src/admin/style/style file from
506the
507.Tn BSD
5084.4-Lite2 release, with updates to reflect the current practice and
509desire of the
510.Tn FreeBSD
511project.
512