]> git.pond.sub.org Git - empserver/blob - doc/coding
client: Make get_password() not echo with POSIX && !HAVE_GETPASS
[empserver] / doc / coding
1                 Guidelines for Writing Empire Code
2
3              compiled and edited by Markus Armbruster
4
5 Preface
6 -------
7
8 Empire is an old program, and the age shows in places.  It took a lot
9 of people a lot of effort to write it.  Chances are that some of them
10 were smarter than you and me.  Treat the code with the respect it
11 deserves.
12
13 These guidelines are just that: guidelines.  Not law.  There's no
14 Empire Coding Police.  People hacked on Empire code long before I knew
15 it existed, and I hope they still will when I fade into Empire
16 history.  But there's substantial experience behind these guidelines,
17 so don't dismiss them cavalierly.
18
19 Here's our goal: algorithmic clarity.  All the rules and guidelines
20 are subservient to it.  If you'd have to obfuscate your code to
21 satisfy the letter of some guideline, don't!
22
23 Mind, I said `clarity', not `self-realization' or `expression of your
24 individuality'.  Dave Pare wrote:
25
26   Be invisible.  When you make a change, think not about marking your
27   place in history, or about showing off how much nicer your two-space
28   tabs are than those old, icky eight-space tabs that the stupid
29   empire hackers of old used, but think instead about the aesthetics
30   of the whole.  The resulting lines of code should flow smoothly from
31   the beginning of the procedure to the end.  Empire is 60,000 lines
32   of code.  If you're the general case, you're only changing fifty
33   lines, so be aware of that.
34
35 Some guidelines are more serious than others.  When I use words like
36 `is', `shall' or `must', I mean it.  When I write `should', it's a
37 recommendation.
38
39 Many guidelines concern style, i.e. they involve matters of taste.
40 That's how it has to be.  Uniformity of style is important for
41 clarity.
42
43 These guidelines don't attempt to be exhaustive.  More complete
44 guidelines that are mostly compatible with Empire can be found at
45 <http://www.jetcafe.org/~jim/c-style.html>.
46
47 See also doc/contributing.
48
49
50 Source tree organization
51 ------------------------
52
53 FIXME
54
55
56 Code formatting
57 ---------------
58
59     In My Egotistical Opinion, most people's C programs should be
60     indented six feet downward and covered with dirt."
61         -- Blair P. Houghton
62
63 Over the years, enough Empire coders lacked the good taste to preserve
64 the style of the original Empire code in their changes, and thus
65 turned the source code into an unreadable mess.  In 2003, we fed it to
66 GNU indent.
67
68 We tried to restore things to the original style, mostly.  There is
69 one notable change: basic indentation is now four spaces.  Restoring
70 the original eight spaces would have resulted in many more long lines,
71 which would have to be broken by indent.  Since indent isn't good at
72 breaking lines tastefully, we reluctantly chose four instead.
73
74 FIXME mention src/scripts/intend-emp, even better: convert it into an
75 indent profile and mention that.
76
77 If you use Emacs, `stroustrup' indentation style produces satisfactory
78 results.  The command `c-set-style', normally bound to `C-c .', lets
79 you set the style for the current buffer.  Set variable
80 `c-default-style' to "stroustrup" to switch to this style for all
81 buffers.
82
83 Avoid gratuitous space change
84
85 Don't change whitespace gratuitiously, say just because your editor
86 screws up tabs.  Such changes make it much harder to figure out who
87 changed what and when.
88
89 TAB character use
90
91 Whether you use TAB characters or not doesn't really matter that much,
92 but TAB stops are every eight characters, period.
93
94 Indentation, placement of braces, function name
95
96 Basic indentation is four spaces.  The opening brace goes on the same
97 line as `if', `struct', etc.  Put `else' and do loops' `while' one the
98 same line as the closing brace.  You are encouraged to leave out
99 syntactically optional braces.  Don't indent case labels.
100
101 Example:
102
103         if (is_fubar())
104             despair();
105         else {
106             do {
107                 char ch = getchar();
108                 switch (ch) {
109                 case EOF:
110                     return;
111                 case '\n':
112                     break;
113                 default:
114                     grind_along(ch);
115                 }
116             } while (happy());
117         }
118
119 In a function definition, the return type, function name and the
120 braces must all start on a new line, unindented, like this:
121
122         type
123         name(arguments)
124         {
125             body
126         }
127
128 This does not apply to function declarations.
129
130 Breaking long lines
131
132 Line length should not exceed 75 characters.  Break such lines at a
133 logical place, preferably before an operator with low precedence.
134 Line up the continuation line with the innermost unclosed parenthesis,
135 if there is one, else indent it four spaces.
136
137 Example:
138
139         FIXME
140
141 Bad example:
142
143         FIXME
144
145 Blank lines
146
147 Use blank lines to separate different things.  Functions must be
148 separated by a blank line.  You are encouraged to insert a blank line
149 between a block's declarations and statements.
150
151 Spaces
152
153 There is a space after `for', `if', and `while'.  If `for' and `while'
154 are followed by `;' (empty loop body) on the same line, there is a
155 space before the `;'.  There is no space between the function name and
156 the `(', but there is a space after each `,'.  There should be no
157 space between type cast operator and operand.  There is no extra space
158 after '(' and before ')'.
159
160 Example:
161
162         for (p = s; *p; ++p) ;
163         printf("%ld\n", (long)(p-s));
164
165 Comments
166
167 The function comment describing what a function does goes directly
168 above the definition.
169
170 Comments to the right of code should start in column 32 if possible
171 (counting from zero).
172
173 Comment lines should be indented exactly like the code they belong to.
174
175 You are encouraged to format multi-line comments like this:
176
177         /*
178          * Please use complete sentences, with proper grammar,
179          * capitalization and punctuation.  Use two spaces between
180          * sentences.
181          */
182
183 But please avoid elaborate boxes like this:
184
185         /***********************************************************
186          * Such decorations are a waste of time, hard to edit, and *
187          * ugly, too.                                              *
188          ***********************************************************/
189
190 Do not use
191
192         // C++/C99 comments
193
194 because they are not portable C89.
195
196 Conditional compilation
197
198 Unless the conditional code is very short, please comment it like
199 this:
200
201         #ifdef FOO
202         ...
203         #endif /* FOO */
204
205         #ifdef BAR
206         ...
207         #else  /* !BAR */
208         ...
209         #endif /* !BAR */
210
211
212 Style
213 -----
214
215 Names
216
217 DoNotUseStudlyCaps!  Stick to lower_case and use underscores.  Upper
218 case is for macros and enumeration constants.
219
220 File names should not differ in case only, since not all file systems
221 distinguish case.  Best stick to lower case.  Avoid funny characters
222 in file names.  This includes space.
223
224 Preprocessor
225
226 Like many good things, the preprocessor is best used sparingly.
227 Especially conditional compilation.
228
229 Do not use the preprocessor to `improve' the syntax of C!
230
231 Macro names should be ALL_CAPS to make them stand out.  Otherwise,
232 they can be mistaken for objects or functions.  This is bad, because
233 `interesting' behavior can hide inside macros, like not evaluating
234 arguments, or changing them.  Exception: if a function-like macro
235 behaves exactly like a function, then you may use a lower case name.
236
237 Parameters that can take expression arguments must be parenthesized in
238 the expansion.  If the expansion is an expression, it should be
239 parenthesized as well.
240
241 You are encouraged to use enumeration constants instead of macros when
242 possible.  The existing code doesn't, but it makes sense all the same.
243
244 Comments
245
246 Every file should have a file comment FIXME
247
248 Every function should have a function comment that describes what it
249 does, unless it's blatantly obvious.  If the function is longer than a
250 few lines, it's almost certainly not obvious.
251
252 The function comment should serve as a contract: state the
253 preconditions, side effects, return values.  Make sure to cover error
254 conditions.
255
256 Writing such comments helps both future maintainers and yourself: when
257 writing a concise function comment is too hard, then your function is
258 likely too complicated and could use a redesign.
259
260 Use @param to refer to parameters.  Use func() to refer to functions
261 or function-like macros.  Use arr[] to refer to arrays.  This is to
262 make the references stand out and to avoid ambiguity.
263
264 Example:
265
266     /*
267      * Read update schedule from file @fname.
268      * Put the first @n-1 updates after @t0 into @sched[] in ascending order,
269      * terminated with a zero.
270      * Use @anchor as initial anchor for anchor-relative times.
271      * Return 0 on success, -1 on failure.
272      */
273     int
274     read_schedule(char *fname, time_t sched[], int n, time_t t0, time_t anchor)
275
276 When documenting a struct or union, use @member to refer to its
277 members.
278
279 The existing code has very little useful comments, and it'll likely
280 take us years to fix it.  Please don't make it harder than it already
281 is.
282
283 Declarations
284
285 Do not declare system functions yourself; include the appropriate
286 system header.
287
288 Use prototypes, not old-style function declarations.
289
290 To get the best use of C's type checking, each function or variable
291 with external linkage should have exactly one declaration, in some
292 header file, and that declaration must be in scope at the definition.
293 No other declarations should exist.  In particular, please include the
294 appropriate header instead of just declaring stuff again.  The code
295 used to be full of this kind of junk, and it was quite some work to
296 clean it up.
297
298 Forward declarations of static functions should all go in one place
299 near the beginning of the file.
300
301 If you want a typedef name in addition to a structure or union tag,
302 give it the same name, like this:
303
304         typedef struct foo foo;
305
306 Yes, this is incompatible with C++.  Reducing the number of names for
307 the same thing is more useful than compatibility to a programming
308 language we don't use.
309
310 Please don't hide away pointers with typedefs, like this:
311
312        typedef struct foo *foop;
313
314 When I see `foo *', I *know* what it is.  When I see `foop', I have to
315 look it up.
316
317 Booleans
318
319 Do not use increment operators to set a variable to logical true!  It
320 obfuscates the purpose, and narrow variables could even overflow.
321 Just assign 1.  A lot of cleanup remains to be done there.
322
323 Null pointer constant
324
325 Please use NULL for clarity, not just 0.
326
327 Type casts
328
329 Casting pointers to and from `void *' clutters the code and serves no
330 purpose (repeat after me: C is not C++).  It is also unsafe, because
331 the cast suppresses type warnings.
332
333 Casting function values to void clutters the code and serves little
334 purpose (repeat after me: C is not Pascal).
335
336 Casting an argument to the type of the parameter clutters the code and
337 serves no purpose (repeat after me: ISO C is not K&R C).
338
339 Factor out common code
340
341 Do not gratuitously duplicate code!  Ken Stevens said it well, and
342 it's as relevant as ever:
343
344   Cut-and-Paste coding is by far the biggest problem that the current
345   Empire suffers from.  This is how cut-and-paste coding happens.  Joe
346   Shmuck decides that he wants to add a new function to the server.
347   So he goes hunting through the server to find some already existing
348   code which does something similar to what he wants to do.  This is
349   good.  You should always write new code to imitate old code.  What
350   is bad is when Joe Shmuck decides to simply "copy" 200 lines of code
351   from the old function into his new function, and then just change a
352   couple of little things here and there to suit his needs.  This
353   method, known as Cut-and-Paste coding is the fastest and easiest way
354   to code.  However, it results in a server that is impossible to
355   maintain.  What Joe _should_ have done, is "move" the 200 lines of
356   code into a new _third_ function which the first two both call.
357   This is called writing a "general solution" to handle both cases.
358   Most of my work in the Empire2 project consisted in cleaning up
359   after a bunch of Joe Shmucks.
360
361
362 Portability
363 -----------
364
365 FIXME C89, POSIX
366
367 FIXME sizes, printf formats
368
369 FIXME reserved names
370
371 FIXME conditional compilation is a last resort
372
373
374 Robustness
375 ----------
376
377 Error checking
378
379 Check error conditions meticulously.  The existing code is bad enough
380 at this, please don't make it worse.
381
382 FIXME what to do on error
383
384 Sanity checking
385
386 In many places, the code checks for conditions that should not happen,
387 and then tries to recover.  This is sound defensive programming.
388 Please use CANT_HAPPEN() and CANT_REACH() for this purpose, because
389 they log the error condition, and optionally abort the program, or
390 write out a core dump.  This is called an "oops".
391
392 Buffer overruns
393
394 FIXME
395
396 Thread safety
397
398 Thread stacks cannot grow.  If you use too much automatic storage, you
399 can overrun the stack with disastrous consequences.  FIXME elaborate
400
401 Empire uses non-preemptive threads: a thread runs until it yields the
402 processor.  This simplifies programming, but there are still traps to
403 avoid.  Yielding the processor is an explicit thread operation, and
404 whether a thread operation yields is documented in empthread.h.
405 However, the operation may be buried in library code.
406
407 In particular, player input may yield.  Player output may yield only
408 if it goes to the current player, and his last command doesn't have
409 the C_MOD flag.  You can use this to simplify command code: set C_MOD
410 if you don't want to worry about yield on output.  This is commonly
411 done for commands that modify game state.
412
413 Be careful with static storage.  Read-only data is fine.  More than
414 one thread writing static data is problematic, but there are safe
415 uses.  For instance, a static scratch buffer that is never used across
416 `yields' is safe.
417
418 Yielding the processor invalidates *all* the game state you copied
419 into variables.  You have to reread and possibly recheck.  See below.
420
421 Accessing game state
422
423 Game state consists of several sets of objects, e.g. sectors, ships,
424 bmaps, ...  Each set is fully held in memory and backed by a file in
425 the data directory.
426
427 There are several ways to access an object in set FOO:
428
429 * You can get a pointer to the object (not a copy!) with getFOOp().
430
431   This is inherently dangerous, because it allows you to update the
432   object in memory without updating the disk file.  It's used mostly
433   in update code, where it pays major performance dividends, but there
434   are uses in other places.  Whether they are wise is debatable.
435
436   Obviously, the object can change when you let another thread run.
437   This is not an issue in update code, because it never yields.
438
439 * You can get a copy with getFOO() and write it back with putFOO().
440
441   Putting updates both the object in memory and the disk file.
442
443   Any change to the object invalidates the copy.  Putting such an
444   invalid copy will clobber the change(s) that invalidated it,
445   possibly resulting in corrupted game state.  The code oopses on such
446   puts, but it can't repair the damage.
447
448   There are two common ways to invalidate a copy: calling a function
449   that updates the object you copied (unless it does that through your
450   copy), and yielding the processor, which lets other threads update
451   the object you copied.
452
453   Therefore, you have to re-get after a possible invalidation, and
454   deal with changes.  In particular, if you checked whether the object
455   is suitable for a task, you need to check again after re-getting it.
456   If you can afford to bail out when something changed, use
457   check_FOO_ok().
458
459   Function comments should state what objects the function can update.
460   Unfortunately, they generally don't.
461
462   It's best to keep puts close to gets, both at runtime and in the
463   source code.
464
465 * Bmaps have special access functions.
466
467   Each country has two bmaps: the working bmap and the true bmap.
468   Unfortunately, the bmap code calls the former `bmap' and the latter
469   `map'.
470
471   You update bmaps with map_set().  This doesn't write through to the
472   file; instead, it returns non-zero when the update changed anything.
473   In that case, you must write bmaps to disk with writemap() before
474   you yield.  If you only updated the working bmap, then you can call
475   writebmap() instead.
476
477 Reading player input
478
479 Reading player input can fail, and you must check for that.
480 Neglecting it can break the interrupt feature for players (normally
481 Ctrl-C), and produce extra prompts that could confuse clients.  Even
482 worse is neglecting it in a loop that terminates only when input is
483 read successfully.
484
485 When reading input fails, you should normally abort the command with
486 status RET_SYN.  There are exceptions, e.g. when aborting a pinpoint
487 bombing run over the target.
488
489 Some functions to read player input return a special error value you
490 can check, e.g. recvclient(), prmptrd() and uprmptrd() return a
491 negative value, getstring() and getstarg() return NULL.
492
493 Others return the same error value for failed read and for successful
494 read of input that is invalid.  Then you need to check
495 player->aborted; if it is set after a read, the read failed.
496
497 \f
498 Historical guidelines, superseded by the above
499
500
501 Remarks from Dave Pare:
502
503 And now, a few editorial remarks on my views on Good Techniques for
504 Modifying Existing Software:
505
506 My safari through the hot and bug-ridden jungle that Empire has become
507 has given me some new insights on the modification of large software
508 packages.  My adventure has prompted me to propose some simple coding
509 guidelines for those dreaming of hacking on the code:
510
511 1) Be invisible.  When you make a change, think not about marking your
512 place in history, or about showing off how much nicer your two-space
513 tabs are than those old, icky eight-space tabs that the stupid empire
514 hackers of old used, but think instead about the asethetics of the whole.
515 The resulting lines of code should flow smoothly from the beginning of the
516 procedure to the end.  Empire is 60,000 lines of code.  If you're the
517 general case, you're only changing fifty lines, so be aware of that.
518
519 2) Procedurize.  If you find yourself in a triple-nested loop, or a five
520 hundred line procedure, perhaps it's because you need to split some of
521 that code off into a procedure.  In general, if you've got more than two
522 levels of tabs (or indentations), or more than one or two major loops in
523 a procedure, something may well be amiss.
524
525
526 Sasha Mikheev on indentation:
527
528 The empire indentation style can be achived by using
529 indent -orig -i8 foo.c
530
531 or in old c-mode emacs (versions before 19.29):
532 ;add this to .emacs
533 (setq c-indent-level 8)
534 (setq c-continued-statement-offset 8)
535 (setq c-argdecl-indent 8)
536 (setq c-brace-offset -8)
537 (setq c-label-offset -8)
538
539
540 Further comments by Ken Stevens:
541
542 1) Global variables
543 The only variables which should be global are constants.  If you write
544 a routine which changes a global variable, then you will corrupt the
545 data when two different players run that routine at the same time.
546
547 2) Portability.
548 The following code:
549                 char    a;
550         #ifdef FOO
551                 unsigned char b;
552         #endif FOO
553 Should be rewritten as:
554                 s_char  a;
555         #ifdef FOO
556                 u_char  b;
557         #endif /* FOO */
558
559 AIX has different conventions for signed chars, and IRIX requires the
560 /* comments */ after #endif.
561
562 3) Cut-and-Paste
563 Cut-and-Paste coding is by far the biggest problem that the current
564 Empire suffers from.  This is how cut-and-paste coding happens.  Joe
565 Shmuck decides that he wants to add a new function to the server.  So
566 he goes hunting through the server to find some already existing code
567 which does something similar to what he wants to do.  This is good.
568 You should always write new code to imitate old code.  What is bad is
569 when Joe Shmuck decides to simply "copy" 200 lines of code from the old
570 function into his new function, and then just change a couple of
571 little things here and there to suit his needs.  This method, known as
572 Cut-and-Paste coding is the fastest and easiest way to code.  However,
573 it results in a server that is impossible to maintain.  What Joe
574 _should_ have done, is "move" the 200 lines of code into a new _third_
575 function which the first two both call.  This is called writing a
576 "general solution" to handle both cases.  Most of my work in the
577 Empire2 project consisted in cleaning up after a bonch of Joe Shmucks.
578 I took repeated code and "consolidated" it into general function
579 libraries.
580
581 4) Good style.
582 Just to add to Dave's "Be Invisible" motto, I'd like to give a little
583 example to illustrate some basic do's and don'ts for coding style:
584
585 The following function has bad style:
586
587 double att_combat_eff(com,own)
588 struct combat *com;
589 natid own;{
590   double str;
591   double eff=1.0;
592   if(com->type==EF_SECTOR)
593   {
594     eff=com->eff/100.0;
595     if(com->own==own){
596       str=com->sct_dcp->d_ostr;
597     }else{
598 str=com->sct_dcp->d_dstr;eff=2.0+(str-2.0)*eff;
599     }else if(com->type==EF_SHIP&&com->own!=own)
600       eff=(1.0+com->shp_mcp->m_armor/100.0);
601   return eff;}
602
603 Here is the same function written with "good" style:
604
605 double
606 att_combat_eff(com, own)
607         struct  combat *com;
608         natid   own;
609 {
610         double  eff = 1.0;
611         double  str;
612
613         if (com->type == EF_SECTOR) {
614                 eff = com->eff / 100.0;
615                 if (com->own == own)
616                         str = com->sct_dcp->d_ostr;
617                 else
618                         str = com->sct_dcp->d_dstr;
619                 eff = 2.0 + (str - 2.0) * eff;
620         } else if (com->type == EF_SHIP && com->own != own)
621                 eff = (1.0 + com->shp_mcp->m_armor / 100.0);
622
623         return eff;
624 }
625
626 These are all the things I fixed when changing the bad to the good:
627 - Function names should always start a new line (so you can search for them)
628 - There should always be a space after a ","
629 - Function arguments should be indented 8 spaces
630 - There should always be a tab after a type declaration
631 - Opening function bracket should be on a line by itself
632 - Indentation should be 8 spaces
633 - There should always be a space on both sides of every operator
634 - There should always be a space after if, for, while, switch
635 - The opening bracket should be on the same line as the if
636 - There should always be a space on either side of a {
637 - There should always be a new line after a ;
638 - The closing function bracket should be on a line by itself