fix codetest failure - ASSERT_ARGS does not have a ; after and
[parrot.git] / docs / pdds / pdd07_codingstd.pod
blob8741a1b679b52ff5df683951146ed0942195fc14
1 # Copyright (C) 2001-2010, Parrot Foundation.
2 # $Id$
4 =head1 PDD 7: Conventions and Guidelines for Parrot Source Code
6 =head2 Version
8 $Revision$
10 =head2 Abstract
12 This document describes the various rules, guidelines and advice for those
13 wishing to contribute to the source code of Parrot, in such areas as code
14 structure, naming conventions, comments etc.
16 =head2 Synopsis
18 Not applicable.
20 =head2 Description
22 One of the criticisms of Perl 5 is that its source code is impenetrable to
23 newcomers, due to such things as inconsistent or obscure variable naming
24 conventions, lack of comments in the source code, and so on.  We don't intend
25 to make the same mistake when writing Parrot. Hence this document.
27 We define three classes of conventions:
29 =over 4
31 =item I<"must">
33 Items labelled I<must> are mandatory; and code will not be accepted (apart
34 from in exceptional circumstances) unless it obeys them.
36 =item I<"should">
38 Items labelled I<should> are strong guidelines that should normally be
39 followed unless there is a sensible reason to do otherwise.
41 =item I<"may">
43 Items labelled I<may> are tentative suggestions to be used at your discretion.
45 =back
47 Note that since Parrot is substantially implemented in C, these rules apply to
48 C language source code unless otherwise specified.
50 =head2 Implementation
53 =head3 Language Standards and Portability
55 =over 4
57 =item *
59 C code must generally depend on only those language and library features
60 specified by the ISO C89 standard.
62 In addition, C code may assume that any pointer value can be coerced to an
63 integral type (no smaller than typedef C<INTVAL> in Parrot), then back to its
64 original type, without loss.
66 Also C code may assume that there is a single NULL pointer representation
67 and that it consists of a number, usually 4 or 8, of '\0' chars in memory.
69 C code that makes assumptions beyond these must depend on the configuration
70 system, either to not compile an entire non-portable source where it will not
71 work, or to provide an appropriate #ifdef macro.
73 =item *
75 Perl code must be written for Perl 5.8.0 and all later versions.
77 Perl code may use features not available in Perl 5.8.0 only if it is not vital
78 to Parrot, and if it uses C<$^O> and C<$]> to degrade or fail gracefully when
79 it is run where the features it depends on are not available.
81 =back
84 =head3 Code Formatting
86 The following I<must> apply:
88 =over 4
90 =item *
92 Source line width is limited to 100 characters.  Exceptions can be made for
93 technical requirements, but not for style reasons.  And please bear in mind
94 that very long lines I<can> be hard to read.
96 =item *
98 Indentation must consist only of spaces.  (Tab characters just complicate
99 things.)
101 =item *
103 C and Perl code must be indented four columns per nesting level.
105 =item *
107 Preprocessor #directives must be indented two columns per nesting level, with
108 two exceptions: neither PARROT_IN_CORE nor the outermost _GUARD #ifdefs cause
109 the level of indenting to increase.
111 =item *
113 Labels (including case labels) must be outdented two columns relative to the
114 code they label.
116 =item *
118 Closing braces for control structures must line up vertically with the
119 start of the control structures; e.g. C<}> that closes an C<if> must
120 line up with the C<if>.
122 =item *
124 Long lines, when split, must use at least one extra level of indentation on
125 the continued line.
127 =item *
129 Cuddled C<else>s are forbidden: i.e. avoid  C<} else {> .
131 =item *
133 C macro parameters must be parenthesized in macro bodies, to allow expressions
134 passed as arguments; e.g.:
136     #define POBJ_FLAG(n) ((UINTVAL)1 << (n))
138 =back
141 The following I<should> apply:
143 =over 4
145 =item *
147 In function definitions, the function name must be on the left margin, with
148 the return type on the previous line.
150 =item *
152 In function declarations (e.g. in header files), the function name must be on
153 the same line as the return type.
155 =item *
157 Pointer types should be written with separation between the star and the base
158 type, e.g. C<Interp *foo>, but not C<Interp* foo>.
160 =item *
162 To distinguish keywords from function calls visually, there should be at least
163 one space between a C keyword and any subsequent open parenthesis, e.g.
164 C<return (x+y)*2>.  There should be no space between a function name and the
165 following open parenthesis, e.g. C<z = foo(x+y)*2>
167 =item *
169 Use patterns of formatting to indicate patterns of semantics.  Similar items
170 should look similar, as the language permits.  Note that some dimensions of
171 similarity are incidental, not worth emphasizing; e.g. "these are all ints".
173 =item *
175 Binary operators (except C<.> and C<< -> >>) should have at least one space on
176 either side; there should be no space between unary operators and their
177 operands; parentheses should not have space immediately after the opening
178 parenthesis nor immediately before the closing parenthesis; commas should have
179 at least one space after, but not before; e.g.:
181         x = (a-- + b) * f(c, d / e.f)
183 =item *
185 Use vertical alignment for clarity of parallelism.  Compare this (bad):
187      foo = 1 + 100;
188      x = 100 + 1;
189      whatever = 100 + 100;
191 ... to this (good):
193      foo      =   1 + 100;
194      x        = 100 +   1;
195      whatever = 100 + 100;
197 =item *
199 Do not routinely put single statements in statement blocks.
201 (Note that formatting consistency trumps this rule.  For example, a long
202 C<if>/C<else if> chain is easier to read if all (or none) of the conditional
203 code is in blocks.)
205 =item *
207 Return values should not be parenthesized without need.  It may be necessary
208 to parenthesize a long return expression so that a smart editor will properly
209 indent it.
211 =item *
213 When assigning inside a conditional, use extra parentheses,
214 e.g. C<if (a && (b = c)) ...> or C<if ((a = b)) ...>.
216 =item *
218 When splitting a long line at a binary operator (other than comma), the split
219 should be I<before> the operator, so that the continued line looks like one,
220 e.g.:
222     something_long_here = something_very_long + something_else_also_long
223             - something_which_also_could_be_long;
225 =item *
227 When splitting a long line inside parentheses (or brackets), the continuation
228 should be indented to the right of the innermost unclosed punctuation, e.g.:
230     z = foo(bar + baz(something_very_long_here
231                        * something_else_very_long),
232             corge);
234 =back
237 =head3 Code Structure
239 The following I<must> apply:
241 =over 4
243 =item *
245 C code must use C-style comments only, i.e. C</* comment */>.  (Not all C
246 compilers handle C++-style comments.)
248 =item *
250 Structure types must have tags.
252 =item *
254 Functions must have prototypes in scope at the point of use.  Prototypes for
255 extern functions must appear only in header files. If static functions are
256 defined before use, their definitions serve as prototypes.
258 =item *
260 Parameters in function prototypes must be named. These names should match the
261 parameters in the function definition.
263 =item *
265 Variable names must be included for all function parameters in the function
266 declarations.
268 =item *
270 Header files must be wrapped with guard macros to prevent header redefinition.
271 The guard macro must begin with C<PARROT_>, followed by unique and descriptive
272 text identifying the header file (usually the directory path and filename),
273 and end with a C<_GUARD> suffix.  The matching C<#endif> must have the guard
274 macro name in a comment, to prevent confusion.  For example, a file named
275 F<parrot/foo.h> might look like:
277     #ifndef PARROT_FOO_H_GUARD
278     #define PARROT_FOO_H_GUARD
280     #include "parrot/config.h"
281     #ifdef PARROT_HAS_FEATURE_FOO
282     #  define FOO_TYPE bar
283     typedef struct foo {
284         ...
285     } foo_t;
286     #endif /* PARROT_HAS_FEATURE_FOO */
288     #endif /* PARROT_FOO_H_GUARD */
290 =back
293 The following I<should> apply
295 =over 4
297 =item *
299 Structure types should have typedefs with the same name as their tags, e.g.:
301     typedef struct Foo {
302         ...
303     } Foo;
305 =item *
307 Avoid double negatives, e.g. C<#ifndef NO_FEATURE_FOO>.
309 =item *
311 Do not compare directly against NULL, 0, or FALSE.  Instead, write a boolean
312 test, e.g. C<if (!foo) ...>.
314 However, the sense of the expression being checked must be a boolean.
315 Specifically, C<strcmp()> and its brethren are three-state returns.
317     if ( !strcmp(x,y) )     # BAD, checks for if x and y match, but looks
318                             # like it is checking that they do NOT match.
319     if ( strcmp(x,y) == 0 ) # GOOD, checks proper return value
320     if ( STREQ(x,y) )       # GOOD, uses boolean wrapper macro
322 (Note: C<PMC *> values should be checked for nullity with the C<PMC_IS_NULL>
323 macro, unfortunately leading to violations of the double-negative rule.)
325 =item *
327 Avoid dependency on "FIXME" and "TODO" labels: use the external bug tracking
328 system.  If a bug must be fixed soon, use "XXX" B<and> put a ticket in the
329 bug tracking system.  This means that each "XXX" should have a Trac ticket
330 number next to it.
332 =back
335 =head3 Smart Editor Style Support
337 All developers using Emacs must ensure that their Emacs instances load the
338 elisp source file F<editor/parrot.el> before opening Parrot source files.
339 See L<editor/README.pod> for instructions.
341 All source files must end with an editor instruction coda:
343 =over 4
345 =item *
347 C source files, and files largely consisting of C (e.g. yacc, lex, PMC, and
348 opcode source files), must end with this coda:
350    /*
351     * Local variables:
352     *   c-file-style: "parrot"
353     * End:
354     * vim: expandtab shiftwidth=4:
355     */
357 =item *
359 Make source files must end with this coda:
361     # Local Variables:
362     #   mode: makefile
363     # End:
364     # vim: ft=make:
366 =item *
368 Perl source files must end with this coda:
370     # Local Variables:
371     #   mode: cperl
372     #   cperl-indent-level: 4
373     #   fill-column: 100
374     # End:
375     # vim: expandtab shiftwidth=4:
377 B<Exception>: Files with C<__END__> or C<__DATA__> blocks do not require the
378 coda.  This is at least until there is some consensus as to how solve the
379 issue of using editor hints in files with such blocks.
381 =item *
383 PIR source files should end with this coda:
385     # Local Variables:
386     #   mode: pir
387     #   fill-column: 100
388     # End:
389     # vim: expandtab shiftwidth=4 ft=pir:
391 =back
393 {{ XXX - Proper formatting and syntax coloring of C code under Emacs requires
394 that Emacs know about typedefs.  We should provide a simple script to update a
395 list of typedefs, and parrot.el should read it or contain it. }}
398 =head3 Portability
400 Parrot runs on many, many platforms, and will no doubt be ported to ever more
401 bizarre and obscure ones over time.  You should never assume an operating
402 system, processor architecture, endian-ness, size of standard type, or
403 anything else that varies from system to system.
405 Since most of Parrot's development uses GNU C, you might accidentally depend
406 on a GNU feature without noticing.  To avoid this, know what features of gcc
407 are GNU extensions, and use them only when they're protected by #ifdefs.
410 =head3 Defensive Programming
412 =head4 Use Parrot data structures instead of C strings and arrays
414 C arrays, including strings, are very sharp tools without safety guards, and
415 Parrot is a large program maintained by many people.  Therefore:
417 Don't use a C<char *> when a Parrot STRING would suffice.  Don't use a C array
418 when a Parrot array PMC would suffice.  If you do use a C<char *> or C array,
419 check and recheck your code for even the slightest possibility of buffer
420 overflow or memory leak.
422 Note that efficiency of some low-level operations may be a reason to break
423 this rule.  Be prepared to justify your choices to a jury of your peers.
425 =head4 Pass only C<unsigned char> to C<isxxx()> and C<toxxx()>
427 Pass only values in the range of C<unsigned char> (and the special value -1,
428 a.k.a. C<EOF>) to the isxxx() and toxxx() library functions.  Passing signed
429 characters to these functions is a very common error and leads to incorrect
430 behavior at best and crashes at worst.  And under most of the compilers Parrot
431 targets, C<char> I<is> signed.
433 =head4 The C<const> keyword on arguments
435 Use the C<const> keyword as often as possible on pointers.  It lets
436 the compiler know when you intend to modify the contents of something.
437 For example, take this definition:
439     int strlen(const char *p);
441 The C<const> qualifier tells the compiler that the argument will not be
442 modified.  The compiler can then tell you that this is an uninitialized
443 variable:
445     char *p;
446     int n = strlen(p);
448 Without the C<const>, the compiler has to assume that C<strlen()> is
449 actually initializing the contents of C<p>.
451 =head4 The C<const> keyword on variables
453 If you're declaring a temporary pointer, declare it C<const>, with the
454 const to the right of the C<*>, to indicate that the pointer should not
455 be modified.
457     Wango * const w = get_current_wango();
458     w->min  = 0;
459     w->max  = 14;
460     w->name = "Ted";
462 This prevents you from modifying C<w> inadvertently.
464     new_wango = w++; /* Error */
466 If you're not going to modify the target of the pointer, put a C<const>
467 to the left of the type, as in:
469     const Wango * const w = get_current_wango();
470     if (n < wango->min || n > wango->max) {
471         /* do something */
472     }
474 =head4 Localizing variables
476 Declare variables in the innermost scope possible.
478     if (foo) {
479         int i;
480         for (i = 0; i < n; i++)
481             do_something(i);
482     }
484 Don't reuse unrelated variables.  Localize as much as possible, even if
485 the variables happen to have the same names.
487     if (foo) {
488         int i;
489         for (i = 0; i < n; i++)
490             do_something(i);
491     }
492     else {
493         int i;
494         for (i = 14; i > 0; i--)
495             do_something_else(i * i);
496     }
498 You could hoist the C<int i;> outside the test, but then you'd have an
499 C<i> that's visible after it's used, which is confusing at best.
501 =head3 Subversion Properties
503 =head4 svn:ignore
505 Sometimes new files will be created in the configuration and build process of
506 Parrot. These files should not show up when checking the distribution with
508     svn status
512     perl tools/dev/manicheck.pl
514 The list of these ignore files can be set up with:
516     svn propedit svn:ignore <PATH>
518 In order to keep the two different checks synchronized,
519 the MANIFEST and MANIFEST.SKIP files should be regenerated with:
521     perl tools/dev/mk_manifest_and_skip.pl
523 and the files then committed to the Parrot svn repository.
525 =head4 svn:mime-type
527 The C<svn:mime-type> property must be set to C<text/plain> for all test
528 files, and may be set to C<text/plain> for other source code files in
529 the repository. Using I<auto-props>, Subversion can automatically set
530 this property for you on test files.  To enable this option, add the
531 following to your F<~/.subversion/config>:
533     [miscellany]
534     enable-auto-props = yes
535     [auto-props]
536     *.t = svn:mime-type=text/plain
538 The F<t/distro/file_metadata.t> test checks that the files needing
539 this property have it set.
541 =head4 svn:keywords
543 The C<svn:keywords> property should be set to:
545     Author Date Id Revision
547 on each file with a mime-type of C<text/plain>.  Do this with the command:
549     svn propset svn:keywords "Author Date Id Revision" <filename>
551 The F<t/distro/file_metadata.t> test checks that the files needing
552 this property have it set.
554 =head4 svn:eol-style
556 The C<svn:eol-style> property makes sure that whenever a file is checked out
557 of subversion it has the correct end-of-line characters appropriate for
558 the given platform.  Therefore, most files should have their
559 C<svn:eol-style> property set to C<native>.  However, this is not true
560 for all files.  Some input files to tests (such as the C<*.input> and
561 C<*.output> files for PIR tests) need to have C<LF> as their
562 C<svn:eol-style> property.  The current list of such files is described in
563 F<t/distro/file_metadata.t>.
565 Set the C<svn:eol-style> property to C<native> with the command:
567     svn propset svn:eol-style "native" <filename>
569 Set the C<svn:eol-style> property to C<LF> with the command:
571     svn propset svn:eol-style "LF" <filename>
573 The F<t/distro/file_metadata.t> test checks that the files needing
574 this property have it set.
576 =head3 Naming Conventions
578 =over 4
580 =item Filenames
582 Filenames must be assumed to be case-insensitive, in the sense that that you
583 may not have two different files called F<Foo> and F<foo>. Normal source-code
584 filenames should be all lower-case; filenames with upper-case letters in them
585 are reserved for notice-me-first files such as F<README>, and for files which
586 need some sort of pre-processing applied to them or which do the preprocessing
587 - e.g. a script F<foo.SH> might read F<foo.TEMPLATE> and output F<foo.c>.
589 The characters making up filenames must be chosen from the ASCII set
590 A-Z,a-z,0-9 plus .-_
592 An underscore should be used to separate words rather than a hyphen (-).
593 A file should not normally have more than a single '.' in it, and this
594 should be used to denote a suffix of some description. The filename must
595 still be unique if the main part is truncated to 8 characters and any
596 suffix truncated to 3 characters. Ideally, filenames should restricted
597 to 8.3 in the first place, but this is not essential.
599 Each subsystem I<foo> should supply the following files. This
600 arrangement is based on the assumption that each subsystem will -- as
601 far as is practical -- present an opaque interface to all other
602 subsystems within the core, as well as to extensions and embeddings.
604 =over 4
606 =item C<foo.h>
608 This contains all the declarations needed for external users of that API
609 (and nothing more), i.e. it defines the API. It is permissible for the
610 API to include different or extra functionality when used by other parts
611 of the core, compared with its use in extensions and embeddings. In this
612 case, the extra stuff within the file is enabled by testing for the
613 macro C<PARROT_IN_CORE>.
615 =item C<foo_private.h>
617 This contains declarations used internally by that subsystem, and which
618 must only be included within source files associated the subsystem. This
619 file defines the macro C<PARROT_IN_FOO> so that code knows when it is
620 being used within that subsystem. The file will also contain all the
621 'convenience' macros used to define shorter working names for functions
622 without the perl prefix (see below).
624 =item C<foo_globals.h>
626 This file contains the declaration of a single structure containing the
627 private global variables used by the subsystem (see the section on
628 globals below for more details).
630 =item C<foo_bar.[ch]> etc.
632 All other source files associated with the subsystem will have the
633 prefix C<foo_>.
635 =back
637 =item Names of code entities
639 Code entities such as variables, functions, macros etc. (apart from strictly
640 local ones) should all follow these general guidelines.
642 =over 4
644 =item *
646 Multiple words or components should be separated with underscores rather
647 than using tricks such as capitalization, e.g. C<new_foo_bar> rather
648 than C<NewFooBar> or (gasp) C<newfoobar>.
650 =item *
652 The names of entities should err on the side of verbosity, e.g.
653 C<create_foo_from_bar()> in preference to C<ct_foo_bar()>. Avoid cryptic
654 abbreviations wherever possible.
656 =item *
658 All entities should be prefixed with the name of the subsystem in which they
659 appear, e.g. C<pmc_foo()>, C<struct io_bar>.
661 =item *
663 Functions with external visibility should be of the form C<Parrot_foo>,
664 and should only use typedefs with external visibility (or types defined
665 in C89).  Generally these functions should not be used inside the core,
666 but this is not a hard and fast rule.
668 =item *
670 Variables and structure names should be all lower-case, e.g. C<pmc_foo>.
672 =item *
674 Structure elements should be all lower-case, and the first component of the
675 name should incorporate the structure's name or an abbreviation of it.
677 =item *
679 Typedef names should be lower-case except for the first letter, e.g.
680 C<Foo_bar>.  The exception to this is when the first component is a
681 short abbreviation, in which case the whole first component may be made
682 uppercase for readability purposes, e.g. C<IO_foo> rather than
683 C<Io_foo>.  Structures should generally be typedefed.
685 =item *
687 Macros should have their first component uppercase, and the majority of
688 the remaining components should be likewise. Where there is a family of
689 macros, the variable part can be indicated in lowercase, e.g.
690 C<PMC_foo_FLAG>, C<PMC_bar_FLAG>, ....
692 =item *
694 A macro which defines a flag bit should be suffixed with C<_FLAG>, e.g.
695 C<PMC_readonly_FLAG> (although you probably want to use an C<enum> instead.)
697 =item *
699 A macro which tests a flag bit should be suffixed with C<_TEST>, e.g. C<if
700 (PMC_readonly_TEST(foo)) ...>
702 =item *
704 A macro which sets a flag bit should be suffixed with C<_SET>, e.g.
705 C<PMC_readonly_SET(foo);>
707 =item *
709 A macro which clears a flag bit should be suffixed with C<_CLEAR>, e.g.
710 C<PMC_readonly_CLEAR(foo);>
712 =item *
714 A macro defining a mask of flag bits should be suffixed with C<_MASK>, e.g.
715 C<foo &= ~PMC_STATUS_MASK> (but see notes on extensibility below).
717 =item *
719 Macros can be defined to cover common flag combinations, in which case they
720 should have C<_SETALL>, C<_CLEARALL>, C<_TESTALL> or C<_TESTANY> suffixes as
721 appropriate, to indicate aggregate bits, e.g. C<PMC_valid_CLEARALL(foo)>.
723 =item *
725 A macro defining an auto-configuration value should be prefixed with C<HAS_>,
726 e.g. C<HAS_BROKEN_FLOCK>, C<HAS_EBCDIC>.
728 =item *
730 A macro indicating the compilation 'location' should be prefixed with
731 C<IN_>, e.g. C<PARROT_IN_CORE>, C<PARROT_IN_PMC>, C<PARROT_IN_X2P>.
732 Individual include file visitations should be marked with C<PARROT_IN_FOO_H>
733 for file C<foo.h>
735 =item *
737 A macro indicating major compilation switches should be prefixed with C<USE_>,
738 e.g. C<PARROT_USE_STDIO>, C<USE_MULTIPLICITY>.
740 =item *
742 A macro that may declare stuff and thus needs to be at the start of a
743 block should be prefixed with C<DECL_>, e.g. C<DECL_SAVE_STACK>. Note
744 that macros which implicitly declare and then use variables are strongly
745 discouraged, unless it is essential for portability or extensibility.
746 The following are in decreasing preference style-wise, but increasing
747 preference extensibility-wise.
749     { Stack sp = GETSTACK;  x = POPSTACK(sp) ... /* sp is an auto variable */
750     { DECL_STACK(sp);  x = POPSTACK(sp); ... /* sp may or may not be auto */
751     { DECL_STACK; x = POPSTACK; ... /* anybody's guess */
754 =back
756 =item Global Variables
758 Global variables must never be accessed directly outside the subsystem
759 in which they are used. Some other method, such as accessor functions,
760 must be provided by that subsystem's API. (For efficiency the 'accessor
761 functions' may occasionally actually be macros, but then the rule still
762 applies in spirit at least).
764 All global variables needed for the internal use of a particular subsystem
765 should all be declared within a single struct called C<foo_globals> for
766 subsystem C<foo>. This structure's declaration is placed in the file
767 C<foo_globals.h>. Then somewhere a single compound structure will be
768 declared which has as members the individual structures from each subsystem.
769 Instances of this structure are then defined as a one-off global variable,
770 or as per-thread instances, or whatever is required.
772 [Actually, three separate structures may be required, for global,
773 per-interpreter and per-thread variables.]
775 Within an individual subsystem, macros are defined for each global variable of
776 the form C<GLOBAL_foo> (the name being deliberately clunky). So we might for
777 example have the following macros:
779     /* perl_core.h or similar */
781     #ifdef HAS_THREADS
782     #  define GLOBALS_BASE (aTHX_->globals)
783     #else
784     #  define GLOBALS_BASE (Parrot_globals)
785     #endif
787     /* pmc_private.h */
789     #define GLOBAL_foo   GLOBALS_BASE.pmc.foo
790     #define GLOBAL_bar   GLOBALS_BASE.pmc.bar
791     ... etc ...
793 =back
796 =head3 Code Comments
798 The importance of good code documentation cannot be stressed enough. To make
799 your code understandable by others (and indeed by yourself when you come to
800 make changes a year later), the following conventions apply to all source
801 files.
803 =over 4
805 =item Developer files
807 Each source file (e.g. a F<foo.c>, F<foo.h> pair), should contain inline
808 Pod documentation containing information on the implementation decisions
809 associated with the source file. (Note that this is in contrast to PDDs,
810 which describe design decisions). In addition, more discussive
811 documentation can be placed in F<*.pod> files in the F<docs/dev>
812 directory. This is the place for mini-essays on how to avoid overflows
813 in unsigned arithmetic, or on the pros and cons of differing hash
814 algorithms, and why the current one was chosen, and how it works.
816 In principle, someone coming to a particular source file for the first time
817 should be able to read the inline documentation file and gain an immediate
818 overview of what the source file is for, the algorithms it implements, etc.
820 The Pod documentation should follow the layout:
822 =over 4
824 =item Version
826 A SVN id string.
828 =item Title
830     =head1 Foo
832 =item Synopsis
834 When appropriate, some simple examples of usage.
836 =item Description
838 A description of the contents of the file, how the implementation works, data
839 structures and algorithms, and anything that may be of interest to your
840 successors, e.g. benchmarks of differing hash algorithms, essays on how to do
841 integer arithmetic.
843 =item See Also
845 Links to pages and books that may contain useful information relevant to the
846 stuff going on in the code -- e.g. the book you stole the hash function from.
848 =back
850 Don't include author information in individual files. Author information
851 can be added to the CREDITS file. (Languages are an exception to this rule,
852 and may follow whatever convention they choose.)
854 Don't include Pod sections for License or Copyright in individual files.
856 =item Per-section comments
858 If there is a collection of functions, structures or whatever which are
859 grouped together and have a common theme or purpose, there should be a
860 general comment at the start of the section briefly explaining their
861 overall purpose. (Detailed essays should be left to the developer file).
862 If there is really only one section, then the top-of-file comment
863 already satisfies this requirement.
865 =item Per-entity comments
867 Every non-local named entity, be it a function, variable, structure, macro or
868 whatever, must have an accompanying comment explaining its purpose.  This
869 comment must be in the special format described below, in order to allow
870 automatic extraction by tools - for example, to generate per API man pages,
871 B<perldoc -f> style utilities and so on.
873 Often the comment need only be a single line explaining its purpose, but
874 sometimes more explanation may be needed. For example, "return an Integer Foo
875 to its allocation pool" may be enough to demystify the function C<del_I_foo()>
877 Each comment should be of the form
879     /*
881     =item C<function(arguments)>
883     Description.
885     =cut
887     */
889 This inline Pod documentation is parsed to HTML by running:
891     $ perl tools/docs/write_docs.pl --delete
894     $ make html
896 =item Optimizations
898 Whenever code has deliberately been written in an odd way for performance
899 reasons, you should point this out - if nothing else, to avoid some poor
900 schmuck trying subsequently to replace it with something 'cleaner'.
902     /* The loop is partially unrolled here as it makes it a lot faster.
903      * See the file in docs/dev for the full details
904      */
906 =item General comments
908 While there is no need to go mad commenting every line of code, it is
909 immensely helpful to provide a "running commentary" every 10 lines or so
910 if nothing else, this makes it easy to quickly locate a specific chunk
911 of code. Such comments are particularly useful at the top of each major
912 branch, e.g.
914     if (FOO_bar_BAZ(**p+*q) <= (r-s[FOZ & FAZ_MASK]) || FLOP_2(z99)) {
915         /* we're in foo mode: clean up lexicals */
916         ... (20 lines of gibberish) ...
917     }
918     else if (...) {
919         /* we're in bar mode: clean up globals */
920         ... (20 more lines of gibberish) ...
921     }
922     else {
923         /* we're in baz mode: self-destruct */
924         ....
925     }
927 =item Copyright notice
929 The first line of every file (or the second line if the first line is a
930 I<shebang> line such as C<#!/usr/bin/perl>) should be a copyright notice, in
931 the comment style appropriate to the file type. It should list the first year
932 the file was created and the last year the file was modified.  (This isn't
933 necessarily the current year, the file might not have been modified this
934 year.)
936     /* Copyright (C) 2001-2008, Parrot Foundation. */
938 For files that were newly added this year, just list the current year.
940     /* Copyright (C) 2009, Parrot Foundation. */
942 =back
944 =head3 Extensibility
946 Over the lifetime of Parrot, the source code will undergo many major changes
947 never envisaged by its original authors. To this end, your code should balance
948 out the assumptions that make things possible, fast or small, with the
949 assumptions that make it difficult to change things in future. This is
950 especially important for parts of the code which are exposed through APIs --
951 the requirements of source or binary compatibility for such things as
952 extensions can make it very hard to change things later on.
954 For example, if you define suitable macros to set/test flags in a struct, then
955 you can later add a second word of flags to the struct without breaking source
956 compatibility. (Although you might still break binary compatibility if you're
957 not careful.) Of the following two methods of setting a common combination of
958 flags, the second doesn't assume that all the flags are contained within a
959 single field:
961     foo->flags |= (FOO_int_FLAG | FOO_num_FLAG | FOO_str_FLAG);
962     FOO_valid_value_SETALL(foo);
964 Similarly, avoid using a C<char*> (or C<{char*,length}>) if it is feasible
965 to later use a C<PMC *> at the same point: c.f. UTF-8 hash keys in Perl 5.
967 Of course, private code hidden behind an API can play more fast and loose than
968 code which gets exposed.
970 =head3 Performance
972 We want Parrot to be fast. Very fast. But we also want it to be portable and
973 extensible. Based on the 90/10 principle, (or 80/20, or 95/5, depending on who
974 you speak to), most performance is gained or lost in a few small but critical
975 areas of code. Concentrate your optimization efforts there.
977 Note that the most overwhelmingly important factor in performance is in
978 choosing the correct algorithms and data structures in the first place. Any
979 subsequent tweaking of code is secondary to this. Also, any tweaking that is
980 done should as far as possible be platform independent, or at least likely to
981 cause speed-ups in a wide variety of environments, and do no harm elsewhere.
983 If you do put an optimization in, time it on as many architectures as
984 you can, and be suspicious of it if it slows down on any of them!
985 Perhaps it will be slow on other architectures too (current and future).
986 Perhaps it wasn't so clever after all? If the optimization is platform
987 specific, you should probably put it in a platform-specific function in
988 a platform-specific file, rather than cluttering the main source with
989 zillions of #ifdefs.
991 And remember to document it.
993 =head2 Exemptions
995 Not all files can strictly fall under these guidelines as they are
996 automatically generated by other tools, or are external files included in
997 the Parrot repository for convenience.  Such files include the C header and
998 source files automatically generated by (f)lex and yacc/bison, and some of
999 the Perl modules under the F<lib/> directory.
1001 To exempt a file (or directory of files) from checking by the coding
1002 standards tests, one must edit the appropriate exemption list within
1003 C<lib/Parrot/Distribution.pm> (in either of the methods C<is_c_exemption()>
1004 or C<is_perl_exemption()>).  One can use wildcards in the list to exempt,
1005 for example, all files under a given directory.
1007 =head2 References
1009 None.
1011 =cut
1013 __END__
1014 Local Variables:
1015   fill-column:78
1016 End:
1017 vim: expandtab shiftwidth=4: