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