style revision 1.50
1/* $NetBSD: style,v 1.50 2012/06/27 22:04:02 riastradh Exp $ */
2
3/*
4 * The revision control tag appears first, with a blank line after it.
5 * Copyright text appears after the revision control tag.
6 */
7
8/*
9 * The NetBSD source code style guide.
10 * (Previously known as KNF - Kernel Normal Form).
11 *
12 *	from: @(#)style	1.12 (Berkeley) 3/18/94
13 */
14/*
15 * An indent(1) profile approximating the style outlined in
16 * this document lives in /usr/share/misc/indent.pro.  It is a
17 * useful tool to assist in converting code to KNF, but indent(1)
18 * output generated using this profile must not be considered to
19 * be an authoritative reference.
20 */
21
22/*
23 * Source code revision control identifiers appear after any copyright
24 * text.  Use the appropriate macros from <sys/cdefs.h>.  Usually only one
25 * source file per program contains a __COPYRIGHT() section.
26 * Historic Berkeley code may also have an __SCCSID() section.
27 * Only one instance of each of these macros can occur in each file.
28 * Don't use newlines in the identifiers.
29 */
30#include <sys/cdefs.h>
31__COPYRIGHT("@(#) Copyright (c) 2008\
32 The NetBSD Foundation, inc. All rights reserved.");
33__RCSID("$NetBSD: style,v 1.50 2012/06/27 22:04:02 riastradh Exp $");
34
35/*
36 * VERY important single-line comments look like this.
37 */
38
39/* Most single-line comments look like this. */
40
41/*
42 * Multi-line comments look like this.  Make them real sentences.  Fill
43 * them so they look like real paragraphs.
44 */
45
46/*
47 * Attempt to wrap lines longer than 80 characters appropriately.
48 * Refer to the examples below for more information.
49 */
50
51/*
52 * EXAMPLE HEADER FILE:
53 *
54 * A header file should protect itself against multiple inclusion.
55 * E.g, <sys/socket.h> would contain something like:
56 */
57#ifndef _SYS_SOCKET_H_
58#define _SYS_SOCKET_H_
59/*
60 * Contents of #include file go between the #ifndef and the #endif at the end.
61 */
62#endif /* !_SYS_SOCKET_H_ */
63/*
64 * END OF EXAMPLE HEADER FILE.
65 */
66
67/*
68 * If a header file requires structures, defines, typedefs, etc. from
69 * another header file it should include that header file and not depend
70 * on the including file for that header including both.  If there are
71 * exceptions to this for specific headers it should be clearly documented
72 * in the headers and, if appropriate, the documentation.  Nothing in this
73 * rule should suggest relaxation of the multiple inclusion rule and the
74 * application programmer should be free to include both regardless.
75 */
76
77/*
78 * Kernel include files come first.
79 */
80#include <sys/param.h>		/* <sys/param.h> first, */
81#include <sys/types.h>		/*   <sys/types.h> next, */
82#include <sys/ioctl.h>		/*   and then the rest, */
83#include <sys/socket.h>		/*   sorted lexicographically.  */
84#include <sys/stat.h>
85#include <sys/wait.h>		/* Non-local includes in brackets.  */
86
87/*
88 * If it's a network program, put the network include files next.
89 * Group the includes files by subdirectory.
90 */
91#include <net/if.h>
92#include <net/if_dl.h>
93#include <net/route.h>
94#include <netinet/in.h>
95#include <protocols/rwhod.h>
96
97/*
98 * Then there's a blank line, followed by the /usr include files.
99 * The /usr include files should be sorted lexicographically!
100 */
101#include <assert.h>
102#include <errno.h>
103#include <inttypes.h>
104#include <stdio.h>
105#include <stdlib.h>
106
107/*
108 * Global pathnames are defined in /usr/include/paths.h.  Pathnames local
109 * to the program go in pathnames.h in the local directory.
110 */
111#include <paths.h>
112
113/* Then, there's a blank line, and the user include files. */
114#include "pathnames.h"		/* Local includes in double quotes. */
115
116/*
117 * ANSI function declarations for private functions (i.e. functions not used
118 * elsewhere) and the main() function go at the top of the source module.
119 * Don't associate a name with the types.  I.e. use:
120 *	void function(int);
121 * Use your discretion on indenting between the return type and the name, and
122 * how to wrap a prototype too long for a single line.  In the latter case,
123 * lining up under the initial left parenthesis may be more readable.
124 * In any case, consistency is important!
125 */
126static char *function(int, int, float, int);
127static int dirinfo(const char *, struct stat *, struct dirent *,
128		   struct statfs *, int *, char **[]);
129static void usage(void) __dead;	/* declare functions that don't return dead */
130
131/*
132 * Macros are capitalized, parenthesized, and should avoid side-effects.
133 * Spacing before and after the macro name may be any whitespace, though
134 * use of TABs should be consistent through a file.
135 * If they are an inline expansion of a function, the function is defined
136 * all in lowercase, the macro has the same name all in uppercase.
137 * If the macro is an expression, wrap the expression in parenthesis.
138 * If the macro is more than a single statement, use ``do { ... } while (0)'',
139 * so that a trailing semicolon works.  Right-justify the backslashes; it
140 * makes it easier to read. The CONSTCOND comment is to satisfy lint(1).
141 */
142#define	MACRO(v, w, x, y)						\
143do {									\
144	v = (x) + (y);							\
145	w = (y) + 2;							\
146} while (/* CONSTCOND */ 0)
147
148#define	DOUBLE(x) ((x) * 2)
149
150/* Enum types are capitalized.  No comma on the last element. */
151enum enumtype {
152	ONE,
153	TWO
154} et;
155
156/*
157 * When declaring variables in structures, declare them organized by use in
158 * a manner to attempt to minimize memory wastage because of compiler alignment
159 * issues, then by size, and then by alphabetical order. E.g, don't use
160 * ``int a; char *b; int c; char *d''; use ``int a; int b; char *c; char *d''.
161 * Each variable gets its own type and line, although an exception can be made
162 * when declaring bitfields (to clarify that it's part of the one bitfield).
163 * Note that the use of bitfields in general is discouraged.
164 *
165 * Major structures should be declared at the top of the file in which they
166 * are used, or in separate header files, if they are used in multiple
167 * source files.  Use of the structures should be by separate declarations
168 * and should be "extern" if they are declared in a header file.
169 *
170 * It may be useful to use a meaningful prefix for each member name.
171 * E.g, for ``struct softc'' the prefix could be ``sc_''.
172 */
173struct foo {
174	struct foo *next;	/* List of active foo */
175	struct mumble amumble;	/* Comment for mumble */
176	int bar;
177	unsigned int baz:1,	/* Bitfield; line up entries if desired */
178		     fuz:5,
179		     zap:2;
180	uint8_t flag;
181};
182struct foo *foohead;		/* Head of global foo list */
183
184/* Make the structure name match the typedef. */
185typedef struct BAR {
186	int level;
187} BAR;
188
189/* C99 uintN_t is preferred over u_intN_t. */
190uint32_t zero;
191
192/*
193 * All major routines should have a comment briefly describing what
194 * they do.  The comment before the "main" routine should describe
195 * what the program does.
196 */
197int
198main(int argc, char *argv[])
199{
200	long num;
201	int ch;
202	char *ep;
203
204	/*
205	 * At the start of main(), call setprogname() to set the program
206	 * name.  This does nothing on NetBSD, but increases portability
207	 * to other systems.
208	 */
209	setprogname(argv[0]);
210
211	/*
212	 * For consistency, getopt should be used to parse options.
213	 * Options should be sorted in the getopt call and the switch
214	 * statement, unless parts of the switch cascade.  For the
215	 * sorting order, see the usage() example below.  Don't forget
216	 * to add option descriptions to the usage and the manpage.
217	 * Elements in a switch statement that cascade should have a
218	 * FALLTHROUGH comment.  Numerical arguments should be checked
219	 * for accuracy.  Code that cannot be reached should have a
220	 * NOTREACHED comment.
221	 */
222	while ((ch = getopt(argc, argv, "abn:")) != -1) {
223		switch (ch) {		/* Indent the switch. */
224		case 'a':		/* Don't indent the case. */
225			aflag = 1;
226			/* FALLTHROUGH */
227		case 'b':
228			bflag = 1;
229			break;
230		case 'n':
231			errno = 0;
232			num = strtol(optarg, &ep, 10);
233			if (num <= 0 || *ep != '\0' || (errno == ERANGE &&
234			    (num == LONG_MAX || num == LONG_MIN)) )
235				errx(1, "illegal number -- %s", optarg);
236			break;
237		case '?':
238		default:
239			usage();
240			/* NOTREACHED */
241		}
242	}
243	argc -= optind;
244	argv += optind;
245
246	/*
247	 * Space after keywords (while, for, return, switch).  No braces are
248	 * required for control statements with only a single statement,
249	 * unless it's a long statement.
250	 *
251	 * Forever loops are done with for's, not while's.
252	 */
253	for (p = buf; *p != '\0'; ++p)
254		continue;		/* Explicit no-op */
255	for (;;)
256		stmt;
257
258	/*
259	 * Braces are required for control statements with a single statement
260	 * that may expand to nothing.
261	 */
262#ifdef DEBUG_FOO
263#define DPRINTF(a) printf a
264#else
265#define DPRINTF(a)
266#endif
267	if (broken) {
268		DPRINTF(("broken is %d\n", broken));
269	}
270
271	/*
272	 * Parts of a for loop may be left empty.  Don't put declarations
273	 * inside blocks unless the routine is unusually complicated.
274	 */
275	for (; cnt < 15; cnt++) {
276		stmt1;
277		stmt2;
278	}
279
280	/* Second level indents are four spaces. */
281	while (cnt < 20)
282		z = a + really + long + statement + that + needs + two + lines +
283		    gets + indented + four + spaces + on + the + second +
284		    and + subsequent + lines;
285
286	/*
287	 * Closing and opening braces go on the same line as the else.
288	 * Don't add braces that aren't necessary except in cases where
289	 * there are ambiguity or readability issues.
290	 */
291	if (test) {
292		/*
293		 * I have a long comment here.
294		 */
295#ifdef zorro
296		z = 1;
297#else
298		b = 3;
299#endif
300	} else if (bar) {
301		stmt;
302		stmt;
303	} else
304		stmt;
305
306	/* No spaces after function names. */
307	if ((result = function(a1, a2, a3, a4)) == NULL)
308		exit(1);
309
310	/*
311	 * Unary operators don't require spaces, binary operators do.
312	 * Don't excessively use parenthesis, but they should be used if
313	 * statement is really confusing without them, such as:
314	 * a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
315	 */
316	a = ((b->c[0] + ~d == (e || f)) || (g && h)) ? i : (j >> 1);
317	k = !(l & FLAGS);
318
319	/*
320	 * Exits should be EXIT_SUCCESS on success, and EXIT_FAILURE on
321	 * failure.  Don't denote all the possible exit points, using the
322	 * integers 1 through 127.  Avoid obvious comments such as "Exit
323	 * 0 on success.". Since main is a function that returns an int,
324	 * prefer returning from it, than calling exit.
325	 */
326	return EXIT_SUCCESS;
327}
328
329/*
330 * The function type must be declared on a line by itself
331 * preceding the function.
332 */
333static char *
334function(int a1, int a2, float fl, int a4)
335{
336	/*
337	 * When declaring variables in functions declare them sorted by size,
338	 * then in alphabetical order; multiple ones per line are okay.
339	 * Function prototypes should go in the include file "extern.h".
340	 * If a line overflows reuse the type keyword.
341	 *
342	 * DO NOT initialize variables in the declarations.
343	 */
344	extern u_char one;
345	extern char two;
346	struct foo three, *four;
347	double five;
348	int *six, seven;
349	char *eight, *nine, ten, eleven, twelve, thirteen;
350	char fourteen, fifteen, sixteen;
351
352	/*
353	 * Casts and sizeof's are not followed by a space.  NULL is any
354	 * pointer type, and doesn't need to be cast, so use NULL instead
355	 * of (struct foo *)0 or (struct foo *)NULL.  Also, test pointers
356	 * against NULL.  I.e. use:
357	 *
358	 *	(p = f()) == NULL
359	 * not:
360	 *	!(p = f())
361	 *
362	 * The notable exception here is varyadic functions. Since our
363	 * code is designed to compile and work on different environments
364	 * where we don't have control over the NULL definition (on NetBSD
365	 * it is defined as ((void *)0), but on other systems it can be
366	 * defined as (0) and both definitions are valid under ANSI C), it
367	 * it advised to cast NULL to a pointer on varyadic functions,
368	 * because on machines where sizeof(pointer) != sizeof(int) and in
369	 * the absence of a prototype in scope, passing an un-casted NULL,
370	 * will result in passing an int on the stack instead of a pointer.
371	 *
372	 * Don't use `!' for tests unless it's a boolean.
373	 * E.g. use "if (*p == '\0')", not "if (!*p)".
374	 *
375	 * Routines returning ``void *'' should not have their return
376	 * values cast to more specific pointer types.
377	 *
378	 * Prefer sizeof(*var) over sizeof(type) because if type changes,
379	 * the change needs to be done in one place.
380	 *
381	 * Use err/warn(3), don't roll your own!
382	 */
383	if ((four = malloc(sizeof(*four))) == NULL)
384		err(1, NULL);
385	if ((six = (int *)overflow()) == NULL)
386		errx(1, "Number overflowed.");
387
388	/* No parentheses are needed around the return value. */
389	return eight;
390}
391
392/*
393 * Use ANSI function declarations.  ANSI function braces look like
394 * old-style (K&R) function braces.
395 * As per the wrapped prototypes, use your discretion on how to format
396 * the subsequent lines.
397 */
398static int
399dirinfo(const char *p, struct stat *sb, struct dirent *de, struct statfs *sf,
400	int *rargc, char **rargv[])
401{	/* Insert an empty line if the function has no local variables. */
402
403	/*
404	 * In system libraries, catch obviously invalid function arguments
405	 * using _DIAGASSERT(3).
406	 */
407	_DIAGASSERT(p != NULL);
408	_DIAGASSERT(filedesc != -1);
409
410	if (stat(p, sb) < 0)
411		err(1, "Unable to stat %s", p);
412
413	/*
414	 * To printf quantities that might be larger that "long", include
415	 * <inttypes.h>, cast quantities to intmax_t or uintmax_t and use
416	 * PRI?MAX constants.
417	 */
418	(void)printf("The size of %s is %" PRIdMAX " (%#" PRIxMAX ")\n", p,
419	    (intmax_t)sb->st_size, (uintmax_t)sb->st_size);
420
421	/*
422	 * To printf quantities of known bit-width, use the corresponding
423	 * defines (generally only done within NetBSD for quantities that
424	 * exceed 32-bits).
425	 */
426	(void)printf("%s uses %" PRId64 " blocks and has flags %#" PRIx32 "\n",
427	    p, sb->st_blocks, sb->st_flags);
428
429	/*
430	 * There are similar constants that should be used with the *scanf(3)
431	 * family of functions: SCN?MAX, SCN?64, etc.
432	 */
433}
434
435/*
436 * Functions that support variable numbers of arguments should look like this.
437 * (With the #include <stdarg.h> appearing at the top of the file with the
438 * other include files.)
439 */
440#include <stdarg.h>
441
442void
443vaf(const char *fmt, ...)
444{
445	va_list ap;
446
447	va_start(ap, fmt);
448	STUFF;
449	va_end(ap);
450				/* No return needed for void functions. */
451}
452
453static void
454usage(void)
455{
456
457	/*
458	 * Use printf(3), not fputs/puts/putchar/whatever, it's faster and
459	 * usually cleaner, not to mention avoiding stupid bugs.
460	 * Use snprintf(3) or strlcpy(3)/strlcat(3) instead of sprintf(3);
461	 * again to avoid stupid bugs.
462	 *
463	 * Usage statements should look like the manual pages.
464	 * Options w/o operands come first, in alphabetical order
465	 * inside a single set of braces, upper case before lower case
466	 * (AaBbCc...).  Next are options with operands, in the same
467	 * order, each in braces.  Then required arguments in the
468	 * order they are specified, followed by optional arguments in
469	 * the order they are specified.  A bar (`|') separates
470	 * either/or options/arguments, and multiple options/arguments
471	 * which are specified together are placed in a single set of
472	 * braces.
473	 *
474	 * Use getprogname() instead of hardcoding the program name.
475	 *
476	 * "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\n"
477	 * "usage: f [-a | -b] [-c [-de] [-n number]]\n"
478	 */
479	(void)fprintf(stderr, "usage: %s [-ab]\n", getprogname());
480	exit(EXIT_FAILURE);
481}
482