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