xref: /freebsd/share/man/man9/style.9 (revision 380a989b3223d455375b4fae70fd0b9bdd43bafb)
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.21 1997/12/07 20:19:20 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.
260Forever loops are done with for's, not while's.
261.Bd -literal -offset 0i
262	for (p = buf; *p != '\e0'; ++p)
263		;	/* nothing */
264	for (;;)
265		stmt;
266	if (val != NULL)
267		val = realloc(val, newsize);
268.Ed
269.Pp
270Parts of a for loop may be left empty.  Don't put declarations
271inside blocks unless the routine is unusually complicated.
272.Bd -literal -offset 0i
273	for (; cnt < 15; cnt++) {
274		stmt1;
275		stmt2;
276	}
277.Ed
278.Pp
279Indentation is an 8 character tab.
280Second level indents are four spaces.
281.Bd -literal -offset 0i
282	while (cnt < 20)
283		z = a + really + long + statement + that + needs +
284		    two lines + gets + indented + four + spaces +
285		    on + the + second + and + subsequent + lines.
286.Ed
287.Pp
288Do not add whitespace at the end of a line, and only use tabs then spaces
289to form the indentation.  Do not use more spaces than a tab will produce
290and do not use spaces in front of tabs.
291.Pp
292Closing and opening braces go on the same line as the else.
293Don't add braces that aren't necessary.
294.Bd -literal -offset 0i
295	if (test)
296		stmt;
297	else if (bar) {
298		stmt;
299		stmt;
300	} else
301		stmt;
302.Ed
303.Pp
304No spaces after function names.  Commas have a space after them.  No spaces
305after
306.Sq \&(
307or
308.Sq \&[
309or preceding
310.Sq \&]
311or
312.Sq \&)
313characters.
314.Bd -literal -offset 0i
315	if (error = function(a1, a2))
316		exit(error);
317.Ed
318.Pp
319Unary operators don't require spaces, binary operators do. Don't
320use parentheses unless they're required for precedence, or the
321statement is really confusing without them.
322.Bd -literal -offset 0i
323	a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
324	k = !(l & FLAGS);
325.Ed
326.Pp
327Exits should be 0 on success, or according to the predefined
328values in
329.Xr sysexits 3 .
330.Bd -literal -offset 0i
331	exit(EX_OK);	/*
332			 * Avoid obvious comments such as
333			 * "Exit 0 on success."
334			 */
335}
336.Ed
337.Pp
338The function type should be on a line by itself
339preceding the function.
340.Bd -literal -offset 0i
341static char *
342function(int a1, int a2, float fl, int a4)
343{
344.Ed
345.Pp
346When declaring variables in functions declare them sorted by size,
347then in alphabetical order; multiple ones per line are okay.
348Declaring functions inside functions is not recommendable, since their
349linkage scope is always global.  If a line overflows reuse the type
350keyword.
351.Pp
352Be careful to not obfuscate the code by initializing variables in
353the declarations.  Use this feature only thoughtfully.
354DO NOT use function calls in initializers!
355.Bd -literal -offset 0i
356	struct foo one, *two;
357	double three;
358	int *four, five;
359	char *six, seven, eight, nine, ten, eleven, twelve;
360
361	four = myfunction();
362.Ed
363.Pp
364Do not declare functions inside other functions; ANSI C says that
365such declarations have file scope regardless of the nesting of the
366declaration.  Hiding file declarations in what appears to be a local
367scope is undesirable and will elicit complaints from a good compiler.
368.Pp
369Casts and sizeof's are not followed by a space.  Note that
370.Xr indent 1
371does not understand this rule.
372.Pp
373NULL is the preferred null pointer constant.  Use NULL instead of
374(type *)0 or (type *)NULL in contexts where the compiler knows the
375type, e.g., in assignments.  Use (type *)NULL in other contexts,
376in particular for all function args.  (Casting is essential for
377varadic args and is necessary for other args if the function prototype
378might not be in scope.)
379Test pointers
380against NULL, e.g., use:
381.Bd -literal -offset 0i
382(p = f()) == NULL
383.Ed
384.Pp
385not:
386.Bd -literal -offset 0i
387!(p = f())
388.Ed
389.Pp
390Don't use '!' for tests unless it's a boolean, e.g. use
391.Bd -literal -offset 0i
392if (*p == '\e0')
393.Ed
394.Pp
395not
396.Bd -literal -offset 0i
397if (!*p)
398.Ed
399.Pp
400Routines returning void * should not have their return values cast
401to any pointer type.
402.Pp
403Use
404.Xr err 3
405or
406.Xr warn 3 ,
407don't roll your own!
408.Bd -literal -offset 0i
409	if ((four = malloc(sizeof(struct foo))) == NULL)
410		err(1, (char *)NULL);
411	if ((six = (int *)overflow()) == NULL)
412		errx(1, "Number overflowed.");
413	return (eight);
414}
415.Ed
416.Pp
417Old-style function declarations look like this:
418.Bd -literal -offset 0i
419static char *
420function(a1, a2, fl, a4)
421	int a1, a2;	/* Declare ints, too, don't default them. */
422	float fl;	/* Beware double vs. float prototype differences. */
423	int a4;		/* List in order declared. */
424{
425.Ed
426.Pp
427Use ANSI function declarations unless you explicitly need K&R compatability.
428.Pp
429Variable numbers of arguments should look like this.
430.Bd -literal -offset 0i
431#include <stdarg.h>
432
433void
434vaf(const char *fmt, ...)
435{
436	va_list ap;
437
438	va_start(ap, fmt);
439	STUFF;
440	va_end(ap);
441	/* No return needed for void functions. */
442}
443
444static void
445usage()
446{
447	/* Insert an empty line if the function has no local variables. */
448.Ed
449.Pp
450Use
451.Xr printf 3 ,
452not fputs/puts/putchar/whatever, it's faster and usually cleaner, not
453to mention avoiding stupid bugs.
454.Pp
455Usage statements should look like the manual pages.  Options w/o
456operands come first, in alphabetical order inside a single set of
457braces.  Followed by options with operands, in alphabetical order,
458each in braces.  Followed by required arguments in the order they
459are specified, followed by optional arguments in the order they
460are specified.  A bar
461.Pq Sq \&|
462separates either/or options/arguments,
463and multiple options/arguments which are specified together are
464placed in a single set of braces.
465.Pp
466.Bd -ragged -offset 0.3i
467"usage: f [-ade] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
468"usage: f [-a | -b] [-c [-de] [-n number]]\en"
469.Ed
470.Bd -literal -offset 0i
471	(void)fprintf(stderr, "usage: f [-ab]\en");
472	exit(1);
473}
474.Ed
475.Pp
476New core kernel code should be reasonably compliant with the style guides.
477The guidelines for third-party maintained modules and device drivers are more
478relaxed but at a minimum should be internally consistant with their style.
479.Pp
480Stylistic changes (including whitespace changes) are hard on the source
481repository and are to be avoided without good reason.  Code that is
482approximately KNF compliant in the repository must not diverge from
483compliance.
484.Sh SEE ALSO
485.Xr indent 1 ,
486.Xr err 3 ,
487.Xr sysexits 3 ,
488.Xr warn 3
489.Sh HISTORY
490This man page is largely based on the src/admin/style/style file from
491the
492.Tn BSD
4934.4-Lite2 release, with updates to reflect the current practice and
494desire of the
495.Tn FreeBSD
496project.
497