1.. role:: switch(samp)
2
3.. |with| replace:: *with*
4.. |withs| replace:: *with*\ s
5.. |withed| replace:: *with*\ ed
6.. |withing| replace:: *with*\ ing
7
8.. -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
9
10
11.. _Elaboration_Order_Handling_in_GNAT:
12
13**********************************
14Elaboration Order Handling in GNAT
15**********************************
16
17.. index:: Order of elaboration
18.. index:: Elaboration control
19
20This appendix describes the handling of elaboration code in Ada and GNAT, and
21discusses how the order of elaboration of program units can be controlled in
22GNAT, either automatically or with explicit programming features.
23
24.. _Elaboration_Code:
25
26Elaboration Code
27================
28
29Ada defines the term *execution* as the process by which a construct achieves
30its run-time effect. This process is also referred to as **elaboration** for
31declarations and *evaluation* for expressions.
32
33The execution model in Ada allows for certain sections of an Ada program to be
34executed prior to execution of the program itself, primarily with the intent of
35initializing data. These sections are referred to as **elaboration code**.
36Elaboration code is executed as follows:
37
38* All partitions of an Ada program are executed in parallel with one another,
39  possibly in a separate address space, and possibly on a separate computer.
40
41* The execution of a partition involves running the environment task for that
42  partition.
43
44* The environment task executes all elaboration code (if available) for all
45  units within that partition. This code is said to be executed at
46  **elaboration time**.
47
48* The environment task executes the Ada program (if available) for that
49  partition.
50
51In addition to the Ada terminology, this appendix defines the following terms:
52
53* *Invocation*
54
55  The act of calling a subprogram, instantiating a generic, or activating a
56  task.
57
58* *Scenario*
59
60  A construct that is elaborated or invoked by elaboration code is referred to
61  as an *elaboration scenario* or simply a **scenario**. GNAT recognizes the
62  following scenarios:
63
64  - ``'Access`` of entries, operators, and subprograms
65
66  - Activation of tasks
67
68  - Calls to entries, operators, and subprograms
69
70  - Instantiations of generic templates
71
72* *Target*
73
74  A construct elaborated by a scenario is referred to as *elaboration target*
75  or simply **target**. GNAT recognizes the following targets:
76
77  - For ``'Access`` of entries, operators, and subprograms, the target is the
78    entry, operator, or subprogram being aliased.
79
80  - For activation of tasks, the target is the task body
81
82  - For calls to entries, operators, and subprograms, the target is the entry,
83    operator, or subprogram being invoked.
84
85  - For instantiations of generic templates, the target is the generic template
86    being instantiated.
87
88Elaboration code may appear in two distinct contexts:
89
90* *Library level*
91
92  A scenario appears at the library level when it is encapsulated by a package
93  [body] compilation unit, ignoring any other package [body] declarations in
94  between.
95
96  ::
97
98     with Server;
99     package Client is
100        procedure Proc;
101
102        package Nested is
103           Val : ... := Server.Func;
104        end Nested;
105     end Client;
106
107  In the example above, the call to ``Server.Func`` is an elaboration scenario
108  because it appears at the library level of package ``Client``. Note that the
109  declaration of package ``Nested`` is ignored according to the definition
110  given above. As a result, the call to ``Server.Func`` will be invoked when
111  the spec of unit ``Client`` is elaborated.
112
113* *Package body statements*
114
115  A scenario appears within the statement sequence of a package body when it is
116  bounded by the region starting from the ``begin`` keyword of the package body
117  and ending at the ``end`` keyword of the package body.
118
119  ::
120
121     package body Client is
122        procedure Proc is
123        begin
124           ...
125        end Proc;
126     begin
127        Proc;
128     end Client;
129
130  In the example above, the call to ``Proc`` is an elaboration scenario because
131  it appears within the statement sequence of package body ``Client``. As a
132  result, the call to ``Proc`` will be invoked when the body of ``Client`` is
133  elaborated.
134
135.. _Elaboration_Order:
136
137Elaboration Order
138=================
139
140The sequence by which the elaboration code of all units within a partition is
141executed is referred to as **elaboration order**.
142
143Within a single unit, elaboration code is executed in sequential order.
144
145  ::
146
147     package body Client is
148        Result : ... := Server.Func;
149
150        procedure Proc is
151           package Inst is new Server.Gen;
152        begin
153           Inst.Eval (Result);
154        end Proc;
155     begin
156        Proc;
157     end Client;
158
159In the example above, the elaboration order within package body ``Client`` is
160as follows:
161
1621. The object declaration of ``Result`` is elaborated.
163
164   * Function ``Server.Func`` is invoked.
165
1662. The subprogram body of ``Proc`` is elaborated.
167
1683. Procedure ``Proc`` is invoked.
169
170   * Generic unit ``Server.Gen`` is instantiated as ``Inst``.
171
172   * Instance ``Inst`` is elaborated.
173
174   * Procedure ``Inst.Eval`` is invoked.
175
176The elaboration order of all units within a partition depends on the following
177factors:
178
179* |withed| units
180
181* parent units
182
183* purity of units
184
185* preelaborability of units
186
187* presence of elaboration-control pragmas
188
189* invocations performed in elaboration code
190
191A program may have several elaboration orders depending on its structure.
192
193  ::
194
195     package Server is
196        function Func (Index : Integer) return Integer;
197     end Server;
198
199  ::
200
201     package body Server is
202        Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
203
204        function Func (Index : Integer) return Integer is
205        begin
206           return Results (Index);
207        end Func;
208     end Server;
209
210  ::
211
212     with Server;
213     package Client is
214        Val : constant Integer := Server.Func (3);
215     end Client;
216
217  ::
218
219     with Client;
220     procedure Main is begin null; end Main;
221
222The following elaboration order exhibits a fundamental problem referred to as
223*access-before-elaboration* or simply **ABE**.
224
225  ::
226
227     spec of Server
228     spec of Client
229     body of Server
230     body of Main
231
232The elaboration of ``Server``'s spec materializes function ``Func``, making it
233callable. The elaboration of ``Client``'s spec elaborates the declaration of
234``Val``. This invokes function ``Server.Func``, however the body of
235``Server.Func`` has not been elaborated yet because ``Server``'s body comes
236after ``Client``'s spec in the elaboration order. As a result, the value of
237constant ``Val`` is now undefined.
238
239Without any guarantees from the language, an undetected ABE problem may hinder
240proper initialization of data, which in turn may lead to undefined behavior at
241run time. To prevent such ABE problems, Ada employs dynamic checks in the same
242vein as index or null exclusion checks. A failed ABE check raises exception
243``Program_Error``.
244
245The following elaboration order avoids the ABE problem and the program can be
246successfully elaborated.
247
248  ::
249
250     spec of Server
251     body of Server
252     spec of Client
253     body of Main
254
255Ada states that a total elaboration order must exist, but it does not define
256what this order is. A compiler is thus tasked with choosing a suitable
257elaboration order which satisfies the dependencies imposed by |with| clauses,
258unit categorization, elaboration-control pragmas, and invocations performed in
259elaboration code. Ideally an order that avoids ABE problems should be chosen,
260however a compiler may not always find such an order due to complications with
261respect to control and data flow.
262
263.. _Checking_the_Elaboration_Order:
264
265Checking the Elaboration Order
266==============================
267
268To avoid placing the entire elaboration-order burden on the programmer, Ada
269provides three lines of defense:
270
271* *Static semantics*
272
273  Static semantic rules restrict the possible choice of elaboration order. For
274  instance, if unit Client |withs| unit Server, then the spec of Server is
275  always elaborated prior to Client. The same principle applies to child units
276  - the spec of a parent unit is always elaborated prior to the child unit.
277
278* *Dynamic semantics*
279
280  Dynamic checks are performed at run time, to ensure that a target is
281  elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
282  A failed run-time check raises exception ``Program_Error``. The following
283  restrictions apply:
284
285  - *Restrictions on calls*
286
287    An entry, operator, or subprogram can be called from elaboration code only
288    when the corresponding body has been elaborated.
289
290  - *Restrictions on instantiations*
291
292    A generic unit can be instantiated by elaboration code only when the
293    corresponding body has been elaborated.
294
295  - *Restrictions on task activation*
296
297    A task can be activated by elaboration code only when the body of the
298    associated task type has been elaborated.
299
300  The restrictions above can be summarized by the following rule:
301
302  *If a target has a body, then this body must be elaborated prior to the
303  scenario that invokes the target.*
304
305* *Elaboration control*
306
307  Pragmas are provided for the programmer to specify the desired elaboration
308  order.
309
310.. _Controlling_the_Elaboration_Order_in_Ada:
311
312Controlling the Elaboration Order in Ada
313========================================
314
315Ada provides several idioms and pragmas to aid the programmer with specifying
316the desired elaboration order and avoiding ABE problems altogether.
317
318* *Packages without a body*
319
320  A library package which does not require a completing body does not suffer
321  from ABE problems.
322
323  ::
324
325     package Pack is
326        generic
327           type Element is private;
328        package Containers is
329           type Element_Array is array (1 .. 10) of Element;
330        end Containers;
331     end Pack;
332
333  In the example above, package ``Pack`` does not require a body because it
334  does not contain any constructs which require completion in a body. As a
335  result, generic ``Pack.Containers`` can be instantiated without encountering
336  any ABE problems.
337
338.. index:: pragma Pure
339
340* *pragma Pure*
341
342  Pragma ``Pure`` places sufficient restrictions on a unit to guarantee that no
343  scenario within the unit can result in an ABE problem.
344
345.. index:: pragma Preelaborate
346
347* *pragma Preelaborate*
348
349  Pragma ``Preelaborate`` is slightly less restrictive than pragma ``Pure``,
350  but still strong enough to prevent ABE problems within a unit.
351
352.. index:: pragma Elaborate_Body
353
354* *pragma Elaborate_Body*
355
356  Pragma ``Elaborate_Body`` requires that the body of a unit is elaborated
357  immediately after its spec. This restriction guarantees that no client
358  scenario can invoke a server target before the target body has been
359  elaborated because the spec and body are effectively "glued" together.
360
361  ::
362
363     package Server is
364        pragma Elaborate_Body;
365
366        function Func return Integer;
367     end Server;
368
369  ::
370
371     package body Server is
372        function Func return Integer is
373        begin
374           ...
375        end Func;
376     end Server;
377
378  ::
379
380     with Server;
381     package Client is
382        Val : constant Integer := Server.Func;
383     end Client;
384
385  In the example above, pragma ``Elaborate_Body`` guarantees the following
386  elaboration order:
387
388  ::
389
390     spec of Server
391     body of Server
392     spec of Client
393
394  because the spec of ``Server`` must be elaborated prior to ``Client`` by
395  virtue of the |with| clause, and in addition the body of ``Server`` must be
396  elaborated immediately after the spec of ``Server``.
397
398  Removing pragma ``Elaborate_Body`` could result in the following incorrect
399  elaboration order:
400
401  ::
402
403     spec of Server
404     spec of Client
405     body of Server
406
407  where ``Client`` invokes ``Server.Func``, but the body of ``Server.Func`` has
408  not been elaborated yet.
409
410The pragmas outlined above allow a server unit to guarantee safe elaboration
411use by client units. Thus it is a good rule to mark units as ``Pure`` or
412``Preelaborate``, and if this is not possible, mark them as ``Elaborate_Body``.
413
414There are however situations where ``Pure``, ``Preelaborate``, and
415``Elaborate_Body`` are not applicable. Ada provides another set of pragmas for
416use by client units to help ensure the elaboration safety of server units they
417depend on.
418
419.. index:: pragma Elaborate (Unit)
420
421* *pragma Elaborate (Unit)*
422
423  Pragma ``Elaborate`` can be placed in the context clauses of a unit, after a
424  |with| clause. It guarantees that both the spec and body of its argument will
425  be elaborated prior to the unit with the pragma. Note that other unrelated
426  units may be elaborated in between the spec and the body.
427
428  ::
429
430     package Server is
431        function Func return Integer;
432     end Server;
433
434  ::
435
436     package body Server is
437        function Func return Integer is
438        begin
439           ...
440        end Func;
441     end Server;
442
443  ::
444
445     with Server;
446     pragma Elaborate (Server);
447     package Client is
448        Val : constant Integer := Server.Func;
449     end Client;
450
451  In the example above, pragma ``Elaborate`` guarantees the following
452  elaboration order:
453
454  ::
455
456     spec of Server
457     body of Server
458     spec of Client
459
460  Removing pragma ``Elaborate`` could result in the following incorrect
461  elaboration order:
462
463  ::
464
465     spec of Server
466     spec of Client
467     body of Server
468
469  where ``Client`` invokes ``Server.Func``, but the body of ``Server.Func``
470  has not been elaborated yet.
471
472.. index:: pragma Elaborate_All (Unit)
473
474* *pragma Elaborate_All (Unit)*
475
476  Pragma ``Elaborate_All`` is placed in the context clauses of a unit, after
477  a |with| clause. It guarantees that both the spec and body of its argument
478  will be elaborated prior to the unit with the pragma, as well as all units
479  |withed| by the spec and body of the argument, recursively. Note that other
480  unrelated units may be elaborated in between the spec and the body.
481
482  ::
483
484     package Math is
485        function Factorial (Val : Natural) return Natural;
486     end Math;
487
488  ::
489
490     package body Math is
491        function Factorial (Val : Natural) return Natural is
492        begin
493           ...;
494        end Factorial;
495     end Math;
496
497  ::
498
499     package Computer is
500        type Operation_Kind is (None, Op_Factorial);
501
502        function Compute
503          (Val : Natural;
504           Op  : Operation_Kind) return Natural;
505     end Computer;
506
507  ::
508
509     with Math;
510     package body Computer is
511        function Compute
512          (Val : Natural;
513           Op  : Operation_Kind) return Natural
514        is
515           if Op = Op_Factorial then
516              return Math.Factorial (Val);
517           end if;
518
519           return 0;
520        end Compute;
521     end Computer;
522
523  ::
524
525     with Computer;
526     pragma Elaborate_All (Computer);
527     package Client is
528        Val : constant Natural :=
529                Computer.Compute (123, Computer.Op_Factorial);
530     end Client;
531
532  In the example above, pragma ``Elaborate_All`` can result in the following
533  elaboration order:
534
535  ::
536
537     spec of Math
538     body of Math
539     spec of Computer
540     body of Computer
541     spec of Client
542
543  Note that there are several allowable suborders for the specs and bodies of
544  ``Math`` and ``Computer``, but the point is that these specs and bodies will
545  be elaborated prior to ``Client``.
546
547  Removing pragma ``Elaborate_All`` could result in the following incorrect
548  elaboration order:
549
550  ::
551
552     spec of Math
553     spec of Computer
554     body of Computer
555     spec of Client
556     body of Math
557
558  where ``Client`` invokes ``Computer.Compute``, which in turn invokes
559  ``Math.Factorial``, but the body of ``Math.Factorial`` has not been
560  elaborated yet.
561
562All pragmas shown above can be summarized by the following rule:
563
564*If a client unit elaborates a server target directly or indirectly, then if
565the server unit requires a body and does not have pragma Pure, Preelaborate,
566or Elaborate_Body, then the client unit should have pragma Elaborate or
567Elaborate_All for the server unit.*
568
569If the rule outlined above is not followed, then a program may fall in one of
570the following states:
571
572* *No elaboration order exists*
573
574  In this case a compiler must diagnose the situation, and refuse to build an
575  executable program.
576
577* *One or more incorrect elaboration orders exist*
578
579  In this case a compiler can build an executable program, but
580  ``Program_Error`` will be raised when the program is run.
581
582* *Several elaboration orders exist, some correct, some incorrect*
583
584  In this case the programmer has not controlled the elaboration order. As a
585  result, a compiler may or may not pick one of the correct orders, and the
586  program may or may not raise ``Program_Error`` when it is run. This is the
587  worst possible state because the program may fail on another compiler, or
588  even another version of the same compiler.
589
590* *One or more correct orders exist*
591
592  In this case a compiler can build an executable program, and the program is
593  run successfully. This state may be guaranteed by following the outlined
594  rules, or may be the result of good program architecture.
595
596Note that one additional advantage of using ``Elaborate`` and ``Elaborate_All``
597is that the program continues to stay in the last state (one or more correct
598orders exist) even if maintenance changes the bodies of targets.
599
600.. _Controlling_the_Elaboration_Order_in_GNAT:
601
602Controlling the Elaboration Order in GNAT
603=========================================
604
605In addition to Ada semantics and rules synthesized from them, GNAT offers
606three elaboration models to aid the programmer with specifying the correct
607elaboration order and to diagnose elaboration problems.
608
609.. index:: Dynamic elaboration model
610
611* *Dynamic elaboration model*
612
613  This is the most permissive of the three elaboration models and emulates the
614  behavior specified by the Ada Reference Manual. When the dynamic model is in
615  effect, GNAT makes the following assumptions:
616
617  - All code within all units in a partition is considered to be elaboration
618    code.
619
620  - Some of the invocations in elaboration code may not take place at run time
621    due to conditional execution.
622
623  GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
624  that invoke internal targets. In addition, GNAT generates run-time checks for
625  all external targets and for all scenarios that may exhibit ABE problems.
626
627  The elaboration order is obtained by honoring all |with| clauses, purity and
628  preelaborability of units, and elaboration-control pragmas. The dynamic model
629  attempts to take all invocations in elaboration code into account. If an
630  invocation leads to a circularity, GNAT ignores the invocation based on the
631  assumptions stated above. An order obtained using the dynamic model may fail
632  an ABE check at run time when GNAT ignored an invocation.
633
634  The dynamic model is enabled with compiler switch :switch:`-gnatE`.
635
636.. index:: Static elaboration model
637
638* *Static elaboration model*
639
640  This is the middle ground of the three models. When the static model is in
641  effect, GNAT makes the following assumptions:
642
643  - Only code at the library level and in package body statements within all
644    units in a partition is considered to be elaboration code.
645
646  - All invocations in elaboration will take place at run time, regardless of
647    conditional execution.
648
649  GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
650  that invoke internal targets. In addition, GNAT generates run-time checks for
651  all external targets and for all scenarios that may exhibit ABE problems.
652
653  The elaboration order is obtained by honoring all |with| clauses, purity and
654  preelaborability of units, presence of elaboration-control pragmas, and all
655  invocations in elaboration code. An order obtained using the static model is
656  guaranteed to be ABE problem-free, excluding dispatching calls and
657  access-to-subprogram types.
658
659  The static model is the default model in GNAT.
660
661.. index:: SPARK elaboration model
662
663* *SPARK elaboration model*
664
665  This is the most conservative of the three models and enforces the SPARK
666  rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
667  The SPARK model is in effect only when a scenario and a target reside in a
668  region subject to ``SPARK_Mode On``, otherwise the dynamic or static model
669  is in effect.
670
671  The SPARK model is enabled with compiler switch :switch:`-gnatd.v`.
672
673.. index:: Legacy elaboration models
674
675* *Legacy elaboration models*
676
677  In addition to the three elaboration models outlined above, GNAT provides the
678  following legacy models:
679
680  - `Legacy elaboration-checking model` available in pre-18.x versions of GNAT.
681    This model is enabled with compiler switch :switch:`-gnatH`.
682
683  - `Legacy elaboration-order model` available in pre-20.x versions of GNAT.
684    This model is enabled with binder switch :switch:`-H`.
685
686.. index:: Relaxed elaboration mode
687
688The dynamic, legacy, and static models can be relaxed using compiler switch
689:switch:`-gnatJ`, making them more permissive. Note that in this mode, GNAT
690may not diagnose certain elaboration issues or install run-time checks.
691
692.. _Mixing_Elaboration_Models:
693
694Mixing Elaboration Models
695=========================
696
697It is possible to mix units compiled with a different elaboration model,
698however the following rules must be observed:
699
700* A client unit compiled with the dynamic model can only |with| a server unit
701  that meets at least one of the following criteria:
702
703  - The server unit is compiled with the dynamic model.
704
705  - The server unit is a GNAT implementation unit from the ``Ada``, ``GNAT``,
706    ``Interfaces``, or ``System`` hierarchies.
707
708  - The server unit has pragma ``Pure`` or ``Preelaborate``.
709
710  - The client unit has an explicit ``Elaborate_All`` pragma for the server
711    unit.
712
713These rules ensure that elaboration checks are not omitted. If the rules are
714violated, the binder emits a warning:
715
716  ::
717
718     warning: "x.ads" has dynamic elaboration checks and with's
719     warning:   "y.ads" which has static elaboration checks
720
721The warnings can be suppressed by binder switch :switch:`-ws`.
722
723.. _ABE_Diagnostics:
724
725ABE Diagnostics
726===============
727
728GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
729that invoke internal targets, regardless of whether the dynamic, SPARK, or
730static model is in effect.
731
732Note that GNAT emits warnings rather than hard errors whenever it encounters an
733elaboration problem. This is because the elaboration model in effect may be too
734conservative, or a particular scenario may not be invoked due conditional
735execution. The warnings can be suppressed selectively with ``pragma Warnings
736(Off)`` or globally with compiler switch :switch:`-gnatwL`.
737
738A *guaranteed ABE* arises when the body of a target is not elaborated early
739enough, and causes *all* scenarios that directly invoke the target to fail.
740
741  ::
742
743     package body Guaranteed_ABE is
744        function ABE return Integer;
745
746        Val : constant Integer := ABE;
747
748        function ABE return Integer is
749        begin
750          ...
751        end ABE;
752     end Guaranteed_ABE;
753
754In the example above, the elaboration of ``Guaranteed_ABE``'s body elaborates
755the declaration of ``Val``. This invokes function ``ABE``, however the body of
756``ABE`` has not been elaborated yet. GNAT emits the following diagnostic:
757
758  ::
759
760     4.    Val : constant Integer := ABE;
761                                     |
762        >>> warning: cannot call "ABE" before body seen
763        >>> warning: Program_Error will be raised at run time
764
765A *conditional ABE* arises when the body of a target is not elaborated early
766enough, and causes *some* scenarios that directly invoke the target to fail.
767
768  ::
769
770      1. package body Conditional_ABE is
771      2.    procedure Force_Body is null;
772      3.
773      4.    generic
774      5.       with function Func return Integer;
775      6.    package Gen is
776      7.       Val : constant Integer := Func;
777      8.    end Gen;
778      9.
779     10.    function ABE return Integer;
780     11.
781     12.    function Cause_ABE return Boolean is
782     13.       package Inst is new Gen (ABE);
783     14.    begin
784     15.       ...
785     16.    end Cause_ABE;
786     17.
787     18.    Val : constant Boolean := Cause_ABE;
788     19.
789     20.    function ABE return Integer is
790     21.    begin
791     22.       ...
792     23.    end ABE;
793     24.
794     25.    Safe : constant Boolean := Cause_ABE;
795     26. end Conditional_ABE;
796
797In the example above, the elaboration of package body ``Conditional_ABE``
798elaborates the declaration of ``Val``. This invokes function ``Cause_ABE``,
799which instantiates generic unit ``Gen`` as ``Inst``. The elaboration of
800``Inst`` invokes function ``ABE``, however the body of ``ABE`` has not been
801elaborated yet. GNAT emits the following diagnostic:
802
803  ::
804
805     13.       package Inst is new Gen (ABE);
806               |
807         >>> warning: in instantiation at line 7
808         >>> warning: cannot call "ABE" before body seen
809         >>> warning: Program_Error may be raised at run time
810         >>> warning:   body of unit "Conditional_ABE" elaborated
811         >>> warning:   function "Cause_ABE" called at line 18
812         >>> warning:   function "ABE" called at line 7, instance at line 13
813
814Note that the same ABE problem does not occur with the elaboration of
815declaration ``Safe`` because the body of function ``ABE`` has already been
816elaborated at that point.
817
818.. _SPARK_Diagnostics:
819
820SPARK Diagnostics
821=================
822
823GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
824Manual section 7.7 when compiler switch :switch:`-gnatd.v` is in effect. Note
825that GNAT emits hard errors whenever it encounters a violation of the SPARK
826rules.
827
828  ::
829
830     1. with Server;
831     2. package body SPARK_Diagnostics with SPARK_Mode is
832     3.    Val : constant Integer := Server.Func;
833                                           |
834        >>> call to "Func" during elaboration in SPARK
835        >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
836        >>>   body of unit "SPARK_Model" elaborated
837        >>>   function "Func" called at line 3
838
839     4. end SPARK_Diagnostics;
840
841.. _Elaboration_Circularities:
842
843Elaboration Circularities
844=========================
845
846An **elaboration circularity** occurs whenever the elaboration of a set of
847units enters a deadlocked state, where each unit is waiting for another unit
848to be elaborated. This situation may be the result of improper use of |with|
849clauses, elaboration-control pragmas, or invocations in elaboration code.
850
851The following example exhibits an elaboration circularity.
852
853  ::
854
855     with B; pragma Elaborate (B);
856     package A is
857     end A;
858
859  ::
860
861     package B is
862        procedure Force_Body;
863     end B;
864
865  ::
866
867     with C;
868     package body B is
869        procedure Force_Body is null;
870
871        Elab : constant Integer := C.Func;
872     end B;
873
874  ::
875
876     package C is
877        function Func return Integer;
878     end C;
879
880  ::
881
882     with A;
883     package body C is
884        function Func return Integer is
885        begin
886           ...
887        end Func;
888     end C;
889
890The binder emits the following diagnostic:
891
892  ::
893
894     error: Elaboration circularity detected
895     info:
896     info:    Reason:
897     info:
898     info:      unit "a (spec)" depends on its own elaboration
899     info:
900     info:    Circularity:
901     info:
902     info:      unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
903     info:      unit "b (body)" is in the closure of pragma Elaborate
904     info:      unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
905     info:      unit "c (body)" has with clause for unit "a (spec)"
906     info:
907     info:    Suggestions:
908     info:
909     info:      remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
910     info:      use the dynamic elaboration model (compiler switch -gnatE)
911
912The diagnostic consist of the following sections:
913
914* Reason
915
916  This section provides a short explanation describing why the set of units
917  could not be ordered.
918
919* Circularity
920
921  This section enumerates the units comprising the deadlocked set, along with
922  their interdependencies.
923
924* Suggestions
925
926  This section enumerates various tactics for eliminating the circularity.
927
928.. _Resolving_Elaboration_Circularities:
929
930Resolving Elaboration Circularities
931===================================
932
933The most desirable option from the point of view of long-term maintenance is to
934rearrange the program so that the elaboration problems are avoided. One useful
935technique is to place the elaboration code into separate child packages.
936Another is to move some of the initialization code to explicitly invoked
937subprograms, where the program controls the order of initialization explicitly.
938Although this is the most desirable option, it may be impractical and involve
939too much modification, especially in the case of complex legacy code.
940
941When faced with an elaboration circularity, the programmer should also consider
942the tactics given in the suggestions section of the circularity diagnostic.
943Depending on the units involved in the circularity, their |with| clauses,
944purity, preelaborability, presence of elaboration-control pragmas and
945invocations at elaboration time, the binder may suggest one or more of the
946following tactics to eliminate the circularity:
947
948* Pragma Elaborate elimination
949
950  ::
951
952     remove pragma Elaborate for unit "..." in unit "..."
953
954  This tactic is suggested when the binder has determined that pragma
955  ``Elaborate``:
956
957  - Prevents a set of units from being elaborated.
958
959  - The removal of the pragma will not eliminate the semantic effects of the
960    pragma. In other words, the argument of the pragma will still be elaborated
961    prior to the unit containing the pragma.
962
963  - The removal of the pragma will enable the successful ordering of the units.
964
965  The programmer should remove the pragma as advised, and rebuild the program.
966
967* Pragma Elaborate_All elimination
968
969  ::
970
971     remove pragma Elaborate_All for unit "..." in unit "..."
972
973  This tactic is suggested when the binder has determined that pragma
974  ``Elaborate_All``:
975
976  - Prevents a set of units from being elaborated.
977
978  - The removal of the pragma will not eliminate the semantic effects of the
979    pragma. In other words, the argument of the pragma along with its |with|
980    closure will still be elaborated prior to the unit containing the pragma.
981
982  - The removal of the pragma will enable the successful ordering of the units.
983
984  The programmer should remove the pragma as advised, and rebuild the program.
985
986* Pragma Elaborate_All downgrade
987
988  ::
989
990     change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
991
992  This tactic is always suggested with the pragma ``Elaborate_All`` elimination
993  tactic. It offers a different alernative of guaranteeing that the argument of
994  the pragma will still be elaborated prior to the unit containing the pragma.
995
996  The programmer should update the pragma as advised, and rebuild the program.
997
998* Pragma Elaborate_Body elimination
999
1000  ::
1001
1002     remove pragma Elaborate_Body in unit "..."
1003
1004  This tactic is suggested when the binder has determined that pragma
1005  ``Elaborate_Body``:
1006
1007  - Prevents a set of units from being elaborated.
1008
1009  - The removal of the pragma will enable the successful ordering of the units.
1010
1011  Note that the binder cannot determine whether the pragma is required for
1012  other purposes, such as guaranteeing the initialization of a variable
1013  declared in the spec by elaboration code in the body.
1014
1015  The programmer should remove the pragma as advised, and rebuild the program.
1016
1017* Use of pragma Restrictions
1018
1019  ::
1020
1021     use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
1022
1023  This tactic is suggested when the binder has determined that a task
1024  activation at elaboration time:
1025
1026  - Prevents a set of units from being elaborated.
1027
1028  Note that the binder cannot determine with certainty whether the task will
1029  block at elaboration time.
1030
1031  The programmer should create a configuration file, place the pragma within,
1032  update the general compilation arguments, and rebuild the program.
1033
1034* Use of dynamic elaboration model
1035
1036  ::
1037
1038     use the dynamic elaboration model (compiler switch -gnatE)
1039
1040  This tactic is suggested when the binder has determined that an invocation at
1041  elaboration time:
1042
1043  - Prevents a set of units from being elaborated.
1044
1045  - The use of the dynamic model will enable the successful ordering of the
1046    units.
1047
1048  The programmer has two options:
1049
1050  - Determine the units involved in the invocation using the detailed
1051    invocation information, and add compiler switch :switch:`-gnatE` to the
1052    compilation arguments of selected files only. This approach will yield
1053    safer elaboration orders compared to the other option because it will
1054    minimize the opportunities presented to the dynamic model for ignoring
1055    invocations.
1056
1057  - Add compiler switch :switch:`-gnatE` to the general compilation arguments.
1058
1059* Use of detailed invocation information
1060
1061  ::
1062
1063     use detailed invocation information (compiler switch -gnatd_F)
1064
1065  This tactic is always suggested with the use of the dynamic model tactic. It
1066  causes the circularity section of the circularity diagnostic to describe the
1067  flow of elaboration code from a unit to a unit, enumerating all such paths in
1068  the process.
1069
1070  The programmer should analyze this information to determine which units
1071  should be compiled with the dynamic model.
1072
1073* Forced-dependency elimination
1074
1075  ::
1076
1077     remove the dependency of unit "..." on unit "..." from the argument of switch -f
1078
1079  This tactic is suggested when the binder has determined that a dependency
1080  present in the forced-elaboration-order file indicated by binder switch
1081  :switch:`-f`:
1082
1083  - Prevents a set of units from being elaborated.
1084
1085  - The removal of the dependency will enable the successful ordering of the
1086    units.
1087
1088  The programmer should edit the forced-elaboration-order file, remove the
1089  dependency, and rebind the program.
1090
1091* All forced-dependency elimination
1092
1093  ::
1094
1095     remove switch -f
1096
1097  This tactic is suggested in case editing the forced-elaboration-order file is
1098  not an option.
1099
1100  The programmer should remove binder switch :switch:`-f` from the binder
1101  arguments, and rebind.
1102
1103* Multiple-circularities diagnostic
1104
1105  ::
1106
1107     diagnose all circularities (binder switch -d_C)
1108
1109  By default, the binder will diagnose only the highest-precedence circularity.
1110  If the program contains multiple circularities, the binder will suggest the
1111  use of binder switch :switch:`-d_C` in order to obtain the diagnostics of all
1112  circularities.
1113
1114  The programmer should add binder switch :switch:`-d_C` to the binder
1115  arguments, and rebind.
1116
1117If none of the tactics suggested by the binder eliminate the elaboration
1118circularity, the programmer should consider using one of the legacy elaboration
1119models, in the following order:
1120
1121* Use the pre-20.x legacy elaboration-order model, with binder switch
1122  :switch:`-H`.
1123
1124* Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
1125  switch :switch:`-gnatH` and binder switch :switch:`-H`.
1126
1127* Use the relaxed static-elaboration model, with compiler switches
1128  :switch:`-gnatH` :switch:`-gnatJ` and binder switch :switch:`-H`.
1129
1130* Use the relaxed dynamic-elaboration model, with compiler switches
1131  :switch:`-gnatH` :switch:`-gnatJ` :switch:`-gnatE` and binder switch
1132  :switch:`-H`.
1133
1134.. _Elaboration_Related_Compiler_Switches:
1135
1136Elaboration-related Compiler Switches
1137=====================================
1138
1139GNAT has several switches that affect the elaboration model and consequently
1140the elaboration order chosen by the binder.
1141
1142.. index:: -gnatE  (gnat)
1143
1144:switch:`-gnatE`
1145  Dynamic elaboration checking mode enabled
1146
1147  When this switch is in effect, GNAT activates the dynamic model.
1148
1149.. index:: -gnatel  (gnat)
1150
1151:switch:`-gnatel`
1152  Turn on info messages on generated Elaborate[_All] pragmas
1153
1154  This switch is only applicable to the pre-20.x legacy elaboration models.
1155  The post-20.x elaboration model no longer relies on implicitly generated
1156  ``Elaborate`` and ``Elaborate_All`` pragmas to order units.
1157
1158  When this switch is in effect, GNAT will emit the following supplementary
1159  information depending on the elaboration model in effect.
1160
1161  - *Dynamic model*
1162
1163    GNAT will indicate missing ``Elaborate`` and ``Elaborate_All`` pragmas for
1164    all library-level scenarios within the partition.
1165
1166  - *Static model*
1167
1168    GNAT will indicate all scenarios invoked during elaboration. In addition,
1169    it will provide detailed traceback when an implicit ``Elaborate`` or
1170    ``Elaborate_All`` pragma is generated.
1171
1172  - *SPARK model*
1173
1174    GNAT will indicate how an elaboration requirement is met by the context of
1175    a unit. This diagnostic requires compiler switch :switch:`-gnatd.v`.
1176
1177    ::
1178
1179       1. with Server; pragma Elaborate_All (Server);
1180       2. package Client with SPARK_Mode is
1181       3.    Val : constant Integer := Server.Func;
1182                                             |
1183          >>> info: call to "Func" during elaboration in SPARK
1184          >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
1185
1186       4. end Client;
1187
1188.. index:: -gnatH  (gnat)
1189
1190:switch:`-gnatH`
1191  Legacy elaboration checking mode enabled
1192
1193  When this switch is in effect, GNAT will utilize the pre-18.x elaboration
1194  model.
1195
1196.. index:: -gnatJ  (gnat)
1197
1198:switch:`-gnatJ`
1199  Relaxed elaboration checking mode enabled
1200
1201  When this switch is in effect, GNAT will not process certain scenarios,
1202  resulting in a more permissive elaboration model. Note that this may
1203  eliminate some diagnostics and run-time checks.
1204
1205.. index:: -gnatw.f  (gnat)
1206
1207:switch:`-gnatw.f`
1208  Turn on warnings for suspicious Subp'Access
1209
1210  When this switch is in effect, GNAT will treat ``'Access`` of an entry,
1211  operator, or subprogram as a potential call to the target and issue warnings:
1212
1213  ::
1214
1215     1. package body Attribute_Call is
1216     2.    function Func return Integer;
1217     3.    type Func_Ptr is access function return Integer;
1218     4.
1219     5.    Ptr : constant Func_Ptr := Func'Access;
1220                                          |
1221        >>> warning: "Access" attribute of "Func" before body seen
1222        >>> warning: possible Program_Error on later references
1223        >>> warning:   body of unit "Attribute_Call" elaborated
1224        >>> warning:   "Access" of "Func" taken at line 5
1225
1226     6.
1227     7.    function Func return Integer is
1228     8.    begin
1229     9.       ...
1230    10.    end Func;
1231    11. end Attribute_Call;
1232
1233  In the example above, the elaboration of declaration ``Ptr`` is assigned
1234  ``Func'Access`` before the body of ``Func`` has been elaborated.
1235
1236.. index:: -gnatwl  (gnat)
1237
1238:switch:`-gnatwl`
1239  Turn on warnings for elaboration problems
1240
1241  When this switch is in effect, GNAT emits diagnostics in the form of warnings
1242  concerning various elaboration problems. The warnings are enabled by default.
1243  The switch is provided in case all warnings are suppressed, but elaboration
1244  warnings are still desired.
1245
1246:switch:`-gnatwL`
1247  Turn off warnings for elaboration problems
1248
1249  When this switch is in effect, GNAT no longer emits any diagnostics in the
1250  form of warnings. Selective suppression of elaboration problems is possible
1251  using ``pragma Warnings (Off)``.
1252
1253  ::
1254
1255     1. package body Selective_Suppression is
1256     2.    function ABE return Integer;
1257     3.
1258     4.    Val_1 : constant Integer := ABE;
1259                                       |
1260        >>> warning: cannot call "ABE" before body seen
1261        >>> warning: Program_Error will be raised at run time
1262
1263     5.
1264     6.    pragma Warnings (Off);
1265     7.    Val_2 : constant Integer := ABE;
1266     8.    pragma Warnings (On);
1267     9.
1268    10.    function ABE return Integer is
1269    11.    begin
1270    12.       ...
1271    13.    end ABE;
1272    14. end Selective_Suppression;
1273
1274  Note that suppressing elaboration warnings does not eliminate run-time
1275  checks. The example above will still fail at run time with an ABE.
1276
1277.. _Summary_of_Procedures_for_Elaboration_Control:
1278
1279Summary of Procedures for Elaboration Control
1280=============================================
1281
1282A programmer should first compile the program with the default options, using
1283none of the binder or compiler switches. If the binder succeeds in finding an
1284elaboration order, then apart from possible cases involing dispatching calls
1285and access-to-subprogram types, the program is free of elaboration errors.
1286
1287If it is important for the program to be portable to compilers other than GNAT,
1288then the programmer should use compiler switch :switch:`-gnatel` and consider
1289the messages about missing or implicitly created ``Elaborate`` and
1290``Elaborate_All`` pragmas.
1291
1292If the binder reports an elaboration circularity, the programmer has several
1293options:
1294
1295* Ensure that elaboration warnings are enabled. This will allow the static
1296  model to output trace information of elaboration issues. The trace
1297  information could shed light on previously unforeseen dependencies, as well
1298  as their origins. Elaboration warnings are enabled with compiler switch
1299  :switch:`-gnatwl`.
1300
1301* Cosider the tactics given in the suggestions section of the circularity
1302  diagnostic.
1303
1304* If none of the steps outlined above resolve the circularity, use a more
1305  permissive elaboration model, in the following order:
1306
1307  - Use the pre-20.x legacy elaboration-order model, with binder switch
1308    :switch:`-H`.
1309
1310  - Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
1311    switch :switch:`-gnatH` and binder switch :switch:`-H`.
1312
1313  - Use the relaxed static elaboration model, with compiler switches
1314    :switch:`-gnatH` :switch:`-gnatJ` and binder switch :switch:`-H`.
1315
1316  - Use the relaxed dynamic elaboration model, with compiler switches
1317    :switch:`-gnatH` :switch:`-gnatJ` :switch:`-gnatE` and binder switch
1318    :switch:`-H`.
1319
1320.. _Inspecting_the_Chosen_Elaboration_Order:
1321
1322Inspecting the Chosen Elaboration Order
1323=======================================
1324
1325To see the elaboration order chosen by the binder, inspect the contents of file
1326`b~xxx.adb`. On certain targets, this file appears as `b_xxx.adb`. The
1327elaboration order appears as a sequence of calls to ``Elab_Body`` and
1328``Elab_Spec``, interspersed with assignments to `Exxx` which indicates that a
1329particular unit is elaborated. For example:
1330
1331  ::
1332
1333     System.Soft_Links'Elab_Body;
1334     E14 := True;
1335     System.Secondary_Stack'Elab_Body;
1336     E18 := True;
1337     System.Exception_Table'Elab_Body;
1338     E24 := True;
1339     Ada.Io_Exceptions'Elab_Spec;
1340     E67 := True;
1341     Ada.Tags'Elab_Spec;
1342     Ada.Streams'Elab_Spec;
1343     E43 := True;
1344     Interfaces.C'Elab_Spec;
1345     E69 := True;
1346     System.Finalization_Root'Elab_Spec;
1347     E60 := True;
1348     System.Os_Lib'Elab_Body;
1349     E71 := True;
1350     System.Finalization_Implementation'Elab_Spec;
1351     System.Finalization_Implementation'Elab_Body;
1352     E62 := True;
1353     Ada.Finalization'Elab_Spec;
1354     E58 := True;
1355     Ada.Finalization.List_Controller'Elab_Spec;
1356     E76 := True;
1357     System.File_Control_Block'Elab_Spec;
1358     E74 := True;
1359     System.File_Io'Elab_Body;
1360     E56 := True;
1361     Ada.Tags'Elab_Body;
1362     E45 := True;
1363     Ada.Text_Io'Elab_Spec;
1364     Ada.Text_Io'Elab_Body;
1365     E07 := True;
1366
1367Note also binder switch :switch:`-l`, which outputs the chosen elaboration
1368order and provides a more readable form of the above:
1369
1370  ::
1371
1372     ada (spec)
1373     interfaces (spec)
1374     system (spec)
1375     system.case_util (spec)
1376     system.case_util (body)
1377     system.concat_2 (spec)
1378     system.concat_2 (body)
1379     system.concat_3 (spec)
1380     system.concat_3 (body)
1381     system.htable (spec)
1382     system.parameters (spec)
1383     system.parameters (body)
1384     system.crtl (spec)
1385     interfaces.c_streams (spec)
1386     interfaces.c_streams (body)
1387     system.restrictions (spec)
1388     system.restrictions (body)
1389     system.standard_library (spec)
1390     system.exceptions (spec)
1391     system.exceptions (body)
1392     system.storage_elements (spec)
1393     system.storage_elements (body)
1394     system.secondary_stack (spec)
1395     system.stack_checking (spec)
1396     system.stack_checking (body)
1397     system.string_hash (spec)
1398     system.string_hash (body)
1399     system.htable (body)
1400     system.strings (spec)
1401     system.strings (body)
1402     system.traceback (spec)
1403     system.traceback (body)
1404     system.traceback_entries (spec)
1405     system.traceback_entries (body)
1406     ada.exceptions (spec)
1407     ada.exceptions.last_chance_handler (spec)
1408     system.soft_links (spec)
1409     system.soft_links (body)
1410     ada.exceptions.last_chance_handler (body)
1411     system.secondary_stack (body)
1412     system.exception_table (spec)
1413     system.exception_table (body)
1414     ada.io_exceptions (spec)
1415     ada.tags (spec)
1416     ada.streams (spec)
1417     interfaces.c (spec)
1418     interfaces.c (body)
1419     system.finalization_root (spec)
1420     system.finalization_root (body)
1421     system.memory (spec)
1422     system.memory (body)
1423     system.standard_library (body)
1424     system.os_lib (spec)
1425     system.os_lib (body)
1426     system.unsigned_types (spec)
1427     system.stream_attributes (spec)
1428     system.stream_attributes (body)
1429     system.finalization_implementation (spec)
1430     system.finalization_implementation (body)
1431     ada.finalization (spec)
1432     ada.finalization (body)
1433     ada.finalization.list_controller (spec)
1434     ada.finalization.list_controller (body)
1435     system.file_control_block (spec)
1436     system.file_io (spec)
1437     system.file_io (body)
1438     system.val_uns (spec)
1439     system.val_util (spec)
1440     system.val_util (body)
1441     system.val_uns (body)
1442     system.wch_con (spec)
1443     system.wch_con (body)
1444     system.wch_cnv (spec)
1445     system.wch_jis (spec)
1446     system.wch_jis (body)
1447     system.wch_cnv (body)
1448     system.wch_stw (spec)
1449     system.wch_stw (body)
1450     ada.tags (body)
1451     ada.exceptions (body)
1452     ada.text_io (spec)
1453     ada.text_io (body)
1454     text_io (spec)
1455     gdbstr (body)
1456