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