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