xref: /plan9/sys/src/cmd/gs/doc/C-style.htm (revision 593dc095aefb2a85c828727bbfa9da139a49bdf4)
1<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
2<html>
3<head>
4<title>Ghostscript C coding guidelines</title>
5<!-- $Id: C-style.htm,v 1.55 2005/10/20 19:46:23 ray Exp $ -->
6<!-- Originally: c-style.txt -->
7<link rel="stylesheet" type="text/css" href="gs.css" title="Ghostscript Style">
8</head>
9
10<body>
11<!-- [1.0 begin visible header] ============================================ -->
12
13<!-- [1.1 begin headline] ================================================== -->
14
15<h1>Ghostscript C coding guidelines</h1>
16
17<!-- [1.1 end headline] ==================================================== -->
18
19<!-- [1.2 begin table of contents] ========================================= -->
20
21<h2>Table of contents</h2>
22
23<blockquote><ul>
24<li><a href="#Introduction">Introduction</a>
25<li><a href="#C_language">C language do's and don'ts</a>
26<ul>
27<li>Preprocessor:
28    <a href="#Conditionals">Conditionals</a>,
29    <a href="#Macros">Macros</a>,
30    <a href="#Preprocessor_other">Other</a>
31<li><a href="#Lexical_elements">Lexical elements</a>
32<li><a href="#Scoping">Scoping</a>
33<li>Data types:
34    <a href="#Scalars">Scalars</a>,
35    <a href="#Arrays">Arrays</a>,
36    <a href="#Typedefs">Typedefs</a>,
37    <a href="#Structures">Structures</a>,
38    <a href="#Unions">Unions</a>
39<li><a href="#Expressions">Expressions</a>
40<li><a href="#Statements">Statements</a>
41<li><a href="#Procedures">Procedures</a> (prototypes and definitions)
42<li><a href="#Standard_library">Standard library</a>
43</ul>
44<li><a href="#Language_extensions">Language extensions</a>
45<li><a href="#Stylistic_conventions">Stylistic conventions</a>
46<ul>
47<li>Formatting:
48    <a href="#Indentation">Indentation</a>,
49    <a href="#Spaces">Spaces</a>,
50    <a href="#Parentheses">Parentheses</a>
51<li><a href="#Preprocessor_style">Preprocessor</a>
52<li><a href="#Naming">Naming</a>
53<li><a href="#Types">Types</a>
54<li><a href="#Procedures_style">Procedures</a>,
55<li>Miscellany:
56    <a href="#Local_variables">Local variables</a>,
57    <a href="#Compiler_warnings">Compiler warnings</a>
58</ul>
59<li><a href="#File_structuring">File structuring and naming</a>
60<ul>
61<li><a href="#All_files">All files</a>
62<li><a href="#Makefiles">Makefiles</a>
63<li><a href="#General_C_code">General C Code</a>
64<li><a href="#Headers">Headers (<b><tt>.h</tt></b> files)</a>
65<li><a href="#Source">Source (<b><tt>.c</tt></b> files)</a>
66</ul>
67<li><a href="#Conventions">Ghostscript conventions</a>
68<ul>
69<li><a href="#Specific_names">Specific names</a>:
70    <a href="#code"><b><tt>code</tt></b></a>,
71    <a href="#status"><b><tt>status</tt></b></a>
72<li><a href="#Structure_type_descriptors">Structure type descriptors</a>
73<li><a href="#Objects">"Objects"</a>
74<li><a href="#Error_handling">Error handling</a>
75</ul>
76</ul></blockquote>
77
78<!-- [1.2 end table of contents] =========================================== -->
79
80<!-- [1.3 begin hint] ====================================================== -->
81
82<p>
83For other information, see the <a href="Readme.htm">Ghostscript
84overview</a>.
85
86<!-- [1.3 end hint] ======================================================== -->
87
88<hr>
89
90<!-- [1.0 end visible header] ============================================== -->
91
92<!-- [2.0 begin contents] ================================================== -->
93
94<h2><a name="Introduction"></a>Introduction</h2>
95
96<p>
97This document describes Ghostscript's C coding conventions.  It is primarily
98<em>prescriptive</em>, documenting what developers should do when writing
99new code; the companion developer documentation (<a
100 href="Develop.htm">Develop.htm</a>) is primarily <em>descriptive</em>,
101documenting the way things are.
102
103<p>
104We encourage following the general language usage and stylistic rules for
105any code that will be integrated with Ghostscript, even if the code doesn't
106use Ghostscript's run-time facilities or have anything to do with
107PostScript, PDF, or page description languages.  Ghostscript itself follows
108some additional conventions; these are documented separately under "<a
109href="#Conventions">Ghostscript conventions</a>" below.
110
111<hr>
112
113<h2><a name="C_language"></a>C language do's and don'ts</h2>
114
115<p>
116There are several different versions of the C language, and even of the ANSI
117C standard.  Ghostscript versions through 7.0 were designed to compile on
118pre-ANSI compilers as well as on many compilers that implemented the ANSI
119standard with varying faithfulness.  Ghostscript versions since 7.0 do not
120cater for pre-ANSI compilers: they must conform to the ANSI 1989 standard
121(ANS X3.159-1989), with certain restrictions and a few conventional
122additions.
123
124<h3>Preprocessor</h3>
125
126<h4><a name="Conditionals"></a>Conditionals</h4>
127
128Restrictions:
129
130<ul>
131
132<li>Don't assume that <b><tt>#if</tt></b> will treat undefined names as 0.
133While the ANSI standard requires this, it may produce a warning.
134
135<li>In <b><tt>.c</tt></b> files, don't use preprocessor conditionals that
136test for individual platforms or compilers.  Use them only in header files
137named xxx<b><tt>_.h</tt></b>.
138
139</ul>
140
141<h4><a name="Macros"></a>Macros</h4>
142
143<p>
144Restrictions:
145
146<ul>
147
148<li>Don't redefine a macro, even with the same definition, without using
149<b><tt>#undef</tt></b>.
150
151<li><b><tt>CAPITALIZE</tt></b> macro names unless there is a good reason not
152to.
153
154<li>Even though the legacy code contains some macros which contain
155control flow statments, avoid the use of this in new code and do not
156create macros which contain hidden control flow, especially 'return'.
157The use of control flow in macros complicates debug significantly
158requiring tedious expansion of macros to build a module to be debugged
159or resorting to disassembly windows to set breakpoints or to trace
160flow.
161
162<li>Don't use a macro call within a macro argument if the call expands to a
163token sequence that includes any commas not within parentheses: this
164produces different results depending on whether the compiler expands the
165inner call before or after the argument is substituted into the macro body.
166(The ANSI standard says that calls must be expanded after substitution, but
167some compilers do it the other way.)
168
169<li>Don't use macro names, even inadvertently, in string constants.  Some
170compilers erroneously try to expand them.
171
172<li>Don't use macros to define shorthands for casted pointers.  For
173instance, avoid
174
175<blockquote><b><tt>
176#define fdev ((gx_device_fubar *)dev)
177</tt></b></blockquote>
178
179<p>
180and instead use
181
182<blockquote><b><tt>
183gx_device_fubar * const fdev = (gx_device_fubar *)dev;
184</tt></b></blockquote>
185
186<p>
187The use of <b><tt>const</tt></b> alerts the reader that this is effectively
188a synonym.
189
190<li>If a macro generates anything larger than a single expression (that is,
191one or more statements), surround it with <b><tt>BEGIN</tt></b> and
192<b><tt>END</tt></b>.  These work around the fact that simple statements and
193compound statements in C can't be substituted for each other syntactically.
194
195<li>If a macro introduces local variables, only use names that end with an
196underscore (<b><tt>_</tt></b>), such as <b><tt>code_</tt></b>.  This avoids
197clashes both with ordinary variable names (which should never end with an
198underscore) and with system-defined names (which may begin with an
199underscore).
200
201</ul>
202
203<h3><a name="Preprocessor_other"></a>Other</h3>
204
205<p>
206Restrictions:
207
208<ul>
209
210<li>Only use <b><tt>#pragma</tt></b> in files that are explicitly identified
211as being platform-dependent.  Many compilers complain if this is used at
212all, and some complain if they don't recognize the specific pragma being
213requested (both incorrect according to the ANSI standard).
214
215</ul>
216
217<h3><a name="Lexical_elements"></a>Lexical elements</h3>
218
219<p>
220Do not use:
221
222<ul>
223
224<li>ANSI trigraphs (??x)
225<li>Nested comments (/* /* */ */) (not ANSI compliant, but often accepted)
226<li>Multi-character character constants ('abc')
227<li>Wide-character character or string constants (L'x', L"x")
228
229</ul>
230
231<p>
232Restrictions:
233
234<ul>
235
236<li>Procedure and static variable names must be 31 characters or less.
237
238<li>Externally visible procedure and variable names must be unique in the
239first 23 characters.
240
241</ul>
242
243<h3><a name="Scoping"></a>Scoping (extern, static, ...)</h3>
244
245<p>
246Do not use:
247
248<ul>
249
250<li><b><tt>register</tt></b>
251
252</ul>
253
254<p>
255Restrictions:
256
257<ul>
258
259<li>Do not allow a global variable (constant) to have more than one
260non-<b><tt>extern</tt></b> definition, even though some ANSI C compilers
261allow this.  Every global constant should have exactly one definition, in a
262<b><tt>.c</tt></b> file, and preferably just one <b><tt>extern</tt></b>
263declaration, in a header file.
264
265<li>Use <b><tt>private</tt></b> instead of <b><tt>static</tt></b> for
266procedures and variables declared at the outermost scope of a file.  This
267allows making such constructs either visible or invisible to profilers by
268changing a single <b><tt>#define</tt></b>.
269
270<li><b><tt>static</tt></b> or <b><tt>private</tt></b> variables must be
271<b><tt>const</tt></b> and initialized: non-<b><tt>const</tt></b> statically
272allocated variables are incompatible with reentrancy, and we're in the
273process of eliminating all of them.
274
275<li>Do not use <b><tt>extern</tt></b> in <b><tt>.c</tt></b> files, only in
276<b><tt>.h</tt></b> files, unless you have a very good reason for it (e.g.,
277as in <a href="../src/iconf.c">iconf.c</a>).  There are too many such
278<b><tt>extern</tt></b>s in the code now: we are eliminating them over time.
279
280<li>Do not declare the same name as both <b><tt>static</tt></b>
281(<b><tt>private</tt></b>) and non-<b><tt>static</tt></b> within the same
282compilation.  (Some compilers complain, some do not.)  This is especially a
283problem for procedures: it is easy to declare a procedure as
284<b><tt>private</tt></b> near the beginning of a file and accidentally not
285declare it <b><tt>private</tt></b> where it is defined later in the file.
286
287<li>Even though the ANSI standard allows initialized external declarations
288(<b><tt>extern&nbsp;int&nbsp;x&nbsp;=&nbsp;0</tt></b>), don't use them.
289
290</ul>
291
292<h3><a name="Scalars"></a>Scalars</h3>
293
294<p>
295Restrictions:
296
297<ul>
298
299<li>Avoid using <b><tt>char</tt></b>, except for <b><tt>char&nbsp;*</tt></b>
300for a pointer to a string.  Don't assume that <b><tt>char</tt></b> is
301signed; also don't assume it is unsigned.
302
303<li>Never cast a <b><tt>float</tt></b> to a <b><tt>double</tt></b>
304explicitly.  ANSI compilers in their default mode do all floating point
305computations in double precision, and handle such casts automatically.
306
307<li>Don't use <b><tt>long long</tt></b>: even though it is in the ANSI
308standard, not all compilers support it.  Use <b><tt>bits64</tt></b> instead
309(see below under "<a href="#Language_extensions">Language extensions</a>").
310
311<li>Don't assume anything about whether <b><tt>sizeof(long)</tt></b> is less
312than, equal to, or greater than <b><tt>sizeof(ptr)</tt></b>.  (However, you
313can make such comparisons in preprocessor conditionals using
314<b><tt>ARCH_SIZEOF_LONG</tt></b> and <b><tt>ARCH_SIZEOF_PTR</tt></b>.)
315
316</ul>
317
318<h3><a name="Arrays"></a>Arrays</h3>
319
320<p>
321Restrictions:
322
323<ul>
324
325<li>Don't declare arrays of size 0.  (The newer ANSI standard allows this,
326but the older one doesn't.)
327
328<li>Don't declare an array of size 1 at the end of a structure to indicate
329that a variable-size array follows.
330
331<li>Don't declare initialized <b><tt>auto</tt></b> arrays.
332
333</ul>
334
335<h3><a name="Typedefs"></a>Typedefs</h3>
336
337<p>
338Restrictions:
339
340<ul>
341
342<li>Don't use <b><tt>typedef</tt></b> for function types, such as
343
344<blockquote>
345<b><tt>typedef int proc_xyz_t(double, int *);</tt></b>
346</blockquote>
347
348<p>Many compilers don't handle this correctly -- they will give errors, or
349do the wrong thing, when declaring variables of type
350<b><tt>proc_xyz_t</tt></b> and/or <b><tt>proc_xyz_t *</tt></b>.  Instead, do
351this:
352
353<blockquote>
354<b><tt>#define PROC_XYZ(proc) int proc(double, int *)<br>
355PROC_XYZ(some_proc);  /* declare a procedure of this type */<br>
356typedef PROC_XYZ((*proc_xyz_ptr_t));  /* define a type for procedure ptrs */<br>
357<br>
358proc_xyz_ptr_t pp;  /* pointer to procedure */</tt></b>
359</blockquote>
360
361<li>Don't redefine <b><tt>typedef</tt></b>'ed names, even with the same
362definition.  Some compilers complain about this, and the standard doesn't
363allow it.
364
365</ul>
366
367<h3><a name="Structures"></a>Structures</h3>
368
369<p>
370Restrictions:
371
372<ul>
373
374<li>Don't use anonymous structures if you can possibly avoid it, except
375occasionally as components of other structures. Ideally, use the
376<b><tt>struct</tt></b> keyword only for declaring named structure types,
377like this:
378
379<blockquote>
380<b><tt>typedef struct xxx_s {</tt></b><br>
381&nbsp;&nbsp;&nbsp;... members ...<br>
382<b><tt>} xxx_t;</tt></b>
383</blockquote>
384
385<li>Use <b><tt>struct</tt></b> only when declaring structure types, never
386for referring to them (e.g., never declare a variable as type
387<b><tt>struct&nbsp;xxx_s&nbsp;*</tt></b>).
388
389<li>Don't assume that the compiler will (or won't) insert padding in
390structures to align members for best performance.  To preserve alignment,
391only declare structure members that are narrower than an <b><tt>int</tt></b>
392if there will be a lot of instances of that structure in memory.  For such
393structures, insert <b><tt>byte</tt></b> and/or <b><tt>short</tt></b> padding
394members as necessary to re-establish <b><tt>int</tt></b> alignment.
395
396<li>Don't declare initialized <b><tt>auto</tt></b> structures.
397
398</ul>
399
400<h3><a name="Unions"></a>Unions</h3>
401
402<p>
403Restrictions:
404
405<ul>
406
407<li>Use unions only as components of structures, not as typedefs in their
408own right.
409
410<li>Don't attempt to initialize unions: not all compilers support this, even
411though it is in the 1989 ANSI standard.
412
413</ul>
414
415<h3><a name="Expressions"></a>Expressions</h3>
416
417<p>
418Restrictions:
419
420<ul>
421
422<li>Don't assign a larger integer data type to a smaller one without a cast
423(<b><tt>int_x&nbsp;=&nbsp;long_y</tt></b>).
424
425<li>It's OK to use the address of a structure or array element
426(<b><tt>&p->e</tt></b>, <b><tt>&a[i]</tt></b>) locally, or pass it to a
427procedure that won't store it, but don't store such an address in allocated
428storage unless you're very sure of what you're doing.
429
430<li>Don't use conditional expressions with structure or union values.
431(Pointers to structures or unions are OK.)
432
433<li>For calling a variable or parameter procedure, use
434<b><tt>ptr-&gt;func(...)</tt></b>.  Some old code uses explicit indirection,
435<b><tt>(*ptr-&gt;func)(...)</tt></b>: don't use this in new code.
436
437<li>Don't write expressions that depend on order of evaluation, unless the
438order is created explicitly by use of <b><tt>||</tt></b>,
439<b><tt>&amp;&amp;</tt></b>, <b><tt>?:</tt></b>, <b><tt>,</tt></b>, or
440function nesting (the arguments of a function must be evaluated before the
441function is called).  In particular, don't assume that the arguments of a
442function will be evaluated left-to-right, or that the left side of an
443assignment will be evaluated before the right.
444
445<li>Don't mix integer and enumerated types ad lib: treat enumerated types as
446distinct from integer types, and use casts to convert between the two.
447(Some compilers generate warnings if you do not do this.)
448
449</ul>
450
451<h3><a name="Statements"></a>Statements</h3>
452
453<p>
454Restrictions:
455
456<ul>
457
458<li>If you use an expression as a statement, other than an assignment or a
459function call with <b><tt>void</tt></b> return value, enclose it explicitly
460in <b><tt>DISCARD()</tt></b>.
461
462<li>The type of the operand of a <b><tt>switch</tt></b> must match the type
463of the case labels, whether the labels are <b><tt>int</tt></b>s or the
464members of an <b><tt>enum</tt></b> type.  (Use a cast if necessary.)
465
466<li>It is OK for one case of a switch to "fall through" into another (i.e.,
467for the statement just before a case label not to be a control transfer),
468but a comment <b><tt>/*&nbsp;falls&nbsp;through&nbsp;*/</tt></b> is
469required.
470
471<li>If you are returning an error code specified explicitly (e.g.,
472<b><tt>return&nbsp;gs_error_rangecheck</tt></b> or
473<b><tt>return&nbsp;e_rangecheck</tt></b>), use
474<b><tt>return_error()</tt></b> rather than plain <b><tt>return</tt></b>.
475However, if the program is simply propagating an error code generated
476elsewhere, as opposed to generating the error, use <b><tt>return</tt></b>
477(e.g., <b><tt>if&nbsp;(code&nbsp;<&nbsp;0)&nbsp;return&nbsp;code</tt></b>).
478
479</ul>
480
481<h3><a name="Procedures"></a>Procedures</h3>
482
483<p>
484Restrictions:
485
486<ul>
487
488<li>Provide a prototype for every procedure, and make sure the prototype is
489available at every call site.  If the procedure is local to a file
490(<b><tt>private</tt></b>), the prototype should precede the procedure, in
491the same file; if the procedure is global, the prototype should be in a
492header file.
493
494<li>If a procedure parameter is itself a procedure, do list its parameter
495types rather than just using <b><tt>()</tt></b>.  For example,
496
497<blockquote><b><tt>
498int foo(int (*callback)(int, int));
499</tt></b></blockquote>
500
501<p>
502rather than just
503
504<blockquote><b><tt>
505int foo(int (*callback)());
506</tt></b></blockquote>
507
508<li>Don't use the <b><tt>P</tt></b>* macros in new code.  (See the
509Procedures section of <a href="#Language_extensions">Language extensions</a>
510below for more information.)
511
512<li>Always provide an explicit return type for procedures, in both the
513prototype and the definition: don't rely on the implicit declaration as
514<b><tt>int</tt></b>.
515
516<li>Don't use <b><tt>float</tt></b> as the return type of a procedure,
517unless there's a special reason.  Floating point hardware typically does
518everything in double precision internally and has to do extra work to
519convert between double and single precision.
520
521<li>Don't declare parameters as being of type <b><tt>float</tt></b>,
522<b><tt>short</tt></b>, or <b><tt>char</tt></b>.  If you do this and forget
523to include the prototype at a call site, ANSI compilers will generate
524incompatible calling sequences.  Use <b><tt>floatp</tt></b> (a synonym for
525<b><tt>double</tt></b>, mnemonic for "float parameter") instead of
526<b><tt>float</tt></b>, and use <b><tt>int</tt></b> or <b><tt>uint</tt></b>
527instead of <b><tt>short</tt></b> or <b><tt>char</tt></b>.
528
529</ul>
530
531<h3><a name="Standard_library"></a>Standard library</h3>
532
533<p>
534Restrictions:
535
536<ul>
537
538<li>Only use library features that are documented in the established ANSI
539standard (e.g., Harbison & Steele's book).  Do not use procedures that are
540"standards" promulgated by Microsoft (e.g., <b><tt>stricmp</tt></b>), or
541originate in BSD Unix (e.g., <b><tt>strcasecmp</tt></b>), or were added in
542later versions of the standard such as C 9X.
543
544<li>Do not use any features from <b><tt>stdio.h</tt></b> that assume the
545existence of <b><tt>stdin</tt></b>, <b><tt>stdout</tt></b>, or
546<b><tt>stderr</tt></b>.  See <a href="../src/gsio.h">gsio.h</a> for the full
547list.  Instead, use <b><tt>gs_stdin</tt></b> et al.
548
549</ul>
550
551<hr>
552
553<h2><a name="Language_extensions"></a>Language extensions</h2>
554
555<h3>Scoping</h3>
556
557<dl>
558
559<dt><b><tt>inline</tt></b>
560
561<dd><b><tt>inline</tt></b> is available even if the compiler does not
562support it.  Be aware, however, that it may have no effect.  In particular,
563do not use <b><tt>inline</tt></b> in header files.  Instead, use the
564<b><tt>extern_inline</tt></b> facility described just below.
565
566<dt><b><tt>extern_inline</tt></b>
567
568<dd>Compilers that do support <b><tt>inline</tt></b> vary in how they decide
569whether to (also) compile a closed-code copy of the procedure.  Because of
570this, putting an <b><tt>inline</tt></b> procedure in a header file may
571produce multiple closed copies, causing duplicate name errors at link time.
572<b><tt>extern_inline</tt></b> provides a safe way to put
573<b><tt>inline</tt></b> procedures in header files, regardless of compiler.
574Unfortunately, the only way we've found to make this fully portable involves
575a fair amount of boilerplate.  For details, please see <a
576href="../src/stdpre.h">stdpre.h</a>.
577
578<dt><b><tt>private</tt></b>
579
580<dd><b>Use <tt>private</tt></b> instead of <b><tt>static</tt></b> for all
581file-local procedures, and also for file-local variables defined at the
582outermost level.  However, use <b><tt>static</tt></b>, not
583<b><tt>private</tt></b>, for variables defined within a procedure.
584
585<p>
586<b><tt>private</tt></b> is normally #define'd as <b><tt>static</tt></b>.
587However, it can also be #define'd as empty, which allows profilers to
588measure all procedures, and 'nm' to list all interesting statically
589allocated variables, not just public ones.
590
591</dl>
592
593<h3>Scalar types</h3>
594
595<dl>
596
597<dt><b><tt>bool, true, false</tt></b>
598
599<dd><b><tt>bool</tt></b> is intended as a Boolean type, with canonical
600values <b><tt>true</tt></b> and <b><tt>false</tt></b>.  In a more reasonable
601language, such as Java, <b><tt>bool</tt></b> is an enumerated type requiring
602an explicit cast to or from <b><tt>int</tt></b>; however, because C's
603conditionals are defined as producing <b><tt>int</tt></b> values, we can't
604even define <b><tt>bool</tt></b> as a C <b><tt>enum</tt></b> without
605provoking compiler warnings.
606
607<p>
608Even though <b><tt>bool</tt></b> is a synonym for <b><tt>int</tt></b>, treat
609them as conceptually different types:
610
611<ul>
612<li>Initialize or set <b><tt>bool</tt></b> variables to <b><tt>true</tt></b>
613or <b><tt>false</tt></b>, not 0 or 1.
614<li>Use the Boolean operators <b><tt>!</tt></b>, <b><tt>&&</tt></b>,
615and <b><tt>||</tt></b> only with Booleans.  Don't use the idiom
616<b><tt>!!x</tt></b> to create a Boolean that is true iff <b><tt>x</tt></b>
617!= 0: use <b><tt>x != 0</tt></b>.
618<li>Use an explicit <b><tt>(int)</tt></b> cast to convert a Boolean to an
619integer.
620</ul>
621
622<dt><b><tt>byte, ushort, uint, ulong</tt></b>
623
624<dd>These types are simply shorthands for <b><tt>unsigned char, short, int,
625long</tt></b>.
626
627<p>
628In addition, the use of <b><tt>byte *</tt></b> indicates a
629Ghostscript-style string, with explicit length given separately, as
630opposed to a null terminated C-style string, which is <b><tt>char
631*</tt></b>.
632
633<dt><b><tt>floatp</tt></b>
634
635<dd>This is a synonym for <b><tt>double</tt></b>.  It should be used for,
636and only for, procedure parameters that would otherwise be
637<b><tt>float</tt></b>.  (As noted above, procedure parameters should not be
638declared as <b><tt>float</tt></b>.)
639
640<dt><b><tt>bits8, bits16, bits32</tt></b>
641
642<dd>These are unsigned integer types of the given width.  Use them wherever
643the actual width matters: do <em>not</em>, for example, use
644<b><tt>short</tt></b> assuming that it is 16 bits wide.
645
646<dt><b><tt>bits64</tt></b>
647
648<dd><strong>****** NOT IMPLEMENTED YET ******</strong>
649This is an unsigned 64-bit integer type, but it may not be available on all
650platforms.  Any code that uses this type should be surrounded by
651<b><tt>#if&nbsp;ARCH_HAS_BITS64</tt></b>.
652
653</dl>
654
655<hr>
656
657<h2><a name="Stylistic_conventions"></a>Stylistic conventions</h2>
658
659<p>
660Ghostscript's coding rules cover not only the use of the language, but also
661many stylistic issues like the choice of names and the use of whitespace.
662The stylistic rules are meant to produce code that is easy to read.  It's
663important to observe them as much as possible in order to maintain a
664consistent style, but if you find these rules getting in your way or
665producing ugly-looking results once in a while, it's OK to break it.
666
667<h3><a name="Formatting"></a>Formatting</h3>
668
669<h4><a name="Indentation"></a>Indentation</h4>
670
671<p>
672We've formatted all of our code using the GNU <b><tt>indent</tt></b> program.
673
674<blockquote><b><tt>
675indent&nbsp;-bad&nbsp;-nbap&nbsp;-nsob&nbsp;-br&nbsp;-ce&nbsp;-cli4&nbsp;-npcs&nbsp;-ncs&nbsp;\<br>
676&nbsp;&nbsp;&nbsp;-i4&nbsp;-di0&nbsp;-psl&nbsp;-lp&nbsp;-lps&nbsp;somefile.c
677</tt></b></blockquote>
678
679<p>
680does a 98% accurate job of producing our preferred style.  Unfortunately,
681there are bugs in all versions of GNU <b><tt>indent</tt></b>, requiring
682both pre- and post-processing of the code.  The <b><tt>gsindent</tt></b>
683script in the Ghostscript fileset contains the necessary workarounds.
684
685<p>
686Put indentation points every 4 spaces, with 8 spaces = 1 tab stop.
687
688<p>
689Don't indent the initial <b><tt>#</tt></b> of preprocessor commands.
690However, for nested preprocessor commands, do use indentation between the
691<b><tt>#</tt></b> and the command itself.  Use 2 spaces per level of
692nesting, e.g.:
693
694<blockquote>
695<b><tt>#ifndef&nbsp;xyz</tt></b><br>
696<b><tt>#&nbsp;&nbsp;define&nbsp;xyz&nbsp;0</tt></b><br>
697<b><tt>#endif</tt></b>
698</blockquote>
699
700<p>
701For assignments (including chain assignments), put the entire statement on
702one line if it will fit; if not, break it after a <b><tt>=</tt></b> and
703indent all the following lines.  I.e., format like this:
704
705<blockquote>
706var1&nbsp;<b><tt>=</tt></b>&nbsp;value<b><tt>;</tt></b><br>
707var1&nbsp;<b><tt>=</tt></b>&nbsp;var2&nbsp;<b><tt>=</tt></b>&nbsp;value<b><tt>;</tt></b><br>
708var1&nbsp;<b><tt>=</tt></b><br>
709&nbsp;&nbsp;&nbsp;&nbsp;value<b><tt>;</tt></b><br>
710var1&nbsp;<b><tt>=</tt></b><br>
711&nbsp;&nbsp;&nbsp;&nbsp;var2&nbsp;<b><tt>=</tt></b>&nbsp;value<b><tt>;</tt></b><br>
712var1&nbsp;<b><tt>=</tt></b>&nbsp;var2&nbsp;<b><tt>=</tt></b><br>
713&nbsp;&nbsp;&nbsp;&nbsp;value<b><tt>;</tt></b>
714</blockquote>
715
716<p>
717But not like this:
718
719<blockquote>
720var1&nbsp;<b><tt>=</tt></b><br>
721var2&nbsp;<b><tt>=</tt></b> value<b><tt>;</tt></b>
722</blockquote>
723
724<p>
725Indent in-line blocks thus:
726
727<blockquote>
728<b><tt>{</tt></b><br>
729&nbsp;&nbsp;&nbsp;... declarations ...<br>
730&nbsp;&nbsp;&nbsp;{{ blank line if any declarations above }}<br>
731&nbsp;&nbsp;&nbsp;... statements ...<br>
732<b><tt>}</tt></b>
733</blockquote>
734
735<p>
736Similarly, indent procedures thus:
737
738<blockquote>
739return_type<br>
740proc_name(... arguments ...)<br>
741<b><tt>{</tt></b><br>
742&nbsp;&nbsp;&nbsp;... declarations ...<br>
743&nbsp;&nbsp;&nbsp;{{ blank line if any declarations above }}<br>
744&nbsp;&nbsp;&nbsp;... statements ...<br>
745<b><tt>}</tt></b>
746</blockquote>
747
748<p>
749If a control construct (<b><tt>if</tt></b>, <b><tt>do</tt></b>,
750<b><tt>while</tt></b>, or <b><tt>for</tt></b>) has a one-line body, use
751this:
752
753<blockquote>
754... control construct ...<br>
755&nbsp;&nbsp;&nbsp;... subordinate simple statement ...
756</blockquote>
757
758<p>
759If it has a multi-line body, use this:
760
761<blockquote>
762... control construct ... <b><tt>{</tt></b><br>
763&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
764<b><tt>}</tt></b>
765</blockquote>
766
767<p>
768If the subordinate code has declarations, see blocks above.
769
770<p>
771For if-else statements, do this:
772
773<blockquote>
774<b><tt>if (</tt></b> ...<b><tt> ) {</tt></b><br>
775&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
776<b><tt>} else if (</tt></b> ...<b><tt> ) {</tt></b><br>
777&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
778<b><tt>} else {</tt></b><br>
779&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
780<b><tt>}</tt></b>
781</blockquote>
782
783<p>
784When there are more than two alternatives, as in the example above, use the
785above ("parallel") syntax rather than the following ("nested") syntax:
786
787<blockquote>
788<b><tt>if (</tt></b> ...<b><tt> ) {</tt></b><br>
789&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
790<b><tt>} else {</tt></b><br>
791<b><tt>&nbsp;&nbsp;&nbsp;if (</tt></b> ...<b><tt> ) {</tt></b><br>
792&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
793<b><tt>&nbsp;&nbsp;&nbsp;} else {</tt></b><br>
794&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;... subordinate code ...<br>
795<b><tt>&nbsp;&nbsp;&nbsp;}</tt></b><br>
796<b><tt>}</tt></b>
797</blockquote>
798
799<p>
800Similarly, for do-while statements, do this:
801
802<blockquote>
803<b><tt>do {</tt></b><br>
804&nbsp;&nbsp;&nbsp;... body ...<br>
805<b><tt>} while (</tt></b> ... condition ... <b><tt>);</tt></b>
806</blockquote>
807
808<h4><a name="Spaces"></a>Spaces</h4>
809
810<p>
811Do put a space:
812<ul>
813<li>after every comma and semicolon, unless it ends a line;
814<li>around every binary operator other than "<b><tt>-&gt;</tt></b>" and
815"<b><tt>.</tt></b>", although you can omit the spaces around the innermost
816operator in a nested expression if you like;
817<li>on both sides of the parentheses of an <b><tt>if</tt></b>, <b><tt>for</tt></b>, or <b><tt>while</tt></b>.
818</ul>
819
820<p>
821Don't put a space:
822<ul>
823<li>at the end of a line;
824<li>before a comma or semicolon;
825<li>after unary prefix operators;
826<li>before the parenthesis of a macro or procedure call.
827</ul>
828
829<h4><a name="Parentheses"></a>Parentheses</h4>
830
831<p>
832Parentheses are important in only a few places:
833
834<ul>
835<li>Around the inner subexpressions in expressions that mix
836<b><tt>&amp;&amp;</tt></b> and <b><tt>||</tt></b>, even if they are not
837required by precedence, for example
838
839<blockquote><b><tt>
840(xx &amp;&amp; yy) || zz
841</tt></b></blockquote>
842
843<li>Similarly around inner subexpressions in expressions that mix
844<b><tt>&amp;</tt></b>, <b><tt>|</tt></b>, or shifts, especially if mixing
845these with other operators, for instance
846
847<blockquote><b><tt>
848(x &lt;&lt; 3) | (y &gt;&gt; 5)
849</tt></b></blockquote>
850
851<li>In macro definitions around every use of an argument that logically
852could be an expression, for example
853
854<blockquote><b><tt>
855((x) * (x) + (y) * (y))
856</tt></b></blockquote>
857
858</ul>
859
860<p>
861Anywhere else, given the choice, use fewer parentheses.
862
863<p>
864For stylistic consistency with the existing Ghostscript code, put
865parentheses around conditional expressions even if they aren't
866syntactically required, unless you really dislike doing this.  Note that
867the parentheses should go around the entire expression, not the condition.
868For instance, instead of
869
870<blockquote><b><tt>
871hpgl_add_point_to_path(pgls, arccoord_x, arccoord_y,<br>
872&nbsp;&nbsp;&nbsp;(pgls-&gt;g.pen_down) ? gs_lineto : gs_moveto);
873</tt></b></blockquote>
874
875<p>
876use
877
878<blockquote><b><tt>
879hpgl_add_point_to_path(pgls, arccoord_x, arccoord_y,<br>
880&nbsp;&nbsp;&nbsp;(pgls-&gt;g.pen_down ? gs_lineto : gs_moveto));
881</tt></b></blockquote>
882
883<h3><a name="Preprocessor_style"></a>Preprocessor</h3>
884
885<h4>Conditionals</h4>
886
887<p>
888Using preprocessor conditionals can easily lead to unreadable code, since
889the eye really wants to read linearly rather than having to parse the
890conditionals just to figure out what code is relevant.  It's OK to use
891conditionals that have small scope and that don't change the structure or
892logic of the program (typically, they select between different sets of
893values depending on some configuration parameter), but where possible, break
894up source modules rather than use conditionals that affect the structure or
895logic.
896
897<h4>Macros</h4>
898
899<p>
900Ghostscript code uses macros heavily to effectively extend the rather
901weak abstraction capabilities of the C language, specifically in the area of
902memory management and garbage collection: in order to read Ghostscript code
903effectively, you simply have to learn some of these macros as though they
904were part of the language.  The current code also uses macros heavily for
905other purposes, but we are trying to phase these out as rapidly as possible,
906because they make the code harder to read and debug, and to use the
907rules that follow consistently in new code.
908
909<p>
910Define macros in the smallest scope you can manage (procedure, file, or
911<b><tt>.h</tt></b> file), and <b><tt>#undef</tt></b> them at the end of
912that scope: that way, someone reading the code can see the definitions
913easily when reading the uses.  If that isn't appropriate, define them in as
914large a scope as possible, so that they effectively become part of the
915language.  This places an additional burden on the reader, but it can be
916amortized over reading larger amounts of code.
917
918<p>
919Try hard to use procedures instead of macros.  Use "<b><tt>inline</tt></b>"
920if you really think the extra speed is needed, but only within a
921<b><tt>.c</tt></b> file: don't put inline procedures in <b><tt>.h</tt></b>
922files, because most compilers don't honor "<b><tt>inline</tt></b>" and
923you'll wind up with a copy of the procedure in every <b><tt>.c</tt></b>
924file that includes the <b><tt>.h</tt></b> file.
925
926<p>
927If you define a macro that looks like a procedure, make sure it will work
928wherever a procedure will work.  In particular, put parentheses around every
929use of an argument within the macro body, so that the macro will parse
930correctly if some of the arguments are expressions, and put parentheses
931around the entire macro body.  (This is still subject to the problem that an
932argument may be evaluated more than once, but there is no way around this in
933C, since C doesn't provide for local variables within expressions.)
934
935<p>
936If you define macros for special loop control structures, make their uses
937look somewhat like ordinary loops, for instance:
938
939<blockquote>
940<b><tt>BEGIN_RECT(xx, yy) {</tt></b><br>
941&nbsp;&nbsp;... body indented one position ...<br>
942<b><tt>} END_RECT(xx, yy);</tt></b>
943</blockquote>
944
945<p>
946If at all possible, don't use free variables in macros -- that is, variables
947that aren't apparent as arguments of the macro.  If you must use free
948variables, list them all in a comment at the point where the macro is
949defined.
950
951<p>
952If you define new macros or groups of macros, especially if they aren't
953simply inline procedures or named constant values, put some extra effort
954into documenting them, to compensate for the fact that macros are
955intrinsically harder to understand than procedures.
956
957<h3><a name="Comments"></a>Comments</h3>
958
959<p>
960The most important descriptive comments are ones in header files that
961describe structures, including invariants; but every procedure or structure
962declaration, or group of other declarations, should have a comment.  Don't
963spend a lot of time commenting executable code unless something unusual or
964subtle is going on.
965
966<h3><a name="Naming"></a>Naming</h3>
967
968<p>
969Use fully spelled-out English words in names, rather than contractions.
970This is most important for procedure and macro names, global variables and
971constants, values of <b><tt>#define</tt></b> and <b><tt>enum</tt></b>,
972<b><tt>struct</tt></b> and other <b><tt>typedef</tt></b> names, and
973structure member names, and for argument and variable names which have
974uninformative types like <b><tt>int</tt></b>.  It's not very important for
975arguments or local variables of distinctive types, or for local index or
976count variables.
977
978<p>
979Avoid names that run English words together:
980"<b><tt>hpgl_compute_arc_center</tt></b>" is better than
981"<b><tt>hpgl_compute_arccenter</tt></b>".  However, for terms drawn from
982some predefined source, like the names of PostScript operators, use a term
983in its well-known form (for instance, <b><tt>gs_setlinewidth</tt></b>
984rather than <b><tt>gs_set_line_width</tt></b>).
985
986<p>
987Procedures, variables, and structures visible outside a single
988<b><tt>.c</tt></b> file should generally have prefixes that indicate what
989subsystem they belong to (in the case of Ghostscript, <b><tt>gs_</tt></b>
990or <b><tt>gx_</tt></b>).  This rule isn't followed very consistently.
991
992<h3><a name="Types"></a>Types</h3>
993
994<p>
995Many older structure names don't have <b><tt>_t</tt></b> on the end, but
996this suffix should be used in all new code.  (The <b><tt>_s</tt></b>
997structure name is needed only to satisfy some debuggers.  No code other than
998the structure declaration should refer to it.)
999
1000<p>
1001Declare structure types that contain pointers to other instances of
1002themselves like this:
1003
1004<blockquote>
1005<b><tt>typedef struct xxx_s xxx_t;</tt></b><br>
1006<b><tt>struct xxx_s {</tt></b><br>
1007&nbsp;&nbsp;&nbsp;... members ...<br>
1008&nbsp;&nbsp;&nbsp;<b><tt>xxx_t *</tt></b>ptr_member_name;<br>
1009&nbsp;&nbsp;&nbsp;... members ...<br>
1010<b><tt>};</tt></b>
1011</blockquote>
1012
1013<p>
1014If, to maintain data abstraction and avoid including otherwise unnecessary
1015header files, you find that you want the type <b><tt>xxx_t</tt></b> to be
1016available in a header file that doesn't include the definition of the
1017structure <b><tt>xxx_s</tt></b>, use this approach:
1018
1019<blockquote>
1020<b><tt>#ifndef xxx_DEFINED</tt></b><br>
1021<b><tt>#&nbsp;&nbsp;define xxx_DEFINED</tt></b><br>
1022<b><tt>typedef struct xxx_s xxx_t;</tt></b><br>
1023<b><tt>#endif</tt></b><br>
1024<b><tt>struct xxx_s {</tt></b><br>
1025&nbsp;&nbsp;&nbsp;... members ...<br>
1026<b><tt>};</tt></b>
1027</blockquote>
1028
1029<p>
1030You can then copy the first 4 lines in other header files.  (Don't ever
1031include them in an executable code file.)
1032
1033<p>
1034Don't bother using <b><tt>const</tt></b> for anything other than with
1035pointers as described below.  However, in those places where it is necessary
1036to cast a pointer of type <b><tt>const&nbsp;T&nbsp;*</tt></b> to type
1037<b><tt>T&nbsp;*</tt></b>, always include a comment that explains why you are
1038"breaking const".
1039
1040<h4>Pointers</h4>
1041
1042<p>
1043Use <b><tt>const</tt></b> for pointer referents (that is,
1044<b><tt>const&nbsp;T&nbsp;*</tt></b>) wherever possible and appropriate.
1045
1046<p>
1047If you find yourself wanting to use <b><tt>void&nbsp;*</tt></b>, try to
1048find an alternative using unions or (in the case of super- and subclasses)
1049casts, unless you're writing something like a memory manager that really
1050treats memory as opaque.
1051
1052<h3><a name="Procedures_style"></a>Procedures</h3>
1053
1054<p>
1055In general, don't create procedures that are private and only called from
1056one place.  However, if a compound statement (especially an arm of a
1057conditional) is too long for the eye easily to match its enclosing braces
1058"<b><tt>{...}</tt></b>" -- that is, longer than 10 or 15 lines -- and it
1059doesn't use or set a lot of state held in outer local variables, it may be
1060more readable if you put it in a procedure.
1061
1062<h3>Miscellany</h3>
1063
1064<h4><a name="Local_variables"></a>Local variables</h4>
1065
1066<p>
1067Don't assign new values to procedure parameters.  It makes debugging very
1068confusing when the parameter values printed for a procedure are not the
1069ones actually supplied by the caller.  Instead use a separate local
1070variable initialized to the value of the parameter.
1071
1072<p>
1073If a local variable is only assigned a value once, assign it that value at
1074its declaration, if possible.  For example,
1075
1076<blockquote>
1077<b><tt>int x = </tt></b>some expression <b><tt>;</tt></b>
1078</blockquote>
1079
1080<p>
1081rather than
1082
1083<blockquote>
1084<b><tt>int x;</tt></b><br>
1085...<br>
1086<b><tt>x = </tt></b> some expression <b><tt>;</tt></b>
1087</blockquote>
1088
1089<p>
1090Use a local pointer variable like this to "narrow" pointer types:
1091
1092<blockquote>
1093<b><tt>int</tt></b><br>
1094someproc(... <b><tt>gx_device *dev</tt></b> ...)<br>
1095<b><tt>{<br>
1096&nbsp;&nbsp;&nbsp;gx_device_printer *const pdev = (gx_device_printer *)dev;</tt></b><br>
1097&nbsp;&nbsp;&nbsp;...<br>
1098<b><tt>}</tt></b>
1099</blockquote>
1100
1101<p>
1102Don't "shadow" a local variable or procedure parameter with an inner local
1103variable of the same name.  I.e., don't do this:
1104
1105<blockquote>
1106<b><tt>int</tt></b><br>
1107someproc(... <b><tt>int x</tt></b> ...)<br>
1108<b><tt>{</tt></b><br>
1109&nbsp;&nbsp;&nbsp;...<br>
1110<b><tt>&nbsp;&nbsp;&nbsp;int x;</tt></b><br>
1111&nbsp;&nbsp;&nbsp;...<br>
1112<b><tt>}</tt></b>
1113</blockquote>
1114
1115<h4><a name="Compiler_warnings"></a>Compiler warnings</h4>
1116
1117<p>
1118The following section refers to the warnings produced by <b><tt>gcc</tt></b>:
1119your compiler may produce different ones.
1120
1121<p>
1122It's OK if compilation produces the following warnings:
1123
1124<ul>
1125<li><b><tt>&lt;name&gt; might be used uninitialized in this function</tt></b>
1126<li><b><tt>cast discards `const' from pointer target type</tt></b>
1127</ul>
1128
1129<p>
1130The first of these often occurs because the compiler isn't aware of control
1131flow restrictions that guarantee the variable will be initialized before
1132use: if it occurs in new code, check the code carefully, but don't worry
1133about the message.  The second is often unavoidable in code that initializes
1134or frees a structure that is otherwise <b><tt>const</tt></b> during its
1135lifetime.
1136<p>
1137
1138Do work hard to eliminate all warnings other than these,
1139since they often indicate the possible presence of coding errors.
1140In particular, get rid of warnings about parameter passing or
1141initialization that discards <b><tt>const</tt></b>,
1142by using explicit casts.
1143
1144<hr>
1145
1146<h2><a name="File_structuring"></a>File structuring</h2>
1147
1148<h3><a name="All_files"></a>All files</h3>
1149
1150<p>
1151Keep file names within the "8.3" format for portability:
1152<ul>
1153<li>Use only letters, digits, dash, and underscore in file names.
1154<li>Don't assume upper and lower case letters are distinct.
1155<li>Put no more than 8 characters before the ".", if any.
1156<li>If there is a ".", put between 1 and 3 characters after the ".".
1157</ul>
1158
1159<p>
1160For files other than documentation files, use only lower case letters
1161in the names; for HTML documentation files, capitalize the first letter.
1162
1163<p>
1164Every code file should start with comments containing
1165
1166<ol>
1167<li>a copyright notice,
1168<li>the name of the file in the form of an RCS Id:
1169
1170<blockquote><b><tt>
1171/* $<!-- -->Id: filename.ext $*/
1172</tt></b></blockquote>
1173
1174<p>
1175(using the comment convention appropriate to the language of the file), and
1176
1177<li>a summary, no more than one line, of what the file contains.
1178</ol>
1179
1180<p>
1181If you create a file by copying the beginning of another file, be sure to
1182update the copyright year and change the file name.
1183
1184<h3><a name="Makefiles"></a>Makefiles</h3>
1185
1186<p>
1187Use the extension <b><tt>.mak</tt></b> for makefiles.
1188
1189<p>
1190For each
1191
1192<blockquote><b><tt>
1193#include "xxx.h"
1194</tt></b></blockquote>
1195
1196<p>
1197make sure there is a dependency on <b><tt>$(xxx_h)</tt></b> in the
1198makefile.  If xxx ends with a "<b><tt>_</tt></b>", this rule still holds,
1199so that if you code
1200
1201<blockquote><b><tt>
1202#include "math_.h"
1203</tt></b></blockquote>
1204
1205<p>
1206the makefile must contain a dependency on "<b><tt>$(math__h)</tt></b>"
1207(note the two underscores "<b><tt>__</tt></b>").
1208
1209<p>
1210List the dependencies bottom-to-top, like the <b><tt>#include</tt></b>
1211statements themselves; within each level, list them alphabetically.  Do
1212this also with <b><tt>#include</tt></b> statements themselves whenever
1213possible (but sometimes there are inter-header dependencies that require
1214bending this rule).
1215
1216<p>
1217For compatibility with the build utilities on OpenVMS, always put a space
1218before the colon that separates the target(s) of a rule from the dependents.
1219
1220<h3><a name="General_C_code"></a>General C code</h3>
1221
1222<p>
1223List <b><tt>#include</tt></b> statements from "bottom" to "top", that is,
1224in the following order:
1225
1226<blockquote><ol>
1227<li>System includes (<b><tt>"xxx_.h"</tt></b>)
1228<li><b><tt>gs*.h</tt></b>
1229<li><b><tt>gx*.h</tt></b> (yes, <b><tt>gs</tt></b> and <b><tt>gx</tt></b>
1230are in the wrong order.)
1231<li><b><tt>s*.h</tt></b>
1232<li><b><tt>i*.h</tt></b> (or other interpreter headers that don't start
1233with "<b><tt>i</tt></b>")
1234</ol></blockquote>
1235
1236<h3><a name="Headers"></a>Headers (<b><tt>.h</tt></b> files)</h3>
1237
1238<p>
1239In header files, always use the following at the beginning of a header file
1240to prevent double inclusion:
1241
1242<blockquote>
1243{{ Copyright notice etc. }}<br><br>
1244
1245<b><tt>#ifndef </tt></b>&lt;filename&gt;<b><tt>_INCLUDED</tt></b><br>
1246<b><tt>#define </tt></b>&lt;filename&gt;<b><tt>_INCLUDED</tt></b><br><br>
1247
1248{{ The contents of the file }}<br><br>
1249
1250<b><tt>#endif /* </tt></b>&lt;filename&gt;<b><tt>_INCLUDED */</tt></b>
1251</blockquote>
1252
1253<p>
1254The header file is the first place that a reader goes for
1255information about procedures, structures, constants, etc., so ensure that
1256every procedure and structure has a comment that says what it does.  Divide
1257procedures into meaningful groups set off by some distinguished form of
1258comment.
1259
1260<h3><a name="Source"></a>Source (<b><tt>.c</tt></b> files)</h3>
1261
1262<p>
1263After the initial comments, arrange C files in the following order:
1264
1265<blockquote><ol>
1266<li><b><tt>#include</tt></b> statements
1267<li>Exported data declarations
1268<li>Explicit externs (if necessary)
1269<li>Forward declarations of procedures
1270<li>Private data declarations
1271<li>Exported procedures
1272<li>Private procedures
1273</ol></blockquote>
1274
1275<p>
1276Be flexible about the order of the declarations if necessary to improve
1277readability.  Many older files don't follow this order, often without good
1278reason.
1279
1280<hr>
1281
1282<h2><a name="Conventions"></a>Ghostscript conventions</h2>
1283
1284<h3><a name="Specific_names"></a>Specific names</h3>
1285
1286<p>
1287The Ghostscript code uses certain names consistently for certain kinds of
1288values.  Some of the commonest and least obvious are these two:
1289
1290<h4><a name="code"></a><b><tt>code</tt></b></h4>
1291
1292<blockquote>
1293A value to be returned from a procedure:
1294
1295<table cellpadding=0 cellspacing=0>
1296<tr valign=top>	<td align=right>&lt; 0
1297	<td>&nbsp;&nbsp;&nbsp;&nbsp;
1298	<td>An error code defined in
1299<a href="../src/gserrors.h">gserrors.h</a>
1300(or <a href="../src/ierrors.h">ierrors.h</a>)
1301<tr valign=top>	<td align=right>0
1302	<td>&nbsp;
1303	<td>Normal return
1304<tr valign=top>	<td align=right>&gt; 0
1305	<td>&nbsp;
1306	<td>A non-standard but successful return (which must be documented, preferably with the procedure's prototype)
1307</table>
1308
1309</blockquote>
1310
1311<h4><a name="status"></a><b><tt>status</tt></b></h4>
1312
1313<blockquote>
1314A value returned from a stream procedure:
1315
1316<table cellpadding=0 cellspacing=0>
1317<tr valign=top>	<td align=right>&lt; 0
1318	<td>&nbsp;&nbsp;&nbsp;&nbsp;
1319	<td>An exceptional condition as defined in
1320<a href="../src/scommon.h">scommon.h</a>
1321<tr valign=top>	<td align=right>0
1322	<td>&nbsp;
1323	<td>Normal return (or, from the "<b><tt>process</tt></b>" procedure, means that more input is needed)
1324<tr valign=top>	<td align=right>1
1325	<td>&nbsp;
1326	<td>More output space is needed (from the "<b><tt>process</tt></b>" procedure)
1327</table>
1328</blockquote>
1329
1330<h3><a name="Structure_type_descriptors"></a>Structure type descriptors</h3>
1331
1332<p>
1333The Ghostscript memory manager requires run-time type information for every
1334structure.  (We don't document this in detail here: see the <a
1335href="Develop.htm#Structure_descriptors">Structure descriptors</a> section
1336of the developer documentation for details.)  Putting the descriptor for a
1337structure next to the structure definition will help keep the two
1338consistent, so immediately after the definition of a structure
1339<b><tt>xxx_s</tt></b>, define its structure descriptor:
1340
1341<blockquote>
1342<b><tt>struct xxx_s {</tt></b><br>
1343&nbsp;&nbsp;&nbsp;... members ...<br>
1344<b><tt>};</tt></b><br>
1345<b><tt>#define private_st_xxx()&nbsp;&nbsp;/* in </tt></b>&lt;filename&gt;<tt><b>.c */\</tt></b><br>
1346<b><tt>&nbsp;&nbsp;gs_private_st_</tt></b>&lt;whatever&gt;<b><tt>(st_xxx, xxx_t,\</tt></b><br>
1347<b><tt>&nbsp;&nbsp;&nbsp;&nbsp;"xxx_t", xxx_enum_ptrs, xxx_reloc_ptrs,\</tt></b><br>
1348<b><tt>&nbsp;&nbsp;&nbsp;&nbsp;</tt></b>... additional parameters as needed ...<b><tt>)</tt></b>
1349</blockquote>
1350
1351<p>
1352The file that implements operations on this structure
1353(&lt;filename&gt;<b><tt>.c</tt></b>) should then include, near the
1354beginning, the line:
1355
1356<blockquote>
1357<b><tt>private_st_xxx();</tt></b>
1358</blockquote>
1359
1360<p>
1361In much existing code, structure descriptors are declared as
1362<b><tt>public</tt></b>, which allows clients to allocate instances of the
1363structure directly.  We now consider this bad design.  Instead, structure
1364descriptors should always be <b><tt>private</tt></b>; the implementation
1365file should provide one or more procedures for allocating instances, e.g.,
1366
1367<blockquote>
1368<b><tt>xxx_t *gs_xxx_alloc(P1(gs_memory_t *mem));</tt></b>
1369</blockquote>
1370
1371<p>
1372If it is necessary to make a structure descriptor public, it should be
1373declared in its clients as
1374
1375<blockquote>
1376<b><tt>extern_st(st_xxx);</tt></b>
1377</blockquote>
1378
1379<h3><a name="Objects"></a>"Objects"</h3>
1380
1381<p>
1382Ghostscript makes heavy use of object-oriented constructs, including
1383analogues of classes, instances, subclassing, and class-associated
1384procedures.  However, these constructs are implemented in C rather than C++,
1385for two reasons:
1386
1387<ul>
1388
1389<li>The first Ghostscript code was written in 1986, long before C++ was
1390codified or was well supported by tools.  Even today, C++ tools rarely
1391support C++ as well as C tools support C.
1392
1393<li>C++ imposes its own implementations for virtual procedures, inheritance,
1394run-time type information, and (to some extent) memory management.
1395Ghostscript requires use of its own memory manager, and also sometimes
1396requires the ability to change the virtual procedures of an object
1397dynamically.
1398
1399</ul>
1400
1401<h4>Classes</h4>
1402
1403<p>
1404The source code representation of a class is simply a
1405<b><tt>typedef</tt></b> for a C <b><tt>struct</tt></b>.  See <a
1406href="C-style.htm#Structures">Structures</a>, above, for details.
1407
1408<h4>Procedures</h4>
1409
1410<p>
1411Ghostscript has no special construct for non-virtual procedures associated
1412with a class.  In some cases, the <b><tt>typedef</tt></b> for the class is
1413in a header file but the <b><tt>struct</tt></b> declaration is in the
1414implementation code file: this provides an extra level of opaqueness, since
1415clients then can't see the representation and must make all accesses through
1416procedures.  You should use this approach in new code, if it doesn't
1417increase the size of the code too much or require procedure calls for very
1418heavily used accesses.
1419
1420<p>
1421Ghostscript uses three different approaches for storing and accessing
1422virtual procedures, plus a fourth one that is recommended but not currently
1423used.  For exposition, we assume the class (type) is named
1424<b><tt>xxx_t</tt></b>, it has a virtual procedure
1425<b><tt>void&nbsp;(*virtu)(P1(xxx_t&nbsp;*))</tt></b>, and we have a variable
1426declared as <b><tt>xxx_t&nbsp;*pxx</tt></b>.
1427
1428<ol>
1429
1430<li>The procedures are stored in a separate, constant structure of type
1431<b><tt>xxx_procs</tt></b>, of which <b><tt>virtu</tt></b> is a member.  The
1432structure definition of <b><tt>xxx_t</tt></b> includes a member defined as
1433<b><tt>const&nbsp;xxx_procs&nbsp;*procs</tt></b> (always named
1434<b><tt>procs</tt></b>).  The construct for calling the virtual procedure is
1435<b><tt>pxx->procs->virtu(pxx)</tt></b>.
1436
1437<li>The procedures are defined in a structure of type
1438<b><tt>xxx_procs</tt></b> as above.  The structure definition of
1439<b><tt>xxx_t</tt></b> includes a member defined as
1440<b><tt>xxx_procs&nbsp;procs</tt></b> (always named <b><tt>procs</tt></b>).
1441The construct for calling the virtual procedure is
1442<b><tt>pxx->procs.virtu(pxx)</tt></b>.
1443
1444<li>The procedures are not defined in a separate structure: each procedure
1445is a separate member of <b><tt>xxx_t</tt></b>.  The construct for calling
1446the virtual procedure is <b><tt>pxx->virtu(pxx)</tt></b>.
1447
1448<li>The procedures are defined in a structure of type
1449<b><tt>xxx_procs</tt></b> as above.  The structure definition of
1450<b><tt>xxx_t</tt></b> includes a member defined as
1451<b><tt>xxx_procs&nbsp;procs[1]</tt></b> (always named
1452<b><tt>procs</tt></b>).  The construct for calling the virtual procedure is
1453again <b><tt>pxx->procs->virtu(pxx)</tt></b>.
1454
1455</ol>
1456
1457<p>
1458Note that in approach 1, the procedures are in a shared constant structure;
1459in approaches 2 - 4, they are in a per-instance structure that can be
1460changed dynamically, which is sometimes important.
1461
1462<p>
1463In the present Ghostscript code, approach 1 is most common, followed by 2
1464and 3; 4 is not used at all.  For new code, you should use 1 or 4: that way,
1465all virtual procedure calls have the same form, regardless of whether the
1466procedures are shared and constant or per-instance and mutable.
1467
1468<h4>Subclassing</h4>
1469
1470<p>
1471Ghostscript's class mechanism allows for subclasses that can add data
1472members, or can add procedure members if approach 1 or 3 (above) is used.
1473Since C doesn't support subclassing, we use a convention to accomplish it.
1474In the example below, <b><tt>gx_device</tt></b> is the root class; it has a
1475subclass <b><tt>gx_device_forward</tt></b>, which in turn has a subclass
1476<b><tt>gx_device_null</tt></b>.  First we define a macro for all the members
1477of the root class, and the root class type.  (As for structures in general,
1478classes need a structure descriptor, as discussed in <a
1479href="#Structures">Structures</a> above: we include these in the examples
1480below.)
1481
1482<blockquote><b><tt>
1483#define gx_device_common\<br>
1484&nbsp;&nbsp;&nbsp;&nbsp;type1 member1;\<br>
1485&nbsp;&nbsp;&nbsp;&nbsp;</tt></b>...<b><tt><br>
1486&nbsp;&nbsp;&nbsp;&nbsp;typeN memberN<br>
1487<br>
1488typedef struct gx_device_s {<br>
1489&nbsp;&nbsp;&nbsp;&nbsp;gx_device_common;<br>
1490} gx_device;<br>
1491<br>
1492#define private_st_gx_device()&nbsp;&nbsp;/* in gsdevice.c */\<br>
1493&nbsp;&nbsp;gs_private_st_</tt></b>&lt;whatever&gt;<b><tt>(st_gx_device, gx_device,\<br>
1494&nbsp;&nbsp;&nbsp;&nbsp;"gx_device", device_enum_ptrs, device_reloc_ptrs,\<br>
1495&nbsp;&nbsp;&nbsp;&nbsp;</tt></b>... additional parameters as needed ...<b><tt>)</tt></b>
1496</tt></b></blockquote>
1497
1498<p>
1499We then define a similar macro and type for the subclass.
1500
1501<blockquote><b><tt>
1502#define gx_device_forward_common\<br>
1503&nbsp;&nbsp;&nbsp;&nbsp;gx_device_common;\<br>
1504&nbsp;&nbsp;&nbsp;&nbsp;gx_device *target<br>
1505<br>
1506typedef struct gx_device_forward_s {<br>
1507&nbsp;&nbsp;&nbsp;&nbsp;gx_device_forward_common;<br>
1508} gx_device_forward;<br>
1509<br>
1510#define private_st_device_forward()&nbsp;&nbsp;/* in gsdevice.c */\<br>
1511&nbsp;&nbsp;gs_private_st_suffix_add1(st_device_forward, gx_device_forward,\<br>
1512&nbsp;&nbsp;&nbsp;&nbsp;"gx_device_forward", device_forward_enum_ptrs, device_forward_reloc_ptrs,\<br>
1513&nbsp;&nbsp;&nbsp;&nbsp;gx_device, target)
1514</tt></b></blockquote>
1515
1516<p>
1517Finally, we define a leaf class, which doesn't need a macro because we don't
1518currently subclass it.  (We can create the macro later if needed, with no
1519changes anywhere else.)  In this particular case, the leaf class has no
1520additional data members, but it could have some.
1521
1522<blockquote><b><tt>
1523typedef struct gx_device_null_s {<br>
1524&nbsp;&nbsp;&nbsp;&nbsp;gx_device_forward_common;<br>
1525};<br>
1526<br>
1527#define private_st_device_null()&nbsp;&nbsp;/* in gsdevice.c */\<br>
1528&nbsp;&nbsp;gs_private_st_suffix_add0_local(st_device_null, gx_device_null,\<br>
1529&nbsp;&nbsp;&nbsp;&nbsp;"gx_device_null", device_null_enum_ptrs, device_null_reloc_ptrs,\<br>
1530&nbsp;&nbsp;&nbsp;&nbsp;gx_device_forward)
1531</tt></b></blockquote>
1532
1533<p>
1534Note that the above example is <strong>not</strong> the actual definition of
1535the <b><tt>gx_device</tt></b> structure type: the actual type has some
1536additional complications because it has a finalization procedure.  See <a
1537href="../src/gxdevcli.h">src/gxdevcli.h</a> for the details.
1538
1539<p>
1540If you add members to a root class (such as <b><tt>gx_device</tt></b> in
1541this example), or change existing members, do this in the
1542<b><tt>gx_device_common</tt></b> macro, not the <b><tt>gx_device</tt></b>
1543structure definition.  Similarly, to change the
1544<b><tt>gx_device_forward</tt></b> class, modify the
1545<b><tt>gx_device_forward_common</tt></b> macro, not the structure
1546definition.  Only change the structure definition if the class is a leaf
1547class (one with no <b><tt>_common</tt></b> macro and no possibility of
1548subclassing), like <b><tt>gx_device_null</tt></b>.
1549
1550<h3><a name="Error_handling"></a>Error handling</h3>
1551
1552<p>
1553Every caller should check for error returns and, in general, propagate them
1554to <b>its</b> callers.  By convention, nearly every procedure returns an
1555<b><tt>int</tt></b> to indicate the outcome of the call:
1556
1557<blockquote><table cellpadding=0 cellspacing=0>
1558<tr valign=top>	<td align=right>&lt; 0
1559	<td>&nbsp;&nbsp;&nbsp;&nbsp;
1560	<td>Error return
1561<tr valign=top>	<td align=right>0
1562	<td>&nbsp;
1563	<td>Normal return
1564<tr valign=top>	<td align=right>&gt; 0
1565	<td>&nbsp;
1566	<td>Non-error return other than the normal case
1567</table></blockquote>
1568
1569<p>
1570To make a procedure generate an error and return it, as opposed to
1571propagating an error generated by a lower procedure, you should use
1572
1573<blockquote>
1574<b><tt>return_error(</tt></b><em>error_number</em><b><tt>);</tt></b>
1575</blockquote>
1576
1577<p>
1578Sometimes it is more convenient to generate the error in one place and
1579return it in another.  In this case, you should use
1580
1581<blockquote>
1582<b><tt>code = gs_note_error(</tt></b><em>error_number</em><b><tt>);</tt></b><br>
1583...<br>
1584<b><tt>return code;</tt></b>
1585</blockquote>
1586
1587<p>
1588In executables built for debugging, the <b><tt>-E</tt></b> (or
1589<b><tt>-Z#</tt></b>) command line switch causes <b><tt>return_error</tt></b>
1590and <b><tt>gs_note_error</tt></b> to print the error number and the source
1591file and line: this is often helpful for identifying the original cause of
1592an error.
1593
1594<p>
1595See the file <a href="../src/gserrors.h">src/gserrors.h</a> for the error
1596return codes used by the graphics library, most of which correspond directly
1597to PostScript error conditions.
1598
1599<!-- [2.0 end contents] ==================================================== -->
1600
1601<!-- [3.0 begin visible trailer] =========================================== -->
1602<hr>
1603
1604<p>
1605<small>Copyright &copy; 1996, 1997, 1998 Aladdin Enterprises.
1606Copyright &copy; 2001 artofcode LLC.
1607All rights reserved.</small>
1608
1609<p>
1610<small>This file is part of AFPL Ghostscript.  See the <a
1611href="Public.htm">Aladdin Free Public License</a> (the "License") for full
1612details of the terms of using, copying, modifying, and redistributing AFPL
1613Ghostscript.</small>
1614
1615<p>
1616<small>Ghostscript version 8.53, 20 October 2005
1617
1618<!-- [3.0 end visible trailer] ============================================= -->
1619
1620</body>
1621</html>
1622