webperimental: killstack decides stack protects.
[freeciv.git] / doc / CodingStyle
blob358528f3ff59a700e5d8e24e89b751bce23b1c7a
1 ============================================================================
2   Freeciv Coding Style Guide
3 ============================================================================
5 If you want to hack Freeciv, and want your patches to be accepted, it helps
6 to follow some simple style rules. Yes, some of these are a bit nit-picky,
7 but wars are fought over the silliest things ...
9 - This style is used for all code in Freeciv. Freeciv gtk-clients use
10   this style, not gtk style.
12 - Freeciv is mostly programmed in C, C89 with some C99 features.
13   Qt parts are programmed in C++. Even C++ parts should have mostly
14   consistent style with C parts, so where not otherwise noted, this
15   guide applies to C++ parts too. Headers that are included to both
16   C and C++ source files follow C style.
18 - C++-style comments (i.e., // comments) are forbidden in C code.
19   They should be used for single-line comments in C++ code.
21 - Declaring variables in the middle of the scope is forbidden
22   (unless you are using C99 dynamic arrays and you need to check the size
23    of the array before you declare it).
25 - Where variable is logically boolean, 'bool' type should be used even in
26   C code. To make sure that the type is defined, include utility/support.h.
27   In C code boolean values are uppercase macros 'TRUE' and 'FALSE'.
28   In C++ code lowercase boolean values 'true' and 'false' should be used.
30 - Functions that take no arguments should be declared and defined with
31   'void' argument list in C code, and empty argument list in C++ code.
33   C:
34     int no_arguments(void);
36   C++:
37     int no_arguments();
39 - Use K&R indentation style with indentation 2 (if in doubt, use "indent -kr
40   -i2 -l77", but beware that that will probably mangle the _() macros used
41   to mark translated strings and the brace style for iteration macros).
43 - Do not re-indent areas of code you are not modifying or creating.
45 - Here are the most important formatting rules:
47   - Lines are at most 77 characters long, including the terminating newline.
49   - The tab width is 8 spaces for tabs that already exist in the source code
50     (this is just so that old code will appear correctly in your editor).
51     However, tabs should be avoided in newly written code.
53   - The indentation is 2 spaces per level for all new code; do not use tabs
54     for any kind of indentation. The one exception to this is if you are
55     just adding one line to a set of lines that are already indented with
56     some strange mix of tabs and spaces; in this case you may use the same
57     indentation as the surrounding lines.
59   - Do not add more than 2 empty lines between any sections in the code.
61   - Spaces are inserted before and after operators: instead of "int a,b,c;"
62     use "int i, j, k;" and instead of
64       if(foo<=bar){
65         c=a+b;
66       }
68     use
70       if (foo <= bar) {
71         c = a + b;
72       }
74     Note the space between "if" and the bracket.
76   - Switch statement case labels are aligned with the enclosing "switch":
78       switch (value) {
79       case MY_VALUE1:
80         do_some_stuff(value);
81         break;
82       case MY_VALUE2:
83         {
84           int value2 = value + 5;
85           do_some_other_stuff(value2);
86         }
87         break;
88       }
90   - In the rare case that you actually use goto, the label should be all
91     capitals and "out-dented" in the block in which it is contained:
93       static int frob(int n)
94       {
95         int i, j;
96         for (i = 0; i < n; i++) {
97           for (j = i; j < n; j++) {
98             if (some_condition(i, j)) {
99               goto EXIT_LOOP;
100             }
101           }
102         }
103       EXIT_LOOP:
104         return 123;
105       }
107   - If a function prototype exceeds 77 characters on one line, you should
108     put the return value type and storage specifier on the line immediately
109     above it:
111       static const struct incredibly_long_structure_name *
112       get_a_const_struct_incredibly_long_structure_name(int id);
114   - If arguments in a function prototype or a function call cause the line
115     to exceed 77 characters, they should be placed on the following line and
116     lined up with spaces to the column after the '(':
118       void some_function(const struct another_really_long_name *arln,
119                          int some_other_argument);
121   - If the line is still too long for some reason, you may place the
122     arguments two indentation levels on the next line:
124       a_very_awkward_long_function_name(some_argument,
125           "A really long string that would have to be cut up.");
127     But you should try to avoid this situation, either by naming your
128     functions/types/variables more succinctly, or by using helper variables
129     or functions to split the expression over a number of lines.
131 - An empty line should be placed between two separate blocks of code.
133 - Place operators at the beginning of a line, not at the end. It should be
135     if ((a
136          && b)
137         || c) {
139   instead of
141     if ((a &&
142          b) ||
143         c) {
146 ============================================================================
147   Comments
148 ============================================================================
150 - All comments should have proper English grammar, spelling and punctuation,
151   but you should not capitalize names of identifiers (variables, types,
152   functions, etc.) used in the code. If using plain identifiers in sentences
153   would be confusing to the reader, you should put the names in quotes.
155 - Every function should have a comment header. The comment should look like
156   the example below, indented by two spaces. It should be above the
157   function's implementation, not the prototype:
159 /****************************************************************************
160   The description of the function should be here. Also describe what is
161   expected of the arguments if it is not obvious. Especially note down any
162   non-trivial assumptions that the function makes.
164   Do _not_ introduce a new function without some sort of comment.
165 ****************************************************************************/
166 int the_function_starts_here(int value) 
168   return value + 2;
171 - One line comments should be indented correctly and placed above the code
172   being commented upon:
174     int x;
176     /* I am a single line comment. */
177     x = 3;
179 - For multiline comments, asterisks should be placed in front of the comment
180   line like so:
182     /* I am a multiline
183      * comment, blah 
184      * blah blah. */
186 - If you need to comment a declared variable, it should be as such:
188     struct foo {
189       int bar;     /* bar is used for ...
190                     * in ... way. */
191       int blah;    /* blah is used for ... . */
192     };
194   Or if the comment is very long, it may be placed above the field
195   declaration, as in the one-line or multi-line comment cases.
197 - Comments in conditionals: if you need a comment to show program flow, it
198   should be below the if or else:
200     if (is_barbarian(pplayer)) {
201       x++;
202     } else {
203       /* If not barbarian... */
204       x--;
205     }
207 - Comments to translators are placed before the N_(), _(), Q_() or PL_()
208   marked string, and are preceded by "TRANS:". . They must be on the same or
209   immediately previous line to the gettext invocation. These comments are
210   copied to the translator's file. Use them whenever you think the
211   translators may need some more information:
213     /* TRANS: Do not translate "commandname". */
214     printf(_("commandname <arg> [-o <optarg>]"));
217 ============================================================================
218   Declaring Variables
219 ============================================================================
221 - Avoid static and global variables if at all possible. When you absolutely
222   do need them, minimize the number of times they are referenced in the code
223   (e.g. use a helper function to wrap their access).
225 - Never initialize variables with values that make no sense as their
226   value in case they get used. If there's no sensible initialization
227   value for a variable, leave it uninitialized. This allows various
228   tools to detect if such a variable ever gets used without assigning
229   proper value to it.
231 - Variables can be initialized as soon as they are declared:
233     int foo(struct unit *punit)
234     {
235       int x = punit->x;
236       int foo = x;
237       char *blah;
239       /* Etc. */
241   (But you should generally check arguments to functions before using them,
242   unless you are absolutely sure that pointers are not NULL, etc.)
244 - After variables are declared, there should be an empty line before the
245   rest of the function body.
247 - Merging declarations: variables do not have to be declared one per line;
248   however, they should only be grouped by similar function.
250     int foo(struct city *pcity)
251     {
252       int i, j, k;
253       int total, cost;
254       int build = pcity->shield_stock;
255     }
257 - When declaring a pointer, there should be a space before '*' and no space
258   after, except if it is a second '*'.
260     struct unit *find_random_unit(struct unit **array, size_t num)
261     {
262       struct unit *const *prand = array + fc_rand(num);
264       return *prand;
265     }
267   instead of
269     struct unit* find_random_unit(struct unit* *array, size_t num)
270     {
271       struct unit * const* prand = array + fc_rand(num);
273       return *prand;
274     }
277 ============================================================================
278   Bracing
279 ============================================================================
281 - Function braces begin and end in the first column:
283     int foo(void)
284     {
285       return 0;
286     }
288   instead of
290     int foo(void) {
291       return 0;
292     }
294 - Use extra braces for iteration macros. Note that the "*_iterate_end;"
295   should be placed on the same line as the end brace:
297     unit_list_iterate(pcity->units_supported, punit) {
298       kill(punit);
299     } unit_list_iterate_end;
301 - In switch statements, braces should only be placed where needed, i.e. to
302   protect local variables.
304 - Braces shall always be used after conditionals, loops, etc.:
306     if (x == 3) {
307       return;
308     }
310   and
312     if (x == 3) {
313       return 1;
314     } else {
315       return 0;
316     }
318   not
320     if (x == 3)
321       return 1;  /* BAD! */
324 ============================================================================
325   Enumerators
326 ============================================================================
327 - First of all, reread comment about the switch statement indentations and
328   braces.
330 - Avoid the usage of magic values (plain hard-coded value, such as 0 or -1)
331   and prefer the usage of enumerators. If an enumeration cannot be defined
332   for any reason, then define a macro for this value.
334 - Avoid storing magic values in external processes. For example, savegames
335   shouldn't contain any enumerators as magic numbers. They should be saved
336   as strings, to keep compatibility when their definition is changed. For
337   doing this, there are some tools in utility/specenum_gen.h; have a look at
338   it.
340 - Avoid the usage of the default case in switch statements, if possible. The
341   default case removes the warning of the compiler when a value is missing
342   in a switch statement.
345 ============================================================================
346   Including Headers
347 ============================================================================
348 - Order include files consistently: all includes are grouped together.
349   These groups are divided by an empty line. The order of these groups is as
350   follows:
352     1) fc_config.h (see below)
353     2) system include files which are OS-independent (part of C-standard or
354        POSIX)
355     3) system include files which are OS-dependent or conditional includes
356     4) include files from utility/
357     5) include files from common/
358     6) include files from client/
359     7) include files from server/ and ai/
360     8) include the header corresponding to the current c source file after
361        all other headers.
363   Each group is sorted in alphabetic order. This helps to avoid adding
364   unnecessary or duplicated include files.
366   Always set a comment to determine the location of the following headers
367   before every group.
369   It is very important that '#include <fc_config.h>' is at the top of
370   every .c file (it need not be included from .h files). Some definitions in
371   fc_config.h will affect how the code is compiled, without which you can end
372   up with bad and untraceable memory bugs.
374     #ifdef HAVE_CONFIG_H
375     #include <fc_config.h>
376     #endif
378     #include <stdlib.h>
380     /* utility */
381     #include "log.h"
383     /* common */
384     #include "game.h"
386     #include "myfileheader.h"
388 - For headers within a subdirectory path, the common rule is to set them
389   in an additional group, after the same group (don't forget the location
390   comment).
392     /* common */
393     #include "game.h"
395     /* common/aicore */
396     #include "pf_tools.h"
398   However, there is an exception to this. The last group is always the one
399   we are working on. So, if we are working on the common part, the order
400   should be:
402     /* common/aicore */
403     #include "pf_tools.h"
405     /* common */
406     #include "game.h"
408   Same observations with ai/ and server/. When working on the server/
409   directory, the order should be:
411     /* ai */
412     #include "aitools.h"
414     /* server */
415     #include "srv_main.h"
417   and working on the ai/ directory:
419     /* server */
420     #include "srv_main.h"
422     /* ai */
423     #include "aitools.h"
425 - Do not include headers in other headers if at all possible. Use forward
426   declarations for pointers to structs:
428     struct connection;
429     void a_function(struct connection *pconn);
431   instead of
433     #include "connection.h"
434     void a_function(struct connection *pconn);
436 - Of course, never include headers of non-linked parts of the code. For
437   example, never include client/ headers into a server/ file. Also, in the
438   client/ directory, GUI specific headers are never included. Always, use
439   the common set of headers defined in client/include/.
442 ============================================================================
443   Object-Oriented Programming
444 ============================================================================
445 Freeciv is not really object-oriented programming, but last written parts
446 seems to tend to there. Also, there are more and more parts which are
447 modular, so there are some observations to do:
449 - Any function or member of a module must be prefixed by the name of this
450   module, or an abbreviation of it (but use the same prefix for all members
451   please!). Never set the module name as suffix!
453     /* Super mega cool module! */
454     void smc_module_init(void);
455     void smc_module_free(void);
457   not
459     /* Super mega cool module! */
460     void smc_module_init(void);
461     void sm_cool_free(void);
463   neither
465     /* Super mega cool module! */
466     void init_smc_module(void);
467     void free_smc_module(void);
469 - A function which allocates memory for a pointer variable should use the
470   suffix '_new'. The memory is freed by a corresponding function with the
471   suffix '_destroy'.
473     {
474       struct test *t = test_new();
475       /* Do something. */
476       test_destroy(t);
477     }
479 - The suffix '_init' should be used for functions which initialize some
480   static data. The name of the corresponding function to deinitialize stuff
481   should use the suffix '_free' (see server/settings.c or common/map.c).
483     {
484       struct astring str;
486       astr_init(&str);
487       /* Do something. */
488       astr_free(&str);
489     }
492 ============================================================================
493   Miscellaneous
494 ============================================================================
496 - If an empty statement is needed, you should put an explanatory comment
497   in an empty block (i.e. {}):
499     while (*i++) {
500       /* Do nothing. */
501     }
503 - Use the postfix operator instead of the prefix operator when either will
504   work. That is, write "a++" instead of "++a".
506 - Strive to make your code re-entrant (thread/recursion safe), as long as
507   this does not make the implementation too cumbersome or involved.
509 - Strive to make your code modular: make it independent from other parts of
510   the codebase, and assume as little as possible about the circumstances in
511   which it is used.
513 - Strive to avoid code duplication: if some part of the code is repeated in
514   several places, factor it out into a helper function.
516 - Try to use static inline functions and const data instead of macros.
518 - If helper functions internal to freeciv are added, prefix their names
519   with 'fc_'. Do not use 'my_' because it is also used by MySQL and could
520   be included in some libs.
522 - Do not use assert() or die(); instead use the macros defined within
523   utility/log.h:
525     fc_assert(condition)
526     fc_assert_ret(condition)
527     fc_assert_ret_val(condition, val)
528     fc_assert_action(condition, action_on_failure)
529     fc_assert_exit(condition, action_on_failure)
531     fc_assert_msg(condition, message, ...)
532     fc_assert_ret_msg(condition, message, ...)
533     fc_assert_ret_val_msg(condition, val, message, ...)
534     fc_assert_action_msg(condition, action_on_failure, message, ...)
535     fc_assert_exit_msg(condition, action_on_failure, message, ...)
537   This way error conditions can be handled gracefully while still enforcing
538   invariants you expect not to be violated in the code.
539   (By default execution will continue with a warning, but it can be made
540   to halt by specifying the '-F' option to the client or server.)
542     int foo_get_id(const struct foo *pfoo)
543     {
544       fc_assert_ret_val(pfoo != NULL, -1);
545       return pfoo->id;
546     }
548 - Do not put multiple conditions in the same fc_assert*() statement:
550     fc_assert(pfoo != NULL);
551     fc_assert(pfoo->id >= 0);
553   instead of
555     fc_assert(pfoo != NULL && pfoo->id >= 0);
557 - Never include functionality also otherwise necessary inside fc_assert*().
558   Such functionality would be missing from release builds where asserts
559   are disabled. If you want to assert return value of a critical function
560   call, make the call outside assert and place the return value to variable
561   and then assert value of that variable.
563 - For strings containing multiple sentences, use a single space after periods
564   (not two, not zero, just one).
566 - If you use a system specific feature, do not add #ifdef __CRAY__ or
567   something like that. Rather write a check for that feature for
568   configure.ac, and use a meaningful macro name in the source.
570 - Always prototype global functions in the appropriate header file. Local
571   functions should always be declared as static. To catch these and some
572   other problems please use the following warning options "-Wall
573   -Wpointer-arith -Wcast-align -Wmissing-prototypes -Wmissing-declarations
574   -Wstrict-prototypes -Wnested-externs -Wl,--no-add-needed" if you use gcc.
576 - Always check compilation with the configure option --enable-debug set.
578 - Header files should be compatible with C++ but code (.c) files need not
579   be. This means some C++ keywords (like "this" or "class") may not be used
580   in header files. It also means casts on void pointers (which should be
581   avoided in C files) must be used in headers.
583 - To assign null pointer, or to compare against one, use 'NULL' in C code,
584   and 'nullptr' in C++ code.
586 - If you send patches, use "diff -u" (or "diff -r -u"). "svn diff" works
587   correctly without extra parameters.
589   For further information, see:
590   <http://www.freeciv.org/wiki/How_to_Contribute>.
592   Also, name patch files descriptively (e.g. "fix-foo-bug-0.patch" is good,
593   but "freeciv.patch" is not).
595 - When doing a "diff" for a patch, be sure to exclude unnecessary files by
596   using the "-X" argument to "diff". E.g.:
598     % diff -ruN -Xdiff_ignore freeciv_svn freeciv >/tmp/fix-foo-bug-0.patch
600   A suggested "diff_ignore" file is included in the Freeciv distribution.
602 ============================================================================