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