Home | History | Annotate | Line # | Download | only in misc
style revision 1.64
      1 /* $NetBSD: style,v 1.64 2022/03/10 23:39:12 rillig 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.64 2022/03/10 23:39:12 rillig 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 include 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  */
    126 static char *function(int, int, float, int);
    127 static int dirinfo(const char *, struct stat *, struct dirent *,
    128 		   struct statfs *, int *, char **[]);
    129 static 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  * or ``do { ... } while (false)'', so that a trailing semicolon works.
    140  * Right-justify the backslashes; it makes it easier to read.
    141  */
    142 #define	MACRO(v, w, x, y)						\
    143 do {									\
    144 	v = (x) + (y);							\
    145 	w = (y) + 2;							\
    146 } while (0)
    147 
    148 #define	DOUBLE(x) ((x) * 2)
    149 
    150 /* Enum constants are capitalized.  No comma on the last element. */
    151 enum enumtype {
    152 	ONE,
    153 	TWO
    154 };
    155 
    156 /*
    157  * Sometimes we want a macro to be conditionally defined for debugging
    158  * and expand to nothing (but still as statement) when we are not debugging:
    159  */
    160 #ifdef FOO_DEBUG
    161 # define DPRINTF(...) printf(__VA_ARGS__)
    162 #else
    163 # define DPRINTF(...) __nothing
    164 #endif
    165 
    166 /*
    167  * When declaring variables in structures, declare them organized by use in
    168  * a manner to attempt to minimize memory wastage because of compiler alignment
    169  * issues, then by size, and then by alphabetical order. E.g, don't use
    170  * ``int a; char *b; int c; char *d''; use ``int a; int b; char *c; char *d''.
    171  * Each variable gets its own type and line, although an exception can be made
    172  * when declaring bitfields (to clarify that it's part of the one bitfield).
    173  * Note that the use of bitfields in general is discouraged.
    174  *
    175  * Major structures should be declared at the top of the file in which they
    176  * are used, or in separate header files, if they are used in multiple
    177  * source files.  Use of the structures should be by separate declarations
    178  * and should be "extern" if they are declared in a header file.
    179  *
    180  * It may be useful to use a meaningful prefix for each member name.
    181  * E.g, for ``struct softc'' the prefix could be ``sc_''.
    182  */
    183 struct foo {
    184 	struct foo *next;	/* List of active foo */
    185 	struct mumble amumble;	/* Comment for mumble */
    186 	int bar;
    187 	unsigned int baz:1,	/* Bitfield; line up entries if desired */
    188 		     fuz:5,
    189 		     zap:2;
    190 	uint8_t flag;
    191 };
    192 struct foo *foohead;		/* Head of global foo list */
    193 
    194 /* Make the structure name match the typedef. */
    195 typedef struct BAR {
    196 	int level;
    197 } BAR;
    198 
    199 /* C99 uintN_t is preferred over u_intN_t. */
    200 uint32_t zero;
    201 
    202 /*
    203  * All major routines should have a comment briefly describing what
    204  * they do.  The comment before the "main" routine should describe
    205  * what the program does.
    206  */
    207 int
    208 main(int argc, char *argv[])
    209 {
    210 	long num;
    211 	int ch;
    212 	char *ep;
    213 
    214 	/*
    215 	 * At the start of main(), call setprogname() to set the program
    216 	 * name.  This does nothing on NetBSD, but increases portability
    217 	 * to other systems.
    218 	 */
    219 	setprogname(argv[0]);
    220 
    221 	/*
    222 	 * For consistency, getopt should be used to parse options.
    223 	 * Options should be sorted in the getopt call and the switch
    224 	 * statement, unless parts of the switch cascade.  For the
    225 	 * sorting order, see the usage() example below.  Don't forget
    226 	 * to add option descriptions to the usage and the manpage.
    227 	 * Elements in a switch statement that cascade should have a
    228 	 * FALLTHROUGH comment.  Numerical arguments should be checked
    229 	 * for accuracy.  Code that cannot be reached should have a
    230 	 * NOTREACHED comment.
    231 	 */
    232 	while ((ch = getopt(argc, argv, "abn:")) != -1) {
    233 		switch (ch) {		/* Indent the switch. */
    234 		case 'a':		/* Don't indent the case. */
    235 			aflag = 1;
    236 			/* FALLTHROUGH */
    237 		case 'b':
    238 			bflag = 1;
    239 			break;
    240 		case 'n':
    241 			errno = 0;
    242 			num = strtol(optarg, &ep, 10);
    243 			if (num <= 0 || *ep != '\0' || (errno == ERANGE &&
    244 			    (num == LONG_MAX || num == LONG_MIN)) ) {
    245 				errx(1, "illegal number -- %s", optarg);
    246 			}
    247 			break;
    248 		case '?':
    249 		default:
    250 			usage();
    251 			/* NOTREACHED */
    252 		}
    253 	}
    254 	argc -= optind;
    255 	argv += optind;
    256 
    257 	/*
    258 	 * Space after keywords (while, for, return, switch).
    259 	 *
    260 	 * Braces around single-line bodies are optional; use discretion.
    261 	 *
    262 	 * Forever loops are done with for's, not while's.
    263 	 */
    264 	for (p = buf; *p != '\0'; ++p)
    265 		continue;		/* Explicit no-op */
    266 	for (;;)
    267 		stmt;
    268 
    269 	/*
    270 	 * Parts of a for loop may be left empty.  Don't put declarations
    271 	 * inside blocks unless the routine is unusually complicated.
    272 	 */
    273 	for (; cnt < 15; cnt++) {
    274 		stmt1;
    275 		stmt2;
    276 	}
    277 
    278 	/* Second level indents are four spaces. */
    279 	while (cnt < 20) {
    280 		z = a + really + long + statement + that + needs + two + lines +
    281 		    gets + indented + four + spaces + on + the + second +
    282 		    and + subsequent + lines;
    283 	}
    284 
    285 	/*
    286 	 * Closing and opening braces go on the same line as the else.
    287 	 */
    288 	if (test) {
    289 		/*
    290 		 * I have a long comment here.
    291 		 */
    292 #ifdef zorro
    293 		z = 1;
    294 #else
    295 		b = 3;
    296 #endif
    297 	} else if (bar) {
    298 		stmt;
    299 		stmt;
    300 	} else {
    301 		stmt;
    302 	}
    303 
    304 	/* No spaces after function names. */
    305 	if ((result = function(a1, a2, a3, a4)) == NULL)
    306 		exit(1);
    307 
    308 	/*
    309 	 * Unary operators don't require spaces, binary operators do.
    310 	 * Don't excessively use parenthesis, but they should be used if
    311 	 * statement is really confusing without them, such as:
    312 	 * a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
    313 	 */
    314 	a = ((b->c[0] + ~d == (e || f)) || (g && h)) ? i : (j >> 1);
    315 	k = !(l & FLAGS);
    316 
    317 	/*
    318 	 * Exits should be EXIT_SUCCESS on success, and EXIT_FAILURE on
    319 	 * failure.  Don't denote all the possible exit points, using the
    320 	 * integers 1 through 127.  Avoid obvious comments such as "Exit
    321 	 * 0 on success.". Since main is a function that returns an int,
    322 	 * prefer returning from it, than calling exit.
    323 	 */
    324 	return EXIT_SUCCESS;
    325 }
    326 
    327 /*
    328  * The function type must be declared on a line by itself
    329  * preceding the function.
    330  */
    331 static char *
    332 function(int a1, int a2, float fl, int a4)
    333 {
    334 	/*
    335 	 * When declaring variables in functions declare them sorted by size,
    336 	 * then in alphabetical order; multiple ones per line are okay.
    337 	 * Function prototypes should go in the include file "extern.h".
    338 	 * If a line overflows reuse the type keyword.
    339 	 *
    340 	 * Avoid initializing variables in the declarations; move
    341 	 * declarations next to their first use, and initialize
    342 	 * opportunistically. This avoids over-initialization and
    343 	 * accidental bugs caused by declaration reordering.
    344 	 */
    345 	extern u_char one;
    346 	extern char two;
    347 	struct foo three, *four;
    348 	double five;
    349 	int *six, seven;
    350 	char *eight, *nine, ten, eleven, twelve, thirteen;
    351 	char fourteen, fifteen, sixteen;
    352 
    353 	/*
    354 	 * Casts and sizeof's are not followed by a space.
    355 	 *
    356 	 * We parenthesize sizeof expressions to clarify their precedence:
    357 	 *
    358 	 * 	sizeof(e) + 4
    359 	 * not:
    360 	 *	sizeof e + 4
    361 	 *
    362 	 * We don't put a space before the parenthesis so that it looks like
    363 	 * a function call. We always parenthesize the sizeof expression for
    364 	 * consistency.
    365 	 *
    366 	 * On the other hand, we don't parenthesize the return statement
    367 	 * because there is never a precedence ambiguity situation (it is
    368 	 * a single statement).
    369 	 *
    370 	 * NULL is any pointer type, and doesn't need to be cast, so use
    371 	 * NULL instead of (struct foo *)0 or (struct foo *)NULL.  Also,
    372 	 * test pointers against NULL because it indicates the type of the
    373 	 * expression to the user. I.e. use:
    374 	 *
    375 	 *	(p = f()) == NULL
    376 	 * not:
    377 	 *	!(p = f())
    378 	 *
    379 	 * The notable exception here is variadic functions. Since our
    380 	 * code is designed to compile and work on different environments
    381 	 * where we don't have control over the NULL definition (on NetBSD
    382 	 * it is defined as ((void *)0), but on other systems it can be
    383 	 * defined as (0) and both definitions are valid under ANSI C), it
    384 	 * it advised to cast NULL to a pointer on variadic functions,
    385 	 * because on machines where sizeof(pointer) != sizeof(int) and in
    386 	 * the absence of a prototype in scope, passing an un-casted NULL,
    387 	 * will result in passing an int on the stack instead of a pointer.
    388 	 *
    389 	 * Don't use `!' for tests unless it's a boolean.
    390 	 * E.g. use "if (*p == '\0')", not "if (!*p)".
    391 	 *
    392 	 * Routines returning ``void *'' should not have their return
    393 	 * values cast to more specific pointer types.
    394 	 *
    395 	 * Prefer sizeof(*var) over sizeof(type) because if type changes,
    396 	 * the change needs to be done in one place.
    397 	 *
    398 	 * Use err/warn(3), don't roll your own!
    399 	 *
    400 	 * Prefer EXIT_FAILURE instead of random error codes.
    401 	 */
    402 	if ((four = malloc(sizeof(*four))) == NULL)
    403 		err(EXIT_FAILURE, NULL);
    404 	if ((six = (int *)overflow()) == NULL)
    405 		errx(EXIT_FAILURE, "Number overflowed.");
    406 
    407 	/* No parentheses are needed around the return value. */
    408 	return eight;
    409 }
    410 
    411 /*
    412  * Use ANSI function declarations.  ANSI function braces look like
    413  * old-style (K&R) function braces.
    414  * As per the wrapped prototypes, use your discretion on how to format
    415  * the subsequent lines.
    416  */
    417 static int
    418 dirinfo(const char *p, struct stat *sb, struct dirent *de, struct statfs *sf,
    419 	int *rargc, char **rargv[])
    420 {	/* Insert an empty line if the function has no local variables. */
    421 
    422 	/*
    423 	 * In system libraries, catch obviously invalid function arguments
    424 	 * using _DIAGASSERT(3).
    425 	 */
    426 	_DIAGASSERT(p != NULL);
    427 	_DIAGASSERT(filedesc != -1);
    428 
    429 	/* Prefer checking syscalls against -1 instead of < 0 */
    430 	if (stat(p, sb) == -1)
    431 		err(EXIT_FAILURE, "Unable to stat %s", p);
    432 
    433 	/*
    434 	 * To printf quantities that might be larger than "long",
    435 	 * cast quantities to intmax_t or uintmax_t and use %j
    436 	 */
    437 	(void)printf("The size of %s is %jd (%#ju)\n", p,
    438 	    (intmax_t)sb->st_size, (uintmax_t)sb->st_size);
    439 
    440 	/*
    441 	 * To printf quantities of known bit-width, include <inttypes.h> and
    442 	 * use the corresponding defines (generally only done within NetBSD
    443 	 * for quantities that exceed 32-bits).
    444 	 */
    445 	(void)printf("%s uses %" PRId64 " blocks and has flags %#" PRIx32 "\n",
    446 	    p, sb->st_blocks, sb->st_flags);
    447 
    448 	/*
    449 	 * There are similar constants that should be used with the *scanf(3)
    450 	 * family of functions: SCN?MAX, SCN?64, etc.
    451 	 */
    452 }
    453 
    454 /*
    455  * Functions that support variable numbers of arguments should look like this.
    456  * (With the #include <stdarg.h> appearing at the top of the file with the
    457  * other include files.)
    458  */
    459 #include <stdarg.h>
    460 
    461 void
    462 vaf(const char *fmt, ...)
    463 {
    464 	va_list ap;
    465 
    466 	va_start(ap, fmt);
    467 	STUFF;
    468 	va_end(ap);
    469 				/* No return needed for void functions. */
    470 }
    471 
    472 static void
    473 usage(void)
    474 {
    475 
    476 	/*
    477 	 * Use printf(3), not fputs/puts/putchar/whatever, it's faster and
    478 	 * usually cleaner, not to mention avoiding stupid bugs.
    479 	 * Use snprintf(3) or strlcpy(3)/strlcat(3) instead of sprintf(3);
    480 	 * again to avoid stupid bugs.
    481 	 *
    482 	 * Usage statements should look like the manual pages.
    483 	 * Options w/o operands come first, in alphabetical order
    484 	 * inside a single set of braces, upper case before lower case
    485 	 * (AaBbCc...).  Next are options with operands, in the same
    486 	 * order, each in braces.  Then required arguments in the
    487 	 * order they are specified, followed by optional arguments in
    488 	 * the order they are specified.  A bar (`|') separates
    489 	 * either/or options/arguments, and multiple options/arguments
    490 	 * which are specified together are placed in a single set of
    491 	 * braces.
    492 	 *
    493 	 * Use getprogname() instead of hardcoding the program name.
    494 	 *
    495 	 * "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\n"
    496 	 * "usage: f [-a | -b] [-c [-de] [-n number]]\n"
    497 	 */
    498 	(void)fprintf(stderr, "usage: %s [-ab]\n", getprogname());
    499 	exit(EXIT_FAILURE);
    500 }
    501