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