1LIBXENLIGHT CODING STYLE
2========================
3
4
5AN APOLOGY AND WARNING
6----------------------
7
8Much of the code in libxl does not yet follow this coding style
9document in every respect.  However, new code is expected to conform.
10
11Patches to improve the style of existing code are welcome.  Please
12separate these out from functional changes.
13
14If it is not feasible to conform fully to the style while patching old
15code, without doing substantial style reengineering first, we may
16accept patches which contain nonconformant elements, provided that
17they don't make the coding style problem worse overall.
18
19In this case, the new code should conform to the prevailing style in
20the area being touched.
21
22
23MEMORY ALLOCATION
24-----------------
25
26Memory allocation for libxl-internal purposes should normally be done
27with the provided gc mechanisms; there is then no need to free.  See
28"libxl memory management" in libxl.h.
29
30
31CONVENTIONAL VARIABLE NAMES
32---------------------------
33
34The following local variable names should be used where applicable:
35
36  int rc;    /* a libxl error code - and not anything else */
37  int r;     /* the return value from a system call (or libxc call) */
38  bool ok;   /* the success return value from a boolean function */
39
40  uint32_t domid;
41  libxl__gc *gc;
42  libxl__egc *egc;
43  libxl__ao *ao;
44
45  libxl_foo_bar_state *fbs;    /* local variable */
46  libxl_foo_bar_state foo_bar; /* inside another state struct */
47
48
49CONVENIENCE MACROS
50------------------
51
52There are a number of convenience macros which shorten the program and
53avoid opportunity for mistakes.  In some cases non-use of the macros
54produces functional bugs or incorrect error handling.  Use the macros
55whenever they are applicable.  For example:
56
57 Usually, don't use:     Instead, use (see libxl_internal.h):
58  libxl__log[v]           LOG, LOGE, LOGEV
59  libxl__sprintf          GCSPRINTF
60  libxl__*alloc et al.    GCNEW, GCNEW_ARRAY, GCREALLOC_ARRAY
61  isalnum etc. directly   CTYPE
62  libxl__ctx_[un]lock     CTX_LOCK, CTX_UNLOCK
63  gc=...; ao=...;         EGC_GC, AO_GC, STATE_AO_GC
64  explicit gc creation    GC_INIT, GC_FREE
65  memset(..,0,sizeof..)   FILLZERO
66
67Instead of malloc et al one should (as an exception to the above) use
68libxl__{zalloc,calloc,realloc} etc but passing NOGC.
69
70ERROR HANDLING
71--------------
72
73Unless, there are good reasons to do otherwise, the following error
74handling and cleanup paradigm should be used:
75
76  * All local variables referring to resources which might need
77    cleaning up are declared at the top of the function, and
78    initialised to a sentinel value indicating "nothing allocated".
79    For example,
80            libxl_evgen_disk_eject *evg = NULL;
81            int nullfd = -1;
82
83  * If the function is to return a libxl error value, `rc' is
84    used to contain the error code, but it is NOT initialised:
85            int rc;
86
87  * There is only one error cleanup path out of the function.  It
88    starts with a label `out:'.  That error cleanup path checks for
89    each allocated resource and frees it iff necessary.  It then
90    returns rc.  For example,
91         out:
92             if (evg) libxl__evdisable_disk_eject(gc, evg);
93             if (nullfd >= 0) close(nullfd);
94             return rc;
95
96  * Function calls which might fail (ie most function calls) are
97    handled by putting the return/status value into a variable, and
98    then checking it in a separate statement:
99            char *dompath = libxl__xs_get_dompath(gc, bl->domid);
100            if (!dompath) { rc = ERROR_FAIL; goto out; }
101
102  * If a resource is freed in the main body of the function (for
103    example, in a loop), the corresponding variable has to be reset to
104    the sentinel at the point where it's freed.
105
106Whether to use the `out' path for successful returns as well as error
107returns is a matter of taste and convenience for the specific
108function.  Not reusing the out path is fine if the duplicated function
109exit code is only `CTX_UNLOCK; GC_FREE;' (or similar).
110
111If you reuse the `out' path for successful returns, there may be
112resources which are to be returned to the caller rather than freed.
113In that case you have to reset the local variable to `nothing here',
114to avoid the resource being freed on the out path.  That resetting
115should be done immediately after the resource value is stored at the
116applicable _r function parameter (or equivalent).  Do not test `rc' in
117the out section, to discover whether to free things.
118
119The uses of the single-line formatting in the examples above are
120permitted exceptions to the usual libxl code formatting rules.
121
122
123
124IDEMPOTENT DATA STRUCTURE CONSTRUCTION/DESTRUCTION
125--------------------------------------------------
126
127Nontrivial data structures (in structs) should come with an idempotent
128_dispose function, which must free all resources associated with the
129data structure (but not free the struct itself).
130
131Such a struct should also come with an _init function which
132initialises the struct so that _dispose is a no-op.
133
134
135ASYNCHRONOUS/LONG-RUNNING OPERATIONS
136------------------------------------
137
138All long-running operations in libxl need to use the asynchronous
139operation machinery.  Consult the programmer documentation in
140libxl_internal.h for details - search for "Machinery for asynchronous
141operations".
142
143The code for asynchronous operations should be laid out in
144chronological order.  That is, where there is a chain of callback
145functions, each subsequent function should be, textually, the next
146function in the file.  This will normally involve predeclaring the
147callback functions.  Synchronous helper functions should be separated
148out into a section preceding the main callback chain.
149
150Control flow arrangements in asynchronous operations should be made as
151simple as possible, because it can otherwise be very hard to see
152through the tangle.
153
154
155When inventing a new sub-operation in asynchronous code, consider
156whether to structure it formally as a sub-operation with its own state
157structure.  (See, for example, libxl__datacopier_*.)
158
159An ao-suboperation state structure should contain, in this order:
160  * fields that the caller must fill in, and which are,
161    effectively, the parameters to the operation, including:
162      - libxl__ao *ao
163      - the callback function pointer(s), which
164        should be named callback or callback_*.
165  * shared information fields or ones used for returning information
166    to the calling operation
167  * private fields
168These sections should be clearly demarcated by comments.
169
170An asynchronous operation should normally have an idempotent stop or
171cancel function.  It should normally also have an _init function for
172its state struct, which arranges that the stop is a no-op.
173
174The permitted order of calls into your ao operation's methods must be
175documented in comments, if it is nontrivial.
176
177
178When using an ao sub-operation, you should normally:
179 * Physically include the sub-operation state struct in your
180   own state struct;
181 * Use CONTAINER_OF to find your own state struct at the start of
182   your implementations of the sub-operation callback functions;
183 * Unconditionally initialise the sub-operation's struct (with its
184   _init method) in your own _init method.
185 * Unconditionally cancel or destroy the sub-operation in your own
186   cancel or destroy method.
187
188
189FORMATTING AND NAMING
190---------------------
191
192Blatantly copied from qemu and linux with few modifications.
193
194
1951. Whitespace
196
197Of course, the most important aspect in any coding style is whitespace.
198Crusty old coders who have trouble spotting the glasses on their noses
199can tell the difference between a tab and eight spaces from a distance
200of approximately fifteen parsecs.  Many a flamewar have been fought and
201lost on this issue.
202
203Libxenlight indents are four spaces.  Tabs are never used, except in
204Makefiles where they have been irreversibly coded into the syntax.
205Spaces of course are superior to tabs because:
206
207 - You have just one way to specify whitespace, not two.  Ambiguity breeds
208   mistakes.
209 - The confusion surrounding 'use tabs to indent, spaces to justify' is gone.
210 - Tab indents push your code to the right, making your screen seriously
211   unbalanced.
212 - Tabs will be rendered incorrectly on editors who are misconfigured not
213   to use tab stops of eight positions.
214 - Tabs are rendered badly in patches, causing off-by-one errors in almost
215   every line.
216 - It is the libxenlight coding style.
217
218Do not leave whitespace dangling off the ends of lines.
219
220
2212. Line width
222
223Lines are limited to 75 characters.
224
225Rationale:
226 - Some people like to tile their 24" screens with a 6x4 matrix of 80x24
227   xterms and use vi in all of them.  The best way to punish them is to
228   let them keep doing it.
229 - In an 80 column terminal, some room needs to be left for > quoting
230   characters, +/- diff characters, and so on, in emails.
231 - Code and especially patches is much more readable if limited to a sane
232   line length.  Eighty is traditional.
233 - It is the libxenlight coding style.
234
235
2363. Naming
237
238C is a Spartan language, and so should your naming be.  Unlike Modula-2
239and Pascal programmers, C programmers do not use cute names like
240ThisVariableIsATemporaryCounter.  A C programmer would call that
241variable "tmp", which is much easier to write, and not the least more
242difficult to understand.
243
244HOWEVER, while mixed-case names are frowned upon, descriptive names for
245global variables are a must.  To call a global function "foo" is a
246shooting offense.
247
248GLOBAL variables (to be used only if you _really_ need them) need to
249have descriptive names, as do global functions.  If you have a function
250that counts the number of active users, you should call that
251"count_active_users()" or similar, you should _not_ call it "cntusr()".
252
253Encoding the type of a function into the name (so-called Hungarian
254notation) is brain damaged - the compiler knows the types anyway and can
255check those, and it only confuses the programmer.
256
257LOCAL variable names should be short, and to the point.  If you have
258some random integer loop counter, it should probably be called "i".
259Calling it "loop_counter" is non-productive, if there is no chance of it
260being mis-understood.  Similarly, "tmp" can be just about any type of
261variable that is used to hold a temporary value.
262
263Local variables used to store return values should have descriptive name
264like "rc" or "ret". Following the same reasoning the label used as exit
265path should be called "out".
266
267Function arguments which are used to return values to the caller
268should be suffixed `_r' or `_out'.
269
270Variables, type names and function names are
271lower_case_with_underscores.
272Type names and function names use the prefix libxl__ when internal to
273libxenlight and libxl_ when exported in libxl.h.
274Xl should avoid using libxl_ and libxl__ as prefix for its own function
275names.
276
277When wrapping standard library functions, use the prefix libxl_ to alert
278readers that they are seeing a wrapped version; otherwise avoid this prefix.
279
280Typedefs are used to eliminate the redundant 'struct' keyword.
281It is the libxenlight coding style.
282
283
2844. Statements
285
286Don't put multiple statements on a single line.
287Don't put multiple assignments on a single line either.
288Error code paths with an if statement and a goto or a return on the same
289line are allowed. Examples:
290
291    if (rc) goto out;
292    if (rc < 0) return;
293
294Libxenlight coding style is super simple.  Avoid tricky expressions.
295
296
2975. Block structure
298
299Every indented statement is braced, but blocks that contain just one
300statement may have the braces omitted.  To avoid confusion, either all
301the blocks in an if...else chain have braces, or none of them do.
302
303The opening brace is on the line that contains the control flow
304statement that introduces the new block; the closing brace is on the
305same line as the else keyword, or on a line by itself if there is no
306else keyword.  Examples:
307
308    if (a == 5) {
309        printf("a was 5.\n");
310    } else if (a == 6) {
311        printf("a was 6.\n");
312    } else {
313        printf("a was something else entirely.\n");
314    }
315
316    if (a == 5)
317        printf("a was 5.\n");
318
319An exception is the opening brace for a function; for reasons of tradition
320and clarity it comes on a line by itself:
321
322    void a_function(void)
323    {
324        do_something();
325    }
326
327Rationale: a consistent (except for functions...) bracing style reduces
328ambiguity and avoids needless churn when lines are added or removed.
329Furthermore, it is the libxenlight coding style.
330
331