Skip several gcc.dg/builtin-dynamic-object-size tests on hppa*-*-hpux*
[official-gcc.git] / gcc / ada / doc / gnat-style.rst
blob527e7ba2a66d7b2df71eb6d6ca2a88cb784578ad
1 GNAT Coding Style: A Guide for GNAT Developers
2 ==============================================
4 General
5 -------
7 Most of GNAT is written in Ada using a consistent style to ensure
8 readability of the code.  This document has been written to help
9 maintain this consistent style, while having a large group of developers
10 work on the compiler.
12 For the coding style in the C parts of the compiler and run time,
13 see the GNU Coding Guidelines.
15 This document is structured after the Ada Reference Manual.
16 Those familiar with that document should be able to quickly
17 lookup style rules for particular constructs.
19 Lexical Elements
20 ----------------
22 Character Set and Separators
23 ****************************
25 .. index:: Character set
26 .. index:: ASCII
27 .. index:: Separators
28 .. index:: End-of-line
29 .. index:: Line length
30 .. index:: Indentation
32 * The character set used should be plain 7-bit ASCII.
33   The only separators allowed are space and the end-of-line sequence.
34   No other control character or format effector (such as ``HT``,
35   ``VT``, ``FF`` )
36   should be used.
37   The normal end-of-line sequence is used, which may be
38   ``LF``, ``CR/LF`` or ``CR``,
39   depending on the host system.  An optional ``SUB``
40   ( ``16#1A#`` ) may be present as the
41   last character in the file on hosts using that character as file terminator.
43 * Files that are checked in or distributed should be in host format.
45 * A line should never be longer than 79 characters, not counting the line
46   separator.
48 * Lines must not have trailing blanks.
50 * Indentation is 3 characters per level for ``if`` statements, loops, and
51   ``case`` statements.
52   For exact information on required spacing between lexical
53   elements, see file style.adb.
55   .. index:: style.adb file
57 Identifiers
58 ***********
60 * Identifiers will start with an upper case letter, and each letter following
61   an underscore will be upper case.
63   .. index:: Casing (for identifiers)
65   Short acronyms may be all upper case.
66   All other letters are lower case.
67   An exception is for identifiers matching a foreign language.  In particular,
68   we use all lower case where appropriate for C.
70 * Use underscores to separate words in an identifier.
72   .. index:: Underscores
74 * Try to limit your use of abbreviations in identifiers.
75   It is ok to make a few abbreviations, explain what they mean, and then
76   use them frequently, but don't use lots of obscure abbreviations.  An
77   example is the ``ALI`` word which stands for Ada Library
78   Information and is by convention always written in upper-case when
79   used in entity names.
81   .. code-block:: ada
83            procedure Find_ALI_Files;
85 * Don't use the variable name ``I``, use ``J`` instead; ``I`` is too
86   easily confused with ``1`` in some fonts.  Similarly don't use the
87   variable ``O``, which is too easily mistaken for the number ``0``.
89 Numeric Literals
90 ****************
92 * Numeric literals should include underscores where helpful for
93   readability.
95   .. index:: Underscores
97   .. code-block:: ada
99           1_000_000
100           16#8000_0000#
101           3.14159_26535_89793_23846
103 Reserved Words
104 **************
106 * Reserved words use all lower case.
108   .. index:: Casing (for reserved words)
110   .. code-block:: ada
112            return else
114 * The words ``Access``, ``Delta`` and ``Digits`` are
115   capitalized when used as attribute_designator.
117 Comments
118 ********
120 * A comment starts with ``--`` followed by two spaces.
121   The only exception to this rule (i.e. one space is tolerated) is when the
122   comment ends with a single space followed by ``--``.
123   It is also acceptable to have only one space between ``--`` and the start
124   of the comment when the comment is at the end of a line,
125   after some Ada code.
127 * Every sentence in a comment should start with an upper-case letter (including
128   the first letter of the comment).
130   .. index:: Casing (in comments)
132 * When declarations are commented with 'hanging' comments, i.e.
133   comments after the declaration, there is no blank line before the
134   comment, and if it is absolutely necessary to have blank lines within
135   the comments, e.g. to make paragraph separations within a single comment,
136   these blank lines *do* have a ``--`` (unlike the
137   normal rule, which is to use entirely blank lines for separating
138   comment paragraphs).  The comment starts at same level of indentation
139   as code it is commenting.
141   .. index:: Blank lines (in comments)
142   .. index:: Indentation
144   .. code-block:: ada
146            z : Integer;
147            --  Integer value for storing value of z
148            --
149            --  The previous line was a blank line.
151 * Comments that are dubious or incomplete, or that comment on possibly
152   wrong or incomplete code, should be preceded or followed by ``???``.
154 * Comments in a subprogram body must generally be surrounded by blank lines.
155   An exception is a comment that follows a line containing a single keyword
156   ( ``begin``, ``else``, ``loop`` ):
158   .. code-block:: ada
160            begin
161               --  Comment for the next statement
163               A := 5;
165               --  Comment for the B statement
167               B := 6;
168            end;
170 * In sequences of statements, comments at the end of the lines should be
171   aligned.
173   .. index:: Alignment (in comments)
175   .. code-block:: ada
177             My_Identifier := 5;      --  First comment
178             Other_Id := 6;           --  Second comment
180 * Short comments that fit on a single line are *not* ended with a
181   period.  Comments taking more than a line are punctuated in the normal
182   manner.
184 * Comments should focus on *why* instead of *what*.
185   Descriptions of what subprograms do go with the specification.
187 * Comments describing a subprogram spec should specifically mention the
188   formal argument names.  General rule: write a comment that does not
189   depend on the names of things.  The names are supplementary, not
190   sufficient, as comments.
192 * *Do not* put two spaces after periods in comments.
194 Declarations and Types
195 ----------------------
197 * In entity declarations, colons must be surrounded by spaces.  Colons
198   should be aligned.
200   .. index:: Alignment (in declarations)
202   .. code-block:: ada
204             Entity1   : Integer;
205             My_Entity : Integer;
207 * Declarations should be grouped in a logical order.
208   Related groups of declarations may be preceded by a header comment.
210 * All local subprograms in a subprogram or package body should be declared
211   before the first local subprogram body.
213 * Do not declare local entities that hide global entities.
215   .. index:: Hiding of outer entities
217 * Do not declare multiple variables in one declaration that spans lines.
218   Start a new declaration on each line, instead.
220 * The defining_identifiers of global declarations serve as
221   comments of a sort.  So don't choose terse names, but look for names
222   that give useful information instead.
224 * Local names can be shorter, because they are used only within
225   one context, where comments explain their purpose.
227 * When starting an initialization or default expression on the line that follows
228   the declaration line, use 2 characters for indentation.
230   .. code-block:: ada
232             Entity1 : Integer :=
233               Function_Name (Parameters, For_Call);
235 * If an initialization or default expression needs to be continued on subsequent
236   lines, the continuations should be indented from the start of the expression.
238   .. code-block:: ada
240             Entity1 : Integer := Long_Function_Name
241                                    (parameters for call);
243 Expressions and Names
244 ---------------------
246 * Every operator must be surrounded by spaces. An exception is that
247   this rule does not apply to the exponentiation operator, for which
248   there are no specific layout rules. The reason for this exception
249   is that sometimes it makes clearer reading to leave out the spaces
250   around exponentiation.
252   .. index:: Operators
254   .. code-block:: ada
256            E := A * B**2 + 3 * (C - D);
258 * Use parentheses where they clarify the intended association of operands
259   with operators:
261   .. index:: Parenthesization of expressions
263   .. code-block:: ada
265            (A / B) * C
267 Statements
268 ----------
270 Simple and Compound Statements
271 ******************************
273 * Use only one statement or label per line.
275 * A longer sequence_of_statements may be divided in logical
276   groups or separated from surrounding code using a blank line.
279 If Statements
280 *************
282 * When the ``if``, ``elsif`` or ``else`` keywords fit on the
283   same line with the condition and the ``then`` keyword, then the
284   statement is formatted as follows:
286   .. index:: Alignment (in an if statement)
288   .. code-block:: ada
290             if condition then
291                ...
292             elsif condition then
293                ...
294             else
295                ...
296             end if;
298   When the above layout is not possible, ``then`` should be aligned
299   with ``if``, and conditions should preferably be split before an
300   ``and`` or ``or`` keyword a follows:
302   .. code-block:: ada
304             if long_condition_that_has_to_be_split
305               and then continued_on_the_next_line
306             then
307                ...
308             end if;
310   The ``elsif``, ``else`` and ``end if`` always line up with
311   the ``if`` keyword.  The preferred location for splitting the line
312   is before ``and`` or ``or``.  The continuation of a condition is
313   indented with two spaces or as many as needed to make nesting clear.
314   As an exception, if conditions are closely related either of the
315   following is allowed:
317   .. code-block:: ada
319          if x = lakdsjfhlkashfdlkflkdsalkhfsalkdhflkjdsahf
320               or else
321             x = asldkjhalkdsjfhhfd
322               or else
323             x = asdfadsfadsf
324          then
325            ...
326          end if;
328          if x = lakdsjfhlkashfdlkflkdsalkhfsalkdhflkjdsahf or else
329             x = asldkjhalkdsjfhhfd                         or else
330             x = asdfadsfadsf
331          then
332            ...
333          end if;
335 * Conditions should use short-circuit forms ( ``and then``,
336   ``or else`` ), except when the operands are boolean variables
337   or boolean constants.
339   .. index:: Short-circuit forms
341 * Complex conditions in ``if`` statements are indented two characters:
343   .. index:: Indentation (in if statements)
345   .. code-block:: ada
347           if this_complex_condition
348             and then that_other_one
349             and then one_last_one
350           then
351              ...
352           end if;
354   There are some cases where complex conditionals can be laid out
355   in manners that do not follow these rules to preserve better
356   parallelism between branches, e.g.
358   .. code-block:: ada
360           if xyz.abc (gef) = 'c'
361                or else
362              xyz.abc (gef) = 'x'
363           then
364              ...
365           end if;
367 * Every ``if`` block is preceded and followed by a blank line, except
368   where it begins or ends a sequence_of_statements.
370   .. index:: Blank lines (in an if statement)
372   .. code-block:: ada
374             A := 5;
376             if A = 5 then
377                null;
378             end if;
380             A := 6;
382 Case Statements
383 ***************
385 * Layout is as below.  For long ``case`` statements, the extra indentation
386   can be saved by aligning the ``when`` clauses with the opening ``case``.
388   .. code-block:: ada
390            case expression is
391               when condition =>
392                  ...
393               when condition =>
394                  ...
395            end case;
397 Loop Statements
398 ***************
400 * When possible, have ``for`` or ``while`` on one line with the
401   condition and the ``loop`` keyword.
403   .. code-block:: ada
405            for J in S'Range loop
406               ...
407            end loop;
409   If the condition is too long, split the condition (see 'If
410   statements' above) and align ``loop`` with the ``for`` or
411   ``while`` keyword.
413   .. index:: Alignment (in a loop statement)
415   .. code-block:: ada
417           while long_condition_that_has_to_be_split
418             and then continued_on_the_next_line
419           loop
420              ...
421           end loop;
423   If the loop_statement has an identifier, it is laid out as follows:
425   .. code-block:: ada
427           Outer : while not condition loop
428              ...
429           end Outer;
431 Block Statements
432 ****************
434 * The ``declare`` (optional), ``begin`` and ``end`` words
435   are aligned, except when the block_statement is named.  There
436   is a blank line before the ``begin`` keyword:
438   .. index:: Alignment (in a block statement)
440   .. code-block:: ada
442           Some_Block : declare
443              ...
445           begin
446              ...
447           end Some_Block;
449 Subprograms
450 -----------
452 Subprogram Declarations
453 ***********************
455 * Do not write the ``in`` for parameters.
457   .. code-block:: ada
459           function Length (S : String) return Integer;
461 * When the declaration line for a procedure or a function is too long to fit
462   the entire declaration (including the keyword procedure or function) on a
463   single line, then fold it, putting a single parameter on a line, aligning
464   the colons, as in:
466   .. code-block:: ada
468          procedure Set_Heading
469            (Source : String;
470             Count  : Natural;
471             Pad    : Character := Space;
472             Fill   : Boolean   := True);
474   In the case of a function, if the entire spec does not fit on one line, then
475   the return may appear after the last parameter, as in:
477   .. code-block:: ada
479           function Head
480             (Source : String;
481              Count  : Natural;
482              Pad    : Character := Space) return String;
484   Or it may appear on its own as a separate line. This form is preferred when
485   putting the return on the same line as the last parameter would result in
486   an overlong line. The return type may optionally be aligned with the types
487   of the parameters (usually we do this aligning if it results only in a small
488   number of extra spaces, and otherwise we don't attempt to align). So two
489   alternative forms for the above spec are:
491   .. code-block:: ada
493           function Head
494             (Source : String;
495              Count  : Natural;
496              Pad    : Character := Space)
497              return   String;
499           function Head
500             (Source : String;
501              Count  : Natural;
502              Pad    : Character := Space)
503              return String;
505 Subprogram Bodies
506 *****************
508 * Function and procedure bodies should usually be sorted alphabetically. Do
509   not attempt to sort them in some logical order by functionality. For a
510   sequence of subprogram specs, a general alphabetical sorting is also
511   usually appropriate, but occasionally it makes sense to group by major
512   function, with appropriate headers.
514 * All subprograms have a header giving the function name, with the following
515   format:
517   .. code-block:: ada
519           -----------------
520           -- My_Function --
521           -----------------
523           procedure My_Function is
524           begin
525             ...
526           end My_Function;
528   Note that the name in the header is preceded by a single space,
529   not two spaces as for other comments. These headers are used on
530   nested subprograms as well as outer level subprograms. They may
531   also be used as headers for sections of comments, or collections
532   of declarations that are related.
534 * Every subprogram body must have a preceding subprogram_declaration,
535   which includes proper client documentation so that you do not need to
536   read the subprogram body in order to understand what the subprogram does and
537   how to call it. All subprograms should be documented, without exceptions.
539   .. index:: Blank lines (in subprogram bodies)
541 * A sequence of declarations may optionally be separated from the following
542   begin by a blank line.  Just as we optionally allow blank lines in general
543   between declarations, this blank line should be present only if it improves
544   readability. Generally we avoid this blank line if the declarative part is
545   small (one or two lines) and the body has no blank lines, and we include it
546   if the declarative part is long or if the body has blank lines.
548 * If the declarations in a subprogram contain at least one nested
549   subprogram body, then just before the ``begin`` of the enclosing
550   subprogram, there is a comment line and a blank line:
552   .. code-block:: ada
554         --  Start of processing for Enclosing_Subprogram
556         begin
557           ...
558         end Enclosing_Subprogram;
560 * When nested subprograms are present, variables that are referenced by any
561   nested subprogram should precede the nested subprogram specs. For variables
562   that are not referenced by nested procedures, the declarations can either also
563   be before any of the nested subprogram specs (this is the old style, more
564   generally used). Or then can come just before the begin, with a header. The
565   following example shows the two possible styles:
567   .. code-block:: ada
569         procedure Style1 is
570            Var_Referenced_In_Nested      : Integer;
571            Var_Referenced_Only_In_Style1 : Integer;
573            proc Nested;
574            --  Comments ...
576            ------------
577            -- Nested --
578            ------------
580            procedure Nested is
581            begin
582               ...
583            end Nested;
585         --  Start of processing for Style1
587         begin
588            ...
589         end Style1;
591         procedure Style2 is
592            Var_Referenced_In_Nested : Integer;
594            proc Nested;
595            --  Comments ...
597            ------------
598            -- Nested --
599            ------------
601            procedure Nested is
602            begin
603               ...
604            end Nested;
606            --  Local variables
608            Var_Referenced_Only_In_Style2 : Integer;
610         --  Start of processing for Style2
612         begin
613            ...
614         end Style2;
616   For new code, we generally prefer Style2, but we do not insist on
617   modifying all legacy occurrences of Style1, which is still much
618   more common in the sources.
620 Packages and Visibility Rules
621 -----------------------------
623 * All program units and subprograms have their name at the end:
625   .. code-block:: ada
627           package P is
628              ...
629           end P;
631 * We will use the style of ``use`` -ing ``with`` -ed packages, with
632   the context clauses looking like:
634   .. index:: use clauses
636   .. code-block:: ada
638           with A; use A;
639           with B; use B;
641 * Names declared in the visible part of packages should be
642   unique, to prevent name clashes when the packages are ``use`` d.
644   .. index:: Name clash avoidance
646   .. code-block:: ada
648           package Entity is
649              type Entity_Kind is ...;
650              ...
651           end Entity;
653 * After the file header comment, the context clause and unit specification
654   should be the first thing in a program_unit.
656 * Preelaborate, Pure and Elaborate_Body pragmas should be added right after the
657   package name, indented an extra level and using the parameterless form:
659   .. code-block:: ada
661           package Preelaborate_Package is
662              pragma Preelaborate;
663              ...
664           end Preelaborate_Package;
666 Program Structure and Compilation Issues
667 ----------------------------------------
669 * Every GNAT source file must be compiled with the ``-gnatg``
670   switch to check the coding style.
671   (Note that you should look at
672   style.adb to see the lexical rules enforced by ``-gnatg`` ).
674   .. index:: -gnatg option (to gcc)
675   .. index:: style.adb file
677 * Each source file should contain only one compilation unit.
679 * Filenames should be 8 or fewer characters, followed by the ``.adb``
680   extension for a body or ``.ads`` for a spec.
682   .. index:: File name length
684 * Unit names should be distinct when 'krunch'ed to 8 characters
685   (see krunch.ads) and the filenames should match the unit name,
686   except that they are all lower case.
688   .. index:: krunch.ads file
690 .. toctree::
691    share/gnu_free_documentation_license