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