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