1/* $NetBSD: style,v 1.77 2024/01/29 05:42:41 rin 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.77 2024/01/29 05:42:41 rin 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/*
61 * Include other header files only as necessary, mainly for type
62 * definitions or macros that are necessary to use in this header file.
63 *
64 * Avoid relying on transitive inclusions.
65 *
66 * Avoid header files dependencies just for struct and union types that
67 * are used in pointer types, which don't require type definitions.
68 * Instead, use forward declarations of the struct or union tag.
69 */
70#include <sys/foobar.h>
71
72/*
73 * Forward declarations for struct and union tags that don't need
74 * definitions go next.
75 */
76struct dirent;
77
78/*
79 * Define public structs and unions, only if they are user-allocated or
80 * otherwise exposed to users for a good reason; otherwise keep them
81 * private to .c files or `_impl.h' or `_private.h' files.
82 *
83 * Do not create a typedef like `typedef struct example example_t;' or
84 * `typedef struct example *example_t;'.  Use `struct example' or
85 * `struct example *' in the public API; that way, other header files
86 * which declare functions or define struct or union types that involve
87 * only pointers to `struct example' need not pull in unnecessary
88 * header files.
89 */
90struct example {
91	struct data *p;
92	int x;
93	char y;
94};
95
96/*
97 * Use typedefs judiciously.
98 *
99 * Function or function pointer types:
100 */
101typedef void sighandler_t(int);
102
103/*
104 * Aliases for arithmetic types:
105 */
106typedef uint16_t nlink_t;
107
108/*
109 * Types that might be defined differently in some contexts, like
110 * uint8_t on one port, a pointer to a struct on another port, and an
111 * in-line struct larger than a pointer on a third port:
112 */
113typedef uint8_t foo_t;		/* Hypothetical leg26 definition */
114typedef struct foo *foo_t;	/* Hypothetical i786 definition */
115typedef struct {		/* Hypothetical risc72 definition */
116	uint32_t p;
117	uint32_t q;
118	uint8_t t;
119} foo_t;
120
121/*
122 * For opaque data structures that are always represented by a pointer
123 * when stored in other data structures or passed to functions, don't
124 * use a type `foo_t' with `typedef void *foo_t'.  Use `struct foo *'
125 * with no public definition for `struct foo', so the compiler can
126 * detect type errors, and other header files can use `struct foo *'
127 * without creating header file dependencies.
128 */
129
130/*
131 * extern declarations must only appear in header files, not in .c
132 * files, so the same declaration is used by the .c file defining it
133 * and the .c file using it, giving the compiler the opportunity to
134 * detect type errors.
135 *
136 * extern function declarations should not use the extern keyword,
137 * which is unnecessary.
138 *
139 * Exception: A subroutine written in assembly in an adjacent .S file,
140 * which is used only in one .c file, may be declared in the .c file.
141 */
142extern int frotz;
143
144int frobnicate(const char *, struct dirent *, foobar_t);
145
146/*
147 * Contents of #include file go between the #ifndef and the #endif at the end.
148 */
149#endif /* !_SYS_SOCKET_H_ */
150/*
151 * END OF EXAMPLE HEADER FILE.
152 */
153
154/*
155 * If a header file requires structures, defines, typedefs, etc. from
156 * another header file it should include that header file and not depend
157 * on the including file for that header including both.  If there are
158 * exceptions to this for specific headers it should be clearly documented
159 * in the headers and, if appropriate, the documentation.  Nothing in this
160 * rule should suggest relaxation of the multiple inclusion rule and the
161 * application programmer should be free to include both regardless.
162 */
163
164/*
165 * Kernel include files come first.
166 */
167#include <sys/param.h>		/* <sys/param.h> first, */
168#include <sys/types.h>		/*   <sys/types.h> next, */
169#include <sys/ioctl.h>		/*   and then the rest, */
170#include <sys/socket.h>		/*   sorted lexicographically.  */
171#include <sys/stat.h>
172#include <sys/wait.h>		/* Non-local includes in brackets.  */
173
174/*
175 * If it's a network program, put the network include files next.
176 * Group the include files by subdirectory.
177 */
178#include <net/if.h>
179#include <net/if_dl.h>
180#include <net/route.h>
181#include <netinet/in.h>
182#include <protocols/rwhod.h>
183
184/*
185 * Then there's a blank line, followed by the /usr include files.
186 * The /usr include files should be sorted lexicographically!
187 */
188#include <assert.h>
189#include <errno.h>
190#include <inttypes.h>
191#include <stdio.h>
192#include <stdlib.h>
193
194/*
195 * Global pathnames are defined in /usr/include/paths.h.  Pathnames local
196 * to the program go in pathnames.h in the local directory.
197 */
198#include <paths.h>
199
200/* Then, there's a blank line, and the user include files. */
201#include "pathnames.h"		/* Local includes in double quotes. */
202
203/*
204 * Declarations for file-static functions go at the top of the file.
205 * Don't associate a name with the parameter types.  I.e. use:
206 *	void function(int);
207 * Use your discretion on indenting between the return type and the name, and
208 * how to wrap a prototype too long for a single line.  In the latter case,
209 * lining up under the initial left parenthesis may be more readable.
210 * In any case, consistency is important!
211 */
212static char *function(int, int, float, int);
213static int dirinfo(const char *, struct stat *, struct dirent *,
214		   struct statfs *, int *, char **[]);
215static void usage(void) __dead;	/* declare functions that don't return dead */
216
217/*
218 * Macros are capitalized, parenthesized, and should avoid side-effects.
219 * Spacing before and after the macro name may be any whitespace, though
220 * use of TABs should be consistent through a file.
221 * If they are an inline expansion of a function, the function is defined
222 * all in lowercase, the macro has the same name all in uppercase.
223 * If the macro is an expression, wrap the expression in parentheses.
224 * If the macro is more than a single statement, use ``do { ... } while (0)''
225 * or ``do { ... } while (false)'', so that a trailing semicolon works.
226 * Right-justify the backslashes; it makes it easier to read.
227 */
228#define	MACRO(v, w, x, y)						\
229do {									\
230	v = (x) + (y);							\
231	w = (y) + 2;							\
232} while (0)
233
234#define	DOUBLE(x) ((x) * 2)
235
236/* Enum constants are capitalized.  No comma on the last element. */
237enum enumtype {
238	ONE,
239	TWO
240};
241
242/*
243 * Sometimes we want a macro to be conditionally defined for debugging
244 * and expand to nothing (but still as statement) when we are not debugging:
245 */
246#ifdef FOO_DEBUG
247# define DPRINTF(...) printf(__VA_ARGS__)
248#else
249# define DPRINTF(...) __nothing
250#endif
251
252/*
253 * When declaring variables in structures, declare them organized by use in
254 * a manner to attempt to minimize memory wastage because of compiler alignment
255 * issues, then by size, and then by alphabetical order. E.g, don't use
256 * ``int a; char *b; int c; char *d''; use ``int a; int b; char *c; char *d''.
257 * Each variable gets its own type and line, although an exception can be made
258 * when declaring bitfields (to clarify that it's part of the one bitfield).
259 * Note that the use of bitfields in general is discouraged.
260 *
261 * Major structures should be declared at the top of the file in which they
262 * are used, or in separate header files, if they are used in multiple
263 * source files.  Use of the structures should be by separate declarations
264 * and should be "extern" if they are declared in a header file.
265 *
266 * It may be useful to use a meaningful prefix for each member name.
267 * E.g, for ``struct softc'' the prefix could be ``sc_''.
268 *
269 * Don't create typedef aliases for struct or union types.  That way,
270 * other header files can use pointer types to them without the header
271 * file defining the typedef.
272 */
273struct foo {
274	struct foo *next;	/* List of active foo */
275	struct mumble amumble;	/* Comment for mumble */
276	int bar;
277	unsigned int baz:1,	/* Bitfield; line up entries if desired */
278		     fuz:5,
279		     zap:2;
280	uint8_t flag;
281};
282struct foo *foohead;		/* Head of global foo list */
283
284/* C99 uintN_t is preferred over u_intN_t. */
285uint32_t zero;
286
287/*
288 * All major routines should have a comment briefly describing what
289 * they do.  The comment before the "main" routine should describe
290 * what the program does.
291 */
292int
293main(int argc, char *argv[])
294{
295	long num;
296	int ch;
297	char *ep;
298
299	/*
300	 * At the start of main(), call setprogname() to set the program
301	 * name.  This does nothing on NetBSD, but increases portability
302	 * to other systems.
303	 */
304	setprogname(argv[0]);
305
306	/*
307	 * For consistency, getopt should be used to parse options.
308	 * Options should be sorted in the getopt call and the switch
309	 * statement, unless parts of the switch cascade.  For the
310	 * sorting order, see the usage() example below.  Don't forget
311	 * to add option descriptions to the usage and the manpage.
312	 * Elements in a switch statement that cascade should have a
313	 * FALLTHROUGH comment.  Numerical arguments should be checked
314	 * for accuracy.  Code that cannot be reached should have a
315	 * NOTREACHED comment.
316	 */
317	while ((ch = getopt(argc, argv, "abn:")) != -1) {
318		switch (ch) {		/* Indent the switch. */
319		case 'a':		/* Don't indent the case. */
320			aflag = 1;
321			/* FALLTHROUGH */
322		case 'b':
323			bflag = 1;
324			break;
325		case 'n':
326			errno = 0;
327			num = strtol(optarg, &ep, 10);
328			if (num <= 0 || *ep != '\0' || (errno == ERANGE &&
329			    (num == LONG_MAX || num == LONG_MIN)) ) {
330				errx(1, "illegal number -- %s", optarg);
331			}
332			break;
333		case '?':
334		default:
335			usage();
336			/* NOTREACHED */
337		}
338	}
339	argc -= optind;
340	argv += optind;
341
342	/*
343	 * Space after keywords (while, for, return, switch).
344	 *
345	 * Braces around single-line bodies are optional; use discretion.
346	 *
347	 * Use narrow scopes for loop variables where possible.
348	 */
349	for (char *p = buf; *p != '\0'; ++p)
350		continue;		/* Explicit no-op */
351
352	/*
353	 * Forever loops are done with for's, not while's.
354	 */
355	for (;;)
356		stmt;
357
358	/*
359	 * Parts of a for loop may be left empty.  Don't put declarations
360	 * inside blocks unless the routine is unusually complicated.
361	 */
362	for (; cnt < 15; cnt++) {
363		stmt1;
364		stmt2;
365	}
366
367	/* Second level indents are four spaces. */
368	while (cnt < 20) {
369		z = a + really + long + statement + that + needs + two + lines +
370		    gets + indented + four + spaces + on + the + second +
371		    and + subsequent + lines;
372	}
373
374	/*
375	 * Closing and opening braces go on the same line as the else.
376	 */
377	if (test) {
378		/*
379		 * I have a long comment here.
380		 */
381#ifdef zorro
382		z = 1;
383#else
384		b = 3;
385#endif
386	} else if (bar) {
387		stmt;
388		stmt;
389	} else {
390		stmt;
391	}
392
393	/* No spaces after function names. */
394	if ((result = function(a1, a2, a3, a4)) == NULL)
395		exit(EXIT_FAILURE);
396
397	/*
398	 * Unary operators don't require spaces, binary operators do.
399	 * Don't excessively use parentheses, but they should be used if a
400	 * statement is really confusing without them, such as:
401	 * a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
402	 */
403	a = ((b->c[0] + ~d == (e || f)) || (g && h)) ? i : (j >> 1);
404	k = !(l & FLAGS);
405
406	/*
407	 * Exits should be EXIT_SUCCESS on success, and EXIT_FAILURE on
408	 * failure.  Don't denote all the possible exit points, using the
409	 * integers 1 through 127.  Avoid obvious comments such as "Exit
410	 * 0 on success.". Since main is a function that returns an int,
411	 * prefer returning from it, than calling exit.
412	 */
413	return EXIT_SUCCESS;
414}
415
416/*
417 * The function type must be declared on a line by itself
418 * preceding the function.
419 */
420static char *
421function(int a1, int a2, float fl, int a4)
422{
423	/*
424	 * When declaring variables in functions, multiple variables per line
425	 * are okay. If a line overflows reuse the type keyword.
426	 *
427	 * Function prototypes and external data declarations should go in a
428	 * suitable include file.
429	 *
430	 * Avoid initializing variables in the declarations; move
431	 * declarations next to their first use, and initialize
432	 * opportunistically. This avoids over-initialization and
433	 * accidental bugs caused by declaration reordering.
434	 */
435	struct foo three, *four;
436	double five;
437	int *six, seven;
438	char *eight, *nine, ten, eleven, twelve, thirteen;
439	char fourteen, fifteen, sixteen;
440
441	/*
442	 * Casts and sizeof's are not followed by a space.
443	 *
444	 * We parenthesize sizeof expressions to clarify their precedence:
445	 *
446	 * 	sizeof(e) + 4
447	 * not:
448	 *	sizeof e + 4
449	 *
450	 * We don't put a space before the parenthesis so that it looks like
451	 * a function call. We always parenthesize the sizeof expression for
452	 * consistency.
453	 *
454	 * On the other hand, we don't parenthesize the return statement
455	 * because there is never a precedence ambiguity situation (it is
456	 * a single statement).
457	 *
458	 * NULL is any pointer type, and doesn't need to be cast, so use
459	 * NULL instead of (struct foo *)0 or (struct foo *)NULL.  Also,
460	 * test pointers against NULL because it indicates the type of the
461	 * expression to the user. I.e. use:
462	 *
463	 *	(p = f()) == NULL
464	 * not:
465	 *	!(p = f())
466	 *
467	 * The notable exception here is variadic functions. Since our
468	 * code is designed to compile and work on different environments
469	 * where we don't have control over the NULL definition (on NetBSD
470	 * it is defined as ((void *)0), but on other systems it can be
471	 * defined as (0) and both definitions are valid), it
472	 * is advised to cast NULL to a pointer on variadic functions,
473	 * because on machines where sizeof(pointer) != sizeof(int) and in
474	 * the absence of a prototype in scope, passing an un-casted NULL,
475	 * will result in passing an int on the stack instead of a pointer.
476	 *
477	 * Don't use `!' for tests unless it's a boolean.
478	 * E.g. use "if (*p == '\0')", not "if (!*p)".
479	 *
480	 * Routines returning ``void *'' should not have their return
481	 * values cast to more specific pointer types.
482	 *
483	 * Prefer sizeof(*var) over sizeof(type) because if type changes,
484	 * the change needs to be done in one place.
485	 *
486	 * Use err/warn(3), don't roll your own!
487	 *
488	 * Prefer EXIT_FAILURE instead of random error codes.
489	 */
490	if ((four = malloc(sizeof(*four))) == NULL)
491		err(EXIT_FAILURE, NULL);
492	if ((six = (int *)overflow()) == NULL)
493		errx(EXIT_FAILURE, "Number overflowed.");
494
495	/* No parentheses are needed around the return value. */
496	return eight;
497}
498
499/*
500 * Place the opening brace of a function body in column 1.
501 * As per the wrapped prototypes, use your discretion on how to format
502 * the subsequent lines.
503 */
504static int
505dirinfo(const char *p, struct stat *sb, struct dirent *de, struct statfs *sf,
506	int *rargc, char **rargv[])
507{	/* Insert an empty line if the function has no local variables. */
508
509	/*
510	 * In system libraries, catch obviously invalid function arguments
511	 * using _DIAGASSERT(3).
512	 */
513	_DIAGASSERT(p != NULL);
514	_DIAGASSERT(filedesc != -1);
515
516	/* Prefer checking syscalls against -1 instead of < 0 */
517	if (stat(p, sb) == -1)
518		err(EXIT_FAILURE, "Unable to stat %s", p);
519
520	/*
521	 * To printf quantities that might be larger than "long",
522	 * cast quantities to intmax_t or uintmax_t and use %j.
523	 */
524	(void)printf("The size of %s is %jd (%#ju)\n", p,
525	    (intmax_t)sb->st_size, (uintmax_t)sb->st_size);
526
527	/*
528	 * To printf quantities of known bit-width, include <inttypes.h> and
529	 * use the corresponding defines (generally only done within NetBSD
530	 * for quantities that exceed 32-bits).
531	 */
532	(void)printf("%s uses %" PRId64 " blocks and has flags %#" PRIx32 "\n",
533	    p, sb->st_blocks, sb->st_flags);
534
535	/*
536	 * There are similar constants that should be used with the *scanf(3)
537	 * family of functions: SCN?MAX, SCN?64, etc.
538	 */
539}
540
541/*
542 * Functions that support variable numbers of arguments should look like this.
543 * (With the #include <stdarg.h> appearing at the top of the file with the
544 * other include files.)
545 */
546#include <stdarg.h>
547
548void
549vaf(const char *fmt, ...)
550{
551	va_list ap;
552
553	va_start(ap, fmt);
554	STUFF;
555	va_end(ap);
556				/* No return needed for void functions. */
557}
558
559static void
560usage(void)
561{
562
563	/*
564	 * Use printf(3), not fputs/puts/putchar/whatever, it's faster and
565	 * usually cleaner, not to mention avoiding stupid bugs.
566	 * Use snprintf(3) or strlcpy(3)/strlcat(3) instead of sprintf(3);
567	 * again to avoid stupid bugs.
568	 *
569	 * Usage statements should look like the manual pages.
570	 * Options w/o operands come first, in alphabetical order
571	 * inside a single set of braces, upper case before lower case
572	 * (AaBbCc...).  Next are options with operands, in the same
573	 * order, each in braces.  Then required arguments in the
574	 * order they are specified, followed by optional arguments in
575	 * the order they are specified.  A bar (`|') separates
576	 * either/or options/arguments, and multiple options/arguments
577	 * which are specified together are placed in a single set of
578	 * braces.
579	 *
580	 * Use getprogname() instead of hardcoding the program name.
581	 *
582	 * "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\n"
583	 * "usage: f [-a | -b] [-c [-de] [-n number]]\n"
584	 */
585	(void)fprintf(stderr, "usage: %s [-ab]\n", getprogname());
586	exit(EXIT_FAILURE);
587}
588