1------------------------------------------------------------------------------
2--                                                                          --
3--                         GNAT COMPILER COMPONENTS                         --
4--                                                                          --
5--                              S E M _ C H 7                               --
6--                                                                          --
7--                                 B o d y                                  --
8--                                                                          --
9--          Copyright (C) 1992-2019, Free Software Foundation, Inc.         --
10--                                                                          --
11-- GNAT is free software;  you can  redistribute it  and/or modify it under --
12-- terms of the  GNU General Public License as published  by the Free Soft- --
13-- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14-- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15-- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16-- or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License --
17-- for  more details.  You should have  received  a copy of the GNU General --
18-- Public License  distributed with GNAT; see file COPYING3.  If not, go to --
19-- http://www.gnu.org/licenses for a complete copy of the license.          --
20--                                                                          --
21-- GNAT was originally developed  by the GNAT team at  New York University. --
22-- Extensive contributions were provided by Ada Core Technologies Inc.      --
23--                                                                          --
24------------------------------------------------------------------------------
25
26--  This package contains the routines to process package specifications and
27--  bodies. The most important semantic aspects of package processing are the
28--  handling of private and full declarations, and the construction of dispatch
29--  tables for tagged types.
30
31with Aspects;   use Aspects;
32with Atree;     use Atree;
33with Contracts; use Contracts;
34with Debug;     use Debug;
35with Einfo;     use Einfo;
36with Elists;    use Elists;
37with Errout;    use Errout;
38with Exp_Disp;  use Exp_Disp;
39with Exp_Dist;  use Exp_Dist;
40with Exp_Dbug;  use Exp_Dbug;
41with Freeze;    use Freeze;
42with Ghost;     use Ghost;
43with Lib;       use Lib;
44with Lib.Xref;  use Lib.Xref;
45with Namet;     use Namet;
46with Nmake;     use Nmake;
47with Nlists;    use Nlists;
48with Opt;       use Opt;
49with Output;    use Output;
50with Restrict;  use Restrict;
51with Rtsfind;   use Rtsfind;
52with Sem;       use Sem;
53with Sem_Aux;   use Sem_Aux;
54with Sem_Cat;   use Sem_Cat;
55with Sem_Ch3;   use Sem_Ch3;
56with Sem_Ch6;   use Sem_Ch6;
57with Sem_Ch8;   use Sem_Ch8;
58with Sem_Ch10;  use Sem_Ch10;
59with Sem_Ch12;  use Sem_Ch12;
60with Sem_Ch13;  use Sem_Ch13;
61with Sem_Disp;  use Sem_Disp;
62with Sem_Eval;  use Sem_Eval;
63with Sem_Prag;  use Sem_Prag;
64with Sem_Util;  use Sem_Util;
65with Sem_Warn;  use Sem_Warn;
66with Snames;    use Snames;
67with Stand;     use Stand;
68with Sinfo;     use Sinfo;
69with Sinput;    use Sinput;
70with Style;
71with Uintp;     use Uintp;
72
73with GNAT.HTable;
74
75package body Sem_Ch7 is
76
77   -----------------------------------
78   -- Handling private declarations --
79   -----------------------------------
80
81   --  The principle that each entity has a single defining occurrence clashes
82   --  with the presence of two separate definitions for private types: the
83   --  first is the private type declaration, and the second is the full type
84   --  declaration. It is important that all references to the type point to
85   --  the same defining occurrence, namely the first one. To enforce the two
86   --  separate views of the entity, the corresponding information is swapped
87   --  between the two declarations. Outside of the package, the defining
88   --  occurrence only contains the private declaration information, while in
89   --  the private part and the body of the package the defining occurrence
90   --  contains the full declaration. To simplify the swap, the defining
91   --  occurrence that currently holds the private declaration points to the
92   --  full declaration. During semantic processing the defining occurrence
93   --  also points to a list of private dependents, that is to say access types
94   --  or composite types whose designated types or component types are
95   --  subtypes or derived types of the private type in question. After the
96   --  full declaration has been seen, the private dependents are updated to
97   --  indicate that they have full definitions.
98
99   -----------------------
100   -- Local Subprograms --
101   -----------------------
102
103   procedure Analyze_Package_Body_Helper (N : Node_Id);
104   --  Does all the real work of Analyze_Package_Body
105
106   procedure Check_Anonymous_Access_Types
107     (Spec_Id : Entity_Id;
108      P_Body  : Node_Id);
109   --  If the spec of a package has a limited_with_clause, it may declare
110   --  anonymous access types whose designated type is a limited view, such an
111   --  anonymous access return type for a function. This access type cannot be
112   --  elaborated in the spec itself, but it may need an itype reference if it
113   --  is used within a nested scope. In that case the itype reference is
114   --  created at the beginning of the corresponding package body and inserted
115   --  before other body declarations.
116
117   procedure Declare_Inherited_Private_Subprograms (Id : Entity_Id);
118   --  Called upon entering the private part of a public child package and the
119   --  body of a nested package, to potentially declare certain inherited
120   --  subprograms that were inherited by types in the visible part, but whose
121   --  declaration was deferred because the parent operation was private and
122   --  not visible at that point. These subprograms are located by traversing
123   --  the visible part declarations looking for non-private type extensions
124   --  and then examining each of the primitive operations of such types to
125   --  find those that were inherited but declared with a special internal
126   --  name. Each such operation is now declared as an operation with a normal
127   --  name (using the name of the parent operation) and replaces the previous
128   --  implicit operation in the primitive operations list of the type. If the
129   --  inherited private operation has been overridden, then it's replaced by
130   --  the overriding operation.
131
132   procedure Install_Package_Entity (Id : Entity_Id);
133   --  Supporting procedure for Install_{Visible,Private}_Declarations. Places
134   --  one entity on its visibility chain, and recurses on the visible part if
135   --  the entity is an inner package.
136
137   function Is_Private_Base_Type (E : Entity_Id) return Boolean;
138   --  True for a private type that is not a subtype
139
140   function Is_Visible_Dependent (Dep : Entity_Id) return Boolean;
141   --  If the private dependent is a private type whose full view is derived
142   --  from the parent type, its full properties are revealed only if we are in
143   --  the immediate scope of the private dependent. Should this predicate be
144   --  tightened further???
145
146   function Requires_Completion_In_Body
147     (Id                 : Entity_Id;
148      Pack_Id            : Entity_Id;
149      Do_Abstract_States : Boolean := False) return Boolean;
150   --  Subsidiary to routines Unit_Requires_Body and Unit_Requires_Body_Info.
151   --  Determine whether entity Id declared in package spec Pack_Id requires
152   --  completion in a package body. Flag Do_Abstract_Stats should be set when
153   --  abstract states are to be considered in the completion test.
154
155   procedure Unit_Requires_Body_Info (Pack_Id : Entity_Id);
156   --  Outputs info messages showing why package Pack_Id requires a body. The
157   --  caller has checked that the switch requesting this information is set,
158   --  and that the package does indeed require a body.
159
160   --------------------------
161   -- Analyze_Package_Body --
162   --------------------------
163
164   procedure Analyze_Package_Body (N : Node_Id) is
165      Loc : constant Source_Ptr := Sloc (N);
166
167   begin
168      if Debug_Flag_C then
169         Write_Str ("==> package body ");
170         Write_Name (Chars (Defining_Entity (N)));
171         Write_Str (" from ");
172         Write_Location (Loc);
173         Write_Eol;
174         Indent;
175      end if;
176
177      --  The real work is split out into the helper, so it can do "return;"
178      --  without skipping the debug output.
179
180      Analyze_Package_Body_Helper (N);
181
182      if Debug_Flag_C then
183         Outdent;
184         Write_Str ("<== package body ");
185         Write_Name (Chars (Defining_Entity (N)));
186         Write_Str (" from ");
187         Write_Location (Loc);
188         Write_Eol;
189      end if;
190   end Analyze_Package_Body;
191
192   ------------------------------------------------------
193   -- Analyze_Package_Body_Helper Data and Subprograms --
194   ------------------------------------------------------
195
196   Entity_Table_Size : constant := 4093;
197   --  Number of headers in hash table
198
199   subtype Entity_Header_Num is Integer range 0 .. Entity_Table_Size - 1;
200   --  Range of headers in hash table
201
202   function Node_Hash (Id : Entity_Id) return Entity_Header_Num;
203   --  Simple hash function for Entity_Ids
204
205   package Subprogram_Table is new GNAT.Htable.Simple_HTable
206     (Header_Num => Entity_Header_Num,
207      Element    => Boolean,
208      No_Element => False,
209      Key        => Entity_Id,
210      Hash       => Node_Hash,
211      Equal      => "=");
212   --  Hash table to record which subprograms are referenced. It is declared
213   --  at library level to avoid elaborating it for every call to Analyze.
214
215   package Traversed_Table is new GNAT.Htable.Simple_HTable
216     (Header_Num => Entity_Header_Num,
217      Element    => Boolean,
218      No_Element => False,
219      Key        => Node_Id,
220      Hash       => Node_Hash,
221      Equal      => "=");
222   --  Hash table to record which nodes we have traversed, so we can avoid
223   --  traversing the same nodes repeatedly.
224
225   -----------------
226   -- Node_Hash --
227   -----------------
228
229   function Node_Hash (Id : Entity_Id) return Entity_Header_Num is
230   begin
231      return Entity_Header_Num (Id mod Entity_Table_Size);
232   end Node_Hash;
233
234   ---------------------------------
235   -- Analyze_Package_Body_Helper --
236   ---------------------------------
237
238   --  WARNING: This routine manages Ghost regions. Return statements must be
239   --  replaced by gotos which jump to the end of the routine and restore the
240   --  Ghost mode.
241
242   procedure Analyze_Package_Body_Helper (N : Node_Id) is
243      procedure Hide_Public_Entities (Decls : List_Id);
244      --  Attempt to hide all public entities found in declarative list Decls
245      --  by resetting their Is_Public flag to False depending on whether the
246      --  entities are not referenced by inlined or generic bodies. This kind
247      --  of processing is a conservative approximation and will still leave
248      --  entities externally visible if the package is not simple enough.
249
250      procedure Install_Composite_Operations (P : Entity_Id);
251      --  Composite types declared in the current scope may depend on types
252      --  that were private at the point of declaration, and whose full view
253      --  is now in scope. Indicate that the corresponding operations on the
254      --  composite type are available.
255
256      --------------------------
257      -- Hide_Public_Entities --
258      --------------------------
259
260      procedure Hide_Public_Entities (Decls : List_Id) is
261         function Has_Referencer
262           (Decls                                   : List_Id;
263            In_Nested_Instance                      : Boolean;
264            Has_Outer_Referencer_Of_Non_Subprograms : Boolean) return Boolean;
265         --  A "referencer" is a construct which may reference a previous
266         --  declaration. Examine all declarations in list Decls in reverse
267         --  and determine whether one such referencer exists. All entities
268         --  in the range Last (Decls) .. Referencer are hidden from external
269         --  visibility.
270
271         function Scan_Subprogram_Ref (N : Node_Id) return Traverse_Result;
272         --  Determine whether a node denotes a reference to a subprogram
273
274         procedure Traverse_And_Scan_Subprogram_Refs is
275           new Traverse_Proc (Scan_Subprogram_Ref);
276         --  Subsidiary to routine Has_Referencer. Determine whether a node
277         --  contains references to a subprogram and record them.
278         --  WARNING: this is a very expensive routine as it performs a full
279         --  tree traversal.
280
281         procedure Scan_Subprogram_Refs (Node : Node_Id);
282         --  If we haven't already traversed Node, then mark it and traverse
283         --  it.
284
285         --------------------
286         -- Has_Referencer --
287         --------------------
288
289         function Has_Referencer
290           (Decls                                   : List_Id;
291            In_Nested_Instance                      : Boolean;
292            Has_Outer_Referencer_Of_Non_Subprograms : Boolean) return Boolean
293         is
294            Decl    : Node_Id;
295            Decl_Id : Entity_Id;
296            Spec    : Node_Id;
297
298            Has_Referencer_Of_Non_Subprograms : Boolean :=
299                                       Has_Outer_Referencer_Of_Non_Subprograms;
300            --  Set if an inlined subprogram body was detected as a referencer.
301            --  In this case, we do not return True immediately but keep hiding
302            --  subprograms from external visibility.
303
304         begin
305            if No (Decls) then
306               return False;
307            end if;
308
309            --  Examine all declarations in reverse order, hiding all entities
310            --  from external visibility until a referencer has been found. The
311            --  algorithm recurses into nested packages.
312
313            Decl := Last (Decls);
314            while Present (Decl) loop
315
316               --  A stub is always considered a referencer
317
318               if Nkind (Decl) in N_Body_Stub then
319                  return True;
320
321               --  Package declaration
322
323               elsif Nkind (Decl) = N_Package_Declaration then
324                  Spec := Specification (Decl);
325                  Decl_Id := Defining_Entity (Spec);
326
327                  --  Inspect the declarations of a non-generic package to try
328                  --  and hide more entities from external visibility.
329
330                  if not Is_Generic_Unit (Decl_Id) then
331                     if Has_Referencer (Private_Declarations (Spec),
332                                        In_Nested_Instance
333                                          or else
334                                        Is_Generic_Instance (Decl_Id),
335                                        Has_Referencer_Of_Non_Subprograms)
336                       or else
337                        Has_Referencer (Visible_Declarations (Spec),
338                                        In_Nested_Instance
339                                          or else
340                                        Is_Generic_Instance (Decl_Id),
341                                        Has_Referencer_Of_Non_Subprograms)
342                     then
343                        return True;
344                     end if;
345                  end if;
346
347               --  Package body
348
349               elsif Nkind (Decl) = N_Package_Body
350                 and then Present (Corresponding_Spec (Decl))
351               then
352                  Decl_Id := Corresponding_Spec (Decl);
353
354                  --  A generic package body is a referencer. It would seem
355                  --  that we only have to consider generics that can be
356                  --  exported, i.e. where the corresponding spec is the
357                  --  spec of the current package, but because of nested
358                  --  instantiations, a fully private generic body may export
359                  --  other private body entities. Furthermore, regardless of
360                  --  whether there was a previous inlined subprogram, (an
361                  --  instantiation of) the generic package may reference any
362                  --  entity declared before it.
363
364                  if Is_Generic_Unit (Decl_Id) then
365                     return True;
366
367                  --  Inspect the declarations of a non-generic package body to
368                  --  try and hide more entities from external visibility.
369
370                  elsif Has_Referencer (Declarations (Decl),
371                                        In_Nested_Instance
372                                          or else
373                                        Is_Generic_Instance (Decl_Id),
374                                        Has_Referencer_Of_Non_Subprograms)
375                  then
376                     return True;
377                  end if;
378
379               --  Subprogram body
380
381               elsif Nkind (Decl) = N_Subprogram_Body then
382                  if Present (Corresponding_Spec (Decl)) then
383                     Decl_Id := Corresponding_Spec (Decl);
384
385                     --  A generic subprogram body acts as a referencer
386
387                     if Is_Generic_Unit (Decl_Id) then
388                        return True;
389                     end if;
390
391                     --  An inlined subprogram body acts as a referencer
392                     --  unless we generate C code since inlining is then
393                     --  handled by the C compiler.
394
395                     --  Note that we test Has_Pragma_Inline here in addition
396                     --  to Is_Inlined. We are doing this for a client, since
397                     --  we are computing which entities should be public, and
398                     --  it is the client who will decide if actual inlining
399                     --  should occur, so we need to catch all cases where the
400                     --  subprogram may be inlined by the client.
401
402                     if not Generate_C_Code
403                       and then (Is_Inlined (Decl_Id)
404                                  or else Has_Pragma_Inline (Decl_Id))
405                     then
406                        Has_Referencer_Of_Non_Subprograms := True;
407
408                        --  Inspect the statements of the subprogram body
409                        --  to determine whether the body references other
410                        --  subprograms.
411
412                        Scan_Subprogram_Refs (Decl);
413                     end if;
414
415                  --  Otherwise this is a stand alone subprogram body
416
417                  else
418                     Decl_Id := Defining_Entity (Decl);
419
420                     --  An inlined subprogram body acts as a referencer
421                     --  unless we generate C code since inlining is then
422                     --  handled by the C compiler.
423
424                     if not Generate_C_Code
425                       and then (Is_Inlined (Decl_Id)
426                                  or else Has_Pragma_Inline (Decl_Id))
427                     then
428                        Has_Referencer_Of_Non_Subprograms := True;
429
430                        --  Inspect the statements of the subprogram body
431                        --  to determine whether the body references other
432                        --  subprograms.
433
434                        Scan_Subprogram_Refs (Decl);
435
436                     --  Otherwise we can reset Is_Public right away
437
438                     elsif not Subprogram_Table.Get (Decl_Id) then
439                        Set_Is_Public (Decl_Id, False);
440                     end if;
441                  end if;
442
443               --  Freeze node
444
445               elsif Nkind (Decl) = N_Freeze_Entity then
446                  declare
447                     Discard : Boolean;
448                     pragma Unreferenced (Discard);
449                  begin
450                     --  Inspect the actions to find references to subprograms.
451                     --  We assume that the actions do not contain other kinds
452                     --  of references and, therefore, we do not stop the scan
453                     --  or set Has_Referencer_Of_Non_Subprograms here. Doing
454                     --  it would pessimize common cases for which the actions
455                     --  contain the declaration of an init procedure, since
456                     --  such a procedure is automatically marked inline.
457
458                     Discard :=
459                       Has_Referencer (Actions (Decl),
460                                       In_Nested_Instance,
461                                       Has_Referencer_Of_Non_Subprograms);
462                  end;
463
464               --  Exceptions, objects and renamings do not need to be public
465               --  if they are not followed by a construct which can reference
466               --  and export them. Likewise for subprograms but we work harder
467               --  for them to see whether they are referenced on an individual
468               --  basis by looking into the table of referenced subprograms.
469               --  But we cannot say anything for entities declared in nested
470               --  instances because instantiations are not done yet so the
471               --  bodies are not visible and could contain references to them.
472               elsif Nkind_In (Decl, N_Exception_Declaration,
473                                     N_Object_Declaration,
474                                     N_Object_Renaming_Declaration,
475                                     N_Subprogram_Declaration,
476                                     N_Subprogram_Renaming_Declaration)
477               then
478                  Decl_Id := Defining_Entity (Decl);
479
480                  if not In_Nested_Instance
481                    and then not Is_Imported (Decl_Id)
482                    and then not Is_Exported (Decl_Id)
483                    and then No (Interface_Name (Decl_Id))
484                    and then
485                      ((Nkind (Decl) /= N_Subprogram_Declaration
486                         and then not Has_Referencer_Of_Non_Subprograms)
487                        or else (Nkind (Decl) = N_Subprogram_Declaration
488                                  and then not Subprogram_Table.Get (Decl_Id)))
489                  then
490                     Set_Is_Public (Decl_Id, False);
491                  end if;
492
493                  --  For a subprogram renaming, if the entity is referenced,
494                  --  then so is the renamed subprogram. But there is an issue
495                  --  with generic bodies because instantiations are not done
496                  --  yet and, therefore, cannot be scanned for referencers.
497                  --  That's why we use an approximation and test that we have
498                  --  at least one subprogram referenced by an inlined body
499                  --  instead of precisely the entity of this renaming.
500
501                  if Nkind (Decl) = N_Subprogram_Renaming_Declaration
502                    and then Subprogram_Table.Get_First
503                    and then Is_Entity_Name (Name (Decl))
504                    and then Present (Entity (Name (Decl)))
505                    and then Is_Subprogram (Entity (Name (Decl)))
506                  then
507                     Subprogram_Table.Set (Entity (Name (Decl)), True);
508                  end if;
509               end if;
510
511               Prev (Decl);
512            end loop;
513
514            return Has_Referencer_Of_Non_Subprograms;
515         end Has_Referencer;
516
517         -------------------------
518         -- Scan_Subprogram_Ref --
519         -------------------------
520
521         function Scan_Subprogram_Ref (N : Node_Id) return Traverse_Result is
522         begin
523            --  Detect a reference of the form
524            --    Subp_Call
525
526            if Nkind (N) in N_Subprogram_Call
527              and then Is_Entity_Name (Name (N))
528              and then Present (Entity (Name (N)))
529              and then Is_Subprogram (Entity (Name (N)))
530            then
531               Subprogram_Table.Set (Entity (Name (N)), True);
532
533            --  Detect a reference of the form
534            --    Subp'Some_Attribute
535
536            elsif Nkind (N) = N_Attribute_Reference
537              and then Is_Entity_Name (Prefix (N))
538              and then Present (Entity (Prefix (N)))
539              and then Is_Subprogram (Entity (Prefix (N)))
540            then
541               Subprogram_Table.Set (Entity (Prefix (N)), True);
542
543            --  Constants can be substituted by their value in gigi, which may
544            --  contain a reference, so scan the value recursively.
545
546            elsif Is_Entity_Name (N)
547              and then Present (Entity (N))
548              and then Ekind (Entity (N)) = E_Constant
549            then
550               declare
551                  Val : constant Node_Id := Constant_Value (Entity (N));
552               begin
553                  if Present (Val)
554                    and then not Compile_Time_Known_Value (Val)
555                  then
556                     Scan_Subprogram_Refs (Val);
557                  end if;
558               end;
559            end if;
560
561            return OK;
562         end Scan_Subprogram_Ref;
563
564         --------------------------
565         -- Scan_Subprogram_Refs --
566         --------------------------
567
568         procedure Scan_Subprogram_Refs (Node : Node_Id) is
569         begin
570            if not Traversed_Table.Get (Node) then
571               Traversed_Table.Set (Node, True);
572               Traverse_And_Scan_Subprogram_Refs (Node);
573            end if;
574         end Scan_Subprogram_Refs;
575
576         --  Local variables
577
578         Discard : Boolean;
579         pragma Unreferenced (Discard);
580
581      --  Start of processing for Hide_Public_Entities
582
583      begin
584         --  The algorithm examines the top level declarations of a package
585         --  body in reverse looking for a construct that may export entities
586         --  declared prior to it. If such a scenario is encountered, then all
587         --  entities in the range Last (Decls) .. construct are hidden from
588         --  external visibility. Consider:
589
590         --    package Pack is
591         --       generic
592         --       package Gen is
593         --       end Gen;
594         --    end Pack;
595
596         --    package body Pack is
597         --       External_Obj : ...;      --  (1)
598
599         --       package body Gen is      --  (2)
600         --          ... External_Obj ...  --  (3)
601         --       end Gen;
602
603         --       Local_Obj : ...;         --  (4)
604         --    end Pack;
605
606         --  In this example Local_Obj (4) must not be externally visible as
607         --  it cannot be exported by anything in Pack. The body of generic
608         --  package Gen (2) on the other hand acts as a "referencer" and may
609         --  export anything declared before it. Since the compiler does not
610         --  perform flow analysis, it is not possible to determine precisely
611         --  which entities will be exported when Gen is instantiated. In the
612         --  example above External_Obj (1) is exported at (3), but this may
613         --  not always be the case. The algorithm takes a conservative stance
614         --  and leaves entity External_Obj public.
615
616         --  This very conservative algorithm is supplemented by a more precise
617         --  processing for inlined bodies. For them, we traverse the syntactic
618         --  tree and record which subprograms are actually referenced from it.
619         --  This makes it possible to compute a much smaller set of externally
620         --  visible subprograms in the absence of generic bodies, which can
621         --  have a significant impact on the inlining decisions made in the
622         --  back end and the removal of out-of-line bodies from the object
623         --  code. We do it only for inlined bodies because they are supposed
624         --  to be reasonably small and tree traversal is very expensive.
625
626         --  Note that even this special processing is not optimal for inlined
627         --  bodies, because we treat all inlined subprograms alike. An optimal
628         --  algorithm would require computing the transitive closure of the
629         --  inlined subprograms that can really be referenced from other units
630         --  in the source code.
631
632         --  We could extend this processing for inlined bodies and record all
633         --  entities, not just subprograms, referenced from them, which would
634         --  make it possible to compute a much smaller set of all externally
635         --  visible entities in the absence of generic bodies. But this would
636         --  mean implementing a more thorough tree traversal of the bodies,
637         --  i.e. not just syntactic, and the gain would very likely be worth
638         --  neither the hassle nor the slowdown of the compiler.
639
640         --  Finally, an important thing to be aware of is that, at this point,
641         --  instantiations are not done yet so we cannot directly see inlined
642         --  bodies coming from them. That's not catastrophic because only the
643         --  actual parameters of the instantiations matter here, and they are
644         --  present in the declarations list of the instantiated packages.
645
646         Traversed_Table.Reset;
647         Subprogram_Table.Reset;
648         Discard := Has_Referencer (Decls, False, False);
649      end Hide_Public_Entities;
650
651      ----------------------------------
652      -- Install_Composite_Operations --
653      ----------------------------------
654
655      procedure Install_Composite_Operations (P : Entity_Id) is
656         Id : Entity_Id;
657
658      begin
659         Id := First_Entity (P);
660         while Present (Id) loop
661            if Is_Type (Id)
662              and then (Is_Limited_Composite (Id)
663                         or else Is_Private_Composite (Id))
664              and then No (Private_Component (Id))
665            then
666               Set_Is_Limited_Composite (Id, False);
667               Set_Is_Private_Composite (Id, False);
668            end if;
669
670            Next_Entity (Id);
671         end loop;
672      end Install_Composite_Operations;
673
674      --  Local variables
675
676      Saved_GM   : constant Ghost_Mode_Type := Ghost_Mode;
677      Saved_IGR  : constant Node_Id         := Ignored_Ghost_Region;
678      Saved_EA   : constant Boolean         := Expander_Active;
679      Saved_ISMP : constant Boolean         :=
680                     Ignore_SPARK_Mode_Pragmas_In_Instance;
681      --  Save the Ghost and SPARK mode-related data to restore on exit
682
683      Body_Id          : Entity_Id;
684      HSS              : Node_Id;
685      Last_Spec_Entity : Entity_Id;
686      New_N            : Node_Id;
687      Pack_Decl        : Node_Id;
688      Spec_Id          : Entity_Id;
689
690   --  Start of processing for Analyze_Package_Body_Helper
691
692   begin
693      --  Find corresponding package specification, and establish the current
694      --  scope. The visible defining entity for the package is the defining
695      --  occurrence in the spec. On exit from the package body, all body
696      --  declarations are attached to the defining entity for the body, but
697      --  the later is never used for name resolution. In this fashion there
698      --  is only one visible entity that denotes the package.
699
700      --  Set Body_Id. Note that this will be reset to point to the generic
701      --  copy later on in the generic case.
702
703      Body_Id := Defining_Entity (N);
704
705      --  Body is body of package instantiation. Corresponding spec has already
706      --  been set.
707
708      if Present (Corresponding_Spec (N)) then
709         Spec_Id   := Corresponding_Spec (N);
710         Pack_Decl := Unit_Declaration_Node (Spec_Id);
711
712      else
713         Spec_Id := Current_Entity_In_Scope (Defining_Entity (N));
714
715         if Present (Spec_Id)
716           and then Is_Package_Or_Generic_Package (Spec_Id)
717         then
718            Pack_Decl := Unit_Declaration_Node (Spec_Id);
719
720            if Nkind (Pack_Decl) = N_Package_Renaming_Declaration then
721               Error_Msg_N ("cannot supply body for package renaming", N);
722               return;
723
724            elsif Present (Corresponding_Body (Pack_Decl)) then
725               Error_Msg_N ("redefinition of package body", N);
726               return;
727            end if;
728
729         else
730            Error_Msg_N ("missing specification for package body", N);
731            return;
732         end if;
733
734         if Is_Package_Or_Generic_Package (Spec_Id)
735           and then (Scope (Spec_Id) = Standard_Standard
736                      or else Is_Child_Unit (Spec_Id))
737           and then not Unit_Requires_Body (Spec_Id)
738         then
739            if Ada_Version = Ada_83 then
740               Error_Msg_N
741                 ("optional package body (not allowed in Ada 95)??", N);
742            else
743               Error_Msg_N ("spec of this package does not allow a body", N);
744            end if;
745         end if;
746      end if;
747
748      --  A [generic] package body freezes the contract of the nearest
749      --  enclosing package body and all other contracts encountered in
750      --  the same declarative part up to and excluding the package body:
751
752      --    package body Nearest_Enclosing_Package
753      --      with Refined_State => (State => Constit)
754      --    is
755      --       Constit : ...;
756
757      --       package body Freezes_Enclosing_Package_Body
758      --         with Refined_State => (State_2 => Constit_2)
759      --       is
760      --          Constit_2 : ...;
761
762      --          procedure Proc
763      --            with Refined_Depends => (Input => (Constit, Constit_2)) ...
764
765      --  This ensures that any annotations referenced by the contract of a
766      --  [generic] subprogram body declared within the current package body
767      --  are available. This form of freezing is decoupled from the usual
768      --  Freeze_xxx mechanism because it must also work in the context of
769      --  generics where normal freezing is disabled.
770
771      --  Only bodies coming from source should cause this type of freezing.
772      --  Instantiated generic bodies are excluded because their processing is
773      --  performed in a separate compilation pass which lacks enough semantic
774      --  information with respect to contract analysis. It is safe to suppress
775      --  the freezing of contracts in this case because this action already
776      --  took place at the end of the enclosing declarative part.
777
778      if Comes_From_Source (N)
779        and then not Is_Generic_Instance (Spec_Id)
780      then
781         Freeze_Previous_Contracts (N);
782      end if;
783
784      --  A package body is Ghost when the corresponding spec is Ghost. Set
785      --  the mode now to ensure that any nodes generated during analysis and
786      --  expansion are properly flagged as ignored Ghost.
787
788      Mark_And_Set_Ghost_Body (N, Spec_Id);
789
790      --  Deactivate expansion inside the body of ignored Ghost entities,
791      --  as this code will ultimately be ignored. This avoids requiring the
792      --  presence of run-time units which are not needed. Only do this for
793      --  user entities, as internally generated entities might still need
794      --  to be expanded (e.g. those generated for types).
795
796      if Present (Ignored_Ghost_Region)
797        and then Comes_From_Source (Body_Id)
798      then
799         Expander_Active := False;
800      end if;
801
802      --  If the body completes the initial declaration of a compilation unit
803      --  which is subject to pragma Elaboration_Checks, set the model of the
804      --  pragma because it applies to all parts of the unit.
805
806      Install_Elaboration_Model (Spec_Id);
807
808      Set_Is_Compilation_Unit (Body_Id, Is_Compilation_Unit (Spec_Id));
809      Style.Check_Identifier (Body_Id, Spec_Id);
810
811      if Is_Child_Unit (Spec_Id) then
812         if Nkind (Parent (N)) /= N_Compilation_Unit then
813            Error_Msg_NE
814              ("body of child unit& cannot be an inner package", N, Spec_Id);
815         end if;
816
817         Set_Is_Child_Unit (Body_Id);
818      end if;
819
820      --  Generic package case
821
822      if Ekind (Spec_Id) = E_Generic_Package then
823
824         --  Disable expansion and perform semantic analysis on copy. The
825         --  unannotated body will be used in all instantiations.
826
827         Body_Id := Defining_Entity (N);
828         Set_Ekind (Body_Id, E_Package_Body);
829         Set_Scope (Body_Id, Scope (Spec_Id));
830         Set_Is_Obsolescent (Body_Id, Is_Obsolescent (Spec_Id));
831         Set_Body_Entity (Spec_Id, Body_Id);
832         Set_Spec_Entity (Body_Id, Spec_Id);
833
834         New_N := Copy_Generic_Node (N, Empty, Instantiating => False);
835         Rewrite (N, New_N);
836
837         --  Once the contents of the generic copy and the template are
838         --  swapped, do the same for their respective aspect specifications.
839
840         Exchange_Aspects (N, New_N);
841
842         --  Collect all contract-related source pragmas found within the
843         --  template and attach them to the contract of the package body.
844         --  This contract is used in the capture of global references within
845         --  annotations.
846
847         Create_Generic_Contract (N);
848
849         --  Update Body_Id to point to the copied node for the remainder of
850         --  the processing.
851
852         Body_Id := Defining_Entity (N);
853         Start_Generic;
854      end if;
855
856      --  The Body_Id is that of the copied node in the generic case, the
857      --  current node otherwise. Note that N was rewritten above, so we must
858      --  be sure to get the latest Body_Id value.
859
860      Set_Ekind (Body_Id, E_Package_Body);
861      Set_Body_Entity (Spec_Id, Body_Id);
862      Set_Spec_Entity (Body_Id, Spec_Id);
863
864      --  Defining name for the package body is not a visible entity: Only the
865      --  defining name for the declaration is visible.
866
867      Set_Etype (Body_Id, Standard_Void_Type);
868      Set_Scope (Body_Id, Scope (Spec_Id));
869      Set_Corresponding_Spec (N, Spec_Id);
870      Set_Corresponding_Body (Pack_Decl, Body_Id);
871
872      --  The body entity is not used for semantics or code generation, but
873      --  it is attached to the entity list of the enclosing scope to simplify
874      --  the listing of back-annotations for the types it main contain.
875
876      if Scope (Spec_Id) /= Standard_Standard then
877         Append_Entity (Body_Id, Scope (Spec_Id));
878      end if;
879
880      --  Indicate that we are currently compiling the body of the package
881
882      Set_In_Package_Body (Spec_Id);
883      Set_Has_Completion (Spec_Id);
884      Last_Spec_Entity := Last_Entity (Spec_Id);
885
886      if Has_Aspects (N) then
887         Analyze_Aspect_Specifications (N, Body_Id);
888      end if;
889
890      Push_Scope (Spec_Id);
891
892      --  Set SPARK_Mode only for non-generic package
893
894      if Ekind (Spec_Id) = E_Package then
895         Set_SPARK_Pragma               (Body_Id, SPARK_Mode_Pragma);
896         Set_SPARK_Aux_Pragma           (Body_Id, SPARK_Mode_Pragma);
897         Set_SPARK_Pragma_Inherited     (Body_Id);
898         Set_SPARK_Aux_Pragma_Inherited (Body_Id);
899
900         --  A package body may be instantiated or inlined at a later pass.
901         --  Restore the state of Ignore_SPARK_Mode_Pragmas_In_Instance when
902         --  it applied to the package spec.
903
904         if Ignore_SPARK_Mode_Pragmas (Spec_Id) then
905            Ignore_SPARK_Mode_Pragmas_In_Instance := True;
906         end if;
907      end if;
908
909      Set_Categorization_From_Pragmas (N);
910
911      Install_Visible_Declarations (Spec_Id);
912      Install_Private_Declarations (Spec_Id);
913      Install_Private_With_Clauses (Spec_Id);
914      Install_Composite_Operations (Spec_Id);
915
916      Check_Anonymous_Access_Types (Spec_Id, N);
917
918      if Ekind (Spec_Id) = E_Generic_Package then
919         Set_Use (Generic_Formal_Declarations (Pack_Decl));
920      end if;
921
922      Set_Use (Visible_Declarations (Specification (Pack_Decl)));
923      Set_Use (Private_Declarations (Specification (Pack_Decl)));
924
925      --  This is a nested package, so it may be necessary to declare certain
926      --  inherited subprograms that are not yet visible because the parent
927      --  type's subprograms are now visible.
928      --  Note that for child units these operations were generated when
929      --  analyzing the package specification.
930
931      if Ekind (Scope (Spec_Id)) = E_Package
932        and then Scope (Spec_Id) /= Standard_Standard
933        and then not Is_Child_Unit (Spec_Id)
934      then
935         Declare_Inherited_Private_Subprograms (Spec_Id);
936      end if;
937
938      if Present (Declarations (N)) then
939         Analyze_Declarations (Declarations (N));
940         Inspect_Deferred_Constant_Completion (Declarations (N));
941      end if;
942
943      --  Verify that the SPARK_Mode of the body agrees with that of its spec
944
945      if Present (SPARK_Pragma (Body_Id)) then
946         if Present (SPARK_Aux_Pragma (Spec_Id)) then
947            if Get_SPARK_Mode_From_Annotation (SPARK_Aux_Pragma (Spec_Id)) =
948                 Off
949              and then
950                Get_SPARK_Mode_From_Annotation (SPARK_Pragma (Body_Id)) = On
951            then
952               Error_Msg_Sloc := Sloc (SPARK_Pragma (Body_Id));
953               Error_Msg_N ("incorrect application of SPARK_Mode#", N);
954               Error_Msg_Sloc := Sloc (SPARK_Aux_Pragma (Spec_Id));
955               Error_Msg_NE
956                 ("\value Off was set for SPARK_Mode on & #", N, Spec_Id);
957            end if;
958
959         else
960            Error_Msg_Sloc := Sloc (SPARK_Pragma (Body_Id));
961            Error_Msg_N ("incorrect application of SPARK_Mode#", N);
962            Error_Msg_Sloc := Sloc (Spec_Id);
963            Error_Msg_NE
964              ("\no value was set for SPARK_Mode on & #", N, Spec_Id);
965         end if;
966      end if;
967
968      --  Analyze_Declarations has caused freezing of all types. Now generate
969      --  bodies for RACW primitives and stream attributes, if any.
970
971      if Ekind (Spec_Id) = E_Package and then Has_RACW (Spec_Id) then
972
973         --  Attach subprogram bodies to support RACWs declared in spec
974
975         Append_RACW_Bodies (Declarations (N), Spec_Id);
976         Analyze_List (Declarations (N));
977      end if;
978
979      HSS := Handled_Statement_Sequence (N);
980
981      if Present (HSS) then
982         Process_End_Label (HSS, 't', Spec_Id);
983         Analyze (HSS);
984
985         --  Check that elaboration code in a preelaborable package body is
986         --  empty other than null statements and labels (RM 10.2.1(6)).
987
988         Validate_Null_Statement_Sequence (N);
989      end if;
990
991      Validate_Categorization_Dependency (N, Spec_Id);
992      Check_Completion (Body_Id);
993
994      --  Generate start of body reference. Note that we do this fairly late,
995      --  because the call will use In_Extended_Main_Source_Unit as a check,
996      --  and we want to make sure that Corresponding_Stub links are set
997
998      Generate_Reference (Spec_Id, Body_Id, 'b', Set_Ref => False);
999
1000      --  For a generic package, collect global references and mark them on
1001      --  the original body so that they are not resolved again at the point
1002      --  of instantiation.
1003
1004      if Ekind (Spec_Id) /= E_Package then
1005         Save_Global_References (Original_Node (N));
1006         End_Generic;
1007      end if;
1008
1009      --  The entities of the package body have so far been chained onto the
1010      --  declaration chain for the spec. That's been fine while we were in the
1011      --  body, since we wanted them to be visible, but now that we are leaving
1012      --  the package body, they are no longer visible, so we remove them from
1013      --  the entity chain of the package spec entity, and copy them to the
1014      --  entity chain of the package body entity, where they will never again
1015      --  be visible.
1016
1017      if Present (Last_Spec_Entity) then
1018         Set_First_Entity (Body_Id, Next_Entity (Last_Spec_Entity));
1019         Set_Next_Entity (Last_Spec_Entity, Empty);
1020         Set_Last_Entity (Body_Id, Last_Entity (Spec_Id));
1021         Set_Last_Entity (Spec_Id, Last_Spec_Entity);
1022
1023      else
1024         Set_First_Entity (Body_Id, First_Entity (Spec_Id));
1025         Set_Last_Entity  (Body_Id, Last_Entity  (Spec_Id));
1026         Set_First_Entity (Spec_Id, Empty);
1027         Set_Last_Entity  (Spec_Id, Empty);
1028      end if;
1029
1030      Update_Use_Clause_Chain;
1031      End_Package_Scope (Spec_Id);
1032
1033      --  All entities declared in body are not visible
1034
1035      declare
1036         E : Entity_Id;
1037
1038      begin
1039         E := First_Entity (Body_Id);
1040         while Present (E) loop
1041            Set_Is_Immediately_Visible (E, False);
1042            Set_Is_Potentially_Use_Visible (E, False);
1043            Set_Is_Hidden (E);
1044
1045            --  Child units may appear on the entity list (e.g. if they appear
1046            --  in the context of a subunit) but they are not body entities.
1047
1048            if not Is_Child_Unit (E) then
1049               Set_Is_Package_Body_Entity (E);
1050            end if;
1051
1052            Next_Entity (E);
1053         end loop;
1054      end;
1055
1056      Check_References (Body_Id);
1057
1058      --  For a generic unit, check that the formal parameters are referenced,
1059      --  and that local variables are used, as for regular packages.
1060
1061      if Ekind (Spec_Id) = E_Generic_Package then
1062         Check_References (Spec_Id);
1063      end if;
1064
1065      --  At this point all entities of the package body are externally visible
1066      --  to the linker as their Is_Public flag is set to True. This proactive
1067      --  approach is necessary because an inlined or a generic body for which
1068      --  code is generated in other units may need to see these entities. Cut
1069      --  down the number of global symbols that do not need public visibility
1070      --  as this has two beneficial effects:
1071      --    (1) It makes the compilation process more efficient.
1072      --    (2) It gives the code generator more leeway to optimize within each
1073      --        unit, especially subprograms.
1074
1075      --  This is done only for top-level library packages or child units as
1076      --  the algorithm does a top-down traversal of the package body.
1077
1078      if (Scope (Spec_Id) = Standard_Standard or else Is_Child_Unit (Spec_Id))
1079        and then not Is_Generic_Unit (Spec_Id)
1080      then
1081         Hide_Public_Entities (Declarations (N));
1082      end if;
1083
1084      --  If expander is not active, then here is where we turn off the
1085      --  In_Package_Body flag, otherwise it is turned off at the end of the
1086      --  corresponding expansion routine. If this is an instance body, we need
1087      --  to qualify names of local entities, because the body may have been
1088      --  compiled as a preliminary to another instantiation.
1089
1090      if not Expander_Active then
1091         Set_In_Package_Body (Spec_Id, False);
1092
1093         if Is_Generic_Instance (Spec_Id)
1094           and then Operating_Mode = Generate_Code
1095         then
1096            Qualify_Entity_Names (N);
1097         end if;
1098      end if;
1099
1100      if Present (Ignored_Ghost_Region) then
1101         Expander_Active := Saved_EA;
1102      end if;
1103
1104      Ignore_SPARK_Mode_Pragmas_In_Instance := Saved_ISMP;
1105      Restore_Ghost_Region (Saved_GM, Saved_IGR);
1106   end Analyze_Package_Body_Helper;
1107
1108   ---------------------------------
1109   -- Analyze_Package_Declaration --
1110   ---------------------------------
1111
1112   procedure Analyze_Package_Declaration (N : Node_Id) is
1113      Id  : constant Node_Id := Defining_Entity (N);
1114
1115      Is_Comp_Unit : constant Boolean :=
1116                       Nkind (Parent (N)) = N_Compilation_Unit;
1117
1118      Body_Required : Boolean;
1119      --  True when this package declaration requires a corresponding body
1120
1121   begin
1122      if Debug_Flag_C then
1123         Write_Str ("==> package spec ");
1124         Write_Name (Chars (Id));
1125         Write_Str (" from ");
1126         Write_Location (Sloc (N));
1127         Write_Eol;
1128         Indent;
1129      end if;
1130
1131      Generate_Definition (Id);
1132      Enter_Name (Id);
1133      Set_Ekind  (Id, E_Package);
1134      Set_Etype  (Id, Standard_Void_Type);
1135
1136      --  Set SPARK_Mode from context
1137
1138      Set_SPARK_Pragma               (Id, SPARK_Mode_Pragma);
1139      Set_SPARK_Aux_Pragma           (Id, SPARK_Mode_Pragma);
1140      Set_SPARK_Pragma_Inherited     (Id);
1141      Set_SPARK_Aux_Pragma_Inherited (Id);
1142
1143      --  Save the state of flag Ignore_SPARK_Mode_Pragmas_In_Instance in case
1144      --  the body of this package is instantiated or inlined later and out of
1145      --  context. The body uses this attribute to restore the value of the
1146      --  global flag.
1147
1148      if Ignore_SPARK_Mode_Pragmas_In_Instance then
1149         Set_Ignore_SPARK_Mode_Pragmas (Id);
1150      end if;
1151
1152      --  Analyze aspect specifications immediately, since we need to recognize
1153      --  things like Pure early enough to diagnose violations during analysis.
1154
1155      if Has_Aspects (N) then
1156         Analyze_Aspect_Specifications (N, Id);
1157      end if;
1158
1159      --  Ada 2005 (AI-217): Check if the package has been illegally named in
1160      --  a limited-with clause of its own context. In this case the error has
1161      --  been previously notified by Analyze_Context.
1162
1163      --     limited with Pkg; -- ERROR
1164      --     package Pkg is ...
1165
1166      if From_Limited_With (Id) then
1167         return;
1168      end if;
1169
1170      Push_Scope (Id);
1171
1172      Set_Is_Pure (Id, Is_Pure (Enclosing_Lib_Unit_Entity));
1173      Set_Categorization_From_Pragmas (N);
1174
1175      Analyze (Specification (N));
1176      Validate_Categorization_Dependency (N, Id);
1177
1178      --  Determine whether the package requires a body. Abstract states are
1179      --  intentionally ignored because they do require refinement which can
1180      --  only come in a body, but at the same time they do not force the need
1181      --  for a body on their own (SPARK RM 7.1.4(4) and 7.2.2(3)).
1182
1183      Body_Required := Unit_Requires_Body (Id);
1184
1185      if not Body_Required then
1186
1187         --  If the package spec does not require an explicit body, then there
1188         --  are not entities requiring completion in the language sense. Call
1189         --  Check_Completion now to ensure that nested package declarations
1190         --  that require an implicit body get one. (In the case where a body
1191         --  is required, Check_Completion is called at the end of the body's
1192         --  declarative part.)
1193
1194         Check_Completion;
1195
1196         --  If the package spec does not require an explicit body, then all
1197         --  abstract states declared in nested packages cannot possibly get
1198         --  a proper refinement (SPARK RM 7.2.2(3)). This check is performed
1199         --  only when the compilation unit is the main unit to allow for
1200         --  modular SPARK analysis where packages do not necessarily have
1201         --  bodies.
1202
1203         if Is_Comp_Unit then
1204            Check_State_Refinements
1205              (Context      => N,
1206               Is_Main_Unit => Parent (N) = Cunit (Main_Unit));
1207         end if;
1208      end if;
1209
1210      --  Set Body_Required indication on the compilation unit node
1211
1212      if Is_Comp_Unit then
1213         Set_Body_Required (Parent (N), Body_Required);
1214
1215         if Legacy_Elaboration_Checks and not Body_Required then
1216            Set_Suppress_Elaboration_Warnings (Id);
1217         end if;
1218      end if;
1219
1220      End_Package_Scope (Id);
1221
1222      --  For the declaration of a library unit that is a remote types package,
1223      --  check legality rules regarding availability of stream attributes for
1224      --  types that contain non-remote access values. This subprogram performs
1225      --  visibility tests that rely on the fact that we have exited the scope
1226      --  of Id.
1227
1228      if Is_Comp_Unit then
1229         Validate_RT_RAT_Component (N);
1230      end if;
1231
1232      if Debug_Flag_C then
1233         Outdent;
1234         Write_Str ("<== package spec ");
1235         Write_Name (Chars (Id));
1236         Write_Str (" from ");
1237         Write_Location (Sloc (N));
1238         Write_Eol;
1239      end if;
1240   end Analyze_Package_Declaration;
1241
1242   -----------------------------------
1243   -- Analyze_Package_Specification --
1244   -----------------------------------
1245
1246   --  Note that this code is shared for the analysis of generic package specs
1247   --  (see Sem_Ch12.Analyze_Generic_Package_Declaration for details).
1248
1249   procedure Analyze_Package_Specification (N : Node_Id) is
1250      Id           : constant Entity_Id  := Defining_Entity (N);
1251      Orig_Decl    : constant Node_Id    := Original_Node (Parent (N));
1252      Vis_Decls    : constant List_Id    := Visible_Declarations (N);
1253      Priv_Decls   : constant List_Id    := Private_Declarations (N);
1254      E            : Entity_Id;
1255      L            : Entity_Id;
1256      Public_Child : Boolean;
1257
1258      Private_With_Clauses_Installed : Boolean := False;
1259      --  In Ada 2005, private with_clauses are visible in the private part
1260      --  of a nested package, even if it appears in the public part of the
1261      --  enclosing package. This requires a separate step to install these
1262      --  private_with_clauses, and remove them at the end of the nested
1263      --  package.
1264
1265      procedure Check_One_Tagged_Type_Or_Extension_At_Most;
1266      --  Issue an error in SPARK mode if a package specification contains
1267      --  more than one tagged type or type extension.
1268
1269      procedure Clear_Constants (Id : Entity_Id; FE : Entity_Id);
1270      --  Clears constant indications (Never_Set_In_Source, Constant_Value, and
1271      --  Is_True_Constant) on all variables that are entities of Id, and on
1272      --  the chain whose first element is FE. A recursive call is made for all
1273      --  packages and generic packages.
1274
1275      procedure Generate_Parent_References;
1276      --  For a child unit, generate references to parent units, for
1277      --  GNAT Studio navigation purposes.
1278
1279      function Is_Public_Child (Child, Unit : Entity_Id) return Boolean;
1280      --  Child and Unit are entities of compilation units. True if Child
1281      --  is a public child of Parent as defined in 10.1.1
1282
1283      procedure Inspect_Unchecked_Union_Completion (Decls : List_Id);
1284      --  Reject completion of an incomplete or private type declarations
1285      --  having a known discriminant part by an unchecked union.
1286
1287      procedure Install_Parent_Private_Declarations (Inst_Id : Entity_Id);
1288      --  Given the package entity of a generic package instantiation or
1289      --  formal package whose corresponding generic is a child unit, installs
1290      --  the private declarations of each of the child unit's parents.
1291      --  This has to be done at the point of entering the instance package's
1292      --  private part rather than being done in Sem_Ch12.Install_Parent
1293      --  (which is where the parents' visible declarations are installed).
1294
1295      ------------------------------------------------
1296      -- Check_One_Tagged_Type_Or_Extension_At_Most --
1297      ------------------------------------------------
1298
1299      procedure Check_One_Tagged_Type_Or_Extension_At_Most is
1300         Previous : Node_Id;
1301
1302         procedure Check_Decls (Decls : List_Id);
1303         --  Check that either Previous is Empty and Decls does not contain
1304         --  more than one tagged type or type extension, or Previous is
1305         --  already set and Decls contains no tagged type or type extension.
1306
1307         -----------------
1308         -- Check_Decls --
1309         -----------------
1310
1311         procedure Check_Decls (Decls : List_Id) is
1312            Decl : Node_Id;
1313
1314         begin
1315            Decl := First (Decls);
1316            while Present (Decl) loop
1317               if Nkind (Decl) = N_Full_Type_Declaration
1318                 and then Is_Tagged_Type (Defining_Identifier (Decl))
1319               then
1320                  if No (Previous) then
1321                     Previous := Decl;
1322
1323                  else
1324                     Error_Msg_Sloc := Sloc (Previous);
1325                     Check_SPARK_05_Restriction
1326                       ("at most one tagged type or type extension allowed",
1327                        "\\ previous declaration#",
1328                        Decl);
1329                  end if;
1330               end if;
1331
1332               Next (Decl);
1333            end loop;
1334         end Check_Decls;
1335
1336      --  Start of processing for Check_One_Tagged_Type_Or_Extension_At_Most
1337
1338      begin
1339         Previous := Empty;
1340         Check_Decls (Vis_Decls);
1341
1342         if Present (Priv_Decls) then
1343            Check_Decls (Priv_Decls);
1344         end if;
1345      end Check_One_Tagged_Type_Or_Extension_At_Most;
1346
1347      ---------------------
1348      -- Clear_Constants --
1349      ---------------------
1350
1351      procedure Clear_Constants (Id : Entity_Id; FE : Entity_Id) is
1352         E : Entity_Id;
1353
1354      begin
1355         --  Ignore package renamings, not interesting and they can cause self
1356         --  referential loops in the code below.
1357
1358         if Nkind (Parent (Id)) = N_Package_Renaming_Declaration then
1359            return;
1360         end if;
1361
1362         --  Note: in the loop below, the check for Next_Entity pointing back
1363         --  to the package entity may seem odd, but it is needed, because a
1364         --  package can contain a renaming declaration to itself, and such
1365         --  renamings are generated automatically within package instances.
1366
1367         E := FE;
1368         while Present (E) and then E /= Id loop
1369            if Is_Assignable (E) then
1370               Set_Never_Set_In_Source (E, False);
1371               Set_Is_True_Constant    (E, False);
1372               Set_Current_Value       (E, Empty);
1373               Set_Is_Known_Null       (E, False);
1374               Set_Last_Assignment     (E, Empty);
1375
1376               if not Can_Never_Be_Null (E) then
1377                  Set_Is_Known_Non_Null (E, False);
1378               end if;
1379
1380            elsif Is_Package_Or_Generic_Package (E) then
1381               Clear_Constants (E, First_Entity (E));
1382               Clear_Constants (E, First_Private_Entity (E));
1383            end if;
1384
1385            Next_Entity (E);
1386         end loop;
1387      end Clear_Constants;
1388
1389      --------------------------------
1390      -- Generate_Parent_References --
1391      --------------------------------
1392
1393      procedure Generate_Parent_References is
1394         Decl : constant Node_Id := Parent (N);
1395
1396      begin
1397         if Id = Cunit_Entity (Main_Unit)
1398           or else Parent (Decl) = Library_Unit (Cunit (Main_Unit))
1399         then
1400            Generate_Reference (Id, Scope (Id), 'k', False);
1401
1402         elsif not Nkind_In (Unit (Cunit (Main_Unit)), N_Subprogram_Body,
1403                                                       N_Subunit)
1404         then
1405            --  If current unit is an ancestor of main unit, generate a
1406            --  reference to its own parent.
1407
1408            declare
1409               U         : Node_Id;
1410               Main_Spec : Node_Id := Unit (Cunit (Main_Unit));
1411
1412            begin
1413               if Nkind (Main_Spec) = N_Package_Body then
1414                  Main_Spec := Unit (Library_Unit (Cunit (Main_Unit)));
1415               end if;
1416
1417               U := Parent_Spec (Main_Spec);
1418               while Present (U) loop
1419                  if U = Parent (Decl) then
1420                     Generate_Reference (Id, Scope (Id), 'k',  False);
1421                     exit;
1422
1423                  elsif Nkind (Unit (U)) = N_Package_Body then
1424                     exit;
1425
1426                  else
1427                     U := Parent_Spec (Unit (U));
1428                  end if;
1429               end loop;
1430            end;
1431         end if;
1432      end Generate_Parent_References;
1433
1434      ---------------------
1435      -- Is_Public_Child --
1436      ---------------------
1437
1438      function Is_Public_Child (Child, Unit : Entity_Id) return Boolean is
1439      begin
1440         if not Is_Private_Descendant (Child) then
1441            return True;
1442         else
1443            if Child = Unit then
1444               return not Private_Present (
1445                 Parent (Unit_Declaration_Node (Child)));
1446            else
1447               return Is_Public_Child (Scope (Child), Unit);
1448            end if;
1449         end if;
1450      end Is_Public_Child;
1451
1452      ----------------------------------------
1453      -- Inspect_Unchecked_Union_Completion --
1454      ----------------------------------------
1455
1456      procedure Inspect_Unchecked_Union_Completion (Decls : List_Id) is
1457         Decl : Node_Id;
1458
1459      begin
1460         Decl := First (Decls);
1461         while Present (Decl) loop
1462
1463            --  We are looking at an incomplete or private type declaration
1464            --  with a known_discriminant_part whose full view is an
1465            --  Unchecked_Union. The seemingly useless check with Is_Type
1466            --  prevents cascaded errors when routines defined only for type
1467            --  entities are called with non-type entities.
1468
1469            if Nkind_In (Decl, N_Incomplete_Type_Declaration,
1470                               N_Private_Type_Declaration)
1471              and then Is_Type (Defining_Identifier (Decl))
1472              and then Has_Discriminants (Defining_Identifier (Decl))
1473              and then Present (Full_View (Defining_Identifier (Decl)))
1474              and then
1475                Is_Unchecked_Union (Full_View (Defining_Identifier (Decl)))
1476            then
1477               Error_Msg_N
1478                 ("completion of discriminated partial view "
1479                  & "cannot be an unchecked union",
1480                 Full_View (Defining_Identifier (Decl)));
1481            end if;
1482
1483            Next (Decl);
1484         end loop;
1485      end Inspect_Unchecked_Union_Completion;
1486
1487      -----------------------------------------
1488      -- Install_Parent_Private_Declarations --
1489      -----------------------------------------
1490
1491      procedure Install_Parent_Private_Declarations (Inst_Id : Entity_Id) is
1492         Inst_Par  : Entity_Id;
1493         Gen_Par   : Entity_Id;
1494         Inst_Node : Node_Id;
1495
1496      begin
1497         Inst_Par := Inst_Id;
1498
1499         Gen_Par :=
1500           Generic_Parent (Specification (Unit_Declaration_Node (Inst_Par)));
1501         while Present (Gen_Par) and then Is_Child_Unit (Gen_Par) loop
1502            Inst_Node := Get_Unit_Instantiation_Node (Inst_Par);
1503
1504            if Nkind_In (Inst_Node, N_Package_Instantiation,
1505                                    N_Formal_Package_Declaration)
1506              and then Nkind (Name (Inst_Node)) = N_Expanded_Name
1507            then
1508               Inst_Par := Entity (Prefix (Name (Inst_Node)));
1509
1510               if Present (Renamed_Entity (Inst_Par)) then
1511                  Inst_Par := Renamed_Entity (Inst_Par);
1512               end if;
1513
1514               --  The instance may appear in a sibling generic unit, in
1515               --  which case the prefix must include the common (generic)
1516               --  ancestor, which is treated as a current instance.
1517
1518               if Inside_A_Generic
1519                 and then Ekind (Inst_Par) = E_Generic_Package
1520               then
1521                  Gen_Par := Inst_Par;
1522                  pragma Assert (In_Open_Scopes (Gen_Par));
1523
1524               else
1525                  Gen_Par :=
1526                    Generic_Parent
1527                      (Specification (Unit_Declaration_Node (Inst_Par)));
1528               end if;
1529
1530               --  Install the private declarations and private use clauses
1531               --  of a parent instance of the child instance, unless the
1532               --  parent instance private declarations have already been
1533               --  installed earlier in Analyze_Package_Specification, which
1534               --  happens when a generic child is instantiated, and the
1535               --  instance is a child of the parent instance.
1536
1537               --  Installing the use clauses of the parent instance twice
1538               --  is both unnecessary and wrong, because it would cause the
1539               --  clauses to be chained to themselves in the use clauses
1540               --  list of the scope stack entry. That in turn would cause
1541               --  an endless loop from End_Use_Clauses upon scope exit.
1542
1543               --  The parent is now fully visible. It may be a hidden open
1544               --  scope if we are currently compiling some child instance
1545               --  declared within it, but while the current instance is being
1546               --  compiled the parent is immediately visible. In particular
1547               --  its entities must remain visible if a stack save/restore
1548               --  takes place through a call to Rtsfind.
1549
1550               if Present (Gen_Par) then
1551                  if not In_Private_Part (Inst_Par) then
1552                     Install_Private_Declarations (Inst_Par);
1553                     Set_Use (Private_Declarations
1554                                (Specification
1555                                   (Unit_Declaration_Node (Inst_Par))));
1556                     Set_Is_Hidden_Open_Scope (Inst_Par, False);
1557                  end if;
1558
1559               --  If we've reached the end of the generic instance parents,
1560               --  then finish off by looping through the nongeneric parents
1561               --  and installing their private declarations.
1562
1563               --  If one of the non-generic parents is itself on the scope
1564               --  stack, do not install its private declarations: they are
1565               --  installed in due time when the private part of that parent
1566               --  is analyzed.
1567
1568               else
1569                  while Present (Inst_Par)
1570                    and then Inst_Par /= Standard_Standard
1571                    and then (not In_Open_Scopes (Inst_Par)
1572                               or else not In_Private_Part (Inst_Par))
1573                  loop
1574                     if Nkind (Inst_Node) = N_Formal_Package_Declaration
1575                       or else
1576                         not Is_Ancestor_Package
1577                               (Inst_Par, Cunit_Entity (Current_Sem_Unit))
1578                     then
1579                        Install_Private_Declarations (Inst_Par);
1580                        Set_Use
1581                          (Private_Declarations
1582                            (Specification
1583                              (Unit_Declaration_Node (Inst_Par))));
1584                        Inst_Par := Scope (Inst_Par);
1585                     else
1586                        exit;
1587                     end if;
1588                  end loop;
1589
1590                  exit;
1591               end if;
1592
1593            else
1594               exit;
1595            end if;
1596         end loop;
1597      end Install_Parent_Private_Declarations;
1598
1599   --  Start of processing for Analyze_Package_Specification
1600
1601   begin
1602      if Present (Vis_Decls) then
1603         Analyze_Declarations (Vis_Decls);
1604      end if;
1605
1606      --  Inspect the entities defined in the package and ensure that all
1607      --  incomplete types have received full declarations. Build default
1608      --  initial condition and invariant procedures for all qualifying types.
1609
1610      E := First_Entity (Id);
1611      while Present (E) loop
1612
1613         --  Check on incomplete types
1614
1615         --  AI05-0213: A formal incomplete type has no completion, and neither
1616         --  does the corresponding subtype in an instance.
1617
1618         if Is_Incomplete_Type (E)
1619           and then No (Full_View (E))
1620           and then not Is_Generic_Type (E)
1621           and then not From_Limited_With (E)
1622           and then not Is_Generic_Actual_Type (E)
1623         then
1624            Error_Msg_N ("no declaration in visible part for incomplete}", E);
1625         end if;
1626
1627         Next_Entity (E);
1628      end loop;
1629
1630      if Is_Remote_Call_Interface (Id)
1631        and then Nkind (Parent (Parent (N))) = N_Compilation_Unit
1632      then
1633         Validate_RCI_Declarations (Id);
1634      end if;
1635
1636      --  Save global references in the visible declarations, before installing
1637      --  private declarations of parent unit if there is one, because the
1638      --  privacy status of types defined in the parent will change. This is
1639      --  only relevant for generic child units, but is done in all cases for
1640      --  uniformity.
1641
1642      if Ekind (Id) = E_Generic_Package
1643        and then Nkind (Orig_Decl) = N_Generic_Package_Declaration
1644      then
1645         declare
1646            Orig_Spec : constant Node_Id := Specification (Orig_Decl);
1647            Save_Priv : constant List_Id := Private_Declarations (Orig_Spec);
1648
1649         begin
1650            --  Insert the freezing nodes after the visible declarations to
1651            --  ensure that we analyze its aspects; needed to ensure that
1652            --  global entities referenced in the aspects are properly handled.
1653
1654            if Ada_Version >= Ada_2012
1655              and then Is_Non_Empty_List (Vis_Decls)
1656              and then Is_Empty_List (Priv_Decls)
1657            then
1658               Insert_List_After_And_Analyze
1659                 (Last (Vis_Decls), Freeze_Entity (Id, Last (Vis_Decls)));
1660            end if;
1661
1662            Set_Private_Declarations (Orig_Spec, Empty_List);
1663            Save_Global_References   (Orig_Decl);
1664            Set_Private_Declarations (Orig_Spec, Save_Priv);
1665         end;
1666      end if;
1667
1668      --  If package is a public child unit, then make the private declarations
1669      --  of the parent visible.
1670
1671      Public_Child := False;
1672
1673      declare
1674         Par       : Entity_Id;
1675         Pack_Decl : Node_Id;
1676         Par_Spec  : Node_Id;
1677
1678      begin
1679         Par := Id;
1680         Par_Spec := Parent_Spec (Parent (N));
1681
1682         --  If the package is formal package of an enclosing generic, it is
1683         --  transformed into a local generic declaration, and compiled to make
1684         --  its spec available. We need to retrieve the original generic to
1685         --  determine whether it is a child unit, and install its parents.
1686
1687         if No (Par_Spec)
1688           and then
1689             Nkind (Original_Node (Parent (N))) = N_Formal_Package_Declaration
1690         then
1691            Par := Entity (Name (Original_Node (Parent (N))));
1692            Par_Spec := Parent_Spec (Unit_Declaration_Node (Par));
1693         end if;
1694
1695         if Present (Par_Spec) then
1696            Generate_Parent_References;
1697
1698            while Scope (Par) /= Standard_Standard
1699              and then Is_Public_Child (Id, Par)
1700              and then In_Open_Scopes (Par)
1701            loop
1702               Public_Child := True;
1703               Par := Scope (Par);
1704               Install_Private_Declarations (Par);
1705               Install_Private_With_Clauses (Par);
1706               Pack_Decl := Unit_Declaration_Node (Par);
1707               Set_Use (Private_Declarations (Specification (Pack_Decl)));
1708            end loop;
1709         end if;
1710      end;
1711
1712      if Is_Compilation_Unit (Id) then
1713         Install_Private_With_Clauses (Id);
1714      else
1715         --  The current compilation unit may include private with_clauses,
1716         --  which are visible in the private part of the current nested
1717         --  package, and have to be installed now. This is not done for
1718         --  nested instantiations, where the private with_clauses of the
1719         --  enclosing unit have no effect once the instantiation info is
1720         --  established and we start analyzing the package declaration.
1721
1722         declare
1723            Comp_Unit : constant Entity_Id := Cunit_Entity (Current_Sem_Unit);
1724         begin
1725            if Is_Package_Or_Generic_Package (Comp_Unit)
1726              and then not In_Private_Part (Comp_Unit)
1727              and then not In_Instance
1728            then
1729               Install_Private_With_Clauses (Comp_Unit);
1730               Private_With_Clauses_Installed := True;
1731            end if;
1732         end;
1733      end if;
1734
1735      --  If this is a package associated with a generic instance or formal
1736      --  package, then the private declarations of each of the generic's
1737      --  parents must be installed at this point.
1738
1739      if Is_Generic_Instance (Id) then
1740         Install_Parent_Private_Declarations (Id);
1741      end if;
1742
1743      --  Analyze private part if present. The flag In_Private_Part is reset
1744      --  in End_Package_Scope.
1745
1746      L := Last_Entity (Id);
1747
1748      if Present (Priv_Decls) then
1749         Set_In_Private_Part (Id);
1750
1751         --  Upon entering a public child's private part, it may be necessary
1752         --  to declare subprograms that were derived in the package's visible
1753         --  part but not yet made visible.
1754
1755         if Public_Child then
1756            Declare_Inherited_Private_Subprograms (Id);
1757         end if;
1758
1759         Analyze_Declarations (Priv_Decls);
1760
1761         --  Check the private declarations for incomplete deferred constants
1762
1763         Inspect_Deferred_Constant_Completion (Priv_Decls);
1764
1765         --  The first private entity is the immediate follower of the last
1766         --  visible entity, if there was one.
1767
1768         if Present (L) then
1769            Set_First_Private_Entity (Id, Next_Entity (L));
1770         else
1771            Set_First_Private_Entity (Id, First_Entity (Id));
1772         end if;
1773
1774      --  There may be inherited private subprograms that need to be declared,
1775      --  even in the absence of an explicit private part. If there are any
1776      --  public declarations in the package and the package is a public child
1777      --  unit, then an implicit private part is assumed.
1778
1779      elsif Present (L) and then Public_Child then
1780         Set_In_Private_Part (Id);
1781         Declare_Inherited_Private_Subprograms (Id);
1782         Set_First_Private_Entity (Id, Next_Entity (L));
1783      end if;
1784
1785      E := First_Entity (Id);
1786      while Present (E) loop
1787
1788         --  Check rule of 3.6(11), which in general requires waiting till all
1789         --  full types have been seen.
1790
1791         if Ekind (E) = E_Record_Type or else Ekind (E) = E_Array_Type then
1792            Check_Aliased_Component_Types (E);
1793         end if;
1794
1795         --  Check preelaborable initialization for full type completing a
1796         --  private type for which pragma Preelaborable_Initialization given.
1797
1798         if Is_Type (E)
1799           and then Must_Have_Preelab_Init (E)
1800           and then not Has_Preelaborable_Initialization (E)
1801         then
1802            Error_Msg_N
1803              ("full view of & does not have preelaborable initialization", E);
1804         end if;
1805
1806         Next_Entity (E);
1807      end loop;
1808
1809      --  Ada 2005 (AI-216): The completion of an incomplete or private type
1810      --  declaration having a known_discriminant_part shall not be an
1811      --  unchecked union type.
1812
1813      if Present (Vis_Decls) then
1814         Inspect_Unchecked_Union_Completion (Vis_Decls);
1815      end if;
1816
1817      if Present (Priv_Decls) then
1818         Inspect_Unchecked_Union_Completion (Priv_Decls);
1819      end if;
1820
1821      if Ekind (Id) = E_Generic_Package
1822        and then Nkind (Orig_Decl) = N_Generic_Package_Declaration
1823        and then Present (Priv_Decls)
1824      then
1825         --  Save global references in private declarations, ignoring the
1826         --  visible declarations that were processed earlier.
1827
1828         declare
1829            Orig_Spec : constant Node_Id := Specification (Orig_Decl);
1830            Save_Vis  : constant List_Id := Visible_Declarations (Orig_Spec);
1831            Save_Form : constant List_Id :=
1832                          Generic_Formal_Declarations (Orig_Decl);
1833
1834         begin
1835            --  Insert the freezing nodes after the private declarations to
1836            --  ensure that we analyze its aspects; needed to ensure that
1837            --  global entities referenced in the aspects are properly handled.
1838
1839            if Ada_Version >= Ada_2012
1840              and then Is_Non_Empty_List (Priv_Decls)
1841            then
1842               Insert_List_After_And_Analyze
1843                 (Last (Priv_Decls), Freeze_Entity (Id, Last (Priv_Decls)));
1844            end if;
1845
1846            Set_Visible_Declarations        (Orig_Spec, Empty_List);
1847            Set_Generic_Formal_Declarations (Orig_Decl, Empty_List);
1848            Save_Global_References          (Orig_Decl);
1849            Set_Generic_Formal_Declarations (Orig_Decl, Save_Form);
1850            Set_Visible_Declarations        (Orig_Spec, Save_Vis);
1851         end;
1852      end if;
1853
1854      Process_End_Label (N, 'e', Id);
1855
1856      --  Remove private_with_clauses of enclosing compilation unit, if they
1857      --  were installed.
1858
1859      if Private_With_Clauses_Installed then
1860         Remove_Private_With_Clauses (Cunit (Current_Sem_Unit));
1861      end if;
1862
1863      --  For the case of a library level package, we must go through all the
1864      --  entities clearing the indications that the value may be constant and
1865      --  not modified. Why? Because any client of this package may modify
1866      --  these values freely from anywhere. This also applies to any nested
1867      --  packages or generic packages.
1868
1869      --  For now we unconditionally clear constants for packages that are
1870      --  instances of generic packages. The reason is that we do not have the
1871      --  body yet, and we otherwise think things are unreferenced when they
1872      --  are not. This should be fixed sometime (the effect is not terrible,
1873      --  we just lose some warnings, and also some cases of value propagation)
1874      --  ???
1875
1876      if Is_Library_Level_Entity (Id)
1877        or else Is_Generic_Instance (Id)
1878      then
1879         Clear_Constants (Id, First_Entity (Id));
1880         Clear_Constants (Id, First_Private_Entity (Id));
1881      end if;
1882
1883      --  Issue an error in SPARK mode if a package specification contains
1884      --  more than one tagged type or type extension.
1885
1886      Check_One_Tagged_Type_Or_Extension_At_Most;
1887
1888      --  Output relevant information as to why the package requires a body.
1889      --  Do not consider generated packages as this exposes internal symbols
1890      --  and leads to confusing messages.
1891
1892      if List_Body_Required_Info
1893        and then In_Extended_Main_Source_Unit (Id)
1894        and then Unit_Requires_Body (Id)
1895        and then Comes_From_Source (Id)
1896      then
1897         Unit_Requires_Body_Info (Id);
1898      end if;
1899
1900      --  Nested package specs that do not require bodies are not checked for
1901      --  ineffective use clauses due to the possibility of subunits. This is
1902      --  because at this stage it is impossible to tell whether there will be
1903      --  a separate body.
1904
1905      if not Unit_Requires_Body (Id)
1906        and then Is_Compilation_Unit (Id)
1907        and then not Is_Private_Descendant (Id)
1908      then
1909         Update_Use_Clause_Chain;
1910      end if;
1911   end Analyze_Package_Specification;
1912
1913   --------------------------------------
1914   -- Analyze_Private_Type_Declaration --
1915   --------------------------------------
1916
1917   procedure Analyze_Private_Type_Declaration (N : Node_Id) is
1918      Id : constant Entity_Id := Defining_Identifier (N);
1919      PF : constant Boolean   := Is_Pure (Enclosing_Lib_Unit_Entity);
1920
1921   begin
1922      Generate_Definition (Id);
1923      Set_Is_Pure         (Id, PF);
1924      Init_Size_Align     (Id);
1925
1926      if not Is_Package_Or_Generic_Package (Current_Scope)
1927        or else In_Private_Part (Current_Scope)
1928      then
1929         Error_Msg_N ("invalid context for private declaration", N);
1930      end if;
1931
1932      New_Private_Type (N, Id, N);
1933      Set_Depends_On_Private (Id);
1934
1935      --  Set the SPARK mode from the current context
1936
1937      Set_SPARK_Pragma           (Id, SPARK_Mode_Pragma);
1938      Set_SPARK_Pragma_Inherited (Id);
1939
1940      if Has_Aspects (N) then
1941         Analyze_Aspect_Specifications (N, Id);
1942      end if;
1943   end Analyze_Private_Type_Declaration;
1944
1945   ----------------------------------
1946   -- Check_Anonymous_Access_Types --
1947   ----------------------------------
1948
1949   procedure Check_Anonymous_Access_Types
1950     (Spec_Id : Entity_Id;
1951      P_Body  : Node_Id)
1952   is
1953      E  : Entity_Id;
1954      IR : Node_Id;
1955
1956   begin
1957      --  Itype references are only needed by gigi, to force elaboration of
1958      --  itypes. In the absence of code generation, they are not needed.
1959
1960      if not Expander_Active then
1961         return;
1962      end if;
1963
1964      E := First_Entity (Spec_Id);
1965      while Present (E) loop
1966         if Ekind (E) = E_Anonymous_Access_Type
1967           and then From_Limited_With (E)
1968         then
1969            IR := Make_Itype_Reference (Sloc (P_Body));
1970            Set_Itype (IR, E);
1971
1972            if No (Declarations (P_Body)) then
1973               Set_Declarations (P_Body, New_List (IR));
1974            else
1975               Prepend (IR, Declarations (P_Body));
1976            end if;
1977         end if;
1978
1979         Next_Entity (E);
1980      end loop;
1981   end Check_Anonymous_Access_Types;
1982
1983   -------------------------------------------
1984   -- Declare_Inherited_Private_Subprograms --
1985   -------------------------------------------
1986
1987   procedure Declare_Inherited_Private_Subprograms (Id : Entity_Id) is
1988
1989      function Is_Primitive_Of (T : Entity_Id; S : Entity_Id) return Boolean;
1990      --  Check whether an inherited subprogram S is an operation of an
1991      --  untagged derived type T.
1992
1993      ---------------------
1994      -- Is_Primitive_Of --
1995      ---------------------
1996
1997      function Is_Primitive_Of (T : Entity_Id; S : Entity_Id) return Boolean is
1998         Formal : Entity_Id;
1999
2000      begin
2001         --  If the full view is a scalar type, the type is the anonymous base
2002         --  type, but the operation mentions the first subtype, so check the
2003         --  signature against the base type.
2004
2005         if Base_Type (Etype (S)) = Base_Type (T) then
2006            return True;
2007
2008         else
2009            Formal := First_Formal (S);
2010            while Present (Formal) loop
2011               if Base_Type (Etype (Formal)) = Base_Type (T) then
2012                  return True;
2013               end if;
2014
2015               Next_Formal (Formal);
2016            end loop;
2017
2018            return False;
2019         end if;
2020      end Is_Primitive_Of;
2021
2022      --  Local variables
2023
2024      E           : Entity_Id;
2025      Op_List     : Elist_Id;
2026      Op_Elmt     : Elmt_Id;
2027      Op_Elmt_2   : Elmt_Id;
2028      Prim_Op     : Entity_Id;
2029      New_Op      : Entity_Id := Empty;
2030      Parent_Subp : Entity_Id;
2031      Tag         : Entity_Id;
2032
2033   --  Start of processing for Declare_Inherited_Private_Subprograms
2034
2035   begin
2036      E := First_Entity (Id);
2037      while Present (E) loop
2038
2039         --  If the entity is a nonprivate type extension whose parent type
2040         --  is declared in an open scope, then the type may have inherited
2041         --  operations that now need to be made visible. Ditto if the entity
2042         --  is a formal derived type in a child unit.
2043
2044         if ((Is_Derived_Type (E) and then not Is_Private_Type (E))
2045               or else
2046                 (Nkind (Parent (E)) = N_Private_Extension_Declaration
2047                   and then Is_Generic_Type (E)))
2048           and then In_Open_Scopes (Scope (Etype (E)))
2049           and then Is_Base_Type (E)
2050         then
2051            if Is_Tagged_Type (E) then
2052               Op_List := Primitive_Operations (E);
2053               New_Op  := Empty;
2054               Tag     := First_Tag_Component (E);
2055
2056               Op_Elmt := First_Elmt (Op_List);
2057               while Present (Op_Elmt) loop
2058                  Prim_Op := Node (Op_Elmt);
2059
2060                  --  Search primitives that are implicit operations with an
2061                  --  internal name whose parent operation has a normal name.
2062
2063                  if Present (Alias (Prim_Op))
2064                    and then Find_Dispatching_Type (Alias (Prim_Op)) /= E
2065                    and then not Comes_From_Source (Prim_Op)
2066                    and then Is_Internal_Name (Chars (Prim_Op))
2067                    and then not Is_Internal_Name (Chars (Alias (Prim_Op)))
2068                  then
2069                     Parent_Subp := Alias (Prim_Op);
2070
2071                     --  Case 1: Check if the type has also an explicit
2072                     --  overriding for this primitive.
2073
2074                     Op_Elmt_2 := Next_Elmt (Op_Elmt);
2075                     while Present (Op_Elmt_2) loop
2076
2077                        --  Skip entities with attribute Interface_Alias since
2078                        --  they are not overriding primitives (these entities
2079                        --  link an interface primitive with their covering
2080                        --  primitive)
2081
2082                        if Chars (Node (Op_Elmt_2)) = Chars (Parent_Subp)
2083                          and then Type_Conformant (Prim_Op, Node (Op_Elmt_2))
2084                          and then No (Interface_Alias (Node (Op_Elmt_2)))
2085                        then
2086                           --  The private inherited operation has been
2087                           --  overridden by an explicit subprogram:
2088                           --  replace the former by the latter.
2089
2090                           New_Op := Node (Op_Elmt_2);
2091                           Replace_Elmt (Op_Elmt, New_Op);
2092                           Remove_Elmt  (Op_List, Op_Elmt_2);
2093                           Set_Overridden_Operation (New_Op, Parent_Subp);
2094
2095                           --  We don't need to inherit its dispatching slot.
2096                           --  Set_All_DT_Position has previously ensured that
2097                           --  the same slot was assigned to the two primitives
2098
2099                           if Present (Tag)
2100                             and then Present (DTC_Entity (New_Op))
2101                             and then Present (DTC_Entity (Prim_Op))
2102                           then
2103                              pragma Assert
2104                                (DT_Position (New_Op) = DT_Position (Prim_Op));
2105                              null;
2106                           end if;
2107
2108                           goto Next_Primitive;
2109                        end if;
2110
2111                        Next_Elmt (Op_Elmt_2);
2112                     end loop;
2113
2114                     --  Case 2: We have not found any explicit overriding and
2115                     --  hence we need to declare the operation (i.e., make it
2116                     --  visible).
2117
2118                     Derive_Subprogram (New_Op, Alias (Prim_Op), E, Etype (E));
2119
2120                     --  Inherit the dispatching slot if E is already frozen
2121
2122                     if Is_Frozen (E)
2123                       and then Present (DTC_Entity (Alias (Prim_Op)))
2124                     then
2125                        Set_DTC_Entity_Value (E, New_Op);
2126                        Set_DT_Position_Value (New_Op,
2127                          DT_Position (Alias (Prim_Op)));
2128                     end if;
2129
2130                     pragma Assert
2131                       (Is_Dispatching_Operation (New_Op)
2132                         and then Node (Last_Elmt (Op_List)) = New_Op);
2133
2134                     --  Substitute the new operation for the old one in the
2135                     --  type's primitive operations list. Since the new
2136                     --  operation was also just added to the end of list,
2137                     --  the last element must be removed.
2138
2139                     --  (Question: is there a simpler way of declaring the
2140                     --  operation, say by just replacing the name of the
2141                     --  earlier operation, reentering it in the in the symbol
2142                     --  table (how?), and marking it as private???)
2143
2144                     Replace_Elmt (Op_Elmt, New_Op);
2145                     Remove_Last_Elmt (Op_List);
2146                  end if;
2147
2148                  <<Next_Primitive>>
2149                  Next_Elmt (Op_Elmt);
2150               end loop;
2151
2152               --  Generate listing showing the contents of the dispatch table
2153
2154               if Debug_Flag_ZZ then
2155                  Write_DT (E);
2156               end if;
2157
2158            else
2159               --  For untagged type, scan forward to locate inherited hidden
2160               --  operations.
2161
2162               Prim_Op := Next_Entity (E);
2163               while Present (Prim_Op) loop
2164                  if Is_Subprogram (Prim_Op)
2165                    and then Present (Alias (Prim_Op))
2166                    and then not Comes_From_Source (Prim_Op)
2167                    and then Is_Internal_Name (Chars (Prim_Op))
2168                    and then not Is_Internal_Name (Chars (Alias (Prim_Op)))
2169                    and then Is_Primitive_Of (E, Prim_Op)
2170                  then
2171                     Derive_Subprogram (New_Op, Alias (Prim_Op), E, Etype (E));
2172                  end if;
2173
2174                  Next_Entity (Prim_Op);
2175
2176                  --  Derived operations appear immediately after the type
2177                  --  declaration (or the following subtype indication for
2178                  --  a derived scalar type). Further declarations cannot
2179                  --  include inherited operations of the type.
2180
2181                  if Present (Prim_Op) then
2182                     exit when Ekind (Prim_Op) not in Overloadable_Kind;
2183                  end if;
2184               end loop;
2185            end if;
2186         end if;
2187
2188         Next_Entity (E);
2189      end loop;
2190   end Declare_Inherited_Private_Subprograms;
2191
2192   -----------------------
2193   -- End_Package_Scope --
2194   -----------------------
2195
2196   procedure End_Package_Scope (P : Entity_Id) is
2197   begin
2198      Uninstall_Declarations (P);
2199      Pop_Scope;
2200   end End_Package_Scope;
2201
2202   ---------------------------
2203   -- Exchange_Declarations --
2204   ---------------------------
2205
2206   procedure Exchange_Declarations (Id : Entity_Id) is
2207      Full_Id : constant Entity_Id := Full_View (Id);
2208      H1      : constant Entity_Id := Homonym (Id);
2209      Next1   : constant Entity_Id := Next_Entity (Id);
2210      H2      : Entity_Id;
2211      Next2   : Entity_Id;
2212
2213   begin
2214      --  If missing full declaration for type, nothing to exchange
2215
2216      if No (Full_Id) then
2217         return;
2218      end if;
2219
2220      --  Otherwise complete the exchange, and preserve semantic links
2221
2222      Next2 := Next_Entity (Full_Id);
2223      H2    := Homonym (Full_Id);
2224
2225      --  Reset full declaration pointer to reflect the switched entities and
2226      --  readjust the next entity chains.
2227
2228      Exchange_Entities (Id, Full_Id);
2229
2230      Link_Entities (Id, Next1);
2231      Set_Homonym   (Id, H1);
2232
2233      Set_Full_View (Full_Id, Id);
2234      Link_Entities (Full_Id, Next2);
2235      Set_Homonym   (Full_Id, H2);
2236   end Exchange_Declarations;
2237
2238   ----------------------------
2239   -- Install_Package_Entity --
2240   ----------------------------
2241
2242   procedure Install_Package_Entity (Id : Entity_Id) is
2243   begin
2244      if not Is_Internal (Id) then
2245         if Debug_Flag_E then
2246            Write_Str ("Install: ");
2247            Write_Name (Chars (Id));
2248            Write_Eol;
2249         end if;
2250
2251         if Is_Child_Unit (Id) then
2252            null;
2253
2254         --  Do not enter implicitly inherited non-overridden subprograms of
2255         --  a tagged type back into visibility if they have non-conformant
2256         --  homographs (Ada RM 8.3 12.3/2).
2257
2258         elsif Is_Hidden_Non_Overridden_Subpgm (Id) then
2259            null;
2260
2261         else
2262            Set_Is_Immediately_Visible (Id);
2263         end if;
2264      end if;
2265   end Install_Package_Entity;
2266
2267   ----------------------------------
2268   -- Install_Private_Declarations --
2269   ----------------------------------
2270
2271   procedure Install_Private_Declarations (P : Entity_Id) is
2272      Id        : Entity_Id;
2273      Full      : Entity_Id;
2274      Priv_Deps : Elist_Id;
2275
2276      procedure Swap_Private_Dependents (Priv_Deps : Elist_Id);
2277      --  When the full view of a private type is made available, we do the
2278      --  same for its private dependents under proper visibility conditions.
2279      --  When compiling a child unit this needs to be done recursively.
2280
2281      -----------------------------
2282      -- Swap_Private_Dependents --
2283      -----------------------------
2284
2285      procedure Swap_Private_Dependents (Priv_Deps : Elist_Id) is
2286         Cunit     : Entity_Id;
2287         Deps      : Elist_Id;
2288         Priv      : Entity_Id;
2289         Priv_Elmt : Elmt_Id;
2290         Is_Priv   : Boolean;
2291
2292      begin
2293         Priv_Elmt := First_Elmt (Priv_Deps);
2294         while Present (Priv_Elmt) loop
2295            Priv := Node (Priv_Elmt);
2296
2297            --  Before the exchange, verify that the presence of the Full_View
2298            --  field. This field will be empty if the entity has already been
2299            --  installed due to a previous call.
2300
2301            if Present (Full_View (Priv)) and then Is_Visible_Dependent (Priv)
2302            then
2303               if Is_Private_Type (Priv) then
2304                  Cunit := Cunit_Entity (Current_Sem_Unit);
2305                  Deps := Private_Dependents (Priv);
2306                  Is_Priv := True;
2307               else
2308                  Is_Priv := False;
2309               end if;
2310
2311               --  For each subtype that is swapped, we also swap the reference
2312               --  to it in Private_Dependents, to allow access to it when we
2313               --  swap them out in End_Package_Scope.
2314
2315               Replace_Elmt (Priv_Elmt, Full_View (Priv));
2316
2317               --  Ensure that both views of the dependent private subtype are
2318               --  immediately visible if within some open scope. Check full
2319               --  view before exchanging views.
2320
2321               if In_Open_Scopes (Scope (Full_View (Priv))) then
2322                  Set_Is_Immediately_Visible (Priv);
2323               end if;
2324
2325               Exchange_Declarations (Priv);
2326               Set_Is_Immediately_Visible
2327                 (Priv, In_Open_Scopes (Scope (Priv)));
2328
2329               Set_Is_Potentially_Use_Visible
2330                 (Priv, Is_Potentially_Use_Visible (Node (Priv_Elmt)));
2331
2332               --  Recurse for child units, except in generic child units,
2333               --  which unfortunately handle private_dependents separately.
2334               --  Note that the current unit may not have been analyzed,
2335               --  for example a package body, so we cannot rely solely on
2336               --  the Is_Child_Unit flag, but that's only an optimization.
2337
2338               if Is_Priv
2339                 and then (No (Etype (Cunit)) or else Is_Child_Unit (Cunit))
2340                 and then not Is_Empty_Elmt_List (Deps)
2341                 and then not Inside_A_Generic
2342               then
2343                  Swap_Private_Dependents (Deps);
2344               end if;
2345            end if;
2346
2347            Next_Elmt (Priv_Elmt);
2348         end loop;
2349      end Swap_Private_Dependents;
2350
2351   --  Start of processing for Install_Private_Declarations
2352
2353   begin
2354      --  First exchange declarations for private types, so that the full
2355      --  declaration is visible. For each private type, we check its
2356      --  Private_Dependents list and also exchange any subtypes of or derived
2357      --  types from it. Finally, if this is a Taft amendment type, the
2358      --  incomplete declaration is irrelevant, and we want to link the
2359      --  eventual full declaration with the original private one so we
2360      --  also skip the exchange.
2361
2362      Id := First_Entity (P);
2363      while Present (Id) and then Id /= First_Private_Entity (P) loop
2364         if Is_Private_Base_Type (Id)
2365           and then Present (Full_View (Id))
2366           and then Comes_From_Source (Full_View (Id))
2367           and then Scope (Full_View (Id)) = Scope (Id)
2368           and then Ekind (Full_View (Id)) /= E_Incomplete_Type
2369         then
2370            --  If there is a use-type clause on the private type, set the full
2371            --  view accordingly.
2372
2373            Set_In_Use (Full_View (Id), In_Use (Id));
2374            Full := Full_View (Id);
2375
2376            if Is_Private_Base_Type (Full)
2377              and then Has_Private_Declaration (Full)
2378              and then Nkind (Parent (Full)) = N_Full_Type_Declaration
2379              and then In_Open_Scopes (Scope (Etype (Full)))
2380              and then In_Package_Body (Current_Scope)
2381              and then not Is_Private_Type (Etype (Full))
2382            then
2383               --  This is the completion of a private type by a derivation
2384               --  from another private type which is not private anymore. This
2385               --  can only happen in a package nested within a child package,
2386               --  when the parent type is defined in the parent unit. At this
2387               --  point the current type is not private either, and we have
2388               --  to install the underlying full view, which is now visible.
2389               --  Save the current full view as well, so that all views can be
2390               --  restored on exit. It may seem that after compiling the child
2391               --  body there are not environments to restore, but the back-end
2392               --  expects those links to be valid, and freeze nodes depend on
2393               --  them.
2394
2395               if No (Full_View (Full))
2396                 and then Present (Underlying_Full_View (Full))
2397               then
2398                  Set_Full_View (Id, Underlying_Full_View (Full));
2399                  Set_Underlying_Full_View (Id, Full);
2400                  Set_Is_Underlying_Full_View (Full);
2401
2402                  Set_Underlying_Full_View (Full, Empty);
2403                  Set_Is_Frozen (Full_View (Id));
2404               end if;
2405            end if;
2406
2407            Priv_Deps := Private_Dependents (Id);
2408            Exchange_Declarations (Id);
2409            Set_Is_Immediately_Visible (Id);
2410            Swap_Private_Dependents (Priv_Deps);
2411         end if;
2412
2413         Next_Entity (Id);
2414      end loop;
2415
2416      --  Next make other declarations in the private part visible as well
2417
2418      Id := First_Private_Entity (P);
2419      while Present (Id) loop
2420         Install_Package_Entity (Id);
2421         Set_Is_Hidden (Id, False);
2422         Next_Entity (Id);
2423      end loop;
2424
2425      --  An abstract state is partially refined when it has at least one
2426      --  Part_Of constituent. Since these constituents are being installed
2427      --  into visibility, update the partial refinement status of any state
2428      --  defined in the associated package, subject to at least one Part_Of
2429      --  constituent.
2430
2431      if Ekind_In (P, E_Generic_Package, E_Package) then
2432         declare
2433            States     : constant Elist_Id := Abstract_States (P);
2434            State_Elmt : Elmt_Id;
2435            State_Id   : Entity_Id;
2436
2437         begin
2438            if Present (States) then
2439               State_Elmt := First_Elmt (States);
2440               while Present (State_Elmt) loop
2441                  State_Id := Node (State_Elmt);
2442
2443                  if Present (Part_Of_Constituents (State_Id)) then
2444                     Set_Has_Partial_Visible_Refinement (State_Id);
2445                  end if;
2446
2447                  Next_Elmt (State_Elmt);
2448               end loop;
2449            end if;
2450         end;
2451      end if;
2452
2453      --  Indicate that the private part is currently visible, so it can be
2454      --  properly reset on exit.
2455
2456      Set_In_Private_Part (P);
2457   end Install_Private_Declarations;
2458
2459   ----------------------------------
2460   -- Install_Visible_Declarations --
2461   ----------------------------------
2462
2463   procedure Install_Visible_Declarations (P : Entity_Id) is
2464      Id          : Entity_Id;
2465      Last_Entity : Entity_Id;
2466
2467   begin
2468      pragma Assert
2469        (Is_Package_Or_Generic_Package (P) or else Is_Record_Type (P));
2470
2471      if Is_Package_Or_Generic_Package (P) then
2472         Last_Entity := First_Private_Entity (P);
2473      else
2474         Last_Entity := Empty;
2475      end if;
2476
2477      Id := First_Entity (P);
2478      while Present (Id) and then Id /= Last_Entity loop
2479         Install_Package_Entity (Id);
2480         Next_Entity (Id);
2481      end loop;
2482   end Install_Visible_Declarations;
2483
2484   --------------------------
2485   -- Is_Private_Base_Type --
2486   --------------------------
2487
2488   function Is_Private_Base_Type (E : Entity_Id) return Boolean is
2489   begin
2490      return Ekind (E) = E_Private_Type
2491        or else Ekind (E) = E_Limited_Private_Type
2492        or else Ekind (E) = E_Record_Type_With_Private;
2493   end Is_Private_Base_Type;
2494
2495   --------------------------
2496   -- Is_Visible_Dependent --
2497   --------------------------
2498
2499   function Is_Visible_Dependent (Dep : Entity_Id) return Boolean
2500   is
2501      S : constant Entity_Id := Scope (Dep);
2502
2503   begin
2504      --  Renamings created for actual types have the visibility of the actual
2505
2506      if Ekind (S) = E_Package
2507        and then Is_Generic_Instance (S)
2508        and then (Is_Generic_Actual_Type (Dep)
2509                   or else Is_Generic_Actual_Type (Full_View (Dep)))
2510      then
2511         return True;
2512
2513      elsif not (Is_Derived_Type (Dep))
2514        and then Is_Derived_Type (Full_View (Dep))
2515      then
2516         --  When instantiating a package body, the scope stack is empty, so
2517         --  check instead whether the dependent type is defined in the same
2518         --  scope as the instance itself.
2519
2520         return In_Open_Scopes (S)
2521           or else (Is_Generic_Instance (Current_Scope)
2522                     and then Scope (Dep) = Scope (Current_Scope));
2523      else
2524         return True;
2525      end if;
2526   end Is_Visible_Dependent;
2527
2528   ----------------------------
2529   -- May_Need_Implicit_Body --
2530   ----------------------------
2531
2532   procedure May_Need_Implicit_Body (E : Entity_Id) is
2533      P     : constant Node_Id := Unit_Declaration_Node (E);
2534      S     : constant Node_Id := Parent (P);
2535      B     : Node_Id;
2536      Decls : List_Id;
2537
2538   begin
2539      if not Has_Completion (E)
2540        and then Nkind (P) = N_Package_Declaration
2541        and then (Present (Activation_Chain_Entity (P)) or else Has_RACW (E))
2542      then
2543         B :=
2544           Make_Package_Body (Sloc (E),
2545             Defining_Unit_Name => Make_Defining_Identifier (Sloc (E),
2546               Chars => Chars (E)),
2547             Declarations  => New_List);
2548
2549         if Nkind (S) = N_Package_Specification then
2550            if Present (Private_Declarations (S)) then
2551               Decls := Private_Declarations (S);
2552            else
2553               Decls := Visible_Declarations (S);
2554            end if;
2555         else
2556            Decls := Declarations (S);
2557         end if;
2558
2559         Append (B, Decls);
2560         Analyze (B);
2561      end if;
2562   end May_Need_Implicit_Body;
2563
2564   ----------------------
2565   -- New_Private_Type --
2566   ----------------------
2567
2568   procedure New_Private_Type (N : Node_Id; Id : Entity_Id; Def : Node_Id) is
2569   begin
2570      --  For other than Ada 2012, enter the name in the current scope
2571
2572      if Ada_Version < Ada_2012 then
2573         Enter_Name (Id);
2574
2575      --  Ada 2012 (AI05-0162): Enter the name in the current scope. Note that
2576      --  there may be an incomplete previous view.
2577
2578      else
2579         declare
2580            Prev : Entity_Id;
2581         begin
2582            Prev := Find_Type_Name (N);
2583            pragma Assert (Prev = Id
2584              or else (Ekind (Prev) = E_Incomplete_Type
2585                        and then Present (Full_View (Prev))
2586                        and then Full_View (Prev) = Id));
2587         end;
2588      end if;
2589
2590      if Limited_Present (Def) then
2591         Set_Ekind (Id, E_Limited_Private_Type);
2592      else
2593         Set_Ekind (Id, E_Private_Type);
2594      end if;
2595
2596      Set_Etype              (Id, Id);
2597      Set_Has_Delayed_Freeze (Id);
2598      Set_Is_First_Subtype   (Id);
2599      Init_Size_Align        (Id);
2600
2601      Set_Is_Constrained (Id,
2602        No (Discriminant_Specifications (N))
2603          and then not Unknown_Discriminants_Present (N));
2604
2605      --  Set tagged flag before processing discriminants, to catch illegal
2606      --  usage.
2607
2608      Set_Is_Tagged_Type (Id, Tagged_Present (Def));
2609
2610      Set_Discriminant_Constraint (Id, No_Elist);
2611      Set_Stored_Constraint (Id, No_Elist);
2612
2613      if Present (Discriminant_Specifications (N)) then
2614         Push_Scope (Id);
2615         Process_Discriminants (N);
2616         End_Scope;
2617
2618      elsif Unknown_Discriminants_Present (N) then
2619         Set_Has_Unknown_Discriminants (Id);
2620      end if;
2621
2622      Set_Private_Dependents (Id, New_Elmt_List);
2623
2624      if Tagged_Present (Def) then
2625         Set_Ekind                       (Id, E_Record_Type_With_Private);
2626         Set_Direct_Primitive_Operations (Id, New_Elmt_List);
2627         Set_Is_Abstract_Type            (Id, Abstract_Present (Def));
2628         Set_Is_Limited_Record           (Id, Limited_Present (Def));
2629         Set_Has_Delayed_Freeze          (Id, True);
2630
2631         --  Recognize Ada.Real_Time.Timing_Events.Timing_Events here
2632
2633         if Is_RTE (Id, RE_Timing_Event) then
2634            Set_Has_Timing_Event (Id);
2635         end if;
2636
2637         --  Create a class-wide type with the same attributes
2638
2639         Make_Class_Wide_Type (Id);
2640
2641      elsif Abstract_Present (Def) then
2642         Error_Msg_N ("only a tagged type can be abstract", N);
2643      end if;
2644   end New_Private_Type;
2645
2646   ---------------------------------
2647   -- Requires_Completion_In_Body --
2648   ---------------------------------
2649
2650   function Requires_Completion_In_Body
2651     (Id                 : Entity_Id;
2652      Pack_Id            : Entity_Id;
2653      Do_Abstract_States : Boolean := False) return Boolean
2654   is
2655   begin
2656      --  Always ignore child units. Child units get added to the entity list
2657      --  of a parent unit, but are not original entities of the parent, and
2658      --  so do not affect whether the parent needs a body.
2659
2660      if Is_Child_Unit (Id) then
2661         return False;
2662
2663      --  Ignore formal packages and their renamings
2664
2665      elsif Ekind (Id) = E_Package
2666        and then Nkind (Original_Node (Unit_Declaration_Node (Id))) =
2667                   N_Formal_Package_Declaration
2668      then
2669         return False;
2670
2671      --  Otherwise test to see if entity requires a completion. Note that
2672      --  subprogram entities whose declaration does not come from source are
2673      --  ignored here on the basis that we assume the expander will provide an
2674      --  implicit completion at some point.
2675
2676      elsif (Is_Overloadable (Id)
2677              and then not Ekind_In (Id, E_Enumeration_Literal, E_Operator)
2678              and then not Is_Abstract_Subprogram (Id)
2679              and then not Has_Completion (Id)
2680              and then Comes_From_Source (Parent (Id)))
2681
2682        or else
2683          (Ekind (Id) = E_Package
2684            and then Id /= Pack_Id
2685            and then not Has_Completion (Id)
2686            and then Unit_Requires_Body (Id, Do_Abstract_States))
2687
2688        or else
2689          (Ekind (Id) = E_Incomplete_Type
2690            and then No (Full_View (Id))
2691            and then not Is_Generic_Type (Id))
2692
2693        or else
2694          (Ekind_In (Id, E_Task_Type, E_Protected_Type)
2695            and then not Has_Completion (Id))
2696
2697        or else
2698          (Ekind (Id) = E_Generic_Package
2699            and then Id /= Pack_Id
2700            and then not Has_Completion (Id)
2701            and then Unit_Requires_Body (Id, Do_Abstract_States))
2702
2703        or else
2704          (Is_Generic_Subprogram (Id)
2705            and then not Has_Completion (Id))
2706      then
2707         return True;
2708
2709      --  Otherwise the entity does not require completion in a package body
2710
2711      else
2712         return False;
2713      end if;
2714   end Requires_Completion_In_Body;
2715
2716   ----------------------------
2717   -- Uninstall_Declarations --
2718   ----------------------------
2719
2720   procedure Uninstall_Declarations (P : Entity_Id) is
2721      Decl      : constant Node_Id := Unit_Declaration_Node (P);
2722      Id        : Entity_Id;
2723      Full      : Entity_Id;
2724
2725      procedure Preserve_Full_Attributes (Priv : Entity_Id; Full : Entity_Id);
2726      --  Copy to the private declaration the attributes of the full view that
2727      --  need to be available for the partial view also.
2728
2729      procedure Swap_Private_Dependents (Priv_Deps : Elist_Id);
2730      --  When the full view of a private type is made unavailable, we do the
2731      --  same for its private dependents under proper visibility conditions.
2732      --  When compiling a child unit this needs to be done recursively.
2733
2734      function Type_In_Use (T : Entity_Id) return Boolean;
2735      --  Check whether type or base type appear in an active use_type clause
2736
2737      ------------------------------
2738      -- Preserve_Full_Attributes --
2739      ------------------------------
2740
2741      procedure Preserve_Full_Attributes
2742        (Priv : Entity_Id;
2743         Full : Entity_Id)
2744      is
2745         Full_Base         : constant Entity_Id := Base_Type (Full);
2746         Priv_Is_Base_Type : constant Boolean   := Is_Base_Type (Priv);
2747
2748      begin
2749         Set_Size_Info               (Priv,                             Full);
2750         Set_RM_Size                 (Priv, RM_Size                    (Full));
2751         Set_Size_Known_At_Compile_Time
2752                                     (Priv, Size_Known_At_Compile_Time (Full));
2753         Set_Is_Volatile             (Priv, Is_Volatile                (Full));
2754         Set_Treat_As_Volatile       (Priv, Treat_As_Volatile          (Full));
2755         Set_Is_Ada_2005_Only        (Priv, Is_Ada_2005_Only           (Full));
2756         Set_Is_Ada_2012_Only        (Priv, Is_Ada_2012_Only           (Full));
2757         Set_Has_Pragma_Unmodified   (Priv, Has_Pragma_Unmodified      (Full));
2758         Set_Has_Pragma_Unreferenced (Priv, Has_Pragma_Unreferenced    (Full));
2759         Set_Has_Pragma_Unreferenced_Objects
2760                                     (Priv, Has_Pragma_Unreferenced_Objects
2761                                                                       (Full));
2762         if Is_Unchecked_Union (Full) then
2763            Set_Is_Unchecked_Union (Base_Type (Priv));
2764         end if;
2765         --  Why is atomic not copied here ???
2766
2767         if Referenced (Full) then
2768            Set_Referenced (Priv);
2769         end if;
2770
2771         if Priv_Is_Base_Type then
2772            Set_Is_Controlled_Active
2773                              (Priv, Is_Controlled_Active     (Full_Base));
2774            Set_Finalize_Storage_Only
2775                              (Priv, Finalize_Storage_Only    (Full_Base));
2776            Set_Has_Controlled_Component
2777                              (Priv, Has_Controlled_Component (Full_Base));
2778
2779            Propagate_Concurrent_Flags (Priv, Base_Type (Full));
2780         end if;
2781
2782         --  As explained in Freeze_Entity, private types are required to point
2783         --  to the same freeze node as their corresponding full view, if any.
2784         --  But we ought not to overwrite a node already inserted in the tree.
2785
2786         pragma Assert
2787           (Serious_Errors_Detected /= 0
2788             or else No (Freeze_Node (Priv))
2789             or else No (Parent (Freeze_Node (Priv)))
2790             or else Freeze_Node (Priv) = Freeze_Node (Full));
2791
2792         Set_Freeze_Node (Priv, Freeze_Node (Full));
2793
2794         --  Propagate Default_Initial_Condition-related attributes from the
2795         --  base type of the full view to the full view and vice versa. This
2796         --  may seem strange, but is necessary depending on which type
2797         --  triggered the generation of the DIC procedure body. As a result,
2798         --  both the full view and its base type carry the same DIC-related
2799         --  information.
2800
2801         Propagate_DIC_Attributes (Full, From_Typ => Full_Base);
2802         Propagate_DIC_Attributes (Full_Base, From_Typ => Full);
2803
2804         --  Propagate Default_Initial_Condition-related attributes from the
2805         --  full view to the private view.
2806
2807         Propagate_DIC_Attributes (Priv, From_Typ => Full);
2808
2809         --  Propagate invariant-related attributes from the base type of the
2810         --  full view to the full view and vice versa. This may seem strange,
2811         --  but is necessary depending on which type triggered the generation
2812         --  of the invariant procedure body. As a result, both the full view
2813         --  and its base type carry the same invariant-related information.
2814
2815         Propagate_Invariant_Attributes (Full, From_Typ => Full_Base);
2816         Propagate_Invariant_Attributes (Full_Base, From_Typ => Full);
2817
2818         --  Propagate invariant-related attributes from the full view to the
2819         --  private view.
2820
2821         Propagate_Invariant_Attributes (Priv, From_Typ => Full);
2822
2823         if Is_Tagged_Type (Priv)
2824           and then Is_Tagged_Type (Full)
2825           and then not Error_Posted (Full)
2826         then
2827            if Is_Tagged_Type (Priv) then
2828
2829               --  If the type is tagged, the tag itself must be available on
2830               --  the partial view, for expansion purposes.
2831
2832               Set_First_Entity (Priv, First_Entity (Full));
2833
2834               --  If there are discriminants in the partial view, these remain
2835               --  visible. Otherwise only the tag itself is visible, and there
2836               --  are no nameable components in the partial view.
2837
2838               if No (Last_Entity (Priv)) then
2839                  Set_Last_Entity (Priv, First_Entity (Priv));
2840               end if;
2841            end if;
2842
2843            Set_Has_Discriminants (Priv, Has_Discriminants (Full));
2844
2845            if Has_Discriminants (Full) then
2846               Set_Discriminant_Constraint (Priv,
2847                 Discriminant_Constraint (Full));
2848            end if;
2849         end if;
2850      end Preserve_Full_Attributes;
2851
2852      -----------------------------
2853      -- Swap_Private_Dependents --
2854      -----------------------------
2855
2856      procedure Swap_Private_Dependents (Priv_Deps : Elist_Id) is
2857         Cunit     : Entity_Id;
2858         Deps      : Elist_Id;
2859         Priv      : Entity_Id;
2860         Priv_Elmt : Elmt_Id;
2861         Is_Priv   : Boolean;
2862
2863      begin
2864         Priv_Elmt := First_Elmt (Priv_Deps);
2865         while Present (Priv_Elmt) loop
2866            Priv := Node (Priv_Elmt);
2867
2868            --  Before we do the swap, we verify the presence of the Full_View
2869            --  field, which may be empty due to a swap by a previous call to
2870            --  End_Package_Scope (e.g. from the freezing mechanism).
2871
2872            if Present (Full_View (Priv)) then
2873               if Is_Private_Type (Priv) then
2874                  Cunit := Cunit_Entity (Current_Sem_Unit);
2875                  Deps := Private_Dependents (Priv);
2876                  Is_Priv := True;
2877               else
2878                  Is_Priv := False;
2879               end if;
2880
2881               if Scope (Priv) = P
2882                 or else not In_Open_Scopes (Scope (Priv))
2883               then
2884                  Set_Is_Immediately_Visible (Priv, False);
2885               end if;
2886
2887               if Is_Visible_Dependent (Priv) then
2888                  Preserve_Full_Attributes (Priv, Full_View (Priv));
2889                  Replace_Elmt (Priv_Elmt, Full_View (Priv));
2890                  Exchange_Declarations (Priv);
2891
2892                  --  Recurse for child units, except in generic child units,
2893                  --  which unfortunately handle private_dependents separately.
2894                  --  Note that the current unit may not have been analyzed,
2895                  --  for example a package body, so we cannot rely solely on
2896                  --  the Is_Child_Unit flag, but that's only an optimization.
2897
2898                  if Is_Priv
2899                    and then (No (Etype (Cunit)) or else Is_Child_Unit (Cunit))
2900                    and then not Is_Empty_Elmt_List (Deps)
2901                    and then not Inside_A_Generic
2902                  then
2903                     Swap_Private_Dependents (Deps);
2904                  end if;
2905               end if;
2906            end if;
2907
2908            Next_Elmt (Priv_Elmt);
2909         end loop;
2910      end Swap_Private_Dependents;
2911
2912      -----------------
2913      -- Type_In_Use --
2914      -----------------
2915
2916      function Type_In_Use (T : Entity_Id) return Boolean is
2917      begin
2918         return Scope (Base_Type (T)) = P
2919           and then (In_Use (T) or else In_Use (Base_Type (T)));
2920      end Type_In_Use;
2921
2922   --  Start of processing for Uninstall_Declarations
2923
2924   begin
2925      Id := First_Entity (P);
2926      while Present (Id) and then Id /= First_Private_Entity (P) loop
2927         if Debug_Flag_E then
2928            Write_Str ("unlinking visible entity ");
2929            Write_Int (Int (Id));
2930            Write_Eol;
2931         end if;
2932
2933         --  On exit from the package scope, we must preserve the visibility
2934         --  established by use clauses in the current scope. Two cases:
2935
2936         --  a) If the entity is an operator, it may be a primitive operator of
2937         --  a type for which there is a visible use-type clause.
2938
2939         --  b) For other entities, their use-visibility is determined by a
2940         --  visible use clause for the package itself or a use-all-type clause
2941         --  applied directly to the entity's type. For a generic instance,
2942         --  the instantiation of the formals appears in the visible part,
2943         --  but the formals are private and remain so.
2944
2945         if Ekind (Id) = E_Function
2946           and then Is_Operator_Symbol_Name (Chars (Id))
2947           and then not Is_Hidden (Id)
2948           and then not Error_Posted (Id)
2949         then
2950            Set_Is_Potentially_Use_Visible (Id,
2951              In_Use (P)
2952              or else Type_In_Use (Etype (Id))
2953              or else Type_In_Use (Etype (First_Formal (Id)))
2954              or else (Present (Next_Formal (First_Formal (Id)))
2955                        and then
2956                          Type_In_Use
2957                            (Etype (Next_Formal (First_Formal (Id))))));
2958         else
2959            if In_Use (P) and then not Is_Hidden (Id) then
2960
2961               --  A child unit of a use-visible package remains use-visible
2962               --  only if it is itself a visible child unit. Otherwise it
2963               --  would remain visible in other contexts where P is use-
2964               --  visible, because once compiled it stays in the entity list
2965               --  of its parent unit.
2966
2967               if Is_Child_Unit (Id) then
2968                  Set_Is_Potentially_Use_Visible
2969                    (Id, Is_Visible_Lib_Unit (Id));
2970               else
2971                  Set_Is_Potentially_Use_Visible (Id);
2972               end if;
2973
2974            --  We need to avoid incorrectly marking enumeration literals as
2975            --  non-visible when a visible use-all-type clause is in effect.
2976
2977            elsif Type_In_Use (Etype (Id))
2978              and then Nkind (Current_Use_Clause (Etype (Id))) =
2979                         N_Use_Type_Clause
2980              and then All_Present (Current_Use_Clause (Etype (Id)))
2981            then
2982               null;
2983
2984            else
2985               Set_Is_Potentially_Use_Visible (Id, False);
2986            end if;
2987         end if;
2988
2989         --  Local entities are not immediately visible outside of the package
2990
2991         Set_Is_Immediately_Visible (Id, False);
2992
2993         --  If this is a private type with a full view (for example a local
2994         --  subtype of a private type declared elsewhere), ensure that the
2995         --  full view is also removed from visibility: it may be exposed when
2996         --  swapping views in an instantiation. Similarly, ensure that the
2997         --  use-visibility is properly set on both views.
2998
2999         if Is_Type (Id) and then Present (Full_View (Id)) then
3000            Set_Is_Immediately_Visible     (Full_View (Id), False);
3001            Set_Is_Potentially_Use_Visible (Full_View (Id),
3002              Is_Potentially_Use_Visible (Id));
3003         end if;
3004
3005         if Is_Tagged_Type (Id) and then Ekind (Id) = E_Record_Type then
3006            Check_Abstract_Overriding (Id);
3007            Check_Conventions (Id);
3008         end if;
3009
3010         if Ekind_In (Id, E_Private_Type, E_Limited_Private_Type)
3011           and then No (Full_View (Id))
3012           and then not Is_Generic_Type (Id)
3013           and then not Is_Derived_Type (Id)
3014         then
3015            Error_Msg_N ("missing full declaration for private type&", Id);
3016
3017         elsif Ekind (Id) = E_Record_Type_With_Private
3018           and then not Is_Generic_Type (Id)
3019           and then No (Full_View (Id))
3020         then
3021            if Nkind (Parent (Id)) = N_Private_Type_Declaration then
3022               Error_Msg_N ("missing full declaration for private type&", Id);
3023            else
3024               Error_Msg_N
3025                 ("missing full declaration for private extension", Id);
3026            end if;
3027
3028         --  Case of constant, check for deferred constant declaration with
3029         --  no full view. Likely just a matter of a missing expression, or
3030         --  accidental use of the keyword constant.
3031
3032         elsif Ekind (Id) = E_Constant
3033
3034           --  OK if constant value present
3035
3036           and then No (Constant_Value (Id))
3037
3038           --  OK if full view present
3039
3040           and then No (Full_View (Id))
3041
3042           --  OK if imported, since that provides the completion
3043
3044           and then not Is_Imported (Id)
3045
3046           --  OK if object declaration replaced by renaming declaration as
3047           --  a result of OK_To_Rename processing (e.g. for concatenation)
3048
3049           and then Nkind (Parent (Id)) /= N_Object_Renaming_Declaration
3050
3051           --  OK if object declaration with the No_Initialization flag set
3052
3053           and then not (Nkind (Parent (Id)) = N_Object_Declaration
3054                          and then No_Initialization (Parent (Id)))
3055         then
3056            --  If no private declaration is present, we assume the user did
3057            --  not intend a deferred constant declaration and the problem
3058            --  is simply that the initializing expression is missing.
3059
3060            if not Has_Private_Declaration (Etype (Id)) then
3061
3062               --  We assume that the user did not intend a deferred constant
3063               --  declaration, and the expression is just missing.
3064
3065               Error_Msg_N
3066                 ("constant declaration requires initialization expression",
3067                   Parent (Id));
3068
3069               if Is_Limited_Type (Etype (Id)) then
3070                  Error_Msg_N
3071                    ("\if variable intended, remove CONSTANT from declaration",
3072                    Parent (Id));
3073               end if;
3074
3075            --  Otherwise if a private declaration is present, then we are
3076            --  missing the full declaration for the deferred constant.
3077
3078            else
3079               Error_Msg_N
3080                 ("missing full declaration for deferred constant (RM 7.4)",
3081                  Id);
3082
3083               if Is_Limited_Type (Etype (Id)) then
3084                  Error_Msg_N
3085                    ("\if variable intended, remove CONSTANT from declaration",
3086                     Parent (Id));
3087               end if;
3088            end if;
3089         end if;
3090
3091         Next_Entity (Id);
3092      end loop;
3093
3094      --  If the specification was installed as the parent of a public child
3095      --  unit, the private declarations were not installed, and there is
3096      --  nothing to do.
3097
3098      if not In_Private_Part (P) then
3099         return;
3100      else
3101         Set_In_Private_Part (P, False);
3102      end if;
3103
3104      --  Make private entities invisible and exchange full and private
3105      --  declarations for private types. Id is now the first private entity
3106      --  in the package.
3107
3108      while Present (Id) loop
3109         if Debug_Flag_E then
3110            Write_Str ("unlinking private entity ");
3111            Write_Int (Int (Id));
3112            Write_Eol;
3113         end if;
3114
3115         if Is_Tagged_Type (Id) and then Ekind (Id) = E_Record_Type then
3116            Check_Abstract_Overriding (Id);
3117            Check_Conventions (Id);
3118         end if;
3119
3120         Set_Is_Immediately_Visible (Id, False);
3121
3122         if Is_Private_Base_Type (Id) and then Present (Full_View (Id)) then
3123            Full := Full_View (Id);
3124
3125            --  If the partial view is not declared in the visible part of the
3126            --  package (as is the case when it is a type derived from some
3127            --  other private type in the private part of the current package),
3128            --  no exchange takes place.
3129
3130            if No (Parent (Id))
3131              or else List_Containing (Parent (Id)) /=
3132                               Visible_Declarations (Specification (Decl))
3133            then
3134               goto Next_Id;
3135            end if;
3136
3137            --  The entry in the private part points to the full declaration,
3138            --  which is currently visible. Exchange them so only the private
3139            --  type declaration remains accessible, and link private and full
3140            --  declaration in the opposite direction. Before the actual
3141            --  exchange, we copy back attributes of the full view that must
3142            --  be available to the partial view too.
3143
3144            Preserve_Full_Attributes (Id, Full);
3145
3146            Set_Is_Potentially_Use_Visible (Id, In_Use (P));
3147
3148            --  The following test may be redundant, as this is already
3149            --  diagnosed in sem_ch3. ???
3150
3151            if not Is_Definite_Subtype (Full)
3152              and then Is_Definite_Subtype (Id)
3153            then
3154               Error_Msg_Sloc := Sloc (Parent (Id));
3155               Error_Msg_NE
3156                 ("full view of& not compatible with declaration#", Full, Id);
3157            end if;
3158
3159            --  Swap out the subtypes and derived types of Id that
3160            --  were compiled in this scope, or installed previously
3161            --  by Install_Private_Declarations.
3162
3163            Swap_Private_Dependents (Private_Dependents (Id));
3164
3165            --  Now restore the type itself to its private view
3166
3167            Exchange_Declarations (Id);
3168
3169            --  If we have installed an underlying full view for a type derived
3170            --  from a private type in a child unit, restore the proper views
3171            --  of private and full view. See corresponding code in
3172            --  Install_Private_Declarations.
3173
3174            --  After the exchange, Full denotes the private type in the
3175            --  visible part of the package.
3176
3177            if Is_Private_Base_Type (Full)
3178              and then Present (Full_View (Full))
3179              and then Present (Underlying_Full_View (Full))
3180              and then In_Package_Body (Current_Scope)
3181            then
3182               Set_Full_View (Full, Underlying_Full_View (Full));
3183               Set_Underlying_Full_View (Full, Empty);
3184            end if;
3185
3186         elsif Ekind (Id) = E_Incomplete_Type
3187           and then Comes_From_Source (Id)
3188           and then No (Full_View (Id))
3189         then
3190            --  Mark Taft amendment types. Verify that there are no primitive
3191            --  operations declared for the type (3.10.1(9)).
3192
3193            Set_Has_Completion_In_Body (Id);
3194
3195            declare
3196               Elmt : Elmt_Id;
3197               Subp : Entity_Id;
3198
3199            begin
3200               Elmt := First_Elmt (Private_Dependents (Id));
3201               while Present (Elmt) loop
3202                  Subp := Node (Elmt);
3203
3204                  --  Is_Primitive is tested because there can be cases where
3205                  --  nonprimitive subprograms (in nested packages) are added
3206                  --  to the Private_Dependents list.
3207
3208                  if Is_Overloadable (Subp) and then Is_Primitive (Subp) then
3209                     Error_Msg_NE
3210                       ("type& must be completed in the private part",
3211                        Parent (Subp), Id);
3212
3213                  --  The result type of an access-to-function type cannot be a
3214                  --  Taft-amendment type, unless the version is Ada 2012 or
3215                  --  later (see AI05-151).
3216
3217                  elsif Ada_Version < Ada_2012
3218                    and then Ekind (Subp) = E_Subprogram_Type
3219                  then
3220                     if Etype (Subp) = Id
3221                       or else
3222                         (Is_Class_Wide_Type (Etype (Subp))
3223                           and then Etype (Etype (Subp)) = Id)
3224                     then
3225                        Error_Msg_NE
3226                          ("type& must be completed in the private part",
3227                             Associated_Node_For_Itype (Subp), Id);
3228                     end if;
3229                  end if;
3230
3231                  Next_Elmt (Elmt);
3232               end loop;
3233            end;
3234
3235         elsif not Is_Child_Unit (Id)
3236           and then (not Is_Private_Type (Id) or else No (Full_View (Id)))
3237         then
3238            Set_Is_Hidden (Id);
3239            Set_Is_Potentially_Use_Visible (Id, False);
3240         end if;
3241
3242         <<Next_Id>>
3243            Next_Entity (Id);
3244      end loop;
3245   end Uninstall_Declarations;
3246
3247   ------------------------
3248   -- Unit_Requires_Body --
3249   ------------------------
3250
3251   function Unit_Requires_Body
3252     (Pack_Id            : Entity_Id;
3253      Do_Abstract_States : Boolean := False) return Boolean
3254   is
3255      E : Entity_Id;
3256
3257      Requires_Body : Boolean := False;
3258      --  Flag set when the unit has at least one construct that requires
3259      --  completion in a body.
3260
3261   begin
3262      --  Imported entity never requires body. Right now, only subprograms can
3263      --  be imported, but perhaps in the future we will allow import of
3264      --  packages.
3265
3266      if Is_Imported (Pack_Id) then
3267         return False;
3268
3269      --  Body required if library package with pragma Elaborate_Body
3270
3271      elsif Has_Pragma_Elaborate_Body (Pack_Id) then
3272         return True;
3273
3274      --  Body required if subprogram
3275
3276      elsif Is_Subprogram_Or_Generic_Subprogram (Pack_Id) then
3277         return True;
3278
3279      --  Treat a block as requiring a body
3280
3281      elsif Ekind (Pack_Id) = E_Block then
3282         return True;
3283
3284      elsif Ekind (Pack_Id) = E_Package
3285        and then Nkind (Parent (Pack_Id)) = N_Package_Specification
3286        and then Present (Generic_Parent (Parent (Pack_Id)))
3287      then
3288         declare
3289            G_P : constant Entity_Id := Generic_Parent (Parent (Pack_Id));
3290         begin
3291            if Has_Pragma_Elaborate_Body (G_P) then
3292               return True;
3293            end if;
3294         end;
3295      end if;
3296
3297      --  Traverse the entity chain of the package and look for constructs that
3298      --  require a completion in a body.
3299
3300      E := First_Entity (Pack_Id);
3301      while Present (E) loop
3302
3303         --  Skip abstract states because their completion depends on several
3304         --  criteria (see below).
3305
3306         if Ekind (E) = E_Abstract_State then
3307            null;
3308
3309         elsif Requires_Completion_In_Body
3310                 (E, Pack_Id, Do_Abstract_States)
3311         then
3312            Requires_Body := True;
3313            exit;
3314         end if;
3315
3316         Next_Entity (E);
3317      end loop;
3318
3319      --  A [generic] package that defines at least one non-null abstract state
3320      --  requires a completion only when at least one other construct requires
3321      --  a completion in a body (SPARK RM 7.1.4(4) and (5)). This check is not
3322      --  performed if the caller requests this behavior.
3323
3324      if Do_Abstract_States
3325        and then Ekind_In (Pack_Id, E_Generic_Package, E_Package)
3326        and then Has_Non_Null_Abstract_State (Pack_Id)
3327        and then Requires_Body
3328      then
3329         return True;
3330      end if;
3331
3332      return Requires_Body;
3333   end Unit_Requires_Body;
3334
3335   -----------------------------
3336   -- Unit_Requires_Body_Info --
3337   -----------------------------
3338
3339   procedure Unit_Requires_Body_Info (Pack_Id : Entity_Id) is
3340      E : Entity_Id;
3341
3342   begin
3343      --  An imported entity never requires body. Right now, only subprograms
3344      --  can be imported, but perhaps in the future we will allow import of
3345      --  packages.
3346
3347      if Is_Imported (Pack_Id) then
3348         return;
3349
3350      --  Body required if library package with pragma Elaborate_Body
3351
3352      elsif Has_Pragma_Elaborate_Body (Pack_Id) then
3353         Error_Msg_N ("info: & requires body (Elaborate_Body)?Y?", Pack_Id);
3354
3355      --  Body required if subprogram
3356
3357      elsif Is_Subprogram_Or_Generic_Subprogram (Pack_Id) then
3358         Error_Msg_N ("info: & requires body (subprogram case)?Y?", Pack_Id);
3359
3360      --  Body required if generic parent has Elaborate_Body
3361
3362      elsif Ekind (Pack_Id) = E_Package
3363        and then Nkind (Parent (Pack_Id)) = N_Package_Specification
3364        and then Present (Generic_Parent (Parent (Pack_Id)))
3365      then
3366         declare
3367            G_P : constant Entity_Id := Generic_Parent (Parent (Pack_Id));
3368         begin
3369            if Has_Pragma_Elaborate_Body (G_P) then
3370               Error_Msg_N
3371                 ("info: & requires body (generic parent Elaborate_Body)?Y?",
3372                  Pack_Id);
3373            end if;
3374         end;
3375
3376      --  A [generic] package that introduces at least one non-null abstract
3377      --  state requires completion. However, there is a separate rule that
3378      --  requires that such a package have a reason other than this for a
3379      --  body being required (if necessary a pragma Elaborate_Body must be
3380      --  provided). If Ignore_Abstract_State is True, we don't do this check
3381      --  (so we can use Unit_Requires_Body to check for some other reason).
3382
3383      elsif Ekind_In (Pack_Id, E_Generic_Package, E_Package)
3384        and then Present (Abstract_States (Pack_Id))
3385        and then not Is_Null_State
3386                       (Node (First_Elmt (Abstract_States (Pack_Id))))
3387      then
3388         Error_Msg_N
3389           ("info: & requires body (non-null abstract state aspect)?Y?",
3390            Pack_Id);
3391      end if;
3392
3393      --  Otherwise search entity chain for entity requiring completion
3394
3395      E := First_Entity (Pack_Id);
3396      while Present (E) loop
3397         if Requires_Completion_In_Body (E, Pack_Id) then
3398            Error_Msg_Node_2 := E;
3399            Error_Msg_NE
3400              ("info: & requires body (& requires completion)?Y?", E, Pack_Id);
3401         end if;
3402
3403         Next_Entity (E);
3404      end loop;
3405   end Unit_Requires_Body_Info;
3406
3407end Sem_Ch7;
3408