2015-02-20 Arnaud Charlet <charlet@adacore.com>
[official-gcc.git] / gcc / ada / doc / gnat_ugn / elaboration_order_handling_in_gnat.rst
blob90b64a7f17a0f113060c3f73818eba20b604fa8d
1 .. |with| replace:: *with*
2 .. |withs| replace:: *with*\ s
3 .. |withed| replace:: *with*\ ed
4 .. |withing| replace:: *with*\ ing
6 .. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
9 .. _Elaboration_Order_Handling_in_GNAT:
11 **********************************
12 Elaboration Order Handling in GNAT
13 **********************************
15 .. index:: Order of elaboration
16 .. index:: Elaboration control
18 This appendix describes the handling of elaboration code in Ada and
19 in GNAT, and discusses how the order of elaboration of program units can
20 be controlled in GNAT, either automatically or with explicit programming
21 features.
23 .. _Elaboration_Code:
25 Elaboration Code
26 ================
28 Ada provides rather general mechanisms for executing code at elaboration
29 time, that is to say before the main program starts executing. Such code arises
30 in three contexts:
32 * *Initializers for variables*
34   Variables declared at the library level, in package specs or bodies, can
35   require initialization that is performed at elaboration time, as in:
37   .. code-block:: ada
39        Sqrt_Half : Float := Sqrt (0.5);
41 * *Package initialization code*
43   Code in a `BEGIN-END` section at the outer level of a package body is
44   executed as part of the package body elaboration code.
46 * *Library level task allocators*
48   Tasks that are declared using task allocators at the library level
49   start executing immediately and hence can execute at elaboration time.
51 Subprogram calls are possible in any of these contexts, which means that
52 any arbitrary part of the program may be executed as part of the elaboration
53 code. It is even possible to write a program which does all its work at
54 elaboration time, with a null main program, although stylistically this
55 would usually be considered an inappropriate way to structure
56 a program.
58 An important concern arises in the context of elaboration code:
59 we have to be sure that it is executed in an appropriate order. What we
60 have is a series of elaboration code sections, potentially one section
61 for each unit in the program. It is important that these execute
62 in the correct order. Correctness here means that, taking the above
63 example of the declaration of `Sqrt_Half`,
64 if some other piece of
65 elaboration code references `Sqrt_Half`,
66 then it must run after the
67 section of elaboration code that contains the declaration of
68 `Sqrt_Half`.
70 There would never be any order of elaboration problem if we made a rule
71 that whenever you |with| a unit, you must elaborate both the spec and body
72 of that unit before elaborating the unit doing the |withing|:
74 .. code-block:: ada
76      with Unit_1;
77      package Unit_2 is ...
78   
79 would require that both the body and spec of `Unit_1` be elaborated
80 before the spec of `Unit_2`. However, a rule like that would be far too
81 restrictive. In particular, it would make it impossible to have routines
82 in separate packages that were mutually recursive.
84 You might think that a clever enough compiler could look at the actual
85 elaboration code and determine an appropriate correct order of elaboration,
86 but in the general case, this is not possible. Consider the following
87 example.
89 In the body of `Unit_1`, we have a procedure `Func_1`
90 that references
91 the variable `Sqrt_1`, which is declared in the elaboration code
92 of the body of `Unit_1`:
94 .. code-block:: ada
96      Sqrt_1 : Float := Sqrt (0.1);
97   
98 The elaboration code of the body of `Unit_1` also contains:
100 .. code-block:: ada
102      if expression_1 = 1 then
103         Q := Unit_2.Func_2;
104      end if;
106 `Unit_2` is exactly parallel,
107 it has a procedure `Func_2` that references
108 the variable `Sqrt_2`, which is declared in the elaboration code of
109 the body `Unit_2`:
111 .. code-block:: ada
113       Sqrt_2 : Float := Sqrt (0.1);
114   
115 The elaboration code of the body of `Unit_2` also contains:
117 .. code-block:: ada
119      if expression_2 = 2 then
120         Q := Unit_1.Func_1;
121      end if;
122   
123 Now the question is, which of the following orders of elaboration is
124 acceptable:
128      Spec of Unit_1
129      Spec of Unit_2
130      Body of Unit_1
131      Body of Unit_2
132   
137      Spec of Unit_2
138      Spec of Unit_1
139      Body of Unit_2
140      Body of Unit_1
141   
142 If you carefully analyze the flow here, you will see that you cannot tell
143 at compile time the answer to this question.
144 If `expression_1` is not equal to 1,
145 and `expression_2` is not equal to 2,
146 then either order is acceptable, because neither of the function calls is
147 executed. If both tests evaluate to true, then neither order is acceptable
148 and in fact there is no correct order.
150 If one of the two expressions is true, and the other is false, then one
151 of the above orders is correct, and the other is incorrect. For example,
152 if `expression_1` /= 1 and `expression_2` = 2,
153 then the call to `Func_1`
154 will occur, but not the call to `Func_2.`
155 This means that it is essential
156 to elaborate the body of `Unit_1` before
157 the body of `Unit_2`, so the first
158 order of elaboration is correct and the second is wrong.
160 By making `expression_1` and `expression_2`
161 depend on input data, or perhaps
162 the time of day, we can make it impossible for the compiler or binder
163 to figure out which of these expressions will be true, and hence it
164 is impossible to guarantee a safe order of elaboration at run time.
166 .. _Checking_the_Elaboration_Order:
168 Checking the Elaboration Order
169 ==============================
171 In some languages that involve the same kind of elaboration problems,
172 e.g., Java and C++, the programmer needs to take these
173 ordering problems into account, and it is common to
174 write a program in which an incorrect elaboration order  gives
175 surprising results, because it references variables before they
176 are initialized.
177 Ada is designed to be a safe language, and a programmer-beware approach is
178 clearly not sufficient. Consequently, the language provides three lines
179 of defense:
181 * *Standard rules*
183   Some standard rules restrict the possible choice of elaboration
184   order. In particular, if you |with| a unit, then its spec is always
185   elaborated before the unit doing the |with|. Similarly, a parent
186   spec is always elaborated before the child spec, and finally
187   a spec is always elaborated before its corresponding body.
189 .. index:: Elaboration checks
190 .. index:: Checks, elaboration
192 * *Dynamic elaboration checks*
194   Dynamic checks are made at run time, so that if some entity is accessed
195   before it is elaborated (typically  by means of a subprogram call)
196   then the exception (`Program_Error`) is raised.
198 * *Elaboration control*
200   Facilities are provided for the programmer to specify the desired order
201   of elaboration.
203 Let's look at these facilities in more detail. First, the rules for
204 dynamic checking. One possible rule would be simply to say that the
205 exception is raised if you access a variable which has not yet been
206 elaborated. The trouble with this approach is that it could require
207 expensive checks on every variable reference. Instead Ada has two
208 rules which are a little more restrictive, but easier to check, and
209 easier to state:
211 * *Restrictions on calls*
213   A subprogram can only be called at elaboration time if its body
214   has been elaborated. The rules for elaboration given above guarantee
215   that the spec of the subprogram has been elaborated before the
216   call, but not the body. If this rule is violated, then the
217   exception `Program_Error` is raised.
219 * *Restrictions on instantiations*
221   A generic unit can only be instantiated if the body of the generic
222   unit has been elaborated. Again, the rules for elaboration given above
223   guarantee that the spec of the generic unit has been elaborated
224   before the instantiation, but not the body. If this rule is
225   violated, then the exception `Program_Error` is raised.
227 The idea is that if the body has been elaborated, then any variables
228 it references must have been elaborated; by checking for the body being
229 elaborated we guarantee that none of its references causes any
230 trouble. As we noted above, this is a little too restrictive, because a
231 subprogram that has no non-local references in its body may in fact be safe
232 to call. However, it really would be unsafe to rely on this, because
233 it would mean that the caller was aware of details of the implementation
234 in the body. This goes against the basic tenets of Ada.
236 A plausible implementation can be described as follows.
237 A Boolean variable is associated with each subprogram
238 and each generic unit. This variable is initialized to False, and is set to
239 True at the point body is elaborated. Every call or instantiation checks the
240 variable, and raises `Program_Error` if the variable is False.
242 Note that one might think that it would be good enough to have one Boolean
243 variable for each package, but that would not deal with cases of trying
244 to call a body in the same package as the call
245 that has not been elaborated yet.
246 Of course a compiler may be able to do enough analysis to optimize away
247 some of the Boolean variables as unnecessary, and `GNAT` indeed
248 does such optimizations, but still the easiest conceptual model is to
249 think of there being one variable per subprogram.
251 .. _Controlling_the_Elaboration_Order:
253 Controlling the Elaboration Order
254 =================================
256 In the previous section we discussed the rules in Ada which ensure
257 that `Program_Error` is raised if an incorrect elaboration order is
258 chosen. This prevents erroneous executions, but we need mechanisms to
259 specify a correct execution and avoid the exception altogether.
260 To achieve this, Ada provides a number of features for controlling
261 the order of elaboration. We discuss these features in this section.
263 First, there are several ways of indicating to the compiler that a given
264 unit has no elaboration problems:
266 * *packages that do not require a body*
268   A library package that does not require a body does not permit
269   a body (this rule was introduced in Ada 95).
270   Thus if we have a such a package, as in:
272   .. code-block:: ada
274        package Definitions is
275           generic
276              type m is new integer;
277           package Subp is
278              type a is array (1 .. 10) of m;
279              type b is array (1 .. 20) of m;
280           end Subp;
281        end Definitions;
283   A package that |withs| `Definitions` may safely instantiate
284   `Definitions.Subp` because the compiler can determine that there
285   definitely is no package body to worry about in this case
287 .. index:: pragma Pure
289 * *pragma Pure*
291   This pragma places sufficient restrictions on a unit to guarantee that
292   no call to any subprogram in the unit can result in an
293   elaboration problem. This means that the compiler does not need
294   to worry about the point of elaboration of such units, and in
295   particular, does not need to check any calls to any subprograms
296   in this unit.
298 .. index:: pragma Preelaborate
300 * *pragma Preelaborate*
302   This pragma places slightly less stringent restrictions on a unit than
303   does pragma Pure,
304   but these restrictions are still sufficient to ensure that there
305   are no elaboration problems with any calls to the unit.
307 .. index:: pragma Elaborate_Body
309 * *pragma Elaborate_Body*
311   This pragma requires that the body of a unit be elaborated immediately
312   after its spec. Suppose a unit `A` has such a pragma,
313   and unit `B` does
314   a |with| of unit `A`. Recall that the standard rules require
315   the spec of unit `A`
316   to be elaborated before the |withing| unit; given the pragma in
317   `A`, we also know that the body of `A`
318   will be elaborated before `B`, so
319   that calls to `A` are safe and do not need a check.
321   Note that, unlike pragma `Pure` and pragma `Preelaborate`,
322   the use of `Elaborate_Body` does not guarantee that the program is
323   free of elaboration problems, because it may not be possible
324   to satisfy the requested elaboration order.
325   Let's go back to the example with `Unit_1` and `Unit_2`.
326   If a programmer marks `Unit_1` as `Elaborate_Body`,
327   and not `Unit_2,` then the order of
328   elaboration will be::
330        Spec of Unit_2
331        Spec of Unit_1
332        Body of Unit_1
333        Body of Unit_2
335   Now that means that the call to `Func_1` in `Unit_2`
336   need not be checked,
337   it must be safe. But the call to `Func_2` in
338   `Unit_1` may still fail if
339   `Expression_1` is equal to 1,
340   and the programmer must still take
341   responsibility for this not being the case.
343   If all units carry a pragma `Elaborate_Body`, then all problems are
344   eliminated, except for calls entirely within a body, which are
345   in any case fully under programmer control. However, using the pragma
346   everywhere is not always possible.
347   In particular, for our `Unit_1`/`Unit_2` example, if
348   we marked both of them as having pragma `Elaborate_Body`, then
349   clearly there would be no possible elaboration order.
351 The above pragmas allow a server to guarantee safe use by clients, and
352 clearly this is the preferable approach. Consequently a good rule
353 is to mark units as `Pure` or `Preelaborate` if possible,
354 and if this is not possible,
355 mark them as `Elaborate_Body` if possible.
356 As we have seen, there are situations where neither of these
357 three pragmas can be used.
358 So we also provide methods for clients to control the
359 order of elaboration of the servers on which they depend:
361 .. index:: pragma Elaborate
363 * *pragma Elaborate (unit)*
365   This pragma is placed in the context clause, after a |with| clause,
366   and it requires that the body of the named unit be elaborated before
367   the unit in which the pragma occurs. The idea is to use this pragma
368   if the current unit calls at elaboration time, directly or indirectly,
369   some subprogram in the named unit.
372 .. index:: pragma Elaborate_All
374 * *pragma Elaborate_All (unit)*
376   This is a stronger version of the Elaborate pragma. Consider the
377   following example::
379         Unit A |withs| unit B and calls B.Func in elab code
380         Unit B |withs| unit C, and B.Func calls C.Func
381     
383   Now if we put a pragma `Elaborate (B)`
384   in unit `A`, this ensures that the
385   body of `B` is elaborated before the call, but not the
386   body of `C`, so
387   the call to `C.Func` could still cause `Program_Error` to
388   be raised.
390   The effect of a pragma `Elaborate_All` is stronger, it requires
391   not only that the body of the named unit be elaborated before the
392   unit doing the |with|, but also the bodies of all units that the
393   named unit uses, following |with| links transitively. For example,
394   if we put a pragma `Elaborate_All (B)` in unit `A`,
395   then it requires not only that the body of `B` be elaborated before `A`,
396   but also the body of `C`, because `B` |withs| `C`.
398 We are now in a position to give a usage rule in Ada for avoiding
399 elaboration problems, at least if dynamic dispatching and access to
400 subprogram values are not used. We will handle these cases separately
401 later.
403 The rule is simple:
405 *If a unit has elaboration code that can directly or
406 indirectly make a call to a subprogram in a |withed| unit, or instantiate
407 a generic package in a |withed| unit,
408 then if the |withed| unit does not have
409 pragma `Pure` or `Preelaborate`, then the client should have
410 a pragma `Elaborate_All`for the |withed| unit.**
412 By following this rule a client is
413 assured that calls can be made without risk of an exception.
415 For generic subprogram instantiations, the rule can be relaxed to
416 require only a pragma `Elaborate` since elaborating the body
417 of a subprogram cannot cause any transitive elaboration (we are
418 not calling the subprogram in this case, just elaborating its
419 declaration).
421 If this rule is not followed, then a program may be in one of four
422 states:
424 * *No order exists*
426   No order of elaboration exists which follows the rules, taking into
427   account any `Elaborate`, `Elaborate_All`,
428   or `Elaborate_Body` pragmas. In
429   this case, an Ada compiler must diagnose the situation at bind
430   time, and refuse to build an executable program.
432 * *One or more orders exist, all incorrect*
434   One or more acceptable elaboration orders exist, and all of them
435   generate an elaboration order problem. In this case, the binder
436   can build an executable program, but `Program_Error` will be raised
437   when the program is run.
439 * *Several orders exist, some right, some incorrect*
441   One or more acceptable elaboration orders exists, and some of them
442   work, and some do not. The programmer has not controlled
443   the order of elaboration, so the binder may or may not pick one of
444   the correct orders, and the program may or may not raise an
445   exception when it is run. This is the worst case, because it means
446   that the program may fail when moved to another compiler, or even
447   another version of the same compiler.
449 * *One or more orders exists, all correct*
451   One ore more acceptable elaboration orders exist, and all of them
452   work. In this case the program runs successfully. This state of
453   affairs can be guaranteed by following the rule we gave above, but
454   may be true even if the rule is not followed.
456 Note that one additional advantage of following our rules on the use
457 of `Elaborate` and `Elaborate_All`
458 is that the program continues to stay in the ideal (all orders OK) state
459 even if maintenance
460 changes some bodies of some units. Conversely, if a program that does
461 not follow this rule happens to be safe at some point, this state of affairs
462 may deteriorate silently as a result of maintenance changes.
464 You may have noticed that the above discussion did not mention
465 the use of `Elaborate_Body`. This was a deliberate omission. If you
466 |with| an `Elaborate_Body` unit, it still may be the case that
467 code in the body makes calls to some other unit, so it is still necessary
468 to use `Elaborate_All` on such units.
471 .. _Controlling_Elaboration_in_GNAT_-_Internal_Calls:
473 Controlling Elaboration in GNAT - Internal Calls
474 ================================================
476 In the case of internal calls, i.e., calls within a single package, the
477 programmer has full control over the order of elaboration, and it is up
478 to the programmer to elaborate declarations in an appropriate order. For
479 example writing:
481 .. code-block:: ada
483      function One return Float;
485      Q : Float := One;
486   
487      function One return Float is
488      begin
489           return 1.0;
490      end One;
491   
492 will obviously raise `Program_Error` at run time, because function
493 One will be called before its body is elaborated. In this case GNAT will
494 generate a warning that the call will raise `Program_Error`::
496      1. procedure y is
497      2.    function One return Float;
498      3.
499      4.    Q : Float := One;
500                         |
501         >>> warning: cannot call "One" before body is elaborated
502         >>> warning: Program_Error will be raised at run time
504      5.
505      6.    function One return Float is
506      7.    begin
507      8.         return 1.0;
508      9.    end One;
509     10.
510     11. begin
511     12.    null;
512     13. end;
513   
515 Note that in this particular case, it is likely that the call is safe, because
516 the function `One` does not access any global variables.
517 Nevertheless in Ada, we do not want the validity of the check to depend on
518 the contents of the body (think about the separate compilation case), so this
519 is still wrong, as we discussed in the previous sections.
521 The error is easily corrected by rearranging the declarations so that the
522 body of `One` appears before the declaration containing the call
523 (note that in Ada 95 as well as later versions of the Ada standard,
524 declarations can appear in any order, so there is no restriction that
525 would prevent this reordering, and if we write:
527 .. code-block:: ada
529      function One return Float;
531      function One return Float is
532      begin
533           return 1.0;
534      end One;
536      Q : Float := One;
538 then all is well, no warning is generated, and no
539 `Program_Error` exception
540 will be raised.
541 Things are more complicated when a chain of subprograms is executed:
543 .. code-block:: ada
545      function A return Integer;
546      function B return Integer;
547      function C return Integer;
549      function B return Integer is begin return A; end;
550      function C return Integer is begin return B; end;
552      X : Integer := C;
554      function A return Integer is begin return 1; end;
556 Now the call to `C`
557 at elaboration time in the declaration of `X` is correct, because
558 the body of `C` is already elaborated,
559 and the call to `B` within the body of
560 `C` is correct, but the call
561 to `A` within the body of `B` is incorrect, because the body
562 of `A` has not been elaborated, so `Program_Error`
563 will be raised on the call to `A`.
564 In this case GNAT will generate a
565 warning that `Program_Error` may be
566 raised at the point of the call. Let's look at the warning::
568      1. procedure x is
569      2.    function A return Integer;
570      3.    function B return Integer;
571      4.    function C return Integer;
572      5.
573      6.    function B return Integer is begin return A; end;
574                                                         |
575         >>> warning: call to "A" before body is elaborated may
576                      raise Program_Error
577         >>> warning: "B" called at line 7
578         >>> warning: "C" called at line 9
580      7.    function C return Integer is begin return B; end;
581      8.
582      9.    X : Integer := C;
583     10.
584     11.    function A return Integer is begin return 1; end;
585     12.
586     13. begin
587     14.    null;
588     15. end;
589   
591 Note that the message here says 'may raise', instead of the direct case,
592 where the message says 'will be raised'. That's because whether
593 `A` is
594 actually called depends in general on run-time flow of control.
595 For example, if the body of `B` said
597 .. code-block:: ada
599      function B return Integer is
600      begin
601         if some-condition-depending-on-input-data then
602            return A;
603         else
604            return 1;
605         end if;
606      end B;
608 then we could not know until run time whether the incorrect call to A would
609 actually occur, so `Program_Error` might
610 or might not be raised. It is possible for a compiler to
611 do a better job of analyzing bodies, to
612 determine whether or not `Program_Error`
613 might be raised, but it certainly
614 couldn't do a perfect job (that would require solving the halting problem
615 and is provably impossible), and because this is a warning anyway, it does
616 not seem worth the effort to do the analysis. Cases in which it
617 would be relevant are rare.
619 In practice, warnings of either of the forms given
620 above will usually correspond to
621 real errors, and should be examined carefully and eliminated.
622 In the rare case where a warning is bogus, it can be suppressed by any of
623 the following methods:
625 * Compile with the *-gnatws* switch set
627 * Suppress `Elaboration_Check` for the called subprogram
629 * Use pragma `Warnings_Off` to turn warnings off for the call
631 For the internal elaboration check case,
632 GNAT by default generates the
633 necessary run-time checks to ensure
634 that `Program_Error` is raised if any
635 call fails an elaboration check. Of course this can only happen if a
636 warning has been issued as described above. The use of pragma
637 `Suppress (Elaboration_Check)` may (but is not guaranteed to) suppress
638 some of these checks, meaning that it may be possible (but is not
639 guaranteed) for a program to be able to call a subprogram whose body
640 is not yet elaborated, without raising a `Program_Error` exception.
643 .. _Controlling_Elaboration_in_GNAT_-_External_Calls:
645 Controlling Elaboration in GNAT - External Calls
646 ================================================
648 The previous section discussed the case in which the execution of a
649 particular thread of elaboration code occurred entirely within a
650 single unit. This is the easy case to handle, because a programmer
651 has direct and total control over the order of elaboration, and
652 furthermore, checks need only be generated in cases which are rare
653 and which the compiler can easily detect.
654 The situation is more complex when separate compilation is taken into account.
655 Consider the following:
657 .. code-block:: ada
659       package Math is
660          function Sqrt (Arg : Float) return Float;
661       end Math;
663       package body Math is
664          function Sqrt (Arg : Float) return Float is
665          begin
666                ...
667          end Sqrt;
668       end Math;
670       with Math;
671       package Stuff is
672          X : Float := Math.Sqrt (0.5);
673       end Stuff;
675       with Stuff;
676       procedure Main is
677       begin
678          ...
679       end Main;
680   
681 where `Main` is the main program. When this program is executed, the
682 elaboration code must first be executed, and one of the jobs of the
683 binder is to determine the order in which the units of a program are
684 to be elaborated. In this case we have four units: the spec and body
685 of `Math`,
686 the spec of `Stuff` and the body of `Main`).
687 In what order should the four separate sections of elaboration code
688 be executed?
690 There are some restrictions in the order of elaboration that the binder
691 can choose. In particular, if unit U has a |with|
692 for a package `X`, then you
693 are assured that the spec of `X`
694 is elaborated before U , but you are
695 not assured that the body of `X`
696 is elaborated before U.
697 This means that in the above case, the binder is allowed to choose the
698 order::
700      spec of Math
701      spec of Stuff
702      body of Math
703      body of Main
705 but that's not good, because now the call to `Math.Sqrt`
706 that happens during
707 the elaboration of the `Stuff`
708 spec happens before the body of `Math.Sqrt` is
709 elaborated, and hence causes `Program_Error` exception to be raised.
710 At first glance, one might say that the binder is misbehaving, because
711 obviously you want to elaborate the body of something you |with| first, but
712 that is not a general rule that can be followed in all cases. Consider
714 .. code-block:: ada
716       package X is ...
718       package Y is ...
720       with X;
721       package body Y is ...
723       with Y;
724       package body X is ...
726 This is a common arrangement, and, apart from the order of elaboration
727 problems that might arise in connection with elaboration code, this works fine.
728 A rule that says that you must first elaborate the body of anything you
729 |with| cannot work in this case:
730 the body of `X` |withs| `Y`,
731 which means you would have to
732 elaborate the body of `Y` first, but that |withs| `X`,
733 which means
734 you have to elaborate the body of `X` first, but ... and we have a
735 loop that cannot be broken.
737 It is true that the binder can in many cases guess an order of elaboration
738 that is unlikely to cause a `Program_Error`
739 exception to be raised, and it tries to do so (in the
740 above example of `Math/Stuff/Spec`, the GNAT binder will
741 by default
742 elaborate the body of `Math` right after its spec, so all will be well).
744 However, a program that blindly relies on the binder to be helpful can
745 get into trouble, as we discussed in the previous sections, so GNAT
746 provides a number of facilities for assisting the programmer in
747 developing programs that are robust with respect to elaboration order.
750 .. _Default_Behavior_in_GNAT_-_Ensuring_Safety:
752 Default Behavior in GNAT - Ensuring Safety
753 ==========================================
755 The default behavior in GNAT ensures elaboration safety. In its
756 default mode GNAT implements the
757 rule we previously described as the right approach. Let's restate it:
759 *If a unit has elaboration code that can directly or indirectly make a
760 call to a subprogram in a |withed| unit, or instantiate a generic
761 package in a |withed| unit, then if the |withed| unit
762 does not have pragma `Pure` or `Preelaborate`, then the client should have an
763 `Elaborate_All` pragma for the |withed| unit.*
765 *In the case of instantiating a generic subprogram, it is always
766 sufficient to have only an `Elaborate` pragma for the
767 |withed| unit.*
769 By following this rule a client is assured that calls and instantiations
770 can be made without risk of an exception.
772 In this mode GNAT traces all calls that are potentially made from
773 elaboration code, and puts in any missing implicit `Elaborate`
774 and `Elaborate_All` pragmas.
775 The advantage of this approach is that no elaboration problems
776 are possible if the binder can find an elaboration order that is
777 consistent with these implicit `Elaborate` and
778 `Elaborate_All` pragmas. The
779 disadvantage of this approach is that no such order may exist.
781 If the binder does not generate any diagnostics, then it means that it has
782 found an elaboration order that is guaranteed to be safe. However, the binder
783 may still be relying on implicitly generated `Elaborate` and
784 `Elaborate_All` pragmas so portability to other compilers than GNAT is not
785 guaranteed.
787 If it is important to guarantee portability, then the compilations should
788 use the *-gnatel*
789 (info messages for elaboration pragmas) switch. This will cause info messages
790 to be generated indicating the missing `Elaborate` and
791 `Elaborate_All` pragmas.
792 Consider the following source program:
794 .. code-block:: ada
796      with k;
797      package j is
798        m : integer := k.r;
799      end;
801 where it is clear that there
802 should be a pragma `Elaborate_All`
803 for unit `k`. An implicit pragma will be generated, and it is
804 likely that the binder will be able to honor it. However, if you want
805 to port this program to some other Ada compiler than GNAT.
806 it is safer to include the pragma explicitly in the source. If this
807 unit is compiled with the *-gnatel*
808 switch, then the compiler outputs an information message::
810      1. with k;
811      2. package j is
812      3.   m : integer := k.r;
813                           |
814         >>> info: call to "r" may raise Program_Error
815         >>> info: missing pragma Elaborate_All for "k"
816    
817      4. end;
819 and these messages can be used as a guide for supplying manually
820 the missing pragmas. It is usually a bad idea to use this
821 option during development. That's because it will tell you when
822 you need to put in a pragma, but cannot tell you when it is time
823 to take it out. So the use of pragma `Elaborate_All` may lead to
824 unnecessary dependencies and even false circularities.
826 This default mode is more restrictive than the Ada Reference
827 Manual, and it is possible to construct programs which will compile
828 using the dynamic model described there, but will run into a
829 circularity using the safer static model we have described.
831 Of course any Ada compiler must be able to operate in a mode
832 consistent with the requirements of the Ada Reference Manual,
833 and in particular must have the capability of implementing the
834 standard dynamic model of elaboration with run-time checks.
836 In GNAT, this standard mode can be achieved either by the use of
837 the *-gnatE* switch on the compiler (*gcc* or
838 *gnatmake*) command, or by the use of the configuration pragma:
840 .. code-block:: ada
842       pragma Elaboration_Checks (DYNAMIC);
843   
844 Either approach will cause the unit affected to be compiled using the
845 standard dynamic run-time elaboration checks described in the Ada
846 Reference Manual. The static model is generally preferable, since it
847 is clearly safer to rely on compile and link time checks rather than
848 run-time checks. However, in the case of legacy code, it may be
849 difficult to meet the requirements of the static model. This
850 issue is further discussed in
851 :ref:`What_to_Do_If_the_Default_Elaboration_Behavior_Fails`.
853 Note that the static model provides a strict subset of the allowed
854 behavior and programs of the Ada Reference Manual, so if you do
855 adhere to the static model and no circularities exist,
856 then you are assured that your program will
857 work using the dynamic model, providing that you remove any
858 pragma Elaborate statements from the source.
861 .. _Treatment_of_Pragma_Elaborate:
863 Treatment of Pragma Elaborate
864 =============================
866 .. index:: Pragma Elaborate
868 The use of `pragma Elaborate`
869 should generally be avoided in Ada 95 and Ada 2005 programs,
870 since there is no guarantee that transitive calls
871 will be properly handled. Indeed at one point, this pragma was placed
872 in Annex J (Obsolescent Features), on the grounds that it is never useful.
874 Now that's a bit restrictive. In practice, the case in which
875 `pragma Elaborate` is useful is when the caller knows that there
876 are no transitive calls, or that the called unit contains all necessary
877 transitive `pragma Elaborate` statements, and legacy code often
878 contains such uses.
880 Strictly speaking the static mode in GNAT should ignore such pragmas,
881 since there is no assurance at compile time that the necessary safety
882 conditions are met. In practice, this would cause GNAT to be incompatible
883 with correctly written Ada 83 code that had all necessary
884 `pragma Elaborate` statements in place. Consequently, we made the
885 decision that GNAT in its default mode will believe that if it encounters
886 a `pragma Elaborate` then the programmer knows what they are doing,
887 and it will trust that no elaboration errors can occur.
889 The result of this decision is two-fold. First to be safe using the
890 static mode, you should remove all `pragma Elaborate` statements.
891 Second, when fixing circularities in existing code, you can selectively
892 use `pragma Elaborate` statements to convince the static mode of
893 GNAT that it need not generate an implicit `pragma Elaborate_All`
894 statement.
896 When using the static mode with *-gnatwl*, any use of
897 `pragma Elaborate` will generate a warning about possible
898 problems.
901 .. _Elaboration_Issues_for_Library_Tasks:
903 Elaboration Issues for Library Tasks
904 ====================================
906 .. index:: Library tasks, elaboration issues
908 .. index:: Elaboration of library tasks
910 In this section we examine special elaboration issues that arise for
911 programs that declare library level tasks.
913 Generally the model of execution of an Ada program is that all units are
914 elaborated, and then execution of the program starts. However, the
915 declaration of library tasks definitely does not fit this model. The
916 reason for this is that library tasks start as soon as they are declared
917 (more precisely, as soon as the statement part of the enclosing package
918 body is reached), that is to say before elaboration
919 of the program is complete. This means that if such a task calls a
920 subprogram, or an entry in another task, the callee may or may not be
921 elaborated yet, and in the standard
922 Reference Manual model of dynamic elaboration checks, you can even
923 get timing dependent Program_Error exceptions, since there can be
924 a race between the elaboration code and the task code.
926 The static model of elaboration in GNAT seeks to avoid all such
927 dynamic behavior, by being conservative, and the conservative
928 approach in this particular case is to assume that all the code
929 in a task body is potentially executed at elaboration time if
930 a task is declared at the library level.
932 This can definitely result in unexpected circularities. Consider
933 the following example
935 .. code-block:: ada
937       package Decls is
938         task Lib_Task is
939            entry Start;
940         end Lib_Task;
942         type My_Int is new Integer;
944         function Ident (M : My_Int) return My_Int;
945       end Decls;
947       with Utils;
948       package body Decls is
949         task body Lib_Task is
950         begin
951            accept Start;
952            Utils.Put_Val (2);
953         end Lib_Task;
955         function Ident (M : My_Int) return My_Int is
956         begin
957            return M;
958         end Ident;
959       end Decls;
961       with Decls;
962       package Utils is
963         procedure Put_Val (Arg : Decls.My_Int);
964       end Utils;
966       with Text_IO;
967       package body Utils is
968         procedure Put_Val (Arg : Decls.My_Int) is
969         begin
970            Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
971         end Put_Val;
972       end Utils;
974       with Decls;
975       procedure Main is
976       begin
977          Decls.Lib_Task.Start;
978       end;
979   
980 If the above example is compiled in the default static elaboration
981 mode, then a circularity occurs. The circularity comes from the call
982 `Utils.Put_Val` in the task body of `Decls.Lib_Task`. Since
983 this call occurs in elaboration code, we need an implicit pragma
984 `Elaborate_All` for `Utils`. This means that not only must
985 the spec and body of `Utils` be elaborated before the body
986 of `Decls`, but also the spec and body of any unit that is
987 |withed| by the body of `Utils` must also be elaborated before
988 the body of `Decls`. This is the transitive implication of
989 pragma `Elaborate_All` and it makes sense, because in general
990 the body of `Put_Val` might have a call to something in a
991 |withed| unit.
993 In this case, the body of Utils (actually its spec) |withs|
994 `Decls`. Unfortunately this means that the body of `Decls`
995 must be elaborated before itself, in case there is a call from the
996 body of `Utils`.
998 Here is the exact chain of events we are worrying about:
1000 * In the body of `Decls` a call is made from within the body of a library
1001   task to a subprogram in the package `Utils`. Since this call may
1002   occur at elaboration time (given that the task is activated at elaboration
1003   time), we have to assume the worst, i.e., that the
1004   call does happen at elaboration time.
1006 * This means that the body and spec of `Util` must be elaborated before
1007   the body of `Decls` so that this call does not cause an access before
1008   elaboration.
1010 * Within the body of `Util`, specifically within the body of
1011   `Util.Put_Val` there may be calls to any unit |withed|
1012   by this package.
1014 * One such |withed| package is package `Decls`, so there
1015   might be a call to a subprogram in `Decls` in `Put_Val`.
1016   In fact there is such a call in this example, but we would have to
1017   assume that there was such a call even if it were not there, since
1018   we are not supposed to write the body of `Decls` knowing what
1019   is in the body of `Utils`; certainly in the case of the
1020   static elaboration model, the compiler does not know what is in
1021   other bodies and must assume the worst.
1023 * This means that the spec and body of `Decls` must also be
1024   elaborated before we elaborate the unit containing the call, but
1025   that unit is `Decls`! This means that the body of `Decls`
1026   must be elaborated before itself, and that's a circularity.
1028 Indeed, if you add an explicit pragma `Elaborate_All` for `Utils` in
1029 the body of `Decls` you will get a true Ada Reference Manual
1030 circularity that makes the program illegal.
1032 In practice, we have found that problems with the static model of
1033 elaboration in existing code often arise from library tasks, so
1034 we must address this particular situation.
1036 Note that if we compile and run the program above, using the dynamic model of
1037 elaboration (that is to say use the *-gnatE* switch),
1038 then it compiles, binds,
1039 links, and runs, printing the expected result of 2. Therefore in some sense
1040 the circularity here is only apparent, and we need to capture
1041 the properties of this program that  distinguish it from other library-level
1042 tasks that have real elaboration problems.
1044 We have four possible answers to this question:
1047 * Use the dynamic model of elaboration.
1049   If we use the *-gnatE* switch, then as noted above, the program works.
1050   Why is this? If we examine the task body, it is apparent that the task cannot
1051   proceed past the
1052   `accept` statement until after elaboration has been completed, because
1053   the corresponding entry call comes from the main program, not earlier.
1054   This is why the dynamic model works here. But that's really giving
1055   up on a precise analysis, and we prefer to take this approach only if we cannot
1056   solve the
1057   problem in any other manner. So let us examine two ways to reorganize
1058   the program to avoid the potential elaboration problem.
1060 * Split library tasks into separate packages.
1062   Write separate packages, so that library tasks are isolated from
1063   other declarations as much as possible. Let us look at a variation on
1064   the above program.
1067   .. code-block:: ada
1069       package Decls1 is
1070         task Lib_Task is
1071            entry Start;
1072         end Lib_Task;
1073       end Decls1;
1075       with Utils;
1076       package body Decls1 is
1077         task body Lib_Task is
1078         begin
1079            accept Start;
1080            Utils.Put_Val (2);
1081         end Lib_Task;
1082       end Decls1;
1084       package Decls2 is
1085         type My_Int is new Integer;
1086         function Ident (M : My_Int) return My_Int;
1087       end Decls2;
1089       with Utils;
1090       package body Decls2 is
1091         function Ident (M : My_Int) return My_Int is
1092         begin
1093            return M;
1094         end Ident;
1095       end Decls2;
1097       with Decls2;
1098       package Utils is
1099         procedure Put_Val (Arg : Decls2.My_Int);
1100       end Utils;
1102       with Text_IO;
1103       package body Utils is
1104         procedure Put_Val (Arg : Decls2.My_Int) is
1105         begin
1106            Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
1107         end Put_Val;
1108       end Utils;
1110       with Decls1;
1111       procedure Main is
1112       begin
1113          Decls1.Lib_Task.Start;
1114       end;
1115     
1117   All we have done is to split `Decls` into two packages, one
1118   containing the library task, and one containing everything else. Now
1119   there is no cycle, and the program compiles, binds, links and executes
1120   using the default static model of elaboration.
1122 * Declare separate task types.
1124   A significant part of the problem arises because of the use of the
1125   single task declaration form. This means that the elaboration of
1126   the task type, and the elaboration of the task itself (i.e., the
1127   creation of the task) happen at the same time. A good rule
1128   of style in Ada is to always create explicit task types. By
1129   following the additional step of placing task objects in separate
1130   packages from the task type declaration, many elaboration problems
1131   are avoided. Here is another modified example of the example program:
1133   .. code-block:: ada
1135       package Decls is
1136         task type Lib_Task_Type is
1137            entry Start;
1138         end Lib_Task_Type;
1140         type My_Int is new Integer;
1142         function Ident (M : My_Int) return My_Int;
1143       end Decls;
1145       with Utils;
1146       package body Decls is
1147         task body Lib_Task_Type is
1148         begin
1149            accept Start;
1150            Utils.Put_Val (2);
1151         end Lib_Task_Type;
1153         function Ident (M : My_Int) return My_Int is
1154         begin
1155            return M;
1156         end Ident;
1157       end Decls;
1159       with Decls;
1160       package Utils is
1161         procedure Put_Val (Arg : Decls.My_Int);
1162       end Utils;
1164       with Text_IO;
1165       package body Utils is
1166         procedure Put_Val (Arg : Decls.My_Int) is
1167         begin
1168            Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
1169         end Put_Val;
1170       end Utils;
1172       with Decls;
1173       package Declst is
1174          Lib_Task : Decls.Lib_Task_Type;
1175       end Declst;
1177       with Declst;
1178       procedure Main is
1179       begin
1180          Declst.Lib_Task.Start;
1181       end;
1182     
1184   What we have done here is to replace the `task` declaration in
1185   package `Decls` with a `task type` declaration. Then we
1186   introduce a separate package `Declst` to contain the actual
1187   task object. This separates the elaboration issues for
1188   the `task type`
1189   declaration, which causes no trouble, from the elaboration issues
1190   of the task object, which is also unproblematic, since it is now independent
1191   of the elaboration of  `Utils`.
1192   This separation of concerns also corresponds to
1193   a generally sound engineering principle of separating declarations
1194   from instances. This version of the program also compiles, binds, links,
1195   and executes, generating the expected output.
1197 .. index:: No_Entry_Calls_In_Elaboration_Code restriction
1199 * Use No_Entry_Calls_In_Elaboration_Code restriction.
1201   The previous two approaches described how a program can be restructured
1202   to avoid the special problems caused by library task bodies. in practice,
1203   however, such restructuring may be difficult to apply to existing legacy code,
1204   so we must consider solutions that do not require massive rewriting.
1206   Let us consider more carefully why our original sample program works
1207   under the dynamic model of elaboration. The reason is that the code
1208   in the task body blocks immediately on the `accept`
1209   statement. Now of course there is nothing to prohibit elaboration
1210   code from making entry calls (for example from another library level task),
1211   so we cannot tell in isolation that
1212   the task will not execute the accept statement  during elaboration.
1214   However, in practice it is very unusual to see elaboration code
1215   make any entry calls, and the pattern of tasks starting
1216   at elaboration time and then immediately blocking on `accept` or
1217   `select` statements is very common. What this means is that
1218   the compiler is being too pessimistic when it analyzes the
1219   whole package body as though it might be executed at elaboration
1220   time.
1222   If we know that the elaboration code contains no entry calls, (a very safe
1223   assumption most of the time, that could almost be made the default
1224   behavior), then we can compile all units of the program under control
1225   of the following configuration pragma:
1227   .. code-block:: ada
1229       pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
1230     
1231   This pragma can be placed in the :file:`gnat.adc` file in the usual
1232   manner. If we take our original unmodified program and compile it
1233   in the presence of a :file:`gnat.adc` containing the above pragma,
1234   then once again, we can compile, bind, link, and execute, obtaining
1235   the expected result. In the presence of this pragma, the compiler does
1236   not trace calls in a task body, that appear after the first `accept`
1237   or `select` statement, and therefore does not report a potential
1238   circularity in the original program.
1240   The compiler will check to the extent it can that the above
1241   restriction is not violated, but it is not always possible to do a
1242   complete check at compile time, so it is important to use this
1243   pragma only if the stated restriction is in fact met, that is to say
1244   no task receives an entry call before elaboration of all units is completed.
1247 .. _Mixing_Elaboration_Models:
1249 Mixing Elaboration Models
1250 =========================
1252 So far, we have assumed that the entire program is either compiled
1253 using the dynamic model or static model, ensuring consistency. It
1254 is possible to mix the two models, but rules have to be followed
1255 if this mixing is done to ensure that elaboration checks are not
1256 omitted.
1258 The basic rule is that
1259 **a unit compiled with the static model cannot
1260 be |withed| by a unit compiled with the dynamic model**.
1261 The reason for this is that in the static model, a unit assumes that
1262 its clients guarantee to use (the equivalent of) pragma
1263 `Elaborate_All` so that no elaboration checks are required
1264 in inner subprograms, and this assumption is violated if the
1265 client is compiled with dynamic checks.
1267 The precise rule is as follows. A unit that is compiled with dynamic
1268 checks can only |with| a unit that meets at least one of the
1269 following criteria:
1272 * The |withed| unit is itself compiled with dynamic elaboration
1273   checks (that is with the *-gnatE* switch.
1275 * The |withed| unit is an internal GNAT implementation unit from
1276   the System, Interfaces, Ada, or GNAT hierarchies.
1278 * The |withed| unit has pragma Preelaborate or pragma Pure.
1280 * The |withing| unit (that is the client) has an explicit pragma
1281   `Elaborate_All` for the |withed| unit.
1284 If this rule is violated, that is if a unit with dynamic elaboration
1285 checks |withs| a unit that does not meet one of the above four
1286 criteria, then the binder (`gnatbind`) will issue a warning
1287 similar to that in the following example::
1289      warning: "x.ads" has dynamic elaboration checks and with's
1290      warning:   "y.ads" which has static elaboration checks
1292 These warnings indicate that the rule has been violated, and that as a result
1293 elaboration checks may be missed in the resulting executable file.
1294 This warning may be suppressed using the *-ws* binder switch
1295 in the usual manner.
1297 One useful application of this mixing rule is in the case of a subsystem
1298 which does not itself |with| units from the remainder of the
1299 application. In this case, the entire subsystem can be compiled with
1300 dynamic checks to resolve a circularity in the subsystem, while
1301 allowing the main application that uses this subsystem to be compiled
1302 using the more reliable default static model.
1305 .. _What_to_Do_If_the_Default_Elaboration_Behavior_Fails:
1307 What to Do If the Default Elaboration Behavior Fails
1308 ====================================================
1310 If the binder cannot find an acceptable order, it outputs detailed
1311 diagnostics. For example::
1313      error: elaboration circularity detected
1314      info:   "proc (body)" must be elaborated before "pack (body)"
1315      info:     reason: Elaborate_All probably needed in unit "pack (body)"
1316      info:     recompile "pack (body)" with -gnatel
1317      info:                             for full details
1318      info:       "proc (body)"
1319      info:         is needed by its spec:
1320      info:       "proc (spec)"
1321      info:         which is withed by:
1322      info:       "pack (body)"
1323      info:  "pack (body)" must be elaborated before "proc (body)"
1324      info:     reason: pragma Elaborate in unit "proc (body)"
1326 In this case we have a cycle that the binder cannot break. On the one
1327 hand, there is an explicit pragma Elaborate in `proc` for
1328 `pack`. This means that the body of `pack` must be elaborated
1329 before the body of `proc`. On the other hand, there is elaboration
1330 code in `pack` that calls a subprogram in `proc`. This means
1331 that for maximum safety, there should really be a pragma
1332 Elaborate_All in `pack` for `proc` which would require that
1333 the body of `proc` be elaborated before the body of
1334 `pack`. Clearly both requirements cannot be satisfied.
1335 Faced with a circularity of this kind, you have three different options.
1338 * *Fix the program*
1340   The most desirable option from the point of view of long-term maintenance
1341   is to rearrange the program so that the elaboration problems are avoided.
1342   One useful technique is to place the elaboration code into separate
1343   child packages. Another is to move some of the initialization code to
1344   explicitly called subprograms, where the program controls the order
1345   of initialization explicitly. Although this is the most desirable option,
1346   it may be impractical and involve too much modification, especially in
1347   the case of complex legacy code.
1349 * *Perform dynamic checks*
1351   If the compilations are done using the *-gnatE*
1352   (dynamic elaboration check) switch, then GNAT behaves in a quite different
1353   manner. Dynamic checks are generated for all calls that could possibly result
1354   in raising an exception. With this switch, the compiler does not generate
1355   implicit `Elaborate` or `Elaborate_All` pragmas. The behavior then is
1356   exactly as specified in the :title:`Ada Reference Manual`.
1357   The binder will generate
1358   an executable program that may or may not raise `Program_Error`, and then
1359   it is the programmer's job to ensure that it does not raise an exception. Note
1360   that it is important to compile all units with the switch, it cannot be used
1361   selectively.
1363 * *Suppress checks*
1365   The drawback of dynamic checks is that they generate a
1366   significant overhead at run time, both in space and time. If you
1367   are absolutely sure that your program cannot raise any elaboration
1368   exceptions, and you still want to use the dynamic elaboration model,
1369   then you can use the configuration pragma
1370   `Suppress (Elaboration_Check)` to suppress all such checks. For
1371   example this pragma could be placed in the :file:`gnat.adc` file.
1373 * *Suppress checks selectively*
1375   When you know that certain calls or instantiations in elaboration code cannot
1376   possibly lead to an elaboration error, and the binder nevertheless complains
1377   about implicit `Elaborate` and `Elaborate_All` pragmas that lead to
1378   elaboration circularities, it is possible to remove those warnings locally and
1379   obtain a program that will bind. Clearly this can be unsafe, and it is the
1380   responsibility of the programmer to make sure that the resulting program has no
1381   elaboration anomalies. The pragma `Suppress (Elaboration_Check)` can be
1382   used with different granularity to suppress warnings and break elaboration
1383   circularities:
1385   * Place the pragma that names the called subprogram in the declarative part
1386     that contains the call.
1388   * Place the pragma in the declarative part, without naming an entity. This
1389     disables warnings on all calls in the corresponding  declarative region.
1391   * Place the pragma in the package spec that declares the called subprogram,
1392     and name the subprogram. This disables warnings on all elaboration calls to
1393     that subprogram.
1395   * Place the pragma in the package spec that declares the called subprogram,
1396     without naming any entity. This disables warnings on all elaboration calls to
1397     all subprograms declared in this spec.
1399   * Use Pragma Elaborate.
1401     As previously described in section :ref:`Treatment_of_Pragma_Elaborate`,
1402     GNAT in static mode assumes that a `pragma` Elaborate indicates correctly
1403     that no elaboration checks are required on calls to the designated unit.
1404     There may be cases in which the caller knows that no transitive calls
1405     can occur, so that a `pragma Elaborate` will be sufficient in a
1406     case where `pragma Elaborate_All` would cause a circularity.
1408   These five cases are listed in order of decreasing safety, and therefore
1409   require increasing programmer care in their application. Consider the
1410   following program:
1412   .. code-block:: ada
1414         package Pack1 is
1415           function F1 return Integer;
1416           X1 : Integer;
1417         end Pack1;
1419         package Pack2 is
1420           function F2 return Integer;
1421           function Pure (x : integer) return integer;
1422           --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
1423           --  pragma Suppress (Elaboration_Check);              -- (4)
1424         end Pack2;
1426         with Pack2;
1427         package body Pack1 is
1428           function F1 return Integer is
1429           begin
1430             return 100;
1431           end F1;
1432           Val : integer := Pack2.Pure (11);    --  Elab. call (1)
1433         begin
1434           declare
1435             --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
1436             --  pragma Suppress(Elaboration_Check);             -- (2)
1437           begin
1438             X1 := Pack2.F2 + 1;                --  Elab. call (2)
1439           end;
1440         end Pack1;
1442         with Pack1;
1443         package body Pack2 is
1444           function F2 return Integer is
1445           begin
1446              return Pack1.F1;
1447           end F2;
1448           function Pure (x : integer) return integer is
1449           begin
1450              return x ** 3 - 3 * x;
1451           end;
1452         end Pack2;
1454         with Pack1, Ada.Text_IO;
1455         procedure Proc3 is
1456         begin
1457           Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
1458         end Proc3;
1459     
1460   In the absence of any pragmas, an attempt to bind this program produces
1461   the following diagnostics::
1463        error: elaboration circularity detected
1464        info:    "pack1 (body)" must be elaborated before "pack1 (body)"
1465        info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
1466        info:       recompile "pack1 (body)" with -gnatel for full details
1467        info:          "pack1 (body)"
1468        info:             must be elaborated along with its spec:
1469        info:          "pack1 (spec)"
1470        info:             which is withed by:
1471        info:          "pack2 (body)"
1472        info:             which must be elaborated along with its spec:
1473        info:          "pack2 (spec)"
1474        info:             which is withed by:
1475        info:          "pack1 (body)"
1476     
1477   The sources of the circularity are the two calls to `Pack2.Pure` and
1478   `Pack2.F2` in the body of `Pack1`. We can see that the call to
1479   F2 is safe, even though F2 calls F1, because the call appears after the
1480   elaboration of the body of F1. Therefore the pragma (1) is safe, and will
1481   remove the warning on the call. It is also possible to use pragma (2)
1482   because there are no other potentially unsafe calls in the block.
1484   The call to `Pure` is safe because this function does not depend on the
1485   state of `Pack2`. Therefore any call to this function is safe, and it
1486   is correct to place pragma (3) in the corresponding package spec.
1488   Finally, we could place pragma (4) in the spec of `Pack2` to disable
1489   warnings on all calls to functions declared therein. Note that this is not
1490   necessarily safe, and requires more detailed examination of the subprogram
1491   bodies involved. In particular, a call to `F2` requires that `F1`
1492   be already elaborated.
1494 It is hard to generalize on which of these four approaches should be
1495 taken. Obviously if it is possible to fix the program so that the default
1496 treatment works, this is preferable, but this may not always be practical.
1497 It is certainly simple enough to use *-gnatE*
1498 but the danger in this case is that, even if the GNAT binder
1499 finds a correct elaboration order, it may not always do so,
1500 and certainly a binder from another Ada compiler might not. A
1501 combination of testing and analysis (for which the
1502 information messages generated with the *-gnatel*
1503 switch can be useful) must be used to ensure that the program is free
1504 of errors. One switch that is useful in this testing is the
1505 *-p (pessimistic elaboration order)* switch for `gnatbind`.
1506 Normally the binder tries to find an order that has the best chance
1507 of avoiding elaboration problems. However, if this switch is used, the binder
1508 plays a devil's advocate role, and tries to choose the order that
1509 has the best chance of failing. If your program works even with this
1510 switch, then it has a better chance of being error free, but this is still
1511 not a guarantee.
1513 For an example of this approach in action, consider the C-tests (executable
1514 tests) from the ACATS suite. If these are compiled and run with the default
1515 treatment, then all but one of them succeed without generating any error
1516 diagnostics from the binder. However, there is one test that fails, and
1517 this is not surprising, because the whole point of this test is to ensure
1518 that the compiler can handle cases where it is impossible to determine
1519 a correct order statically, and it checks that an exception is indeed
1520 raised at run time.
1522 This one test must be compiled and run using the *-gnatE*
1523 switch, and then it passes. Alternatively, the entire suite can
1524 be run using this switch. It is never wrong to run with the dynamic
1525 elaboration switch if your code is correct, and we assume that the
1526 C-tests are indeed correct (it is less efficient, but efficiency is
1527 not a factor in running the ACATS tests.)
1530 .. _Elaboration_for_Indirect_Calls:
1532 Elaboration for Indirect Calls
1533 ==============================
1535 .. index:: Dispatching calls
1536 .. index:: Indirect calls
1538 In rare cases, the static elaboration model fails to prevent
1539 dispatching calls to not-yet-elaborated subprograms. In such cases, we
1540 fall back to run-time checks; premature calls to any primitive
1541 operation of a tagged type before the body of the operation has been
1542 elaborated will raise `Program_Error`.
1544 Access-to-subprogram types, however, are handled conservatively, and
1545 do not require run-time checks. This was not true in earlier versions
1546 of the compiler; you can use the *-gnatd.U* debug switch to
1547 revert to the old behavior if the new conservative behavior causes
1548 elaboration cycles. Here, 'conservative' means that if you do
1549 `P'Access` during elaboration, the compiler will assume that you
1550 might call `P` indirectly during elaboration, so it adds an
1551 implicit `pragma Elaborate_All` on the library unit containing
1552 `P`. The *-gnatd.U* switch is safe if you know there are
1553 no such calls. If the program worked before, it will continue to work
1554 with *-gnatd.U*. But beware that code modifications such as
1555 adding an indirect call can cause erroneous behavior in the presence
1556 of *-gnatd.U*.
1559 .. _Summary_of_Procedures_for_Elaboration_Control:
1561 Summary of Procedures for Elaboration Control
1562 =============================================
1564 .. index:: Elaboration control
1566 First, compile your program with the default options, using none of
1567 the special elaboration control switches. If the binder successfully
1568 binds your program, then you can be confident that, apart from issues
1569 raised by the use of access-to-subprogram types and dynamic dispatching,
1570 the program is free of elaboration errors. If it is important that the
1571 program be portable to other compilers than GNAT, then use the
1572 *-gnatel*
1573 switch to generate messages about missing `Elaborate` or
1574 `Elaborate_All` pragmas, and supply the missing pragmas.
1576 If the program fails to bind using the default static elaboration
1577 handling, then you can fix the program to eliminate the binder
1578 message, or recompile the entire program with the
1579 *-gnatE* switch to generate dynamic elaboration checks,
1580 and, if you are sure there really are no elaboration problems,
1581 use a global pragma `Suppress (Elaboration_Check)`.
1584 .. _Other_Elaboration_Order_Considerations:
1586 Other Elaboration Order Considerations
1587 ======================================
1589 This section has been entirely concerned with the issue of finding a valid
1590 elaboration order, as defined by the Ada Reference Manual. In a case
1591 where several elaboration orders are valid, the task is to find one
1592 of the possible valid elaboration orders (and the static model in GNAT
1593 will ensure that this is achieved).
1595 The purpose of the elaboration rules in the Ada Reference Manual is to
1596 make sure that no entity is accessed before it has been elaborated. For
1597 a subprogram, this means that the spec and body must have been elaborated
1598 before the subprogram is called. For an object, this means that the object
1599 must have been elaborated before its value is read or written. A violation
1600 of either of these two requirements is an access before elaboration order,
1601 and this section has been all about avoiding such errors.
1603 In the case where more than one order of elaboration is possible, in the
1604 sense that access before elaboration errors are avoided, then any one of
1605 the orders is 'correct' in the sense that it meets the requirements of
1606 the Ada Reference Manual, and no such error occurs.
1608 However, it may be the case for a given program, that there are
1609 constraints on the order of elaboration that come not from consideration
1610 of avoiding elaboration errors, but rather from extra-lingual logic
1611 requirements. Consider this example:
1613 .. code-block:: ada
1615      with Init_Constants;
1616      package Constants is
1617         X : Integer := 0;
1618         Y : Integer := 0;
1619      end Constants;
1621      package Init_Constants is
1622         procedure P; --* require a body*
1623      end Init_Constants;
1625      with Constants;
1626      package body Init_Constants is
1627         procedure P is begin null; end;
1628      begin
1629         Constants.X := 3;
1630         Constants.Y := 4;
1631      end Init_Constants;
1633      with Constants;
1634      package Calc is
1635         Z : Integer := Constants.X + Constants.Y;
1636      end Calc;
1638      with Calc;
1639      with Text_IO; use Text_IO;
1640      procedure Main is
1641      begin
1642         Put_Line (Calc.Z'Img);
1643      end Main;
1644   
1645 In this example, there is more than one valid order of elaboration. For
1646 example both the following are correct orders::
1648      Init_Constants spec
1649      Constants spec
1650      Calc spec
1651      Init_Constants body
1652      Main body
1657   
1658     Init_Constants spec
1659     Init_Constants body
1660     Constants spec
1661     Calc spec
1662     Main body
1663   
1664 There is no language rule to prefer one or the other, both are correct
1665 from an order of elaboration point of view. But the programmatic effects
1666 of the two orders are very different. In the first, the elaboration routine
1667 of `Calc` initializes `Z` to zero, and then the main program
1668 runs with this value of zero. But in the second order, the elaboration
1669 routine of `Calc` runs after the body of Init_Constants has set
1670 `X` and `Y` and thus `Z` is set to 7 before `Main` runs.
1672 One could perhaps by applying pretty clever non-artificial intelligence
1673 to the situation guess that it is more likely that the second order of
1674 elaboration is the one desired, but there is no formal linguistic reason
1675 to prefer one over the other. In fact in this particular case, GNAT will
1676 prefer the second order, because of the rule that bodies are elaborated
1677 as soon as possible, but it's just luck that this is what was wanted
1678 (if indeed the second order was preferred).
1680 If the program cares about the order of elaboration routines in a case like
1681 this, it is important to specify the order required. In this particular
1682 case, that could have been achieved by adding to the spec of Calc:
1684 .. code-block:: ada
1686      pragma Elaborate_All (Constants);
1687   
1688 which requires that the body (if any) and spec of `Constants`,
1689 as well as the body and spec of any unit |withed| by
1690 `Constants` be elaborated before `Calc` is elaborated.
1692 Clearly no automatic method can always guess which alternative you require,
1693 and if you are working with legacy code that had constraints of this kind
1694 which were not properly specified by adding `Elaborate` or
1695 `Elaborate_All` pragmas, then indeed it is possible that two different
1696 compilers can choose different orders.
1698 However, GNAT does attempt to diagnose the common situation where there
1699 are uninitialized variables in the visible part of a package spec, and the
1700 corresponding package body has an elaboration block that directly or
1701 indirectly initialized one or more of these variables. This is the situation
1702 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
1703 a warning that suggests this addition if it detects this situation.
1705 The `gnatbind` *-p* switch may be useful in smoking
1706 out problems. This switch causes bodies to be elaborated as late as possible
1707 instead of as early as possible. In the example above, it would have forced
1708 the choice of the first elaboration order. If you get different results
1709 when using this switch, and particularly if one set of results is right,
1710 and one is wrong as far as you are concerned, it shows that you have some
1711 missing `Elaborate` pragmas. For the example above, we have the
1712 following output:
1714 .. code-block:: sh
1716      $ gnatmake -f -q main
1717      $ main
1718       7
1719      $ gnatmake -f -q main -bargs -p
1720      $ main
1721       0
1722   
1723 It is of course quite unlikely that both these results are correct, so
1724 it is up to you in a case like this to investigate the source of the
1725 difference, by looking at the two elaboration orders that are chosen,
1726 and figuring out which is correct, and then adding the necessary
1727 `Elaborate` or `Elaborate_All` pragmas to ensure the desired order.
1730 .. _Determining_the_Chosen_Elaboration_Order:
1732 Determining the Chosen Elaboration Order
1733 ========================================
1735 To see the elaboration order that the binder chooses, you can look at
1736 the last part of the file:`b~xxx.adb` binder output file. Here is an example::
1738      System.Soft_Links'Elab_Body;
1739      E14 := True;
1740      System.Secondary_Stack'Elab_Body;
1741      E18 := True;
1742      System.Exception_Table'Elab_Body;
1743      E24 := True;
1744      Ada.Io_Exceptions'Elab_Spec;
1745      E67 := True;
1746      Ada.Tags'Elab_Spec;
1747      Ada.Streams'Elab_Spec;
1748      E43 := True;
1749      Interfaces.C'Elab_Spec;
1750      E69 := True;
1751      System.Finalization_Root'Elab_Spec;
1752      E60 := True;
1753      System.Os_Lib'Elab_Body;
1754      E71 := True;
1755      System.Finalization_Implementation'Elab_Spec;
1756      System.Finalization_Implementation'Elab_Body;
1757      E62 := True;
1758      Ada.Finalization'Elab_Spec;
1759      E58 := True;
1760      Ada.Finalization.List_Controller'Elab_Spec;
1761      E76 := True;
1762      System.File_Control_Block'Elab_Spec;
1763      E74 := True;
1764      System.File_Io'Elab_Body;
1765      E56 := True;
1766      Ada.Tags'Elab_Body;
1767      E45 := True;
1768      Ada.Text_Io'Elab_Spec;
1769      Ada.Text_Io'Elab_Body;
1770      E07 := True;
1771   
1772 Here Elab_Spec elaborates the spec
1773 and Elab_Body elaborates the body. The assignments to the :samp:`E{xx}` flags
1774 flag that the corresponding body is now elaborated.
1776 You can also ask the binder to generate a more
1777 readable list of the elaboration order using the
1778 `-l` switch when invoking the binder. Here is
1779 an example of the output generated by this switch::
1781      ada (spec)
1782      interfaces (spec)
1783      system (spec)
1784      system.case_util (spec)
1785      system.case_util (body)
1786      system.concat_2 (spec)
1787      system.concat_2 (body)
1788      system.concat_3 (spec)
1789      system.concat_3 (body)
1790      system.htable (spec)
1791      system.parameters (spec)
1792      system.parameters (body)
1793      system.crtl (spec)
1794      interfaces.c_streams (spec)
1795      interfaces.c_streams (body)
1796      system.restrictions (spec)
1797      system.restrictions (body)
1798      system.standard_library (spec)
1799      system.exceptions (spec)
1800      system.exceptions (body)
1801      system.storage_elements (spec)
1802      system.storage_elements (body)
1803      system.secondary_stack (spec)
1804      system.stack_checking (spec)
1805      system.stack_checking (body)
1806      system.string_hash (spec)
1807      system.string_hash (body)
1808      system.htable (body)
1809      system.strings (spec)
1810      system.strings (body)
1811      system.traceback (spec)
1812      system.traceback (body)
1813      system.traceback_entries (spec)
1814      system.traceback_entries (body)
1815      ada.exceptions (spec)
1816      ada.exceptions.last_chance_handler (spec)
1817      system.soft_links (spec)
1818      system.soft_links (body)
1819      ada.exceptions.last_chance_handler (body)
1820      system.secondary_stack (body)
1821      system.exception_table (spec)
1822      system.exception_table (body)
1823      ada.io_exceptions (spec)
1824      ada.tags (spec)
1825      ada.streams (spec)
1826      interfaces.c (spec)
1827      interfaces.c (body)
1828      system.finalization_root (spec)
1829      system.finalization_root (body)
1830      system.memory (spec)
1831      system.memory (body)
1832      system.standard_library (body)
1833      system.os_lib (spec)
1834      system.os_lib (body)
1835      system.unsigned_types (spec)
1836      system.stream_attributes (spec)
1837      system.stream_attributes (body)
1838      system.finalization_implementation (spec)
1839      system.finalization_implementation (body)
1840      ada.finalization (spec)
1841      ada.finalization (body)
1842      ada.finalization.list_controller (spec)
1843      ada.finalization.list_controller (body)
1844      system.file_control_block (spec)
1845      system.file_io (spec)
1846      system.file_io (body)
1847      system.val_uns (spec)
1848      system.val_util (spec)
1849      system.val_util (body)
1850      system.val_uns (body)
1851      system.wch_con (spec)
1852      system.wch_con (body)
1853      system.wch_cnv (spec)
1854      system.wch_jis (spec)
1855      system.wch_jis (body)
1856      system.wch_cnv (body)
1857      system.wch_stw (spec)
1858      system.wch_stw (body)
1859      ada.tags (body)
1860      ada.exceptions (body)
1861      ada.text_io (spec)
1862      ada.text_io (body)
1863      text_io (spec)
1864      gdbstr (body)