samba_tool: make exception handling statements py2/py3 compatible
[samba.git] / README.Coding
1 Coding conventions in the Samba tree
2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4 .. contents::
5
6 ===========
7 Quick Start
8 ===========
9
10 Coding style guidelines are about reducing the number of unnecessary
11 reformatting patches and making things easier for developers to work
12 together.
13 You don't have to like them or even agree with them, but once put in place
14 we all have to abide by them (or vote to change them).  However, coding
15 style should never outweigh coding itself and so the guidelines
16 described here are hopefully easy enough to follow as they are very
17 common and supported by tools and editors.
18
19 The basic style for C code is the Linux kernel coding style (See
20 Documentation/CodingStyle in the kernel source tree). This closely matches
21 what most Samba developers use already anyways, with a few exceptions as
22 mentioned below.
23
24 The coding style for Python code is documented in PEP8,
25 http://www.python.org/pep/pep8. New Python code should be compatible with
26 Python 2.6, 2.7, and Python 3.4 onwards. This means using Python 3 syntax
27 with the appropriate 'from __future__' imports.
28
29 But to save you the trouble of reading the Linux kernel style guide, here
30 are the highlights.
31
32 * Maximum Line Width is 80 Characters
33   The reason is not about people with low-res screens but rather sticking
34   to 80 columns prevents you from easily nesting more than one level of
35   if statements or other code blocks.  Use source3/script/count_80_col.pl
36   to check your changes.
37
38 * Use 8 Space Tabs to Indent
39   No whitespace fillers.
40
41 * No Trailing Whitespace
42   Use source3/script/strip_trail_ws.pl to clean up your files before
43   committing.
44
45 * Follow the K&R guidelines.  We won't go through all of them here. Do you
46   have a copy of "The C Programming Language" anyways right? You can also use
47   the format_indent.sh script found in source3/script/ if all else fails.
48
49
50
51 ============
52 Editor Hints
53 ============
54
55 Emacs
56 -----
57 Add the follow to your $HOME/.emacs file:
58
59   (add-hook 'c-mode-hook
60         (lambda ()
61                 (c-set-style "linux")
62                 (c-toggle-auto-state)))
63
64
65 Vi
66 --
67 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
68
69 For the basic vi editor included with all variants of \*nix, add the
70 following to $HOME/.exrc:
71
72   set tabstop=8
73   set shiftwidth=8
74
75 For Vim, the following settings in $HOME/.vimrc will also deal with
76 displaying trailing whitespace:
77
78   if has("syntax") && (&t_Co > 2 || has("gui_running"))
79         syntax on
80         function! ActivateInvisibleCharIndicator()
81                 syntax match TrailingSpace "[ \t]\+$" display containedin=ALL
82                 highlight TrailingSpace ctermbg=Red
83         endf
84         autocmd BufNewFile,BufRead * call ActivateInvisibleCharIndicator()
85   endif
86   " Show tabs, trailing whitespace, and continued lines visually
87   set list listchars=tab:»·,trail:·,extends:…
88
89   " highlight overly long lines same as TODOs.
90   set textwidth=80
91   autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
92
93 clang-format
94 ------------
95 BasedOnStyle: LLVM
96 IndentWidth: 8
97 UseTab: true
98 BreakBeforeBraces: Linux
99 AllowShortIfStatementsOnASingleLine: false
100 IndentCaseLabels: false
101 BinPackParameters: false
102 BinPackArguments: false
103
104
105 =========================
106 FAQ & Statement Reference
107 =========================
108
109 Comments
110 --------
111
112 Comments should always use the standard C syntax.  C++
113 style comments are not currently allowed.
114
115 The lines before a comment should be empty. If the comment directly
116 belongs to the following code, there should be no empty line
117 after the comment, except if the comment contains a summary
118 of multiple following code blocks.
119
120 This is good:
121
122         ...
123         int i;
124
125         /*
126          * This is a multi line comment,
127          * which explains the logical steps we have to do:
128          *
129          * 1. We need to set i=5, because...
130          * 2. We need to call complex_fn1
131          */
132
133         /* This is a one line comment about i = 5. */
134         i = 5;
135
136         /*
137          * This is a multi line comment,
138          * explaining the call to complex_fn1()
139          */
140         ret = complex_fn1();
141         if (ret != 0) {
142         ...
143
144         /**
145          * @brief This is a doxygen comment.
146          *
147          * This is a more detailed explanation of
148          * this simple function.
149          *
150          * @param[in]   param1     The parameter value of the function.
151          *
152          * @param[out]  result1    The result value of the function.
153          *
154          * @return              0 on success and -1 on error.
155          */
156         int example(int param1, int *result1);
157
158 This is bad:
159
160         ...
161         int i;
162         /*
163          * This is a multi line comment,
164          * which explains the logical steps we have to do:
165          *
166          * 1. We need to set i=5, because...
167          * 2. We need to call complex_fn1
168          */
169         /* This is a one line comment about i = 5. */
170         i = 5;
171         /*
172          * This is a multi line comment,
173          * explaining the call to complex_fn1()
174          */
175         ret = complex_fn1();
176         if (ret != 0) {
177         ...
178
179         /*This is a one line comment.*/
180
181         /* This is a multi line comment,
182            with some more words...*/
183
184         /*
185          * This is a multi line comment,
186          * with some more words...*/
187
188 Indention & Whitespace & 80 columns
189 -----------------------------------
190
191 To avoid confusion, indentations have to be tabs with length 8 (not 8
192 ' ' characters).  When wrapping parameters for function calls,
193 align the parameter list with the first parameter on the previous line.
194 Use tabs to get as close as possible and then fill in the final 7
195 characters or less with whitespace.  For example,
196
197         var1 = foo(arg1, arg2,
198                    arg3);
199
200 The previous example is intended to illustrate alignment of function
201 parameters across lines and not as encourage for gratuitous line
202 splitting.  Never split a line before columns 70 - 79 unless you
203 have a really good reason. Be smart about formatting.
204
205 One exception to the previous rule is function calls, declarations, and
206 definitions. In function calls, declarations, and definitions, either the
207 declaration is a one-liner, or each parameter is listed on its own
208 line. The rationale is that if there are many parameters, each one
209 should be on its own line to make tracking interface changes easier.
210
211
212 If, switch, & Code blocks
213 -------------------------
214
215 Always follow an 'if' keyword with a space but don't include additional
216 spaces following or preceding the parentheses in the conditional.
217 This is good:
218
219         if (x == 1)
220
221 This is bad:
222
223         if ( x == 1 )
224
225 Yes we have a lot of code that uses the second form and we are trying
226 to clean it up without being overly intrusive.
227
228 Note that this is a rule about parentheses following keywords and not
229 functions.  Don't insert a space between the name and left parentheses when
230 invoking functions.
231
232 Braces for code blocks used by for, if, switch, while, do..while, etc.
233 should begin on the same line as the statement keyword and end on a line
234 of their own. You should always include braces, even if the block only
235 contains one statement.  NOTE: Functions are different and the beginning left
236 brace should be located in the first column on the next line.
237
238 If the beginning statement has to be broken across lines due to length,
239 the beginning brace should be on a line of its own.
240
241 The exception to the ending rule is when the closing brace is followed by
242 another language keyword such as else or the closing while in a do..while
243 loop.
244
245 Good examples:
246
247         if (x == 1) {
248                 printf("good\n");
249         }
250
251         for (x=1; x<10; x++) {
252                 print("%d\n", x);
253         }
254
255         for (really_really_really_really_long_var_name=0;
256              really_really_really_really_long_var_name<10;
257              really_really_really_really_long_var_name++)
258         {
259                 print("%d\n", really_really_really_really_long_var_name);
260         }
261
262         do {
263                 printf("also good\n");
264         } while (1);
265
266 Bad examples:
267
268         while (1)
269         {
270                 print("I'm in a loop!\n"); }
271
272         for (x=1;
273              x<10;
274              x++)
275         {
276                 print("no good\n");
277         }
278
279         if (i < 10)
280                 print("I should be in braces.\n");
281
282
283 Goto
284 ----
285
286 While many people have been academically taught that "goto"s are
287 fundamentally evil, they can greatly enhance readability and reduce memory
288 leaks when used as the single exit point from a function. But in no Samba
289 world what so ever is a goto outside of a function or block of code a good
290 idea.
291
292 Good Examples:
293
294         int function foo(int y)
295         {
296                 int *z = NULL;
297                 int ret = 0;
298
299                 if (y < 10) {
300                         z = malloc(sizeof(int) * y);
301                         if (z == NULL) {
302                                 ret = 1;
303                                 goto done;
304                         }
305                 }
306
307                 print("Allocated %d elements.\n", y);
308
309          done:
310                 if (z != NULL) {
311                         free(z);
312                 }
313
314                 return ret;
315         }
316
317
318 Primitive Data Types
319 --------------------
320
321 Samba has large amounts of historical code which makes use of data types
322 commonly supported by the C99 standard. However, at the time such types
323 as boolean and exact width integers did not exist and Samba developers
324 were forced to provide their own.  Now that these types are guaranteed to
325 be available either as part of the compiler C99 support or from
326 lib/replace/, new code should adhere to the following conventions:
327
328   * Booleans are of type "bool" (not BOOL)
329   * Boolean values are "true" and "false" (not True or False)
330   * Exact width integers are of type [u]int[8|16|32|64]_t
331
332 Most of the time a good name for a boolean variable is 'ok'. Here is an
333 example we often use:
334
335         bool ok;
336
337         ok = foo();
338         if (!ok) {
339                 /* do something */
340         }
341
342 It makes the code more readable and is easy to debug.
343
344 Typedefs
345 --------
346
347 Samba tries to avoid "typedef struct { .. } x_t;" so we do always try to use
348 "struct x { .. };". We know there are still such typedefs in the code,
349 but for new code, please don't do that anymore.
350
351 Initialize pointers
352 -------------------
353
354 All pointer variables MUST be initialized to NULL. History has
355 demonstrated that uninitialized pointer variables have lead to various
356 bugs and security issues.
357
358 Pointers MUST be initialized even if the assignment directly follows
359 the declaration, like pointer2 in the example below, because the
360 instructions sequence may change over time.
361
362 Good Example:
363
364         char *pointer1 = NULL;
365         char *pointer2 = NULL;
366
367         pointer2 = some_func2();
368
369         ...
370
371         pointer1 = some_func1();
372
373 Bad Example:
374
375         char *pointer1;
376         char *pointer2;
377
378         pointer2 = some_func2();
379
380         ...
381
382         pointer1 = some_func1();
383
384 Make use of helper variables
385 ----------------------------
386
387 Please try to avoid passing function calls as function parameters
388 in new code. This makes the code much easier to read and
389 it's also easier to use the "step" command within gdb.
390
391 Good Example:
392
393         char *name = NULL;
394         int ret;
395
396         name = get_some_name();
397         if (name == NULL) {
398                 ...
399         }
400
401         ret = some_function_my_name(name);
402         ...
403
404
405 Bad Example:
406
407         ret = some_function_my_name(get_some_name());
408         ...
409
410 Please try to avoid passing function return values to if- or
411 while-conditions. The reason for this is better handling of code under a
412 debugger.
413
414 Good example:
415
416         x = malloc(sizeof(short)*10);
417         if (x == NULL) {
418                 fprintf(stderr, "Unable to alloc memory!\n");
419         }
420
421 Bad example:
422
423         if ((x = malloc(sizeof(short)*10)) == NULL ) {
424                 fprintf(stderr, "Unable to alloc memory!\n");
425         }
426
427 There are exceptions to this rule. One example is walking a data structure in
428 an iterator style:
429
430         while ((opt = poptGetNextOpt(pc)) != -1) {
431                    ... do something with opt ...
432         }
433
434 But in general, please try to avoid this pattern.
435
436
437 Control-Flow changing macros
438 ----------------------------
439
440 Macros like NT_STATUS_NOT_OK_RETURN that change control flow
441 (return/goto/etc) from within the macro are considered bad, because
442 they look like function calls that never change control flow. Please
443 do not use them in new code.
444
445 The only exception is the test code that depends repeated use of calls
446 like CHECK_STATUS, CHECK_VAL and others.
447
448
449 Error and out logic
450 -------------------
451
452 Don't do this:
453
454         frame = talloc_stackframe();
455
456         if (ret == LDB_SUCCESS) {
457                 if (result->count == 0) {
458                         ret = LDB_ERR_NO_SUCH_OBJECT;
459                 } else {
460                         struct ldb_message *match =
461                                 get_best_match(dn, result);
462                         if (match == NULL) {
463                                 TALLOC_FREE(frame);
464                                 return LDB_ERR_OPERATIONS_ERROR;
465                         }
466                         *msg = talloc_move(mem_ctx, &match);
467                 }
468         }
469
470         TALLOC_FREE(frame);
471         return ret;
472
473 It should be:
474
475         frame = talloc_stackframe();
476
477         if (ret != LDB_SUCCESS) {
478                 TALLOC_FREE(frame);
479                 return ret;
480         }
481
482         if (result->count == 0) {
483                 TALLOC_FREE(frame);
484                 return LDB_ERR_NO_SUCH_OBJECT;
485         }
486
487         match = get_best_match(dn, result);
488         if (match == NULL) {
489                 TALLOC_FREE(frame);
490                 return LDB_ERR_OPERATIONS_ERROR;
491         }
492
493         *msg = talloc_move(mem_ctx, &match);
494         TALLOC_FREE(frame);
495         return LDB_SUCCESS;
496
497
498 DEBUG statements
499 ----------------
500
501 Use these following macros instead of DEBUG:
502
503 DBG_ERR log level 0             error conditions
504 DBG_WARNING     log level 1             warning conditions
505 DBG_NOTICE      log level 3             normal, but significant, condition
506 DBG_INFO        log level 5             informational message
507 DBG_DEBUG       log level 10            debug-level message
508
509 Example usage:
510
511 DBG_ERR("Memory allocation failed\n");
512 DBG_DEBUG("Received %d bytes\n", count);
513
514 The messages from these macros are automatically prefixed with the
515 function name.