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