style revision 1.49
11.49Schristos/* $NetBSD: style,v 1.49 2011/09/01 09:33:01 christos Exp $ */
21.6Sthorpej
31.1Scgd/*
41.12Slukem * The revision control tag appears first, with a blank line after it.
51.12Slukem * Copyright text appears after the revision control tag.
61.12Slukem */
71.12Slukem
81.12Slukem/*
91.12Slukem * The NetBSD source code style guide.
101.12Slukem * (Previously known as KNF - Kernel Normal Form).
111.1Scgd *
121.2Scgd *	from: @(#)style	1.12 (Berkeley) 3/18/94
131.10Sscottr */
141.10Sscottr/*
151.10Sscottr * An indent(1) profile approximating the style outlined in
161.10Sscottr * this document lives in /usr/share/misc/indent.pro.  It is a
171.10Sscottr * useful tool to assist in converting code to KNF, but indent(1)
181.10Sscottr * output generated using this profile must not be considered to
191.10Sscottr * be an authoritative reference.
201.1Scgd */
211.1Scgd
221.1Scgd/*
231.12Slukem * Source code revision control identifiers appear after any copyright
241.12Slukem * text.  Use the appropriate macros from <sys/cdefs.h>.  Usually only one
251.12Slukem * source file per program contains a __COPYRIGHT() section.
261.12Slukem * Historic Berkeley code may also have an __SCCSID() section.
271.12Slukem * Only one instance of each of these macros can occur in each file.
281.43Slukem * Don't use newlines in the identifiers.
291.12Slukem */
301.12Slukem#include <sys/cdefs.h>
311.43Slukem__COPYRIGHT("@(#) Copyright (c) 2008\
321.43Slukem The NetBSD Foundation, inc. All rights reserved.");
331.49Schristos__RCSID("$NetBSD: style,v 1.49 2011/09/01 09:33:01 christos Exp $");
341.12Slukem
351.12Slukem/*
361.1Scgd * VERY important single-line comments look like this.
371.1Scgd */
381.1Scgd
391.1Scgd/* Most single-line comments look like this. */
401.1Scgd
411.1Scgd/*
421.1Scgd * Multi-line comments look like this.  Make them real sentences.  Fill
431.1Scgd * them so they look like real paragraphs.
441.1Scgd */
451.1Scgd
461.2Scgd/*
471.12Slukem * Attempt to wrap lines longer than 80 characters appropriately.
481.12Slukem * Refer to the examples below for more information.
491.12Slukem */
501.12Slukem
511.12Slukem/*
521.12Slukem * EXAMPLE HEADER FILE:
531.12Slukem *
541.12Slukem * A header file should protect itself against multiple inclusion.
551.12Slukem * E.g, <sys/socket.h> would contain something like:
561.12Slukem */
571.12Slukem#ifndef _SYS_SOCKET_H_
581.12Slukem#define _SYS_SOCKET_H_
591.12Slukem/*
601.12Slukem * Contents of #include file go between the #ifndef and the #endif at the end.
611.12Slukem */
621.12Slukem#endif /* !_SYS_SOCKET_H_ */
631.12Slukem/*
641.12Slukem * END OF EXAMPLE HEADER FILE.
651.12Slukem */
661.12Slukem
671.12Slukem/*
681.39Sdarcy * If a header file requires structures, defines, typedefs, etc. from
691.39Sdarcy * another header file it should include that header file and not depend
701.39Sdarcy * on the including file for that header including both.  If there are
711.39Sdarcy * exceptions to this for specific headers it should be clearly documented
721.39Sdarcy * in the headers and, if appropriate, the documentation.  Nothing in this
731.39Sdarcy * rule should suggest relaxation of the multiple inclusion rule and the
741.39Sdarcy * application programmer should be free to include both regardless.
751.39Sdarcy */
761.39Sdarcy
771.39Sdarcy/*
781.12Slukem * Kernel include files come first.
791.2Scgd */
801.2Scgd#include <sys/types.h>		/* Non-local includes in brackets. */
811.2Scgd
821.12Slukem/*
831.12Slukem * If it's a network program, put the network include files next.
841.12Slukem * Group the includes files by subdirectory.
851.12Slukem */
861.2Scgd#include <net/if.h>
871.2Scgd#include <net/if_dl.h>
881.2Scgd#include <net/route.h>
891.2Scgd#include <netinet/in.h>
901.2Scgd#include <protocols/rwhod.h>
911.2Scgd
921.2Scgd/*
931.2Scgd * Then there's a blank line, followed by the /usr include files.
941.2Scgd * The /usr include files should be sorted!
951.2Scgd */
961.20Skleink#include <assert.h>
971.25Slukem#include <errno.h>
981.36Sbriggs#include <inttypes.h>
991.2Scgd#include <stdio.h>
1001.18Scgd#include <stdlib.h>
1011.1Scgd
1021.1Scgd/*
1031.1Scgd * Global pathnames are defined in /usr/include/paths.h.  Pathnames local
1041.1Scgd * to the program go in pathnames.h in the local directory.
1051.1Scgd */
1061.2Scgd#include <paths.h>
1071.2Scgd
1081.2Scgd/* Then, there's a blank line, and the user include files. */
1091.12Slukem#include "pathnames.h"		/* Local includes in double quotes. */
1101.1Scgd
1111.1Scgd/*
1121.2Scgd * ANSI function declarations for private functions (i.e. functions not used
1131.45Sdholland * elsewhere) and the main() function go at the top of the source module.
1141.12Slukem * Don't associate a name with the types.  I.e. use:
1151.12Slukem *	void function(int);
1161.12Slukem * Use your discretion on indenting between the return type and the name, and
1171.12Slukem * how to wrap a prototype too long for a single line.  In the latter case,
1181.15Slukem * lining up under the initial left parenthesis may be more readable.
1191.12Slukem * In any case, consistency is important!
1201.12Slukem */
1211.12Slukemstatic char *function(int, int, float, int);
1221.12Slukemstatic int dirinfo(const char *, struct stat *, struct dirent *,
1231.12Slukem		   struct statfs *, int *, char **[]);
1241.47Schristosstatic void usage(void) __dead;	/* declare functions that don't return dead */
1251.1Scgd
1261.1Scgd/*
1271.1Scgd * Macros are capitalized, parenthesized, and should avoid side-effects.
1281.22Sjhawk * Spacing before and after the macro name may be any whitespace, though
1291.22Sjhawk * use of TABs should be consistent through a file.
1301.1Scgd * If they are an inline expansion of a function, the function is defined
1311.12Slukem * all in lowercase, the macro has the same name all in uppercase.
1321.12Slukem * If the macro is an expression, wrap the expression in parenthesis.
1331.12Slukem * If the macro is more than a single statement, use ``do { ... } while (0)'',
1341.12Slukem * so that a trailing semicolon works.  Right-justify the backslashes; it
1351.13Slukem * makes it easier to read. The CONSTCOND comment is to satisfy lint(1).
1361.12Slukem */
1371.12Slukem#define	MACRO(v, w, x, y)						\
1381.12Slukemdo {									\
1391.12Slukem	v = (x) + (y);							\
1401.12Slukem	w = (y) + 2;							\
1411.12Slukem} while (/* CONSTCOND */ 0)
1421.12Slukem
1431.15Slukem#define	DOUBLE(x) ((x) * 2)
1441.12Slukem
1451.12Slukem/* Enum types are capitalized.  No comma on the last element. */
1461.12Slukemenum enumtype {
1471.12Slukem	ONE,
1481.12Slukem	TWO
1491.12Slukem} et;
1501.12Slukem
1511.12Slukem/*
1521.16Senami * When declaring variables in structures, declare them organized by use in
1531.16Senami * a manner to attempt to minimize memory wastage because of compiler alignment
1541.12Slukem * issues, then by size, and then by alphabetical order. E.g, don't use
1551.12Slukem * ``int a; char *b; int c; char *d''; use ``int a; int b; char *c; char *d''.
1561.12Slukem * Each variable gets its own type and line, although an exception can be made
1571.12Slukem * when declaring bitfields (to clarify that it's part of the one bitfield).
1581.12Slukem * Note that the use of bitfields in general is discouraged.
1591.1Scgd *
1601.2Scgd * Major structures should be declared at the top of the file in which they
1611.2Scgd * are used, or in separate header files, if they are used in multiple
1621.2Scgd * source files.  Use of the structures should be by separate declarations
1631.1Scgd * and should be "extern" if they are declared in a header file.
1641.12Slukem *
1651.12Slukem * It may be useful to use a meaningful prefix for each member name.
1661.12Slukem * E.g, for ``struct softc'' the prefix could be ``sc_''.
1671.1Scgd */
1681.1Scgdstruct foo {
1691.12Slukem	struct foo *next;	/* List of active foo */
1701.12Slukem	struct mumble amumble;	/* Comment for mumble */
1711.12Slukem	int bar;
1721.12Slukem	unsigned int baz:1,	/* Bitfield; line up entries if desired */
1731.12Slukem		     fuz:5,
1741.12Slukem		     zap:2;
1751.27Ssimonb	uint8_t flag;
1761.1Scgd};
1771.1Scgdstruct foo *foohead;		/* Head of global foo list */
1781.2Scgd
1791.2Scgd/* Make the structure name match the typedef. */
1801.12Slukemtypedef struct BAR {
1811.12Slukem	int level;
1821.2Scgd} BAR;
1831.12Slukem
1841.32Sjunyoung/* C99 uintN_t is preferred over u_intN_t. */
1851.32Sjunyounguint32_t zero;
1861.32Sjunyoung
1871.1Scgd/*
1881.1Scgd * All major routines should have a comment briefly describing what
1891.2Scgd * they do.  The comment before the "main" routine should describe
1901.1Scgd * what the program does.
1911.1Scgd */
1921.2Scgdint
1931.12Slukemmain(int argc, char *argv[])
1941.1Scgd{
1951.1Scgd	long num;
1961.1Scgd	int ch;
1971.1Scgd	char *ep;
1981.1Scgd
1991.1Scgd	/*
2001.17Scgd	 * At the start of main(), call setprogname() to set the program
2011.17Scgd	 * name.  This does nothing on NetBSD, but increases portability
2021.17Scgd	 * to other systems.
2031.17Scgd	 */
2041.17Scgd	setprogname(argv[0]);
2051.17Scgd
2061.17Scgd	/*
2071.37Swiz	 * For consistency, getopt should be used to parse options.
2081.37Swiz	 * Options should be sorted in the getopt call and the switch
2091.37Swiz	 * statement, unless parts of the switch cascade.  For the
2101.37Swiz	 * sorting order, see the usage() example below.  Don't forget
2111.37Swiz	 * to add option descriptions to the usage and the manpage.
2121.37Swiz	 * Elements in a switch statement that cascade should have a
2131.37Swiz	 * FALLTHROUGH comment.  Numerical arguments should be checked
2141.37Swiz	 * for accuracy.  Code that cannot be reached should have a
2151.37Swiz	 * NOTREACHED comment.
2161.1Scgd	 */
2171.41Splunky	while ((ch = getopt(argc, argv, "abn:")) != -1) {
2181.1Scgd		switch (ch) {		/* Indent the switch. */
2191.1Scgd		case 'a':		/* Don't indent the case. */
2201.1Scgd			aflag = 1;
2211.1Scgd			/* FALLTHROUGH */
2221.1Scgd		case 'b':
2231.1Scgd			bflag = 1;
2241.1Scgd			break;
2251.1Scgd		case 'n':
2261.25Slukem			errno = 0;
2271.1Scgd			num = strtol(optarg, &ep, 10);
2281.25Slukem			if (num <= 0 || *ep != '\0' || (errno == ERANGE &&
2291.25Slukem			    (num == LONG_MAX || num == LONG_MIN)) )
2301.12Slukem				errx(1, "illegal number -- %s", optarg);
2311.1Scgd			break;
2321.1Scgd		case '?':
2331.1Scgd		default:
2341.1Scgd			usage();
2351.2Scgd			/* NOTREACHED */
2361.1Scgd		}
2371.12Slukem	}
2381.1Scgd	argc -= optind;
2391.1Scgd	argv += optind;
2401.1Scgd
2411.1Scgd	/*
2421.1Scgd	 * Space after keywords (while, for, return, switch).  No braces are
2431.38Schristos	 * required for control statements with only a single statement,
2441.12Slukem	 * unless it's a long statement.
2451.1Scgd	 *
2461.1Scgd	 * Forever loops are done with for's, not while's.
2471.1Scgd	 */
2481.12Slukem	for (p = buf; *p != '\0'; ++p)
2491.12Slukem		continue;		/* Explicit no-op */
2501.1Scgd	for (;;)
2511.1Scgd		stmt;
2521.12Slukem
2531.1Scgd	/*
2541.38Schristos	 * Braces are required for control statements with a single statement
2551.38Schristos	 * that may expand to nothing.
2561.38Schristos	 */
2571.38Schristos#ifdef DEBUG_FOO
2581.40Schristos#define DPRINTF(a) printf a
2591.40Schristos#else
2601.38Schristos#define DPRINTF(a)
2611.38Schristos#endif
2621.38Schristos	if (broken) {
2631.38Schristos		DPRINTF(("broken is %d\n", broken));
2641.38Schristos	}
2651.38Schristos
2661.38Schristos	/*
2671.2Scgd	 * Parts of a for loop may be left empty.  Don't put declarations
2681.2Scgd	 * inside blocks unless the routine is unusually complicated.
2691.1Scgd	 */
2701.1Scgd	for (; cnt < 15; cnt++) {
2711.1Scgd		stmt1;
2721.1Scgd		stmt2;
2731.1Scgd	}
2741.1Scgd
2751.2Scgd	/* Second level indents are four spaces. */
2761.2Scgd	while (cnt < 20)
2771.40Schristos		z = a + really + long + statement + that + needs + two + lines +
2781.1Scgd		    gets + indented + four + spaces + on + the + second +
2791.7Senami		    and + subsequent + lines;
2801.1Scgd
2811.1Scgd	/*
2821.2Scgd	 * Closing and opening braces go on the same line as the else.
2831.12Slukem	 * Don't add braces that aren't necessary except in cases where
2841.12Slukem	 * there are ambiguity or readability issues.
2851.1Scgd	 */
2861.12Slukem	if (test) {
2871.12Slukem		/*
2881.12Slukem		 * I have a long comment here.
2891.12Slukem		 */
2901.12Slukem#ifdef zorro
2911.12Slukem		z = 1;
2921.12Slukem#else
2931.12Slukem		b = 3;
2941.12Slukem#endif
2951.12Slukem	} else if (bar) {
2961.1Scgd		stmt;
2971.1Scgd		stmt;
2981.1Scgd	} else
2991.1Scgd		stmt;
3001.12Slukem
3011.2Scgd	/* No spaces after function names. */
3021.12Slukem	if ((result = function(a1, a2, a3, a4)) == NULL)
3031.12Slukem		exit(1);
3041.1Scgd
3051.1Scgd	/*
3061.12Slukem	 * Unary operators don't require spaces, binary operators do.
3071.12Slukem	 * Don't excessively use parenthesis, but they should be used if
3081.9Slukem	 * statement is really confusing without them, such as:
3091.9Slukem	 * a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
3101.1Scgd	 */
3111.9Slukem	a = ((b->c[0] + ~d == (e || f)) || (g && h)) ? i : (j >> 1);
3121.2Scgd	k = !(l & FLAGS);
3131.1Scgd
3141.1Scgd	/*
3151.26Sjmmv	 * Exits should be EXIT_SUCCESS on success, and EXIT_FAILURE on
3161.26Sjmmv	 * failure.  Don't denote all the possible exit points, using the
3171.29Schristos	 * integers 1 through 127.  Avoid obvious comments such as "Exit
3181.29Schristos	 * 0 on success.". Since main is a function that returns an int,
3191.29Schristos	 * prefer returning from it, than calling exit.
3201.1Scgd	 */
3211.29Schristos	return EXIT_SUCCESS;
3221.1Scgd}
3231.1Scgd
3241.1Scgd/*
3251.8Ssimonb * The function type must be declared on a line by itself
3261.16Senami * preceding the function.
3271.1Scgd */
3281.1Scgdstatic char *
3291.12Slukemfunction(int a1, int a2, float fl, int a4)
3301.1Scgd{
3311.1Scgd	/*
3321.1Scgd	 * When declaring variables in functions declare them sorted by size,
3331.12Slukem	 * then in alphabetical order; multiple ones per line are okay.
3341.12Slukem	 * Function prototypes should go in the include file "extern.h".
3351.1Scgd	 * If a line overflows reuse the type keyword.
3361.1Scgd	 *
3371.2Scgd	 * DO NOT initialize variables in the declarations.
3381.1Scgd	 */
3391.1Scgd	extern u_char one;
3401.1Scgd	extern char two;
3411.1Scgd	struct foo three, *four;
3421.1Scgd	double five;
3431.12Slukem	int *six, seven;
3441.12Slukem	char *eight, *nine, ten, eleven, twelve, thirteen;
3451.12Slukem	char fourteen, fifteen, sixteen;
3461.1Scgd
3471.1Scgd	/*
3481.1Scgd	 * Casts and sizeof's are not followed by a space.  NULL is any
3491.1Scgd	 * pointer type, and doesn't need to be cast, so use NULL instead
3501.1Scgd	 * of (struct foo *)0 or (struct foo *)NULL.  Also, test pointers
3511.12Slukem	 * against NULL.  I.e. use:
3521.1Scgd	 *
3531.12Slukem	 *	(p = f()) == NULL
3541.1Scgd	 * not:
3551.1Scgd	 *	!(p = f())
3561.2Scgd	 *
3571.49Schristos	 * The notable exception here is varyadic functions. Since our
3581.49Schristos	 * code is designed to compile and work on different environments
3591.49Schristos	 * where we don't have control over the NULL definition (on NetBSD
3601.49Schristos	 * it is defined as ((void *)0), but on other systems it can be
3611.49Schristos	 * defined as (0) and both definitions are valid under ANSI C), it
3621.49Schristos	 * it advised to cast NULL to a pointer on varyadic functions,
3631.49Schristos	 * because on machines where sizeof(pointer) != sizeof(int) and in
3641.49Schristos	 * the absence of a prototype in scope, passing an un-casted NULL,
3651.49Schristos	 * will result in passing an int on the stack instead of a pointer.
3661.49Schristos	 *
3671.12Slukem	 * Don't use `!' for tests unless it's a boolean.
3681.12Slukem	 * E.g. use "if (*p == '\0')", not "if (!*p)".
3691.12Slukem	 *
3701.31Schristos	 * Routines returning ``void *'' should not have their return
3711.31Schristos	 * values cast to more specific pointer types.
3721.2Scgd	 *
3731.46Schristos	 * Prefer sizeof(*var) over sizeof(type) because if type changes,
3741.46Schristos	 * the change needs to be done in one place.
3751.46Schristos	 *
3761.2Scgd	 * Use err/warn(3), don't roll your own!
3771.1Scgd	 */
3781.46Schristos	if ((four = malloc(sizeof(*four))) == NULL)
3791.2Scgd		err(1, NULL);
3801.1Scgd	if ((six = (int *)overflow()) == NULL)
3811.2Scgd		errx(1, "Number overflowed.");
3821.23Sfvdl
3831.23Sfvdl	/* No parentheses are needed around the return value. */
3841.23Sfvdl	return eight;
3851.1Scgd}
3861.1Scgd
3871.2Scgd/*
3881.12Slukem * Use ANSI function declarations.  ANSI function braces look like
3891.12Slukem * old-style (K&R) function braces.
3901.12Slukem * As per the wrapped prototypes, use your discretion on how to format
3911.12Slukem * the subsequent lines.
3921.12Slukem */
3931.12Slukemstatic int
3941.12Slukemdirinfo(const char *p, struct stat *sb, struct dirent *de, struct statfs *sf,
3951.12Slukem	int *rargc, char **rargv[])
3961.12Slukem{	/* Insert an empty line if the function has no local variables. */
3971.19Skleink
3981.19Skleink	/*
3991.19Skleink	 * In system libraries, catch obviously invalid function arguments
4001.19Skleink	 * using _DIAGASSERT(3).
4011.19Skleink	 */
4021.19Skleink	_DIAGASSERT(p != NULL);
4031.19Skleink	_DIAGASSERT(filedesc != -1);
4041.12Slukem
4051.14Slukem	if (stat(p, sb) < 0)
4061.14Slukem		err(1, "Unable to stat %s", p);
4071.14Slukem
4081.14Slukem	/*
4091.36Sbriggs	 * To printf quantities that might be larger that "long", include
4101.36Sbriggs	 * <inttypes.h>, cast quantities to intmax_t or uintmax_t and use
4111.42Sapb	 * PRI?MAX constants.
4121.36Sbriggs	 */
4131.36Sbriggs	(void)printf("The size of %s is %" PRIdMAX " (%#" PRIxMAX ")\n", p,
4141.36Sbriggs	    (intmax_t)sb->st_size, (uintmax_t)sb->st_size);
4151.36Sbriggs
4161.36Sbriggs	/*
4171.36Sbriggs	 * To printf quantities of known bit-width, use the corresponding
4181.36Sbriggs	 * defines (generally only done within NetBSD for quantities that
4191.36Sbriggs	 * exceed 32-bits).
4201.36Sbriggs	 */
4211.36Sbriggs	(void)printf("%s uses %" PRId64 " blocks and has flags %#" PRIx32 "\n",
4221.36Sbriggs	    p, sb->st_blocks, sb->st_flags);
4231.36Sbriggs
4241.36Sbriggs	/*
4251.36Sbriggs	 * There are similar constants that should be used with the *scanf(3)
4261.36Sbriggs	 * family of functions: SCN?MAX, SCN?64, etc.
4271.14Slukem	 */
4281.2Scgd}
4291.2Scgd
4301.12Slukem/*
4311.12Slukem * Functions that support variable numbers of arguments should look like this.
4321.12Slukem * (With the #include <stdarg.h> appearing at the top of the file with the
4331.44Sjschauma * other include files.)
4341.12Slukem */
4351.2Scgd#include <stdarg.h>
4361.2Scgd
4371.2Scgdvoid
4381.2Scgdvaf(const char *fmt, ...)
4391.2Scgd{
4401.2Scgd	va_list ap;
4411.12Slukem
4421.2Scgd	va_start(ap, fmt);
4431.2Scgd	STUFF;
4441.45Sdholland	va_end(ap);
4451.12Slukem				/* No return needed for void functions. */
4461.1Scgd}
4471.1Scgd
4481.1Scgdstatic void
4491.12Slukemusage(void)
4501.12Slukem{
4511.1Scgd
4521.1Scgd	/*
4531.1Scgd	 * Use printf(3), not fputs/puts/putchar/whatever, it's faster and
4541.1Scgd	 * usually cleaner, not to mention avoiding stupid bugs.
4551.12Slukem	 * Use snprintf(3) or strlcpy(3)/strlcat(3) instead of sprintf(3);
4561.12Slukem	 * again to avoid stupid bugs.
4571.1Scgd	 *
4581.37Swiz	 * Usage statements should look like the manual pages.
4591.37Swiz	 * Options w/o operands come first, in alphabetical order
4601.37Swiz	 * inside a single set of braces, upper case before lower case
4611.37Swiz	 * (AaBbCc...).  Next are options with operands, in the same
4621.37Swiz	 * order, each in braces.  Then required arguments in the
4631.37Swiz	 * order they are specified, followed by optional arguments in
4641.37Swiz	 * the order they are specified.  A bar (`|') separates
4651.37Swiz	 * either/or options/arguments, and multiple options/arguments
4661.37Swiz	 * which are specified together are placed in a single set of
4671.37Swiz	 * braces.
4681.1Scgd	 *
4691.17Scgd	 * Use getprogname() instead of hardcoding the program name.
4701.12Slukem	 *
4711.37Swiz	 * "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\n"
4721.1Scgd	 * "usage: f [-a | -b] [-c [-de] [-n number]]\n"
4731.1Scgd	 */
4741.17Scgd	(void)fprintf(stderr, "usage: %s [-ab]\n", getprogname());
4751.33Srillig	exit(EXIT_FAILURE);
4761.1Scgd}
477