1.. |with| replace:: *with*
2.. |withs| replace:: *with*\ s
3.. |withed| replace:: *with*\ ed
4.. |withing| replace:: *with*\ ing
5
6.. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7
8
9.. _Elaboration_Order_Handling_in_GNAT:
10
11**********************************
12Elaboration Order Handling in GNAT
13**********************************
14
15.. index:: Order of elaboration
16.. index:: Elaboration control
17
18This appendix describes the handling of elaboration code in Ada and
19in GNAT, and discusses how the order of elaboration of program units can
20be controlled in GNAT, either automatically or with explicit programming
21features.
22
23.. _Elaboration_Code:
24
25Elaboration Code
26================
27
28Ada provides rather general mechanisms for executing code at elaboration
29time, that is to say before the main program starts executing. Such code arises
30in three contexts:
31
32* *Initializers for variables*
33
34  Variables declared at the library level, in package specs or bodies, can
35  require initialization that is performed at elaboration time, as in:
36
37  .. code-block:: ada
38
39       Sqrt_Half : Float := Sqrt (0.5);
40
41* *Package initialization code*
42
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.
45
46* *Library level task allocators*
47
48  Tasks that are declared using task allocators at the library level
49  start executing immediately and hence can execute at elaboration time.
50
51Subprogram calls are possible in any of these contexts, which means that
52any arbitrary part of the program may be executed as part of the elaboration
53code. It is even possible to write a program which does all its work at
54elaboration time, with a null main program, although stylistically this
55would usually be considered an inappropriate way to structure
56a program.
57
58An important concern arises in the context of elaboration code:
59we have to be sure that it is executed in an appropriate order. What we
60have is a series of elaboration code sections, potentially one section
61for each unit in the program. It is important that these execute
62in the correct order. Correctness here means that, taking the above
63example of the declaration of `Sqrt_Half`,
64if some other piece of
65elaboration code references `Sqrt_Half`,
66then it must run after the
67section of elaboration code that contains the declaration of
68`Sqrt_Half`.
69
70There would never be any order of elaboration problem if we made a rule
71that whenever you |with| a unit, you must elaborate both the spec and body
72of that unit before elaborating the unit doing the |withing|:
73
74.. code-block:: ada
75
76     with Unit_1;
77     package Unit_2 is ...
78
79would require that both the body and spec of `Unit_1` be elaborated
80before the spec of `Unit_2`. However, a rule like that would be far too
81restrictive. In particular, it would make it impossible to have routines
82in separate packages that were mutually recursive.
83
84You might think that a clever enough compiler could look at the actual
85elaboration code and determine an appropriate correct order of elaboration,
86but in the general case, this is not possible. Consider the following
87example.
88
89In the body of `Unit_1`, we have a procedure `Func_1`
90that references
91the variable `Sqrt_1`, which is declared in the elaboration code
92of the body of `Unit_1`:
93
94.. code-block:: ada
95
96     Sqrt_1 : Float := Sqrt (0.1);
97
98The elaboration code of the body of `Unit_1` also contains:
99
100.. code-block:: ada
101
102     if expression_1 = 1 then
103        Q := Unit_2.Func_2;
104     end if;
105
106`Unit_2` is exactly parallel,
107it has a procedure `Func_2` that references
108the variable `Sqrt_2`, which is declared in the elaboration code of
109the body `Unit_2`:
110
111.. code-block:: ada
112
113      Sqrt_2 : Float := Sqrt (0.1);
114
115The elaboration code of the body of `Unit_2` also contains:
116
117.. code-block:: ada
118
119     if expression_2 = 2 then
120        Q := Unit_1.Func_1;
121     end if;
122
123Now the question is, which of the following orders of elaboration is
124acceptable:
125
126::
127
128     Spec of Unit_1
129     Spec of Unit_2
130     Body of Unit_1
131     Body of Unit_2
132
133or
134
135::
136
137     Spec of Unit_2
138     Spec of Unit_1
139     Body of Unit_2
140     Body of Unit_1
141
142If you carefully analyze the flow here, you will see that you cannot tell
143at compile time the answer to this question.
144If `expression_1` is not equal to 1,
145and `expression_2` is not equal to 2,
146then either order is acceptable, because neither of the function calls is
147executed. If both tests evaluate to true, then neither order is acceptable
148and in fact there is no correct order.
149
150If one of the two expressions is true, and the other is false, then one
151of the above orders is correct, and the other is incorrect. For example,
152if `expression_1` /= 1 and `expression_2` = 2,
153then the call to `Func_1`
154will occur, but not the call to `Func_2.`
155This means that it is essential
156to elaborate the body of `Unit_1` before
157the body of `Unit_2`, so the first
158order of elaboration is correct and the second is wrong.
159
160By making `expression_1` and `expression_2`
161depend on input data, or perhaps
162the time of day, we can make it impossible for the compiler or binder
163to figure out which of these expressions will be true, and hence it
164is impossible to guarantee a safe order of elaboration at run time.
165
166.. _Checking_the_Elaboration_Order:
167
168Checking the Elaboration Order
169==============================
170
171In some languages that involve the same kind of elaboration problems,
172e.g., Java and C++, the programmer needs to take these
173ordering problems into account, and it is common to
174write a program in which an incorrect elaboration order  gives
175surprising results, because it references variables before they
176are initialized.
177Ada is designed to be a safe language, and a programmer-beware approach is
178clearly not sufficient. Consequently, the language provides three lines
179of defense:
180
181* *Standard rules*
182
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.
188
189.. index:: Elaboration checks
190.. index:: Checks, elaboration
191
192* *Dynamic elaboration checks*
193
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.
197
198* *Elaboration control*
199
200  Facilities are provided for the programmer to specify the desired order
201  of elaboration.
202
203Let's look at these facilities in more detail. First, the rules for
204dynamic checking. One possible rule would be simply to say that the
205exception is raised if you access a variable which has not yet been
206elaborated. The trouble with this approach is that it could require
207expensive checks on every variable reference. Instead Ada has two
208rules which are a little more restrictive, but easier to check, and
209easier to state:
210
211* *Restrictions on calls*
212
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.
218
219* *Restrictions on instantiations*
220
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.
226
227The idea is that if the body has been elaborated, then any variables
228it references must have been elaborated; by checking for the body being
229elaborated we guarantee that none of its references causes any
230trouble. As we noted above, this is a little too restrictive, because a
231subprogram that has no non-local references in its body may in fact be safe
232to call. However, it really would be unsafe to rely on this, because
233it would mean that the caller was aware of details of the implementation
234in the body. This goes against the basic tenets of Ada.
235
236A plausible implementation can be described as follows.
237A Boolean variable is associated with each subprogram
238and each generic unit. This variable is initialized to False, and is set to
239True at the point body is elaborated. Every call or instantiation checks the
240variable, and raises `Program_Error` if the variable is False.
241
242Note that one might think that it would be good enough to have one Boolean
243variable for each package, but that would not deal with cases of trying
244to call a body in the same package as the call
245that has not been elaborated yet.
246Of course a compiler may be able to do enough analysis to optimize away
247some of the Boolean variables as unnecessary, and `GNAT` indeed
248does such optimizations, but still the easiest conceptual model is to
249think of there being one variable per subprogram.
250
251.. _Controlling_the_Elaboration_Order:
252
253Controlling the Elaboration Order
254=================================
255
256In the previous section we discussed the rules in Ada which ensure
257that `Program_Error` is raised if an incorrect elaboration order is
258chosen. This prevents erroneous executions, but we need mechanisms to
259specify a correct execution and avoid the exception altogether.
260To achieve this, Ada provides a number of features for controlling
261the order of elaboration. We discuss these features in this section.
262
263First, there are several ways of indicating to the compiler that a given
264unit has no elaboration problems:
265
266* *packages that do not require a body*
267
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:
271
272  .. code-block:: ada
273
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;
282
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
286
287.. index:: pragma Pure
288
289* *pragma Pure*
290
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.
297
298.. index:: pragma Preelaborate
299
300* *pragma Preelaborate*
301
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.
306
307.. index:: pragma Elaborate_Body
308
309* *pragma Elaborate_Body*
310
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.
320
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::
329
330       Spec of Unit_2
331       Spec of Unit_1
332       Body of Unit_1
333       Body of Unit_2
334
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.
342
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.
350
351The above pragmas allow a server to guarantee safe use by clients, and
352clearly this is the preferable approach. Consequently a good rule
353is to mark units as `Pure` or `Preelaborate` if possible,
354and if this is not possible,
355mark them as `Elaborate_Body` if possible.
356As we have seen, there are situations where neither of these
357three pragmas can be used.
358So we also provide methods for clients to control the
359order of elaboration of the servers on which they depend:
360
361.. index:: pragma Elaborate
362
363* *pragma Elaborate (unit)*
364
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.
370
371
372.. index:: pragma Elaborate_All
373
374* *pragma Elaborate_All (unit)*
375
376  This is a stronger version of the Elaborate pragma. Consider the
377  following example::
378
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
382
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.
389
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`.
397
398We are now in a position to give a usage rule in Ada for avoiding
399elaboration problems, at least if dynamic dispatching and access to
400subprogram values are not used. We will handle these cases separately
401later.
402
403The rule is simple:
404
405*If a unit has elaboration code that can directly or
406indirectly make a call to a subprogram in a |withed| unit, or instantiate
407a generic package in a |withed| unit,
408then if the |withed| unit does not have
409pragma `Pure` or `Preelaborate`, then the client should have
410a pragma `Elaborate_All`for the |withed| unit.**
411
412By following this rule a client is
413assured that calls can be made without risk of an exception.
414
415For generic subprogram instantiations, the rule can be relaxed to
416require only a pragma `Elaborate` since elaborating the body
417of a subprogram cannot cause any transitive elaboration (we are
418not calling the subprogram in this case, just elaborating its
419declaration).
420
421If this rule is not followed, then a program may be in one of four
422states:
423
424* *No order exists*
425
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.
431
432* *One or more orders exist, all incorrect*
433
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.
438
439* *Several orders exist, some right, some incorrect*
440
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.
448
449* *One or more orders exists, all correct*
450
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.
455
456Note that one additional advantage of following our rules on the use
457of `Elaborate` and `Elaborate_All`
458is that the program continues to stay in the ideal (all orders OK) state
459even if maintenance
460changes some bodies of some units. Conversely, if a program that does
461not follow this rule happens to be safe at some point, this state of affairs
462may deteriorate silently as a result of maintenance changes.
463
464You may have noticed that the above discussion did not mention
465the use of `Elaborate_Body`. This was a deliberate omission. If you
466|with| an `Elaborate_Body` unit, it still may be the case that
467code in the body makes calls to some other unit, so it is still necessary
468to use `Elaborate_All` on such units.
469
470
471.. _Controlling_Elaboration_in_GNAT_-_Internal_Calls:
472
473Controlling Elaboration in GNAT - Internal Calls
474================================================
475
476In the case of internal calls, i.e., calls within a single package, the
477programmer has full control over the order of elaboration, and it is up
478to the programmer to elaborate declarations in an appropriate order. For
479example writing:
480
481.. code-block:: ada
482
483     function One return Float;
484
485     Q : Float := One;
486
487     function One return Float is
488     begin
489          return 1.0;
490     end One;
491
492will obviously raise `Program_Error` at run time, because function
493One will be called before its body is elaborated. In this case GNAT will
494generate a warning that the call will raise `Program_Error`::
495
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
503
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
514
515Note that in this particular case, it is likely that the call is safe, because
516the function `One` does not access any global variables.
517Nevertheless in Ada, we do not want the validity of the check to depend on
518the contents of the body (think about the separate compilation case), so this
519is still wrong, as we discussed in the previous sections.
520
521The error is easily corrected by rearranging the declarations so that the
522body of `One` appears before the declaration containing the call
523(note that in Ada 95 as well as later versions of the Ada standard,
524declarations can appear in any order, so there is no restriction that
525would prevent this reordering, and if we write:
526
527.. code-block:: ada
528
529     function One return Float;
530
531     function One return Float is
532     begin
533          return 1.0;
534     end One;
535
536     Q : Float := One;
537
538then all is well, no warning is generated, and no
539`Program_Error` exception
540will be raised.
541Things are more complicated when a chain of subprograms is executed:
542
543.. code-block:: ada
544
545     function A return Integer;
546     function B return Integer;
547     function C return Integer;
548
549     function B return Integer is begin return A; end;
550     function C return Integer is begin return B; end;
551
552     X : Integer := C;
553
554     function A return Integer is begin return 1; end;
555
556Now the call to `C`
557at elaboration time in the declaration of `X` is correct, because
558the body of `C` is already elaborated,
559and the call to `B` within the body of
560`C` is correct, but the call
561to `A` within the body of `B` is incorrect, because the body
562of `A` has not been elaborated, so `Program_Error`
563will be raised on the call to `A`.
564In this case GNAT will generate a
565warning that `Program_Error` may be
566raised at the point of the call. Let's look at the warning::
567
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
579
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
590
591Note that the message here says 'may raise', instead of the direct case,
592where the message says 'will be raised'. That's because whether
593`A` is
594actually called depends in general on run-time flow of control.
595For example, if the body of `B` said
596
597.. code-block:: ada
598
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;
607
608then we could not know until run time whether the incorrect call to A would
609actually occur, so `Program_Error` might
610or might not be raised. It is possible for a compiler to
611do a better job of analyzing bodies, to
612determine whether or not `Program_Error`
613might be raised, but it certainly
614couldn't do a perfect job (that would require solving the halting problem
615and is provably impossible), and because this is a warning anyway, it does
616not seem worth the effort to do the analysis. Cases in which it
617would be relevant are rare.
618
619In practice, warnings of either of the forms given
620above will usually correspond to
621real errors, and should be examined carefully and eliminated.
622In the rare case where a warning is bogus, it can be suppressed by any of
623the following methods:
624
625* Compile with the *-gnatws* switch set
626
627* Suppress `Elaboration_Check` for the called subprogram
628
629* Use pragma `Warnings_Off` to turn warnings off for the call
630
631For the internal elaboration check case,
632GNAT by default generates the
633necessary run-time checks to ensure
634that `Program_Error` is raised if any
635call fails an elaboration check. Of course this can only happen if a
636warning has been issued as described above. The use of pragma
637`Suppress (Elaboration_Check)` may (but is not guaranteed to) suppress
638some of these checks, meaning that it may be possible (but is not
639guaranteed) for a program to be able to call a subprogram whose body
640is not yet elaborated, without raising a `Program_Error` exception.
641
642
643.. _Controlling_Elaboration_in_GNAT_-_External_Calls:
644
645Controlling Elaboration in GNAT - External Calls
646================================================
647
648The previous section discussed the case in which the execution of a
649particular thread of elaboration code occurred entirely within a
650single unit. This is the easy case to handle, because a programmer
651has direct and total control over the order of elaboration, and
652furthermore, checks need only be generated in cases which are rare
653and which the compiler can easily detect.
654The situation is more complex when separate compilation is taken into account.
655Consider the following:
656
657.. code-block:: ada
658
659      package Math is
660         function Sqrt (Arg : Float) return Float;
661      end Math;
662
663      package body Math is
664         function Sqrt (Arg : Float) return Float is
665         begin
666               ...
667         end Sqrt;
668      end Math;
669
670      with Math;
671      package Stuff is
672         X : Float := Math.Sqrt (0.5);
673      end Stuff;
674
675      with Stuff;
676      procedure Main is
677      begin
678         ...
679      end Main;
680
681where `Main` is the main program. When this program is executed, the
682elaboration code must first be executed, and one of the jobs of the
683binder is to determine the order in which the units of a program are
684to be elaborated. In this case we have four units: the spec and body
685of `Math`,
686the spec of `Stuff` and the body of `Main`).
687In what order should the four separate sections of elaboration code
688be executed?
689
690There are some restrictions in the order of elaboration that the binder
691can choose. In particular, if unit U has a |with|
692for a package `X`, then you
693are assured that the spec of `X`
694is elaborated before U , but you are
695not assured that the body of `X`
696is elaborated before U.
697This means that in the above case, the binder is allowed to choose the
698order::
699
700     spec of Math
701     spec of Stuff
702     body of Math
703     body of Main
704
705but that's not good, because now the call to `Math.Sqrt`
706that happens during
707the elaboration of the `Stuff`
708spec happens before the body of `Math.Sqrt` is
709elaborated, and hence causes `Program_Error` exception to be raised.
710At first glance, one might say that the binder is misbehaving, because
711obviously you want to elaborate the body of something you |with| first, but
712that is not a general rule that can be followed in all cases. Consider
713
714.. code-block:: ada
715
716      package X is ...
717
718      package Y is ...
719
720      with X;
721      package body Y is ...
722
723      with Y;
724      package body X is ...
725
726This is a common arrangement, and, apart from the order of elaboration
727problems that might arise in connection with elaboration code, this works fine.
728A rule that says that you must first elaborate the body of anything you
729|with| cannot work in this case:
730the body of `X` |withs| `Y`,
731which means you would have to
732elaborate the body of `Y` first, but that |withs| `X`,
733which means
734you have to elaborate the body of `X` first, but ... and we have a
735loop that cannot be broken.
736
737It is true that the binder can in many cases guess an order of elaboration
738that is unlikely to cause a `Program_Error`
739exception to be raised, and it tries to do so (in the
740above example of `Math/Stuff/Spec`, the GNAT binder will
741by default
742elaborate the body of `Math` right after its spec, so all will be well).
743
744However, a program that blindly relies on the binder to be helpful can
745get into trouble, as we discussed in the previous sections, so GNAT
746provides a number of facilities for assisting the programmer in
747developing programs that are robust with respect to elaboration order.
748
749
750.. _Default_Behavior_in_GNAT_-_Ensuring_Safety:
751
752Default Behavior in GNAT - Ensuring Safety
753==========================================
754
755The default behavior in GNAT ensures elaboration safety. In its
756default mode GNAT implements the
757rule we previously described as the right approach. Let's restate it:
758
759*If a unit has elaboration code that can directly or indirectly make a
760call to a subprogram in a |withed| unit, or instantiate a generic
761package in a |withed| unit, then if the |withed| unit
762does not have pragma `Pure` or `Preelaborate`, then the client should have an
763`Elaborate_All` pragma for the |withed| unit.*
764
765*In the case of instantiating a generic subprogram, it is always
766sufficient to have only an `Elaborate` pragma for the
767|withed| unit.*
768
769By following this rule a client is assured that calls and instantiations
770can be made without risk of an exception.
771
772In this mode GNAT traces all calls that are potentially made from
773elaboration code, and puts in any missing implicit `Elaborate`
774and `Elaborate_All` pragmas.
775The advantage of this approach is that no elaboration problems
776are possible if the binder can find an elaboration order that is
777consistent with these implicit `Elaborate` and
778`Elaborate_All` pragmas. The
779disadvantage of this approach is that no such order may exist.
780
781If the binder does not generate any diagnostics, then it means that it has
782found an elaboration order that is guaranteed to be safe. However, the binder
783may still be relying on implicitly generated `Elaborate` and
784`Elaborate_All` pragmas so portability to other compilers than GNAT is not
785guaranteed.
786
787If it is important to guarantee portability, then the compilations should
788use the *-gnatel*
789(info messages for elaboration pragmas) switch. This will cause info messages
790to be generated indicating the missing `Elaborate` and
791`Elaborate_All` pragmas.
792Consider the following source program:
793
794.. code-block:: ada
795
796     with k;
797     package j is
798       m : integer := k.r;
799     end;
800
801where it is clear that there
802should be a pragma `Elaborate_All`
803for unit `k`. An implicit pragma will be generated, and it is
804likely that the binder will be able to honor it. However, if you want
805to port this program to some other Ada compiler than GNAT.
806it is safer to include the pragma explicitly in the source. If this
807unit is compiled with the *-gnatel*
808switch, then the compiler outputs an information message::
809
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;
818
819and these messages can be used as a guide for supplying manually
820the missing pragmas. It is usually a bad idea to use this
821option during development. That's because it will tell you when
822you need to put in a pragma, but cannot tell you when it is time
823to take it out. So the use of pragma `Elaborate_All` may lead to
824unnecessary dependencies and even false circularities.
825
826This default mode is more restrictive than the Ada Reference
827Manual, and it is possible to construct programs which will compile
828using the dynamic model described there, but will run into a
829circularity using the safer static model we have described.
830
831Of course any Ada compiler must be able to operate in a mode
832consistent with the requirements of the Ada Reference Manual,
833and in particular must have the capability of implementing the
834standard dynamic model of elaboration with run-time checks.
835
836In GNAT, this standard mode can be achieved either by the use of
837the *-gnatE* switch on the compiler (*gcc* or
838*gnatmake*) command, or by the use of the configuration pragma:
839
840.. code-block:: ada
841
842      pragma Elaboration_Checks (DYNAMIC);
843
844Either approach will cause the unit affected to be compiled using the
845standard dynamic run-time elaboration checks described in the Ada
846Reference Manual. The static model is generally preferable, since it
847is clearly safer to rely on compile and link time checks rather than
848run-time checks. However, in the case of legacy code, it may be
849difficult to meet the requirements of the static model. This
850issue is further discussed in
851:ref:`What_to_Do_If_the_Default_Elaboration_Behavior_Fails`.
852
853Note that the static model provides a strict subset of the allowed
854behavior and programs of the Ada Reference Manual, so if you do
855adhere to the static model and no circularities exist,
856then you are assured that your program will
857work using the dynamic model, providing that you remove any
858pragma Elaborate statements from the source.
859
860
861.. _Treatment_of_Pragma_Elaborate:
862
863Treatment of Pragma Elaborate
864=============================
865
866.. index:: Pragma Elaborate
867
868The use of `pragma Elaborate`
869should generally be avoided in Ada 95 and Ada 2005 programs,
870since there is no guarantee that transitive calls
871will be properly handled. Indeed at one point, this pragma was placed
872in Annex J (Obsolescent Features), on the grounds that it is never useful.
873
874Now that's a bit restrictive. In practice, the case in which
875`pragma Elaborate` is useful is when the caller knows that there
876are no transitive calls, or that the called unit contains all necessary
877transitive `pragma Elaborate` statements, and legacy code often
878contains such uses.
879
880Strictly speaking the static mode in GNAT should ignore such pragmas,
881since there is no assurance at compile time that the necessary safety
882conditions are met. In practice, this would cause GNAT to be incompatible
883with correctly written Ada 83 code that had all necessary
884`pragma Elaborate` statements in place. Consequently, we made the
885decision that GNAT in its default mode will believe that if it encounters
886a `pragma Elaborate` then the programmer knows what they are doing,
887and it will trust that no elaboration errors can occur.
888
889The result of this decision is two-fold. First to be safe using the
890static mode, you should remove all `pragma Elaborate` statements.
891Second, when fixing circularities in existing code, you can selectively
892use `pragma Elaborate` statements to convince the static mode of
893GNAT that it need not generate an implicit `pragma Elaborate_All`
894statement.
895
896When using the static mode with *-gnatwl*, any use of
897`pragma Elaborate` will generate a warning about possible
898problems.
899
900
901.. _Elaboration_Issues_for_Library_Tasks:
902
903Elaboration Issues for Library Tasks
904====================================
905
906.. index:: Library tasks, elaboration issues
907
908.. index:: Elaboration of library tasks
909
910In this section we examine special elaboration issues that arise for
911programs that declare library level tasks.
912
913Generally the model of execution of an Ada program is that all units are
914elaborated, and then execution of the program starts. However, the
915declaration of library tasks definitely does not fit this model. The
916reason 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
918body is reached), that is to say before elaboration
919of the program is complete. This means that if such a task calls a
920subprogram, or an entry in another task, the callee may or may not be
921elaborated yet, and in the standard
922Reference Manual model of dynamic elaboration checks, you can even
923get timing dependent Program_Error exceptions, since there can be
924a race between the elaboration code and the task code.
925
926The static model of elaboration in GNAT seeks to avoid all such
927dynamic behavior, by being conservative, and the conservative
928approach in this particular case is to assume that all the code
929in a task body is potentially executed at elaboration time if
930a task is declared at the library level.
931
932This can definitely result in unexpected circularities. Consider
933the following example
934
935.. code-block:: ada
936
937      package Decls is
938        task Lib_Task is
939           entry Start;
940        end Lib_Task;
941
942        type My_Int is new Integer;
943
944        function Ident (M : My_Int) return My_Int;
945      end Decls;
946
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;
954
955        function Ident (M : My_Int) return My_Int is
956        begin
957           return M;
958        end Ident;
959      end Decls;
960
961      with Decls;
962      package Utils is
963        procedure Put_Val (Arg : Decls.My_Int);
964      end Utils;
965
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;
973
974      with Decls;
975      procedure Main is
976      begin
977         Decls.Lib_Task.Start;
978      end;
979
980If the above example is compiled in the default static elaboration
981mode, then a circularity occurs. The circularity comes from the call
982`Utils.Put_Val` in the task body of `Decls.Lib_Task`. Since
983this call occurs in elaboration code, we need an implicit pragma
984`Elaborate_All` for `Utils`. This means that not only must
985the spec and body of `Utils` be elaborated before the body
986of `Decls`, but also the spec and body of any unit that is
987|withed| by the body of `Utils` must also be elaborated before
988the body of `Decls`. This is the transitive implication of
989pragma `Elaborate_All` and it makes sense, because in general
990the body of `Put_Val` might have a call to something in a
991|withed| unit.
992
993In this case, the body of Utils (actually its spec) |withs|
994`Decls`. Unfortunately this means that the body of `Decls`
995must be elaborated before itself, in case there is a call from the
996body of `Utils`.
997
998Here is the exact chain of events we are worrying about:
999
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.
1005
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.
1009
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.
1013
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.
1022
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.
1027
1028Indeed, if you add an explicit pragma `Elaborate_All` for `Utils` in
1029the body of `Decls` you will get a true Ada Reference Manual
1030circularity that makes the program illegal.
1031
1032In practice, we have found that problems with the static model of
1033elaboration in existing code often arise from library tasks, so
1034we must address this particular situation.
1035
1036Note that if we compile and run the program above, using the dynamic model of
1037elaboration (that is to say use the *-gnatE* switch),
1038then it compiles, binds,
1039links, and runs, printing the expected result of 2. Therefore in some sense
1040the circularity here is only apparent, and we need to capture
1041the properties of this program that  distinguish it from other library-level
1042tasks that have real elaboration problems.
1043
1044We have four possible answers to this question:
1045
1046
1047* Use the dynamic model of elaboration.
1048
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.
1059
1060* Split library tasks into separate packages.
1061
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.
1065
1066
1067  .. code-block:: ada
1068
1069      package Decls1 is
1070        task Lib_Task is
1071           entry Start;
1072        end Lib_Task;
1073      end Decls1;
1074
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;
1083
1084      package Decls2 is
1085        type My_Int is new Integer;
1086        function Ident (M : My_Int) return My_Int;
1087      end Decls2;
1088
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;
1096
1097      with Decls2;
1098      package Utils is
1099        procedure Put_Val (Arg : Decls2.My_Int);
1100      end Utils;
1101
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;
1109
1110      with Decls1;
1111      procedure Main is
1112      begin
1113         Decls1.Lib_Task.Start;
1114      end;
1115
1116
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.
1121
1122* Declare separate task types.
1123
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:
1132
1133  .. code-block:: ada
1134
1135      package Decls is
1136        task type Lib_Task_Type is
1137           entry Start;
1138        end Lib_Task_Type;
1139
1140        type My_Int is new Integer;
1141
1142        function Ident (M : My_Int) return My_Int;
1143      end Decls;
1144
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;
1152
1153        function Ident (M : My_Int) return My_Int is
1154        begin
1155           return M;
1156        end Ident;
1157      end Decls;
1158
1159      with Decls;
1160      package Utils is
1161        procedure Put_Val (Arg : Decls.My_Int);
1162      end Utils;
1163
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;
1171
1172      with Decls;
1173      package Declst is
1174         Lib_Task : Decls.Lib_Task_Type;
1175      end Declst;
1176
1177      with Declst;
1178      procedure Main is
1179      begin
1180         Declst.Lib_Task.Start;
1181      end;
1182
1183
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.
1196
1197.. index:: No_Entry_Calls_In_Elaboration_Code restriction
1198
1199* Use No_Entry_Calls_In_Elaboration_Code restriction.
1200
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.
1205
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.
1213
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.
1221
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:
1226
1227  .. code-block:: ada
1228
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.
1239
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.
1245
1246
1247.. _Mixing_Elaboration_Models:
1248
1249Mixing Elaboration Models
1250=========================
1251
1252So far, we have assumed that the entire program is either compiled
1253using the dynamic model or static model, ensuring consistency. It
1254is possible to mix the two models, but rules have to be followed
1255if this mixing is done to ensure that elaboration checks are not
1256omitted.
1257
1258The basic rule is that
1259**a unit compiled with the static model cannot
1260be |withed| by a unit compiled with the dynamic model**.
1261The reason for this is that in the static model, a unit assumes that
1262its clients guarantee to use (the equivalent of) pragma
1263`Elaborate_All` so that no elaboration checks are required
1264in inner subprograms, and this assumption is violated if the
1265client is compiled with dynamic checks.
1266
1267The precise rule is as follows. A unit that is compiled with dynamic
1268checks can only |with| a unit that meets at least one of the
1269following criteria:
1270
1271
1272* The |withed| unit is itself compiled with dynamic elaboration
1273  checks (that is with the *-gnatE* switch.
1274
1275* The |withed| unit is an internal GNAT implementation unit from
1276  the System, Interfaces, Ada, or GNAT hierarchies.
1277
1278* The |withed| unit has pragma Preelaborate or pragma Pure.
1279
1280* The |withing| unit (that is the client) has an explicit pragma
1281  `Elaborate_All` for the |withed| unit.
1282
1283
1284If this rule is violated, that is if a unit with dynamic elaboration
1285checks |withs| a unit that does not meet one of the above four
1286criteria, then the binder (`gnatbind`) will issue a warning
1287similar to that in the following example::
1288
1289     warning: "x.ads" has dynamic elaboration checks and with's
1290     warning:   "y.ads" which has static elaboration checks
1291
1292These warnings indicate that the rule has been violated, and that as a result
1293elaboration checks may be missed in the resulting executable file.
1294This warning may be suppressed using the *-ws* binder switch
1295in the usual manner.
1296
1297One useful application of this mixing rule is in the case of a subsystem
1298which does not itself |with| units from the remainder of the
1299application. In this case, the entire subsystem can be compiled with
1300dynamic checks to resolve a circularity in the subsystem, while
1301allowing the main application that uses this subsystem to be compiled
1302using the more reliable default static model.
1303
1304
1305.. _What_to_Do_If_the_Default_Elaboration_Behavior_Fails:
1306
1307What to Do If the Default Elaboration Behavior Fails
1308====================================================
1309
1310If the binder cannot find an acceptable order, it outputs detailed
1311diagnostics. For example::
1312
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)"
1325
1326In this case we have a cycle that the binder cannot break. On the one
1327hand, there is an explicit pragma Elaborate in `proc` for
1328`pack`. This means that the body of `pack` must be elaborated
1329before the body of `proc`. On the other hand, there is elaboration
1330code in `pack` that calls a subprogram in `proc`. This means
1331that for maximum safety, there should really be a pragma
1332Elaborate_All in `pack` for `proc` which would require that
1333the body of `proc` be elaborated before the body of
1334`pack`. Clearly both requirements cannot be satisfied.
1335Faced with a circularity of this kind, you have three different options.
1336
1337
1338* *Fix the program*
1339
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.
1348
1349* *Perform dynamic checks*
1350
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.
1362
1363* *Suppress checks*
1364
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.
1372
1373* *Suppress checks selectively*
1374
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:
1384
1385  * Place the pragma that names the called subprogram in the declarative part
1386    that contains the call.
1387
1388  * Place the pragma in the declarative part, without naming an entity. This
1389    disables warnings on all calls in the corresponding  declarative region.
1390
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.
1394
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.
1398
1399  * Use Pragma Elaborate.
1400
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.
1407
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:
1411
1412  .. code-block:: ada
1413
1414        package Pack1 is
1415          function F1 return Integer;
1416          X1 : Integer;
1417        end Pack1;
1418
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;
1425
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;
1441
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;
1453
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::
1462
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.
1483
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.
1487
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.
1493
1494It is hard to generalize on which of these four approaches should be
1495taken. Obviously if it is possible to fix the program so that the default
1496treatment works, this is preferable, but this may not always be practical.
1497It is certainly simple enough to use *-gnatE*
1498but the danger in this case is that, even if the GNAT binder
1499finds a correct elaboration order, it may not always do so,
1500and certainly a binder from another Ada compiler might not. A
1501combination of testing and analysis (for which the
1502information messages generated with the *-gnatel*
1503switch can be useful) must be used to ensure that the program is free
1504of errors. One switch that is useful in this testing is the
1505*-p (pessimistic elaboration order)* switch for `gnatbind`.
1506Normally the binder tries to find an order that has the best chance
1507of avoiding elaboration problems. However, if this switch is used, the binder
1508plays a devil's advocate role, and tries to choose the order that
1509has the best chance of failing. If your program works even with this
1510switch, then it has a better chance of being error free, but this is still
1511not a guarantee.
1512
1513For an example of this approach in action, consider the C-tests (executable
1514tests) from the ACATS suite. If these are compiled and run with the default
1515treatment, then all but one of them succeed without generating any error
1516diagnostics from the binder. However, there is one test that fails, and
1517this is not surprising, because the whole point of this test is to ensure
1518that the compiler can handle cases where it is impossible to determine
1519a correct order statically, and it checks that an exception is indeed
1520raised at run time.
1521
1522This one test must be compiled and run using the *-gnatE*
1523switch, and then it passes. Alternatively, the entire suite can
1524be run using this switch. It is never wrong to run with the dynamic
1525elaboration switch if your code is correct, and we assume that the
1526C-tests are indeed correct (it is less efficient, but efficiency is
1527not a factor in running the ACATS tests.)
1528
1529
1530.. _Elaboration_for_Indirect_Calls:
1531
1532Elaboration for Indirect Calls
1533==============================
1534
1535.. index:: Dispatching calls
1536.. index:: Indirect calls
1537
1538In rare cases, the static elaboration model fails to prevent
1539dispatching calls to not-yet-elaborated subprograms. In such cases, we
1540fall back to run-time checks; premature calls to any primitive
1541operation of a tagged type before the body of the operation has been
1542elaborated will raise `Program_Error`.
1543
1544Access-to-subprogram types, however, are handled conservatively, and
1545do not require run-time checks. This was not true in earlier versions
1546of the compiler; you can use the *-gnatd.U* debug switch to
1547revert to the old behavior if the new conservative behavior causes
1548elaboration cycles. Here, 'conservative' means that if you do
1549`P'Access` during elaboration, the compiler will assume that you
1550might call `P` indirectly during elaboration, so it adds an
1551implicit `pragma Elaborate_All` on the library unit containing
1552`P`. The *-gnatd.U* switch is safe if you know there are
1553no such calls. If the program worked before, it will continue to work
1554with *-gnatd.U*. But beware that code modifications such as
1555adding an indirect call can cause erroneous behavior in the presence
1556of *-gnatd.U*.
1557
1558
1559.. _Summary_of_Procedures_for_Elaboration_Control:
1560
1561Summary of Procedures for Elaboration Control
1562=============================================
1563
1564.. index:: Elaboration control
1565
1566First, compile your program with the default options, using none of
1567the special elaboration control switches. If the binder successfully
1568binds your program, then you can be confident that, apart from issues
1569raised by the use of access-to-subprogram types and dynamic dispatching,
1570the program is free of elaboration errors. If it is important that the
1571program be portable to other compilers than GNAT, then use the
1572*-gnatel*
1573switch to generate messages about missing `Elaborate` or
1574`Elaborate_All` pragmas, and supply the missing pragmas.
1575
1576If the program fails to bind using the default static elaboration
1577handling, then you can fix the program to eliminate the binder
1578message, or recompile the entire program with the
1579*-gnatE* switch to generate dynamic elaboration checks,
1580and, if you are sure there really are no elaboration problems,
1581use a global pragma `Suppress (Elaboration_Check)`.
1582
1583
1584.. _Other_Elaboration_Order_Considerations:
1585
1586Other Elaboration Order Considerations
1587======================================
1588
1589This section has been entirely concerned with the issue of finding a valid
1590elaboration order, as defined by the Ada Reference Manual. In a case
1591where several elaboration orders are valid, the task is to find one
1592of the possible valid elaboration orders (and the static model in GNAT
1593will ensure that this is achieved).
1594
1595The purpose of the elaboration rules in the Ada Reference Manual is to
1596make sure that no entity is accessed before it has been elaborated. For
1597a subprogram, this means that the spec and body must have been elaborated
1598before the subprogram is called. For an object, this means that the object
1599must have been elaborated before its value is read or written. A violation
1600of either of these two requirements is an access before elaboration order,
1601and this section has been all about avoiding such errors.
1602
1603In the case where more than one order of elaboration is possible, in the
1604sense that access before elaboration errors are avoided, then any one of
1605the orders is 'correct' in the sense that it meets the requirements of
1606the Ada Reference Manual, and no such error occurs.
1607
1608However, it may be the case for a given program, that there are
1609constraints on the order of elaboration that come not from consideration
1610of avoiding elaboration errors, but rather from extra-lingual logic
1611requirements. Consider this example:
1612
1613.. code-block:: ada
1614
1615     with Init_Constants;
1616     package Constants is
1617        X : Integer := 0;
1618        Y : Integer := 0;
1619     end Constants;
1620
1621     package Init_Constants is
1622        procedure P; --* require a body*
1623     end Init_Constants;
1624
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;
1632
1633     with Constants;
1634     package Calc is
1635        Z : Integer := Constants.X + Constants.Y;
1636     end Calc;
1637
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
1645In this example, there is more than one valid order of elaboration. For
1646example both the following are correct orders::
1647
1648     Init_Constants spec
1649     Constants spec
1650     Calc spec
1651     Init_Constants body
1652     Main body
1653
1654and
1655
1656::
1657
1658    Init_Constants spec
1659    Init_Constants body
1660    Constants spec
1661    Calc spec
1662    Main body
1663
1664There is no language rule to prefer one or the other, both are correct
1665from an order of elaboration point of view. But the programmatic effects
1666of the two orders are very different. In the first, the elaboration routine
1667of `Calc` initializes `Z` to zero, and then the main program
1668runs with this value of zero. But in the second order, the elaboration
1669routine 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.
1671
1672One could perhaps by applying pretty clever non-artificial intelligence
1673to the situation guess that it is more likely that the second order of
1674elaboration is the one desired, but there is no formal linguistic reason
1675to prefer one over the other. In fact in this particular case, GNAT will
1676prefer the second order, because of the rule that bodies are elaborated
1677as soon as possible, but it's just luck that this is what was wanted
1678(if indeed the second order was preferred).
1679
1680If the program cares about the order of elaboration routines in a case like
1681this, it is important to specify the order required. In this particular
1682case, that could have been achieved by adding to the spec of Calc:
1683
1684.. code-block:: ada
1685
1686     pragma Elaborate_All (Constants);
1687
1688which requires that the body (if any) and spec of `Constants`,
1689as well as the body and spec of any unit |withed| by
1690`Constants` be elaborated before `Calc` is elaborated.
1691
1692Clearly no automatic method can always guess which alternative you require,
1693and if you are working with legacy code that had constraints of this kind
1694which were not properly specified by adding `Elaborate` or
1695`Elaborate_All` pragmas, then indeed it is possible that two different
1696compilers can choose different orders.
1697
1698However, GNAT does attempt to diagnose the common situation where there
1699are uninitialized variables in the visible part of a package spec, and the
1700corresponding package body has an elaboration block that directly or
1701indirectly initialized one or more of these variables. This is the situation
1702in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
1703a warning that suggests this addition if it detects this situation.
1704
1705The `gnatbind` *-p* switch may be useful in smoking
1706out problems. This switch causes bodies to be elaborated as late as possible
1707instead of as early as possible. In the example above, it would have forced
1708the choice of the first elaboration order. If you get different results
1709when using this switch, and particularly if one set of results is right,
1710and one is wrong as far as you are concerned, it shows that you have some
1711missing `Elaborate` pragmas. For the example above, we have the
1712following output:
1713
1714.. code-block:: sh
1715
1716     $ gnatmake -f -q main
1717     $ main
1718      7
1719     $ gnatmake -f -q main -bargs -p
1720     $ main
1721      0
1722
1723It is of course quite unlikely that both these results are correct, so
1724it is up to you in a case like this to investigate the source of the
1725difference, by looking at the two elaboration orders that are chosen,
1726and figuring out which is correct, and then adding the necessary
1727`Elaborate` or `Elaborate_All` pragmas to ensure the desired order.
1728
1729
1730.. _Determining_the_Chosen_Elaboration_Order:
1731
1732Determining the Chosen Elaboration Order
1733========================================
1734
1735To see the elaboration order that the binder chooses, you can look at
1736the last part of the file:`b~xxx.adb` binder output file. Here is an example::
1737
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
1772Here Elab_Spec elaborates the spec
1773and Elab_Body elaborates the body. The assignments to the :samp:`E{xx}` flags
1774flag that the corresponding body is now elaborated.
1775
1776You can also ask the binder to generate a more
1777readable list of the elaboration order using the
1778`-l` switch when invoking the binder. Here is
1779an example of the output generated by this switch::
1780
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)
1865