File : sem_ch3.adb


   1 ------------------------------------------------------------------------------
   2 --                                                                          --
   3 --                         GNAT COMPILER COMPONENTS                         --
   4 --                                                                          --
   5 --                              S E M _ C H 3                               --
   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 with Aspects;   use Aspects;
  27 with Atree;     use Atree;
  28 with Checks;    use Checks;
  29 with Contracts; use Contracts;
  30 with Debug;     use Debug;
  31 with Elists;    use Elists;
  32 with Einfo;     use Einfo;
  33 with Errout;    use Errout;
  34 with Eval_Fat;  use Eval_Fat;
  35 with Exp_Ch3;   use Exp_Ch3;
  36 with Exp_Ch9;   use Exp_Ch9;
  37 with Exp_Disp;  use Exp_Disp;
  38 with Exp_Dist;  use Exp_Dist;
  39 with Exp_Tss;   use Exp_Tss;
  40 with Exp_Util;  use Exp_Util;
  41 with Fname;     use Fname;
  42 with Freeze;    use Freeze;
  43 with Ghost;     use Ghost;
  44 with Itypes;    use Itypes;
  45 with Layout;    use Layout;
  46 with Lib;       use Lib;
  47 with Lib.Xref;  use Lib.Xref;
  48 with Namet;     use Namet;
  49 with Nmake;     use Nmake;
  50 with Opt;       use Opt;
  51 with Restrict;  use Restrict;
  52 with Rident;    use Rident;
  53 with Rtsfind;   use Rtsfind;
  54 with Sem;       use Sem;
  55 with Sem_Aux;   use Sem_Aux;
  56 with Sem_Case;  use Sem_Case;
  57 with Sem_Cat;   use Sem_Cat;
  58 with Sem_Ch6;   use Sem_Ch6;
  59 with Sem_Ch7;   use Sem_Ch7;
  60 with Sem_Ch8;   use Sem_Ch8;
  61 with Sem_Ch13;  use Sem_Ch13;
  62 with Sem_Dim;   use Sem_Dim;
  63 with Sem_Disp;  use Sem_Disp;
  64 with Sem_Dist;  use Sem_Dist;
  65 with Sem_Elim;  use Sem_Elim;
  66 with Sem_Eval;  use Sem_Eval;
  67 with Sem_Mech;  use Sem_Mech;
  68 with Sem_Res;   use Sem_Res;
  69 with Sem_Smem;  use Sem_Smem;
  70 with Sem_Type;  use Sem_Type;
  71 with Sem_Util;  use Sem_Util;
  72 with Sem_Warn;  use Sem_Warn;
  73 with Stand;     use Stand;
  74 with Sinfo;     use Sinfo;
  75 with Sinput;    use Sinput;
  76 with Snames;    use Snames;
  77 with Targparm;  use Targparm;
  78 with Tbuild;    use Tbuild;
  79 with Ttypes;    use Ttypes;
  80 with Uintp;     use Uintp;
  81 with Urealp;    use Urealp;
  82 
  83 package body Sem_Ch3 is
  84 
  85    -----------------------
  86    -- Local Subprograms --
  87    -----------------------
  88 
  89    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
  90    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
  91    --  abstract interface types implemented by a record type or a derived
  92    --  record type.
  93 
  94    procedure Build_Derived_Type
  95      (N             : Node_Id;
  96       Parent_Type   : Entity_Id;
  97       Derived_Type  : Entity_Id;
  98       Is_Completion : Boolean;
  99       Derive_Subps  : Boolean := True);
 100    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
 101    --  the N_Full_Type_Declaration node containing the derived type definition.
 102    --  Parent_Type is the entity for the parent type in the derived type
 103    --  definition and Derived_Type the actual derived type. Is_Completion must
 104    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
 105    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
 106    --  completion of a private type declaration. If Is_Completion is set to
 107    --  True, N is the completion of a private type declaration and Derived_Type
 108    --  is different from the defining identifier inside N (i.e. Derived_Type /=
 109    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
 110    --  subprograms should be derived. The only case where this parameter is
 111    --  False is when Build_Derived_Type is recursively called to process an
 112    --  implicit derived full type for a type derived from a private type (in
 113    --  that case the subprograms must only be derived for the private view of
 114    --  the type).
 115    --
 116    --  ??? These flags need a bit of re-examination and re-documentation:
 117    --  ???  are they both necessary (both seem related to the recursion)?
 118 
 119    procedure Build_Derived_Access_Type
 120      (N            : Node_Id;
 121       Parent_Type  : Entity_Id;
 122       Derived_Type : Entity_Id);
 123    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
 124    --  create an implicit base if the parent type is constrained or if the
 125    --  subtype indication has a constraint.
 126 
 127    procedure Build_Derived_Array_Type
 128      (N            : Node_Id;
 129       Parent_Type  : Entity_Id;
 130       Derived_Type : Entity_Id);
 131    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
 132    --  create an implicit base if the parent type is constrained or if the
 133    --  subtype indication has a constraint.
 134 
 135    procedure Build_Derived_Concurrent_Type
 136      (N            : Node_Id;
 137       Parent_Type  : Entity_Id;
 138       Derived_Type : Entity_Id);
 139    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
 140    --  protected type, inherit entries and protected subprograms, check
 141    --  legality of discriminant constraints if any.
 142 
 143    procedure Build_Derived_Enumeration_Type
 144      (N            : Node_Id;
 145       Parent_Type  : Entity_Id;
 146       Derived_Type : Entity_Id);
 147    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
 148    --  type, we must create a new list of literals. Types derived from
 149    --  Character and [Wide_]Wide_Character are special-cased.
 150 
 151    procedure Build_Derived_Numeric_Type
 152      (N            : Node_Id;
 153       Parent_Type  : Entity_Id;
 154       Derived_Type : Entity_Id);
 155    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
 156    --  an anonymous base type, and propagate constraint to subtype if needed.
 157 
 158    procedure Build_Derived_Private_Type
 159      (N             : Node_Id;
 160       Parent_Type   : Entity_Id;
 161       Derived_Type  : Entity_Id;
 162       Is_Completion : Boolean;
 163       Derive_Subps  : Boolean := True);
 164    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
 165    --  because the parent may or may not have a completion, and the derivation
 166    --  may itself be a completion.
 167 
 168    procedure Build_Derived_Record_Type
 169      (N            : Node_Id;
 170       Parent_Type  : Entity_Id;
 171       Derived_Type : Entity_Id;
 172       Derive_Subps : Boolean := True);
 173    --  Subsidiary procedure used for tagged and untagged record types
 174    --  by Build_Derived_Type and Analyze_Private_Extension_Declaration.
 175    --  All parameters are as in Build_Derived_Type except that N, in
 176    --  addition to being an N_Full_Type_Declaration node, can also be an
 177    --  N_Private_Extension_Declaration node. See the definition of this routine
 178    --  for much more info. Derive_Subps indicates whether subprograms should be
 179    --  derived from the parent type. The only case where Derive_Subps is False
 180    --  is for an implicit derived full type for a type derived from a private
 181    --  type (see Build_Derived_Type).
 182 
 183    procedure Build_Discriminal (Discrim : Entity_Id);
 184    --  Create the discriminal corresponding to discriminant Discrim, that is
 185    --  the parameter corresponding to Discrim to be used in initialization
 186    --  procedures for the type where Discrim is a discriminant. Discriminals
 187    --  are not used during semantic analysis, and are not fully defined
 188    --  entities until expansion. Thus they are not given a scope until
 189    --  initialization procedures are built.
 190 
 191    function Build_Discriminant_Constraints
 192      (T           : Entity_Id;
 193       Def         : Node_Id;
 194       Derived_Def : Boolean := False) return Elist_Id;
 195    --  Validate discriminant constraints and return the list of the constraints
 196    --  in order of discriminant declarations, where T is the discriminated
 197    --  unconstrained type. Def is the N_Subtype_Indication node where the
 198    --  discriminants constraints for T are specified. Derived_Def is True
 199    --  when building the discriminant constraints in a derived type definition
 200    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
 201    --  type and Def is the constraint "(xxx)" on T and this routine sets the
 202    --  Corresponding_Discriminant field of the discriminants in the derived
 203    --  type D to point to the corresponding discriminants in the parent type T.
 204 
 205    procedure Build_Discriminated_Subtype
 206      (T           : Entity_Id;
 207       Def_Id      : Entity_Id;
 208       Elist       : Elist_Id;
 209       Related_Nod : Node_Id;
 210       For_Access  : Boolean := False);
 211    --  Subsidiary procedure to Constrain_Discriminated_Type and to
 212    --  Process_Incomplete_Dependents. Given
 213    --
 214    --     T (a possibly discriminated base type)
 215    --     Def_Id (a very partially built subtype for T),
 216    --
 217    --  the call completes Def_Id to be the appropriate E_*_Subtype.
 218    --
 219    --  The Elist is the list of discriminant constraints if any (it is set
 220    --  to No_Elist if T is not a discriminated type, and to an empty list if
 221    --  T has discriminants but there are no discriminant constraints). The
 222    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
 223    --  The For_Access says whether or not this subtype is really constraining
 224    --  an access type. That is its sole purpose is the designated type of an
 225    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
 226    --  is built to avoid freezing T when the access subtype is frozen.
 227 
 228    function Build_Scalar_Bound
 229      (Bound : Node_Id;
 230       Par_T : Entity_Id;
 231       Der_T : Entity_Id) return Node_Id;
 232    --  The bounds of a derived scalar type are conversions of the bounds of
 233    --  the parent type. Optimize the representation if the bounds are literals.
 234    --  Needs a more complete spec--what are the parameters exactly, and what
 235    --  exactly is the returned value, and how is Bound affected???
 236 
 237    procedure Build_Underlying_Full_View
 238      (N   : Node_Id;
 239       Typ : Entity_Id;
 240       Par : Entity_Id);
 241    --  If the completion of a private type is itself derived from a private
 242    --  type, or if the full view of a private subtype is itself private, the
 243    --  back-end has no way to compute the actual size of this type. We build
 244    --  an internal subtype declaration of the proper parent type to convey
 245    --  this information. This extra mechanism is needed because a full
 246    --  view cannot itself have a full view (it would get clobbered during
 247    --  view exchanges).
 248 
 249    procedure Check_Access_Discriminant_Requires_Limited
 250      (D   : Node_Id;
 251       Loc : Node_Id);
 252    --  Check the restriction that the type to which an access discriminant
 253    --  belongs must be a concurrent type or a descendant of a type with
 254    --  the reserved word 'limited' in its declaration.
 255 
 256    procedure Check_Anonymous_Access_Components
 257       (Typ_Decl  : Node_Id;
 258        Typ       : Entity_Id;
 259        Prev      : Entity_Id;
 260        Comp_List : Node_Id);
 261    --  Ada 2005 AI-382: an access component in a record definition can refer to
 262    --  the enclosing record, in which case it denotes the type itself, and not
 263    --  the current instance of the type. We create an anonymous access type for
 264    --  the component, and flag it as an access to a component, so accessibility
 265    --  checks are properly performed on it. The declaration of the access type
 266    --  is placed ahead of that of the record to prevent order-of-elaboration
 267    --  circularity issues in Gigi. We create an incomplete type for the record
 268    --  declaration, which is the designated type of the anonymous access.
 269 
 270    procedure Check_Delta_Expression (E : Node_Id);
 271    --  Check that the expression represented by E is suitable for use as a
 272    --  delta expression, i.e. it is of real type and is static.
 273 
 274    procedure Check_Digits_Expression (E : Node_Id);
 275    --  Check that the expression represented by E is suitable for use as a
 276    --  digits expression, i.e. it is of integer type, positive and static.
 277 
 278    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
 279    --  Validate the initialization of an object declaration. T is the required
 280    --  type, and Exp is the initialization expression.
 281 
 282    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
 283    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
 284 
 285    procedure Check_Or_Process_Discriminants
 286      (N    : Node_Id;
 287       T    : Entity_Id;
 288       Prev : Entity_Id := Empty);
 289    --  If N is the full declaration of the completion T of an incomplete or
 290    --  private type, check its discriminants (which are already known to be
 291    --  conformant with those of the partial view, see Find_Type_Name),
 292    --  otherwise process them. Prev is the entity of the partial declaration,
 293    --  if any.
 294 
 295    procedure Check_Real_Bound (Bound : Node_Id);
 296    --  Check given bound for being of real type and static. If not, post an
 297    --  appropriate message, and rewrite the bound with the real literal zero.
 298 
 299    procedure Constant_Redeclaration
 300      (Id : Entity_Id;
 301       N  : Node_Id;
 302       T  : out Entity_Id);
 303    --  Various checks on legality of full declaration of deferred constant.
 304    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
 305    --  node. The caller has not yet set any attributes of this entity.
 306 
 307    function Contain_Interface
 308      (Iface  : Entity_Id;
 309       Ifaces : Elist_Id) return Boolean;
 310    --  Ada 2005: Determine whether Iface is present in the list Ifaces
 311 
 312    procedure Convert_Scalar_Bounds
 313      (N            : Node_Id;
 314       Parent_Type  : Entity_Id;
 315       Derived_Type : Entity_Id;
 316       Loc          : Source_Ptr);
 317    --  For derived scalar types, convert the bounds in the type definition to
 318    --  the derived type, and complete their analysis. Given a constraint of the
 319    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
 320    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
 321    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
 322    --  subtype are conversions of those bounds to the derived_type, so that
 323    --  their typing is consistent.
 324 
 325    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
 326    --  Copies attributes from array base type T2 to array base type T1. Copies
 327    --  only attributes that apply to base types, but not subtypes.
 328 
 329    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
 330    --  Copies attributes from array subtype T2 to array subtype T1. Copies
 331    --  attributes that apply to both subtypes and base types.
 332 
 333    procedure Create_Constrained_Components
 334      (Subt        : Entity_Id;
 335       Decl_Node   : Node_Id;
 336       Typ         : Entity_Id;
 337       Constraints : Elist_Id);
 338    --  Build the list of entities for a constrained discriminated record
 339    --  subtype. If a component depends on a discriminant, replace its subtype
 340    --  using the discriminant values in the discriminant constraint. Subt
 341    --  is the defining identifier for the subtype whose list of constrained
 342    --  entities we will create. Decl_Node is the type declaration node where
 343    --  we will attach all the itypes created. Typ is the base discriminated
 344    --  type for the subtype Subt. Constraints is the list of discriminant
 345    --  constraints for Typ.
 346 
 347    function Constrain_Component_Type
 348      (Comp            : Entity_Id;
 349       Constrained_Typ : Entity_Id;
 350       Related_Node    : Node_Id;
 351       Typ             : Entity_Id;
 352       Constraints     : Elist_Id) return Entity_Id;
 353    --  Given a discriminated base type Typ, a list of discriminant constraints,
 354    --  Constraints, for Typ and a component Comp of Typ, create and return the
 355    --  type corresponding to Etype (Comp) where all discriminant references
 356    --  are replaced with the corresponding constraint. If Etype (Comp) contains
 357    --  no discriminant references then it is returned as-is. Constrained_Typ
 358    --  is the final constrained subtype to which the constrained component
 359    --  belongs. Related_Node is the node where we attach all created itypes.
 360 
 361    procedure Constrain_Access
 362      (Def_Id      : in out Entity_Id;
 363       S           : Node_Id;
 364       Related_Nod : Node_Id);
 365    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
 366    --  an anonymous type created for a subtype indication. In that case it is
 367    --  created in the procedure and attached to Related_Nod.
 368 
 369    procedure Constrain_Array
 370      (Def_Id      : in out Entity_Id;
 371       SI          : Node_Id;
 372       Related_Nod : Node_Id;
 373       Related_Id  : Entity_Id;
 374       Suffix      : Character);
 375    --  Apply a list of index constraints to an unconstrained array type. The
 376    --  first parameter is the entity for the resulting subtype. A value of
 377    --  Empty for Def_Id indicates that an implicit type must be created, but
 378    --  creation is delayed (and must be done by this procedure) because other
 379    --  subsidiary implicit types must be created first (which is why Def_Id
 380    --  is an in/out parameter). The second parameter is a subtype indication
 381    --  node for the constrained array to be created (e.g. something of the
 382    --  form string (1 .. 10)). Related_Nod gives the place where this type
 383    --  has to be inserted in the tree. The Related_Id and Suffix parameters
 384    --  are used to build the associated Implicit type name.
 385 
 386    procedure Constrain_Concurrent
 387      (Def_Id      : in out Entity_Id;
 388       SI          : Node_Id;
 389       Related_Nod : Node_Id;
 390       Related_Id  : Entity_Id;
 391       Suffix      : Character);
 392    --  Apply list of discriminant constraints to an unconstrained concurrent
 393    --  type.
 394    --
 395    --    SI is the N_Subtype_Indication node containing the constraint and
 396    --    the unconstrained type to constrain.
 397    --
 398    --    Def_Id is the entity for the resulting constrained subtype. A value
 399    --    of Empty for Def_Id indicates that an implicit type must be created,
 400    --    but creation is delayed (and must be done by this procedure) because
 401    --    other subsidiary implicit types must be created first (which is why
 402    --    Def_Id is an in/out parameter).
 403    --
 404    --    Related_Nod gives the place where this type has to be inserted
 405    --    in the tree.
 406    --
 407    --  The last two arguments are used to create its external name if needed.
 408 
 409    function Constrain_Corresponding_Record
 410      (Prot_Subt   : Entity_Id;
 411       Corr_Rec    : Entity_Id;
 412       Related_Nod : Node_Id) return Entity_Id;
 413    --  When constraining a protected type or task type with discriminants,
 414    --  constrain the corresponding record with the same discriminant values.
 415 
 416    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
 417    --  Constrain a decimal fixed point type with a digits constraint and/or a
 418    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
 419 
 420    procedure Constrain_Discriminated_Type
 421      (Def_Id      : Entity_Id;
 422       S           : Node_Id;
 423       Related_Nod : Node_Id;
 424       For_Access  : Boolean := False);
 425    --  Process discriminant constraints of composite type. Verify that values
 426    --  have been provided for all discriminants, that the original type is
 427    --  unconstrained, and that the types of the supplied expressions match
 428    --  the discriminant types. The first three parameters are like in routine
 429    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
 430    --  of For_Access.
 431 
 432    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
 433    --  Constrain an enumeration type with a range constraint. This is identical
 434    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
 435 
 436    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
 437    --  Constrain a floating point type with either a digits constraint
 438    --  and/or a range constraint, building a E_Floating_Point_Subtype.
 439 
 440    procedure Constrain_Index
 441      (Index        : Node_Id;
 442       S            : Node_Id;
 443       Related_Nod  : Node_Id;
 444       Related_Id   : Entity_Id;
 445       Suffix       : Character;
 446       Suffix_Index : Nat);
 447    --  Process an index constraint S in a constrained array declaration. The
 448    --  constraint can be a subtype name, or a range with or without an explicit
 449    --  subtype mark. The index is the corresponding index of the unconstrained
 450    --  array. The Related_Id and Suffix parameters are used to build the
 451    --  associated Implicit type name.
 452 
 453    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
 454    --  Build subtype of a signed or modular integer type
 455 
 456    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
 457    --  Constrain an ordinary fixed point type with a range constraint, and
 458    --  build an E_Ordinary_Fixed_Point_Subtype entity.
 459 
 460    procedure Copy_And_Swap (Priv, Full : Entity_Id);
 461    --  Copy the Priv entity into the entity of its full declaration then swap
 462    --  the two entities in such a manner that the former private type is now
 463    --  seen as a full type.
 464 
 465    procedure Decimal_Fixed_Point_Type_Declaration
 466      (T   : Entity_Id;
 467       Def : Node_Id);
 468    --  Create a new decimal fixed point type, and apply the constraint to
 469    --  obtain a subtype of this new type.
 470 
 471    procedure Complete_Private_Subtype
 472      (Priv        : Entity_Id;
 473       Full        : Entity_Id;
 474       Full_Base   : Entity_Id;
 475       Related_Nod : Node_Id);
 476    --  Complete the implicit full view of a private subtype by setting the
 477    --  appropriate semantic fields. If the full view of the parent is a record
 478    --  type, build constrained components of subtype.
 479 
 480    procedure Derive_Progenitor_Subprograms
 481      (Parent_Type : Entity_Id;
 482       Tagged_Type : Entity_Id);
 483    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
 484    --  operations of progenitors of Tagged_Type, and replace the subsidiary
 485    --  subtypes with Tagged_Type, to build the specs of the inherited interface
 486    --  primitives. The derived primitives are aliased to those of the
 487    --  interface. This routine takes care also of transferring to the full view
 488    --  subprograms associated with the partial view of Tagged_Type that cover
 489    --  interface primitives.
 490 
 491    procedure Derived_Standard_Character
 492      (N             : Node_Id;
 493       Parent_Type   : Entity_Id;
 494       Derived_Type  : Entity_Id);
 495    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
 496    --  derivations from types Standard.Character and Standard.Wide_Character.
 497 
 498    procedure Derived_Type_Declaration
 499      (T             : Entity_Id;
 500       N             : Node_Id;
 501       Is_Completion : Boolean);
 502    --  Process a derived type declaration. Build_Derived_Type is invoked
 503    --  to process the actual derived type definition. Parameters N and
 504    --  Is_Completion have the same meaning as in Build_Derived_Type.
 505    --  T is the N_Defining_Identifier for the entity defined in the
 506    --  N_Full_Type_Declaration node N, that is T is the derived type.
 507 
 508    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
 509    --  Insert each literal in symbol table, as an overloadable identifier. Each
 510    --  enumeration type is mapped into a sequence of integers, and each literal
 511    --  is defined as a constant with integer value. If any of the literals are
 512    --  character literals, the type is a character type, which means that
 513    --  strings are legal aggregates for arrays of components of the type.
 514 
 515    function Expand_To_Stored_Constraint
 516      (Typ        : Entity_Id;
 517       Constraint : Elist_Id) return Elist_Id;
 518    --  Given a constraint (i.e. a list of expressions) on the discriminants of
 519    --  Typ, expand it into a constraint on the stored discriminants and return
 520    --  the new list of expressions constraining the stored discriminants.
 521 
 522    function Find_Type_Of_Object
 523      (Obj_Def     : Node_Id;
 524       Related_Nod : Node_Id) return Entity_Id;
 525    --  Get type entity for object referenced by Obj_Def, attaching the implicit
 526    --  types generated to Related_Nod.
 527 
 528    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
 529    --  Create a new float and apply the constraint to obtain subtype of it
 530 
 531    function Has_Range_Constraint (N : Node_Id) return Boolean;
 532    --  Given an N_Subtype_Indication node N, return True if a range constraint
 533    --  is present, either directly, or as part of a digits or delta constraint.
 534    --  In addition, a digits constraint in the decimal case returns True, since
 535    --  it establishes a default range if no explicit range is present.
 536 
 537    function Inherit_Components
 538      (N             : Node_Id;
 539       Parent_Base   : Entity_Id;
 540       Derived_Base  : Entity_Id;
 541       Is_Tagged     : Boolean;
 542       Inherit_Discr : Boolean;
 543       Discs         : Elist_Id) return Elist_Id;
 544    --  Called from Build_Derived_Record_Type to inherit the components of
 545    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
 546    --  For more information on derived types and component inheritance please
 547    --  consult the comment above the body of Build_Derived_Record_Type.
 548    --
 549    --    N is the original derived type declaration
 550    --
 551    --    Is_Tagged is set if we are dealing with tagged types
 552    --
 553    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
 554    --    Parent_Base, otherwise no discriminants are inherited.
 555    --
 556    --    Discs gives the list of constraints that apply to Parent_Base in the
 557    --    derived type declaration. If Discs is set to No_Elist, then we have
 558    --    the following situation:
 559    --
 560    --      type Parent (D1..Dn : ..) is [tagged] record ...;
 561    --      type Derived is new Parent [with ...];
 562    --
 563    --    which gets treated as
 564    --
 565    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
 566    --
 567    --  For untagged types the returned value is an association list. The list
 568    --  starts from the association (Parent_Base => Derived_Base), and then it
 569    --  contains a sequence of the associations of the form
 570    --
 571    --    (Old_Component => New_Component),
 572    --
 573    --  where Old_Component is the Entity_Id of a component in Parent_Base and
 574    --  New_Component is the Entity_Id of the corresponding component in
 575    --  Derived_Base. For untagged records, this association list is needed when
 576    --  copying the record declaration for the derived base. In the tagged case
 577    --  the value returned is irrelevant.
 578 
 579    procedure Inherit_Predicate_Flags (Subt, Par : Entity_Id);
 580    --  Propagate static and dynamic predicate flags from a parent to the
 581    --  subtype in a subtype declaration with and without constraints.
 582 
 583    function Is_EVF_Procedure (Subp : Entity_Id) return Boolean;
 584    --  Subsidiary to Check_Abstract_Overriding and Derive_Subprogram.
 585    --  Determine whether subprogram Subp is a procedure subject to pragma
 586    --  Extensions_Visible with value False and has at least one controlling
 587    --  parameter of mode OUT.
 588 
 589    function Is_Valid_Constraint_Kind
 590      (T_Kind          : Type_Kind;
 591       Constraint_Kind : Node_Kind) return Boolean;
 592    --  Returns True if it is legal to apply the given kind of constraint to the
 593    --  given kind of type (index constraint to an array type, for example).
 594 
 595    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
 596    --  Create new modular type. Verify that modulus is in bounds
 597 
 598    procedure New_Concatenation_Op (Typ : Entity_Id);
 599    --  Create an abbreviated declaration for an operator in order to
 600    --  materialize concatenation on array types.
 601 
 602    procedure Ordinary_Fixed_Point_Type_Declaration
 603      (T   : Entity_Id;
 604       Def : Node_Id);
 605    --  Create a new ordinary fixed point type, and apply the constraint to
 606    --  obtain subtype of it.
 607 
 608    procedure Prepare_Private_Subtype_Completion
 609      (Id          : Entity_Id;
 610       Related_Nod : Node_Id);
 611    --  Id is a subtype of some private type. Creates the full declaration
 612    --  associated with Id whenever possible, i.e. when the full declaration
 613    --  of the base type is already known. Records each subtype into
 614    --  Private_Dependents of the base type.
 615 
 616    procedure Process_Incomplete_Dependents
 617      (N      : Node_Id;
 618       Full_T : Entity_Id;
 619       Inc_T  : Entity_Id);
 620    --  Process all entities that depend on an incomplete type. There include
 621    --  subtypes, subprogram types that mention the incomplete type in their
 622    --  profiles, and subprogram with access parameters that designate the
 623    --  incomplete type.
 624 
 625    --  Inc_T is the defining identifier of an incomplete type declaration, its
 626    --  Ekind is E_Incomplete_Type.
 627    --
 628    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
 629    --
 630    --    Full_T is N's defining identifier.
 631    --
 632    --  Subtypes of incomplete types with discriminants are completed when the
 633    --  parent type is. This is simpler than private subtypes, because they can
 634    --  only appear in the same scope, and there is no need to exchange views.
 635    --  Similarly, access_to_subprogram types may have a parameter or a return
 636    --  type that is an incomplete type, and that must be replaced with the
 637    --  full type.
 638    --
 639    --  If the full type is tagged, subprogram with access parameters that
 640    --  designated the incomplete may be primitive operations of the full type,
 641    --  and have to be processed accordingly.
 642 
 643    procedure Process_Real_Range_Specification (Def : Node_Id);
 644    --  Given the type definition for a real type, this procedure processes and
 645    --  checks the real range specification of this type definition if one is
 646    --  present. If errors are found, error messages are posted, and the
 647    --  Real_Range_Specification of Def is reset to Empty.
 648 
 649    procedure Propagate_Default_Init_Cond_Attributes
 650      (From_Typ             : Entity_Id;
 651       To_Typ               : Entity_Id;
 652       Parent_To_Derivation : Boolean := False;
 653       Private_To_Full_View : Boolean := False);
 654    --  Subsidiary to routines Build_Derived_Type and Process_Full_View. Inherit
 655    --  all attributes related to pragma Default_Initial_Condition from From_Typ
 656    --  to To_Typ. Flag Parent_To_Derivation should be set when the context is
 657    --  the creation of a derived type. Flag Private_To_Full_View should be set
 658    --  when processing both views of a private type.
 659 
 660    procedure Record_Type_Declaration
 661      (T    : Entity_Id;
 662       N    : Node_Id;
 663       Prev : Entity_Id);
 664    --  Process a record type declaration (for both untagged and tagged
 665    --  records). Parameters T and N are exactly like in procedure
 666    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
 667    --  for this routine. If this is the completion of an incomplete type
 668    --  declaration, Prev is the entity of the incomplete declaration, used for
 669    --  cross-referencing. Otherwise Prev = T.
 670 
 671    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
 672    --  This routine is used to process the actual record type definition (both
 673    --  for untagged and tagged records). Def is a record type definition node.
 674    --  This procedure analyzes the components in this record type definition.
 675    --  Prev_T is the entity for the enclosing record type. It is provided so
 676    --  that its Has_Task flag can be set if any of the component have Has_Task
 677    --  set. If the declaration is the completion of an incomplete type
 678    --  declaration, Prev_T is the original incomplete type, whose full view is
 679    --  the record type.
 680 
 681    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
 682    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
 683    --  build a copy of the declaration tree of the parent, and we create
 684    --  independently the list of components for the derived type. Semantic
 685    --  information uses the component entities, but record representation
 686    --  clauses are validated on the declaration tree. This procedure replaces
 687    --  discriminants and components in the declaration with those that have
 688    --  been created by Inherit_Components.
 689 
 690    procedure Set_Fixed_Range
 691      (E   : Entity_Id;
 692       Loc : Source_Ptr;
 693       Lo  : Ureal;
 694       Hi  : Ureal);
 695    --  Build a range node with the given bounds and set it as the Scalar_Range
 696    --  of the given fixed-point type entity. Loc is the source location used
 697    --  for the constructed range. See body for further details.
 698 
 699    procedure Set_Scalar_Range_For_Subtype
 700      (Def_Id : Entity_Id;
 701       R      : Node_Id;
 702       Subt   : Entity_Id);
 703    --  This routine is used to set the scalar range field for a subtype given
 704    --  Def_Id, the entity for the subtype, and R, the range expression for the
 705    --  scalar range. Subt provides the parent subtype to be used to analyze,
 706    --  resolve, and check the given range.
 707 
 708    procedure Set_Default_SSO (T : Entity_Id);
 709    --  T is the entity for an array or record being declared. This procedure
 710    --  sets the flags SSO_Set_Low_By_Default/SSO_Set_High_By_Default according
 711    --  to the setting of Opt.Default_SSO.
 712 
 713    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
 714    --  Create a new signed integer entity, and apply the constraint to obtain
 715    --  the required first named subtype of this type.
 716 
 717    procedure Set_Stored_Constraint_From_Discriminant_Constraint
 718      (E : Entity_Id);
 719    --  E is some record type. This routine computes E's Stored_Constraint
 720    --  from its Discriminant_Constraint.
 721 
 722    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
 723    --  Check that an entity in a list of progenitors is an interface,
 724    --  emit error otherwise.
 725 
 726    -----------------------
 727    -- Access_Definition --
 728    -----------------------
 729 
 730    function Access_Definition
 731      (Related_Nod : Node_Id;
 732       N           : Node_Id) return Entity_Id
 733    is
 734       Anon_Type           : Entity_Id;
 735       Anon_Scope          : Entity_Id;
 736       Desig_Type          : Entity_Id;
 737       Enclosing_Prot_Type : Entity_Id := Empty;
 738 
 739    begin
 740       Check_SPARK_05_Restriction ("access type is not allowed", N);
 741 
 742       if Is_Entry (Current_Scope)
 743         and then Is_Task_Type (Etype (Scope (Current_Scope)))
 744       then
 745          Error_Msg_N ("task entries cannot have access parameters", N);
 746          return Empty;
 747       end if;
 748 
 749       --  Ada 2005: For an object declaration the corresponding anonymous
 750       --  type is declared in the current scope.
 751 
 752       --  If the access definition is the return type of another access to
 753       --  function, scope is the current one, because it is the one of the
 754       --  current type declaration, except for the pathological case below.
 755 
 756       if Nkind_In (Related_Nod, N_Object_Declaration,
 757                                 N_Access_Function_Definition)
 758       then
 759          Anon_Scope := Current_Scope;
 760 
 761          --  A pathological case: function returning access functions that
 762          --  return access functions, etc. Each anonymous access type created
 763          --  is in the enclosing scope of the outermost function.
 764 
 765          declare
 766             Par : Node_Id;
 767 
 768          begin
 769             Par := Related_Nod;
 770             while Nkind_In (Par, N_Access_Function_Definition,
 771                                  N_Access_Definition)
 772             loop
 773                Par := Parent (Par);
 774             end loop;
 775 
 776             if Nkind (Par) = N_Function_Specification then
 777                Anon_Scope := Scope (Defining_Entity (Par));
 778             end if;
 779          end;
 780 
 781       --  For the anonymous function result case, retrieve the scope of the
 782       --  function specification's associated entity rather than using the
 783       --  current scope. The current scope will be the function itself if the
 784       --  formal part is currently being analyzed, but will be the parent scope
 785       --  in the case of a parameterless function, and we always want to use
 786       --  the function's parent scope. Finally, if the function is a child
 787       --  unit, we must traverse the tree to retrieve the proper entity.
 788 
 789       elsif Nkind (Related_Nod) = N_Function_Specification
 790         and then Nkind (Parent (N)) /= N_Parameter_Specification
 791       then
 792          --  If the current scope is a protected type, the anonymous access
 793          --  is associated with one of the protected operations, and must
 794          --  be available in the scope that encloses the protected declaration.
 795          --  Otherwise the type is in the scope enclosing the subprogram.
 796 
 797          --  If the function has formals, The return type of a subprogram
 798          --  declaration is analyzed in the scope of the subprogram (see
 799          --  Process_Formals) and thus the protected type, if present, is
 800          --  the scope of the current function scope.
 801 
 802          if Ekind (Current_Scope) = E_Protected_Type then
 803             Enclosing_Prot_Type := Current_Scope;
 804 
 805          elsif Ekind (Current_Scope) = E_Function
 806            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
 807          then
 808             Enclosing_Prot_Type := Scope (Current_Scope);
 809          end if;
 810 
 811          if Present (Enclosing_Prot_Type) then
 812             Anon_Scope := Scope (Enclosing_Prot_Type);
 813 
 814          else
 815             Anon_Scope := Scope (Defining_Entity (Related_Nod));
 816          end if;
 817 
 818       --  For an access type definition, if the current scope is a child
 819       --  unit it is the scope of the type.
 820 
 821       elsif Is_Compilation_Unit (Current_Scope) then
 822          Anon_Scope := Current_Scope;
 823 
 824       --  For access formals, access components, and access discriminants, the
 825       --  scope is that of the enclosing declaration,
 826 
 827       else
 828          Anon_Scope := Scope (Current_Scope);
 829       end if;
 830 
 831       Anon_Type :=
 832         Create_Itype
 833           (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
 834 
 835       if All_Present (N)
 836         and then Ada_Version >= Ada_2005
 837       then
 838          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
 839       end if;
 840 
 841       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
 842       --  the corresponding semantic routine
 843 
 844       if Present (Access_To_Subprogram_Definition (N)) then
 845 
 846          --  Compiler runtime units are compiled in Ada 2005 mode when building
 847          --  the runtime library but must also be compilable in Ada 95 mode
 848          --  (when bootstrapping the compiler).
 849 
 850          Check_Compiler_Unit ("anonymous access to subprogram", N);
 851 
 852          Access_Subprogram_Declaration
 853            (T_Name => Anon_Type,
 854             T_Def  => Access_To_Subprogram_Definition (N));
 855 
 856          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
 857             Set_Ekind
 858               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
 859          else
 860             Set_Ekind (Anon_Type, E_Anonymous_Access_Subprogram_Type);
 861          end if;
 862 
 863          Set_Can_Use_Internal_Rep
 864            (Anon_Type, not Always_Compatible_Rep_On_Target);
 865 
 866          --  If the anonymous access is associated with a protected operation,
 867          --  create a reference to it after the enclosing protected definition
 868          --  because the itype will be used in the subsequent bodies.
 869 
 870          --  If the anonymous access itself is protected, a full type
 871          --  declaratiton will be created for it, so that the equivalent
 872          --  record type can be constructed. For further details, see
 873          --  Replace_Anonymous_Access_To_Protected-Subprogram.
 874 
 875          if Ekind (Current_Scope) = E_Protected_Type
 876            and then not Protected_Present (Access_To_Subprogram_Definition (N))
 877          then
 878             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
 879          end if;
 880 
 881          return Anon_Type;
 882       end if;
 883 
 884       Find_Type (Subtype_Mark (N));
 885       Desig_Type := Entity (Subtype_Mark (N));
 886 
 887       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
 888       Set_Etype (Anon_Type, Anon_Type);
 889 
 890       --  Make sure the anonymous access type has size and alignment fields
 891       --  set, as required by gigi. This is necessary in the case of the
 892       --  Task_Body_Procedure.
 893 
 894       if not Has_Private_Component (Desig_Type) then
 895          Layout_Type (Anon_Type);
 896       end if;
 897 
 898       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
 899       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
 900       --  the null value is allowed. In Ada 95 the null value is never allowed.
 901 
 902       if Ada_Version >= Ada_2005 then
 903          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
 904       else
 905          Set_Can_Never_Be_Null (Anon_Type, True);
 906       end if;
 907 
 908       --  The anonymous access type is as public as the discriminated type or
 909       --  subprogram that defines it. It is imported (for back-end purposes)
 910       --  if the designated type is.
 911 
 912       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
 913 
 914       --  Ada 2005 (AI-231): Propagate the access-constant attribute
 915 
 916       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
 917 
 918       --  The context is either a subprogram declaration, object declaration,
 919       --  or an access discriminant, in a private or a full type declaration.
 920       --  In the case of a subprogram, if the designated type is incomplete,
 921       --  the operation will be a primitive operation of the full type, to be
 922       --  updated subsequently. If the type is imported through a limited_with
 923       --  clause, the subprogram is not a primitive operation of the type
 924       --  (which is declared elsewhere in some other scope).
 925 
 926       if Ekind (Desig_Type) = E_Incomplete_Type
 927         and then not From_Limited_With (Desig_Type)
 928         and then Is_Overloadable (Current_Scope)
 929       then
 930          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
 931          Set_Has_Delayed_Freeze (Current_Scope);
 932       end if;
 933 
 934       --  Ada 2005: If the designated type is an interface that may contain
 935       --  tasks, create a Master entity for the declaration. This must be done
 936       --  before expansion of the full declaration, because the declaration may
 937       --  include an expression that is an allocator, whose expansion needs the
 938       --  proper Master for the created tasks.
 939 
 940       if Nkind (Related_Nod) = N_Object_Declaration and then Expander_Active
 941       then
 942          if Is_Interface (Desig_Type) and then Is_Limited_Record (Desig_Type)
 943          then
 944             Build_Class_Wide_Master (Anon_Type);
 945 
 946          --  Similarly, if the type is an anonymous access that designates
 947          --  tasks, create a master entity for it in the current context.
 948 
 949          elsif Has_Task (Desig_Type) and then Comes_From_Source (Related_Nod)
 950          then
 951             Build_Master_Entity (Defining_Identifier (Related_Nod));
 952             Build_Master_Renaming (Anon_Type);
 953          end if;
 954       end if;
 955 
 956       --  For a private component of a protected type, it is imperative that
 957       --  the back-end elaborate the type immediately after the protected
 958       --  declaration, because this type will be used in the declarations
 959       --  created for the component within each protected body, so we must
 960       --  create an itype reference for it now.
 961 
 962       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
 963          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
 964 
 965       --  Similarly, if the access definition is the return result of a
 966       --  function, create an itype reference for it because it will be used
 967       --  within the function body. For a regular function that is not a
 968       --  compilation unit, insert reference after the declaration. For a
 969       --  protected operation, insert it after the enclosing protected type
 970       --  declaration. In either case, do not create a reference for a type
 971       --  obtained through a limited_with clause, because this would introduce
 972       --  semantic dependencies.
 973 
 974       --  Similarly, do not create a reference if the designated type is a
 975       --  generic formal, because no use of it will reach the backend.
 976 
 977       elsif Nkind (Related_Nod) = N_Function_Specification
 978         and then not From_Limited_With (Desig_Type)
 979         and then not Is_Generic_Type (Desig_Type)
 980       then
 981          if Present (Enclosing_Prot_Type) then
 982             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
 983 
 984          elsif Is_List_Member (Parent (Related_Nod))
 985            and then Nkind (Parent (N)) /= N_Parameter_Specification
 986          then
 987             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
 988          end if;
 989 
 990       --  Finally, create an itype reference for an object declaration of an
 991       --  anonymous access type. This is strictly necessary only for deferred
 992       --  constants, but in any case will avoid out-of-scope problems in the
 993       --  back-end.
 994 
 995       elsif Nkind (Related_Nod) = N_Object_Declaration then
 996          Build_Itype_Reference (Anon_Type, Related_Nod);
 997       end if;
 998 
 999       return Anon_Type;
1000    end Access_Definition;
1001 
1002    -----------------------------------
1003    -- Access_Subprogram_Declaration --
1004    -----------------------------------
1005 
1006    procedure Access_Subprogram_Declaration
1007      (T_Name : Entity_Id;
1008       T_Def  : Node_Id)
1009    is
1010       procedure Check_For_Premature_Usage (Def : Node_Id);
1011       --  Check that type T_Name is not used, directly or recursively, as a
1012       --  parameter or a return type in Def. Def is either a subtype, an
1013       --  access_definition, or an access_to_subprogram_definition.
1014 
1015       -------------------------------
1016       -- Check_For_Premature_Usage --
1017       -------------------------------
1018 
1019       procedure Check_For_Premature_Usage (Def : Node_Id) is
1020          Param : Node_Id;
1021 
1022       begin
1023          --  Check for a subtype mark
1024 
1025          if Nkind (Def) in N_Has_Etype then
1026             if Etype (Def) = T_Name then
1027                Error_Msg_N
1028                  ("type& cannot be used before end of its declaration", Def);
1029             end if;
1030 
1031          --  If this is not a subtype, then this is an access_definition
1032 
1033          elsif Nkind (Def) = N_Access_Definition then
1034             if Present (Access_To_Subprogram_Definition (Def)) then
1035                Check_For_Premature_Usage
1036                  (Access_To_Subprogram_Definition (Def));
1037             else
1038                Check_For_Premature_Usage (Subtype_Mark (Def));
1039             end if;
1040 
1041          --  The only cases left are N_Access_Function_Definition and
1042          --  N_Access_Procedure_Definition.
1043 
1044          else
1045             if Present (Parameter_Specifications (Def)) then
1046                Param := First (Parameter_Specifications (Def));
1047                while Present (Param) loop
1048                   Check_For_Premature_Usage (Parameter_Type (Param));
1049                   Param := Next (Param);
1050                end loop;
1051             end if;
1052 
1053             if Nkind (Def) = N_Access_Function_Definition then
1054                Check_For_Premature_Usage (Result_Definition (Def));
1055             end if;
1056          end if;
1057       end Check_For_Premature_Usage;
1058 
1059       --  Local variables
1060 
1061       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1062       Formal     : Entity_Id;
1063       D_Ityp     : Node_Id;
1064       Desig_Type : constant Entity_Id :=
1065                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1066 
1067    --  Start of processing for Access_Subprogram_Declaration
1068 
1069    begin
1070       Check_SPARK_05_Restriction ("access type is not allowed", T_Def);
1071 
1072       --  Associate the Itype node with the inner full-type declaration or
1073       --  subprogram spec or entry body. This is required to handle nested
1074       --  anonymous declarations. For example:
1075 
1076       --      procedure P
1077       --       (X : access procedure
1078       --                     (Y : access procedure
1079       --                                   (Z : access T)))
1080 
1081       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1082       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1083                                    N_Private_Type_Declaration,
1084                                    N_Private_Extension_Declaration,
1085                                    N_Procedure_Specification,
1086                                    N_Function_Specification,
1087                                    N_Entry_Body)
1088 
1089                    or else
1090                  Nkind_In (D_Ityp, N_Object_Declaration,
1091                                    N_Object_Renaming_Declaration,
1092                                    N_Formal_Object_Declaration,
1093                                    N_Formal_Type_Declaration,
1094                                    N_Task_Type_Declaration,
1095                                    N_Protected_Type_Declaration))
1096       loop
1097          D_Ityp := Parent (D_Ityp);
1098          pragma Assert (D_Ityp /= Empty);
1099       end loop;
1100 
1101       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1102 
1103       if Nkind_In (D_Ityp, N_Procedure_Specification,
1104                            N_Function_Specification)
1105       then
1106          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1107 
1108       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1109                               N_Object_Declaration,
1110                               N_Object_Renaming_Declaration,
1111                               N_Formal_Type_Declaration)
1112       then
1113          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1114       end if;
1115 
1116       if Nkind (T_Def) = N_Access_Function_Definition then
1117          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1118             declare
1119                Acc : constant Node_Id := Result_Definition (T_Def);
1120 
1121             begin
1122                if Present (Access_To_Subprogram_Definition (Acc))
1123                  and then
1124                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1125                then
1126                   Set_Etype
1127                     (Desig_Type,
1128                        Replace_Anonymous_Access_To_Protected_Subprogram
1129                          (T_Def));
1130 
1131                else
1132                   Set_Etype
1133                     (Desig_Type,
1134                        Access_Definition (T_Def, Result_Definition (T_Def)));
1135                end if;
1136             end;
1137 
1138          else
1139             Analyze (Result_Definition (T_Def));
1140 
1141             declare
1142                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1143 
1144             begin
1145                --  If a null exclusion is imposed on the result type, then
1146                --  create a null-excluding itype (an access subtype) and use
1147                --  it as the function's Etype.
1148 
1149                if Is_Access_Type (Typ)
1150                  and then Null_Exclusion_In_Return_Present (T_Def)
1151                then
1152                   Set_Etype (Desig_Type,
1153                     Create_Null_Excluding_Itype
1154                       (T           => Typ,
1155                        Related_Nod => T_Def,
1156                        Scope_Id    => Current_Scope));
1157 
1158                else
1159                   if From_Limited_With (Typ) then
1160 
1161                      --  AI05-151: Incomplete types are allowed in all basic
1162                      --  declarations, including access to subprograms.
1163 
1164                      if Ada_Version >= Ada_2012 then
1165                         null;
1166 
1167                      else
1168                         Error_Msg_NE
1169                          ("illegal use of incomplete type&",
1170                           Result_Definition (T_Def), Typ);
1171                      end if;
1172 
1173                   elsif Ekind (Current_Scope) = E_Package
1174                     and then In_Private_Part (Current_Scope)
1175                   then
1176                      if Ekind (Typ) = E_Incomplete_Type then
1177                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1178 
1179                      elsif Is_Class_Wide_Type (Typ)
1180                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1181                      then
1182                         Append_Elmt
1183                           (Desig_Type, Private_Dependents (Etype (Typ)));
1184                      end if;
1185                   end if;
1186 
1187                   Set_Etype (Desig_Type, Typ);
1188                end if;
1189             end;
1190          end if;
1191 
1192          if not (Is_Type (Etype (Desig_Type))) then
1193             Error_Msg_N
1194               ("expect type in function specification",
1195                Result_Definition (T_Def));
1196          end if;
1197 
1198       else
1199          Set_Etype (Desig_Type, Standard_Void_Type);
1200       end if;
1201 
1202       if Present (Formals) then
1203          Push_Scope (Desig_Type);
1204 
1205          --  Some special tests here. These special tests can be removed
1206          --  if and when Itypes always have proper parent pointers to their
1207          --  declarations???
1208 
1209          --  Special test 1) Link defining_identifier of formals. Required by
1210          --  First_Formal to provide its functionality.
1211 
1212          declare
1213             F : Node_Id;
1214 
1215          begin
1216             F := First (Formals);
1217 
1218             --  In ASIS mode, the access_to_subprogram may be analyzed twice,
1219             --  when it is part of an unconstrained type and subtype expansion
1220             --  is disabled. To avoid back-end problems with shared profiles,
1221             --  use previous subprogram type as the designated type, and then
1222             --  remove scope added above.
1223 
1224             if ASIS_Mode and then Present (Scope (Defining_Identifier (F)))
1225             then
1226                Set_Etype                    (T_Name, T_Name);
1227                Init_Size_Align              (T_Name);
1228                Set_Directly_Designated_Type (T_Name,
1229                  Scope (Defining_Identifier (F)));
1230                End_Scope;
1231                return;
1232             end if;
1233 
1234             while Present (F) loop
1235                if No (Parent (Defining_Identifier (F))) then
1236                   Set_Parent (Defining_Identifier (F), F);
1237                end if;
1238 
1239                Next (F);
1240             end loop;
1241          end;
1242 
1243          Process_Formals (Formals, Parent (T_Def));
1244 
1245          --  Special test 2) End_Scope requires that the parent pointer be set
1246          --  to something reasonable, but Itypes don't have parent pointers. So
1247          --  we set it and then unset it ???
1248 
1249          Set_Parent (Desig_Type, T_Name);
1250          End_Scope;
1251          Set_Parent (Desig_Type, Empty);
1252       end if;
1253 
1254       --  Check for premature usage of the type being defined
1255 
1256       Check_For_Premature_Usage (T_Def);
1257 
1258       --  The return type and/or any parameter type may be incomplete. Mark the
1259       --  subprogram_type as depending on the incomplete type, so that it can
1260       --  be updated when the full type declaration is seen. This only applies
1261       --  to incomplete types declared in some enclosing scope, not to limited
1262       --  views from other packages.
1263 
1264       --  Prior to Ada 2012, access to functions can only have in_parameters.
1265 
1266       if Present (Formals) then
1267          Formal := First_Formal (Desig_Type);
1268          while Present (Formal) loop
1269             if Ekind (Formal) /= E_In_Parameter
1270               and then Nkind (T_Def) = N_Access_Function_Definition
1271               and then Ada_Version < Ada_2012
1272             then
1273                Error_Msg_N ("functions can only have IN parameters", Formal);
1274             end if;
1275 
1276             if Ekind (Etype (Formal)) = E_Incomplete_Type
1277               and then In_Open_Scopes (Scope (Etype (Formal)))
1278             then
1279                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1280                Set_Has_Delayed_Freeze (Desig_Type);
1281             end if;
1282 
1283             Next_Formal (Formal);
1284          end loop;
1285       end if;
1286 
1287       --  Check whether an indirect call without actuals may be possible. This
1288       --  is used when resolving calls whose result is then indexed.
1289 
1290       May_Need_Actuals (Desig_Type);
1291 
1292       --  If the return type is incomplete, this is legal as long as the type
1293       --  is declared in the current scope and will be completed in it (rather
1294       --  than being part of limited view).
1295 
1296       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1297         and then not Has_Delayed_Freeze (Desig_Type)
1298         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1299       then
1300          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1301          Set_Has_Delayed_Freeze (Desig_Type);
1302       end if;
1303 
1304       Check_Delayed_Subprogram (Desig_Type);
1305 
1306       if Protected_Present (T_Def) then
1307          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1308          Set_Convention (Desig_Type, Convention_Protected);
1309       else
1310          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1311       end if;
1312 
1313       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1314 
1315       Set_Etype                    (T_Name, T_Name);
1316       Init_Size_Align              (T_Name);
1317       Set_Directly_Designated_Type (T_Name, Desig_Type);
1318 
1319       Generate_Reference_To_Formals (T_Name);
1320 
1321       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1322 
1323       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1324 
1325       Check_Restriction (No_Access_Subprograms, T_Def);
1326    end Access_Subprogram_Declaration;
1327 
1328    ----------------------------
1329    -- Access_Type_Declaration --
1330    ----------------------------
1331 
1332    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1333       P : constant Node_Id := Parent (Def);
1334       S : constant Node_Id := Subtype_Indication (Def);
1335 
1336       Full_Desig : Entity_Id;
1337 
1338    begin
1339       Check_SPARK_05_Restriction ("access type is not allowed", Def);
1340 
1341       --  Check for permissible use of incomplete type
1342 
1343       if Nkind (S) /= N_Subtype_Indication then
1344          Analyze (S);
1345 
1346          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1347             Set_Directly_Designated_Type (T, Entity (S));
1348 
1349             --  If the designated type is a limited view, we cannot tell if
1350             --  the full view contains tasks, and there is no way to handle
1351             --  that full view in a client. We create a master entity for the
1352             --  scope, which will be used when a client determines that one
1353             --  is needed.
1354 
1355             if From_Limited_With (Entity (S))
1356               and then not Is_Class_Wide_Type (Entity (S))
1357             then
1358                Set_Ekind (T, E_Access_Type);
1359                Build_Master_Entity (T);
1360                Build_Master_Renaming (T);
1361             end if;
1362 
1363          else
1364             Set_Directly_Designated_Type (T, Process_Subtype (S, P, T, 'P'));
1365          end if;
1366 
1367          --  If the access definition is of the form: ACCESS NOT NULL ..
1368          --  the subtype indication must be of an access type. Create
1369          --  a null-excluding subtype of it.
1370 
1371          if Null_Excluding_Subtype (Def) then
1372             if not Is_Access_Type (Entity (S)) then
1373                Error_Msg_N ("null exclusion must apply to access type", Def);
1374 
1375             else
1376                declare
1377                   Loc  : constant Source_Ptr := Sloc (S);
1378                   Decl : Node_Id;
1379                   Nam  : constant Entity_Id := Make_Temporary (Loc, 'S');
1380 
1381                begin
1382                   Decl :=
1383                     Make_Subtype_Declaration (Loc,
1384                       Defining_Identifier => Nam,
1385                       Subtype_Indication  =>
1386                         New_Occurrence_Of (Entity (S), Loc));
1387                   Set_Null_Exclusion_Present (Decl);
1388                   Insert_Before (Parent (Def), Decl);
1389                   Analyze (Decl);
1390                   Set_Entity (S, Nam);
1391                end;
1392             end if;
1393          end if;
1394 
1395       else
1396          Set_Directly_Designated_Type (T,
1397            Process_Subtype (S, P, T, 'P'));
1398       end if;
1399 
1400       if All_Present (Def) or Constant_Present (Def) then
1401          Set_Ekind (T, E_General_Access_Type);
1402       else
1403          Set_Ekind (T, E_Access_Type);
1404       end if;
1405 
1406       Full_Desig := Designated_Type (T);
1407 
1408       if Base_Type (Full_Desig) = T then
1409          Error_Msg_N ("access type cannot designate itself", S);
1410 
1411       --  In Ada 2005, the type may have a limited view through some unit in
1412       --  its own context, allowing the following circularity that cannot be
1413       --  detected earlier.
1414 
1415       elsif Is_Class_Wide_Type (Full_Desig) and then Etype (Full_Desig) = T
1416       then
1417          Error_Msg_N
1418            ("access type cannot designate its own classwide type", S);
1419 
1420          --  Clean up indication of tagged status to prevent cascaded errors
1421 
1422          Set_Is_Tagged_Type (T, False);
1423       end if;
1424 
1425       Set_Etype (T, T);
1426 
1427       --  If the type has appeared already in a with_type clause, it is frozen
1428       --  and the pointer size is already set. Else, initialize.
1429 
1430       if not From_Limited_With (T) then
1431          Init_Size_Align (T);
1432       end if;
1433 
1434       --  Note that Has_Task is always false, since the access type itself
1435       --  is not a task type. See Einfo for more description on this point.
1436       --  Exactly the same consideration applies to Has_Controlled_Component
1437       --  and to Has_Protected.
1438 
1439       Set_Has_Task                 (T, False);
1440       Set_Has_Protected            (T, False);
1441       Set_Has_Timing_Event         (T, False);
1442       Set_Has_Controlled_Component (T, False);
1443 
1444       --  Initialize field Finalization_Master explicitly to Empty, to avoid
1445       --  problems where an incomplete view of this entity has been previously
1446       --  established by a limited with and an overlaid version of this field
1447       --  (Stored_Constraint) was initialized for the incomplete view.
1448 
1449       --  This reset is performed in most cases except where the access type
1450       --  has been created for the purposes of allocating or deallocating a
1451       --  build-in-place object. Such access types have explicitly set pools
1452       --  and finalization masters.
1453 
1454       if No (Associated_Storage_Pool (T)) then
1455          Set_Finalization_Master (T, Empty);
1456       end if;
1457 
1458       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1459       --  attributes
1460 
1461       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1462       Set_Is_Access_Constant (T, Constant_Present (Def));
1463    end Access_Type_Declaration;
1464 
1465    ----------------------------------
1466    -- Add_Interface_Tag_Components --
1467    ----------------------------------
1468 
1469    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1470       Loc      : constant Source_Ptr := Sloc (N);
1471       L        : List_Id;
1472       Last_Tag : Node_Id;
1473 
1474       procedure Add_Tag (Iface : Entity_Id);
1475       --  Add tag for one of the progenitor interfaces
1476 
1477       -------------
1478       -- Add_Tag --
1479       -------------
1480 
1481       procedure Add_Tag (Iface : Entity_Id) is
1482          Decl   : Node_Id;
1483          Def    : Node_Id;
1484          Tag    : Entity_Id;
1485          Offset : Entity_Id;
1486 
1487       begin
1488          pragma Assert (Is_Tagged_Type (Iface) and then Is_Interface (Iface));
1489 
1490          --  This is a reasonable place to propagate predicates
1491 
1492          if Has_Predicates (Iface) then
1493             Set_Has_Predicates (Typ);
1494          end if;
1495 
1496          Def :=
1497            Make_Component_Definition (Loc,
1498              Aliased_Present    => True,
1499              Subtype_Indication =>
1500                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1501 
1502          Tag := Make_Temporary (Loc, 'V');
1503 
1504          Decl :=
1505            Make_Component_Declaration (Loc,
1506              Defining_Identifier  => Tag,
1507              Component_Definition => Def);
1508 
1509          Analyze_Component_Declaration (Decl);
1510 
1511          Set_Analyzed (Decl);
1512          Set_Ekind               (Tag, E_Component);
1513          Set_Is_Tag              (Tag);
1514          Set_Is_Aliased          (Tag);
1515          Set_Related_Type        (Tag, Iface);
1516          Init_Component_Location (Tag);
1517 
1518          pragma Assert (Is_Frozen (Iface));
1519 
1520          Set_DT_Entry_Count    (Tag,
1521            DT_Entry_Count (First_Entity (Iface)));
1522 
1523          if No (Last_Tag) then
1524             Prepend (Decl, L);
1525          else
1526             Insert_After (Last_Tag, Decl);
1527          end if;
1528 
1529          Last_Tag := Decl;
1530 
1531          --  If the ancestor has discriminants we need to give special support
1532          --  to store the offset_to_top value of the secondary dispatch tables.
1533          --  For this purpose we add a supplementary component just after the
1534          --  field that contains the tag associated with each secondary DT.
1535 
1536          if Typ /= Etype (Typ) and then Has_Discriminants (Etype (Typ)) then
1537             Def :=
1538               Make_Component_Definition (Loc,
1539                 Subtype_Indication =>
1540                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1541 
1542             Offset := Make_Temporary (Loc, 'V');
1543 
1544             Decl :=
1545               Make_Component_Declaration (Loc,
1546                 Defining_Identifier  => Offset,
1547                 Component_Definition => Def);
1548 
1549             Analyze_Component_Declaration (Decl);
1550 
1551             Set_Analyzed (Decl);
1552             Set_Ekind               (Offset, E_Component);
1553             Set_Is_Aliased          (Offset);
1554             Set_Related_Type        (Offset, Iface);
1555             Init_Component_Location (Offset);
1556             Insert_After (Last_Tag, Decl);
1557             Last_Tag := Decl;
1558          end if;
1559       end Add_Tag;
1560 
1561       --  Local variables
1562 
1563       Elmt : Elmt_Id;
1564       Ext  : Node_Id;
1565       Comp : Node_Id;
1566 
1567    --  Start of processing for Add_Interface_Tag_Components
1568 
1569    begin
1570       if not RTE_Available (RE_Interface_Tag) then
1571          Error_Msg
1572            ("(Ada 2005) interface types not supported by this run-time!",
1573             Sloc (N));
1574          return;
1575       end if;
1576 
1577       if Ekind (Typ) /= E_Record_Type
1578         or else (Is_Concurrent_Record_Type (Typ)
1579                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1580         or else (not Is_Concurrent_Record_Type (Typ)
1581                   and then No (Interfaces (Typ))
1582                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1583       then
1584          return;
1585       end if;
1586 
1587       --  Find the current last tag
1588 
1589       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1590          Ext := Record_Extension_Part (Type_Definition (N));
1591       else
1592          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1593          Ext := Type_Definition (N);
1594       end if;
1595 
1596       Last_Tag := Empty;
1597 
1598       if not (Present (Component_List (Ext))) then
1599          Set_Null_Present (Ext, False);
1600          L := New_List;
1601          Set_Component_List (Ext,
1602            Make_Component_List (Loc,
1603              Component_Items => L,
1604              Null_Present => False));
1605       else
1606          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1607             L := Component_Items
1608                    (Component_List
1609                      (Record_Extension_Part
1610                        (Type_Definition (N))));
1611          else
1612             L := Component_Items
1613                    (Component_List
1614                      (Type_Definition (N)));
1615          end if;
1616 
1617          --  Find the last tag component
1618 
1619          Comp := First (L);
1620          while Present (Comp) loop
1621             if Nkind (Comp) = N_Component_Declaration
1622               and then Is_Tag (Defining_Identifier (Comp))
1623             then
1624                Last_Tag := Comp;
1625             end if;
1626 
1627             Next (Comp);
1628          end loop;
1629       end if;
1630 
1631       --  At this point L references the list of components and Last_Tag
1632       --  references the current last tag (if any). Now we add the tag
1633       --  corresponding with all the interfaces that are not implemented
1634       --  by the parent.
1635 
1636       if Present (Interfaces (Typ)) then
1637          Elmt := First_Elmt (Interfaces (Typ));
1638          while Present (Elmt) loop
1639             Add_Tag (Node (Elmt));
1640             Next_Elmt (Elmt);
1641          end loop;
1642       end if;
1643    end Add_Interface_Tag_Components;
1644 
1645    -------------------------------------
1646    -- Add_Internal_Interface_Entities --
1647    -------------------------------------
1648 
1649    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1650       Elmt          : Elmt_Id;
1651       Iface         : Entity_Id;
1652       Iface_Elmt    : Elmt_Id;
1653       Iface_Prim    : Entity_Id;
1654       Ifaces_List   : Elist_Id;
1655       New_Subp      : Entity_Id := Empty;
1656       Prim          : Entity_Id;
1657       Restore_Scope : Boolean := False;
1658 
1659    begin
1660       pragma Assert (Ada_Version >= Ada_2005
1661         and then Is_Record_Type (Tagged_Type)
1662         and then Is_Tagged_Type (Tagged_Type)
1663         and then Has_Interfaces (Tagged_Type)
1664         and then not Is_Interface (Tagged_Type));
1665 
1666       --  Ensure that the internal entities are added to the scope of the type
1667 
1668       if Scope (Tagged_Type) /= Current_Scope then
1669          Push_Scope (Scope (Tagged_Type));
1670          Restore_Scope := True;
1671       end if;
1672 
1673       Collect_Interfaces (Tagged_Type, Ifaces_List);
1674 
1675       Iface_Elmt := First_Elmt (Ifaces_List);
1676       while Present (Iface_Elmt) loop
1677          Iface := Node (Iface_Elmt);
1678 
1679          --  Originally we excluded here from this processing interfaces that
1680          --  are parents of Tagged_Type because their primitives are located
1681          --  in the primary dispatch table (and hence no auxiliary internal
1682          --  entities are required to handle secondary dispatch tables in such
1683          --  case). However, these auxiliary entities are also required to
1684          --  handle derivations of interfaces in formals of generics (see
1685          --  Derive_Subprograms).
1686 
1687          Elmt := First_Elmt (Primitive_Operations (Iface));
1688          while Present (Elmt) loop
1689             Iface_Prim := Node (Elmt);
1690 
1691             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1692                Prim :=
1693                  Find_Primitive_Covering_Interface
1694                    (Tagged_Type => Tagged_Type,
1695                     Iface_Prim  => Iface_Prim);
1696 
1697                if No (Prim) and then Serious_Errors_Detected > 0 then
1698                   goto Continue;
1699                end if;
1700 
1701                pragma Assert (Present (Prim));
1702 
1703                --  Ada 2012 (AI05-0197): If the name of the covering primitive
1704                --  differs from the name of the interface primitive then it is
1705                --  a private primitive inherited from a parent type. In such
1706                --  case, given that Tagged_Type covers the interface, the
1707                --  inherited private primitive becomes visible. For such
1708                --  purpose we add a new entity that renames the inherited
1709                --  private primitive.
1710 
1711                if Chars (Prim) /= Chars (Iface_Prim) then
1712                   pragma Assert (Has_Suffix (Prim, 'P'));
1713                   Derive_Subprogram
1714                     (New_Subp     => New_Subp,
1715                      Parent_Subp  => Iface_Prim,
1716                      Derived_Type => Tagged_Type,
1717                      Parent_Type  => Iface);
1718                   Set_Alias (New_Subp, Prim);
1719                   Set_Is_Abstract_Subprogram
1720                     (New_Subp, Is_Abstract_Subprogram (Prim));
1721                end if;
1722 
1723                Derive_Subprogram
1724                  (New_Subp     => New_Subp,
1725                   Parent_Subp  => Iface_Prim,
1726                   Derived_Type => Tagged_Type,
1727                   Parent_Type  => Iface);
1728 
1729                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1730                --  associated with interface types. These entities are
1731                --  only registered in the list of primitives of its
1732                --  corresponding tagged type because they are only used
1733                --  to fill the contents of the secondary dispatch tables.
1734                --  Therefore they are removed from the homonym chains.
1735 
1736                Set_Is_Hidden (New_Subp);
1737                Set_Is_Internal (New_Subp);
1738                Set_Alias (New_Subp, Prim);
1739                Set_Is_Abstract_Subprogram
1740                  (New_Subp, Is_Abstract_Subprogram (Prim));
1741                Set_Interface_Alias (New_Subp, Iface_Prim);
1742 
1743                --  If the returned type is an interface then propagate it to
1744                --  the returned type. Needed by the thunk to generate the code
1745                --  which displaces "this" to reference the corresponding
1746                --  secondary dispatch table in the returned object.
1747 
1748                if Is_Interface (Etype (Iface_Prim)) then
1749                   Set_Etype (New_Subp, Etype (Iface_Prim));
1750                end if;
1751 
1752                --  Internal entities associated with interface types are only
1753                --  registered in the list of primitives of the tagged type.
1754                --  They are only used to fill the contents of the secondary
1755                --  dispatch tables. Therefore they are not needed in the
1756                --  homonym chains.
1757 
1758                Remove_Homonym (New_Subp);
1759 
1760                --  Hidden entities associated with interfaces must have set
1761                --  the Has_Delay_Freeze attribute to ensure that, in case
1762                --  of locally defined tagged types (or compiling with static
1763                --  dispatch tables generation disabled) the corresponding
1764                --  entry of the secondary dispatch table is filled when such
1765                --  an entity is frozen. This is an expansion activity that must
1766                --  be suppressed for ASIS because it leads to gigi elaboration
1767                --  issues in annotate mode.
1768 
1769                if not ASIS_Mode then
1770                   Set_Has_Delayed_Freeze (New_Subp);
1771                end if;
1772             end if;
1773 
1774             <<Continue>>
1775             Next_Elmt (Elmt);
1776          end loop;
1777 
1778          Next_Elmt (Iface_Elmt);
1779       end loop;
1780 
1781       if Restore_Scope then
1782          Pop_Scope;
1783       end if;
1784    end Add_Internal_Interface_Entities;
1785 
1786    -----------------------------------
1787    -- Analyze_Component_Declaration --
1788    -----------------------------------
1789 
1790    procedure Analyze_Component_Declaration (N : Node_Id) is
1791       Loc : constant Source_Ptr := Sloc (Component_Definition (N));
1792       Id  : constant Entity_Id  := Defining_Identifier (N);
1793       E   : constant Node_Id    := Expression (N);
1794       Typ : constant Node_Id    :=
1795               Subtype_Indication (Component_Definition (N));
1796       T   : Entity_Id;
1797       P   : Entity_Id;
1798 
1799       function Contains_POC (Constr : Node_Id) return Boolean;
1800       --  Determines whether a constraint uses the discriminant of a record
1801       --  type thus becoming a per-object constraint (POC).
1802 
1803       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1804       --  Typ is the type of the current component, check whether this type is
1805       --  a limited type. Used to validate declaration against that of
1806       --  enclosing record.
1807 
1808       ------------------
1809       -- Contains_POC --
1810       ------------------
1811 
1812       function Contains_POC (Constr : Node_Id) return Boolean is
1813       begin
1814          --  Prevent cascaded errors
1815 
1816          if Error_Posted (Constr) then
1817             return False;
1818          end if;
1819 
1820          case Nkind (Constr) is
1821             when N_Attribute_Reference =>
1822                return Attribute_Name (Constr) = Name_Access
1823                  and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1824 
1825             when N_Discriminant_Association =>
1826                return Denotes_Discriminant (Expression (Constr));
1827 
1828             when N_Identifier =>
1829                return Denotes_Discriminant (Constr);
1830 
1831             when N_Index_Or_Discriminant_Constraint =>
1832                declare
1833                   IDC : Node_Id;
1834 
1835                begin
1836                   IDC := First (Constraints (Constr));
1837                   while Present (IDC) loop
1838 
1839                      --  One per-object constraint is sufficient
1840 
1841                      if Contains_POC (IDC) then
1842                         return True;
1843                      end if;
1844 
1845                      Next (IDC);
1846                   end loop;
1847 
1848                   return False;
1849                end;
1850 
1851             when N_Range =>
1852                return Denotes_Discriminant (Low_Bound (Constr))
1853                         or else
1854                       Denotes_Discriminant (High_Bound (Constr));
1855 
1856             when N_Range_Constraint =>
1857                return Denotes_Discriminant (Range_Expression (Constr));
1858 
1859             when others =>
1860                return False;
1861 
1862          end case;
1863       end Contains_POC;
1864 
1865       ----------------------
1866       -- Is_Known_Limited --
1867       ----------------------
1868 
1869       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1870          P : constant Entity_Id := Etype (Typ);
1871          R : constant Entity_Id := Root_Type (Typ);
1872 
1873       begin
1874          if Is_Limited_Record (Typ) then
1875             return True;
1876 
1877          --  If the root type is limited (and not a limited interface)
1878          --  so is the current type
1879 
1880          elsif Is_Limited_Record (R)
1881            and then (not Is_Interface (R) or else not Is_Limited_Interface (R))
1882          then
1883             return True;
1884 
1885          --  Else the type may have a limited interface progenitor, but a
1886          --  limited record parent.
1887 
1888          elsif R /= P and then Is_Limited_Record (P) then
1889             return True;
1890 
1891          else
1892             return False;
1893          end if;
1894       end Is_Known_Limited;
1895 
1896    --  Start of processing for Analyze_Component_Declaration
1897 
1898    begin
1899       Generate_Definition (Id);
1900       Enter_Name (Id);
1901 
1902       if Present (Typ) then
1903          T := Find_Type_Of_Object
1904                 (Subtype_Indication (Component_Definition (N)), N);
1905 
1906          if not Nkind_In (Typ, N_Identifier, N_Expanded_Name) then
1907             Check_SPARK_05_Restriction ("subtype mark required", Typ);
1908          end if;
1909 
1910       --  Ada 2005 (AI-230): Access Definition case
1911 
1912       else
1913          pragma Assert (Present
1914                           (Access_Definition (Component_Definition (N))));
1915 
1916          T := Access_Definition
1917                 (Related_Nod => N,
1918                  N => Access_Definition (Component_Definition (N)));
1919          Set_Is_Local_Anonymous_Access (T);
1920 
1921          --  Ada 2005 (AI-254)
1922 
1923          if Present (Access_To_Subprogram_Definition
1924                       (Access_Definition (Component_Definition (N))))
1925            and then Protected_Present (Access_To_Subprogram_Definition
1926                                         (Access_Definition
1927                                           (Component_Definition (N))))
1928          then
1929             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1930          end if;
1931       end if;
1932 
1933       --  If the subtype is a constrained subtype of the enclosing record,
1934       --  (which must have a partial view) the back-end does not properly
1935       --  handle the recursion. Rewrite the component declaration with an
1936       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1937       --  the tree directly because side effects have already been removed from
1938       --  discriminant constraints.
1939 
1940       if Ekind (T) = E_Access_Subtype
1941         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1942         and then Comes_From_Source (T)
1943         and then Nkind (Parent (T)) = N_Subtype_Declaration
1944         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1945       then
1946          Rewrite
1947            (Subtype_Indication (Component_Definition (N)),
1948              New_Copy_Tree (Subtype_Indication (Parent (T))));
1949          T := Find_Type_Of_Object
1950                  (Subtype_Indication (Component_Definition (N)), N);
1951       end if;
1952 
1953       --  If the component declaration includes a default expression, then we
1954       --  check that the component is not of a limited type (RM 3.7(5)),
1955       --  and do the special preanalysis of the expression (see section on
1956       --  "Handling of Default and Per-Object Expressions" in the spec of
1957       --  package Sem).
1958 
1959       if Present (E) then
1960          Check_SPARK_05_Restriction ("default expression is not allowed", E);
1961          Preanalyze_Default_Expression (E, T);
1962          Check_Initialization (T, E);
1963 
1964          if Ada_Version >= Ada_2005
1965            and then Ekind (T) = E_Anonymous_Access_Type
1966            and then Etype (E) /= Any_Type
1967          then
1968             --  Check RM 3.9.2(9): "if the expected type for an expression is
1969             --  an anonymous access-to-specific tagged type, then the object
1970             --  designated by the expression shall not be dynamically tagged
1971             --  unless it is a controlling operand in a call on a dispatching
1972             --  operation"
1973 
1974             if Is_Tagged_Type (Directly_Designated_Type (T))
1975               and then
1976                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1977               and then
1978                 Ekind (Directly_Designated_Type (Etype (E))) =
1979                   E_Class_Wide_Type
1980             then
1981                Error_Msg_N
1982                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1983             end if;
1984 
1985             --  (Ada 2005: AI-230): Accessibility check for anonymous
1986             --  components
1987 
1988             if Type_Access_Level (Etype (E)) >
1989                Deepest_Type_Access_Level (T)
1990             then
1991                Error_Msg_N
1992                  ("expression has deeper access level than component " &
1993                   "(RM 3.10.2 (12.2))", E);
1994             end if;
1995 
1996             --  The initialization expression is a reference to an access
1997             --  discriminant. The type of the discriminant is always deeper
1998             --  than any access type.
1999 
2000             if Ekind (Etype (E)) = E_Anonymous_Access_Type
2001               and then Is_Entity_Name (E)
2002               and then Ekind (Entity (E)) = E_In_Parameter
2003               and then Present (Discriminal_Link (Entity (E)))
2004             then
2005                Error_Msg_N
2006                  ("discriminant has deeper accessibility level than target",
2007                   E);
2008             end if;
2009          end if;
2010       end if;
2011 
2012       --  The parent type may be a private view with unknown discriminants,
2013       --  and thus unconstrained. Regular components must be constrained.
2014 
2015       if not Is_Definite_Subtype (T) and then Chars (Id) /= Name_uParent then
2016          if Is_Class_Wide_Type (T) then
2017             Error_Msg_N
2018                ("class-wide subtype with unknown discriminants" &
2019                  " in component declaration",
2020                  Subtype_Indication (Component_Definition (N)));
2021          else
2022             Error_Msg_N
2023               ("unconstrained subtype in component declaration",
2024                Subtype_Indication (Component_Definition (N)));
2025          end if;
2026 
2027       --  Components cannot be abstract, except for the special case of
2028       --  the _Parent field (case of extending an abstract tagged type)
2029 
2030       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
2031          Error_Msg_N ("type of a component cannot be abstract", N);
2032       end if;
2033 
2034       Set_Etype (Id, T);
2035       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
2036 
2037       --  The component declaration may have a per-object constraint, set
2038       --  the appropriate flag in the defining identifier of the subtype.
2039 
2040       if Present (Subtype_Indication (Component_Definition (N))) then
2041          declare
2042             Sindic : constant Node_Id :=
2043                        Subtype_Indication (Component_Definition (N));
2044          begin
2045             if Nkind (Sindic) = N_Subtype_Indication
2046               and then Present (Constraint (Sindic))
2047               and then Contains_POC (Constraint (Sindic))
2048             then
2049                Set_Has_Per_Object_Constraint (Id);
2050             end if;
2051          end;
2052       end if;
2053 
2054       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2055       --  out some static checks.
2056 
2057       if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (T) then
2058          Null_Exclusion_Static_Checks (N);
2059       end if;
2060 
2061       --  If this component is private (or depends on a private type), flag the
2062       --  record type to indicate that some operations are not available.
2063 
2064       P := Private_Component (T);
2065 
2066       if Present (P) then
2067 
2068          --  Check for circular definitions
2069 
2070          if P = Any_Type then
2071             Set_Etype (Id, Any_Type);
2072 
2073          --  There is a gap in the visibility of operations only if the
2074          --  component type is not defined in the scope of the record type.
2075 
2076          elsif Scope (P) = Scope (Current_Scope) then
2077             null;
2078 
2079          elsif Is_Limited_Type (P) then
2080             Set_Is_Limited_Composite (Current_Scope);
2081 
2082          else
2083             Set_Is_Private_Composite (Current_Scope);
2084          end if;
2085       end if;
2086 
2087       if P /= Any_Type
2088         and then Is_Limited_Type (T)
2089         and then Chars (Id) /= Name_uParent
2090         and then Is_Tagged_Type (Current_Scope)
2091       then
2092          if Is_Derived_Type (Current_Scope)
2093            and then not Is_Known_Limited (Current_Scope)
2094          then
2095             Error_Msg_N
2096               ("extension of nonlimited type cannot have limited components",
2097                N);
2098 
2099             if Is_Interface (Root_Type (Current_Scope)) then
2100                Error_Msg_N
2101                  ("\limitedness is not inherited from limited interface", N);
2102                Error_Msg_N ("\add LIMITED to type indication", N);
2103             end if;
2104 
2105             Explain_Limited_Type (T, N);
2106             Set_Etype (Id, Any_Type);
2107             Set_Is_Limited_Composite (Current_Scope, False);
2108 
2109          elsif not Is_Derived_Type (Current_Scope)
2110            and then not Is_Limited_Record (Current_Scope)
2111            and then not Is_Concurrent_Type (Current_Scope)
2112          then
2113             Error_Msg_N
2114               ("nonlimited tagged type cannot have limited components", N);
2115             Explain_Limited_Type (T, N);
2116             Set_Etype (Id, Any_Type);
2117             Set_Is_Limited_Composite (Current_Scope, False);
2118          end if;
2119       end if;
2120 
2121       --  If the component is an unconstrained task or protected type with
2122       --  discriminants, the component and the enclosing record are limited
2123       --  and the component is constrained by its default values. Compute
2124       --  its actual subtype, else it may be allocated the maximum size by
2125       --  the backend, and possibly overflow.
2126 
2127       if Is_Concurrent_Type (T)
2128         and then not Is_Constrained (T)
2129         and then Has_Discriminants (T)
2130         and then not Has_Discriminants (Current_Scope)
2131       then
2132          declare
2133             Act_T : constant Entity_Id := Build_Default_Subtype (T, N);
2134 
2135          begin
2136             Set_Etype (Id, Act_T);
2137 
2138             --  Rewrite component definition to use the constrained subtype
2139 
2140             Rewrite (Component_Definition (N),
2141               Make_Component_Definition (Loc,
2142                 Subtype_Indication => New_Occurrence_Of (Act_T, Loc)));
2143          end;
2144       end if;
2145 
2146       Set_Original_Record_Component (Id, Id);
2147 
2148       if Has_Aspects (N) then
2149          Analyze_Aspect_Specifications (N, Id);
2150       end if;
2151 
2152       Analyze_Dimension (N);
2153    end Analyze_Component_Declaration;
2154 
2155    --------------------------
2156    -- Analyze_Declarations --
2157    --------------------------
2158 
2159    procedure Analyze_Declarations (L : List_Id) is
2160       Decl : Node_Id;
2161 
2162       procedure Adjust_Decl;
2163       --  Adjust Decl not to include implicit label declarations, since these
2164       --  have strange Sloc values that result in elaboration check problems.
2165       --  (They have the sloc of the label as found in the source, and that
2166       --  is ahead of the current declarative part).
2167 
2168       procedure Check_Entry_Contracts;
2169       --  Perform a pre-analysis of the pre- and postconditions of an entry
2170       --  declaration. This must be done before full resolution and creation
2171       --  of the parameter block, etc. to catch illegal uses within the
2172       --  contract expression. Full analysis of the expression is done when
2173       --  the contract is processed.
2174 
2175       procedure Handle_Late_Controlled_Primitive (Body_Decl : Node_Id);
2176       --  Determine whether Body_Decl denotes the body of a late controlled
2177       --  primitive (either Initialize, Adjust or Finalize). If this is the
2178       --  case, add a proper spec if the body lacks one. The spec is inserted
2179       --  before Body_Decl and immedately analyzed.
2180 
2181       procedure Remove_Visible_Refinements (Spec_Id : Entity_Id);
2182       --  Spec_Id is the entity of a package that may define abstract states.
2183       --  If the states have visible refinement, remove the visibility of each
2184       --  constituent at the end of the package body declarations.
2185 
2186       -----------------
2187       -- Adjust_Decl --
2188       -----------------
2189 
2190       procedure Adjust_Decl is
2191       begin
2192          while Present (Prev (Decl))
2193            and then Nkind (Decl) = N_Implicit_Label_Declaration
2194          loop
2195             Prev (Decl);
2196          end loop;
2197       end Adjust_Decl;
2198 
2199       ---------------------------
2200       -- Check_Entry_Contracts --
2201       ---------------------------
2202 
2203       procedure Check_Entry_Contracts is
2204          ASN : Node_Id;
2205          Ent : Entity_Id;
2206          Exp : Node_Id;
2207 
2208       begin
2209          Ent := First_Entity (Current_Scope);
2210          while Present (Ent) loop
2211 
2212             --  This only concerns entries with pre/postconditions
2213 
2214             if Ekind (Ent) = E_Entry
2215               and then Present (Contract (Ent))
2216               and then Present (Pre_Post_Conditions (Contract (Ent)))
2217             then
2218                ASN := Pre_Post_Conditions (Contract (Ent));
2219                Push_Scope (Ent);
2220                Install_Formals (Ent);
2221 
2222                --  Pre/postconditions are rewritten as Check pragmas. Analysis
2223                --  is performed on a copy of the pragma expression, to prevent
2224                --  modifying the original expression.
2225 
2226                while Present (ASN) loop
2227                   if Nkind (ASN) = N_Pragma then
2228                      Exp :=
2229                        New_Copy_Tree
2230                          (Expression
2231                            (First (Pragma_Argument_Associations (ASN))));
2232                      Set_Parent (Exp, ASN);
2233 
2234                      --  ??? why not Preanalyze_Assert_Expression
2235 
2236                      Preanalyze (Exp);
2237                   end if;
2238 
2239                   ASN := Next_Pragma (ASN);
2240                end loop;
2241 
2242                End_Scope;
2243             end if;
2244 
2245             Next_Entity (Ent);
2246          end loop;
2247       end Check_Entry_Contracts;
2248 
2249       --------------------------------------
2250       -- Handle_Late_Controlled_Primitive --
2251       --------------------------------------
2252 
2253       procedure Handle_Late_Controlled_Primitive (Body_Decl : Node_Id) is
2254          Body_Spec : constant Node_Id    := Specification (Body_Decl);
2255          Body_Id   : constant Entity_Id  := Defining_Entity (Body_Spec);
2256          Loc       : constant Source_Ptr := Sloc (Body_Id);
2257          Params    : constant List_Id    :=
2258                        Parameter_Specifications (Body_Spec);
2259          Spec      : Node_Id;
2260          Spec_Id   : Entity_Id;
2261          Typ       : Node_Id;
2262 
2263       begin
2264          --  Consider only procedure bodies whose name matches one of the three
2265          --  controlled primitives.
2266 
2267          if Nkind (Body_Spec) /= N_Procedure_Specification
2268            or else not Nam_In (Chars (Body_Id), Name_Adjust,
2269                                                 Name_Finalize,
2270                                                 Name_Initialize)
2271          then
2272             return;
2273 
2274          --  A controlled primitive must have exactly one formal which is not
2275          --  an anonymous access type.
2276 
2277          elsif List_Length (Params) /= 1 then
2278             return;
2279          end if;
2280 
2281          Typ := Parameter_Type (First (Params));
2282 
2283          if Nkind (Typ) = N_Access_Definition then
2284             return;
2285          end if;
2286 
2287          Find_Type (Typ);
2288 
2289          --  The type of the formal must be derived from [Limited_]Controlled
2290 
2291          if not Is_Controlled (Entity (Typ)) then
2292             return;
2293          end if;
2294 
2295          --  Check whether a specification exists for this body. We do not
2296          --  analyze the spec of the body in full, because it will be analyzed
2297          --  again when the body is properly analyzed, and we cannot create
2298          --  duplicate entries in the formals chain. We look for an explicit
2299          --  specification because the body may be an overriding operation and
2300          --  an inherited spec may be present.
2301 
2302          Spec_Id := Current_Entity (Body_Id);
2303 
2304          while Present (Spec_Id) loop
2305             if Ekind_In (Spec_Id, E_Procedure, E_Generic_Procedure)
2306               and then Scope (Spec_Id) = Current_Scope
2307               and then Present (First_Formal (Spec_Id))
2308               and then No (Next_Formal (First_Formal (Spec_Id)))
2309               and then Etype (First_Formal (Spec_Id)) = Entity (Typ)
2310               and then Comes_From_Source (Spec_Id)
2311             then
2312                return;
2313             end if;
2314 
2315             Spec_Id := Homonym (Spec_Id);
2316          end loop;
2317 
2318          --  At this point the body is known to be a late controlled primitive.
2319          --  Generate a matching spec and insert it before the body. Note the
2320          --  use of Copy_Separate_Tree - we want an entirely separate semantic
2321          --  tree in this case.
2322 
2323          Spec := Copy_Separate_Tree (Body_Spec);
2324 
2325          --  Ensure that the subprogram declaration does not inherit the null
2326          --  indicator from the body as we now have a proper spec/body pair.
2327 
2328          Set_Null_Present (Spec, False);
2329 
2330          Insert_Before_And_Analyze (Body_Decl,
2331            Make_Subprogram_Declaration (Loc, Specification => Spec));
2332       end Handle_Late_Controlled_Primitive;
2333 
2334       --------------------------------
2335       -- Remove_Visible_Refinements --
2336       --------------------------------
2337 
2338       procedure Remove_Visible_Refinements (Spec_Id : Entity_Id) is
2339          State_Elmt : Elmt_Id;
2340       begin
2341          if Present (Abstract_States (Spec_Id)) then
2342             State_Elmt := First_Elmt (Abstract_States (Spec_Id));
2343             while Present (State_Elmt) loop
2344                Set_Has_Visible_Refinement (Node (State_Elmt), False);
2345                Next_Elmt (State_Elmt);
2346             end loop;
2347          end if;
2348       end Remove_Visible_Refinements;
2349 
2350       --  Local variables
2351 
2352       Context     : Node_Id   := Empty;
2353       Freeze_From : Entity_Id := Empty;
2354       Next_Decl   : Node_Id;
2355 
2356       Body_Seen : Boolean := False;
2357       --  Flag set when the first body [stub] is encountered
2358 
2359    --  Start of processing for Analyze_Declarations
2360 
2361    begin
2362       if Restriction_Check_Required (SPARK_05) then
2363          Check_Later_Vs_Basic_Declarations (L, During_Parsing => False);
2364       end if;
2365 
2366       Decl := First (L);
2367       while Present (Decl) loop
2368 
2369          --  Package spec cannot contain a package declaration in SPARK
2370 
2371          if Nkind (Decl) = N_Package_Declaration
2372            and then Nkind (Parent (L)) = N_Package_Specification
2373          then
2374             Check_SPARK_05_Restriction
2375               ("package specification cannot contain a package declaration",
2376                Decl);
2377          end if;
2378 
2379          --  Complete analysis of declaration
2380 
2381          Analyze (Decl);
2382          Next_Decl := Next (Decl);
2383 
2384          if No (Freeze_From) then
2385             Freeze_From := First_Entity (Current_Scope);
2386          end if;
2387 
2388          --  At the end of a declarative part, freeze remaining entities
2389          --  declared in it. The end of the visible declarations of package
2390          --  specification is not the end of a declarative part if private
2391          --  declarations are present. The end of a package declaration is a
2392          --  freezing point only if it a library package. A task definition or
2393          --  protected type definition is not a freeze point either. Finally,
2394          --  we do not freeze entities in generic scopes, because there is no
2395          --  code generated for them and freeze nodes will be generated for
2396          --  the instance.
2397 
2398          --  The end of a package instantiation is not a freeze point, but
2399          --  for now we make it one, because the generic body is inserted
2400          --  (currently) immediately after. Generic instantiations will not
2401          --  be a freeze point once delayed freezing of bodies is implemented.
2402          --  (This is needed in any case for early instantiations ???).
2403 
2404          if No (Next_Decl) then
2405             if Nkind (Parent (L)) = N_Component_List then
2406                null;
2407 
2408             elsif Nkind_In (Parent (L), N_Protected_Definition,
2409                                         N_Task_Definition)
2410             then
2411                Check_Entry_Contracts;
2412 
2413             elsif Nkind (Parent (L)) /= N_Package_Specification then
2414                if Nkind (Parent (L)) = N_Package_Body then
2415                   Freeze_From := First_Entity (Current_Scope);
2416                end if;
2417 
2418                --  There may have been several freezing points previously,
2419                --  for example object declarations or subprogram bodies, but
2420                --  at the end of a declarative part we check freezing from
2421                --  the beginning, even though entities may already be frozen,
2422                --  in order to perform visibility checks on delayed aspects.
2423 
2424                Adjust_Decl;
2425                Freeze_All (First_Entity (Current_Scope), Decl);
2426                Freeze_From := Last_Entity (Current_Scope);
2427 
2428             elsif Scope (Current_Scope) /= Standard_Standard
2429               and then not Is_Child_Unit (Current_Scope)
2430               and then No (Generic_Parent (Parent (L)))
2431             then
2432                null;
2433 
2434             elsif L /= Visible_Declarations (Parent (L))
2435               or else No (Private_Declarations (Parent (L)))
2436               or else Is_Empty_List (Private_Declarations (Parent (L)))
2437             then
2438                Adjust_Decl;
2439                Freeze_All (First_Entity (Current_Scope), Decl);
2440                Freeze_From := Last_Entity (Current_Scope);
2441 
2442             --  At the end of the visible declarations the expressions in
2443             --  aspects of all entities declared so far must be resolved.
2444             --  The entities themselves might be frozen later, and the
2445             --  generated pragmas and attribute definition clauses analyzed
2446             --  in full at that point, but name resolution must take place
2447             --  now.
2448             --  In addition to being the proper semantics, this is mandatory
2449             --  within generic units, because global name capture requires
2450             --  those expressions to be analyzed, given that the generated
2451             --  pragmas do not appear in the original generic tree.
2452 
2453             elsif Serious_Errors_Detected = 0 then
2454                declare
2455                   E : Entity_Id;
2456 
2457                begin
2458                   E := First_Entity (Current_Scope);
2459                   while Present (E) loop
2460                      Resolve_Aspect_Expressions (E);
2461                      Next_Entity (E);
2462                   end loop;
2463                end;
2464             end if;
2465 
2466          --  If next node is a body then freeze all types before the body.
2467          --  An exception occurs for some expander-generated bodies. If these
2468          --  are generated at places where in general language rules would not
2469          --  allow a freeze point, then we assume that the expander has
2470          --  explicitly checked that all required types are properly frozen,
2471          --  and we do not cause general freezing here. This special circuit
2472          --  is used when the encountered body is marked as having already
2473          --  been analyzed.
2474 
2475          --  In all other cases (bodies that come from source, and expander
2476          --  generated bodies that have not been analyzed yet), freeze all
2477          --  types now. Note that in the latter case, the expander must take
2478          --  care to attach the bodies at a proper place in the tree so as to
2479          --  not cause unwanted freezing at that point.
2480 
2481          elsif not Analyzed (Next_Decl) and then Is_Body (Next_Decl) then
2482 
2483             --  When a controlled type is frozen, the expander generates stream
2484             --  and controlled type support routines. If the freeze is caused
2485             --  by the stand alone body of Initialize, Adjust and Finalize, the
2486             --  expander will end up using the wrong version of these routines
2487             --  as the body has not been processed yet. To remedy this, detect
2488             --  a late controlled primitive and create a proper spec for it.
2489             --  This ensures that the primitive will override its inherited
2490             --  counterpart before the freeze takes place.
2491 
2492             --  If the declaration we just processed is a body, do not attempt
2493             --  to examine Next_Decl as the late primitive idiom can only apply
2494             --  to the first encountered body.
2495 
2496             --  The spec of the late primitive is not generated in ASIS mode to
2497             --  ensure a consistent list of primitives that indicates the true
2498             --  semantic structure of the program (which is not relevant when
2499             --  generating executable code.
2500 
2501             --  ??? a cleaner approach may be possible and/or this solution
2502             --  could be extended to general-purpose late primitives, TBD.
2503 
2504             if not ASIS_Mode and then not Body_Seen and then not Is_Body (Decl)
2505             then
2506                Body_Seen := True;
2507 
2508                if Nkind (Next_Decl) = N_Subprogram_Body then
2509                   Handle_Late_Controlled_Primitive (Next_Decl);
2510                end if;
2511             end if;
2512 
2513             Adjust_Decl;
2514             Freeze_All (Freeze_From, Decl);
2515             Freeze_From := Last_Entity (Current_Scope);
2516          end if;
2517 
2518          Decl := Next_Decl;
2519       end loop;
2520 
2521       --  Analyze the contracts of packages and their bodies
2522 
2523       if Present (L) then
2524          Context := Parent (L);
2525 
2526          if Nkind (Context) = N_Package_Specification then
2527 
2528             --  When a package has private declarations, its contract must be
2529             --  analyzed at the end of the said declarations. This way both the
2530             --  analysis and freeze actions are properly synchronized in case
2531             --  of private type use within the contract.
2532 
2533             if L = Private_Declarations (Context) then
2534                Analyze_Package_Contract (Defining_Entity (Context));
2535 
2536                --  Build the bodies of the default initial condition procedures
2537                --  for all types subject to pragma Default_Initial_Condition.
2538                --  From a purely Ada stand point, this is a freezing activity,
2539                --  however freezing is not available under GNATprove_Mode. To
2540                --  accomodate both scenarios, the bodies are build at the end
2541                --  of private declaration analysis.
2542 
2543                Build_Default_Init_Cond_Procedure_Bodies (L);
2544 
2545             --  Otherwise the contract is analyzed at the end of the visible
2546             --  declarations.
2547 
2548             elsif L = Visible_Declarations (Context)
2549               and then No (Private_Declarations (Context))
2550             then
2551                Analyze_Package_Contract (Defining_Entity (Context));
2552             end if;
2553 
2554          elsif Nkind (Context) = N_Package_Body then
2555             Analyze_Package_Body_Contract (Defining_Entity (Context));
2556          end if;
2557 
2558          --  Analyze the contracts of various constructs now due to the delayed
2559          --  visibility needs of their aspects and pragmas.
2560 
2561          Analyze_Contracts (L);
2562 
2563          if Nkind (Context) = N_Package_Body then
2564 
2565             --  Ensure that all abstract states and objects declared in the
2566             --  state space of a package body are utilized as constituents.
2567 
2568             Check_Unused_Body_States (Defining_Entity (Context));
2569 
2570             --  State refinements are visible up to the end of the package body
2571             --  declarations. Hide the state refinements from visibility to
2572             --  restore the original state conditions.
2573 
2574             Remove_Visible_Refinements (Corresponding_Spec (Context));
2575          end if;
2576 
2577          --  Verify that all abstract states found in any package declared in
2578          --  the input declarative list have proper refinements. The check is
2579          --  performed only when the context denotes a block, entry, package,
2580          --  protected, subprogram, or task body (SPARK RM 7.2.2(3)).
2581 
2582          Check_State_Refinements (Context);
2583       end if;
2584    end Analyze_Declarations;
2585 
2586    -----------------------------------
2587    -- Analyze_Full_Type_Declaration --
2588    -----------------------------------
2589 
2590    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2591       Def    : constant Node_Id   := Type_Definition (N);
2592       Def_Id : constant Entity_Id := Defining_Identifier (N);
2593       T      : Entity_Id;
2594       Prev   : Entity_Id;
2595 
2596       Is_Remote : constant Boolean :=
2597                     (Is_Remote_Types (Current_Scope)
2598                        or else Is_Remote_Call_Interface (Current_Scope))
2599                       and then not (In_Private_Part (Current_Scope)
2600                                      or else In_Package_Body (Current_Scope));
2601 
2602       procedure Check_Nonoverridable_Aspects;
2603       --  Apply the rule in RM 13.1.1(18.4/4) on iterator aspects that cannot
2604       --  be overridden, and can only be confirmed on derivation.
2605 
2606       procedure Check_Ops_From_Incomplete_Type;
2607       --  If there is a tagged incomplete partial view of the type, traverse
2608       --  the primitives of the incomplete view and change the type of any
2609       --  controlling formals and result to indicate the full view. The
2610       --  primitives will be added to the full type's primitive operations
2611       --  list later in Sem_Disp.Check_Operation_From_Incomplete_Type (which
2612       --  is called from Process_Incomplete_Dependents).
2613 
2614       ----------------------------------
2615       -- Check_Nonoverridable_Aspects --
2616       ----------------------------------
2617 
2618       procedure Check_Nonoverridable_Aspects is
2619          Prev_Aspects   : constant List_Id :=
2620                             Aspect_Specifications (Parent (Def_Id));
2621          Par_Type       : Entity_Id;
2622 
2623          function Has_Aspect_Spec
2624            (Specs : List_Id;
2625             Aspect_Name : Name_Id) return Boolean;
2626          --  Check whether a list of aspect specifications includes an entry
2627          --  for a specific aspect. The list is either that of a partial or
2628          --  a full view.
2629 
2630          ---------------------
2631          -- Has_Aspect_Spec --
2632          ---------------------
2633 
2634          function Has_Aspect_Spec
2635            (Specs : List_Id;
2636             Aspect_Name : Name_Id) return Boolean
2637          is
2638             Spec : Node_Id;
2639          begin
2640             Spec := First (Specs);
2641             while Present (Spec) loop
2642                if Chars (Identifier (Spec)) = Aspect_Name then
2643                   return True;
2644                end if;
2645                Next (Spec);
2646             end loop;
2647             return False;
2648          end Has_Aspect_Spec;
2649 
2650       --  Start of processing for Check_Nonoverridable_Aspects
2651 
2652       begin
2653 
2654          --  Get parent type of derived type. Note that Prev is the entity
2655          --  in the partial declaration, but its contents are now those of
2656          --  full view, while Def_Id reflects the partial view.
2657 
2658          if Is_Private_Type (Def_Id) then
2659             Par_Type := Etype (Full_View (Def_Id));
2660          else
2661             Par_Type := Etype (Def_Id);
2662          end if;
2663 
2664          --  If there is an inherited Implicit_Dereference, verify that it is
2665          --  made explicit in the partial view.
2666 
2667          if Has_Discriminants (Base_Type (Par_Type))
2668            and then Nkind (Parent (Prev)) = N_Full_Type_Declaration
2669            and then Present (Discriminant_Specifications (Parent (Prev)))
2670            and then Present (Get_Reference_Discriminant (Par_Type))
2671          then
2672             if
2673               not Has_Aspect_Spec (Prev_Aspects, Name_Implicit_Dereference)
2674             then
2675                Error_Msg_N
2676                  ("type does not inherit implicit dereference", Prev);
2677 
2678             else
2679                --  If one of the views has the aspect specified, verify that it
2680                --  is consistent with that of the parent.
2681 
2682                declare
2683                   Par_Discr : constant Entity_Id :=
2684                                 Get_Reference_Discriminant (Par_Type);
2685                   Cur_Discr : constant Entity_Id :=
2686                                 Get_Reference_Discriminant (Prev);
2687                begin
2688                   if Corresponding_Discriminant (Cur_Discr) /= Par_Discr then
2689                      Error_Msg_N ("aspect incosistent with that of parent", N);
2690                   end if;
2691                end;
2692             end if;
2693          end if;
2694 
2695          --  TBD : other nonoverridable aspects.
2696       end Check_Nonoverridable_Aspects;
2697 
2698       ------------------------------------
2699       -- Check_Ops_From_Incomplete_Type --
2700       ------------------------------------
2701 
2702       procedure Check_Ops_From_Incomplete_Type is
2703          Elmt   : Elmt_Id;
2704          Formal : Entity_Id;
2705          Op     : Entity_Id;
2706 
2707       begin
2708          if Prev /= T
2709            and then Ekind (Prev) = E_Incomplete_Type
2710            and then Is_Tagged_Type (Prev)
2711            and then Is_Tagged_Type (T)
2712          then
2713             Elmt := First_Elmt (Primitive_Operations (Prev));
2714             while Present (Elmt) loop
2715                Op := Node (Elmt);
2716 
2717                Formal := First_Formal (Op);
2718                while Present (Formal) loop
2719                   if Etype (Formal) = Prev then
2720                      Set_Etype (Formal, T);
2721                   end if;
2722 
2723                   Next_Formal (Formal);
2724                end loop;
2725 
2726                if Etype (Op) = Prev then
2727                   Set_Etype (Op, T);
2728                end if;
2729 
2730                Next_Elmt (Elmt);
2731             end loop;
2732          end if;
2733       end Check_Ops_From_Incomplete_Type;
2734 
2735    --  Start of processing for Analyze_Full_Type_Declaration
2736 
2737    begin
2738       Prev := Find_Type_Name (N);
2739 
2740       --  The full view, if present, now points to the current type. If there
2741       --  is an incomplete partial view, set a link to it, to simplify the
2742       --  retrieval of primitive operations of the type.
2743 
2744       --  Ada 2005 (AI-50217): If the type was previously decorated when
2745       --  imported through a LIMITED WITH clause, it appears as incomplete
2746       --  but has no full view.
2747 
2748       if Ekind (Prev) = E_Incomplete_Type
2749         and then Present (Full_View (Prev))
2750       then
2751          T := Full_View (Prev);
2752          Set_Incomplete_View (N, Parent (Prev));
2753       else
2754          T := Prev;
2755       end if;
2756 
2757       Set_Is_Pure (T, Is_Pure (Current_Scope));
2758 
2759       --  We set the flag Is_First_Subtype here. It is needed to set the
2760       --  corresponding flag for the Implicit class-wide-type created
2761       --  during tagged types processing.
2762 
2763       Set_Is_First_Subtype (T, True);
2764 
2765       --  Only composite types other than array types are allowed to have
2766       --  discriminants.
2767 
2768       case Nkind (Def) is
2769 
2770          --  For derived types, the rule will be checked once we've figured
2771          --  out the parent type.
2772 
2773          when N_Derived_Type_Definition =>
2774             null;
2775 
2776          --  For record types, discriminants are allowed, unless we are in
2777          --  SPARK.
2778 
2779          when N_Record_Definition =>
2780             if Present (Discriminant_Specifications (N)) then
2781                Check_SPARK_05_Restriction
2782                  ("discriminant type is not allowed",
2783                   Defining_Identifier
2784                     (First (Discriminant_Specifications (N))));
2785             end if;
2786 
2787          when others =>
2788             if Present (Discriminant_Specifications (N)) then
2789                Error_Msg_N
2790                  ("elementary or array type cannot have discriminants",
2791                   Defining_Identifier
2792                     (First (Discriminant_Specifications (N))));
2793             end if;
2794       end case;
2795 
2796       --  Elaborate the type definition according to kind, and generate
2797       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2798       --  already done (this happens during the reanalysis that follows a call
2799       --  to the high level optimizer).
2800 
2801       if not Analyzed (T) then
2802          Set_Analyzed (T);
2803 
2804          case Nkind (Def) is
2805             when N_Access_To_Subprogram_Definition =>
2806                Access_Subprogram_Declaration (T, Def);
2807 
2808                --  If this is a remote access to subprogram, we must create the
2809                --  equivalent fat pointer type, and related subprograms.
2810 
2811                if Is_Remote then
2812                   Process_Remote_AST_Declaration (N);
2813                end if;
2814 
2815                --  Validate categorization rule against access type declaration
2816                --  usually a violation in Pure unit, Shared_Passive unit.
2817 
2818                Validate_Access_Type_Declaration (T, N);
2819 
2820             when N_Access_To_Object_Definition =>
2821                Access_Type_Declaration (T, Def);
2822 
2823                --  Validate categorization rule against access type declaration
2824                --  usually a violation in Pure unit, Shared_Passive unit.
2825 
2826                Validate_Access_Type_Declaration (T, N);
2827 
2828                --  If we are in a Remote_Call_Interface package and define a
2829                --  RACW, then calling stubs and specific stream attributes
2830                --  must be added.
2831 
2832                if Is_Remote
2833                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2834                then
2835                   Add_RACW_Features (Def_Id);
2836                end if;
2837 
2838             when N_Array_Type_Definition =>
2839                Array_Type_Declaration (T, Def);
2840 
2841             when N_Derived_Type_Definition =>
2842                Derived_Type_Declaration (T, N, T /= Def_Id);
2843 
2844             when N_Enumeration_Type_Definition =>
2845                Enumeration_Type_Declaration (T, Def);
2846 
2847             when N_Floating_Point_Definition =>
2848                Floating_Point_Type_Declaration (T, Def);
2849 
2850             when N_Decimal_Fixed_Point_Definition =>
2851                Decimal_Fixed_Point_Type_Declaration (T, Def);
2852 
2853             when N_Ordinary_Fixed_Point_Definition =>
2854                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2855 
2856             when N_Signed_Integer_Type_Definition =>
2857                Signed_Integer_Type_Declaration (T, Def);
2858 
2859             when N_Modular_Type_Definition =>
2860                Modular_Type_Declaration (T, Def);
2861 
2862             when N_Record_Definition =>
2863                Record_Type_Declaration (T, N, Prev);
2864 
2865             --  If declaration has a parse error, nothing to elaborate.
2866 
2867             when N_Error =>
2868                null;
2869 
2870             when others =>
2871                raise Program_Error;
2872 
2873          end case;
2874       end if;
2875 
2876       if Etype (T) = Any_Type then
2877          return;
2878       end if;
2879 
2880       --  Controlled type is not allowed in SPARK
2881 
2882       if Is_Visibly_Controlled (T) then
2883          Check_SPARK_05_Restriction ("controlled type is not allowed", N);
2884       end if;
2885 
2886       --  A type declared within a Ghost region is automatically Ghost
2887       --  (SPARK RM 6.9(2)).
2888 
2889       if Ghost_Mode > None then
2890          Set_Is_Ghost_Entity (T);
2891       end if;
2892 
2893       --  Some common processing for all types
2894 
2895       Set_Depends_On_Private (T, Has_Private_Component (T));
2896       Check_Ops_From_Incomplete_Type;
2897 
2898       --  Both the declared entity, and its anonymous base type if one was
2899       --  created, need freeze nodes allocated.
2900 
2901       declare
2902          B : constant Entity_Id := Base_Type (T);
2903 
2904       begin
2905          --  In the case where the base type differs from the first subtype, we
2906          --  pre-allocate a freeze node, and set the proper link to the first
2907          --  subtype. Freeze_Entity will use this preallocated freeze node when
2908          --  it freezes the entity.
2909 
2910          --  This does not apply if the base type is a generic type, whose
2911          --  declaration is independent of the current derived definition.
2912 
2913          if B /= T and then not Is_Generic_Type (B) then
2914             Ensure_Freeze_Node (B);
2915             Set_First_Subtype_Link (Freeze_Node (B), T);
2916          end if;
2917 
2918          --  A type that is imported through a limited_with clause cannot
2919          --  generate any code, and thus need not be frozen. However, an access
2920          --  type with an imported designated type needs a finalization list,
2921          --  which may be referenced in some other package that has non-limited
2922          --  visibility on the designated type. Thus we must create the
2923          --  finalization list at the point the access type is frozen, to
2924          --  prevent unsatisfied references at link time.
2925 
2926          if not From_Limited_With (T) or else Is_Access_Type (T) then
2927             Set_Has_Delayed_Freeze (T);
2928          end if;
2929       end;
2930 
2931       --  Case where T is the full declaration of some private type which has
2932       --  been swapped in Defining_Identifier (N).
2933 
2934       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2935          Process_Full_View (N, T, Def_Id);
2936 
2937          --  Record the reference. The form of this is a little strange, since
2938          --  the full declaration has been swapped in. So the first parameter
2939          --  here represents the entity to which a reference is made which is
2940          --  the "real" entity, i.e. the one swapped in, and the second
2941          --  parameter provides the reference location.
2942 
2943          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2944          --  since we don't want a complaint about the full type being an
2945          --  unwanted reference to the private type
2946 
2947          declare
2948             B : constant Boolean := Has_Pragma_Unreferenced (T);
2949          begin
2950             Set_Has_Pragma_Unreferenced (T, False);
2951             Generate_Reference (T, T, 'c');
2952             Set_Has_Pragma_Unreferenced (T, B);
2953          end;
2954 
2955          Set_Completion_Referenced (Def_Id);
2956 
2957       --  For completion of incomplete type, process incomplete dependents
2958       --  and always mark the full type as referenced (it is the incomplete
2959       --  type that we get for any real reference).
2960 
2961       elsif Ekind (Prev) = E_Incomplete_Type then
2962          Process_Incomplete_Dependents (N, T, Prev);
2963          Generate_Reference (Prev, Def_Id, 'c');
2964          Set_Completion_Referenced (Def_Id);
2965 
2966       --  If not private type or incomplete type completion, this is a real
2967       --  definition of a new entity, so record it.
2968 
2969       else
2970          Generate_Definition (Def_Id);
2971       end if;
2972 
2973       --  Propagate any pending access types whose finalization masters need to
2974       --  be fully initialized from the partial to the full view. Guard against
2975       --  an illegal full view that remains unanalyzed.
2976 
2977       if Is_Type (Def_Id) and then Is_Incomplete_Or_Private_Type (Prev) then
2978          Set_Pending_Access_Types (Def_Id, Pending_Access_Types (Prev));
2979       end if;
2980 
2981       if Chars (Scope (Def_Id)) = Name_System
2982         and then Chars (Def_Id) = Name_Address
2983         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2984       then
2985          Set_Is_Descendant_Of_Address (Def_Id);
2986          Set_Is_Descendant_Of_Address (Base_Type (Def_Id));
2987          Set_Is_Descendant_Of_Address (Prev);
2988       end if;
2989 
2990       Set_Optimize_Alignment_Flags (Def_Id);
2991       Check_Eliminated (Def_Id);
2992 
2993       --  If the declaration is a completion and aspects are present, apply
2994       --  them to the entity for the type which is currently the partial
2995       --  view, but which is the one that will be frozen.
2996 
2997       if Has_Aspects (N) then
2998 
2999          --  In most cases the partial view is a private type, and both views
3000          --  appear in different declarative parts. In the unusual case where
3001          --  the partial view is incomplete, perform the analysis on the
3002          --  full view, to prevent freezing anomalies with the corresponding
3003          --  class-wide type, which otherwise might be frozen before the
3004          --  dispatch table is built.
3005 
3006          if Prev /= Def_Id
3007            and then Ekind (Prev) /= E_Incomplete_Type
3008          then
3009             Analyze_Aspect_Specifications (N, Prev);
3010 
3011          --  Normal case
3012 
3013          else
3014             Analyze_Aspect_Specifications (N, Def_Id);
3015          end if;
3016       end if;
3017 
3018       if Is_Derived_Type (Prev)
3019         and then Def_Id /= Prev
3020       then
3021          Check_Nonoverridable_Aspects;
3022       end if;
3023    end Analyze_Full_Type_Declaration;
3024 
3025    ----------------------------------
3026    -- Analyze_Incomplete_Type_Decl --
3027    ----------------------------------
3028 
3029    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
3030       F : constant Boolean := Is_Pure (Current_Scope);
3031       T : Entity_Id;
3032 
3033    begin
3034       Check_SPARK_05_Restriction ("incomplete type is not allowed", N);
3035 
3036       Generate_Definition (Defining_Identifier (N));
3037 
3038       --  Process an incomplete declaration. The identifier must not have been
3039       --  declared already in the scope. However, an incomplete declaration may
3040       --  appear in the private part of a package, for a private type that has
3041       --  already been declared.
3042 
3043       --  In this case, the discriminants (if any) must match
3044 
3045       T := Find_Type_Name (N);
3046 
3047       Set_Ekind (T, E_Incomplete_Type);
3048       Init_Size_Align (T);
3049       Set_Is_First_Subtype (T, True);
3050       Set_Etype (T, T);
3051 
3052       --  An incomplete type declared within a Ghost region is automatically
3053       --  Ghost (SPARK RM 6.9(2)).
3054 
3055       if Ghost_Mode > None then
3056          Set_Is_Ghost_Entity (T);
3057       end if;
3058 
3059       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
3060       --  incomplete types.
3061 
3062       if Tagged_Present (N) then
3063          Set_Is_Tagged_Type (T, True);
3064          Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
3065          Make_Class_Wide_Type (T);
3066          Set_Direct_Primitive_Operations (T, New_Elmt_List);
3067       end if;
3068 
3069       Set_Stored_Constraint (T, No_Elist);
3070 
3071       if Present (Discriminant_Specifications (N)) then
3072          Push_Scope (T);
3073          Process_Discriminants (N);
3074          End_Scope;
3075       end if;
3076 
3077       --  If the type has discriminants, nontrivial subtypes may be declared
3078       --  before the full view of the type. The full views of those subtypes
3079       --  will be built after the full view of the type.
3080 
3081       Set_Private_Dependents (T, New_Elmt_List);
3082       Set_Is_Pure            (T, F);
3083    end Analyze_Incomplete_Type_Decl;
3084 
3085    -----------------------------------
3086    -- Analyze_Interface_Declaration --
3087    -----------------------------------
3088 
3089    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
3090       CW : constant Entity_Id := Class_Wide_Type (T);
3091 
3092    begin
3093       Set_Is_Tagged_Type (T);
3094       Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
3095 
3096       Set_Is_Limited_Record (T, Limited_Present (Def)
3097                                   or else Task_Present (Def)
3098                                   or else Protected_Present (Def)
3099                                   or else Synchronized_Present (Def));
3100 
3101       --  Type is abstract if full declaration carries keyword, or if previous
3102       --  partial view did.
3103 
3104       Set_Is_Abstract_Type (T);
3105       Set_Is_Interface (T);
3106 
3107       --  Type is a limited interface if it includes the keyword limited, task,
3108       --  protected, or synchronized.
3109 
3110       Set_Is_Limited_Interface
3111         (T, Limited_Present (Def)
3112               or else Protected_Present (Def)
3113               or else Synchronized_Present (Def)
3114               or else Task_Present (Def));
3115 
3116       Set_Interfaces (T, New_Elmt_List);
3117       Set_Direct_Primitive_Operations (T, New_Elmt_List);
3118 
3119       --  Complete the decoration of the class-wide entity if it was already
3120       --  built (i.e. during the creation of the limited view)
3121 
3122       if Present (CW) then
3123          Set_Is_Interface (CW);
3124          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
3125       end if;
3126 
3127       --  Check runtime support for synchronized interfaces
3128 
3129       if (Is_Task_Interface (T)
3130            or else Is_Protected_Interface (T)
3131            or else Is_Synchronized_Interface (T))
3132         and then not RTE_Available (RE_Select_Specific_Data)
3133       then
3134          Error_Msg_CRT ("synchronized interfaces", T);
3135       end if;
3136    end Analyze_Interface_Declaration;
3137 
3138    -----------------------------
3139    -- Analyze_Itype_Reference --
3140    -----------------------------
3141 
3142    --  Nothing to do. This node is placed in the tree only for the benefit of
3143    --  back end processing, and has no effect on the semantic processing.
3144 
3145    procedure Analyze_Itype_Reference (N : Node_Id) is
3146    begin
3147       pragma Assert (Is_Itype (Itype (N)));
3148       null;
3149    end Analyze_Itype_Reference;
3150 
3151    --------------------------------
3152    -- Analyze_Number_Declaration --
3153    --------------------------------
3154 
3155    procedure Analyze_Number_Declaration (N : Node_Id) is
3156       E     : constant Node_Id   := Expression (N);
3157       Id    : constant Entity_Id := Defining_Identifier (N);
3158       Index : Interp_Index;
3159       It    : Interp;
3160       T     : Entity_Id;
3161 
3162    begin
3163       Generate_Definition (Id);
3164       Enter_Name (Id);
3165 
3166       --  A number declared within a Ghost region is automatically Ghost
3167       --  (SPARK RM 6.9(2)).
3168 
3169       if Ghost_Mode > None then
3170          Set_Is_Ghost_Entity (Id);
3171       end if;
3172 
3173       --  This is an optimization of a common case of an integer literal
3174 
3175       if Nkind (E) = N_Integer_Literal then
3176          Set_Is_Static_Expression (E, True);
3177          Set_Etype                (E, Universal_Integer);
3178 
3179          Set_Etype     (Id, Universal_Integer);
3180          Set_Ekind     (Id, E_Named_Integer);
3181          Set_Is_Frozen (Id, True);
3182          return;
3183       end if;
3184 
3185       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3186 
3187       --  Process expression, replacing error by integer zero, to avoid
3188       --  cascaded errors or aborts further along in the processing
3189 
3190       --  Replace Error by integer zero, which seems least likely to cause
3191       --  cascaded errors.
3192 
3193       if E = Error then
3194          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
3195          Set_Error_Posted (E);
3196       end if;
3197 
3198       Analyze (E);
3199 
3200       --  Verify that the expression is static and numeric. If
3201       --  the expression is overloaded, we apply the preference
3202       --  rule that favors root numeric types.
3203 
3204       if not Is_Overloaded (E) then
3205          T := Etype (E);
3206          if Has_Dynamic_Predicate_Aspect (T) then
3207             Error_Msg_N
3208               ("subtype has dynamic predicate, "
3209                & "not allowed in number declaration", N);
3210          end if;
3211 
3212       else
3213          T := Any_Type;
3214 
3215          Get_First_Interp (E, Index, It);
3216          while Present (It.Typ) loop
3217             if (Is_Integer_Type (It.Typ) or else Is_Real_Type (It.Typ))
3218               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
3219             then
3220                if T = Any_Type then
3221                   T := It.Typ;
3222 
3223                elsif It.Typ = Universal_Real
3224                        or else
3225                      It.Typ = Universal_Integer
3226                then
3227                   --  Choose universal interpretation over any other
3228 
3229                   T := It.Typ;
3230                   exit;
3231                end if;
3232             end if;
3233 
3234             Get_Next_Interp (Index, It);
3235          end loop;
3236       end if;
3237 
3238       if Is_Integer_Type (T) then
3239          Resolve (E, T);
3240          Set_Etype (Id, Universal_Integer);
3241          Set_Ekind (Id, E_Named_Integer);
3242 
3243       elsif Is_Real_Type (T) then
3244 
3245          --  Because the real value is converted to universal_real, this is a
3246          --  legal context for a universal fixed expression.
3247 
3248          if T = Universal_Fixed then
3249             declare
3250                Loc  : constant Source_Ptr := Sloc (N);
3251                Conv : constant Node_Id := Make_Type_Conversion (Loc,
3252                         Subtype_Mark =>
3253                           New_Occurrence_Of (Universal_Real, Loc),
3254                         Expression => Relocate_Node (E));
3255 
3256             begin
3257                Rewrite (E, Conv);
3258                Analyze (E);
3259             end;
3260 
3261          elsif T = Any_Fixed then
3262             Error_Msg_N ("illegal context for mixed mode operation", E);
3263 
3264             --  Expression is of the form : universal_fixed * integer. Try to
3265             --  resolve as universal_real.
3266 
3267             T := Universal_Real;
3268             Set_Etype (E, T);
3269          end if;
3270 
3271          Resolve (E, T);
3272          Set_Etype (Id, Universal_Real);
3273          Set_Ekind (Id, E_Named_Real);
3274 
3275       else
3276          Wrong_Type (E, Any_Numeric);
3277          Resolve (E, T);
3278 
3279          Set_Etype               (Id, T);
3280          Set_Ekind               (Id, E_Constant);
3281          Set_Never_Set_In_Source (Id, True);
3282          Set_Is_True_Constant    (Id, True);
3283          return;
3284       end if;
3285 
3286       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
3287          Set_Etype (E, Etype (Id));
3288       end if;
3289 
3290       if not Is_OK_Static_Expression (E) then
3291          Flag_Non_Static_Expr
3292            ("non-static expression used in number declaration!", E);
3293          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
3294          Set_Etype (E, Any_Type);
3295       end if;
3296 
3297       Analyze_Dimension (N);
3298    end Analyze_Number_Declaration;
3299 
3300    --------------------------------
3301    -- Analyze_Object_Declaration --
3302    --------------------------------
3303 
3304    procedure Analyze_Object_Declaration (N : Node_Id) is
3305       Loc   : constant Source_Ptr := Sloc (N);
3306       Id    : constant Entity_Id  := Defining_Identifier (N);
3307       Act_T : Entity_Id;
3308       T     : Entity_Id;
3309 
3310       E : Node_Id := Expression (N);
3311       --  E is set to Expression (N) throughout this routine. When
3312       --  Expression (N) is modified, E is changed accordingly.
3313 
3314       Prev_Entity : Entity_Id := Empty;
3315 
3316       function Count_Tasks (T : Entity_Id) return Uint;
3317       --  This function is called when a non-generic library level object of a
3318       --  task type is declared. Its function is to count the static number of
3319       --  tasks declared within the type (it is only called if Has_Task is set
3320       --  for T). As a side effect, if an array of tasks with non-static bounds
3321       --  or a variant record type is encountered, Check_Restriction is called
3322       --  indicating the count is unknown.
3323 
3324       function Delayed_Aspect_Present return Boolean;
3325       --  If the declaration has an expression that is an aggregate, and it
3326       --  has aspects that require delayed analysis, the resolution of the
3327       --  aggregate must be deferred to the freeze point of the objet. This
3328       --  special processing was created for address clauses, but it must
3329       --  also apply to Alignment. This must be done before the aspect
3330       --  specifications are analyzed because we must handle the aggregate
3331       --  before the analysis of the object declaration is complete.
3332 
3333       --  Any other relevant delayed aspects on object declarations ???
3334 
3335       -----------------
3336       -- Count_Tasks --
3337       -----------------
3338 
3339       function Count_Tasks (T : Entity_Id) return Uint is
3340          C : Entity_Id;
3341          X : Node_Id;
3342          V : Uint;
3343 
3344       begin
3345          if Is_Task_Type (T) then
3346             return Uint_1;
3347 
3348          elsif Is_Record_Type (T) then
3349             if Has_Discriminants (T) then
3350                Check_Restriction (Max_Tasks, N);
3351                return Uint_0;
3352 
3353             else
3354                V := Uint_0;
3355                C := First_Component (T);
3356                while Present (C) loop
3357                   V := V + Count_Tasks (Etype (C));
3358                   Next_Component (C);
3359                end loop;
3360 
3361                return V;
3362             end if;
3363 
3364          elsif Is_Array_Type (T) then
3365             X := First_Index (T);
3366             V := Count_Tasks (Component_Type (T));
3367             while Present (X) loop
3368                C := Etype (X);
3369 
3370                if not Is_OK_Static_Subtype (C) then
3371                   Check_Restriction (Max_Tasks, N);
3372                   return Uint_0;
3373                else
3374                   V := V * (UI_Max (Uint_0,
3375                                     Expr_Value (Type_High_Bound (C)) -
3376                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
3377                end if;
3378 
3379                Next_Index (X);
3380             end loop;
3381 
3382             return V;
3383 
3384          else
3385             return Uint_0;
3386          end if;
3387       end Count_Tasks;
3388 
3389       ----------------------------
3390       -- Delayed_Aspect_Present --
3391       ----------------------------
3392 
3393       function Delayed_Aspect_Present return Boolean is
3394          A    : Node_Id;
3395          A_Id : Aspect_Id;
3396 
3397       begin
3398          if Present (Aspect_Specifications (N)) then
3399             A    := First (Aspect_Specifications (N));
3400             A_Id := Get_Aspect_Id (Chars (Identifier (A)));
3401             while Present (A) loop
3402                if A_Id = Aspect_Alignment or else A_Id = Aspect_Address then
3403                   return True;
3404                end if;
3405 
3406                Next (A);
3407             end loop;
3408          end if;
3409 
3410          return False;
3411       end Delayed_Aspect_Present;
3412 
3413       --  Local variables
3414 
3415       Save_Ghost_Mode : constant Ghost_Mode_Type := Ghost_Mode;
3416       Related_Id      : Entity_Id;
3417 
3418    --  Start of processing for Analyze_Object_Declaration
3419 
3420    begin
3421       --  There are three kinds of implicit types generated by an
3422       --  object declaration:
3423 
3424       --   1. Those generated by the original Object Definition
3425 
3426       --   2. Those generated by the Expression
3427 
3428       --   3. Those used to constrain the Object Definition with the
3429       --      expression constraints when the definition is unconstrained.
3430 
3431       --  They must be generated in this order to avoid order of elaboration
3432       --  issues. Thus the first step (after entering the name) is to analyze
3433       --  the object definition.
3434 
3435       if Constant_Present (N) then
3436          Prev_Entity := Current_Entity_In_Scope (Id);
3437 
3438          if Present (Prev_Entity)
3439            and then
3440              --  If the homograph is an implicit subprogram, it is overridden
3441              --  by the current declaration.
3442 
3443              ((Is_Overloadable (Prev_Entity)
3444                 and then Is_Inherited_Operation (Prev_Entity))
3445 
3446                --  The current object is a discriminal generated for an entry
3447                --  family index. Even though the index is a constant, in this
3448                --  particular context there is no true constant redeclaration.
3449                --  Enter_Name will handle the visibility.
3450 
3451                or else
3452                  (Is_Discriminal (Id)
3453                    and then Ekind (Discriminal_Link (Id)) =
3454                                               E_Entry_Index_Parameter)
3455 
3456                --  The current object is the renaming for a generic declared
3457                --  within the instance.
3458 
3459                or else
3460                  (Ekind (Prev_Entity) = E_Package
3461                    and then Nkind (Parent (Prev_Entity)) =
3462                                                N_Package_Renaming_Declaration
3463                    and then not Comes_From_Source (Prev_Entity)
3464                    and then
3465                      Is_Generic_Instance (Renamed_Entity (Prev_Entity)))
3466 
3467                --  The entity may be a homonym of a private component of the
3468                --  enclosing protected object, for which we create a local
3469                --  renaming declaration. The declaration is legal, even if
3470                --  useless when it just captures that component.
3471 
3472                or else
3473                  (Ekind (Scope (Current_Scope)) = E_Protected_Type
3474                    and then Nkind (Parent (Prev_Entity)) =
3475                               N_Object_Renaming_Declaration))
3476          then
3477             Prev_Entity := Empty;
3478          end if;
3479       end if;
3480 
3481       --  The object declaration is Ghost when it is subject to pragma Ghost or
3482       --  completes a deferred Ghost constant. Set the mode now to ensure that
3483       --  any nodes generated during analysis and expansion are properly marked
3484       --  as Ghost.
3485 
3486       Set_Ghost_Mode (N, Prev_Entity);
3487 
3488       if Present (Prev_Entity) then
3489          Constant_Redeclaration (Id, N, T);
3490 
3491          Generate_Reference (Prev_Entity, Id, 'c');
3492          Set_Completion_Referenced (Id);
3493 
3494          if Error_Posted (N) then
3495 
3496             --  Type mismatch or illegal redeclaration; do not analyze
3497             --  expression to avoid cascaded errors.
3498 
3499             T := Find_Type_Of_Object (Object_Definition (N), N);
3500             Set_Etype (Id, T);
3501             Set_Ekind (Id, E_Variable);
3502             goto Leave;
3503          end if;
3504 
3505       --  In the normal case, enter identifier at the start to catch premature
3506       --  usage in the initialization expression.
3507 
3508       else
3509          Generate_Definition (Id);
3510          Enter_Name (Id);
3511 
3512          Mark_Coextensions (N, Object_Definition (N));
3513 
3514          T := Find_Type_Of_Object (Object_Definition (N), N);
3515 
3516          if Nkind (Object_Definition (N)) = N_Access_Definition
3517            and then Present
3518                       (Access_To_Subprogram_Definition (Object_Definition (N)))
3519            and then Protected_Present
3520                       (Access_To_Subprogram_Definition (Object_Definition (N)))
3521          then
3522             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
3523          end if;
3524 
3525          if Error_Posted (Id) then
3526             Set_Etype (Id, T);
3527             Set_Ekind (Id, E_Variable);
3528             goto Leave;
3529          end if;
3530       end if;
3531 
3532       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
3533       --  out some static checks.
3534 
3535       if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (T) then
3536 
3537          --  In case of aggregates we must also take care of the correct
3538          --  initialization of nested aggregates bug this is done at the
3539          --  point of the analysis of the aggregate (see sem_aggr.adb) ???
3540 
3541          if Present (Expression (N))
3542            and then Nkind (Expression (N)) = N_Aggregate
3543          then
3544             null;
3545 
3546          else
3547             declare
3548                Save_Typ : constant Entity_Id := Etype (Id);
3549             begin
3550                Set_Etype (Id, T); --  Temp. decoration for static checks
3551                Null_Exclusion_Static_Checks (N);
3552                Set_Etype (Id, Save_Typ);
3553             end;
3554          end if;
3555       end if;
3556 
3557       --  Object is marked pure if it is in a pure scope
3558 
3559       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3560 
3561       --  If deferred constant, make sure context is appropriate. We detect
3562       --  a deferred constant as a constant declaration with no expression.
3563       --  A deferred constant can appear in a package body if its completion
3564       --  is by means of an interface pragma.
3565 
3566       if Constant_Present (N) and then No (E) then
3567 
3568          --  A deferred constant may appear in the declarative part of the
3569          --  following constructs:
3570 
3571          --     blocks
3572          --     entry bodies
3573          --     extended return statements
3574          --     package specs
3575          --     package bodies
3576          --     subprogram bodies
3577          --     task bodies
3578 
3579          --  When declared inside a package spec, a deferred constant must be
3580          --  completed by a full constant declaration or pragma Import. In all
3581          --  other cases, the only proper completion is pragma Import. Extended
3582          --  return statements are flagged as invalid contexts because they do
3583          --  not have a declarative part and so cannot accommodate the pragma.
3584 
3585          if Ekind (Current_Scope) = E_Return_Statement then
3586             Error_Msg_N
3587               ("invalid context for deferred constant declaration (RM 7.4)",
3588                N);
3589             Error_Msg_N
3590               ("\declaration requires an initialization expression",
3591                 N);
3592             Set_Constant_Present (N, False);
3593 
3594          --  In Ada 83, deferred constant must be of private type
3595 
3596          elsif not Is_Private_Type (T) then
3597             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
3598                Error_Msg_N
3599                  ("(Ada 83) deferred constant must be private type", N);
3600             end if;
3601          end if;
3602 
3603       --  If not a deferred constant, then the object declaration freezes
3604       --  its type, unless the object is of an anonymous type and has delayed
3605       --  aspects. In that case the type is frozen when the object itself is.
3606 
3607       else
3608          Check_Fully_Declared (T, N);
3609 
3610          if Has_Delayed_Aspects (Id)
3611            and then Is_Array_Type (T)
3612            and then Is_Itype (T)
3613          then
3614             Set_Has_Delayed_Freeze (T);
3615          else
3616             Freeze_Before (N, T);
3617          end if;
3618       end if;
3619 
3620       --  If the object was created by a constrained array definition, then
3621       --  set the link in both the anonymous base type and anonymous subtype
3622       --  that are built to represent the array type to point to the object.
3623 
3624       if Nkind (Object_Definition (Declaration_Node (Id))) =
3625                         N_Constrained_Array_Definition
3626       then
3627          Set_Related_Array_Object (T, Id);
3628          Set_Related_Array_Object (Base_Type (T), Id);
3629       end if;
3630 
3631       --  Special checks for protected objects not at library level
3632 
3633       if Has_Protected (T) and then not Is_Library_Level_Entity (Id) then
3634          Check_Restriction (No_Local_Protected_Objects, Id);
3635 
3636          --  Protected objects with interrupt handlers must be at library level
3637 
3638          --  Ada 2005: This test is not needed (and the corresponding clause
3639          --  in the RM is removed) because accessibility checks are sufficient
3640          --  to make handlers not at the library level illegal.
3641 
3642          --  AI05-0303: The AI is in fact a binding interpretation, and thus
3643          --  applies to the '95 version of the language as well.
3644 
3645          if Is_Protected_Type (T)
3646            and then Has_Interrupt_Handler (T)
3647            and then Ada_Version < Ada_95
3648          then
3649             Error_Msg_N
3650               ("interrupt object can only be declared at library level", Id);
3651          end if;
3652       end if;
3653 
3654       --  Check for violation of No_Local_Timing_Events
3655 
3656       if Has_Timing_Event (T) and then not Is_Library_Level_Entity (Id) then
3657          Check_Restriction (No_Local_Timing_Events, Id);
3658       end if;
3659 
3660       --  The actual subtype of the object is the nominal subtype, unless
3661       --  the nominal one is unconstrained and obtained from the expression.
3662 
3663       Act_T := T;
3664 
3665       --  These checks should be performed before the initialization expression
3666       --  is considered, so that the Object_Definition node is still the same
3667       --  as in source code.
3668 
3669       --  In SPARK, the nominal subtype is always given by a subtype mark
3670       --  and must not be unconstrained. (The only exception to this is the
3671       --  acceptance of declarations of constants of type String.)
3672 
3673       if not Nkind_In (Object_Definition (N), N_Expanded_Name, N_Identifier)
3674       then
3675          Check_SPARK_05_Restriction
3676            ("subtype mark required", Object_Definition (N));
3677 
3678       elsif Is_Array_Type (T)
3679         and then not Is_Constrained (T)
3680         and then T /= Standard_String
3681       then
3682          Check_SPARK_05_Restriction
3683            ("subtype mark of constrained type expected",
3684             Object_Definition (N));
3685       end if;
3686 
3687       --  There are no aliased objects in SPARK
3688 
3689       if Aliased_Present (N) then
3690          Check_SPARK_05_Restriction ("aliased object is not allowed", N);
3691       end if;
3692 
3693       --  Process initialization expression if present and not in error
3694 
3695       if Present (E) and then E /= Error then
3696 
3697          --  Generate an error in case of CPP class-wide object initialization.
3698          --  Required because otherwise the expansion of the class-wide
3699          --  assignment would try to use 'size to initialize the object
3700          --  (primitive that is not available in CPP tagged types).
3701 
3702          if Is_Class_Wide_Type (Act_T)
3703            and then
3704              (Is_CPP_Class (Root_Type (Etype (Act_T)))
3705                or else
3706                  (Present (Full_View (Root_Type (Etype (Act_T))))
3707                    and then
3708                      Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
3709          then
3710             Error_Msg_N
3711               ("predefined assignment not available for 'C'P'P tagged types",
3712                E);
3713          end if;
3714 
3715          Mark_Coextensions (N, E);
3716          Analyze (E);
3717 
3718          --  In case of errors detected in the analysis of the expression,
3719          --  decorate it with the expected type to avoid cascaded errors
3720 
3721          if No (Etype (E)) then
3722             Set_Etype (E, T);
3723          end if;
3724 
3725          --  If an initialization expression is present, then we set the
3726          --  Is_True_Constant flag. It will be reset if this is a variable
3727          --  and it is indeed modified.
3728 
3729          Set_Is_True_Constant (Id, True);
3730 
3731          --  If we are analyzing a constant declaration, set its completion
3732          --  flag after analyzing and resolving the expression.
3733 
3734          if Constant_Present (N) then
3735             Set_Has_Completion (Id);
3736          end if;
3737 
3738          --  Set type and resolve (type may be overridden later on). Note:
3739          --  Ekind (Id) must still be E_Void at this point so that incorrect
3740          --  early usage within E is properly diagnosed.
3741 
3742          Set_Etype (Id, T);
3743 
3744          --  If the expression is an aggregate we must look ahead to detect
3745          --  the possible presence of an address clause, and defer resolution
3746          --  and expansion of the aggregate to the freeze point of the entity.
3747 
3748          --  This is not always legal because the aggregate may contain other
3749          --  references that need freezing, e.g. references to other entities
3750          --  with address clauses. In any case, when compiling with -gnatI the
3751          --  presence of the address clause must be ignored.
3752 
3753          if Comes_From_Source (N)
3754            and then Expander_Active
3755            and then Nkind (E) = N_Aggregate
3756            and then
3757              ((Present (Following_Address_Clause (N))
3758                             and then not Ignore_Rep_Clauses)
3759               or else Delayed_Aspect_Present)
3760          then
3761             Set_Etype (E, T);
3762 
3763          else
3764             Resolve (E, T);
3765          end if;
3766 
3767          --  No further action needed if E is a call to an inlined function
3768          --  which returns an unconstrained type and it has been expanded into
3769          --  a procedure call. In that case N has been replaced by an object
3770          --  declaration without initializing expression and it has been
3771          --  analyzed (see Expand_Inlined_Call).
3772 
3773          if Back_End_Inlining
3774            and then Expander_Active
3775            and then Nkind (E) = N_Function_Call
3776            and then Nkind (Name (E)) in N_Has_Entity
3777            and then Is_Inlined (Entity (Name (E)))
3778            and then not Is_Constrained (Etype (E))
3779            and then Analyzed (N)
3780            and then No (Expression (N))
3781          then
3782             Ghost_Mode := Save_Ghost_Mode;
3783             return;
3784          end if;
3785 
3786          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3787          --  node (which was marked already-analyzed), we need to set the type
3788          --  to something other than Any_Access in order to keep gigi happy.
3789 
3790          if Etype (E) = Any_Access then
3791             Set_Etype (E, T);
3792          end if;
3793 
3794          --  If the object is an access to variable, the initialization
3795          --  expression cannot be an access to constant.
3796 
3797          if Is_Access_Type (T)
3798            and then not Is_Access_Constant (T)
3799            and then Is_Access_Type (Etype (E))
3800            and then Is_Access_Constant (Etype (E))
3801          then
3802             Error_Msg_N
3803               ("access to variable cannot be initialized with an "
3804                & "access-to-constant expression", E);
3805          end if;
3806 
3807          if not Assignment_OK (N) then
3808             Check_Initialization (T, E);
3809          end if;
3810 
3811          Check_Unset_Reference (E);
3812 
3813          --  If this is a variable, then set current value. If this is a
3814          --  declared constant of a scalar type with a static expression,
3815          --  indicate that it is always valid.
3816 
3817          if not Constant_Present (N) then
3818             if Compile_Time_Known_Value (E) then
3819                Set_Current_Value (Id, E);
3820             end if;
3821 
3822          elsif Is_Scalar_Type (T) and then Is_OK_Static_Expression (E) then
3823             Set_Is_Known_Valid (Id);
3824          end if;
3825 
3826          --  Deal with setting of null flags
3827 
3828          if Is_Access_Type (T) then
3829             if Known_Non_Null (E) then
3830                Set_Is_Known_Non_Null (Id, True);
3831             elsif Known_Null (E) and then not Can_Never_Be_Null (Id) then
3832                Set_Is_Known_Null (Id, True);
3833             end if;
3834          end if;
3835 
3836          --  Check incorrect use of dynamically tagged expressions
3837 
3838          if Is_Tagged_Type (T) then
3839             Check_Dynamically_Tagged_Expression
3840               (Expr        => E,
3841                Typ         => T,
3842                Related_Nod => N);
3843          end if;
3844 
3845          Apply_Scalar_Range_Check (E, T);
3846          Apply_Static_Length_Check (E, T);
3847 
3848          if Nkind (Original_Node (N)) = N_Object_Declaration
3849            and then Comes_From_Source (Original_Node (N))
3850 
3851            --  Only call test if needed
3852 
3853            and then Restriction_Check_Required (SPARK_05)
3854            and then not Is_SPARK_05_Initialization_Expr (Original_Node (E))
3855          then
3856             Check_SPARK_05_Restriction
3857               ("initialization expression is not appropriate", E);
3858          end if;
3859 
3860          --  A formal parameter of a specific tagged type whose related
3861          --  subprogram is subject to pragma Extensions_Visible with value
3862          --  "False" cannot be implicitly converted to a class-wide type by
3863          --  means of an initialization expression (SPARK RM 6.1.7(3)). Do
3864          --  not consider internally generated expressions.
3865 
3866          if Is_Class_Wide_Type (T)
3867            and then Comes_From_Source (E)
3868            and then Is_EVF_Expression (E)
3869          then
3870             Error_Msg_N
3871               ("formal parameter cannot be implicitly converted to "
3872                & "class-wide type when Extensions_Visible is False", E);
3873          end if;
3874       end if;
3875 
3876       --  If the No_Streams restriction is set, check that the type of the
3877       --  object is not, and does not contain, any subtype derived from
3878       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3879       --  Has_Stream just for efficiency reasons. There is no point in
3880       --  spending time on a Has_Stream check if the restriction is not set.
3881 
3882       if Restriction_Check_Required (No_Streams) then
3883          if Has_Stream (T) then
3884             Check_Restriction (No_Streams, N);
3885          end if;
3886       end if;
3887 
3888       --  Deal with predicate check before we start to do major rewriting. It
3889       --  is OK to initialize and then check the initialized value, since the
3890       --  object goes out of scope if we get a predicate failure. Note that we
3891       --  do this in the analyzer and not the expander because the analyzer
3892       --  does some substantial rewriting in some cases.
3893 
3894       --  We need a predicate check if the type has predicates that are not
3895       --  ignored, and if either there is an initializing expression, or for
3896       --  default initialization when we have at least one case of an explicit
3897       --  default initial value and then this is not an internal declaration
3898       --  whose initialization comes later (as for an aggregate expansion).
3899 
3900       if not Suppress_Assignment_Checks (N)
3901         and then Present (Predicate_Function (T))
3902         and then not Predicates_Ignored (T)
3903         and then not No_Initialization (N)
3904         and then
3905           (Present (E)
3906             or else
3907               Is_Partially_Initialized_Type (T, Include_Implicit => False))
3908       then
3909          --  If the type has a static predicate and the expression is known at
3910          --  compile time, see if the expression satisfies the predicate.
3911 
3912          if Present (E) then
3913             Check_Expression_Against_Static_Predicate (E, T);
3914          end if;
3915 
3916          --  If the type is a null record and there is no explicit initial
3917          --  expression, no predicate check applies.
3918 
3919          if No (E) and then Is_Null_Record_Type (T) then
3920             null;
3921 
3922          else
3923             Insert_After (N,
3924               Make_Predicate_Check (T, New_Occurrence_Of (Id, Loc)));
3925          end if;
3926       end if;
3927 
3928       --  Case of unconstrained type
3929 
3930       if not Is_Definite_Subtype (T) then
3931 
3932          --  In SPARK, a declaration of unconstrained type is allowed
3933          --  only for constants of type string.
3934 
3935          if Is_String_Type (T) and then not Constant_Present (N) then
3936             Check_SPARK_05_Restriction
3937               ("declaration of object of unconstrained type not allowed", N);
3938          end if;
3939 
3940          --  Nothing to do in deferred constant case
3941 
3942          if Constant_Present (N) and then No (E) then
3943             null;
3944 
3945          --  Case of no initialization present
3946 
3947          elsif No (E) then
3948             if No_Initialization (N) then
3949                null;
3950 
3951             elsif Is_Class_Wide_Type (T) then
3952                Error_Msg_N
3953                  ("initialization required in class-wide declaration ", N);
3954 
3955             else
3956                Error_Msg_N
3957                  ("unconstrained subtype not allowed (need initialization)",
3958                   Object_Definition (N));
3959 
3960                if Is_Record_Type (T) and then Has_Discriminants (T) then
3961                   Error_Msg_N
3962                     ("\provide initial value or explicit discriminant values",
3963                      Object_Definition (N));
3964 
3965                   Error_Msg_NE
3966                     ("\or give default discriminant values for type&",
3967                      Object_Definition (N), T);
3968 
3969                elsif Is_Array_Type (T) then
3970                   Error_Msg_N
3971                     ("\provide initial value or explicit array bounds",
3972                      Object_Definition (N));
3973                end if;
3974             end if;
3975 
3976          --  Case of initialization present but in error. Set initial
3977          --  expression as absent (but do not make above complaints)
3978 
3979          elsif E = Error then
3980             Set_Expression (N, Empty);
3981             E := Empty;
3982 
3983          --  Case of initialization present
3984 
3985          else
3986             --  Check restrictions in Ada 83
3987 
3988             if not Constant_Present (N) then
3989 
3990                --  Unconstrained variables not allowed in Ada 83 mode
3991 
3992                if Ada_Version = Ada_83
3993                  and then Comes_From_Source (Object_Definition (N))
3994                then
3995                   Error_Msg_N
3996                     ("(Ada 83) unconstrained variable not allowed",
3997                      Object_Definition (N));
3998                end if;
3999             end if;
4000 
4001             --  Now we constrain the variable from the initializing expression
4002 
4003             --  If the expression is an aggregate, it has been expanded into
4004             --  individual assignments. Retrieve the actual type from the
4005             --  expanded construct.
4006 
4007             if Is_Array_Type (T)
4008               and then No_Initialization (N)
4009               and then Nkind (Original_Node (E)) = N_Aggregate
4010             then
4011                Act_T := Etype (E);
4012 
4013             --  In case of class-wide interface object declarations we delay
4014             --  the generation of the equivalent record type declarations until
4015             --  its expansion because there are cases in they are not required.
4016 
4017             elsif Is_Interface (T) then
4018                null;
4019 
4020             --  In GNATprove mode, Expand_Subtype_From_Expr does nothing. Thus,
4021             --  we should prevent the generation of another Itype with the
4022             --  same name as the one already generated, or we end up with
4023             --  two identical types in GNATprove.
4024 
4025             elsif GNATprove_Mode then
4026                null;
4027 
4028             --  If the type is an unchecked union, no subtype can be built from
4029             --  the expression. Rewrite declaration as a renaming, which the
4030             --  back-end can handle properly. This is a rather unusual case,
4031             --  because most unchecked_union declarations have default values
4032             --  for discriminants and are thus not indefinite.
4033 
4034             elsif Is_Unchecked_Union (T) then
4035                if Constant_Present (N) or else Nkind (E) = N_Function_Call then
4036                   Set_Ekind (Id, E_Constant);
4037                else
4038                   Set_Ekind (Id, E_Variable);
4039                end if;
4040 
4041                --  An object declared within a Ghost region is automatically
4042                --  Ghost (SPARK RM 6.9(2)).
4043 
4044                if Ghost_Mode > None then
4045                   Set_Is_Ghost_Entity (Id);
4046 
4047                   --  The Ghost policy in effect at the point of declaration
4048                   --  and at the point of completion must match
4049                   --  (SPARK RM 6.9(14)).
4050 
4051                   if Present (Prev_Entity)
4052                     and then Is_Ghost_Entity (Prev_Entity)
4053                   then
4054                      Check_Ghost_Completion (Prev_Entity, Id);
4055                   end if;
4056                end if;
4057 
4058                Rewrite (N,
4059                  Make_Object_Renaming_Declaration (Loc,
4060                    Defining_Identifier => Id,
4061                    Subtype_Mark        => New_Occurrence_Of (T, Loc),
4062                    Name                => E));
4063 
4064                Set_Renamed_Object (Id, E);
4065                Freeze_Before (N, T);
4066                Set_Is_Frozen (Id);
4067 
4068                Ghost_Mode := Save_Ghost_Mode;
4069                return;
4070 
4071             else
4072                --  Ensure that the generated subtype has a unique external name
4073                --  when the related object is public. This guarantees that the
4074                --  subtype and its bounds will not be affected by switches or
4075                --  pragmas that may offset the internal counter due to extra
4076                --  generated code.
4077 
4078                if Is_Public (Id) then
4079                   Related_Id := Id;
4080                else
4081                   Related_Id := Empty;
4082                end if;
4083 
4084                Expand_Subtype_From_Expr
4085                  (N             => N,
4086                   Unc_Type      => T,
4087                   Subtype_Indic => Object_Definition (N),
4088                   Exp           => E,
4089                   Related_Id    => Related_Id);
4090 
4091                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
4092             end if;
4093 
4094             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
4095 
4096             if Aliased_Present (N) then
4097                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
4098             end if;
4099 
4100             Freeze_Before (N, Act_T);
4101             Freeze_Before (N, T);
4102          end if;
4103 
4104       elsif Is_Array_Type (T)
4105         and then No_Initialization (N)
4106         and then (Nkind (Original_Node (E)) = N_Aggregate
4107                    or else (Nkind (Original_Node (E)) = N_Qualified_Expression
4108                              and then Nkind (Original_Node (Expression
4109                                         (Original_Node (E)))) = N_Aggregate))
4110       then
4111          if not Is_Entity_Name (Object_Definition (N)) then
4112             Act_T := Etype (E);
4113             Check_Compile_Time_Size (Act_T);
4114 
4115             if Aliased_Present (N) then
4116                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
4117             end if;
4118          end if;
4119 
4120          --  When the given object definition and the aggregate are specified
4121          --  independently, and their lengths might differ do a length check.
4122          --  This cannot happen if the aggregate is of the form (others =>...)
4123 
4124          if not Is_Constrained (T) then
4125             null;
4126 
4127          elsif Nkind (E) = N_Raise_Constraint_Error then
4128 
4129             --  Aggregate is statically illegal. Place back in declaration
4130 
4131             Set_Expression (N, E);
4132             Set_No_Initialization (N, False);
4133 
4134          elsif T = Etype (E) then
4135             null;
4136 
4137          elsif Nkind (E) = N_Aggregate
4138            and then Present (Component_Associations (E))
4139            and then Present (Choices (First (Component_Associations (E))))
4140            and then Nkind (First
4141             (Choices (First (Component_Associations (E))))) = N_Others_Choice
4142          then
4143             null;
4144 
4145          else
4146             Apply_Length_Check (E, T);
4147          end if;
4148 
4149       --  If the type is limited unconstrained with defaulted discriminants and
4150       --  there is no expression, then the object is constrained by the
4151       --  defaults, so it is worthwhile building the corresponding subtype.
4152 
4153       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
4154         and then not Is_Constrained (T)
4155         and then Has_Discriminants (T)
4156       then
4157          if No (E) then
4158             Act_T := Build_Default_Subtype (T, N);
4159          else
4160             --  Ada 2005: A limited object may be initialized by means of an
4161             --  aggregate. If the type has default discriminants it has an
4162             --  unconstrained nominal type, Its actual subtype will be obtained
4163             --  from the aggregate, and not from the default discriminants.
4164 
4165             Act_T := Etype (E);
4166          end if;
4167 
4168          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
4169 
4170       elsif Nkind (E) = N_Function_Call
4171         and then Constant_Present (N)
4172         and then Has_Unconstrained_Elements (Etype (E))
4173       then
4174          --  The back-end has problems with constants of a discriminated type
4175          --  with defaults, if the initial value is a function call. We
4176          --  generate an intermediate temporary that will receive a reference
4177          --  to the result of the call. The initialization expression then
4178          --  becomes a dereference of that temporary.
4179 
4180          Remove_Side_Effects (E);
4181 
4182       --  If this is a constant declaration of an unconstrained type and
4183       --  the initialization is an aggregate, we can use the subtype of the
4184       --  aggregate for the declared entity because it is immutable.
4185 
4186       elsif not Is_Constrained (T)
4187         and then Has_Discriminants (T)
4188         and then Constant_Present (N)
4189         and then not Has_Unchecked_Union (T)
4190         and then Nkind (E) = N_Aggregate
4191       then
4192          Act_T := Etype (E);
4193       end if;
4194 
4195       --  Check No_Wide_Characters restriction
4196 
4197       Check_Wide_Character_Restriction (T, Object_Definition (N));
4198 
4199       --  Indicate this is not set in source. Certainly true for constants, and
4200       --  true for variables so far (will be reset for a variable if and when
4201       --  we encounter a modification in the source).
4202 
4203       Set_Never_Set_In_Source (Id);
4204 
4205       --  Now establish the proper kind and type of the object
4206 
4207       if Constant_Present (N) then
4208          Set_Ekind            (Id, E_Constant);
4209          Set_Is_True_Constant (Id);
4210 
4211       else
4212          Set_Ekind (Id, E_Variable);
4213 
4214          --  A variable is set as shared passive if it appears in a shared
4215          --  passive package, and is at the outer level. This is not done for
4216          --  entities generated during expansion, because those are always
4217          --  manipulated locally.
4218 
4219          if Is_Shared_Passive (Current_Scope)
4220            and then Is_Library_Level_Entity (Id)
4221            and then Comes_From_Source (Id)
4222          then
4223             Set_Is_Shared_Passive (Id);
4224             Check_Shared_Var (Id, T, N);
4225          end if;
4226 
4227          --  Set Has_Initial_Value if initializing expression present. Note
4228          --  that if there is no initializing expression, we leave the state
4229          --  of this flag unchanged (usually it will be False, but notably in
4230          --  the case of exception choice variables, it will already be true).
4231 
4232          if Present (E) then
4233             Set_Has_Initial_Value (Id);
4234          end if;
4235       end if;
4236 
4237       --  Initialize alignment and size and capture alignment setting
4238 
4239       Init_Alignment               (Id);
4240       Init_Esize                   (Id);
4241       Set_Optimize_Alignment_Flags (Id);
4242 
4243       --  An object declared within a Ghost region is automatically Ghost
4244       --  (SPARK RM 6.9(2)).
4245 
4246       if Ghost_Mode > None
4247         or else (Present (Prev_Entity) and then Is_Ghost_Entity (Prev_Entity))
4248       then
4249          Set_Is_Ghost_Entity (Id);
4250 
4251          --  The Ghost policy in effect at the point of declaration and at the
4252          --  point of completion must match (SPARK RM 6.9(14)).
4253 
4254          if Present (Prev_Entity) and then Is_Ghost_Entity (Prev_Entity) then
4255             Check_Ghost_Completion (Prev_Entity, Id);
4256          end if;
4257       end if;
4258 
4259       --  Deal with aliased case
4260 
4261       if Aliased_Present (N) then
4262          Set_Is_Aliased (Id);
4263 
4264          --  If the object is aliased and the type is unconstrained with
4265          --  defaulted discriminants and there is no expression, then the
4266          --  object is constrained by the defaults, so it is worthwhile
4267          --  building the corresponding subtype.
4268 
4269          --  Ada 2005 (AI-363): If the aliased object is discriminated and
4270          --  unconstrained, then only establish an actual subtype if the
4271          --  nominal subtype is indefinite. In definite cases the object is
4272          --  unconstrained in Ada 2005.
4273 
4274          if No (E)
4275            and then Is_Record_Type (T)
4276            and then not Is_Constrained (T)
4277            and then Has_Discriminants (T)
4278            and then (Ada_Version < Ada_2005
4279                       or else not Is_Definite_Subtype (T))
4280          then
4281             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
4282          end if;
4283       end if;
4284 
4285       --  Now we can set the type of the object
4286 
4287       Set_Etype (Id, Act_T);
4288 
4289       --  Non-constant object is marked to be treated as volatile if type is
4290       --  volatile and we clear the Current_Value setting that may have been
4291       --  set above. Doing so for constants isn't required and might interfere
4292       --  with possible uses of the object as a static expression in contexts
4293       --  incompatible with volatility (e.g. as a case-statement alternative).
4294 
4295       if Ekind (Id) /= E_Constant and then Treat_As_Volatile (Etype (Id)) then
4296          Set_Treat_As_Volatile (Id);
4297          Set_Current_Value (Id, Empty);
4298       end if;
4299 
4300       --  Deal with controlled types
4301 
4302       if Has_Controlled_Component (Etype (Id))
4303         or else Is_Controlled (Etype (Id))
4304       then
4305          if not Is_Library_Level_Entity (Id) then
4306             Check_Restriction (No_Nested_Finalization, N);
4307          else
4308             Validate_Controlled_Object (Id);
4309          end if;
4310       end if;
4311 
4312       if Has_Task (Etype (Id)) then
4313          Check_Restriction (No_Tasking, N);
4314 
4315          --  Deal with counting max tasks
4316 
4317          --  Nothing to do if inside a generic
4318 
4319          if Inside_A_Generic then
4320             null;
4321 
4322          --  If library level entity, then count tasks
4323 
4324          elsif Is_Library_Level_Entity (Id) then
4325             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
4326 
4327          --  If not library level entity, then indicate we don't know max
4328          --  tasks and also check task hierarchy restriction and blocking
4329          --  operation (since starting a task is definitely blocking).
4330 
4331          else
4332             Check_Restriction (Max_Tasks, N);
4333             Check_Restriction (No_Task_Hierarchy, N);
4334             Check_Potentially_Blocking_Operation (N);
4335          end if;
4336 
4337          --  A rather specialized test. If we see two tasks being declared
4338          --  of the same type in the same object declaration, and the task
4339          --  has an entry with an address clause, we know that program error
4340          --  will be raised at run time since we can't have two tasks with
4341          --  entries at the same address.
4342 
4343          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
4344             declare
4345                E : Entity_Id;
4346 
4347             begin
4348                E := First_Entity (Etype (Id));
4349                while Present (E) loop
4350                   if Ekind (E) = E_Entry
4351                     and then Present (Get_Attribute_Definition_Clause
4352                                         (E, Attribute_Address))
4353                   then
4354                      Error_Msg_Warn := SPARK_Mode /= On;
4355                      Error_Msg_N
4356                        ("more than one task with same entry address<<", N);
4357                      Error_Msg_N ("\Program_Error [<<", N);
4358                      Insert_Action (N,
4359                        Make_Raise_Program_Error (Loc,
4360                          Reason => PE_Duplicated_Entry_Address));
4361                      exit;
4362                   end if;
4363 
4364                   Next_Entity (E);
4365                end loop;
4366             end;
4367          end if;
4368       end if;
4369 
4370       --  Some simple constant-propagation: if the expression is a constant
4371       --  string initialized with a literal, share the literal. This avoids
4372       --  a run-time copy.
4373 
4374       if Present (E)
4375         and then Is_Entity_Name (E)
4376         and then Ekind (Entity (E)) = E_Constant
4377         and then Base_Type (Etype (E)) = Standard_String
4378       then
4379          declare
4380             Val : constant Node_Id := Constant_Value (Entity (E));
4381          begin
4382             if Present (Val) and then Nkind (Val) = N_String_Literal then
4383                Rewrite (E, New_Copy (Val));
4384             end if;
4385          end;
4386       end if;
4387 
4388       --  Another optimization: if the nominal subtype is unconstrained and
4389       --  the expression is a function call that returns an unconstrained
4390       --  type, rewrite the declaration as a renaming of the result of the
4391       --  call. The exceptions below are cases where the copy is expected,
4392       --  either by the back end (Aliased case) or by the semantics, as for
4393       --  initializing controlled types or copying tags for classwide types.
4394 
4395       if Present (E)
4396         and then Nkind (E) = N_Explicit_Dereference
4397         and then Nkind (Original_Node (E)) = N_Function_Call
4398         and then not Is_Library_Level_Entity (Id)
4399         and then not Is_Constrained (Underlying_Type (T))
4400         and then not Is_Aliased (Id)
4401         and then not Is_Class_Wide_Type (T)
4402         and then not Is_Controlled_Active (T)
4403         and then not Has_Controlled_Component (Base_Type (T))
4404         and then Expander_Active
4405       then
4406          Rewrite (N,
4407            Make_Object_Renaming_Declaration (Loc,
4408              Defining_Identifier => Id,
4409              Access_Definition   => Empty,
4410              Subtype_Mark        => New_Occurrence_Of
4411                                       (Base_Type (Etype (Id)), Loc),
4412              Name                => E));
4413 
4414          Set_Renamed_Object (Id, E);
4415 
4416          --  Force generation of debugging information for the constant and for
4417          --  the renamed function call.
4418 
4419          Set_Debug_Info_Needed (Id);
4420          Set_Debug_Info_Needed (Entity (Prefix (E)));
4421       end if;
4422 
4423       if Present (Prev_Entity)
4424         and then Is_Frozen (Prev_Entity)
4425         and then not Error_Posted (Id)
4426       then
4427          Error_Msg_N ("full constant declaration appears too late", N);
4428       end if;
4429 
4430       Check_Eliminated (Id);
4431 
4432       --  Deal with setting In_Private_Part flag if in private part
4433 
4434       if Ekind (Scope (Id)) = E_Package
4435         and then In_Private_Part (Scope (Id))
4436       then
4437          Set_In_Private_Part (Id);
4438       end if;
4439 
4440    <<Leave>>
4441       --  Initialize the refined state of a variable here because this is a
4442       --  common destination for legal and illegal object declarations.
4443 
4444       if Ekind (Id) = E_Variable then
4445          Set_Encapsulating_State (Id, Empty);
4446       end if;
4447 
4448       if Has_Aspects (N) then
4449          Analyze_Aspect_Specifications (N, Id);
4450       end if;
4451 
4452       Analyze_Dimension (N);
4453 
4454       --  Verify whether the object declaration introduces an illegal hidden
4455       --  state within a package subject to a null abstract state.
4456 
4457       if Ekind (Id) = E_Variable then
4458          Check_No_Hidden_State (Id);
4459       end if;
4460 
4461       Ghost_Mode := Save_Ghost_Mode;
4462    end Analyze_Object_Declaration;
4463 
4464    ---------------------------
4465    -- Analyze_Others_Choice --
4466    ---------------------------
4467 
4468    --  Nothing to do for the others choice node itself, the semantic analysis
4469    --  of the others choice will occur as part of the processing of the parent
4470 
4471    procedure Analyze_Others_Choice (N : Node_Id) is
4472       pragma Warnings (Off, N);
4473    begin
4474       null;
4475    end Analyze_Others_Choice;
4476 
4477    -------------------------------------------
4478    -- Analyze_Private_Extension_Declaration --
4479    -------------------------------------------
4480 
4481    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
4482       Indic       : constant Node_Id   := Subtype_Indication (N);
4483       T           : constant Entity_Id := Defining_Identifier (N);
4484       Iface       : Entity_Id;
4485       Iface_Elmt  : Elmt_Id;
4486       Parent_Base : Entity_Id;
4487       Parent_Type : Entity_Id;
4488 
4489    begin
4490       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
4491 
4492       if Is_Non_Empty_List (Interface_List (N)) then
4493          declare
4494             Intf : Node_Id;
4495             T    : Entity_Id;
4496 
4497          begin
4498             Intf := First (Interface_List (N));
4499             while Present (Intf) loop
4500                T := Find_Type_Of_Subtype_Indic (Intf);
4501 
4502                Diagnose_Interface (Intf, T);
4503                Next (Intf);
4504             end loop;
4505          end;
4506       end if;
4507 
4508       Generate_Definition (T);
4509 
4510       --  For other than Ada 2012, just enter the name in the current scope
4511 
4512       if Ada_Version < Ada_2012 then
4513          Enter_Name (T);
4514 
4515       --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
4516       --  case of private type that completes an incomplete type.
4517 
4518       else
4519          declare
4520             Prev : Entity_Id;
4521 
4522          begin
4523             Prev := Find_Type_Name (N);
4524 
4525             pragma Assert (Prev = T
4526               or else (Ekind (Prev) = E_Incomplete_Type
4527                         and then Present (Full_View (Prev))
4528                         and then Full_View (Prev) = T));
4529          end;
4530       end if;
4531 
4532       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
4533       Parent_Base := Base_Type (Parent_Type);
4534 
4535       if Parent_Type = Any_Type or else Etype (Parent_Type) = Any_Type then
4536          Set_Ekind (T, Ekind (Parent_Type));
4537          Set_Etype (T, Any_Type);
4538          goto Leave;
4539 
4540       elsif not Is_Tagged_Type (Parent_Type) then
4541          Error_Msg_N
4542            ("parent of type extension must be a tagged type ", Indic);
4543          goto Leave;
4544 
4545       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
4546          Error_Msg_N ("premature derivation of incomplete type", Indic);
4547          goto Leave;
4548 
4549       elsif Is_Concurrent_Type (Parent_Type) then
4550          Error_Msg_N
4551            ("parent type of a private extension cannot be a synchronized "
4552             & "tagged type (RM 3.9.1 (3/1))", N);
4553 
4554          Set_Etype              (T, Any_Type);
4555          Set_Ekind              (T, E_Limited_Private_Type);
4556          Set_Private_Dependents (T, New_Elmt_List);
4557          Set_Error_Posted       (T);
4558          goto Leave;
4559       end if;
4560 
4561       --  Perhaps the parent type should be changed to the class-wide type's
4562       --  specific type in this case to prevent cascading errors ???
4563 
4564       if Is_Class_Wide_Type (Parent_Type) then
4565          Error_Msg_N
4566            ("parent of type extension must not be a class-wide type", Indic);
4567          goto Leave;
4568       end if;
4569 
4570       if (not Is_Package_Or_Generic_Package (Current_Scope)
4571            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
4572         or else In_Private_Part (Current_Scope)
4573       then
4574          Error_Msg_N ("invalid context for private extension", N);
4575       end if;
4576 
4577       --  Set common attributes
4578 
4579       Set_Is_Pure          (T, Is_Pure (Current_Scope));
4580       Set_Scope            (T, Current_Scope);
4581       Set_Ekind            (T, E_Record_Type_With_Private);
4582       Init_Size_Align      (T);
4583       Set_Default_SSO      (T);
4584 
4585       Set_Etype            (T,                Parent_Base);
4586       Propagate_Concurrent_Flags (T, Parent_Base);
4587 
4588       Set_Convention       (T, Convention     (Parent_Type));
4589       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
4590       Set_Is_First_Subtype (T);
4591       Make_Class_Wide_Type (T);
4592 
4593       if Unknown_Discriminants_Present (N) then
4594          Set_Discriminant_Constraint (T, No_Elist);
4595       end if;
4596 
4597       Build_Derived_Record_Type (N, Parent_Type, T);
4598 
4599       --  A private extension inherits any class-wide invariants coming from a
4600       --  parent type or an interface. Note that the invariant procedure of the
4601       --  parent type should not be inherited because the private extension may
4602       --  define invariants of its own.
4603 
4604       if Has_Inheritable_Invariants (Parent_Type) then
4605          Set_Has_Inherited_Invariants (T);
4606 
4607       elsif Present (Interfaces (T)) then
4608          Iface_Elmt := First_Elmt (Interfaces (T));
4609          while Present (Iface_Elmt) loop
4610             Iface := Node (Iface_Elmt);
4611 
4612             if Has_Inheritable_Invariants (Iface) then
4613                Set_Has_Inherited_Invariants (T);
4614                exit;
4615             end if;
4616 
4617             Next_Elmt (Iface_Elmt);
4618          end loop;
4619       end if;
4620 
4621       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
4622       --  synchronized formal derived type.
4623 
4624       if Ada_Version >= Ada_2005 and then Synchronized_Present (N) then
4625          Set_Is_Limited_Record (T);
4626 
4627          --  Formal derived type case
4628 
4629          if Is_Generic_Type (T) then
4630 
4631             --  The parent must be a tagged limited type or a synchronized
4632             --  interface.
4633 
4634             if (not Is_Tagged_Type (Parent_Type)
4635                  or else not Is_Limited_Type (Parent_Type))
4636               and then
4637                 (not Is_Interface (Parent_Type)
4638                   or else not Is_Synchronized_Interface (Parent_Type))
4639             then
4640                Error_Msg_NE
4641                  ("parent type of & must be tagged limited or synchronized",
4642                   N, T);
4643             end if;
4644 
4645             --  The progenitors (if any) must be limited or synchronized
4646             --  interfaces.
4647 
4648             if Present (Interfaces (T)) then
4649                Iface_Elmt := First_Elmt (Interfaces (T));
4650                while Present (Iface_Elmt) loop
4651                   Iface := Node (Iface_Elmt);
4652 
4653                   if not Is_Limited_Interface (Iface)
4654                     and then not Is_Synchronized_Interface (Iface)
4655                   then
4656                      Error_Msg_NE
4657                        ("progenitor & must be limited or synchronized",
4658                         N, Iface);
4659                   end if;
4660 
4661                   Next_Elmt (Iface_Elmt);
4662                end loop;
4663             end if;
4664 
4665          --  Regular derived extension, the parent must be a limited or
4666          --  synchronized interface.
4667 
4668          else
4669             if not Is_Interface (Parent_Type)
4670               or else (not Is_Limited_Interface (Parent_Type)
4671                         and then not Is_Synchronized_Interface (Parent_Type))
4672             then
4673                Error_Msg_NE
4674                  ("parent type of & must be limited interface", N, T);
4675             end if;
4676          end if;
4677 
4678       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
4679       --  extension with a synchronized parent must be explicitly declared
4680       --  synchronized, because the full view will be a synchronized type.
4681       --  This must be checked before the check for limited types below,
4682       --  to ensure that types declared limited are not allowed to extend
4683       --  synchronized interfaces.
4684 
4685       elsif Is_Interface (Parent_Type)
4686         and then Is_Synchronized_Interface (Parent_Type)
4687         and then not Synchronized_Present (N)
4688       then
4689          Error_Msg_NE
4690            ("private extension of& must be explicitly synchronized",
4691              N, Parent_Type);
4692 
4693       elsif Limited_Present (N) then
4694          Set_Is_Limited_Record (T);
4695 
4696          if not Is_Limited_Type (Parent_Type)
4697            and then
4698              (not Is_Interface (Parent_Type)
4699                or else not Is_Limited_Interface (Parent_Type))
4700          then
4701             Error_Msg_NE ("parent type& of limited extension must be limited",
4702               N, Parent_Type);
4703          end if;
4704       end if;
4705 
4706    <<Leave>>
4707       if Has_Aspects (N) then
4708          Analyze_Aspect_Specifications (N, T);
4709       end if;
4710    end Analyze_Private_Extension_Declaration;
4711 
4712    ---------------------------------
4713    -- Analyze_Subtype_Declaration --
4714    ---------------------------------
4715 
4716    procedure Analyze_Subtype_Declaration
4717      (N    : Node_Id;
4718       Skip : Boolean := False)
4719    is
4720       Id       : constant Entity_Id := Defining_Identifier (N);
4721       R_Checks : Check_Result;
4722       T        : Entity_Id;
4723 
4724    begin
4725       Generate_Definition (Id);
4726       Set_Is_Pure (Id, Is_Pure (Current_Scope));
4727       Init_Size_Align (Id);
4728 
4729       --  The following guard condition on Enter_Name is to handle cases where
4730       --  the defining identifier has already been entered into the scope but
4731       --  the declaration as a whole needs to be analyzed.
4732 
4733       --  This case in particular happens for derived enumeration types. The
4734       --  derived enumeration type is processed as an inserted enumeration type
4735       --  declaration followed by a rewritten subtype declaration. The defining
4736       --  identifier, however, is entered into the name scope very early in the
4737       --  processing of the original type declaration and therefore needs to be
4738       --  avoided here, when the created subtype declaration is analyzed. (See
4739       --  Build_Derived_Types)
4740 
4741       --  This also happens when the full view of a private type is derived
4742       --  type with constraints. In this case the entity has been introduced
4743       --  in the private declaration.
4744 
4745       --  Finally this happens in some complex cases when validity checks are
4746       --  enabled, where the same subtype declaration may be analyzed twice.
4747       --  This can happen if the subtype is created by the pre-analysis of
4748       --  an attribute tht gives the range of a loop statement, and the loop
4749       --  itself appears within an if_statement that will be rewritten during
4750       --  expansion.
4751 
4752       if Skip
4753         or else (Present (Etype (Id))
4754                   and then (Is_Private_Type (Etype (Id))
4755                              or else Is_Task_Type (Etype (Id))
4756                              or else Is_Rewrite_Substitution (N)))
4757       then
4758          null;
4759 
4760       elsif Current_Entity (Id) = Id then
4761          null;
4762 
4763       else
4764          Enter_Name (Id);
4765       end if;
4766 
4767       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
4768 
4769       --  Class-wide equivalent types of records with unknown discriminants
4770       --  involve the generation of an itype which serves as the private view
4771       --  of a constrained record subtype. In such cases the base type of the
4772       --  current subtype we are processing is the private itype. Use the full
4773       --  of the private itype when decorating various attributes.
4774 
4775       if Is_Itype (T)
4776         and then Is_Private_Type (T)
4777         and then Present (Full_View (T))
4778       then
4779          T := Full_View (T);
4780       end if;
4781 
4782       --  Inherit common attributes
4783 
4784       Set_Is_Volatile       (Id, Is_Volatile       (T));
4785       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
4786       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
4787       Set_Convention        (Id, Convention        (T));
4788 
4789       --  If ancestor has predicates then so does the subtype, and in addition
4790       --  we must delay the freeze to properly arrange predicate inheritance.
4791 
4792       --  The Ancestor_Type test is really unpleasant, there seem to be cases
4793       --  in which T = ID, so the above tests and assignments do nothing???
4794 
4795       if Has_Predicates (T)
4796         or else (Present (Ancestor_Subtype (T))
4797                   and then Has_Predicates (Ancestor_Subtype (T)))
4798       then
4799          Set_Has_Predicates (Id);
4800          Set_Has_Delayed_Freeze (Id);
4801       end if;
4802 
4803       --  Subtype of Boolean cannot have a constraint in SPARK
4804 
4805       if Is_Boolean_Type (T)
4806         and then Nkind (Subtype_Indication (N)) = N_Subtype_Indication
4807       then
4808          Check_SPARK_05_Restriction
4809            ("subtype of Boolean cannot have constraint", N);
4810       end if;
4811 
4812       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4813          declare
4814             Cstr     : constant Node_Id := Constraint (Subtype_Indication (N));
4815             One_Cstr : Node_Id;
4816             Low      : Node_Id;
4817             High     : Node_Id;
4818 
4819          begin
4820             if Nkind (Cstr) = N_Index_Or_Discriminant_Constraint then
4821                One_Cstr := First (Constraints (Cstr));
4822                while Present (One_Cstr) loop
4823 
4824                   --  Index or discriminant constraint in SPARK must be a
4825                   --  subtype mark.
4826 
4827                   if not
4828                     Nkind_In (One_Cstr, N_Identifier, N_Expanded_Name)
4829                   then
4830                      Check_SPARK_05_Restriction
4831                        ("subtype mark required", One_Cstr);
4832 
4833                   --  String subtype must have a lower bound of 1 in SPARK.
4834                   --  Note that we do not need to test for the non-static case
4835                   --  here, since that was already taken care of in
4836                   --  Process_Range_Expr_In_Decl.
4837 
4838                   elsif Base_Type (T) = Standard_String then
4839                      Get_Index_Bounds (One_Cstr, Low, High);
4840 
4841                      if Is_OK_Static_Expression (Low)
4842                        and then Expr_Value (Low) /= 1
4843                      then
4844                         Check_SPARK_05_Restriction
4845                           ("String subtype must have lower bound of 1", N);
4846                      end if;
4847                   end if;
4848 
4849                   Next (One_Cstr);
4850                end loop;
4851             end if;
4852          end;
4853       end if;
4854 
4855       --  In the case where there is no constraint given in the subtype
4856       --  indication, Process_Subtype just returns the Subtype_Mark, so its
4857       --  semantic attributes must be established here.
4858 
4859       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
4860          Set_Etype (Id, Base_Type (T));
4861 
4862          --  Subtype of unconstrained array without constraint is not allowed
4863          --  in SPARK.
4864 
4865          if Is_Array_Type (T) and then not Is_Constrained (T) then
4866             Check_SPARK_05_Restriction
4867               ("subtype of unconstrained array must have constraint", N);
4868          end if;
4869 
4870          case Ekind (T) is
4871             when Array_Kind =>
4872                Set_Ekind                       (Id, E_Array_Subtype);
4873                Copy_Array_Subtype_Attributes   (Id, T);
4874 
4875             when Decimal_Fixed_Point_Kind =>
4876                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
4877                Set_Digits_Value         (Id, Digits_Value       (T));
4878                Set_Delta_Value          (Id, Delta_Value        (T));
4879                Set_Scale_Value          (Id, Scale_Value        (T));
4880                Set_Small_Value          (Id, Small_Value        (T));
4881                Set_Scalar_Range         (Id, Scalar_Range       (T));
4882                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
4883                Set_Is_Constrained       (Id, Is_Constrained     (T));
4884                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4885                Set_RM_Size              (Id, RM_Size            (T));
4886 
4887             when Enumeration_Kind =>
4888                Set_Ekind                (Id, E_Enumeration_Subtype);
4889                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
4890                Set_Scalar_Range         (Id, Scalar_Range       (T));
4891                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
4892                Set_Is_Constrained       (Id, Is_Constrained     (T));
4893                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4894                Set_RM_Size              (Id, RM_Size            (T));
4895                Inherit_Predicate_Flags  (Id, T);
4896 
4897             when Ordinary_Fixed_Point_Kind =>
4898                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
4899                Set_Scalar_Range         (Id, Scalar_Range       (T));
4900                Set_Small_Value          (Id, Small_Value        (T));
4901                Set_Delta_Value          (Id, Delta_Value        (T));
4902                Set_Is_Constrained       (Id, Is_Constrained     (T));
4903                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4904                Set_RM_Size              (Id, RM_Size            (T));
4905 
4906             when Float_Kind =>
4907                Set_Ekind                (Id, E_Floating_Point_Subtype);
4908                Set_Scalar_Range         (Id, Scalar_Range       (T));
4909                Set_Digits_Value         (Id, Digits_Value       (T));
4910                Set_Is_Constrained       (Id, Is_Constrained     (T));
4911 
4912                --  If the floating point type has dimensions, these will be
4913                --  inherited subsequently when Analyze_Dimensions is called.
4914 
4915             when Signed_Integer_Kind =>
4916                Set_Ekind                (Id, E_Signed_Integer_Subtype);
4917                Set_Scalar_Range         (Id, Scalar_Range       (T));
4918                Set_Is_Constrained       (Id, Is_Constrained     (T));
4919                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4920                Set_RM_Size              (Id, RM_Size            (T));
4921                Inherit_Predicate_Flags  (Id, T);
4922 
4923             when Modular_Integer_Kind =>
4924                Set_Ekind                (Id, E_Modular_Integer_Subtype);
4925                Set_Scalar_Range         (Id, Scalar_Range       (T));
4926                Set_Is_Constrained       (Id, Is_Constrained     (T));
4927                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4928                Set_RM_Size              (Id, RM_Size            (T));
4929                Inherit_Predicate_Flags  (Id, T);
4930 
4931             when Class_Wide_Kind =>
4932                Set_Ekind                (Id, E_Class_Wide_Subtype);
4933                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
4934                Set_Cloned_Subtype       (Id, T);
4935                Set_Is_Tagged_Type       (Id, True);
4936                Set_Has_Unknown_Discriminants
4937                                         (Id, True);
4938                Set_No_Tagged_Streams_Pragma
4939                                         (Id, No_Tagged_Streams_Pragma (T));
4940 
4941                if Ekind (T) = E_Class_Wide_Subtype then
4942                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
4943                end if;
4944 
4945             when E_Record_Type | E_Record_Subtype =>
4946                Set_Ekind                (Id, E_Record_Subtype);
4947 
4948                if Ekind (T) = E_Record_Subtype
4949                  and then Present (Cloned_Subtype (T))
4950                then
4951                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
4952                else
4953                   Set_Cloned_Subtype    (Id, T);
4954                end if;
4955 
4956                Set_First_Entity         (Id, First_Entity       (T));
4957                Set_Last_Entity          (Id, Last_Entity        (T));
4958                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
4959                Set_Is_Constrained       (Id, Is_Constrained     (T));
4960                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
4961                Set_Has_Implicit_Dereference
4962                                         (Id, Has_Implicit_Dereference (T));
4963                Set_Has_Unknown_Discriminants
4964                                         (Id, Has_Unknown_Discriminants (T));
4965 
4966                if Has_Discriminants (T) then
4967                   Set_Discriminant_Constraint
4968                                         (Id, Discriminant_Constraint (T));
4969                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4970 
4971                elsif Has_Unknown_Discriminants (Id) then
4972                   Set_Discriminant_Constraint (Id, No_Elist);
4973                end if;
4974 
4975                if Is_Tagged_Type (T) then
4976                   Set_Is_Tagged_Type    (Id, True);
4977                   Set_No_Tagged_Streams_Pragma
4978                                         (Id, No_Tagged_Streams_Pragma (T));
4979                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
4980                   Set_Direct_Primitive_Operations
4981                                         (Id, Direct_Primitive_Operations (T));
4982                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
4983 
4984                   if Is_Interface (T) then
4985                      Set_Is_Interface (Id);
4986                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
4987                   end if;
4988                end if;
4989 
4990             when Private_Kind =>
4991                Set_Ekind              (Id, Subtype_Kind (Ekind        (T)));
4992                Set_Has_Discriminants  (Id, Has_Discriminants          (T));
4993                Set_Is_Constrained     (Id, Is_Constrained             (T));
4994                Set_First_Entity       (Id, First_Entity               (T));
4995                Set_Last_Entity        (Id, Last_Entity                (T));
4996                Set_Private_Dependents (Id, New_Elmt_List);
4997                Set_Is_Limited_Record  (Id, Is_Limited_Record          (T));
4998                Set_Has_Implicit_Dereference
4999                                       (Id, Has_Implicit_Dereference   (T));
5000                Set_Has_Unknown_Discriminants
5001                                       (Id, Has_Unknown_Discriminants  (T));
5002                Set_Known_To_Have_Preelab_Init
5003                                       (Id, Known_To_Have_Preelab_Init (T));
5004 
5005                if Is_Tagged_Type (T) then
5006                   Set_Is_Tagged_Type              (Id);
5007                   Set_No_Tagged_Streams_Pragma    (Id,
5008                     No_Tagged_Streams_Pragma (T));
5009                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
5010                   Set_Class_Wide_Type             (Id, Class_Wide_Type  (T));
5011                   Set_Direct_Primitive_Operations (Id,
5012                     Direct_Primitive_Operations (T));
5013                end if;
5014 
5015                --  In general the attributes of the subtype of a private type
5016                --  are the attributes of the partial view of parent. However,
5017                --  the full view may be a discriminated type, and the subtype
5018                --  must share the discriminant constraint to generate correct
5019                --  calls to initialization procedures.
5020 
5021                if Has_Discriminants (T) then
5022                   Set_Discriminant_Constraint
5023                     (Id, Discriminant_Constraint (T));
5024                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
5025 
5026                elsif Present (Full_View (T))
5027                  and then Has_Discriminants (Full_View (T))
5028                then
5029                   Set_Discriminant_Constraint
5030                     (Id, Discriminant_Constraint (Full_View (T)));
5031                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
5032 
5033                   --  This would seem semantically correct, but apparently
5034                   --  generates spurious errors about missing components ???
5035 
5036                   --  Set_Has_Discriminants (Id);
5037                end if;
5038 
5039                Prepare_Private_Subtype_Completion (Id, N);
5040 
5041                --  If this is the subtype of a constrained private type with
5042                --  discriminants that has got a full view and we also have
5043                --  built a completion just above, show that the completion
5044                --  is a clone of the full view to the back-end.
5045 
5046                if Has_Discriminants (T)
5047                   and then not Has_Unknown_Discriminants (T)
5048                   and then not Is_Empty_Elmt_List (Discriminant_Constraint (T))
5049                   and then Present (Full_View (T))
5050                   and then Present (Full_View (Id))
5051                then
5052                   Set_Cloned_Subtype (Full_View (Id), Full_View (T));
5053                end if;
5054 
5055             when Access_Kind =>
5056                Set_Ekind             (Id, E_Access_Subtype);
5057                Set_Is_Constrained    (Id, Is_Constrained        (T));
5058                Set_Is_Access_Constant
5059                                      (Id, Is_Access_Constant    (T));
5060                Set_Directly_Designated_Type
5061                                      (Id, Designated_Type       (T));
5062                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
5063 
5064                --  A Pure library_item must not contain the declaration of a
5065                --  named access type, except within a subprogram, generic
5066                --  subprogram, task unit, or protected unit, or if it has
5067                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
5068 
5069                if Comes_From_Source (Id)
5070                  and then In_Pure_Unit
5071                  and then not In_Subprogram_Task_Protected_Unit
5072                  and then not No_Pool_Assigned (Id)
5073                then
5074                   Error_Msg_N
5075                     ("named access types not allowed in pure unit", N);
5076                end if;
5077 
5078             when Concurrent_Kind =>
5079                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
5080                Set_Corresponding_Record_Type (Id,
5081                                          Corresponding_Record_Type (T));
5082                Set_First_Entity         (Id, First_Entity          (T));
5083                Set_First_Private_Entity (Id, First_Private_Entity  (T));
5084                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
5085                Set_Is_Constrained       (Id, Is_Constrained        (T));
5086                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
5087                Set_Last_Entity          (Id, Last_Entity           (T));
5088 
5089                if Is_Tagged_Type (T) then
5090                   Set_No_Tagged_Streams_Pragma
5091                     (Id, No_Tagged_Streams_Pragma (T));
5092                end if;
5093 
5094                if Has_Discriminants (T) then
5095                   Set_Discriminant_Constraint
5096                     (Id, Discriminant_Constraint (T));
5097                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
5098                end if;
5099 
5100             when Incomplete_Kind  =>
5101                if Ada_Version >= Ada_2005 then
5102 
5103                   --  In Ada 2005 an incomplete type can be explicitly tagged:
5104                   --  propagate indication. Note that we also have to include
5105                   --  subtypes for Ada 2012 extended use of incomplete types.
5106 
5107                   Set_Ekind              (Id, E_Incomplete_Subtype);
5108                   Set_Is_Tagged_Type     (Id, Is_Tagged_Type (T));
5109                   Set_Private_Dependents (Id, New_Elmt_List);
5110 
5111                   if Is_Tagged_Type (Id) then
5112                      Set_No_Tagged_Streams_Pragma
5113                        (Id, No_Tagged_Streams_Pragma (T));
5114                      Set_Direct_Primitive_Operations (Id, New_Elmt_List);
5115                   end if;
5116 
5117                   --  Ada 2005 (AI-412): Decorate an incomplete subtype of an
5118                   --  incomplete type visible through a limited with clause.
5119 
5120                   if From_Limited_With (T)
5121                     and then Present (Non_Limited_View (T))
5122                   then
5123                      Set_From_Limited_With (Id);
5124                      Set_Non_Limited_View  (Id, Non_Limited_View (T));
5125 
5126                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
5127                   --  to the private dependents of the original incomplete
5128                   --  type for future transformation.
5129 
5130                   else
5131                      Append_Elmt (Id, Private_Dependents (T));
5132                   end if;
5133 
5134                --  If the subtype name denotes an incomplete type an error
5135                --  was already reported by Process_Subtype.
5136 
5137                else
5138                   Set_Etype (Id, Any_Type);
5139                end if;
5140 
5141             when others =>
5142                raise Program_Error;
5143          end case;
5144       end if;
5145 
5146       if Etype (Id) = Any_Type then
5147          goto Leave;
5148       end if;
5149 
5150       --  Some common processing on all types
5151 
5152       Set_Size_Info      (Id, T);
5153       Set_First_Rep_Item (Id, First_Rep_Item (T));
5154 
5155       --  If the parent type is a generic actual, so is the subtype. This may
5156       --  happen in a nested instance. Why Comes_From_Source test???
5157 
5158       if not Comes_From_Source (N) then
5159          Set_Is_Generic_Actual_Type (Id, Is_Generic_Actual_Type (T));
5160       end if;
5161 
5162       --  If this is a subtype declaration for an actual in an instance,
5163       --  inherit static and dynamic predicates if any.
5164 
5165       --  If declaration has no aspect specifications, inherit predicate
5166       --  info as well. Unclear how to handle the case of both specified
5167       --  and inherited predicates ??? Other inherited aspects, such as
5168       --  invariants, should be OK, but the combination with later pragmas
5169       --  may also require special merging.
5170 
5171       if Has_Predicates (T)
5172         and then Present (Predicate_Function (T))
5173         and then
5174           ((In_Instance and then not Comes_From_Source (N))
5175              or else No (Aspect_Specifications (N)))
5176       then
5177          Set_Subprograms_For_Type (Id, Subprograms_For_Type (T));
5178 
5179          if Has_Static_Predicate (T) then
5180             Set_Has_Static_Predicate (Id);
5181             Set_Static_Discrete_Predicate (Id, Static_Discrete_Predicate (T));
5182          end if;
5183       end if;
5184 
5185       --  Propagate invariant-related attributes from the base type to the
5186       --  subtype.
5187 
5188       Propagate_Invariant_Attributes (Id, From_Typ => Base_Type (T));
5189 
5190       --  Remaining processing depends on characteristics of base type
5191 
5192       T := Etype (Id);
5193 
5194       Set_Is_Immediately_Visible   (Id, True);
5195       Set_Depends_On_Private       (Id, Has_Private_Component (T));
5196       Set_Is_Descendant_Of_Address (Id, Is_Descendant_Of_Address (T));
5197 
5198       if Is_Interface (T) then
5199          Set_Is_Interface (Id);
5200       end if;
5201 
5202       if Present (Generic_Parent_Type (N))
5203         and then
5204           (Nkind (Parent (Generic_Parent_Type (N))) /=
5205                                               N_Formal_Type_Declaration
5206             or else Nkind (Formal_Type_Definition
5207                             (Parent (Generic_Parent_Type (N)))) /=
5208                                               N_Formal_Private_Type_Definition)
5209       then
5210          if Is_Tagged_Type (Id) then
5211 
5212             --  If this is a generic actual subtype for a synchronized type,
5213             --  the primitive operations are those of the corresponding record
5214             --  for which there is a separate subtype declaration.
5215 
5216             if Is_Concurrent_Type (Id) then
5217                null;
5218             elsif Is_Class_Wide_Type (Id) then
5219                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
5220             else
5221                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
5222             end if;
5223 
5224          elsif Scope (Etype (Id)) /= Standard_Standard then
5225             Derive_Subprograms (Generic_Parent_Type (N), Id);
5226          end if;
5227       end if;
5228 
5229       if Is_Private_Type (T) and then Present (Full_View (T)) then
5230          Conditional_Delay (Id, Full_View (T));
5231 
5232       --  The subtypes of components or subcomponents of protected types
5233       --  do not need freeze nodes, which would otherwise appear in the
5234       --  wrong scope (before the freeze node for the protected type). The
5235       --  proper subtypes are those of the subcomponents of the corresponding
5236       --  record.
5237 
5238       elsif Ekind (Scope (Id)) /= E_Protected_Type
5239         and then Present (Scope (Scope (Id))) -- error defense
5240         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
5241       then
5242          Conditional_Delay (Id, T);
5243       end if;
5244 
5245       --  Check that Constraint_Error is raised for a scalar subtype indication
5246       --  when the lower or upper bound of a non-null range lies outside the
5247       --  range of the type mark.
5248 
5249       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
5250          if Is_Scalar_Type (Etype (Id))
5251            and then Scalar_Range (Id) /=
5252                     Scalar_Range
5253                       (Etype (Subtype_Mark (Subtype_Indication (N))))
5254          then
5255             Apply_Range_Check
5256               (Scalar_Range (Id),
5257                Etype (Subtype_Mark (Subtype_Indication (N))));
5258 
5259          --  In the array case, check compatibility for each index
5260 
5261          elsif Is_Array_Type (Etype (Id)) and then Present (First_Index (Id))
5262          then
5263             --  This really should be a subprogram that finds the indications
5264             --  to check???
5265 
5266             declare
5267                Subt_Index   : Node_Id := First_Index (Id);
5268                Target_Index : Node_Id :=
5269                                 First_Index (Etype
5270                                   (Subtype_Mark (Subtype_Indication (N))));
5271                Has_Dyn_Chk  : Boolean := Has_Dynamic_Range_Check (N);
5272 
5273             begin
5274                while Present (Subt_Index) loop
5275                   if ((Nkind (Subt_Index) = N_Identifier
5276                         and then Ekind (Entity (Subt_Index)) in Scalar_Kind)
5277                        or else Nkind (Subt_Index) = N_Subtype_Indication)
5278                     and then
5279                       Nkind (Scalar_Range (Etype (Subt_Index))) = N_Range
5280                   then
5281                      declare
5282                         Target_Typ : constant Entity_Id :=
5283                                        Etype (Target_Index);
5284                      begin
5285                         R_Checks :=
5286                           Get_Range_Checks
5287                             (Scalar_Range (Etype (Subt_Index)),
5288                              Target_Typ,
5289                              Etype (Subt_Index),
5290                              Defining_Identifier (N));
5291 
5292                         --  Reset Has_Dynamic_Range_Check on the subtype to
5293                         --  prevent elision of the index check due to a dynamic
5294                         --  check generated for a preceding index (needed since
5295                         --  Insert_Range_Checks tries to avoid generating
5296                         --  redundant checks on a given declaration).
5297 
5298                         Set_Has_Dynamic_Range_Check (N, False);
5299 
5300                         Insert_Range_Checks
5301                           (R_Checks,
5302                            N,
5303                            Target_Typ,
5304                            Sloc (Defining_Identifier (N)));
5305 
5306                         --  Record whether this index involved a dynamic check
5307 
5308                         Has_Dyn_Chk :=
5309                           Has_Dyn_Chk or else Has_Dynamic_Range_Check (N);
5310                      end;
5311                   end if;
5312 
5313                   Next_Index (Subt_Index);
5314                   Next_Index (Target_Index);
5315                end loop;
5316 
5317                --  Finally, mark whether the subtype involves dynamic checks
5318 
5319                Set_Has_Dynamic_Range_Check (N, Has_Dyn_Chk);
5320             end;
5321          end if;
5322       end if;
5323 
5324       --  Make sure that generic actual types are properly frozen. The subtype
5325       --  is marked as a generic actual type when the enclosing instance is
5326       --  analyzed, so here we identify the subtype from the tree structure.
5327 
5328       if Expander_Active
5329         and then Is_Generic_Actual_Type (Id)
5330         and then In_Instance
5331         and then not Comes_From_Source (N)
5332         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
5333         and then Is_Frozen (T)
5334       then
5335          Freeze_Before (N, Id);
5336       end if;
5337 
5338       Set_Optimize_Alignment_Flags (Id);
5339       Check_Eliminated (Id);
5340 
5341    <<Leave>>
5342       if Has_Aspects (N) then
5343          Analyze_Aspect_Specifications (N, Id);
5344       end if;
5345 
5346       Analyze_Dimension (N);
5347 
5348       --  Check No_Dynamic_Sized_Objects restriction, which disallows subtype
5349       --  indications on composite types where the constraints are dynamic.
5350       --  Note that object declarations and aggregates generate implicit
5351       --  subtype declarations, which this covers. One special case is that the
5352       --  implicitly generated "=" for discriminated types includes an
5353       --  offending subtype declaration, which is harmless, so we ignore it
5354       --  here.
5355 
5356       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
5357          declare
5358             Cstr : constant Node_Id := Constraint (Subtype_Indication (N));
5359          begin
5360             if Nkind (Cstr) = N_Index_Or_Discriminant_Constraint
5361               and then not (Is_Internal (Id)
5362                              and then Is_TSS (Scope (Id),
5363                                               TSS_Composite_Equality))
5364               and then not Within_Init_Proc
5365               and then not All_Composite_Constraints_Static (Cstr)
5366             then
5367                Check_Restriction (No_Dynamic_Sized_Objects, Cstr);
5368             end if;
5369          end;
5370       end if;
5371    end Analyze_Subtype_Declaration;
5372 
5373    --------------------------------
5374    -- Analyze_Subtype_Indication --
5375    --------------------------------
5376 
5377    procedure Analyze_Subtype_Indication (N : Node_Id) is
5378       T : constant Entity_Id := Subtype_Mark (N);
5379       R : constant Node_Id   := Range_Expression (Constraint (N));
5380 
5381    begin
5382       Analyze (T);
5383 
5384       if R /= Error then
5385          Analyze (R);
5386          Set_Etype (N, Etype (R));
5387          Resolve (R, Entity (T));
5388       else
5389          Set_Error_Posted (R);
5390          Set_Error_Posted (T);
5391       end if;
5392    end Analyze_Subtype_Indication;
5393 
5394    --------------------------
5395    -- Analyze_Variant_Part --
5396    --------------------------
5397 
5398    procedure Analyze_Variant_Part (N : Node_Id) is
5399       Discr_Name : Node_Id;
5400       Discr_Type : Entity_Id;
5401 
5402       procedure Process_Variant (A : Node_Id);
5403       --  Analyze declarations for a single variant
5404 
5405       package Analyze_Variant_Choices is
5406         new Generic_Analyze_Choices (Process_Variant);
5407       use Analyze_Variant_Choices;
5408 
5409       ---------------------
5410       -- Process_Variant --
5411       ---------------------
5412 
5413       procedure Process_Variant (A : Node_Id) is
5414          CL : constant Node_Id := Component_List (A);
5415       begin
5416          if not Null_Present (CL) then
5417             Analyze_Declarations (Component_Items (CL));
5418 
5419             if Present (Variant_Part (CL)) then
5420                Analyze (Variant_Part (CL));
5421             end if;
5422          end if;
5423       end Process_Variant;
5424 
5425    --  Start of processing for Analyze_Variant_Part
5426 
5427    begin
5428       Discr_Name := Name (N);
5429       Analyze (Discr_Name);
5430 
5431       --  If Discr_Name bad, get out (prevent cascaded errors)
5432 
5433       if Etype (Discr_Name) = Any_Type then
5434          return;
5435       end if;
5436 
5437       --  Check invalid discriminant in variant part
5438 
5439       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
5440          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
5441       end if;
5442 
5443       Discr_Type := Etype (Entity (Discr_Name));
5444 
5445       if not Is_Discrete_Type (Discr_Type) then
5446          Error_Msg_N
5447            ("discriminant in a variant part must be of a discrete type",
5448              Name (N));
5449          return;
5450       end if;
5451 
5452       --  Now analyze the choices, which also analyzes the declarations that
5453       --  are associated with each choice.
5454 
5455       Analyze_Choices (Variants (N), Discr_Type);
5456 
5457       --  Note: we used to instantiate and call Check_Choices here to check
5458       --  that the choices covered the discriminant, but it's too early to do
5459       --  that because of statically predicated subtypes, whose analysis may
5460       --  be deferred to their freeze point which may be as late as the freeze
5461       --  point of the containing record. So this call is now to be found in
5462       --  Freeze_Record_Declaration.
5463 
5464    end Analyze_Variant_Part;
5465 
5466    ----------------------------
5467    -- Array_Type_Declaration --
5468    ----------------------------
5469 
5470    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
5471       Component_Def : constant Node_Id := Component_Definition (Def);
5472       Component_Typ : constant Node_Id := Subtype_Indication (Component_Def);
5473       Element_Type  : Entity_Id;
5474       Implicit_Base : Entity_Id;
5475       Index         : Node_Id;
5476       Related_Id    : Entity_Id := Empty;
5477       Nb_Index      : Nat;
5478       P             : constant Node_Id := Parent (Def);
5479       Priv          : Entity_Id;
5480 
5481    begin
5482       if Nkind (Def) = N_Constrained_Array_Definition then
5483          Index := First (Discrete_Subtype_Definitions (Def));
5484       else
5485          Index := First (Subtype_Marks (Def));
5486       end if;
5487 
5488       --  Find proper names for the implicit types which may be public. In case
5489       --  of anonymous arrays we use the name of the first object of that type
5490       --  as prefix.
5491 
5492       if No (T) then
5493          Related_Id := Defining_Identifier (P);
5494       else
5495          Related_Id := T;
5496       end if;
5497 
5498       Nb_Index := 1;
5499       while Present (Index) loop
5500          Analyze (Index);
5501 
5502          --  Test for odd case of trying to index a type by the type itself
5503 
5504          if Is_Entity_Name (Index) and then Entity (Index) = T then
5505             Error_Msg_N ("type& cannot be indexed by itself", Index);
5506             Set_Entity (Index, Standard_Boolean);
5507             Set_Etype (Index, Standard_Boolean);
5508          end if;
5509 
5510          --  Check SPARK restriction requiring a subtype mark
5511 
5512          if not Nkind_In (Index, N_Identifier, N_Expanded_Name) then
5513             Check_SPARK_05_Restriction ("subtype mark required", Index);
5514          end if;
5515 
5516          --  Add a subtype declaration for each index of private array type
5517          --  declaration whose etype is also private. For example:
5518 
5519          --     package Pkg is
5520          --        type Index is private;
5521          --     private
5522          --        type Table is array (Index) of ...
5523          --     end;
5524 
5525          --  This is currently required by the expander for the internally
5526          --  generated equality subprogram of records with variant parts in
5527          --  which the etype of some component is such private type.
5528 
5529          if Ekind (Current_Scope) = E_Package
5530            and then In_Private_Part (Current_Scope)
5531            and then Has_Private_Declaration (Etype (Index))
5532          then
5533             declare
5534                Loc   : constant Source_Ptr := Sloc (Def);
5535                New_E : Entity_Id;
5536                Decl  : Entity_Id;
5537 
5538             begin
5539                New_E := Make_Temporary (Loc, 'T');
5540                Set_Is_Internal (New_E);
5541 
5542                Decl :=
5543                  Make_Subtype_Declaration (Loc,
5544                    Defining_Identifier => New_E,
5545                    Subtype_Indication  =>
5546                      New_Occurrence_Of (Etype (Index), Loc));
5547 
5548                Insert_Before (Parent (Def), Decl);
5549                Analyze (Decl);
5550                Set_Etype (Index, New_E);
5551 
5552                --  If the index is a range the Entity attribute is not
5553                --  available. Example:
5554 
5555                --     package Pkg is
5556                --        type T is private;
5557                --     private
5558                --        type T is new Natural;
5559                --        Table : array (T(1) .. T(10)) of Boolean;
5560                --     end Pkg;
5561 
5562                if Nkind (Index) /= N_Range then
5563                   Set_Entity (Index, New_E);
5564                end if;
5565             end;
5566          end if;
5567 
5568          Make_Index (Index, P, Related_Id, Nb_Index);
5569 
5570          --  Check error of subtype with predicate for index type
5571 
5572          Bad_Predicated_Subtype_Use
5573            ("subtype& has predicate, not allowed as index subtype",
5574             Index, Etype (Index));
5575 
5576          --  Move to next index
5577 
5578          Next_Index (Index);
5579          Nb_Index := Nb_Index + 1;
5580       end loop;
5581 
5582       --  Process subtype indication if one is present
5583 
5584       if Present (Component_Typ) then
5585          Element_Type := Process_Subtype (Component_Typ, P, Related_Id, 'C');
5586 
5587          Set_Etype (Component_Typ, Element_Type);
5588 
5589          if not Nkind_In (Component_Typ, N_Identifier, N_Expanded_Name) then
5590             Check_SPARK_05_Restriction
5591               ("subtype mark required", Component_Typ);
5592          end if;
5593 
5594       --  Ada 2005 (AI-230): Access Definition case
5595 
5596       else pragma Assert (Present (Access_Definition (Component_Def)));
5597 
5598          --  Indicate that the anonymous access type is created by the
5599          --  array type declaration.
5600 
5601          Element_Type := Access_Definition
5602                            (Related_Nod => P,
5603                             N           => Access_Definition (Component_Def));
5604          Set_Is_Local_Anonymous_Access (Element_Type);
5605 
5606          --  Propagate the parent. This field is needed if we have to generate
5607          --  the master_id associated with an anonymous access to task type
5608          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
5609 
5610          Set_Parent (Element_Type, Parent (T));
5611 
5612          --  Ada 2005 (AI-230): In case of components that are anonymous access
5613          --  types the level of accessibility depends on the enclosing type
5614          --  declaration
5615 
5616          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
5617 
5618          --  Ada 2005 (AI-254)
5619 
5620          declare
5621             CD : constant Node_Id :=
5622                    Access_To_Subprogram_Definition
5623                      (Access_Definition (Component_Def));
5624          begin
5625             if Present (CD) and then Protected_Present (CD) then
5626                Element_Type :=
5627                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
5628             end if;
5629          end;
5630       end if;
5631 
5632       --  Constrained array case
5633 
5634       if No (T) then
5635          T := Create_Itype (E_Void, P, Related_Id, 'T');
5636       end if;
5637 
5638       if Nkind (Def) = N_Constrained_Array_Definition then
5639 
5640          --  Establish Implicit_Base as unconstrained base type
5641 
5642          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
5643 
5644          Set_Etype              (Implicit_Base, Implicit_Base);
5645          Set_Scope              (Implicit_Base, Current_Scope);
5646          Set_Has_Delayed_Freeze (Implicit_Base);
5647          Set_Default_SSO        (Implicit_Base);
5648 
5649          --  The constrained array type is a subtype of the unconstrained one
5650 
5651          Set_Ekind              (T, E_Array_Subtype);
5652          Init_Size_Align        (T);
5653          Set_Etype              (T, Implicit_Base);
5654          Set_Scope              (T, Current_Scope);
5655          Set_Is_Constrained     (T);
5656          Set_First_Index        (T,
5657            First (Discrete_Subtype_Definitions (Def)));
5658          Set_Has_Delayed_Freeze (T);
5659 
5660          --  Complete setup of implicit base type
5661 
5662          Set_Component_Size (Implicit_Base, Uint_0);
5663          Set_Component_Type (Implicit_Base, Element_Type);
5664          Set_Finalize_Storage_Only
5665                             (Implicit_Base,
5666                               Finalize_Storage_Only (Element_Type));
5667          Set_First_Index    (Implicit_Base, First_Index (T));
5668          Set_Has_Controlled_Component
5669                             (Implicit_Base,
5670                               Has_Controlled_Component (Element_Type)
5671                                 or else Is_Controlled_Active  (Element_Type));
5672          Set_Packed_Array_Impl_Type
5673                             (Implicit_Base, Empty);
5674 
5675          Propagate_Concurrent_Flags (Implicit_Base, Element_Type);
5676 
5677          --  Inherit the "ghostness" from the constrained array type
5678 
5679          if Ghost_Mode > None or else Is_Ghost_Entity (T) then
5680             Set_Is_Ghost_Entity (Implicit_Base);
5681          end if;
5682 
5683       --  Unconstrained array case
5684 
5685       else
5686          Set_Ekind                    (T, E_Array_Type);
5687          Init_Size_Align              (T);
5688          Set_Etype                    (T, T);
5689          Set_Scope                    (T, Current_Scope);
5690          Set_Component_Size           (T, Uint_0);
5691          Set_Is_Constrained           (T, False);
5692          Set_First_Index              (T, First (Subtype_Marks (Def)));
5693          Set_Has_Delayed_Freeze       (T, True);
5694          Propagate_Concurrent_Flags   (T, Element_Type);
5695          Set_Has_Controlled_Component (T, Has_Controlled_Component
5696                                                         (Element_Type)
5697                                             or else
5698                                           Is_Controlled_Active (Element_Type));
5699          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
5700                                                         (Element_Type));
5701          Set_Default_SSO              (T);
5702       end if;
5703 
5704       --  Common attributes for both cases
5705 
5706       Set_Component_Type (Base_Type (T), Element_Type);
5707       Set_Packed_Array_Impl_Type (T, Empty);
5708 
5709       if Aliased_Present (Component_Definition (Def)) then
5710          Check_SPARK_05_Restriction
5711            ("aliased is not allowed", Component_Definition (Def));
5712          Set_Has_Aliased_Components (Etype (T));
5713       end if;
5714 
5715       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
5716       --  array type to ensure that objects of this type are initialized.
5717 
5718       if Ada_Version >= Ada_2005 and then Can_Never_Be_Null (Element_Type) then
5719          Set_Can_Never_Be_Null (T);
5720 
5721          if Null_Exclusion_Present (Component_Definition (Def))
5722 
5723             --  No need to check itypes because in their case this check was
5724             --  done at their point of creation
5725 
5726            and then not Is_Itype (Element_Type)
5727          then
5728             Error_Msg_N
5729               ("`NOT NULL` not allowed (null already excluded)",
5730                Subtype_Indication (Component_Definition (Def)));
5731          end if;
5732       end if;
5733 
5734       Priv := Private_Component (Element_Type);
5735 
5736       if Present (Priv) then
5737 
5738          --  Check for circular definitions
5739 
5740          if Priv = Any_Type then
5741             Set_Component_Type (Etype (T), Any_Type);
5742 
5743          --  There is a gap in the visibility of operations on the composite
5744          --  type only if the component type is defined in a different scope.
5745 
5746          elsif Scope (Priv) = Current_Scope then
5747             null;
5748 
5749          elsif Is_Limited_Type (Priv) then
5750             Set_Is_Limited_Composite (Etype (T));
5751             Set_Is_Limited_Composite (T);
5752          else
5753             Set_Is_Private_Composite (Etype (T));
5754             Set_Is_Private_Composite (T);
5755          end if;
5756       end if;
5757 
5758       --  A syntax error in the declaration itself may lead to an empty index
5759       --  list, in which case do a minimal patch.
5760 
5761       if No (First_Index (T)) then
5762          Error_Msg_N ("missing index definition in array type declaration", T);
5763 
5764          declare
5765             Indexes : constant List_Id :=
5766                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
5767          begin
5768             Set_Discrete_Subtype_Definitions (Def, Indexes);
5769             Set_First_Index (T, First (Indexes));
5770             return;
5771          end;
5772       end if;
5773 
5774       --  Create a concatenation operator for the new type. Internal array
5775       --  types created for packed entities do not need such, they are
5776       --  compatible with the user-defined type.
5777 
5778       if Number_Dimensions (T) = 1
5779         and then not Is_Packed_Array_Impl_Type (T)
5780       then
5781          New_Concatenation_Op (T);
5782       end if;
5783 
5784       --  In the case of an unconstrained array the parser has already verified
5785       --  that all the indexes are unconstrained but we still need to make sure
5786       --  that the element type is constrained.
5787 
5788       if not Is_Definite_Subtype (Element_Type) then
5789          Error_Msg_N
5790            ("unconstrained element type in array declaration",
5791             Subtype_Indication (Component_Def));
5792 
5793       elsif Is_Abstract_Type (Element_Type) then
5794          Error_Msg_N
5795            ("the type of a component cannot be abstract",
5796             Subtype_Indication (Component_Def));
5797       end if;
5798 
5799       --  There may be an invariant declared for the component type, but
5800       --  the construction of the component invariant checking procedure
5801       --  takes place during expansion.
5802    end Array_Type_Declaration;
5803 
5804    ------------------------------------------------------
5805    -- Replace_Anonymous_Access_To_Protected_Subprogram --
5806    ------------------------------------------------------
5807 
5808    function Replace_Anonymous_Access_To_Protected_Subprogram
5809      (N : Node_Id) return Entity_Id
5810    is
5811       Loc : constant Source_Ptr := Sloc (N);
5812 
5813       Curr_Scope : constant Scope_Stack_Entry :=
5814                      Scope_Stack.Table (Scope_Stack.Last);
5815 
5816       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
5817 
5818       Acc : Node_Id;
5819       --  Access definition in declaration
5820 
5821       Comp : Node_Id;
5822       --  Object definition or formal definition with an access definition
5823 
5824       Decl : Node_Id;
5825       --  Declaration of anonymous access to subprogram type
5826 
5827       Spec : Node_Id;
5828       --  Original specification in access to subprogram
5829 
5830       P : Node_Id;
5831 
5832    begin
5833       Set_Is_Internal (Anon);
5834 
5835       case Nkind (N) is
5836          when N_Component_Declaration       |
5837            N_Unconstrained_Array_Definition |
5838            N_Constrained_Array_Definition   =>
5839             Comp := Component_Definition (N);
5840             Acc  := Access_Definition (Comp);
5841 
5842          when N_Discriminant_Specification =>
5843             Comp := Discriminant_Type (N);
5844             Acc  := Comp;
5845 
5846          when N_Parameter_Specification =>
5847             Comp := Parameter_Type (N);
5848             Acc  := Comp;
5849 
5850          when N_Access_Function_Definition  =>
5851             Comp := Result_Definition (N);
5852             Acc  := Comp;
5853 
5854          when N_Object_Declaration  =>
5855             Comp := Object_Definition (N);
5856             Acc  := Comp;
5857 
5858          when N_Function_Specification =>
5859             Comp := Result_Definition (N);
5860             Acc  := Comp;
5861 
5862          when others =>
5863             raise Program_Error;
5864       end case;
5865 
5866       Spec := Access_To_Subprogram_Definition (Acc);
5867 
5868       Decl :=
5869         Make_Full_Type_Declaration (Loc,
5870           Defining_Identifier => Anon,
5871           Type_Definition     => Copy_Separate_Tree (Spec));
5872 
5873       Mark_Rewrite_Insertion (Decl);
5874 
5875       --  In ASIS mode, analyze the profile on the original node, because
5876       --  the separate copy does not provide enough links to recover the
5877       --  original tree. Analysis is limited to type annotations, within
5878       --  a temporary scope that serves as an anonymous subprogram to collect
5879       --  otherwise useless temporaries and itypes.
5880 
5881       if ASIS_Mode then
5882          declare
5883             Typ : constant Entity_Id := Make_Temporary (Loc, 'S');
5884 
5885          begin
5886             if Nkind (Spec) = N_Access_Function_Definition then
5887                Set_Ekind (Typ, E_Function);
5888             else
5889                Set_Ekind (Typ, E_Procedure);
5890             end if;
5891 
5892             Set_Parent (Typ, N);
5893             Set_Scope  (Typ, Current_Scope);
5894             Push_Scope (Typ);
5895 
5896             --  Nothing to do if procedure is parameterless
5897 
5898             if Present (Parameter_Specifications (Spec)) then
5899                Process_Formals (Parameter_Specifications (Spec), Spec);
5900             end if;
5901 
5902             if Nkind (Spec) = N_Access_Function_Definition then
5903                declare
5904                   Def : constant Node_Id := Result_Definition (Spec);
5905 
5906                begin
5907                   --  The result might itself be an anonymous access type, so
5908                   --  have to recurse.
5909 
5910                   if Nkind (Def) = N_Access_Definition then
5911                      if Present (Access_To_Subprogram_Definition (Def)) then
5912                         Set_Etype
5913                           (Def,
5914                            Replace_Anonymous_Access_To_Protected_Subprogram
5915                             (Spec));
5916                      else
5917                         Find_Type (Subtype_Mark (Def));
5918                      end if;
5919 
5920                   else
5921                      Find_Type (Def);
5922                   end if;
5923                end;
5924             end if;
5925 
5926             End_Scope;
5927          end;
5928       end if;
5929 
5930       --  Insert the new declaration in the nearest enclosing scope. If the
5931       --  node is a body and N is its return type, the declaration belongs in
5932       --  the enclosing scope.
5933 
5934       P := Parent (N);
5935 
5936       if Nkind (P) = N_Subprogram_Body
5937         and then Nkind (N) = N_Function_Specification
5938       then
5939          P := Parent (P);
5940       end if;
5941 
5942       while Present (P) and then not Has_Declarations (P) loop
5943          P := Parent (P);
5944       end loop;
5945 
5946       pragma Assert (Present (P));
5947 
5948       if Nkind (P) = N_Package_Specification then
5949          Prepend (Decl, Visible_Declarations (P));
5950       else
5951          Prepend (Decl, Declarations (P));
5952       end if;
5953 
5954       --  Replace the anonymous type with an occurrence of the new declaration.
5955       --  In all cases the rewritten node does not have the null-exclusion
5956       --  attribute because (if present) it was already inherited by the
5957       --  anonymous entity (Anon). Thus, in case of components we do not
5958       --  inherit this attribute.
5959 
5960       if Nkind (N) = N_Parameter_Specification then
5961          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5962          Set_Etype (Defining_Identifier (N), Anon);
5963          Set_Null_Exclusion_Present (N, False);
5964 
5965       elsif Nkind (N) = N_Object_Declaration then
5966          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5967          Set_Etype (Defining_Identifier (N), Anon);
5968 
5969       elsif Nkind (N) = N_Access_Function_Definition then
5970          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5971 
5972       elsif Nkind (N) = N_Function_Specification then
5973          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5974          Set_Etype (Defining_Unit_Name (N), Anon);
5975 
5976       else
5977          Rewrite (Comp,
5978            Make_Component_Definition (Loc,
5979              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
5980       end if;
5981 
5982       Mark_Rewrite_Insertion (Comp);
5983 
5984       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition)
5985         or else (Nkind (Parent (N)) = N_Full_Type_Declaration
5986                   and then not Is_Type (Current_Scope))
5987       then
5988 
5989          --  Declaration can be analyzed in the current scope.
5990 
5991          Analyze (Decl);
5992 
5993       else
5994          --  Temporarily remove the current scope (record or subprogram) from
5995          --  the stack to add the new declarations to the enclosing scope.
5996          --  The anonymous entity is an Itype with the proper attributes.
5997 
5998          Scope_Stack.Decrement_Last;
5999          Analyze (Decl);
6000          Set_Is_Itype (Anon);
6001          Set_Associated_Node_For_Itype (Anon, N);
6002          Scope_Stack.Append (Curr_Scope);
6003       end if;
6004 
6005       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
6006       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
6007       return Anon;
6008    end Replace_Anonymous_Access_To_Protected_Subprogram;
6009 
6010    -------------------------------
6011    -- Build_Derived_Access_Type --
6012    -------------------------------
6013 
6014    procedure Build_Derived_Access_Type
6015      (N            : Node_Id;
6016       Parent_Type  : Entity_Id;
6017       Derived_Type : Entity_Id)
6018    is
6019       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
6020 
6021       Desig_Type      : Entity_Id;
6022       Discr           : Entity_Id;
6023       Discr_Con_Elist : Elist_Id;
6024       Discr_Con_El    : Elmt_Id;
6025       Subt            : Entity_Id;
6026 
6027    begin
6028       --  Set the designated type so it is available in case this is an access
6029       --  to a self-referential type, e.g. a standard list type with a next
6030       --  pointer. Will be reset after subtype is built.
6031 
6032       Set_Directly_Designated_Type
6033         (Derived_Type, Designated_Type (Parent_Type));
6034 
6035       Subt := Process_Subtype (S, N);
6036 
6037       if Nkind (S) /= N_Subtype_Indication
6038         and then Subt /= Base_Type (Subt)
6039       then
6040          Set_Ekind (Derived_Type, E_Access_Subtype);
6041       end if;
6042 
6043       if Ekind (Derived_Type) = E_Access_Subtype then
6044          declare
6045             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
6046             Ibase      : constant Entity_Id :=
6047                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
6048             Svg_Chars  : constant Name_Id   := Chars (Ibase);
6049             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
6050 
6051          begin
6052             Copy_Node (Pbase, Ibase);
6053 
6054             Set_Chars             (Ibase, Svg_Chars);
6055             Set_Next_Entity       (Ibase, Svg_Next_E);
6056             Set_Sloc              (Ibase, Sloc (Derived_Type));
6057             Set_Scope             (Ibase, Scope (Derived_Type));
6058             Set_Freeze_Node       (Ibase, Empty);
6059             Set_Is_Frozen         (Ibase, False);
6060             Set_Comes_From_Source (Ibase, False);
6061             Set_Is_First_Subtype  (Ibase, False);
6062 
6063             Set_Etype (Ibase, Pbase);
6064             Set_Etype (Derived_Type, Ibase);
6065          end;
6066       end if;
6067 
6068       Set_Directly_Designated_Type
6069         (Derived_Type, Designated_Type (Subt));
6070 
6071       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
6072       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
6073       Set_Size_Info          (Derived_Type,                     Parent_Type);
6074       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
6075       Set_Depends_On_Private (Derived_Type,
6076                               Has_Private_Component (Derived_Type));
6077       Conditional_Delay      (Derived_Type, Subt);
6078 
6079       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
6080       --  that it is not redundant.
6081 
6082       if Null_Exclusion_Present (Type_Definition (N)) then
6083          Set_Can_Never_Be_Null (Derived_Type);
6084 
6085       elsif Can_Never_Be_Null (Parent_Type) then
6086          Set_Can_Never_Be_Null (Derived_Type);
6087       end if;
6088 
6089       --  Note: we do not copy the Storage_Size_Variable, since we always go to
6090       --  the root type for this information.
6091 
6092       --  Apply range checks to discriminants for derived record case
6093       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
6094 
6095       Desig_Type := Designated_Type (Derived_Type);
6096 
6097       if Is_Composite_Type (Desig_Type)
6098         and then (not Is_Array_Type (Desig_Type))
6099         and then Has_Discriminants (Desig_Type)
6100         and then Base_Type (Desig_Type) /= Desig_Type
6101       then
6102          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
6103          Discr_Con_El := First_Elmt (Discr_Con_Elist);
6104 
6105          Discr := First_Discriminant (Base_Type (Desig_Type));
6106          while Present (Discr_Con_El) loop
6107             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
6108             Next_Elmt (Discr_Con_El);
6109             Next_Discriminant (Discr);
6110          end loop;
6111       end if;
6112    end Build_Derived_Access_Type;
6113 
6114    ------------------------------
6115    -- Build_Derived_Array_Type --
6116    ------------------------------
6117 
6118    procedure Build_Derived_Array_Type
6119      (N            : Node_Id;
6120       Parent_Type  : Entity_Id;
6121       Derived_Type : Entity_Id)
6122    is
6123       Loc           : constant Source_Ptr := Sloc (N);
6124       Tdef          : constant Node_Id    := Type_Definition (N);
6125       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
6126       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
6127       Implicit_Base : Entity_Id;
6128       New_Indic     : Node_Id;
6129 
6130       procedure Make_Implicit_Base;
6131       --  If the parent subtype is constrained, the derived type is a subtype
6132       --  of an implicit base type derived from the parent base.
6133 
6134       ------------------------
6135       -- Make_Implicit_Base --
6136       ------------------------
6137 
6138       procedure Make_Implicit_Base is
6139       begin
6140          Implicit_Base :=
6141            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
6142 
6143          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
6144          Set_Etype (Implicit_Base, Parent_Base);
6145 
6146          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
6147          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
6148 
6149          Set_Has_Delayed_Freeze (Implicit_Base, True);
6150 
6151          --  Inherit the "ghostness" from the parent base type
6152 
6153          if Ghost_Mode > None or else Is_Ghost_Entity (Parent_Base) then
6154             Set_Is_Ghost_Entity (Implicit_Base);
6155          end if;
6156       end Make_Implicit_Base;
6157 
6158    --  Start of processing for Build_Derived_Array_Type
6159 
6160    begin
6161       if not Is_Constrained (Parent_Type) then
6162          if Nkind (Indic) /= N_Subtype_Indication then
6163             Set_Ekind (Derived_Type, E_Array_Type);
6164 
6165             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
6166             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
6167 
6168             Set_Has_Delayed_Freeze (Derived_Type, True);
6169 
6170          else
6171             Make_Implicit_Base;
6172             Set_Etype (Derived_Type, Implicit_Base);
6173 
6174             New_Indic :=
6175               Make_Subtype_Declaration (Loc,
6176                 Defining_Identifier => Derived_Type,
6177                 Subtype_Indication  =>
6178                   Make_Subtype_Indication (Loc,
6179                     Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
6180                     Constraint => Constraint (Indic)));
6181 
6182             Rewrite (N, New_Indic);
6183             Analyze (N);
6184          end if;
6185 
6186       else
6187          if Nkind (Indic) /= N_Subtype_Indication then
6188             Make_Implicit_Base;
6189 
6190             Set_Ekind                     (Derived_Type, Ekind (Parent_Type));
6191             Set_Etype                     (Derived_Type, Implicit_Base);
6192             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
6193 
6194          else
6195             Error_Msg_N ("illegal constraint on constrained type", Indic);
6196          end if;
6197       end if;
6198 
6199       --  If parent type is not a derived type itself, and is declared in
6200       --  closed scope (e.g. a subprogram), then we must explicitly introduce
6201       --  the new type's concatenation operator since Derive_Subprograms
6202       --  will not inherit the parent's operator. If the parent type is
6203       --  unconstrained, the operator is of the unconstrained base type.
6204 
6205       if Number_Dimensions (Parent_Type) = 1
6206         and then not Is_Limited_Type (Parent_Type)
6207         and then not Is_Derived_Type (Parent_Type)
6208         and then not Is_Package_Or_Generic_Package
6209                        (Scope (Base_Type (Parent_Type)))
6210       then
6211          if not Is_Constrained (Parent_Type)
6212            and then Is_Constrained (Derived_Type)
6213          then
6214             New_Concatenation_Op (Implicit_Base);
6215          else
6216             New_Concatenation_Op (Derived_Type);
6217          end if;
6218       end if;
6219    end Build_Derived_Array_Type;
6220 
6221    -----------------------------------
6222    -- Build_Derived_Concurrent_Type --
6223    -----------------------------------
6224 
6225    procedure Build_Derived_Concurrent_Type
6226      (N            : Node_Id;
6227       Parent_Type  : Entity_Id;
6228       Derived_Type : Entity_Id)
6229    is
6230       Loc : constant Source_Ptr := Sloc (N);
6231 
6232       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
6233       Corr_Decl        : Node_Id;
6234       Corr_Decl_Needed : Boolean;
6235       --  If the derived type has fewer discriminants than its parent, the
6236       --  corresponding record is also a derived type, in order to account for
6237       --  the bound discriminants. We create a full type declaration for it in
6238       --  this case.
6239 
6240       Constraint_Present : constant Boolean :=
6241                              Nkind (Subtype_Indication (Type_Definition (N))) =
6242                                                           N_Subtype_Indication;
6243 
6244       D_Constraint   : Node_Id;
6245       New_Constraint : Elist_Id;
6246       Old_Disc       : Entity_Id;
6247       New_Disc       : Entity_Id;
6248       New_N          : Node_Id;
6249 
6250    begin
6251       Set_Stored_Constraint (Derived_Type, No_Elist);
6252       Corr_Decl_Needed := False;
6253       Old_Disc := Empty;
6254 
6255       if Present (Discriminant_Specifications (N))
6256         and then Constraint_Present
6257       then
6258          Old_Disc := First_Discriminant (Parent_Type);
6259          New_Disc := First (Discriminant_Specifications (N));
6260          while Present (New_Disc) and then Present (Old_Disc) loop
6261             Next_Discriminant (Old_Disc);
6262             Next (New_Disc);
6263          end loop;
6264       end if;
6265 
6266       if Present (Old_Disc) and then Expander_Active then
6267 
6268          --  The new type has fewer discriminants, so we need to create a new
6269          --  corresponding record, which is derived from the corresponding
6270          --  record of the parent, and has a stored constraint that captures
6271          --  the values of the discriminant constraints. The corresponding
6272          --  record is needed only if expander is active and code generation is
6273          --  enabled.
6274 
6275          --  The type declaration for the derived corresponding record has the
6276          --  same discriminant part and constraints as the current declaration.
6277          --  Copy the unanalyzed tree to build declaration.
6278 
6279          Corr_Decl_Needed := True;
6280          New_N := Copy_Separate_Tree (N);
6281 
6282          Corr_Decl :=
6283            Make_Full_Type_Declaration (Loc,
6284              Defining_Identifier         => Corr_Record,
6285              Discriminant_Specifications =>
6286                 Discriminant_Specifications (New_N),
6287              Type_Definition             =>
6288                Make_Derived_Type_Definition (Loc,
6289                  Subtype_Indication =>
6290                    Make_Subtype_Indication (Loc,
6291                      Subtype_Mark =>
6292                         New_Occurrence_Of
6293                           (Corresponding_Record_Type (Parent_Type), Loc),
6294                      Constraint   =>
6295                        Constraint
6296                          (Subtype_Indication (Type_Definition (New_N))))));
6297       end if;
6298 
6299       --  Copy Storage_Size and Relative_Deadline variables if task case
6300 
6301       if Is_Task_Type (Parent_Type) then
6302          Set_Storage_Size_Variable (Derived_Type,
6303            Storage_Size_Variable (Parent_Type));
6304          Set_Relative_Deadline_Variable (Derived_Type,
6305            Relative_Deadline_Variable (Parent_Type));
6306       end if;
6307 
6308       if Present (Discriminant_Specifications (N)) then
6309          Push_Scope (Derived_Type);
6310          Check_Or_Process_Discriminants (N, Derived_Type);
6311 
6312          if Constraint_Present then
6313             New_Constraint :=
6314               Expand_To_Stored_Constraint
6315                 (Parent_Type,
6316                  Build_Discriminant_Constraints
6317                    (Parent_Type,
6318                     Subtype_Indication (Type_Definition (N)), True));
6319          end if;
6320 
6321          End_Scope;
6322 
6323       elsif Constraint_Present then
6324 
6325          --  Build constrained subtype, copying the constraint, and derive
6326          --  from it to create a derived constrained type.
6327 
6328          declare
6329             Loc  : constant Source_Ptr := Sloc (N);
6330             Anon : constant Entity_Id :=
6331                      Make_Defining_Identifier (Loc,
6332                        Chars => New_External_Name (Chars (Derived_Type), 'T'));
6333             Decl : Node_Id;
6334 
6335          begin
6336             Decl :=
6337               Make_Subtype_Declaration (Loc,
6338                 Defining_Identifier => Anon,
6339                 Subtype_Indication =>
6340                   New_Copy_Tree (Subtype_Indication (Type_Definition (N))));
6341             Insert_Before (N, Decl);
6342             Analyze (Decl);
6343 
6344             Rewrite (Subtype_Indication (Type_Definition (N)),
6345               New_Occurrence_Of (Anon, Loc));
6346             Set_Analyzed (Derived_Type, False);
6347             Analyze (N);
6348             return;
6349          end;
6350       end if;
6351 
6352       --  By default, operations and private data are inherited from parent.
6353       --  However, in the presence of bound discriminants, a new corresponding
6354       --  record will be created, see below.
6355 
6356       Set_Has_Discriminants
6357         (Derived_Type, Has_Discriminants         (Parent_Type));
6358       Set_Corresponding_Record_Type
6359         (Derived_Type, Corresponding_Record_Type (Parent_Type));
6360 
6361       --  Is_Constrained is set according the parent subtype, but is set to
6362       --  False if the derived type is declared with new discriminants.
6363 
6364       Set_Is_Constrained
6365         (Derived_Type,
6366          (Is_Constrained (Parent_Type) or else Constraint_Present)
6367            and then not Present (Discriminant_Specifications (N)));
6368 
6369       if Constraint_Present then
6370          if not Has_Discriminants (Parent_Type) then
6371             Error_Msg_N ("untagged parent must have discriminants", N);
6372 
6373          elsif Present (Discriminant_Specifications (N)) then
6374 
6375             --  Verify that new discriminants are used to constrain old ones
6376 
6377             D_Constraint :=
6378               First
6379                 (Constraints
6380                   (Constraint (Subtype_Indication (Type_Definition (N)))));
6381 
6382             Old_Disc := First_Discriminant (Parent_Type);
6383 
6384             while Present (D_Constraint) loop
6385                if Nkind (D_Constraint) /= N_Discriminant_Association then
6386 
6387                   --  Positional constraint. If it is a reference to a new
6388                   --  discriminant, it constrains the corresponding old one.
6389 
6390                   if Nkind (D_Constraint) = N_Identifier then
6391                      New_Disc := First_Discriminant (Derived_Type);
6392                      while Present (New_Disc) loop
6393                         exit when Chars (New_Disc) = Chars (D_Constraint);
6394                         Next_Discriminant (New_Disc);
6395                      end loop;
6396 
6397                      if Present (New_Disc) then
6398                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
6399                      end if;
6400                   end if;
6401 
6402                   Next_Discriminant (Old_Disc);
6403 
6404                   --  if this is a named constraint, search by name for the old
6405                   --  discriminants constrained by the new one.
6406 
6407                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
6408 
6409                   --  Find new discriminant with that name
6410 
6411                   New_Disc := First_Discriminant (Derived_Type);
6412                   while Present (New_Disc) loop
6413                      exit when
6414                        Chars (New_Disc) = Chars (Expression (D_Constraint));
6415                      Next_Discriminant (New_Disc);
6416                   end loop;
6417 
6418                   if Present (New_Disc) then
6419 
6420                      --  Verify that new discriminant renames some discriminant
6421                      --  of the parent type, and associate the new discriminant
6422                      --  with one or more old ones that it renames.
6423 
6424                      declare
6425                         Selector : Node_Id;
6426 
6427                      begin
6428                         Selector := First (Selector_Names (D_Constraint));
6429                         while Present (Selector) loop
6430                            Old_Disc := First_Discriminant (Parent_Type);
6431                            while Present (Old_Disc) loop
6432                               exit when Chars (Old_Disc) = Chars (Selector);
6433                               Next_Discriminant (Old_Disc);
6434                            end loop;
6435 
6436                            if Present (Old_Disc) then
6437                               Set_Corresponding_Discriminant
6438                                 (New_Disc, Old_Disc);
6439                            end if;
6440 
6441                            Next (Selector);
6442                         end loop;
6443                      end;
6444                   end if;
6445                end if;
6446 
6447                Next (D_Constraint);
6448             end loop;
6449 
6450             New_Disc := First_Discriminant (Derived_Type);
6451             while Present (New_Disc) loop
6452                if No (Corresponding_Discriminant (New_Disc)) then
6453                   Error_Msg_NE
6454                     ("new discriminant& must constrain old one", N, New_Disc);
6455 
6456                elsif not
6457                  Subtypes_Statically_Compatible
6458                    (Etype (New_Disc),
6459                     Etype (Corresponding_Discriminant (New_Disc)))
6460                then
6461                   Error_Msg_NE
6462                     ("& not statically compatible with parent discriminant",
6463                       N, New_Disc);
6464                end if;
6465 
6466                Next_Discriminant (New_Disc);
6467             end loop;
6468          end if;
6469 
6470       elsif Present (Discriminant_Specifications (N)) then
6471          Error_Msg_N
6472            ("missing discriminant constraint in untagged derivation", N);
6473       end if;
6474 
6475       --  The entity chain of the derived type includes the new discriminants
6476       --  but shares operations with the parent.
6477 
6478       if Present (Discriminant_Specifications (N)) then
6479          Old_Disc := First_Discriminant (Parent_Type);
6480          while Present (Old_Disc) loop
6481             if No (Next_Entity (Old_Disc))
6482               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
6483             then
6484                Set_Next_Entity
6485                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
6486                exit;
6487             end if;
6488 
6489             Next_Discriminant (Old_Disc);
6490          end loop;
6491 
6492       else
6493          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
6494          if Has_Discriminants (Parent_Type) then
6495             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
6496             Set_Discriminant_Constraint (
6497               Derived_Type, Discriminant_Constraint (Parent_Type));
6498          end if;
6499       end if;
6500 
6501       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
6502 
6503       Set_Has_Completion (Derived_Type);
6504 
6505       if Corr_Decl_Needed then
6506          Set_Stored_Constraint (Derived_Type, New_Constraint);
6507          Insert_After (N, Corr_Decl);
6508          Analyze (Corr_Decl);
6509          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
6510       end if;
6511    end Build_Derived_Concurrent_Type;
6512 
6513    ------------------------------------
6514    -- Build_Derived_Enumeration_Type --
6515    ------------------------------------
6516 
6517    procedure Build_Derived_Enumeration_Type
6518      (N            : Node_Id;
6519       Parent_Type  : Entity_Id;
6520       Derived_Type : Entity_Id)
6521    is
6522       Loc           : constant Source_Ptr := Sloc (N);
6523       Def           : constant Node_Id    := Type_Definition (N);
6524       Indic         : constant Node_Id    := Subtype_Indication (Def);
6525       Implicit_Base : Entity_Id;
6526       Literal       : Entity_Id;
6527       New_Lit       : Entity_Id;
6528       Literals_List : List_Id;
6529       Type_Decl     : Node_Id;
6530       Hi, Lo        : Node_Id;
6531       Rang_Expr     : Node_Id;
6532 
6533    begin
6534       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
6535       --  not have explicit literals lists we need to process types derived
6536       --  from them specially. This is handled by Derived_Standard_Character.
6537       --  If the parent type is a generic type, there are no literals either,
6538       --  and we construct the same skeletal representation as for the generic
6539       --  parent type.
6540 
6541       if Is_Standard_Character_Type (Parent_Type) then
6542          Derived_Standard_Character (N, Parent_Type, Derived_Type);
6543 
6544       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
6545          declare
6546             Lo : Node_Id;
6547             Hi : Node_Id;
6548 
6549          begin
6550             if Nkind (Indic) /= N_Subtype_Indication then
6551                Lo :=
6552                   Make_Attribute_Reference (Loc,
6553                     Attribute_Name => Name_First,
6554                     Prefix         => New_Occurrence_Of (Derived_Type, Loc));
6555                Set_Etype (Lo, Derived_Type);
6556 
6557                Hi :=
6558                   Make_Attribute_Reference (Loc,
6559                     Attribute_Name => Name_Last,
6560                     Prefix         => New_Occurrence_Of (Derived_Type, Loc));
6561                Set_Etype (Hi, Derived_Type);
6562 
6563                Set_Scalar_Range (Derived_Type,
6564                   Make_Range (Loc,
6565                     Low_Bound  => Lo,
6566                     High_Bound => Hi));
6567             else
6568 
6569                --   Analyze subtype indication and verify compatibility
6570                --   with parent type.
6571 
6572                if Base_Type (Process_Subtype (Indic, N)) /=
6573                   Base_Type (Parent_Type)
6574                then
6575                   Error_Msg_N
6576                     ("illegal constraint for formal discrete type", N);
6577                end if;
6578             end if;
6579          end;
6580 
6581       else
6582          --  If a constraint is present, analyze the bounds to catch
6583          --  premature usage of the derived literals.
6584 
6585          if Nkind (Indic) = N_Subtype_Indication
6586            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
6587          then
6588             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
6589             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
6590          end if;
6591 
6592          --  Introduce an implicit base type for the derived type even if there
6593          --  is no constraint attached to it, since this seems closer to the
6594          --  Ada semantics. Build a full type declaration tree for the derived
6595          --  type using the implicit base type as the defining identifier. The
6596          --  build a subtype declaration tree which applies the constraint (if
6597          --  any) have it replace the derived type declaration.
6598 
6599          Literal := First_Literal (Parent_Type);
6600          Literals_List := New_List;
6601          while Present (Literal)
6602            and then Ekind (Literal) = E_Enumeration_Literal
6603          loop
6604             --  Literals of the derived type have the same representation as
6605             --  those of the parent type, but this representation can be
6606             --  overridden by an explicit representation clause. Indicate
6607             --  that there is no explicit representation given yet. These
6608             --  derived literals are implicit operations of the new type,
6609             --  and can be overridden by explicit ones.
6610 
6611             if Nkind (Literal) = N_Defining_Character_Literal then
6612                New_Lit :=
6613                  Make_Defining_Character_Literal (Loc, Chars (Literal));
6614             else
6615                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
6616             end if;
6617 
6618             Set_Ekind                (New_Lit, E_Enumeration_Literal);
6619             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
6620             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
6621             Set_Enumeration_Rep_Expr (New_Lit, Empty);
6622             Set_Alias                (New_Lit, Literal);
6623             Set_Is_Known_Valid       (New_Lit, True);
6624 
6625             Append (New_Lit, Literals_List);
6626             Next_Literal (Literal);
6627          end loop;
6628 
6629          Implicit_Base :=
6630            Make_Defining_Identifier (Sloc (Derived_Type),
6631              Chars => New_External_Name (Chars (Derived_Type), 'B'));
6632 
6633          --  Indicate the proper nature of the derived type. This must be done
6634          --  before analysis of the literals, to recognize cases when a literal
6635          --  may be hidden by a previous explicit function definition (cf.
6636          --  c83031a).
6637 
6638          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
6639          Set_Etype (Derived_Type, Implicit_Base);
6640 
6641          Type_Decl :=
6642            Make_Full_Type_Declaration (Loc,
6643              Defining_Identifier => Implicit_Base,
6644              Discriminant_Specifications => No_List,
6645              Type_Definition =>
6646                Make_Enumeration_Type_Definition (Loc, Literals_List));
6647 
6648          Mark_Rewrite_Insertion (Type_Decl);
6649          Insert_Before (N, Type_Decl);
6650          Analyze (Type_Decl);
6651 
6652          --  The anonymous base now has a full declaration, but this base
6653          --  is not a first subtype.
6654 
6655          Set_Is_First_Subtype (Implicit_Base, False);
6656 
6657          --  After the implicit base is analyzed its Etype needs to be changed
6658          --  to reflect the fact that it is derived from the parent type which
6659          --  was ignored during analysis. We also set the size at this point.
6660 
6661          Set_Etype (Implicit_Base, Parent_Type);
6662 
6663          Set_Size_Info      (Implicit_Base,                 Parent_Type);
6664          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
6665          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
6666 
6667          --  Copy other flags from parent type
6668 
6669          Set_Has_Non_Standard_Rep
6670                             (Implicit_Base, Has_Non_Standard_Rep
6671                                                            (Parent_Type));
6672          Set_Has_Pragma_Ordered
6673                             (Implicit_Base, Has_Pragma_Ordered
6674                                                            (Parent_Type));
6675          Set_Has_Delayed_Freeze (Implicit_Base);
6676 
6677          --  Process the subtype indication including a validation check on the
6678          --  constraint, if any. If a constraint is given, its bounds must be
6679          --  implicitly converted to the new type.
6680 
6681          if Nkind (Indic) = N_Subtype_Indication then
6682             declare
6683                R : constant Node_Id :=
6684                      Range_Expression (Constraint (Indic));
6685 
6686             begin
6687                if Nkind (R) = N_Range then
6688                   Hi := Build_Scalar_Bound
6689                           (High_Bound (R), Parent_Type, Implicit_Base);
6690                   Lo := Build_Scalar_Bound
6691                           (Low_Bound  (R), Parent_Type, Implicit_Base);
6692 
6693                else
6694                   --  Constraint is a Range attribute. Replace with explicit
6695                   --  mention of the bounds of the prefix, which must be a
6696                   --  subtype.
6697 
6698                   Analyze (Prefix (R));
6699                   Hi :=
6700                     Convert_To (Implicit_Base,
6701                       Make_Attribute_Reference (Loc,
6702                         Attribute_Name => Name_Last,
6703                         Prefix =>
6704                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
6705 
6706                   Lo :=
6707                     Convert_To (Implicit_Base,
6708                       Make_Attribute_Reference (Loc,
6709                         Attribute_Name => Name_First,
6710                         Prefix =>
6711                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
6712                end if;
6713             end;
6714 
6715          else
6716             Hi :=
6717               Build_Scalar_Bound
6718                 (Type_High_Bound (Parent_Type),
6719                  Parent_Type, Implicit_Base);
6720             Lo :=
6721                Build_Scalar_Bound
6722                  (Type_Low_Bound (Parent_Type),
6723                   Parent_Type, Implicit_Base);
6724          end if;
6725 
6726          Rang_Expr :=
6727            Make_Range (Loc,
6728              Low_Bound  => Lo,
6729              High_Bound => Hi);
6730 
6731          --  If we constructed a default range for the case where no range
6732          --  was given, then the expressions in the range must not freeze
6733          --  since they do not correspond to expressions in the source.
6734 
6735          if Nkind (Indic) /= N_Subtype_Indication then
6736             Set_Must_Not_Freeze (Lo);
6737             Set_Must_Not_Freeze (Hi);
6738             Set_Must_Not_Freeze (Rang_Expr);
6739          end if;
6740 
6741          Rewrite (N,
6742            Make_Subtype_Declaration (Loc,
6743              Defining_Identifier => Derived_Type,
6744              Subtype_Indication =>
6745                Make_Subtype_Indication (Loc,
6746                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
6747                  Constraint =>
6748                    Make_Range_Constraint (Loc,
6749                      Range_Expression => Rang_Expr))));
6750 
6751          Analyze (N);
6752 
6753          --  Propagate the aspects from the original type declaration to the
6754          --  declaration of the implicit base.
6755 
6756          Move_Aspects (From => Original_Node (N), To => Type_Decl);
6757 
6758          --  Apply a range check. Since this range expression doesn't have an
6759          --  Etype, we have to specifically pass the Source_Typ parameter. Is
6760          --  this right???
6761 
6762          if Nkind (Indic) = N_Subtype_Indication then
6763             Apply_Range_Check
6764               (Range_Expression (Constraint (Indic)), Parent_Type,
6765                Source_Typ => Entity (Subtype_Mark (Indic)));
6766          end if;
6767       end if;
6768    end Build_Derived_Enumeration_Type;
6769 
6770    --------------------------------
6771    -- Build_Derived_Numeric_Type --
6772    --------------------------------
6773 
6774    procedure Build_Derived_Numeric_Type
6775      (N            : Node_Id;
6776       Parent_Type  : Entity_Id;
6777       Derived_Type : Entity_Id)
6778    is
6779       Loc           : constant Source_Ptr := Sloc (N);
6780       Tdef          : constant Node_Id    := Type_Definition (N);
6781       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
6782       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
6783       No_Constraint : constant Boolean    := Nkind (Indic) /=
6784                                                   N_Subtype_Indication;
6785       Implicit_Base : Entity_Id;
6786 
6787       Lo : Node_Id;
6788       Hi : Node_Id;
6789 
6790    begin
6791       --  Process the subtype indication including a validation check on
6792       --  the constraint if any.
6793 
6794       Discard_Node (Process_Subtype (Indic, N));
6795 
6796       --  Introduce an implicit base type for the derived type even if there
6797       --  is no constraint attached to it, since this seems closer to the Ada
6798       --  semantics.
6799 
6800       Implicit_Base :=
6801         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
6802 
6803       Set_Etype          (Implicit_Base, Parent_Base);
6804       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
6805       Set_Size_Info      (Implicit_Base,                 Parent_Base);
6806       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
6807       Set_Parent         (Implicit_Base, Parent (Derived_Type));
6808       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
6809 
6810       --  Set RM Size for discrete type or decimal fixed-point type
6811       --  Ordinary fixed-point is excluded, why???
6812 
6813       if Is_Discrete_Type (Parent_Base)
6814         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
6815       then
6816          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
6817       end if;
6818 
6819       Set_Has_Delayed_Freeze (Implicit_Base);
6820 
6821       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
6822       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
6823 
6824       Set_Scalar_Range (Implicit_Base,
6825         Make_Range (Loc,
6826           Low_Bound  => Lo,
6827           High_Bound => Hi));
6828 
6829       if Has_Infinities (Parent_Base) then
6830          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
6831       end if;
6832 
6833       --  The Derived_Type, which is the entity of the declaration, is a
6834       --  subtype of the implicit base. Its Ekind is a subtype, even in the
6835       --  absence of an explicit constraint.
6836 
6837       Set_Etype (Derived_Type, Implicit_Base);
6838 
6839       --  If we did not have a constraint, then the Ekind is set from the
6840       --  parent type (otherwise Process_Subtype has set the bounds)
6841 
6842       if No_Constraint then
6843          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
6844       end if;
6845 
6846       --  If we did not have a range constraint, then set the range from the
6847       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
6848 
6849       if No_Constraint or else not Has_Range_Constraint (Indic) then
6850          Set_Scalar_Range (Derived_Type,
6851            Make_Range (Loc,
6852              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
6853              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
6854          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
6855 
6856          if Has_Infinities (Parent_Type) then
6857             Set_Includes_Infinities (Scalar_Range (Derived_Type));
6858          end if;
6859 
6860          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
6861       end if;
6862 
6863       Set_Is_Descendant_Of_Address (Derived_Type,
6864         Is_Descendant_Of_Address (Parent_Type));
6865       Set_Is_Descendant_Of_Address (Implicit_Base,
6866         Is_Descendant_Of_Address (Parent_Type));
6867 
6868       --  Set remaining type-specific fields, depending on numeric type
6869 
6870       if Is_Modular_Integer_Type (Parent_Type) then
6871          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
6872 
6873          Set_Non_Binary_Modulus
6874            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
6875 
6876          Set_Is_Known_Valid
6877            (Implicit_Base, Is_Known_Valid (Parent_Base));
6878 
6879       elsif Is_Floating_Point_Type (Parent_Type) then
6880 
6881          --  Digits of base type is always copied from the digits value of
6882          --  the parent base type, but the digits of the derived type will
6883          --  already have been set if there was a constraint present.
6884 
6885          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6886          Set_Float_Rep    (Implicit_Base, Float_Rep    (Parent_Base));
6887 
6888          if No_Constraint then
6889             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
6890          end if;
6891 
6892       elsif Is_Fixed_Point_Type (Parent_Type) then
6893 
6894          --  Small of base type and derived type are always copied from the
6895          --  parent base type, since smalls never change. The delta of the
6896          --  base type is also copied from the parent base type. However the
6897          --  delta of the derived type will have been set already if a
6898          --  constraint was present.
6899 
6900          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
6901          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
6902          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
6903 
6904          if No_Constraint then
6905             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
6906          end if;
6907 
6908          --  The scale and machine radix in the decimal case are always
6909          --  copied from the parent base type.
6910 
6911          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
6912             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
6913             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
6914 
6915             Set_Machine_Radix_10
6916               (Derived_Type,  Machine_Radix_10 (Parent_Base));
6917             Set_Machine_Radix_10
6918               (Implicit_Base, Machine_Radix_10 (Parent_Base));
6919 
6920             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6921 
6922             if No_Constraint then
6923                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
6924 
6925             else
6926                --  the analysis of the subtype_indication sets the
6927                --  digits value of the derived type.
6928 
6929                null;
6930             end if;
6931          end if;
6932       end if;
6933 
6934       if Is_Integer_Type (Parent_Type) then
6935          Set_Has_Shift_Operator
6936            (Implicit_Base, Has_Shift_Operator (Parent_Type));
6937       end if;
6938 
6939       --  The type of the bounds is that of the parent type, and they
6940       --  must be converted to the derived type.
6941 
6942       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
6943 
6944       --  The implicit_base should be frozen when the derived type is frozen,
6945       --  but note that it is used in the conversions of the bounds. For fixed
6946       --  types we delay the determination of the bounds until the proper
6947       --  freezing point. For other numeric types this is rejected by GCC, for
6948       --  reasons that are currently unclear (???), so we choose to freeze the
6949       --  implicit base now. In the case of integers and floating point types
6950       --  this is harmless because subsequent representation clauses cannot
6951       --  affect anything, but it is still baffling that we cannot use the
6952       --  same mechanism for all derived numeric types.
6953 
6954       --  There is a further complication: actually some representation
6955       --  clauses can affect the implicit base type. For example, attribute
6956       --  definition clauses for stream-oriented attributes need to set the
6957       --  corresponding TSS entries on the base type, and this normally
6958       --  cannot be done after the base type is frozen, so the circuitry in
6959       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility
6960       --  and not use Set_TSS in this case.
6961 
6962       --  There are also consequences for the case of delayed representation
6963       --  aspects for some cases. For example, a Size aspect is delayed and
6964       --  should not be evaluated to the freeze point. This early freezing
6965       --  means that the size attribute evaluation happens too early???
6966 
6967       if Is_Fixed_Point_Type (Parent_Type) then
6968          Conditional_Delay (Implicit_Base, Parent_Type);
6969       else
6970          Freeze_Before (N, Implicit_Base);
6971       end if;
6972    end Build_Derived_Numeric_Type;
6973 
6974    --------------------------------
6975    -- Build_Derived_Private_Type --
6976    --------------------------------
6977 
6978    procedure Build_Derived_Private_Type
6979      (N             : Node_Id;
6980       Parent_Type   : Entity_Id;
6981       Derived_Type  : Entity_Id;
6982       Is_Completion : Boolean;
6983       Derive_Subps  : Boolean := True)
6984    is
6985       Loc       : constant Source_Ptr := Sloc (N);
6986       Par_Base  : constant Entity_Id  := Base_Type (Parent_Type);
6987       Par_Scope : constant Entity_Id  := Scope (Par_Base);
6988       Full_N    : constant Node_Id    := New_Copy_Tree (N);
6989       Full_Der  : Entity_Id           := New_Copy (Derived_Type);
6990       Full_P    : Entity_Id;
6991 
6992       procedure Build_Full_Derivation;
6993       --  Build full derivation, i.e. derive from the full view
6994 
6995       procedure Copy_And_Build;
6996       --  Copy derived type declaration, replace parent with its full view,
6997       --  and build derivation
6998 
6999       ---------------------------
7000       -- Build_Full_Derivation --
7001       ---------------------------
7002 
7003       procedure Build_Full_Derivation is
7004       begin
7005          --  If parent scope is not open, install the declarations
7006 
7007          if not In_Open_Scopes (Par_Scope) then
7008             Install_Private_Declarations (Par_Scope);
7009             Install_Visible_Declarations (Par_Scope);
7010             Copy_And_Build;
7011             Uninstall_Declarations (Par_Scope);
7012 
7013          --  If parent scope is open and in another unit, and parent has a
7014          --  completion, then the derivation is taking place in the visible
7015          --  part of a child unit. In that case retrieve the full view of
7016          --  the parent momentarily.
7017 
7018          elsif not In_Same_Source_Unit (N, Parent_Type) then
7019             Full_P := Full_View (Parent_Type);
7020             Exchange_Declarations (Parent_Type);
7021             Copy_And_Build;
7022             Exchange_Declarations (Full_P);
7023 
7024          --  Otherwise it is a local derivation
7025 
7026          else
7027             Copy_And_Build;
7028          end if;
7029       end Build_Full_Derivation;
7030 
7031       --------------------
7032       -- Copy_And_Build --
7033       --------------------
7034 
7035       procedure Copy_And_Build is
7036          Full_Parent : Entity_Id := Parent_Type;
7037 
7038       begin
7039          --  If the parent is itself derived from another private type,
7040          --  installing the private declarations has not affected its
7041          --  privacy status, so use its own full view explicitly.
7042 
7043          if Is_Private_Type (Full_Parent)
7044            and then Present (Full_View (Full_Parent))
7045          then
7046             Full_Parent := Full_View (Full_Parent);
7047          end if;
7048 
7049          --  And its underlying full view if necessary
7050 
7051          if Is_Private_Type (Full_Parent)
7052            and then Present (Underlying_Full_View (Full_Parent))
7053          then
7054             Full_Parent := Underlying_Full_View (Full_Parent);
7055          end if;
7056 
7057          --  For record, access and most enumeration types, derivation from
7058          --  the full view requires a fully-fledged declaration. In the other
7059          --  cases, just use an itype.
7060 
7061          if Ekind (Full_Parent) in Record_Kind
7062            or else Ekind (Full_Parent) in Access_Kind
7063            or else
7064              (Ekind (Full_Parent) in Enumeration_Kind
7065                and then not Is_Standard_Character_Type (Full_Parent)
7066                and then not Is_Generic_Type (Root_Type (Full_Parent)))
7067          then
7068             --  Copy and adjust declaration to provide a completion for what
7069             --  is originally a private declaration. Indicate that full view
7070             --  is internally generated.
7071 
7072             Set_Comes_From_Source (Full_N, False);
7073             Set_Comes_From_Source (Full_Der, False);
7074             Set_Parent (Full_Der, Full_N);
7075             Set_Defining_Identifier (Full_N, Full_Der);
7076 
7077             --  If there are no constraints, adjust the subtype mark
7078 
7079             if Nkind (Subtype_Indication (Type_Definition (Full_N))) /=
7080                                                        N_Subtype_Indication
7081             then
7082                Set_Subtype_Indication
7083                  (Type_Definition (Full_N),
7084                   New_Occurrence_Of (Full_Parent, Sloc (Full_N)));
7085             end if;
7086 
7087             Insert_After (N, Full_N);
7088 
7089             --  Build full view of derived type from full view of parent which
7090             --  is now installed. Subprograms have been derived on the partial
7091             --  view, the completion does not derive them anew.
7092 
7093             if Ekind (Full_Parent) in Record_Kind then
7094 
7095                --  If parent type is tagged, the completion inherits the proper
7096                --  primitive operations.
7097 
7098                if Is_Tagged_Type (Parent_Type) then
7099                   Build_Derived_Record_Type
7100                     (Full_N, Full_Parent, Full_Der, Derive_Subps);
7101                else
7102                   Build_Derived_Record_Type
7103                     (Full_N, Full_Parent, Full_Der, Derive_Subps => False);
7104                end if;
7105 
7106             else
7107                Build_Derived_Type
7108                  (Full_N, Full_Parent, Full_Der,
7109                   Is_Completion => False, Derive_Subps => False);
7110             end if;
7111 
7112             --  The full declaration has been introduced into the tree and
7113             --  processed in the step above. It should not be analyzed again
7114             --  (when encountered later in the current list of declarations)
7115             --  to prevent spurious name conflicts. The full entity remains
7116             --  invisible.
7117 
7118             Set_Analyzed (Full_N);
7119 
7120          else
7121             Full_Der :=
7122               Make_Defining_Identifier (Sloc (Derived_Type),
7123                 Chars => Chars (Derived_Type));
7124             Set_Is_Itype (Full_Der);
7125             Set_Associated_Node_For_Itype (Full_Der, N);
7126             Set_Parent (Full_Der, N);
7127             Build_Derived_Type
7128               (N, Full_Parent, Full_Der,
7129                Is_Completion => False, Derive_Subps => False);
7130          end if;
7131 
7132          Set_Has_Private_Declaration (Full_Der);
7133          Set_Has_Private_Declaration (Derived_Type);
7134 
7135          Set_Scope                (Full_Der, Scope (Derived_Type));
7136          Set_Is_First_Subtype     (Full_Der, Is_First_Subtype (Derived_Type));
7137          Set_Has_Size_Clause      (Full_Der, False);
7138          Set_Has_Alignment_Clause (Full_Der, False);
7139          Set_Has_Delayed_Freeze   (Full_Der);
7140          Set_Is_Frozen            (Full_Der, False);
7141          Set_Freeze_Node          (Full_Der, Empty);
7142          Set_Depends_On_Private   (Full_Der, Has_Private_Component (Full_Der));
7143          Set_Is_Public            (Full_Der, Is_Public (Derived_Type));
7144 
7145          --  The convention on the base type may be set in the private part
7146          --  and not propagated to the subtype until later, so we obtain the
7147          --  convention from the base type of the parent.
7148 
7149          Set_Convention (Full_Der, Convention (Base_Type (Full_Parent)));
7150       end Copy_And_Build;
7151 
7152    --  Start of processing for Build_Derived_Private_Type
7153 
7154    begin
7155       if Is_Tagged_Type (Parent_Type) then
7156          Full_P := Full_View (Parent_Type);
7157 
7158          --  A type extension of a type with unknown discriminants is an
7159          --  indefinite type that the back-end cannot handle directly.
7160          --  We treat it as a private type, and build a completion that is
7161          --  derived from the full view of the parent, and hopefully has
7162          --  known discriminants.
7163 
7164          --  If the full view of the parent type has an underlying record view,
7165          --  use it to generate the underlying record view of this derived type
7166          --  (required for chains of derivations with unknown discriminants).
7167 
7168          --  Minor optimization: we avoid the generation of useless underlying
7169          --  record view entities if the private type declaration has unknown
7170          --  discriminants but its corresponding full view has no
7171          --  discriminants.
7172 
7173          if Has_Unknown_Discriminants (Parent_Type)
7174            and then Present (Full_P)
7175            and then (Has_Discriminants (Full_P)
7176                       or else Present (Underlying_Record_View (Full_P)))
7177            and then not In_Open_Scopes (Par_Scope)
7178            and then Expander_Active
7179          then
7180             declare
7181                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
7182                New_Ext  : constant Node_Id :=
7183                             Copy_Separate_Tree
7184                               (Record_Extension_Part (Type_Definition (N)));
7185                Decl     : Node_Id;
7186 
7187             begin
7188                Build_Derived_Record_Type
7189                  (N, Parent_Type, Derived_Type, Derive_Subps);
7190 
7191                --  Build anonymous completion, as a derivation from the full
7192                --  view of the parent. This is not a completion in the usual
7193                --  sense, because the current type is not private.
7194 
7195                Decl :=
7196                  Make_Full_Type_Declaration (Loc,
7197                    Defining_Identifier => Full_Der,
7198                    Type_Definition     =>
7199                      Make_Derived_Type_Definition (Loc,
7200                        Subtype_Indication =>
7201                          New_Copy_Tree
7202                            (Subtype_Indication (Type_Definition (N))),
7203                        Record_Extension_Part => New_Ext));
7204 
7205                --  If the parent type has an underlying record view, use it
7206                --  here to build the new underlying record view.
7207 
7208                if Present (Underlying_Record_View (Full_P)) then
7209                   pragma Assert
7210                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
7211                        = N_Identifier);
7212                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
7213                     Underlying_Record_View (Full_P));
7214                end if;
7215 
7216                Install_Private_Declarations (Par_Scope);
7217                Install_Visible_Declarations (Par_Scope);
7218                Insert_Before (N, Decl);
7219 
7220                --  Mark entity as an underlying record view before analysis,
7221                --  to avoid generating the list of its primitive operations
7222                --  (which is not really required for this entity) and thus
7223                --  prevent spurious errors associated with missing overriding
7224                --  of abstract primitives (overridden only for Derived_Type).
7225 
7226                Set_Ekind (Full_Der, E_Record_Type);
7227                Set_Is_Underlying_Record_View (Full_Der);
7228                Set_Default_SSO (Full_Der);
7229 
7230                Analyze (Decl);
7231 
7232                pragma Assert (Has_Discriminants (Full_Der)
7233                  and then not Has_Unknown_Discriminants (Full_Der));
7234 
7235                Uninstall_Declarations (Par_Scope);
7236 
7237                --  Freeze the underlying record view, to prevent generation of
7238                --  useless dispatching information, which is simply shared with
7239                --  the real derived type.
7240 
7241                Set_Is_Frozen (Full_Der);
7242 
7243                --  If the derived type has access discriminants, create
7244                --  references to their anonymous types now, to prevent
7245                --  back-end problems when their first use is in generated
7246                --  bodies of primitives.
7247 
7248                declare
7249                   E : Entity_Id;
7250 
7251                begin
7252                   E := First_Entity (Full_Der);
7253 
7254                   while Present (E) loop
7255                      if Ekind (E) = E_Discriminant
7256                        and then Ekind (Etype (E)) = E_Anonymous_Access_Type
7257                      then
7258                         Build_Itype_Reference (Etype (E), Decl);
7259                      end if;
7260 
7261                      Next_Entity (E);
7262                   end loop;
7263                end;
7264 
7265                --  Set up links between real entity and underlying record view
7266 
7267                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
7268                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
7269             end;
7270 
7271          --  If discriminants are known, build derived record
7272 
7273          else
7274             Build_Derived_Record_Type
7275               (N, Parent_Type, Derived_Type, Derive_Subps);
7276          end if;
7277 
7278          return;
7279 
7280       elsif Has_Discriminants (Parent_Type) then
7281 
7282          --  Build partial view of derived type from partial view of parent.
7283          --  This must be done before building the full derivation because the
7284          --  second derivation will modify the discriminants of the first and
7285          --  the discriminants are chained with the rest of the components in
7286          --  the full derivation.
7287 
7288          Build_Derived_Record_Type
7289            (N, Parent_Type, Derived_Type, Derive_Subps);
7290 
7291          --  Build the full derivation if this is not the anonymous derived
7292          --  base type created by Build_Derived_Record_Type in the constrained
7293          --  case (see point 5. of its head comment) since we build it for the
7294          --  derived subtype. And skip it for protected types altogether, as
7295          --  gigi does not use these types directly.
7296 
7297          if Present (Full_View (Parent_Type))
7298            and then not Is_Itype (Derived_Type)
7299            and then not (Ekind (Full_View (Parent_Type)) in Protected_Kind)
7300          then
7301             declare
7302                Der_Base   : constant Entity_Id := Base_Type (Derived_Type);
7303                Discr      : Entity_Id;
7304                Last_Discr : Entity_Id;
7305 
7306             begin
7307                --  If this is not a completion, construct the implicit full
7308                --  view by deriving from the full view of the parent type.
7309                --  But if this is a completion, the derived private type
7310                --  being built is a full view and the full derivation can
7311                --  only be its underlying full view.
7312 
7313                Build_Full_Derivation;
7314 
7315                if not Is_Completion then
7316                   Set_Full_View (Derived_Type, Full_Der);
7317                else
7318                   Set_Underlying_Full_View (Derived_Type, Full_Der);
7319                end if;
7320 
7321                if not Is_Base_Type (Derived_Type) then
7322                   Set_Full_View (Der_Base, Base_Type (Full_Der));
7323                end if;
7324 
7325                --  Copy the discriminant list from full view to the partial
7326                --  view (base type and its subtype). Gigi requires that the
7327                --  partial and full views have the same discriminants.
7328 
7329                --  Note that since the partial view points to discriminants
7330                --  in the full view, their scope will be that of the full
7331                --  view. This might cause some front end problems and need
7332                --  adjustment???
7333 
7334                Discr := First_Discriminant (Base_Type (Full_Der));
7335                Set_First_Entity (Der_Base, Discr);
7336 
7337                loop
7338                   Last_Discr := Discr;
7339                   Next_Discriminant (Discr);
7340                   exit when No (Discr);
7341                end loop;
7342 
7343                Set_Last_Entity (Der_Base, Last_Discr);
7344                Set_First_Entity (Derived_Type, First_Entity (Der_Base));
7345                Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
7346 
7347                Set_Stored_Constraint
7348                  (Full_Der, Stored_Constraint (Derived_Type));
7349             end;
7350          end if;
7351 
7352       elsif Present (Full_View (Parent_Type))
7353         and then Has_Discriminants (Full_View (Parent_Type))
7354       then
7355          if Has_Unknown_Discriminants (Parent_Type)
7356            and then Nkind (Subtype_Indication (Type_Definition (N))) =
7357                                                          N_Subtype_Indication
7358          then
7359             Error_Msg_N
7360               ("cannot constrain type with unknown discriminants",
7361                Subtype_Indication (Type_Definition (N)));
7362             return;
7363          end if;
7364 
7365          --  If this is not a completion, construct the implicit full view by
7366          --  deriving from the full view of the parent type. But if this is a
7367          --  completion, the derived private type being built is a full view
7368          --  and the full derivation can only be its underlying full view.
7369 
7370          Build_Full_Derivation;
7371 
7372          if not Is_Completion then
7373             Set_Full_View (Derived_Type, Full_Der);
7374          else
7375             Set_Underlying_Full_View (Derived_Type, Full_Der);
7376          end if;
7377 
7378          --  In any case, the primitive operations are inherited from the
7379          --  parent type, not from the internal full view.
7380 
7381          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
7382 
7383          if Derive_Subps then
7384             Derive_Subprograms (Parent_Type, Derived_Type);
7385          end if;
7386 
7387          Set_Stored_Constraint (Derived_Type, No_Elist);
7388          Set_Is_Constrained
7389            (Derived_Type, Is_Constrained (Full_View (Parent_Type)));
7390 
7391       else
7392          --  Untagged type, No discriminants on either view
7393 
7394          if Nkind (Subtype_Indication (Type_Definition (N))) =
7395                                                    N_Subtype_Indication
7396          then
7397             Error_Msg_N
7398               ("illegal constraint on type without discriminants", N);
7399          end if;
7400 
7401          if Present (Discriminant_Specifications (N))
7402            and then Present (Full_View (Parent_Type))
7403            and then not Is_Tagged_Type (Full_View (Parent_Type))
7404          then
7405             Error_Msg_N ("cannot add discriminants to untagged type", N);
7406          end if;
7407 
7408          Set_Stored_Constraint  (Derived_Type, No_Elist);
7409          Set_Is_Constrained     (Derived_Type, Is_Constrained (Parent_Type));
7410          Set_Is_Controlled      (Derived_Type, Is_Controlled  (Parent_Type));
7411          Set_Disable_Controlled (Derived_Type, Disable_Controlled
7412                                                               (Parent_Type));
7413          Set_Has_Controlled_Component
7414                                 (Derived_Type, Has_Controlled_Component
7415                                                               (Parent_Type));
7416 
7417          --  Direct controlled types do not inherit Finalize_Storage_Only flag
7418 
7419          if not Is_Controlled_Active (Parent_Type) then
7420             Set_Finalize_Storage_Only
7421               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
7422          end if;
7423 
7424          --  If this is not a completion, construct the implicit full view by
7425          --  deriving from the full view of the parent type.
7426 
7427          --  ??? If the parent is untagged private and its completion is
7428          --  tagged, this mechanism will not work because we cannot derive from
7429          --  the tagged full view unless we have an extension.
7430 
7431          if Present (Full_View (Parent_Type))
7432            and then not Is_Tagged_Type (Full_View (Parent_Type))
7433            and then not Is_Completion
7434          then
7435             Build_Full_Derivation;
7436             Set_Full_View (Derived_Type, Full_Der);
7437          end if;
7438       end if;
7439 
7440       Set_Has_Unknown_Discriminants (Derived_Type,
7441         Has_Unknown_Discriminants (Parent_Type));
7442 
7443       if Is_Private_Type (Derived_Type) then
7444          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7445       end if;
7446 
7447       --  If the parent base type is in scope, add the derived type to its
7448       --  list of private dependents, because its full view may become
7449       --  visible subsequently (in a nested private part, a body, or in a
7450       --  further child unit).
7451 
7452       if Is_Private_Type (Par_Base) and then In_Open_Scopes (Par_Scope) then
7453          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
7454 
7455          --  Check for unusual case where a type completed by a private
7456          --  derivation occurs within a package nested in a child unit, and
7457          --  the parent is declared in an ancestor.
7458 
7459          if Is_Child_Unit (Scope (Current_Scope))
7460            and then Is_Completion
7461            and then In_Private_Part (Current_Scope)
7462            and then Scope (Parent_Type) /= Current_Scope
7463 
7464            --  Note that if the parent has a completion in the private part,
7465            --  (which is itself a derivation from some other private type)
7466            --  it is that completion that is visible, there is no full view
7467            --  available, and no special processing is needed.
7468 
7469            and then Present (Full_View (Parent_Type))
7470          then
7471             --  In this case, the full view of the parent type will become
7472             --  visible in the body of the enclosing child, and only then will
7473             --  the current type be possibly non-private. Build an underlying
7474             --  full view that will be installed when the enclosing child body
7475             --  is compiled.
7476 
7477             if Present (Underlying_Full_View (Derived_Type)) then
7478                Full_Der := Underlying_Full_View (Derived_Type);
7479             else
7480                Build_Full_Derivation;
7481                Set_Underlying_Full_View (Derived_Type, Full_Der);
7482             end if;
7483 
7484             --  The full view will be used to swap entities on entry/exit to
7485             --  the body, and must appear in the entity list for the package.
7486 
7487             Append_Entity (Full_Der, Scope (Derived_Type));
7488          end if;
7489       end if;
7490    end Build_Derived_Private_Type;
7491 
7492    -------------------------------
7493    -- Build_Derived_Record_Type --
7494    -------------------------------
7495 
7496    --  1. INTRODUCTION
7497 
7498    --  Ideally we would like to use the same model of type derivation for
7499    --  tagged and untagged record types. Unfortunately this is not quite
7500    --  possible because the semantics of representation clauses is different
7501    --  for tagged and untagged records under inheritance. Consider the
7502    --  following:
7503 
7504    --     type R (...) is [tagged] record ... end record;
7505    --     type T (...) is new R (...) [with ...];
7506 
7507    --  The representation clauses for T can specify a completely different
7508    --  record layout from R's. Hence the same component can be placed in two
7509    --  very different positions in objects of type T and R. If R and T are
7510    --  tagged types, representation clauses for T can only specify the layout
7511    --  of non inherited components, thus components that are common in R and T
7512    --  have the same position in objects of type R and T.
7513 
7514    --  This has two implications. The first is that the entire tree for R's
7515    --  declaration needs to be copied for T in the untagged case, so that T
7516    --  can be viewed as a record type of its own with its own representation
7517    --  clauses. The second implication is the way we handle discriminants.
7518    --  Specifically, in the untagged case we need a way to communicate to Gigi
7519    --  what are the real discriminants in the record, while for the semantics
7520    --  we need to consider those introduced by the user to rename the
7521    --  discriminants in the parent type. This is handled by introducing the
7522    --  notion of stored discriminants. See below for more.
7523 
7524    --  Fortunately the way regular components are inherited can be handled in
7525    --  the same way in tagged and untagged types.
7526 
7527    --  To complicate things a bit more the private view of a private extension
7528    --  cannot be handled in the same way as the full view (for one thing the
7529    --  semantic rules are somewhat different). We will explain what differs
7530    --  below.
7531 
7532    --  2. DISCRIMINANTS UNDER INHERITANCE
7533 
7534    --  The semantic rules governing the discriminants of derived types are
7535    --  quite subtle.
7536 
7537    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
7538    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
7539 
7540    --  If parent type has discriminants, then the discriminants that are
7541    --  declared in the derived type are [3.4 (11)]:
7542 
7543    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
7544    --    there is one;
7545 
7546    --  o Otherwise, each discriminant of the parent type (implicitly declared
7547    --    in the same order with the same specifications). In this case, the
7548    --    discriminants are said to be "inherited", or if unknown in the parent
7549    --    are also unknown in the derived type.
7550 
7551    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
7552 
7553    --  o The parent subtype must be constrained;
7554 
7555    --  o If the parent type is not a tagged type, then each discriminant of
7556    --    the derived type must be used in the constraint defining a parent
7557    --    subtype. [Implementation note: This ensures that the new discriminant
7558    --    can share storage with an existing discriminant.]
7559 
7560    --  For the derived type each discriminant of the parent type is either
7561    --  inherited, constrained to equal some new discriminant of the derived
7562    --  type, or constrained to the value of an expression.
7563 
7564    --  When inherited or constrained to equal some new discriminant, the
7565    --  parent discriminant and the discriminant of the derived type are said
7566    --  to "correspond".
7567 
7568    --  If a discriminant of the parent type is constrained to a specific value
7569    --  in the derived type definition, then the discriminant is said to be
7570    --  "specified" by that derived type definition.
7571 
7572    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
7573 
7574    --  We have spoken about stored discriminants in point 1 (introduction)
7575    --  above. There are two sort of stored discriminants: implicit and
7576    --  explicit. As long as the derived type inherits the same discriminants as
7577    --  the root record type, stored discriminants are the same as regular
7578    --  discriminants, and are said to be implicit. However, if any discriminant
7579    --  in the root type was renamed in the derived type, then the derived
7580    --  type will contain explicit stored discriminants. Explicit stored
7581    --  discriminants are discriminants in addition to the semantically visible
7582    --  discriminants defined for the derived type. Stored discriminants are
7583    --  used by Gigi to figure out what are the physical discriminants in
7584    --  objects of the derived type (see precise definition in einfo.ads).
7585    --  As an example, consider the following:
7586 
7587    --           type R  (D1, D2, D3 : Int) is record ... end record;
7588    --           type T1 is new R;
7589    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
7590    --           type T3 is new T2;
7591    --           type T4 (Y : Int) is new T3 (Y, 99);
7592 
7593    --  The following table summarizes the discriminants and stored
7594    --  discriminants in R and T1 through T4.
7595 
7596    --   Type      Discrim     Stored Discrim  Comment
7597    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
7598    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
7599    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
7600    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
7601    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
7602 
7603    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
7604    --  find the corresponding discriminant in the parent type, while
7605    --  Original_Record_Component (abbreviated ORC below), the actual physical
7606    --  component that is renamed. Finally the field Is_Completely_Hidden
7607    --  (abbreviated ICH below) is set for all explicit stored discriminants
7608    --  (see einfo.ads for more info). For the above example this gives:
7609 
7610    --                 Discrim     CD        ORC     ICH
7611    --                 ^^^^^^^     ^^        ^^^     ^^^
7612    --                 D1 in R    empty     itself    no
7613    --                 D2 in R    empty     itself    no
7614    --                 D3 in R    empty     itself    no
7615 
7616    --                 D1 in T1  D1 in R    itself    no
7617    --                 D2 in T1  D2 in R    itself    no
7618    --                 D3 in T1  D3 in R    itself    no
7619 
7620    --                 X1 in T2  D3 in T1  D3 in T2   no
7621    --                 X2 in T2  D1 in T1  D1 in T2   no
7622    --                 D1 in T2   empty    itself    yes
7623    --                 D2 in T2   empty    itself    yes
7624    --                 D3 in T2   empty    itself    yes
7625 
7626    --                 X1 in T3  X1 in T2  D3 in T3   no
7627    --                 X2 in T3  X2 in T2  D1 in T3   no
7628    --                 D1 in T3   empty    itself    yes
7629    --                 D2 in T3   empty    itself    yes
7630    --                 D3 in T3   empty    itself    yes
7631 
7632    --                 Y  in T4  X1 in T3  D3 in T3   no
7633    --                 D1 in T3   empty    itself    yes
7634    --                 D2 in T3   empty    itself    yes
7635    --                 D3 in T3   empty    itself    yes
7636 
7637    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
7638 
7639    --  Type derivation for tagged types is fairly straightforward. If no
7640    --  discriminants are specified by the derived type, these are inherited
7641    --  from the parent. No explicit stored discriminants are ever necessary.
7642    --  The only manipulation that is done to the tree is that of adding a
7643    --  _parent field with parent type and constrained to the same constraint
7644    --  specified for the parent in the derived type definition. For instance:
7645 
7646    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
7647    --           type T1 is new R with null record;
7648    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
7649 
7650    --  are changed into:
7651 
7652    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
7653    --              _parent : R (D1, D2, D3);
7654    --           end record;
7655 
7656    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
7657    --              _parent : T1 (X2, 88, X1);
7658    --           end record;
7659 
7660    --  The discriminants actually present in R, T1 and T2 as well as their CD,
7661    --  ORC and ICH fields are:
7662 
7663    --                 Discrim     CD        ORC     ICH
7664    --                 ^^^^^^^     ^^        ^^^     ^^^
7665    --                 D1 in R    empty     itself    no
7666    --                 D2 in R    empty     itself    no
7667    --                 D3 in R    empty     itself    no
7668 
7669    --                 D1 in T1  D1 in R    D1 in R   no
7670    --                 D2 in T1  D2 in R    D2 in R   no
7671    --                 D3 in T1  D3 in R    D3 in R   no
7672 
7673    --                 X1 in T2  D3 in T1   D3 in R   no
7674    --                 X2 in T2  D1 in T1   D1 in R   no
7675 
7676    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
7677    --
7678    --  Regardless of whether we dealing with a tagged or untagged type
7679    --  we will transform all derived type declarations of the form
7680    --
7681    --               type T is new R (...) [with ...];
7682    --  or
7683    --               subtype S is R (...);
7684    --               type T is new S [with ...];
7685    --  into
7686    --               type BT is new R [with ...];
7687    --               subtype T is BT (...);
7688    --
7689    --  That is, the base derived type is constrained only if it has no
7690    --  discriminants. The reason for doing this is that GNAT's semantic model
7691    --  assumes that a base type with discriminants is unconstrained.
7692    --
7693    --  Note that, strictly speaking, the above transformation is not always
7694    --  correct. Consider for instance the following excerpt from ACVC b34011a:
7695    --
7696    --       procedure B34011A is
7697    --          type REC (D : integer := 0) is record
7698    --             I : Integer;
7699    --          end record;
7700 
7701    --          package P is
7702    --             type T6 is new Rec;
7703    --             function F return T6;
7704    --          end P;
7705 
7706    --          use P;
7707    --          package Q6 is
7708    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
7709    --          end Q6;
7710    --
7711    --  The definition of Q6.U is illegal. However transforming Q6.U into
7712 
7713    --             type BaseU is new T6;
7714    --             subtype U is BaseU (Q6.F.I)
7715 
7716    --  turns U into a legal subtype, which is incorrect. To avoid this problem
7717    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
7718    --  the transformation described above.
7719 
7720    --  There is another instance where the above transformation is incorrect.
7721    --  Consider:
7722 
7723    --          package Pack is
7724    --             type Base (D : Integer) is tagged null record;
7725    --             procedure P (X : Base);
7726 
7727    --             type Der is new Base (2) with null record;
7728    --             procedure P (X : Der);
7729    --          end Pack;
7730 
7731    --  Then the above transformation turns this into
7732 
7733    --             type Der_Base is new Base with null record;
7734    --             --  procedure P (X : Base) is implicitly inherited here
7735    --             --  as procedure P (X : Der_Base).
7736 
7737    --             subtype Der is Der_Base (2);
7738    --             procedure P (X : Der);
7739    --             --  The overriding of P (X : Der_Base) is illegal since we
7740    --             --  have a parameter conformance problem.
7741 
7742    --  To get around this problem, after having semantically processed Der_Base
7743    --  and the rewritten subtype declaration for Der, we copy Der_Base field
7744    --  Discriminant_Constraint from Der so that when parameter conformance is
7745    --  checked when P is overridden, no semantic errors are flagged.
7746 
7747    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
7748 
7749    --  Regardless of whether we are dealing with a tagged or untagged type
7750    --  we will transform all derived type declarations of the form
7751 
7752    --               type R (D1, .., Dn : ...) is [tagged] record ...;
7753    --               type T is new R [with ...];
7754    --  into
7755    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
7756 
7757    --  The reason for such transformation is that it allows us to implement a
7758    --  very clean form of component inheritance as explained below.
7759 
7760    --  Note that this transformation is not achieved by direct tree rewriting
7761    --  and manipulation, but rather by redoing the semantic actions that the
7762    --  above transformation will entail. This is done directly in routine
7763    --  Inherit_Components.
7764 
7765    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
7766 
7767    --  In both tagged and untagged derived types, regular non discriminant
7768    --  components are inherited in the derived type from the parent type. In
7769    --  the absence of discriminants component, inheritance is straightforward
7770    --  as components can simply be copied from the parent.
7771 
7772    --  If the parent has discriminants, inheriting components constrained with
7773    --  these discriminants requires caution. Consider the following example:
7774 
7775    --      type R  (D1, D2 : Positive) is [tagged] record
7776    --         S : String (D1 .. D2);
7777    --      end record;
7778 
7779    --      type T1                is new R        [with null record];
7780    --      type T2 (X : positive) is new R (1, X) [with null record];
7781 
7782    --  As explained in 6. above, T1 is rewritten as
7783    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
7784    --  which makes the treatment for T1 and T2 identical.
7785 
7786    --  What we want when inheriting S, is that references to D1 and D2 in R are
7787    --  replaced with references to their correct constraints, i.e. D1 and D2 in
7788    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
7789    --  with either discriminant references in the derived type or expressions.
7790    --  This replacement is achieved as follows: before inheriting R's
7791    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
7792    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
7793    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
7794    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
7795    --  by String (1 .. X).
7796 
7797    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
7798 
7799    --  We explain here the rules governing private type extensions relevant to
7800    --  type derivation. These rules are explained on the following example:
7801 
7802    --      type D [(...)] is new A [(...)] with private;      <-- partial view
7803    --      type D [(...)] is new P [(...)] with null record;  <-- full view
7804 
7805    --  Type A is called the ancestor subtype of the private extension.
7806    --  Type P is the parent type of the full view of the private extension. It
7807    --  must be A or a type derived from A.
7808 
7809    --  The rules concerning the discriminants of private type extensions are
7810    --  [7.3(10-13)]:
7811 
7812    --  o If a private extension inherits known discriminants from the ancestor
7813    --    subtype, then the full view must also inherit its discriminants from
7814    --    the ancestor subtype and the parent subtype of the full view must be
7815    --    constrained if and only if the ancestor subtype is constrained.
7816 
7817    --  o If a partial view has unknown discriminants, then the full view may
7818    --    define a definite or an indefinite subtype, with or without
7819    --    discriminants.
7820 
7821    --  o If a partial view has neither known nor unknown discriminants, then
7822    --    the full view must define a definite subtype.
7823 
7824    --  o If the ancestor subtype of a private extension has constrained
7825    --    discriminants, then the parent subtype of the full view must impose a
7826    --    statically matching constraint on those discriminants.
7827 
7828    --  This means that only the following forms of private extensions are
7829    --  allowed:
7830 
7831    --      type D is new A with private;      <-- partial view
7832    --      type D is new P with null record;  <-- full view
7833 
7834    --  If A has no discriminants than P has no discriminants, otherwise P must
7835    --  inherit A's discriminants.
7836 
7837    --      type D is new A (...) with private;      <-- partial view
7838    --      type D is new P (:::) with null record;  <-- full view
7839 
7840    --  P must inherit A's discriminants and (...) and (:::) must statically
7841    --  match.
7842 
7843    --      subtype A is R (...);
7844    --      type D is new A with private;      <-- partial view
7845    --      type D is new P with null record;  <-- full view
7846 
7847    --  P must have inherited R's discriminants and must be derived from A or
7848    --  any of its subtypes.
7849 
7850    --      type D (..) is new A with private;              <-- partial view
7851    --      type D (..) is new P [(:::)] with null record;  <-- full view
7852 
7853    --  No specific constraints on P's discriminants or constraint (:::).
7854    --  Note that A can be unconstrained, but the parent subtype P must either
7855    --  be constrained or (:::) must be present.
7856 
7857    --      type D (..) is new A [(...)] with private;      <-- partial view
7858    --      type D (..) is new P [(:::)] with null record;  <-- full view
7859 
7860    --  P's constraints on A's discriminants must statically match those
7861    --  imposed by (...).
7862 
7863    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
7864 
7865    --  The full view of a private extension is handled exactly as described
7866    --  above. The model chose for the private view of a private extension is
7867    --  the same for what concerns discriminants (i.e. they receive the same
7868    --  treatment as in the tagged case). However, the private view of the
7869    --  private extension always inherits the components of the parent base,
7870    --  without replacing any discriminant reference. Strictly speaking this is
7871    --  incorrect. However, Gigi never uses this view to generate code so this
7872    --  is a purely semantic issue. In theory, a set of transformations similar
7873    --  to those given in 5. and 6. above could be applied to private views of
7874    --  private extensions to have the same model of component inheritance as
7875    --  for non private extensions. However, this is not done because it would
7876    --  further complicate private type processing. Semantically speaking, this
7877    --  leaves us in an uncomfortable situation. As an example consider:
7878 
7879    --          package Pack is
7880    --             type R (D : integer) is tagged record
7881    --                S : String (1 .. D);
7882    --             end record;
7883    --             procedure P (X : R);
7884    --             type T is new R (1) with private;
7885    --          private
7886    --             type T is new R (1) with null record;
7887    --          end;
7888 
7889    --  This is transformed into:
7890 
7891    --          package Pack is
7892    --             type R (D : integer) is tagged record
7893    --                S : String (1 .. D);
7894    --             end record;
7895    --             procedure P (X : R);
7896    --             type T is new R (1) with private;
7897    --          private
7898    --             type BaseT is new R with null record;
7899    --             subtype  T is BaseT (1);
7900    --          end;
7901 
7902    --  (strictly speaking the above is incorrect Ada)
7903 
7904    --  From the semantic standpoint the private view of private extension T
7905    --  should be flagged as constrained since one can clearly have
7906    --
7907    --             Obj : T;
7908    --
7909    --  in a unit withing Pack. However, when deriving subprograms for the
7910    --  private view of private extension T, T must be seen as unconstrained
7911    --  since T has discriminants (this is a constraint of the current
7912    --  subprogram derivation model). Thus, when processing the private view of
7913    --  a private extension such as T, we first mark T as unconstrained, we
7914    --  process it, we perform program derivation and just before returning from
7915    --  Build_Derived_Record_Type we mark T as constrained.
7916 
7917    --  ??? Are there are other uncomfortable cases that we will have to
7918    --      deal with.
7919 
7920    --  10. RECORD_TYPE_WITH_PRIVATE complications
7921 
7922    --  Types that are derived from a visible record type and have a private
7923    --  extension present other peculiarities. They behave mostly like private
7924    --  types, but if they have primitive operations defined, these will not
7925    --  have the proper signatures for further inheritance, because other
7926    --  primitive operations will use the implicit base that we define for
7927    --  private derivations below. This affect subprogram inheritance (see
7928    --  Derive_Subprograms for details). We also derive the implicit base from
7929    --  the base type of the full view, so that the implicit base is a record
7930    --  type and not another private type, This avoids infinite loops.
7931 
7932    procedure Build_Derived_Record_Type
7933      (N            : Node_Id;
7934       Parent_Type  : Entity_Id;
7935       Derived_Type : Entity_Id;
7936       Derive_Subps : Boolean := True)
7937    is
7938       Discriminant_Specs : constant Boolean :=
7939                              Present (Discriminant_Specifications (N));
7940       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
7941       Loc                : constant Source_Ptr := Sloc (N);
7942       Private_Extension  : constant Boolean :=
7943                              Nkind (N) = N_Private_Extension_Declaration;
7944       Assoc_List         : Elist_Id;
7945       Constraint_Present : Boolean;
7946       Constrs            : Elist_Id;
7947       Discrim            : Entity_Id;
7948       Indic              : Node_Id;
7949       Inherit_Discrims   : Boolean := False;
7950       Last_Discrim       : Entity_Id;
7951       New_Base           : Entity_Id;
7952       New_Decl           : Node_Id;
7953       New_Discrs         : Elist_Id;
7954       New_Indic          : Node_Id;
7955       Parent_Base        : Entity_Id;
7956       Save_Etype         : Entity_Id;
7957       Save_Discr_Constr  : Elist_Id;
7958       Save_Next_Entity   : Entity_Id;
7959       Type_Def           : Node_Id;
7960 
7961       Discs : Elist_Id := New_Elmt_List;
7962       --  An empty Discs list means that there were no constraints in the
7963       --  subtype indication or that there was an error processing it.
7964 
7965    begin
7966       if Ekind (Parent_Type) = E_Record_Type_With_Private
7967         and then Present (Full_View (Parent_Type))
7968         and then Has_Discriminants (Parent_Type)
7969       then
7970          Parent_Base := Base_Type (Full_View (Parent_Type));
7971       else
7972          Parent_Base := Base_Type (Parent_Type);
7973       end if;
7974 
7975       --  AI05-0115 : if this is a derivation from a private type in some
7976       --  other scope that may lead to invisible components for the derived
7977       --  type, mark it accordingly.
7978 
7979       if Is_Private_Type (Parent_Type) then
7980          if Scope (Parent_Type) = Scope (Derived_Type) then
7981             null;
7982 
7983          elsif In_Open_Scopes (Scope (Parent_Type))
7984            and then In_Private_Part (Scope (Parent_Type))
7985          then
7986             null;
7987 
7988          else
7989             Set_Has_Private_Ancestor (Derived_Type);
7990          end if;
7991 
7992       else
7993          Set_Has_Private_Ancestor
7994            (Derived_Type, Has_Private_Ancestor (Parent_Type));
7995       end if;
7996 
7997       --  Before we start the previously documented transformations, here is
7998       --  little fix for size and alignment of tagged types. Normally when we
7999       --  derive type D from type P, we copy the size and alignment of P as the
8000       --  default for D, and in the absence of explicit representation clauses
8001       --  for D, the size and alignment are indeed the same as the parent.
8002 
8003       --  But this is wrong for tagged types, since fields may be added, and
8004       --  the default size may need to be larger, and the default alignment may
8005       --  need to be larger.
8006 
8007       --  We therefore reset the size and alignment fields in the tagged case.
8008       --  Note that the size and alignment will in any case be at least as
8009       --  large as the parent type (since the derived type has a copy of the
8010       --  parent type in the _parent field)
8011 
8012       --  The type is also marked as being tagged here, which is needed when
8013       --  processing components with a self-referential anonymous access type
8014       --  in the call to Check_Anonymous_Access_Components below. Note that
8015       --  this flag is also set later on for completeness.
8016 
8017       if Is_Tagged then
8018          Set_Is_Tagged_Type (Derived_Type);
8019          Init_Size_Align    (Derived_Type);
8020       end if;
8021 
8022       --  STEP 0a: figure out what kind of derived type declaration we have
8023 
8024       if Private_Extension then
8025          Type_Def := N;
8026          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
8027          Set_Default_SSO (Derived_Type);
8028 
8029       else
8030          Type_Def := Type_Definition (N);
8031 
8032          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
8033          --  Parent_Base can be a private type or private extension. However,
8034          --  for tagged types with an extension the newly added fields are
8035          --  visible and hence the Derived_Type is always an E_Record_Type.
8036          --  (except that the parent may have its own private fields).
8037          --  For untagged types we preserve the Ekind of the Parent_Base.
8038 
8039          if Present (Record_Extension_Part (Type_Def)) then
8040             Set_Ekind (Derived_Type, E_Record_Type);
8041             Set_Default_SSO (Derived_Type);
8042 
8043             --  Create internal access types for components with anonymous
8044             --  access types.
8045 
8046             if Ada_Version >= Ada_2005 then
8047                Check_Anonymous_Access_Components
8048                  (N, Derived_Type, Derived_Type,
8049                    Component_List (Record_Extension_Part (Type_Def)));
8050             end if;
8051 
8052          else
8053             Set_Ekind (Derived_Type, Ekind (Parent_Base));
8054          end if;
8055       end if;
8056 
8057       --  Indic can either be an N_Identifier if the subtype indication
8058       --  contains no constraint or an N_Subtype_Indication if the subtype
8059       --  indication has a constraint.
8060 
8061       Indic := Subtype_Indication (Type_Def);
8062       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
8063 
8064       --  Check that the type has visible discriminants. The type may be
8065       --  a private type with unknown discriminants whose full view has
8066       --  discriminants which are invisible.
8067 
8068       if Constraint_Present then
8069          if not Has_Discriminants (Parent_Base)
8070            or else
8071              (Has_Unknown_Discriminants (Parent_Base)
8072                and then Is_Private_Type (Parent_Base))
8073          then
8074             Error_Msg_N
8075               ("invalid constraint: type has no discriminant",
8076                  Constraint (Indic));
8077 
8078             Constraint_Present := False;
8079             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
8080 
8081          elsif Is_Constrained (Parent_Type) then
8082             Error_Msg_N
8083                ("invalid constraint: parent type is already constrained",
8084                   Constraint (Indic));
8085 
8086             Constraint_Present := False;
8087             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
8088          end if;
8089       end if;
8090 
8091       --  STEP 0b: If needed, apply transformation given in point 5. above
8092 
8093       if not Private_Extension
8094         and then Has_Discriminants (Parent_Type)
8095         and then not Discriminant_Specs
8096         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
8097       then
8098          --  First, we must analyze the constraint (see comment in point 5.)
8099          --  The constraint may come from the subtype indication of the full
8100          --  declaration.
8101 
8102          if Constraint_Present then
8103             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
8104 
8105          --  If there is no explicit constraint, there might be one that is
8106          --  inherited from a constrained parent type. In that case verify that
8107          --  it conforms to the constraint in the partial view. In perverse
8108          --  cases the parent subtypes of the partial and full view can have
8109          --  different constraints.
8110 
8111          elsif Present (Stored_Constraint (Parent_Type)) then
8112             New_Discrs := Stored_Constraint (Parent_Type);
8113 
8114          else
8115             New_Discrs := No_Elist;
8116          end if;
8117 
8118          if Has_Discriminants (Derived_Type)
8119            and then Has_Private_Declaration (Derived_Type)
8120            and then Present (Discriminant_Constraint (Derived_Type))
8121            and then Present (New_Discrs)
8122          then
8123             --  Verify that constraints of the full view statically match
8124             --  those given in the partial view.
8125 
8126             declare
8127                C1, C2 : Elmt_Id;
8128 
8129             begin
8130                C1 := First_Elmt (New_Discrs);
8131                C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
8132                while Present (C1) and then Present (C2) loop
8133                   if Fully_Conformant_Expressions (Node (C1), Node (C2))
8134                     or else
8135                       (Is_OK_Static_Expression (Node (C1))
8136                         and then Is_OK_Static_Expression (Node (C2))
8137                         and then
8138                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
8139                   then
8140                      null;
8141 
8142                   else
8143                      if Constraint_Present then
8144                         Error_Msg_N
8145                           ("constraint not conformant to previous declaration",
8146                            Node (C1));
8147                      else
8148                         Error_Msg_N
8149                           ("constraint of full view is incompatible "
8150                            & "with partial view", N);
8151                      end if;
8152                   end if;
8153 
8154                   Next_Elmt (C1);
8155                   Next_Elmt (C2);
8156                end loop;
8157             end;
8158          end if;
8159 
8160          --  Insert and analyze the declaration for the unconstrained base type
8161 
8162          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
8163 
8164          New_Decl :=
8165            Make_Full_Type_Declaration (Loc,
8166               Defining_Identifier => New_Base,
8167               Type_Definition     =>
8168                 Make_Derived_Type_Definition (Loc,
8169                   Abstract_Present      => Abstract_Present (Type_Def),
8170                   Limited_Present       => Limited_Present (Type_Def),
8171                   Subtype_Indication    =>
8172                     New_Occurrence_Of (Parent_Base, Loc),
8173                   Record_Extension_Part =>
8174                     Relocate_Node (Record_Extension_Part (Type_Def)),
8175                   Interface_List        => Interface_List (Type_Def)));
8176 
8177          Set_Parent (New_Decl, Parent (N));
8178          Mark_Rewrite_Insertion (New_Decl);
8179          Insert_Before (N, New_Decl);
8180 
8181          --  In the extension case, make sure ancestor is frozen appropriately
8182          --  (see also non-discriminated case below).
8183 
8184          if Present (Record_Extension_Part (Type_Def))
8185            or else Is_Interface (Parent_Base)
8186          then
8187             Freeze_Before (New_Decl, Parent_Type);
8188          end if;
8189 
8190          --  Note that this call passes False for the Derive_Subps parameter
8191          --  because subprogram derivation is deferred until after creating
8192          --  the subtype (see below).
8193 
8194          Build_Derived_Type
8195            (New_Decl, Parent_Base, New_Base,
8196             Is_Completion => False, Derive_Subps => False);
8197 
8198          --  ??? This needs re-examination to determine whether the
8199          --  above call can simply be replaced by a call to Analyze.
8200 
8201          Set_Analyzed (New_Decl);
8202 
8203          --  Insert and analyze the declaration for the constrained subtype
8204 
8205          if Constraint_Present then
8206             New_Indic :=
8207               Make_Subtype_Indication (Loc,
8208                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
8209                 Constraint   => Relocate_Node (Constraint (Indic)));
8210 
8211          else
8212             declare
8213                Constr_List : constant List_Id := New_List;
8214                C           : Elmt_Id;
8215                Expr        : Node_Id;
8216 
8217             begin
8218                C := First_Elmt (Discriminant_Constraint (Parent_Type));
8219                while Present (C) loop
8220                   Expr := Node (C);
8221 
8222                   --  It is safe here to call New_Copy_Tree since we called
8223                   --  Force_Evaluation on each constraint previously
8224                   --  in Build_Discriminant_Constraints.
8225 
8226                   Append (New_Copy_Tree (Expr), To => Constr_List);
8227 
8228                   Next_Elmt (C);
8229                end loop;
8230 
8231                New_Indic :=
8232                  Make_Subtype_Indication (Loc,
8233                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
8234                    Constraint   =>
8235                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
8236             end;
8237          end if;
8238 
8239          Rewrite (N,
8240            Make_Subtype_Declaration (Loc,
8241              Defining_Identifier => Derived_Type,
8242              Subtype_Indication  => New_Indic));
8243 
8244          Analyze (N);
8245 
8246          --  Derivation of subprograms must be delayed until the full subtype
8247          --  has been established, to ensure proper overriding of subprograms
8248          --  inherited by full types. If the derivations occurred as part of
8249          --  the call to Build_Derived_Type above, then the check for type
8250          --  conformance would fail because earlier primitive subprograms
8251          --  could still refer to the full type prior the change to the new
8252          --  subtype and hence would not match the new base type created here.
8253          --  Subprograms are not derived, however, when Derive_Subps is False
8254          --  (since otherwise there could be redundant derivations).
8255 
8256          if Derive_Subps then
8257             Derive_Subprograms (Parent_Type, Derived_Type);
8258          end if;
8259 
8260          --  For tagged types the Discriminant_Constraint of the new base itype
8261          --  is inherited from the first subtype so that no subtype conformance
8262          --  problem arise when the first subtype overrides primitive
8263          --  operations inherited by the implicit base type.
8264 
8265          if Is_Tagged then
8266             Set_Discriminant_Constraint
8267               (New_Base, Discriminant_Constraint (Derived_Type));
8268          end if;
8269 
8270          return;
8271       end if;
8272 
8273       --  If we get here Derived_Type will have no discriminants or it will be
8274       --  a discriminated unconstrained base type.
8275 
8276       --  STEP 1a: perform preliminary actions/checks for derived tagged types
8277 
8278       if Is_Tagged then
8279 
8280          --  The parent type is frozen for non-private extensions (RM 13.14(7))
8281          --  The declaration of a specific descendant of an interface type
8282          --  freezes the interface type (RM 13.14).
8283 
8284          if not Private_Extension or else Is_Interface (Parent_Base) then
8285             Freeze_Before (N, Parent_Type);
8286          end if;
8287 
8288          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
8289          --  cannot be declared at a deeper level than its parent type is
8290          --  removed. The check on derivation within a generic body is also
8291          --  relaxed, but there's a restriction that a derived tagged type
8292          --  cannot be declared in a generic body if it's derived directly
8293          --  or indirectly from a formal type of that generic.
8294 
8295          if Ada_Version >= Ada_2005 then
8296             if Present (Enclosing_Generic_Body (Derived_Type)) then
8297                declare
8298                   Ancestor_Type : Entity_Id;
8299 
8300                begin
8301                   --  Check to see if any ancestor of the derived type is a
8302                   --  formal type.
8303 
8304                   Ancestor_Type := Parent_Type;
8305                   while not Is_Generic_Type (Ancestor_Type)
8306                     and then Etype (Ancestor_Type) /= Ancestor_Type
8307                   loop
8308                      Ancestor_Type := Etype (Ancestor_Type);
8309                   end loop;
8310 
8311                   --  If the derived type does have a formal type as an
8312                   --  ancestor, then it's an error if the derived type is
8313                   --  declared within the body of the generic unit that
8314                   --  declares the formal type in its generic formal part. It's
8315                   --  sufficient to check whether the ancestor type is declared
8316                   --  inside the same generic body as the derived type (such as
8317                   --  within a nested generic spec), in which case the
8318                   --  derivation is legal. If the formal type is declared
8319                   --  outside of that generic body, then it's guaranteed that
8320                   --  the derived type is declared within the generic body of
8321                   --  the generic unit declaring the formal type.
8322 
8323                   if Is_Generic_Type (Ancestor_Type)
8324                     and then Enclosing_Generic_Body (Ancestor_Type) /=
8325                                Enclosing_Generic_Body (Derived_Type)
8326                   then
8327                      Error_Msg_NE
8328                        ("parent type of& must not be descendant of formal type"
8329                           & " of an enclosing generic body",
8330                             Indic, Derived_Type);
8331                   end if;
8332                end;
8333             end if;
8334 
8335          elsif Type_Access_Level (Derived_Type) /=
8336                  Type_Access_Level (Parent_Type)
8337            and then not Is_Generic_Type (Derived_Type)
8338          then
8339             if Is_Controlled (Parent_Type) then
8340                Error_Msg_N
8341                  ("controlled type must be declared at the library level",
8342                   Indic);
8343             else
8344                Error_Msg_N
8345                  ("type extension at deeper accessibility level than parent",
8346                   Indic);
8347             end if;
8348 
8349          else
8350             declare
8351                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
8352             begin
8353                if Present (GB)
8354                  and then GB /= Enclosing_Generic_Body (Parent_Base)
8355                then
8356                   Error_Msg_NE
8357                     ("parent type of& must not be outside generic body"
8358                        & " (RM 3.9.1(4))",
8359                          Indic, Derived_Type);
8360                end if;
8361             end;
8362          end if;
8363       end if;
8364 
8365       --  Ada 2005 (AI-251)
8366 
8367       if Ada_Version >= Ada_2005 and then Is_Tagged then
8368 
8369          --  "The declaration of a specific descendant of an interface type
8370          --  freezes the interface type" (RM 13.14).
8371 
8372          declare
8373             Iface : Node_Id;
8374          begin
8375             if Is_Non_Empty_List (Interface_List (Type_Def)) then
8376                Iface := First (Interface_List (Type_Def));
8377                while Present (Iface) loop
8378                   Freeze_Before (N, Etype (Iface));
8379                   Next (Iface);
8380                end loop;
8381             end if;
8382          end;
8383       end if;
8384 
8385       --  STEP 1b : preliminary cleanup of the full view of private types
8386 
8387       --  If the type is already marked as having discriminants, then it's the
8388       --  completion of a private type or private extension and we need to
8389       --  retain the discriminants from the partial view if the current
8390       --  declaration has Discriminant_Specifications so that we can verify
8391       --  conformance. However, we must remove any existing components that
8392       --  were inherited from the parent (and attached in Copy_And_Swap)
8393       --  because the full type inherits all appropriate components anyway, and
8394       --  we do not want the partial view's components interfering.
8395 
8396       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
8397          Discrim := First_Discriminant (Derived_Type);
8398          loop
8399             Last_Discrim := Discrim;
8400             Next_Discriminant (Discrim);
8401             exit when No (Discrim);
8402          end loop;
8403 
8404          Set_Last_Entity (Derived_Type, Last_Discrim);
8405 
8406       --  In all other cases wipe out the list of inherited components (even
8407       --  inherited discriminants), it will be properly rebuilt here.
8408 
8409       else
8410          Set_First_Entity (Derived_Type, Empty);
8411          Set_Last_Entity  (Derived_Type, Empty);
8412       end if;
8413 
8414       --  STEP 1c: Initialize some flags for the Derived_Type
8415 
8416       --  The following flags must be initialized here so that
8417       --  Process_Discriminants can check that discriminants of tagged types do
8418       --  not have a default initial value and that access discriminants are
8419       --  only specified for limited records. For completeness, these flags are
8420       --  also initialized along with all the other flags below.
8421 
8422       --  AI-419: Limitedness is not inherited from an interface parent, so to
8423       --  be limited in that case the type must be explicitly declared as
8424       --  limited. However, task and protected interfaces are always limited.
8425 
8426       if Limited_Present (Type_Def) then
8427          Set_Is_Limited_Record (Derived_Type);
8428 
8429       elsif Is_Limited_Record (Parent_Type)
8430         or else (Present (Full_View (Parent_Type))
8431                   and then Is_Limited_Record (Full_View (Parent_Type)))
8432       then
8433          if not Is_Interface (Parent_Type)
8434            or else Is_Synchronized_Interface (Parent_Type)
8435            or else Is_Protected_Interface (Parent_Type)
8436            or else Is_Task_Interface (Parent_Type)
8437          then
8438             Set_Is_Limited_Record (Derived_Type);
8439          end if;
8440       end if;
8441 
8442       --  STEP 2a: process discriminants of derived type if any
8443 
8444       Push_Scope (Derived_Type);
8445 
8446       if Discriminant_Specs then
8447          Set_Has_Unknown_Discriminants (Derived_Type, False);
8448 
8449          --  The following call initializes fields Has_Discriminants and
8450          --  Discriminant_Constraint, unless we are processing the completion
8451          --  of a private type declaration.
8452 
8453          Check_Or_Process_Discriminants (N, Derived_Type);
8454 
8455          --  For untagged types, the constraint on the Parent_Type must be
8456          --  present and is used to rename the discriminants.
8457 
8458          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
8459             Error_Msg_N ("untagged parent must have discriminants", Indic);
8460 
8461          elsif not Is_Tagged and then not Constraint_Present then
8462             Error_Msg_N
8463               ("discriminant constraint needed for derived untagged records",
8464                Indic);
8465 
8466          --  Otherwise the parent subtype must be constrained unless we have a
8467          --  private extension.
8468 
8469          elsif not Constraint_Present
8470            and then not Private_Extension
8471            and then not Is_Constrained (Parent_Type)
8472          then
8473             Error_Msg_N
8474               ("unconstrained type not allowed in this context", Indic);
8475 
8476          elsif Constraint_Present then
8477             --  The following call sets the field Corresponding_Discriminant
8478             --  for the discriminants in the Derived_Type.
8479 
8480             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
8481 
8482             --  For untagged types all new discriminants must rename
8483             --  discriminants in the parent. For private extensions new
8484             --  discriminants cannot rename old ones (implied by [7.3(13)]).
8485 
8486             Discrim := First_Discriminant (Derived_Type);
8487             while Present (Discrim) loop
8488                if not Is_Tagged
8489                  and then No (Corresponding_Discriminant (Discrim))
8490                then
8491                   Error_Msg_N
8492                     ("new discriminants must constrain old ones", Discrim);
8493 
8494                elsif Private_Extension
8495                  and then Present (Corresponding_Discriminant (Discrim))
8496                then
8497                   Error_Msg_N
8498                     ("only static constraints allowed for parent"
8499                      & " discriminants in the partial view", Indic);
8500                   exit;
8501                end if;
8502 
8503                --  If a new discriminant is used in the constraint, then its
8504                --  subtype must be statically compatible with the parent
8505                --  discriminant's subtype (3.7(15)).
8506 
8507                --  However, if the record contains an array constrained by
8508                --  the discriminant but with some different bound, the compiler
8509                --  attemps to create a smaller range for the discriminant type.
8510                --  (See exp_ch3.Adjust_Discriminants). In this case, where
8511                --  the discriminant type is a scalar type, the check must use
8512                --  the original discriminant type in the parent declaration.
8513 
8514                declare
8515                   Corr_Disc : constant Entity_Id :=
8516                                 Corresponding_Discriminant (Discrim);
8517                   Disc_Type : constant Entity_Id := Etype (Discrim);
8518                   Corr_Type : Entity_Id;
8519 
8520                begin
8521                   if Present (Corr_Disc) then
8522                      if Is_Scalar_Type (Disc_Type) then
8523                         Corr_Type :=
8524                            Entity (Discriminant_Type (Parent (Corr_Disc)));
8525                      else
8526                         Corr_Type := Etype (Corr_Disc);
8527                      end if;
8528 
8529                      if not
8530                         Subtypes_Statically_Compatible (Disc_Type, Corr_Type)
8531                      then
8532                         Error_Msg_N
8533                           ("subtype must be compatible "
8534                            & "with parent discriminant",
8535                            Discrim);
8536                      end if;
8537                   end if;
8538                end;
8539 
8540                Next_Discriminant (Discrim);
8541             end loop;
8542 
8543             --  Check whether the constraints of the full view statically
8544             --  match those imposed by the parent subtype [7.3(13)].
8545 
8546             if Present (Stored_Constraint (Derived_Type)) then
8547                declare
8548                   C1, C2 : Elmt_Id;
8549 
8550                begin
8551                   C1 := First_Elmt (Discs);
8552                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
8553                   while Present (C1) and then Present (C2) loop
8554                      if not
8555                        Fully_Conformant_Expressions (Node (C1), Node (C2))
8556                      then
8557                         Error_Msg_N
8558                           ("not conformant with previous declaration",
8559                            Node (C1));
8560                      end if;
8561 
8562                      Next_Elmt (C1);
8563                      Next_Elmt (C2);
8564                   end loop;
8565                end;
8566             end if;
8567          end if;
8568 
8569       --  STEP 2b: No new discriminants, inherit discriminants if any
8570 
8571       else
8572          if Private_Extension then
8573             Set_Has_Unknown_Discriminants
8574               (Derived_Type,
8575                Has_Unknown_Discriminants (Parent_Type)
8576                  or else Unknown_Discriminants_Present (N));
8577 
8578          --  The partial view of the parent may have unknown discriminants,
8579          --  but if the full view has discriminants and the parent type is
8580          --  in scope they must be inherited.
8581 
8582          elsif Has_Unknown_Discriminants (Parent_Type)
8583            and then
8584             (not Has_Discriminants (Parent_Type)
8585               or else not In_Open_Scopes (Scope (Parent_Type)))
8586          then
8587             Set_Has_Unknown_Discriminants (Derived_Type);
8588          end if;
8589 
8590          if not Has_Unknown_Discriminants (Derived_Type)
8591            and then not Has_Unknown_Discriminants (Parent_Base)
8592            and then Has_Discriminants (Parent_Type)
8593          then
8594             Inherit_Discrims := True;
8595             Set_Has_Discriminants
8596               (Derived_Type, True);
8597             Set_Discriminant_Constraint
8598               (Derived_Type, Discriminant_Constraint (Parent_Base));
8599          end if;
8600 
8601          --  The following test is true for private types (remember
8602          --  transformation 5. is not applied to those) and in an error
8603          --  situation.
8604 
8605          if Constraint_Present then
8606             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
8607          end if;
8608 
8609          --  For now mark a new derived type as constrained only if it has no
8610          --  discriminants. At the end of Build_Derived_Record_Type we properly
8611          --  set this flag in the case of private extensions. See comments in
8612          --  point 9. just before body of Build_Derived_Record_Type.
8613 
8614          Set_Is_Constrained
8615            (Derived_Type,
8616             not (Inherit_Discrims
8617                   or else Has_Unknown_Discriminants (Derived_Type)));
8618       end if;
8619 
8620       --  STEP 3: initialize fields of derived type
8621 
8622       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
8623       Set_Stored_Constraint (Derived_Type, No_Elist);
8624 
8625       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
8626       --  but cannot be interfaces
8627 
8628       if not Private_Extension
8629          and then Ekind (Derived_Type) /= E_Private_Type
8630          and then Ekind (Derived_Type) /= E_Limited_Private_Type
8631       then
8632          if Interface_Present (Type_Def) then
8633             Analyze_Interface_Declaration (Derived_Type, Type_Def);
8634          end if;
8635 
8636          Set_Interfaces (Derived_Type, No_Elist);
8637       end if;
8638 
8639       --  Fields inherited from the Parent_Type
8640 
8641       Set_Has_Specified_Layout
8642         (Derived_Type, Has_Specified_Layout     (Parent_Type));
8643       Set_Is_Limited_Composite
8644         (Derived_Type, Is_Limited_Composite     (Parent_Type));
8645       Set_Is_Private_Composite
8646         (Derived_Type, Is_Private_Composite     (Parent_Type));
8647 
8648       if Is_Tagged_Type (Parent_Type) then
8649          Set_No_Tagged_Streams_Pragma
8650            (Derived_Type, No_Tagged_Streams_Pragma (Parent_Type));
8651       end if;
8652 
8653       --  Fields inherited from the Parent_Base
8654 
8655       Set_Has_Controlled_Component
8656         (Derived_Type, Has_Controlled_Component (Parent_Base));
8657       Set_Has_Non_Standard_Rep
8658         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
8659       Set_Has_Primitive_Operations
8660         (Derived_Type, Has_Primitive_Operations (Parent_Base));
8661 
8662       --  Fields inherited from the Parent_Base in the non-private case
8663 
8664       if Ekind (Derived_Type) = E_Record_Type then
8665          Set_Has_Complex_Representation
8666            (Derived_Type, Has_Complex_Representation (Parent_Base));
8667       end if;
8668 
8669       --  Fields inherited from the Parent_Base for record types
8670 
8671       if Is_Record_Type (Derived_Type) then
8672          declare
8673             Parent_Full : Entity_Id;
8674 
8675          begin
8676             --  Ekind (Parent_Base) is not necessarily E_Record_Type since
8677             --  Parent_Base can be a private type or private extension. Go
8678             --  to the full view here to get the E_Record_Type specific flags.
8679 
8680             if Present (Full_View (Parent_Base)) then
8681                Parent_Full := Full_View (Parent_Base);
8682             else
8683                Parent_Full := Parent_Base;
8684             end if;
8685 
8686             Set_OK_To_Reorder_Components
8687               (Derived_Type, OK_To_Reorder_Components (Parent_Full));
8688          end;
8689       end if;
8690 
8691       --  Set fields for private derived types
8692 
8693       if Is_Private_Type (Derived_Type) then
8694          Set_Depends_On_Private (Derived_Type, True);
8695          Set_Private_Dependents (Derived_Type, New_Elmt_List);
8696 
8697       --  Inherit fields from non private record types. If this is the
8698       --  completion of a derivation from a private type, the parent itself
8699       --  is private, and the attributes come from its full view, which must
8700       --  be present.
8701 
8702       else
8703          if Is_Private_Type (Parent_Base)
8704            and then not Is_Record_Type (Parent_Base)
8705          then
8706             Set_Component_Alignment
8707               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
8708             Set_C_Pass_By_Copy
8709               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
8710          else
8711             Set_Component_Alignment
8712               (Derived_Type, Component_Alignment (Parent_Base));
8713             Set_C_Pass_By_Copy
8714               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
8715          end if;
8716       end if;
8717 
8718       --  Set fields for tagged types
8719 
8720       if Is_Tagged then
8721          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
8722 
8723          --  All tagged types defined in Ada.Finalization are controlled
8724 
8725          if Chars (Scope (Derived_Type)) = Name_Finalization
8726            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
8727            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
8728          then
8729             Set_Is_Controlled (Derived_Type);
8730          else
8731             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
8732          end if;
8733 
8734          --  Minor optimization: there is no need to generate the class-wide
8735          --  entity associated with an underlying record view.
8736 
8737          if not Is_Underlying_Record_View (Derived_Type) then
8738             Make_Class_Wide_Type (Derived_Type);
8739          end if;
8740 
8741          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
8742 
8743          if Has_Discriminants (Derived_Type)
8744            and then Constraint_Present
8745          then
8746             Set_Stored_Constraint
8747               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
8748          end if;
8749 
8750          if Ada_Version >= Ada_2005 then
8751             declare
8752                Ifaces_List : Elist_Id;
8753 
8754             begin
8755                --  Checks rules 3.9.4 (13/2 and 14/2)
8756 
8757                if Comes_From_Source (Derived_Type)
8758                  and then not Is_Private_Type (Derived_Type)
8759                  and then Is_Interface (Parent_Type)
8760                  and then not Is_Interface (Derived_Type)
8761                then
8762                   if Is_Task_Interface (Parent_Type) then
8763                      Error_Msg_N
8764                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
8765                         Derived_Type);
8766 
8767                   elsif Is_Protected_Interface (Parent_Type) then
8768                      Error_Msg_N
8769                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
8770                         Derived_Type);
8771                   end if;
8772                end if;
8773 
8774                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
8775 
8776                Check_Interfaces (N, Type_Def);
8777 
8778                --  Ada 2005 (AI-251): Collect the list of progenitors that are
8779                --  not already in the parents.
8780 
8781                Collect_Interfaces
8782                  (T               => Derived_Type,
8783                   Ifaces_List     => Ifaces_List,
8784                   Exclude_Parents => True);
8785 
8786                Set_Interfaces (Derived_Type, Ifaces_List);
8787 
8788                --  If the derived type is the anonymous type created for
8789                --  a declaration whose parent has a constraint, propagate
8790                --  the interface list to the source type. This must be done
8791                --  prior to the completion of the analysis of the source type
8792                --  because the components in the extension may contain current
8793                --  instances whose legality depends on some ancestor.
8794 
8795                if Is_Itype (Derived_Type) then
8796                   declare
8797                      Def : constant Node_Id :=
8798                              Associated_Node_For_Itype (Derived_Type);
8799                   begin
8800                      if Present (Def)
8801                        and then Nkind (Def) = N_Full_Type_Declaration
8802                      then
8803                         Set_Interfaces
8804                           (Defining_Identifier (Def), Ifaces_List);
8805                      end if;
8806                   end;
8807                end if;
8808 
8809                --  A derived type inherits any class-wide invariants coming
8810                --  from a parent type or an interface. Note that the invariant
8811                --  procedure of the parent type should not be inherited because
8812                --  the derived type may define invariants of its own.
8813 
8814                if Ada_Version >= Ada_2012
8815                  and then not Is_Interface (Derived_Type)
8816                then
8817                   if Has_Inherited_Invariants (Parent_Type)
8818                     or else Has_Inheritable_Invariants (Parent_Type)
8819                   then
8820                      Set_Has_Inherited_Invariants (Derived_Type);
8821 
8822                   elsif not Is_Empty_Elmt_List (Ifaces_List) then
8823                      declare
8824                         Iface      : Entity_Id;
8825                         Iface_Elmt : Elmt_Id;
8826 
8827                      begin
8828                         Iface_Elmt := First_Elmt (Ifaces_List);
8829                         while Present (Iface_Elmt) loop
8830                            Iface := Node (Iface_Elmt);
8831 
8832                            if Has_Inheritable_Invariants (Iface) then
8833                               Set_Has_Inherited_Invariants (Derived_Type);
8834                               exit;
8835                            end if;
8836 
8837                            Next_Elmt (Iface_Elmt);
8838                         end loop;
8839                      end;
8840                   end if;
8841                end if;
8842 
8843                --  A type extension is automatically Ghost when one of its
8844                --  progenitors is Ghost (SPARK RM 6.9(9)). This property is
8845                --  also inherited when the parent type is Ghost, but this is
8846                --  done in Build_Derived_Type as the mechanism also handles
8847                --  untagged derivations.
8848 
8849                if Implements_Ghost_Interface (Derived_Type) then
8850                   Set_Is_Ghost_Entity (Derived_Type);
8851                end if;
8852             end;
8853          end if;
8854 
8855       else
8856          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
8857          Set_Has_Non_Standard_Rep
8858                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
8859       end if;
8860 
8861       --  STEP 4: Inherit components from the parent base and constrain them.
8862       --          Apply the second transformation described in point 6. above.
8863 
8864       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
8865         or else not Has_Discriminants (Parent_Type)
8866         or else not Is_Constrained (Parent_Type)
8867       then
8868          Constrs := Discs;
8869       else
8870          Constrs := Discriminant_Constraint (Parent_Type);
8871       end if;
8872 
8873       Assoc_List :=
8874         Inherit_Components
8875           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
8876 
8877       --  STEP 5a: Copy the parent record declaration for untagged types
8878 
8879       if not Is_Tagged then
8880 
8881          --  Discriminant_Constraint (Derived_Type) has been properly
8882          --  constructed. Save it and temporarily set it to Empty because we
8883          --  do not want the call to New_Copy_Tree below to mess this list.
8884 
8885          if Has_Discriminants (Derived_Type) then
8886             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
8887             Set_Discriminant_Constraint (Derived_Type, No_Elist);
8888          else
8889             Save_Discr_Constr := No_Elist;
8890          end if;
8891 
8892          --  Save the Etype field of Derived_Type. It is correctly set now,
8893          --  but the call to New_Copy tree may remap it to point to itself,
8894          --  which is not what we want. Ditto for the Next_Entity field.
8895 
8896          Save_Etype       := Etype (Derived_Type);
8897          Save_Next_Entity := Next_Entity (Derived_Type);
8898 
8899          --  Assoc_List maps all stored discriminants in the Parent_Base to
8900          --  stored discriminants in the Derived_Type. It is fundamental that
8901          --  no types or itypes with discriminants other than the stored
8902          --  discriminants appear in the entities declared inside
8903          --  Derived_Type, since the back end cannot deal with it.
8904 
8905          New_Decl :=
8906            New_Copy_Tree
8907              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
8908 
8909          --  Restore the fields saved prior to the New_Copy_Tree call
8910          --  and compute the stored constraint.
8911 
8912          Set_Etype       (Derived_Type, Save_Etype);
8913          Set_Next_Entity (Derived_Type, Save_Next_Entity);
8914 
8915          if Has_Discriminants (Derived_Type) then
8916             Set_Discriminant_Constraint
8917               (Derived_Type, Save_Discr_Constr);
8918             Set_Stored_Constraint
8919               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
8920             Replace_Components (Derived_Type, New_Decl);
8921             Set_Has_Implicit_Dereference
8922               (Derived_Type, Has_Implicit_Dereference (Parent_Type));
8923          end if;
8924 
8925          --  Insert the new derived type declaration
8926 
8927          Rewrite (N, New_Decl);
8928 
8929       --  STEP 5b: Complete the processing for record extensions in generics
8930 
8931       --  There is no completion for record extensions declared in the
8932       --  parameter part of a generic, so we need to complete processing for
8933       --  these generic record extensions here. The Record_Type_Definition call
8934       --  will change the Ekind of the components from E_Void to E_Component.
8935 
8936       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
8937          Record_Type_Definition (Empty, Derived_Type);
8938 
8939       --  STEP 5c: Process the record extension for non private tagged types
8940 
8941       elsif not Private_Extension then
8942          Expand_Record_Extension (Derived_Type, Type_Def);
8943 
8944          --  Note : previously in ASIS mode we set the Parent_Subtype of the
8945          --  derived type to propagate some semantic information. This led
8946          --  to other ASIS failures and has been removed.
8947 
8948          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
8949          --  implemented interfaces if we are in expansion mode
8950 
8951          if Expander_Active
8952            and then Has_Interfaces (Derived_Type)
8953          then
8954             Add_Interface_Tag_Components (N, Derived_Type);
8955          end if;
8956 
8957          --  Analyze the record extension
8958 
8959          Record_Type_Definition
8960            (Record_Extension_Part (Type_Def), Derived_Type);
8961       end if;
8962 
8963       End_Scope;
8964 
8965       --  Nothing else to do if there is an error in the derivation.
8966       --  An unusual case: the full view may be derived from a type in an
8967       --  instance, when the partial view was used illegally as an actual
8968       --  in that instance, leading to a circular definition.
8969 
8970       if Etype (Derived_Type) = Any_Type
8971         or else Etype (Parent_Type) = Derived_Type
8972       then
8973          return;
8974       end if;
8975 
8976       --  Set delayed freeze and then derive subprograms, we need to do
8977       --  this in this order so that derived subprograms inherit the
8978       --  derived freeze if necessary.
8979 
8980       Set_Has_Delayed_Freeze (Derived_Type);
8981 
8982       if Derive_Subps then
8983          Derive_Subprograms (Parent_Type, Derived_Type);
8984       end if;
8985 
8986       --  If we have a private extension which defines a constrained derived
8987       --  type mark as constrained here after we have derived subprograms. See
8988       --  comment on point 9. just above the body of Build_Derived_Record_Type.
8989 
8990       if Private_Extension and then Inherit_Discrims then
8991          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
8992             Set_Is_Constrained          (Derived_Type, True);
8993             Set_Discriminant_Constraint (Derived_Type, Discs);
8994 
8995          elsif Is_Constrained (Parent_Type) then
8996             Set_Is_Constrained
8997               (Derived_Type, True);
8998             Set_Discriminant_Constraint
8999               (Derived_Type, Discriminant_Constraint (Parent_Type));
9000          end if;
9001       end if;
9002 
9003       --  Update the class-wide type, which shares the now-completed entity
9004       --  list with its specific type. In case of underlying record views,
9005       --  we do not generate the corresponding class wide entity.
9006 
9007       if Is_Tagged
9008         and then not Is_Underlying_Record_View (Derived_Type)
9009       then
9010          Set_First_Entity
9011            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
9012          Set_Last_Entity
9013            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
9014       end if;
9015 
9016       Check_Function_Writable_Actuals (N);
9017    end Build_Derived_Record_Type;
9018 
9019    ------------------------
9020    -- Build_Derived_Type --
9021    ------------------------
9022 
9023    procedure Build_Derived_Type
9024      (N             : Node_Id;
9025       Parent_Type   : Entity_Id;
9026       Derived_Type  : Entity_Id;
9027       Is_Completion : Boolean;
9028       Derive_Subps  : Boolean := True)
9029    is
9030       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
9031 
9032    begin
9033       --  Set common attributes
9034 
9035       Set_Scope                (Derived_Type, Current_Scope);
9036 
9037       Set_Etype                  (Derived_Type,        Parent_Base);
9038       Set_Ekind                  (Derived_Type, Ekind (Parent_Base));
9039       Propagate_Concurrent_Flags (Derived_Type,        Parent_Base);
9040 
9041       Set_Size_Info          (Derived_Type,                     Parent_Type);
9042       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
9043       Set_Is_Controlled      (Derived_Type, Is_Controlled      (Parent_Type));
9044       Set_Disable_Controlled (Derived_Type, Disable_Controlled (Parent_Type));
9045 
9046       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
9047       Set_Is_Volatile    (Derived_Type, Is_Volatile    (Parent_Type));
9048 
9049       if Is_Tagged_Type (Derived_Type) then
9050          Set_No_Tagged_Streams_Pragma
9051            (Derived_Type, No_Tagged_Streams_Pragma (Parent_Type));
9052       end if;
9053 
9054       --  If the parent has primitive routines, set the derived type link
9055 
9056       if Has_Primitive_Operations (Parent_Type) then
9057          Set_Derived_Type_Link (Parent_Base, Derived_Type);
9058       end if;
9059 
9060       --  If the parent type is a private subtype, the convention on the base
9061       --  type may be set in the private part, and not propagated to the
9062       --  subtype until later, so we obtain the convention from the base type.
9063 
9064       Set_Convention (Derived_Type, Convention (Parent_Base));
9065 
9066       --  Set SSO default for record or array type
9067 
9068       if (Is_Array_Type (Derived_Type) or else Is_Record_Type (Derived_Type))
9069         and then Is_Base_Type (Derived_Type)
9070       then
9071          Set_Default_SSO (Derived_Type);
9072       end if;
9073 
9074       --  Propagate invariant information. The new type has invariants if
9075       --  they are inherited from the parent type, and these invariants can
9076       --  be further inherited, so both flags are set.
9077 
9078       --  We similarly inherit predicates
9079 
9080       if Has_Predicates (Parent_Type) then
9081          Set_Has_Predicates (Derived_Type);
9082       end if;
9083 
9084       --  The derived type inherits the representation clauses of the parent
9085 
9086       Inherit_Rep_Item_Chain (Derived_Type, Parent_Type);
9087 
9088       --  Propagate the attributes related to pragma Default_Initial_Condition
9089       --  from the parent type to the private extension. A derived type always
9090       --  inherits the default initial condition flag from the parent type. If
9091       --  the derived type carries its own Default_Initial_Condition pragma,
9092       --  the flag is later reset in Analyze_Pragma. Note that both flags are
9093       --  mutually exclusive.
9094 
9095       Propagate_Default_Init_Cond_Attributes
9096         (From_Typ             => Parent_Type,
9097          To_Typ               => Derived_Type,
9098          Parent_To_Derivation => True);
9099 
9100       --  If the parent type has delayed rep aspects, then mark the derived
9101       --  type as possibly inheriting a delayed rep aspect.
9102 
9103       if Has_Delayed_Rep_Aspects (Parent_Type) then
9104          Set_May_Inherit_Delayed_Rep_Aspects (Derived_Type);
9105       end if;
9106 
9107       --  Propagate the attributes related to pragma Ghost from the parent type
9108       --  to the derived type or type extension (SPARK RM 6.9(9)).
9109 
9110       if Is_Ghost_Entity (Parent_Type) then
9111          Set_Is_Ghost_Entity (Derived_Type);
9112       end if;
9113 
9114       --  Type dependent processing
9115 
9116       case Ekind (Parent_Type) is
9117          when Numeric_Kind =>
9118             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
9119 
9120          when Array_Kind =>
9121             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
9122 
9123          when E_Record_Type
9124             | E_Record_Subtype
9125             | Class_Wide_Kind  =>
9126             Build_Derived_Record_Type
9127               (N, Parent_Type, Derived_Type, Derive_Subps);
9128             return;
9129 
9130          when Enumeration_Kind =>
9131             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
9132 
9133          when Access_Kind =>
9134             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
9135 
9136          when Incomplete_Or_Private_Kind =>
9137             Build_Derived_Private_Type
9138               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
9139 
9140             --  For discriminated types, the derivation includes deriving
9141             --  primitive operations. For others it is done below.
9142 
9143             if Is_Tagged_Type (Parent_Type)
9144               or else Has_Discriminants (Parent_Type)
9145               or else (Present (Full_View (Parent_Type))
9146                         and then Has_Discriminants (Full_View (Parent_Type)))
9147             then
9148                return;
9149             end if;
9150 
9151          when Concurrent_Kind =>
9152             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
9153 
9154          when others =>
9155             raise Program_Error;
9156       end case;
9157 
9158       --  Nothing more to do if some error occurred
9159 
9160       if Etype (Derived_Type) = Any_Type then
9161          return;
9162       end if;
9163 
9164       --  Set delayed freeze and then derive subprograms, we need to do this
9165       --  in this order so that derived subprograms inherit the derived freeze
9166       --  if necessary.
9167 
9168       Set_Has_Delayed_Freeze (Derived_Type);
9169 
9170       if Derive_Subps then
9171          Derive_Subprograms (Parent_Type, Derived_Type);
9172       end if;
9173 
9174       Set_Has_Primitive_Operations
9175         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
9176    end Build_Derived_Type;
9177 
9178    -----------------------
9179    -- Build_Discriminal --
9180    -----------------------
9181 
9182    procedure Build_Discriminal (Discrim : Entity_Id) is
9183       D_Minal : Entity_Id;
9184       CR_Disc : Entity_Id;
9185 
9186    begin
9187       --  A discriminal has the same name as the discriminant
9188 
9189       D_Minal := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
9190 
9191       Set_Ekind     (D_Minal, E_In_Parameter);
9192       Set_Mechanism (D_Minal, Default_Mechanism);
9193       Set_Etype     (D_Minal, Etype (Discrim));
9194       Set_Scope     (D_Minal, Current_Scope);
9195       Set_Parent    (D_Minal, Parent (Discrim));
9196 
9197       Set_Discriminal (Discrim, D_Minal);
9198       Set_Discriminal_Link (D_Minal, Discrim);
9199 
9200       --  For task types, build at once the discriminants of the corresponding
9201       --  record, which are needed if discriminants are used in entry defaults
9202       --  and in family bounds.
9203 
9204       if Is_Concurrent_Type (Current_Scope)
9205            or else
9206          Is_Limited_Type    (Current_Scope)
9207       then
9208          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
9209 
9210          Set_Ekind            (CR_Disc, E_In_Parameter);
9211          Set_Mechanism        (CR_Disc, Default_Mechanism);
9212          Set_Etype            (CR_Disc, Etype (Discrim));
9213          Set_Scope            (CR_Disc, Current_Scope);
9214          Set_Discriminal_Link (CR_Disc, Discrim);
9215          Set_CR_Discriminant  (Discrim, CR_Disc);
9216       end if;
9217    end Build_Discriminal;
9218 
9219    ------------------------------------
9220    -- Build_Discriminant_Constraints --
9221    ------------------------------------
9222 
9223    function Build_Discriminant_Constraints
9224      (T           : Entity_Id;
9225       Def         : Node_Id;
9226       Derived_Def : Boolean := False) return Elist_Id
9227    is
9228       C        : constant Node_Id := Constraint (Def);
9229       Nb_Discr : constant Nat     := Number_Discriminants (T);
9230 
9231       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
9232       --  Saves the expression corresponding to a given discriminant in T
9233 
9234       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
9235       --  Return the Position number within array Discr_Expr of a discriminant
9236       --  D within the discriminant list of the discriminated type T.
9237 
9238       procedure Process_Discriminant_Expression
9239          (Expr : Node_Id;
9240           D    : Entity_Id);
9241       --  If this is a discriminant constraint on a partial view, do not
9242       --  generate an overflow check on the discriminant expression. The check
9243       --  will be generated when constraining the full view. Otherwise the
9244       --  backend creates duplicate symbols for the temporaries corresponding
9245       --  to the expressions to be checked, causing spurious assembler errors.
9246 
9247       ------------------
9248       -- Pos_Of_Discr --
9249       ------------------
9250 
9251       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
9252          Disc : Entity_Id;
9253 
9254       begin
9255          Disc := First_Discriminant (T);
9256          for J in Discr_Expr'Range loop
9257             if Disc = D then
9258                return J;
9259             end if;
9260 
9261             Next_Discriminant (Disc);
9262          end loop;
9263 
9264          --  Note: Since this function is called on discriminants that are
9265          --  known to belong to the discriminated type, falling through the
9266          --  loop with no match signals an internal compiler error.
9267 
9268          raise Program_Error;
9269       end Pos_Of_Discr;
9270 
9271       -------------------------------------
9272       -- Process_Discriminant_Expression --
9273       -------------------------------------
9274 
9275       procedure Process_Discriminant_Expression
9276          (Expr : Node_Id;
9277           D    : Entity_Id)
9278       is
9279          BDT : constant Entity_Id := Base_Type (Etype (D));
9280 
9281       begin
9282          --  If this is a discriminant constraint on a partial view, do
9283          --  not generate an overflow on the discriminant expression. The
9284          --  check will be generated when constraining the full view.
9285 
9286          if Is_Private_Type (T)
9287            and then Present (Full_View (T))
9288          then
9289             Analyze_And_Resolve (Expr, BDT, Suppress => Overflow_Check);
9290          else
9291             Analyze_And_Resolve (Expr, BDT);
9292          end if;
9293       end Process_Discriminant_Expression;
9294 
9295       --  Declarations local to Build_Discriminant_Constraints
9296 
9297       Discr : Entity_Id;
9298       E     : Entity_Id;
9299       Elist : constant Elist_Id := New_Elmt_List;
9300 
9301       Constr   : Node_Id;
9302       Expr     : Node_Id;
9303       Id       : Node_Id;
9304       Position : Nat;
9305       Found    : Boolean;
9306 
9307       Discrim_Present : Boolean := False;
9308 
9309    --  Start of processing for Build_Discriminant_Constraints
9310 
9311    begin
9312       --  The following loop will process positional associations only.
9313       --  For a positional association, the (single) discriminant is
9314       --  implicitly specified by position, in textual order (RM 3.7.2).
9315 
9316       Discr  := First_Discriminant (T);
9317       Constr := First (Constraints (C));
9318       for D in Discr_Expr'Range loop
9319          exit when Nkind (Constr) = N_Discriminant_Association;
9320 
9321          if No (Constr) then
9322             Error_Msg_N ("too few discriminants given in constraint", C);
9323             return New_Elmt_List;
9324 
9325          elsif Nkind (Constr) = N_Range
9326            or else (Nkind (Constr) = N_Attribute_Reference
9327                      and then Attribute_Name (Constr) = Name_Range)
9328          then
9329             Error_Msg_N
9330               ("a range is not a valid discriminant constraint", Constr);
9331             Discr_Expr (D) := Error;
9332 
9333          else
9334             Process_Discriminant_Expression (Constr, Discr);
9335             Discr_Expr (D) := Constr;
9336          end if;
9337 
9338          Next_Discriminant (Discr);
9339          Next (Constr);
9340       end loop;
9341 
9342       if No (Discr) and then Present (Constr) then
9343          Error_Msg_N ("too many discriminants given in constraint", Constr);
9344          return New_Elmt_List;
9345       end if;
9346 
9347       --  Named associations can be given in any order, but if both positional
9348       --  and named associations are used in the same discriminant constraint,
9349       --  then positional associations must occur first, at their normal
9350       --  position. Hence once a named association is used, the rest of the
9351       --  discriminant constraint must use only named associations.
9352 
9353       while Present (Constr) loop
9354 
9355          --  Positional association forbidden after a named association
9356 
9357          if Nkind (Constr) /= N_Discriminant_Association then
9358             Error_Msg_N ("positional association follows named one", Constr);
9359             return New_Elmt_List;
9360 
9361          --  Otherwise it is a named association
9362 
9363          else
9364             --  E records the type of the discriminants in the named
9365             --  association. All the discriminants specified in the same name
9366             --  association must have the same type.
9367 
9368             E := Empty;
9369 
9370             --  Search the list of discriminants in T to see if the simple name
9371             --  given in the constraint matches any of them.
9372 
9373             Id := First (Selector_Names (Constr));
9374             while Present (Id) loop
9375                Found := False;
9376 
9377                --  If Original_Discriminant is present, we are processing a
9378                --  generic instantiation and this is an instance node. We need
9379                --  to find the name of the corresponding discriminant in the
9380                --  actual record type T and not the name of the discriminant in
9381                --  the generic formal. Example:
9382 
9383                --    generic
9384                --       type G (D : int) is private;
9385                --    package P is
9386                --       subtype W is G (D => 1);
9387                --    end package;
9388                --    type Rec (X : int) is record ... end record;
9389                --    package Q is new P (G => Rec);
9390 
9391                --  At the point of the instantiation, formal type G is Rec
9392                --  and therefore when reanalyzing "subtype W is G (D => 1);"
9393                --  which really looks like "subtype W is Rec (D => 1);" at
9394                --  the point of instantiation, we want to find the discriminant
9395                --  that corresponds to D in Rec, i.e. X.
9396 
9397                if Present (Original_Discriminant (Id))
9398                  and then In_Instance
9399                then
9400                   Discr := Find_Corresponding_Discriminant (Id, T);
9401                   Found := True;
9402 
9403                else
9404                   Discr := First_Discriminant (T);
9405                   while Present (Discr) loop
9406                      if Chars (Discr) = Chars (Id) then
9407                         Found := True;
9408                         exit;
9409                      end if;
9410 
9411                      Next_Discriminant (Discr);
9412                   end loop;
9413 
9414                   if not Found then
9415                      Error_Msg_N ("& does not match any discriminant", Id);
9416                      return New_Elmt_List;
9417 
9418                   --  If the parent type is a generic formal, preserve the
9419                   --  name of the discriminant for subsequent instances.
9420                   --  see comment at the beginning of this if statement.
9421 
9422                   elsif Is_Generic_Type (Root_Type (T)) then
9423                      Set_Original_Discriminant (Id, Discr);
9424                   end if;
9425                end if;
9426 
9427                Position := Pos_Of_Discr (T, Discr);
9428 
9429                if Present (Discr_Expr (Position)) then
9430                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
9431 
9432                else
9433                   --  Each discriminant specified in the same named association
9434                   --  must be associated with a separate copy of the
9435                   --  corresponding expression.
9436 
9437                   if Present (Next (Id)) then
9438                      Expr := New_Copy_Tree (Expression (Constr));
9439                      Set_Parent (Expr, Parent (Expression (Constr)));
9440                   else
9441                      Expr := Expression (Constr);
9442                   end if;
9443 
9444                   Discr_Expr (Position) := Expr;
9445                   Process_Discriminant_Expression (Expr, Discr);
9446                end if;
9447 
9448                --  A discriminant association with more than one discriminant
9449                --  name is only allowed if the named discriminants are all of
9450                --  the same type (RM 3.7.1(8)).
9451 
9452                if E = Empty then
9453                   E := Base_Type (Etype (Discr));
9454 
9455                elsif Base_Type (Etype (Discr)) /= E then
9456                   Error_Msg_N
9457                     ("all discriminants in an association " &
9458                      "must have the same type", Id);
9459                end if;
9460 
9461                Next (Id);
9462             end loop;
9463          end if;
9464 
9465          Next (Constr);
9466       end loop;
9467 
9468       --  A discriminant constraint must provide exactly one value for each
9469       --  discriminant of the type (RM 3.7.1(8)).
9470 
9471       for J in Discr_Expr'Range loop
9472          if No (Discr_Expr (J)) then
9473             Error_Msg_N ("too few discriminants given in constraint", C);
9474             return New_Elmt_List;
9475          end if;
9476       end loop;
9477 
9478       --  Determine if there are discriminant expressions in the constraint
9479 
9480       for J in Discr_Expr'Range loop
9481          if Denotes_Discriminant
9482               (Discr_Expr (J), Check_Concurrent => True)
9483          then
9484             Discrim_Present := True;
9485          end if;
9486       end loop;
9487 
9488       --  Build an element list consisting of the expressions given in the
9489       --  discriminant constraint and apply the appropriate checks. The list
9490       --  is constructed after resolving any named discriminant associations
9491       --  and therefore the expressions appear in the textual order of the
9492       --  discriminants.
9493 
9494       Discr := First_Discriminant (T);
9495       for J in Discr_Expr'Range loop
9496          if Discr_Expr (J) /= Error then
9497             Append_Elmt (Discr_Expr (J), Elist);
9498 
9499             --  If any of the discriminant constraints is given by a
9500             --  discriminant and we are in a derived type declaration we
9501             --  have a discriminant renaming. Establish link between new
9502             --  and old discriminant.
9503 
9504             if Denotes_Discriminant (Discr_Expr (J)) then
9505                if Derived_Def then
9506                   Set_Corresponding_Discriminant
9507                     (Entity (Discr_Expr (J)), Discr);
9508                end if;
9509 
9510             --  Force the evaluation of non-discriminant expressions.
9511             --  If we have found a discriminant in the constraint 3.4(26)
9512             --  and 3.8(18) demand that no range checks are performed are
9513             --  after evaluation. If the constraint is for a component
9514             --  definition that has a per-object constraint, expressions are
9515             --  evaluated but not checked either. In all other cases perform
9516             --  a range check.
9517 
9518             else
9519                if Discrim_Present then
9520                   null;
9521 
9522                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
9523                  and then
9524                    Has_Per_Object_Constraint
9525                      (Defining_Identifier (Parent (Parent (Def))))
9526                then
9527                   null;
9528 
9529                elsif Is_Access_Type (Etype (Discr)) then
9530                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
9531 
9532                else
9533                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
9534                end if;
9535 
9536                Force_Evaluation (Discr_Expr (J));
9537             end if;
9538 
9539             --  Check that the designated type of an access discriminant's
9540             --  expression is not a class-wide type unless the discriminant's
9541             --  designated type is also class-wide.
9542 
9543             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
9544               and then not Is_Class_Wide_Type
9545                          (Designated_Type (Etype (Discr)))
9546               and then Etype (Discr_Expr (J)) /= Any_Type
9547               and then Is_Class_Wide_Type
9548                          (Designated_Type (Etype (Discr_Expr (J))))
9549             then
9550                Wrong_Type (Discr_Expr (J), Etype (Discr));
9551 
9552             elsif Is_Access_Type (Etype (Discr))
9553               and then not Is_Access_Constant (Etype (Discr))
9554               and then Is_Access_Type (Etype (Discr_Expr (J)))
9555               and then Is_Access_Constant (Etype (Discr_Expr (J)))
9556             then
9557                Error_Msg_NE
9558                  ("constraint for discriminant& must be access to variable",
9559                     Def, Discr);
9560             end if;
9561          end if;
9562 
9563          Next_Discriminant (Discr);
9564       end loop;
9565 
9566       return Elist;
9567    end Build_Discriminant_Constraints;
9568 
9569    ---------------------------------
9570    -- Build_Discriminated_Subtype --
9571    ---------------------------------
9572 
9573    procedure Build_Discriminated_Subtype
9574      (T           : Entity_Id;
9575       Def_Id      : Entity_Id;
9576       Elist       : Elist_Id;
9577       Related_Nod : Node_Id;
9578       For_Access  : Boolean := False)
9579    is
9580       Has_Discrs  : constant Boolean := Has_Discriminants (T);
9581       Constrained : constant Boolean :=
9582                       (Has_Discrs
9583                          and then not Is_Empty_Elmt_List (Elist)
9584                          and then not Is_Class_Wide_Type (T))
9585                         or else Is_Constrained (T);
9586 
9587    begin
9588       if Ekind (T) = E_Record_Type then
9589          if For_Access then
9590             Set_Ekind (Def_Id, E_Private_Subtype);
9591             Set_Is_For_Access_Subtype (Def_Id, True);
9592          else
9593             Set_Ekind (Def_Id, E_Record_Subtype);
9594          end if;
9595 
9596          --  Inherit preelaboration flag from base, for types for which it
9597          --  may have been set: records, private types, protected types.
9598 
9599          Set_Known_To_Have_Preelab_Init
9600            (Def_Id, Known_To_Have_Preelab_Init (T));
9601 
9602       elsif Ekind (T) = E_Task_Type then
9603          Set_Ekind (Def_Id, E_Task_Subtype);
9604 
9605       elsif Ekind (T) = E_Protected_Type then
9606          Set_Ekind (Def_Id, E_Protected_Subtype);
9607          Set_Known_To_Have_Preelab_Init
9608            (Def_Id, Known_To_Have_Preelab_Init (T));
9609 
9610       elsif Is_Private_Type (T) then
9611          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
9612          Set_Known_To_Have_Preelab_Init
9613            (Def_Id, Known_To_Have_Preelab_Init (T));
9614 
9615          --  Private subtypes may have private dependents
9616 
9617          Set_Private_Dependents (Def_Id, New_Elmt_List);
9618 
9619       elsif Is_Class_Wide_Type (T) then
9620          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
9621 
9622       else
9623          --  Incomplete type. Attach subtype to list of dependents, to be
9624          --  completed with full view of parent type,  unless is it the
9625          --  designated subtype of a record component within an init_proc.
9626          --  This last case arises for a component of an access type whose
9627          --  designated type is incomplete (e.g. a Taft Amendment type).
9628          --  The designated subtype is within an inner scope, and needs no
9629          --  elaboration, because only the access type is needed in the
9630          --  initialization procedure.
9631 
9632          Set_Ekind (Def_Id, Ekind (T));
9633 
9634          if For_Access and then Within_Init_Proc then
9635             null;
9636          else
9637             Append_Elmt (Def_Id, Private_Dependents (T));
9638          end if;
9639       end if;
9640 
9641       Set_Etype             (Def_Id, T);
9642       Init_Size_Align       (Def_Id);
9643       Set_Has_Discriminants (Def_Id, Has_Discrs);
9644       Set_Is_Constrained    (Def_Id, Constrained);
9645 
9646       Set_First_Entity      (Def_Id, First_Entity   (T));
9647       Set_Last_Entity       (Def_Id, Last_Entity    (T));
9648       Set_Has_Implicit_Dereference
9649                             (Def_Id, Has_Implicit_Dereference (T));
9650 
9651       --  If the subtype is the completion of a private declaration, there may
9652       --  have been representation clauses for the partial view, and they must
9653       --  be preserved. Build_Derived_Type chains the inherited clauses with
9654       --  the ones appearing on the extension. If this comes from a subtype
9655       --  declaration, all clauses are inherited.
9656 
9657       if No (First_Rep_Item (Def_Id)) then
9658          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
9659       end if;
9660 
9661       if Is_Tagged_Type (T) then
9662          Set_Is_Tagged_Type (Def_Id);
9663          Set_No_Tagged_Streams_Pragma (Def_Id, No_Tagged_Streams_Pragma (T));
9664          Make_Class_Wide_Type (Def_Id);
9665       end if;
9666 
9667       Set_Stored_Constraint (Def_Id, No_Elist);
9668 
9669       if Has_Discrs then
9670          Set_Discriminant_Constraint (Def_Id, Elist);
9671          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
9672       end if;
9673 
9674       if Is_Tagged_Type (T) then
9675 
9676          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
9677          --  concurrent record type (which has the list of primitive
9678          --  operations).
9679 
9680          if Ada_Version >= Ada_2005
9681            and then Is_Concurrent_Type (T)
9682          then
9683             Set_Corresponding_Record_Type (Def_Id,
9684                Corresponding_Record_Type (T));
9685          else
9686             Set_Direct_Primitive_Operations (Def_Id,
9687               Direct_Primitive_Operations (T));
9688          end if;
9689 
9690          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
9691       end if;
9692 
9693       --  Subtypes introduced by component declarations do not need to be
9694       --  marked as delayed, and do not get freeze nodes, because the semantics
9695       --  verifies that the parents of the subtypes are frozen before the
9696       --  enclosing record is frozen.
9697 
9698       if not Is_Type (Scope (Def_Id)) then
9699          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
9700 
9701          if Is_Private_Type (T)
9702            and then Present (Full_View (T))
9703          then
9704             Conditional_Delay (Def_Id, Full_View (T));
9705          else
9706             Conditional_Delay (Def_Id, T);
9707          end if;
9708       end if;
9709 
9710       if Is_Record_Type (T) then
9711          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
9712 
9713          if Has_Discrs
9714             and then not Is_Empty_Elmt_List (Elist)
9715             and then not For_Access
9716          then
9717             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
9718          elsif not For_Access then
9719             Set_Cloned_Subtype (Def_Id, T);
9720          end if;
9721       end if;
9722    end Build_Discriminated_Subtype;
9723 
9724    ---------------------------
9725    -- Build_Itype_Reference --
9726    ---------------------------
9727 
9728    procedure Build_Itype_Reference
9729      (Ityp : Entity_Id;
9730       Nod  : Node_Id)
9731    is
9732       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
9733    begin
9734 
9735       --  Itype references are only created for use by the back-end
9736 
9737       if Inside_A_Generic then
9738          return;
9739       else
9740          Set_Itype (IR, Ityp);
9741          Insert_After (Nod, IR);
9742       end if;
9743    end Build_Itype_Reference;
9744 
9745    ------------------------
9746    -- Build_Scalar_Bound --
9747    ------------------------
9748 
9749    function Build_Scalar_Bound
9750      (Bound : Node_Id;
9751       Par_T : Entity_Id;
9752       Der_T : Entity_Id) return Node_Id
9753    is
9754       New_Bound : Entity_Id;
9755 
9756    begin
9757       --  Note: not clear why this is needed, how can the original bound
9758       --  be unanalyzed at this point? and if it is, what business do we
9759       --  have messing around with it? and why is the base type of the
9760       --  parent type the right type for the resolution. It probably is
9761       --  not. It is OK for the new bound we are creating, but not for
9762       --  the old one??? Still if it never happens, no problem.
9763 
9764       Analyze_And_Resolve (Bound, Base_Type (Par_T));
9765 
9766       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
9767          New_Bound := New_Copy (Bound);
9768          Set_Etype (New_Bound, Der_T);
9769          Set_Analyzed (New_Bound);
9770 
9771       elsif Is_Entity_Name (Bound) then
9772          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
9773 
9774       --  The following is almost certainly wrong. What business do we have
9775       --  relocating a node (Bound) that is presumably still attached to
9776       --  the tree elsewhere???
9777 
9778       else
9779          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
9780       end if;
9781 
9782       Set_Etype (New_Bound, Der_T);
9783       return New_Bound;
9784    end Build_Scalar_Bound;
9785 
9786    --------------------------------
9787    -- Build_Underlying_Full_View --
9788    --------------------------------
9789 
9790    procedure Build_Underlying_Full_View
9791      (N   : Node_Id;
9792       Typ : Entity_Id;
9793       Par : Entity_Id)
9794    is
9795       Loc  : constant Source_Ptr := Sloc (N);
9796       Subt : constant Entity_Id :=
9797                Make_Defining_Identifier
9798                  (Loc, New_External_Name (Chars (Typ), 'S'));
9799 
9800       Constr : Node_Id;
9801       Indic  : Node_Id;
9802       C      : Node_Id;
9803       Id     : Node_Id;
9804 
9805       procedure Set_Discriminant_Name (Id : Node_Id);
9806       --  If the derived type has discriminants, they may rename discriminants
9807       --  of the parent. When building the full view of the parent, we need to
9808       --  recover the names of the original discriminants if the constraint is
9809       --  given by named associations.
9810 
9811       ---------------------------
9812       -- Set_Discriminant_Name --
9813       ---------------------------
9814 
9815       procedure Set_Discriminant_Name (Id : Node_Id) is
9816          Disc : Entity_Id;
9817 
9818       begin
9819          Set_Original_Discriminant (Id, Empty);
9820 
9821          if Has_Discriminants (Typ) then
9822             Disc := First_Discriminant (Typ);
9823             while Present (Disc) loop
9824                if Chars (Disc) = Chars (Id)
9825                  and then Present (Corresponding_Discriminant (Disc))
9826                then
9827                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
9828                end if;
9829                Next_Discriminant (Disc);
9830             end loop;
9831          end if;
9832       end Set_Discriminant_Name;
9833 
9834    --  Start of processing for Build_Underlying_Full_View
9835 
9836    begin
9837       if Nkind (N) = N_Full_Type_Declaration then
9838          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
9839 
9840       elsif Nkind (N) = N_Subtype_Declaration then
9841          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
9842 
9843       elsif Nkind (N) = N_Component_Declaration then
9844          Constr :=
9845            New_Copy_Tree
9846              (Constraint (Subtype_Indication (Component_Definition (N))));
9847 
9848       else
9849          raise Program_Error;
9850       end if;
9851 
9852       C := First (Constraints (Constr));
9853       while Present (C) loop
9854          if Nkind (C) = N_Discriminant_Association then
9855             Id := First (Selector_Names (C));
9856             while Present (Id) loop
9857                Set_Discriminant_Name (Id);
9858                Next (Id);
9859             end loop;
9860          end if;
9861 
9862          Next (C);
9863       end loop;
9864 
9865       Indic :=
9866         Make_Subtype_Declaration (Loc,
9867           Defining_Identifier => Subt,
9868           Subtype_Indication  =>
9869             Make_Subtype_Indication (Loc,
9870               Subtype_Mark => New_Occurrence_Of (Par, Loc),
9871               Constraint   => New_Copy_Tree (Constr)));
9872 
9873       --  If this is a component subtype for an outer itype, it is not
9874       --  a list member, so simply set the parent link for analysis: if
9875       --  the enclosing type does not need to be in a declarative list,
9876       --  neither do the components.
9877 
9878       if Is_List_Member (N)
9879         and then Nkind (N) /= N_Component_Declaration
9880       then
9881          Insert_Before (N, Indic);
9882       else
9883          Set_Parent (Indic, Parent (N));
9884       end if;
9885 
9886       Analyze (Indic);
9887       Set_Underlying_Full_View (Typ, Full_View (Subt));
9888    end Build_Underlying_Full_View;
9889 
9890    -------------------------------
9891    -- Check_Abstract_Overriding --
9892    -------------------------------
9893 
9894    procedure Check_Abstract_Overriding (T : Entity_Id) is
9895       Alias_Subp : Entity_Id;
9896       Elmt       : Elmt_Id;
9897       Op_List    : Elist_Id;
9898       Subp       : Entity_Id;
9899       Type_Def   : Node_Id;
9900 
9901       procedure Check_Pragma_Implemented (Subp : Entity_Id);
9902       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
9903       --  which has pragma Implemented already set. Check whether Subp's entity
9904       --  kind conforms to the implementation kind of the overridden routine.
9905 
9906       procedure Check_Pragma_Implemented
9907         (Subp       : Entity_Id;
9908          Iface_Subp : Entity_Id);
9909       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
9910       --  Iface_Subp and both entities have pragma Implemented already set on
9911       --  them. Check whether the two implementation kinds are conforming.
9912 
9913       procedure Inherit_Pragma_Implemented
9914         (Subp       : Entity_Id;
9915          Iface_Subp : Entity_Id);
9916       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
9917       --  subprogram Iface_Subp which has been marked by pragma Implemented.
9918       --  Propagate the implementation kind of Iface_Subp to Subp.
9919 
9920       ------------------------------
9921       -- Check_Pragma_Implemented --
9922       ------------------------------
9923 
9924       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
9925          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
9926          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
9927          Subp_Alias  : constant Entity_Id := Alias (Subp);
9928          Contr_Typ   : Entity_Id;
9929          Impl_Subp   : Entity_Id;
9930 
9931       begin
9932          --  Subp must have an alias since it is a hidden entity used to link
9933          --  an interface subprogram to its overriding counterpart.
9934 
9935          pragma Assert (Present (Subp_Alias));
9936 
9937          --  Handle aliases to synchronized wrappers
9938 
9939          Impl_Subp := Subp_Alias;
9940 
9941          if Is_Primitive_Wrapper (Impl_Subp) then
9942             Impl_Subp := Wrapped_Entity (Impl_Subp);
9943          end if;
9944 
9945          --  Extract the type of the controlling formal
9946 
9947          Contr_Typ := Etype (First_Formal (Subp_Alias));
9948 
9949          if Is_Concurrent_Record_Type (Contr_Typ) then
9950             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
9951          end if;
9952 
9953          --  An interface subprogram whose implementation kind is By_Entry must
9954          --  be implemented by an entry.
9955 
9956          if Impl_Kind = Name_By_Entry
9957            and then Ekind (Impl_Subp) /= E_Entry
9958          then
9959             Error_Msg_Node_2 := Iface_Alias;
9960             Error_Msg_NE
9961               ("type & must implement abstract subprogram & with an entry",
9962                Subp_Alias, Contr_Typ);
9963 
9964          elsif Impl_Kind = Name_By_Protected_Procedure then
9965 
9966             --  An interface subprogram whose implementation kind is By_
9967             --  Protected_Procedure cannot be implemented by a primitive
9968             --  procedure of a task type.
9969 
9970             if Ekind (Contr_Typ) /= E_Protected_Type then
9971                Error_Msg_Node_2 := Contr_Typ;
9972                Error_Msg_NE
9973                  ("interface subprogram & cannot be implemented by a " &
9974                   "primitive procedure of task type &", Subp_Alias,
9975                   Iface_Alias);
9976 
9977             --  An interface subprogram whose implementation kind is By_
9978             --  Protected_Procedure must be implemented by a procedure.
9979 
9980             elsif Ekind (Impl_Subp) /= E_Procedure then
9981                Error_Msg_Node_2 := Iface_Alias;
9982                Error_Msg_NE
9983                  ("type & must implement abstract subprogram & with a " &
9984                   "procedure", Subp_Alias, Contr_Typ);
9985 
9986             elsif Present (Get_Rep_Pragma (Impl_Subp, Name_Implemented))
9987               and then Implementation_Kind (Impl_Subp) /= Impl_Kind
9988             then
9989                Error_Msg_Name_1 := Impl_Kind;
9990                Error_Msg_N
9991                 ("overriding operation& must have synchronization%",
9992                  Subp_Alias);
9993             end if;
9994 
9995          --  If primitive has Optional synchronization, overriding operation
9996          --  must match if it has an explicit synchronization..
9997 
9998          elsif Present (Get_Rep_Pragma (Impl_Subp, Name_Implemented))
9999            and then Implementation_Kind (Impl_Subp) /= Impl_Kind
10000          then
10001                Error_Msg_Name_1 := Impl_Kind;
10002                Error_Msg_N
10003                 ("overriding operation& must have syncrhonization%",
10004                  Subp_Alias);
10005          end if;
10006       end Check_Pragma_Implemented;
10007 
10008       ------------------------------
10009       -- Check_Pragma_Implemented --
10010       ------------------------------
10011 
10012       procedure Check_Pragma_Implemented
10013         (Subp       : Entity_Id;
10014          Iface_Subp : Entity_Id)
10015       is
10016          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
10017          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
10018 
10019       begin
10020          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
10021          --  and overriding subprogram are different. In general this is an
10022          --  error except when the implementation kind of the overridden
10023          --  subprograms is By_Any or Optional.
10024 
10025          if Iface_Kind /= Subp_Kind
10026            and then Iface_Kind /= Name_By_Any
10027            and then Iface_Kind /= Name_Optional
10028          then
10029             if Iface_Kind = Name_By_Entry then
10030                Error_Msg_N
10031                  ("incompatible implementation kind, overridden subprogram " &
10032                   "is marked By_Entry", Subp);
10033             else
10034                Error_Msg_N
10035                  ("incompatible implementation kind, overridden subprogram " &
10036                   "is marked By_Protected_Procedure", Subp);
10037             end if;
10038          end if;
10039       end Check_Pragma_Implemented;
10040 
10041       --------------------------------
10042       -- Inherit_Pragma_Implemented --
10043       --------------------------------
10044 
10045       procedure Inherit_Pragma_Implemented
10046         (Subp       : Entity_Id;
10047          Iface_Subp : Entity_Id)
10048       is
10049          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
10050          Loc        : constant Source_Ptr := Sloc (Subp);
10051          Impl_Prag  : Node_Id;
10052 
10053       begin
10054          --  Since the implementation kind is stored as a representation item
10055          --  rather than a flag, create a pragma node.
10056 
10057          Impl_Prag :=
10058            Make_Pragma (Loc,
10059              Chars                        => Name_Implemented,
10060              Pragma_Argument_Associations => New_List (
10061                Make_Pragma_Argument_Association (Loc,
10062                  Expression => New_Occurrence_Of (Subp, Loc)),
10063 
10064                Make_Pragma_Argument_Association (Loc,
10065                  Expression => Make_Identifier (Loc, Iface_Kind))));
10066 
10067          --  The pragma doesn't need to be analyzed because it is internally
10068          --  built. It is safe to directly register it as a rep item since we
10069          --  are only interested in the characters of the implementation kind.
10070 
10071          Record_Rep_Item (Subp, Impl_Prag);
10072       end Inherit_Pragma_Implemented;
10073 
10074    --  Start of processing for Check_Abstract_Overriding
10075 
10076    begin
10077       Op_List := Primitive_Operations (T);
10078 
10079       --  Loop to check primitive operations
10080 
10081       Elmt := First_Elmt (Op_List);
10082       while Present (Elmt) loop
10083          Subp := Node (Elmt);
10084          Alias_Subp := Alias (Subp);
10085 
10086          --  Inherited subprograms are identified by the fact that they do not
10087          --  come from source, and the associated source location is the
10088          --  location of the first subtype of the derived type.
10089 
10090          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
10091          --  subprograms that "require overriding".
10092 
10093          --  Special exception, do not complain about failure to override the
10094          --  stream routines _Input and _Output, as well as the primitive
10095          --  operations used in dispatching selects since we always provide
10096          --  automatic overridings for these subprograms.
10097 
10098          --  The partial view of T may have been a private extension, for
10099          --  which inherited functions dispatching on result are abstract.
10100          --  If the full view is a null extension, there is no need for
10101          --  overriding in Ada 2005, but wrappers need to be built for them
10102          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
10103 
10104          if Is_Null_Extension (T)
10105            and then Has_Controlling_Result (Subp)
10106            and then Ada_Version >= Ada_2005
10107            and then Present (Alias_Subp)
10108            and then not Comes_From_Source (Subp)
10109            and then not Is_Abstract_Subprogram (Alias_Subp)
10110            and then not Is_Access_Type (Etype (Subp))
10111          then
10112             null;
10113 
10114          --  Ada 2005 (AI-251): Internal entities of interfaces need no
10115          --  processing because this check is done with the aliased
10116          --  entity
10117 
10118          elsif Present (Interface_Alias (Subp)) then
10119             null;
10120 
10121          elsif (Is_Abstract_Subprogram (Subp)
10122                  or else Requires_Overriding (Subp)
10123                  or else
10124                    (Has_Controlling_Result (Subp)
10125                      and then Present (Alias_Subp)
10126                      and then not Comes_From_Source (Subp)
10127                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
10128            and then not Is_TSS (Subp, TSS_Stream_Input)
10129            and then not Is_TSS (Subp, TSS_Stream_Output)
10130            and then not Is_Abstract_Type (T)
10131            and then not Is_Predefined_Interface_Primitive (Subp)
10132 
10133             --  Ada 2005 (AI-251): Do not consider hidden entities associated
10134             --  with abstract interface types because the check will be done
10135             --  with the aliased entity (otherwise we generate a duplicated
10136             --  error message).
10137 
10138            and then not Present (Interface_Alias (Subp))
10139          then
10140             if Present (Alias_Subp) then
10141 
10142                --  Only perform the check for a derived subprogram when the
10143                --  type has an explicit record extension. This avoids incorrect
10144                --  flagging of abstract subprograms for the case of a type
10145                --  without an extension that is derived from a formal type
10146                --  with a tagged actual (can occur within a private part).
10147 
10148                --  Ada 2005 (AI-391): In the case of an inherited function with
10149                --  a controlling result of the type, the rule does not apply if
10150                --  the type is a null extension (unless the parent function
10151                --  itself is abstract, in which case the function must still be
10152                --  be overridden). The expander will generate an overriding
10153                --  wrapper function calling the parent subprogram (see
10154                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
10155 
10156                Type_Def := Type_Definition (Parent (T));
10157 
10158                if Nkind (Type_Def) = N_Derived_Type_Definition
10159                  and then Present (Record_Extension_Part (Type_Def))
10160                  and then
10161                    (Ada_Version < Ada_2005
10162                       or else not Is_Null_Extension (T)
10163                       or else Ekind (Subp) = E_Procedure
10164                       or else not Has_Controlling_Result (Subp)
10165                       or else Is_Abstract_Subprogram (Alias_Subp)
10166                       or else Requires_Overriding (Subp)
10167                       or else Is_Access_Type (Etype (Subp)))
10168                then
10169                   --  Avoid reporting error in case of abstract predefined
10170                   --  primitive inherited from interface type because the
10171                   --  body of internally generated predefined primitives
10172                   --  of tagged types are generated later by Freeze_Type
10173 
10174                   if Is_Interface (Root_Type (T))
10175                     and then Is_Abstract_Subprogram (Subp)
10176                     and then Is_Predefined_Dispatching_Operation (Subp)
10177                     and then not Comes_From_Source (Ultimate_Alias (Subp))
10178                   then
10179                      null;
10180 
10181                   --  A null extension is not obliged to override an inherited
10182                   --  procedure subject to pragma Extensions_Visible with value
10183                   --  False and at least one controlling OUT parameter
10184                   --  (SPARK RM 6.1.7(6)).
10185 
10186                   elsif Is_Null_Extension (T)
10187                     and then Is_EVF_Procedure (Subp)
10188                   then
10189                      null;
10190 
10191                   else
10192                      Error_Msg_NE
10193                        ("type must be declared abstract or & overridden",
10194                         T, Subp);
10195 
10196                      --  Traverse the whole chain of aliased subprograms to
10197                      --  complete the error notification. This is especially
10198                      --  useful for traceability of the chain of entities when
10199                      --  the subprogram corresponds with an interface
10200                      --  subprogram (which may be defined in another package).
10201 
10202                      if Present (Alias_Subp) then
10203                         declare
10204                            E : Entity_Id;
10205 
10206                         begin
10207                            E := Subp;
10208                            while Present (Alias (E)) loop
10209 
10210                               --  Avoid reporting redundant errors on entities
10211                               --  inherited from interfaces
10212 
10213                               if Sloc (E) /= Sloc (T) then
10214                                  Error_Msg_Sloc := Sloc (E);
10215                                  Error_Msg_NE
10216                                    ("\& has been inherited #", T, Subp);
10217                               end if;
10218 
10219                               E := Alias (E);
10220                            end loop;
10221 
10222                            Error_Msg_Sloc := Sloc (E);
10223 
10224                            --  AI05-0068: report if there is an overriding
10225                            --  non-abstract subprogram that is invisible.
10226 
10227                            if Is_Hidden (E)
10228                              and then not Is_Abstract_Subprogram (E)
10229                            then
10230                               Error_Msg_NE
10231                                 ("\& subprogram# is not visible",
10232                                  T, Subp);
10233 
10234                            --  Clarify the case where a non-null extension must
10235                            --  override inherited procedure subject to pragma
10236                            --  Extensions_Visible with value False and at least
10237                            --  one controlling OUT param.
10238 
10239                            elsif Is_EVF_Procedure (E) then
10240                               Error_Msg_NE
10241                                 ("\& # is subject to Extensions_Visible False",
10242                                  T, Subp);
10243 
10244                            else
10245                               Error_Msg_NE
10246                                 ("\& has been inherited from subprogram #",
10247                                  T, Subp);
10248                            end if;
10249                         end;
10250                      end if;
10251                   end if;
10252 
10253                --  Ada 2005 (AI-345): Protected or task type implementing
10254                --  abstract interfaces.
10255 
10256                elsif Is_Concurrent_Record_Type (T)
10257                  and then Present (Interfaces (T))
10258                then
10259                   --  There is no need to check here RM 9.4(11.9/3) since we
10260                   --  are processing the corresponding record type and the
10261                   --  mode of the overriding subprograms was verified by
10262                   --  Check_Conformance when the corresponding concurrent
10263                   --  type declaration was analyzed.
10264 
10265                   Error_Msg_NE
10266                     ("interface subprogram & must be overridden", T, Subp);
10267 
10268                   --  Examine primitive operations of synchronized type to find
10269                   --  homonyms that have the wrong profile.
10270 
10271                   declare
10272                      Prim : Entity_Id;
10273 
10274                   begin
10275                      Prim := First_Entity (Corresponding_Concurrent_Type (T));
10276                      while Present (Prim) loop
10277                         if Chars (Prim) = Chars (Subp) then
10278                            Error_Msg_NE
10279                              ("profile is not type conformant with prefixed "
10280                               & "view profile of inherited operation&",
10281                               Prim, Subp);
10282                         end if;
10283 
10284                         Next_Entity (Prim);
10285                      end loop;
10286                   end;
10287                end if;
10288 
10289             else
10290                Error_Msg_Node_2 := T;
10291                Error_Msg_N
10292                  ("abstract subprogram& not allowed for type&", Subp);
10293 
10294                --  Also post unconditional warning on the type (unconditional
10295                --  so that if there are more than one of these cases, we get
10296                --  them all, and not just the first one).
10297 
10298                Error_Msg_Node_2 := Subp;
10299                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
10300             end if;
10301 
10302          --  A subprogram subject to pragma Extensions_Visible with value
10303          --  "True" cannot override a subprogram subject to the same pragma
10304          --  with value "False" (SPARK RM 6.1.7(5)).
10305 
10306          elsif Extensions_Visible_Status (Subp) = Extensions_Visible_True
10307            and then Present (Overridden_Operation (Subp))
10308            and then Extensions_Visible_Status (Overridden_Operation (Subp)) =
10309                     Extensions_Visible_False
10310          then
10311             Error_Msg_Sloc := Sloc (Overridden_Operation (Subp));
10312             Error_Msg_N
10313               ("subprogram & with Extensions_Visible True cannot override "
10314                & "subprogram # with Extensions_Visible False", Subp);
10315          end if;
10316 
10317          --  Ada 2012 (AI05-0030): Perform checks related to pragma Implemented
10318 
10319          --  Subp is an expander-generated procedure which maps an interface
10320          --  alias to a protected wrapper. The interface alias is flagged by
10321          --  pragma Implemented. Ensure that Subp is a procedure when the
10322          --  implementation kind is By_Protected_Procedure or an entry when
10323          --  By_Entry.
10324 
10325          if Ada_Version >= Ada_2012
10326            and then Is_Hidden (Subp)
10327            and then Present (Interface_Alias (Subp))
10328            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
10329          then
10330             Check_Pragma_Implemented (Subp);
10331          end if;
10332 
10333          --  Subp is an interface primitive which overrides another interface
10334          --  primitive marked with pragma Implemented.
10335 
10336          if Ada_Version >= Ada_2012
10337            and then Present (Overridden_Operation (Subp))
10338            and then Has_Rep_Pragma
10339                       (Overridden_Operation (Subp), Name_Implemented)
10340          then
10341             --  If the overriding routine is also marked by Implemented, check
10342             --  that the two implementation kinds are conforming.
10343 
10344             if Has_Rep_Pragma (Subp, Name_Implemented) then
10345                Check_Pragma_Implemented
10346                  (Subp       => Subp,
10347                   Iface_Subp => Overridden_Operation (Subp));
10348 
10349             --  Otherwise the overriding routine inherits the implementation
10350             --  kind from the overridden subprogram.
10351 
10352             else
10353                Inherit_Pragma_Implemented
10354                  (Subp       => Subp,
10355                   Iface_Subp => Overridden_Operation (Subp));
10356             end if;
10357          end if;
10358 
10359          --  If the operation is a wrapper for a synchronized primitive, it
10360          --  may be called indirectly through a dispatching select. We assume
10361          --  that it will be referenced elsewhere indirectly, and suppress
10362          --  warnings about an unused entity.
10363 
10364          if Is_Primitive_Wrapper (Subp)
10365            and then Present (Wrapped_Entity (Subp))
10366          then
10367             Set_Referenced (Wrapped_Entity (Subp));
10368          end if;
10369 
10370          Next_Elmt (Elmt);
10371       end loop;
10372    end Check_Abstract_Overriding;
10373 
10374    ------------------------------------------------
10375    -- Check_Access_Discriminant_Requires_Limited --
10376    ------------------------------------------------
10377 
10378    procedure Check_Access_Discriminant_Requires_Limited
10379      (D   : Node_Id;
10380       Loc : Node_Id)
10381    is
10382    begin
10383       --  A discriminant_specification for an access discriminant shall appear
10384       --  only in the declaration for a task or protected type, or for a type
10385       --  with the reserved word 'limited' in its definition or in one of its
10386       --  ancestors (RM 3.7(10)).
10387 
10388       --  AI-0063: The proper condition is that type must be immutably limited,
10389       --  or else be a partial view.
10390 
10391       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
10392          if Is_Limited_View (Current_Scope)
10393            or else
10394              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
10395                and then Limited_Present (Parent (Current_Scope)))
10396          then
10397             null;
10398 
10399          else
10400             Error_Msg_N
10401               ("access discriminants allowed only for limited types", Loc);
10402          end if;
10403       end if;
10404    end Check_Access_Discriminant_Requires_Limited;
10405 
10406    -----------------------------------
10407    -- Check_Aliased_Component_Types --
10408    -----------------------------------
10409 
10410    procedure Check_Aliased_Component_Types (T : Entity_Id) is
10411       C : Entity_Id;
10412 
10413    begin
10414       --  ??? Also need to check components of record extensions, but not
10415       --  components of protected types (which are always limited).
10416 
10417       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
10418       --  types to be unconstrained. This is safe because it is illegal to
10419       --  create access subtypes to such types with explicit discriminant
10420       --  constraints.
10421 
10422       if not Is_Limited_Type (T) then
10423          if Ekind (T) = E_Record_Type then
10424             C := First_Component (T);
10425             while Present (C) loop
10426                if Is_Aliased (C)
10427                  and then Has_Discriminants (Etype (C))
10428                  and then not Is_Constrained (Etype (C))
10429                  and then not In_Instance_Body
10430                  and then Ada_Version < Ada_2005
10431                then
10432                   Error_Msg_N
10433                     ("aliased component must be constrained (RM 3.6(11))",
10434                       C);
10435                end if;
10436 
10437                Next_Component (C);
10438             end loop;
10439 
10440          elsif Ekind (T) = E_Array_Type then
10441             if Has_Aliased_Components (T)
10442               and then Has_Discriminants (Component_Type (T))
10443               and then not Is_Constrained (Component_Type (T))
10444               and then not In_Instance_Body
10445               and then Ada_Version < Ada_2005
10446             then
10447                Error_Msg_N
10448                  ("aliased component type must be constrained (RM 3.6(11))",
10449                     T);
10450             end if;
10451          end if;
10452       end if;
10453    end Check_Aliased_Component_Types;
10454 
10455    ---------------------------------------
10456    -- Check_Anonymous_Access_Components --
10457    ---------------------------------------
10458 
10459    procedure Check_Anonymous_Access_Components
10460       (Typ_Decl  : Node_Id;
10461        Typ       : Entity_Id;
10462        Prev      : Entity_Id;
10463        Comp_List : Node_Id)
10464    is
10465       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
10466       Anon_Access : Entity_Id;
10467       Acc_Def     : Node_Id;
10468       Comp        : Node_Id;
10469       Comp_Def    : Node_Id;
10470       Decl        : Node_Id;
10471       Type_Def    : Node_Id;
10472 
10473       procedure Build_Incomplete_Type_Declaration;
10474       --  If the record type contains components that include an access to the
10475       --  current record, then create an incomplete type declaration for the
10476       --  record, to be used as the designated type of the anonymous access.
10477       --  This is done only once, and only if there is no previous partial
10478       --  view of the type.
10479 
10480       function Designates_T (Subt : Node_Id) return Boolean;
10481       --  Check whether a node designates the enclosing record type, or 'Class
10482       --  of that type
10483 
10484       function Mentions_T (Acc_Def : Node_Id) return Boolean;
10485       --  Check whether an access definition includes a reference to
10486       --  the enclosing record type. The reference can be a subtype mark
10487       --  in the access definition itself, a 'Class attribute reference, or
10488       --  recursively a reference appearing in a parameter specification
10489       --  or result definition of an access_to_subprogram definition.
10490 
10491       --------------------------------------
10492       -- Build_Incomplete_Type_Declaration --
10493       --------------------------------------
10494 
10495       procedure Build_Incomplete_Type_Declaration is
10496          Decl  : Node_Id;
10497          Inc_T : Entity_Id;
10498          H     : Entity_Id;
10499 
10500          --  Is_Tagged indicates whether the type is tagged. It is tagged if
10501          --  it's "is new ... with record" or else "is tagged record ...".
10502 
10503          Is_Tagged : constant Boolean :=
10504              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
10505                and then
10506                  Present (Record_Extension_Part (Type_Definition (Typ_Decl))))
10507            or else
10508              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
10509                and then Tagged_Present (Type_Definition (Typ_Decl)));
10510 
10511       begin
10512          --  If there is a previous partial view, no need to create a new one
10513          --  If the partial view, given by Prev, is incomplete,  If Prev is
10514          --  a private declaration, full declaration is flagged accordingly.
10515 
10516          if Prev /= Typ then
10517             if Is_Tagged then
10518                Make_Class_Wide_Type (Prev);
10519                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
10520                Set_Etype (Class_Wide_Type (Typ), Typ);
10521             end if;
10522 
10523             return;
10524 
10525          elsif Has_Private_Declaration (Typ) then
10526 
10527             --  If we refer to T'Class inside T, and T is the completion of a
10528             --  private type, then make sure the class-wide type exists.
10529 
10530             if Is_Tagged then
10531                Make_Class_Wide_Type (Typ);
10532             end if;
10533 
10534             return;
10535 
10536          --  If there was a previous anonymous access type, the incomplete
10537          --  type declaration will have been created already.
10538 
10539          elsif Present (Current_Entity (Typ))
10540            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
10541            and then Full_View (Current_Entity (Typ)) = Typ
10542          then
10543             if Is_Tagged
10544               and then Comes_From_Source (Current_Entity (Typ))
10545               and then not Is_Tagged_Type (Current_Entity (Typ))
10546             then
10547                Make_Class_Wide_Type (Typ);
10548                Error_Msg_N
10549                  ("incomplete view of tagged type should be declared tagged??",
10550                   Parent (Current_Entity (Typ)));
10551             end if;
10552             return;
10553 
10554          else
10555             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
10556             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
10557 
10558             --  Type has already been inserted into the current scope. Remove
10559             --  it, and add incomplete declaration for type, so that subsequent
10560             --  anonymous access types can use it. The entity is unchained from
10561             --  the homonym list and from immediate visibility. After analysis,
10562             --  the entity in the incomplete declaration becomes immediately
10563             --  visible in the record declaration that follows.
10564 
10565             H := Current_Entity (Typ);
10566 
10567             if H = Typ then
10568                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
10569             else
10570                while Present (H)
10571                  and then Homonym (H) /= Typ
10572                loop
10573                   H := Homonym (Typ);
10574                end loop;
10575 
10576                Set_Homonym (H, Homonym (Typ));
10577             end if;
10578 
10579             Insert_Before (Typ_Decl, Decl);
10580             Analyze (Decl);
10581             Set_Full_View (Inc_T, Typ);
10582 
10583             if Is_Tagged then
10584 
10585                --  Create a common class-wide type for both views, and set the
10586                --  Etype of the class-wide type to the full view.
10587 
10588                Make_Class_Wide_Type (Inc_T);
10589                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
10590                Set_Etype (Class_Wide_Type (Typ), Typ);
10591             end if;
10592          end if;
10593       end Build_Incomplete_Type_Declaration;
10594 
10595       ------------------
10596       -- Designates_T --
10597       ------------------
10598 
10599       function Designates_T (Subt : Node_Id) return Boolean is
10600          Type_Id : constant Name_Id := Chars (Typ);
10601 
10602          function Names_T (Nam : Node_Id) return Boolean;
10603          --  The record type has not been introduced in the current scope
10604          --  yet, so we must examine the name of the type itself, either
10605          --  an identifier T, or an expanded name of the form P.T, where
10606          --  P denotes the current scope.
10607 
10608          -------------
10609          -- Names_T --
10610          -------------
10611 
10612          function Names_T (Nam : Node_Id) return Boolean is
10613          begin
10614             if Nkind (Nam) = N_Identifier then
10615                return Chars (Nam) = Type_Id;
10616 
10617             elsif Nkind (Nam) = N_Selected_Component then
10618                if Chars (Selector_Name (Nam)) = Type_Id then
10619                   if Nkind (Prefix (Nam)) = N_Identifier then
10620                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
10621 
10622                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
10623                      return Chars (Selector_Name (Prefix (Nam))) =
10624                             Chars (Current_Scope);
10625                   else
10626                      return False;
10627                   end if;
10628 
10629                else
10630                   return False;
10631                end if;
10632 
10633             else
10634                return False;
10635             end if;
10636          end Names_T;
10637 
10638       --  Start of processing for Designates_T
10639 
10640       begin
10641          if Nkind (Subt) = N_Identifier then
10642             return Chars (Subt) = Type_Id;
10643 
10644             --  Reference can be through an expanded name which has not been
10645             --  analyzed yet, and which designates enclosing scopes.
10646 
10647          elsif Nkind (Subt) = N_Selected_Component then
10648             if Names_T (Subt) then
10649                return True;
10650 
10651             --  Otherwise it must denote an entity that is already visible.
10652             --  The access definition may name a subtype of the enclosing
10653             --  type, if there is a previous incomplete declaration for it.
10654 
10655             else
10656                Find_Selected_Component (Subt);
10657                return
10658                  Is_Entity_Name (Subt)
10659                    and then Scope (Entity (Subt)) = Current_Scope
10660                    and then
10661                      (Chars (Base_Type (Entity (Subt))) = Type_Id
10662                        or else
10663                          (Is_Class_Wide_Type (Entity (Subt))
10664                            and then
10665                              Chars (Etype (Base_Type (Entity (Subt)))) =
10666                                                                   Type_Id));
10667             end if;
10668 
10669          --  A reference to the current type may appear as the prefix of
10670          --  a 'Class attribute.
10671 
10672          elsif Nkind (Subt) = N_Attribute_Reference
10673            and then Attribute_Name (Subt) = Name_Class
10674          then
10675             return Names_T (Prefix (Subt));
10676 
10677          else
10678             return False;
10679          end if;
10680       end Designates_T;
10681 
10682       ----------------
10683       -- Mentions_T --
10684       ----------------
10685 
10686       function Mentions_T (Acc_Def : Node_Id) return Boolean is
10687          Param_Spec : Node_Id;
10688 
10689          Acc_Subprg : constant Node_Id :=
10690                         Access_To_Subprogram_Definition (Acc_Def);
10691 
10692       begin
10693          if No (Acc_Subprg) then
10694             return Designates_T (Subtype_Mark (Acc_Def));
10695          end if;
10696 
10697          --  Component is an access_to_subprogram: examine its formals,
10698          --  and result definition in the case of an access_to_function.
10699 
10700          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
10701          while Present (Param_Spec) loop
10702             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
10703               and then Mentions_T (Parameter_Type (Param_Spec))
10704             then
10705                return True;
10706 
10707             elsif Designates_T (Parameter_Type (Param_Spec)) then
10708                return True;
10709             end if;
10710 
10711             Next (Param_Spec);
10712          end loop;
10713 
10714          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
10715             if Nkind (Result_Definition (Acc_Subprg)) =
10716                  N_Access_Definition
10717             then
10718                return Mentions_T (Result_Definition (Acc_Subprg));
10719             else
10720                return Designates_T (Result_Definition (Acc_Subprg));
10721             end if;
10722          end if;
10723 
10724          return False;
10725       end Mentions_T;
10726 
10727    --  Start of processing for Check_Anonymous_Access_Components
10728 
10729    begin
10730       if No (Comp_List) then
10731          return;
10732       end if;
10733 
10734       Comp := First (Component_Items (Comp_List));
10735       while Present (Comp) loop
10736          if Nkind (Comp) = N_Component_Declaration
10737            and then Present
10738              (Access_Definition (Component_Definition (Comp)))
10739            and then
10740              Mentions_T (Access_Definition (Component_Definition (Comp)))
10741          then
10742             Comp_Def := Component_Definition (Comp);
10743             Acc_Def :=
10744               Access_To_Subprogram_Definition (Access_Definition (Comp_Def));
10745 
10746             Build_Incomplete_Type_Declaration;
10747             Anon_Access := Make_Temporary (Loc, 'S');
10748 
10749             --  Create a declaration for the anonymous access type: either
10750             --  an access_to_object or an access_to_subprogram.
10751 
10752             if Present (Acc_Def) then
10753                if Nkind (Acc_Def) = N_Access_Function_Definition then
10754                   Type_Def :=
10755                     Make_Access_Function_Definition (Loc,
10756                       Parameter_Specifications =>
10757                         Parameter_Specifications (Acc_Def),
10758                       Result_Definition        => Result_Definition (Acc_Def));
10759                else
10760                   Type_Def :=
10761                     Make_Access_Procedure_Definition (Loc,
10762                       Parameter_Specifications =>
10763                         Parameter_Specifications (Acc_Def));
10764                end if;
10765 
10766             else
10767                Type_Def :=
10768                  Make_Access_To_Object_Definition (Loc,
10769                    Subtype_Indication =>
10770                       Relocate_Node
10771                         (Subtype_Mark (Access_Definition (Comp_Def))));
10772 
10773                Set_Constant_Present
10774                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
10775                Set_All_Present
10776                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
10777             end if;
10778 
10779             Set_Null_Exclusion_Present
10780               (Type_Def,
10781                Null_Exclusion_Present (Access_Definition (Comp_Def)));
10782 
10783             Decl :=
10784               Make_Full_Type_Declaration (Loc,
10785                 Defining_Identifier => Anon_Access,
10786                 Type_Definition     => Type_Def);
10787 
10788             Insert_Before (Typ_Decl, Decl);
10789             Analyze (Decl);
10790 
10791             --  If an access to subprogram, create the extra formals
10792 
10793             if Present (Acc_Def) then
10794                Create_Extra_Formals (Designated_Type (Anon_Access));
10795 
10796             --  If an access to object, preserve entity of designated type,
10797             --  for ASIS use, before rewriting the component definition.
10798 
10799             else
10800                declare
10801                   Desig : Entity_Id;
10802 
10803                begin
10804                   Desig := Entity (Subtype_Indication (Type_Def));
10805 
10806                   --  If the access definition is to the current  record,
10807                   --  the visible entity at this point is an  incomplete
10808                   --  type. Retrieve the full view to simplify  ASIS queries
10809 
10810                   if Ekind (Desig) = E_Incomplete_Type then
10811                      Desig := Full_View (Desig);
10812                   end if;
10813 
10814                   Set_Entity
10815                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
10816                end;
10817             end if;
10818 
10819             Rewrite (Comp_Def,
10820               Make_Component_Definition (Loc,
10821                 Subtype_Indication =>
10822                New_Occurrence_Of (Anon_Access, Loc)));
10823 
10824             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
10825                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
10826             else
10827                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
10828             end if;
10829 
10830             Set_Is_Local_Anonymous_Access (Anon_Access);
10831          end if;
10832 
10833          Next (Comp);
10834       end loop;
10835 
10836       if Present (Variant_Part (Comp_List)) then
10837          declare
10838             V : Node_Id;
10839          begin
10840             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
10841             while Present (V) loop
10842                Check_Anonymous_Access_Components
10843                  (Typ_Decl, Typ, Prev, Component_List (V));
10844                Next_Non_Pragma (V);
10845             end loop;
10846          end;
10847       end if;
10848    end Check_Anonymous_Access_Components;
10849 
10850    ----------------------
10851    -- Check_Completion --
10852    ----------------------
10853 
10854    procedure Check_Completion (Body_Id : Node_Id := Empty) is
10855       E : Entity_Id;
10856 
10857       procedure Post_Error;
10858       --  Post error message for lack of completion for entity E
10859 
10860       ----------------
10861       -- Post_Error --
10862       ----------------
10863 
10864       procedure Post_Error is
10865          procedure Missing_Body;
10866          --  Output missing body message
10867 
10868          ------------------
10869          -- Missing_Body --
10870          ------------------
10871 
10872          procedure Missing_Body is
10873          begin
10874             --  Spec is in same unit, so we can post on spec
10875 
10876             if In_Same_Source_Unit (Body_Id, E) then
10877                Error_Msg_N ("missing body for &", E);
10878 
10879             --  Spec is in a separate unit, so we have to post on the body
10880 
10881             else
10882                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
10883             end if;
10884          end Missing_Body;
10885 
10886       --  Start of processing for Post_Error
10887 
10888       begin
10889          if not Comes_From_Source (E) then
10890             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
10891 
10892                --  It may be an anonymous protected type created for a
10893                --  single variable. Post error on variable, if present.
10894 
10895                declare
10896                   Var : Entity_Id;
10897 
10898                begin
10899                   Var := First_Entity (Current_Scope);
10900                   while Present (Var) loop
10901                      exit when Etype (Var) = E
10902                        and then Comes_From_Source (Var);
10903 
10904                      Next_Entity (Var);
10905                   end loop;
10906 
10907                   if Present (Var) then
10908                      E := Var;
10909                   end if;
10910                end;
10911             end if;
10912          end if;
10913 
10914          --  If a generated entity has no completion, then either previous
10915          --  semantic errors have disabled the expansion phase, or else we had
10916          --  missing subunits, or else we are compiling without expansion,
10917          --  or else something is very wrong.
10918 
10919          if not Comes_From_Source (E) then
10920             pragma Assert
10921               (Serious_Errors_Detected > 0
10922                 or else Configurable_Run_Time_Violations > 0
10923                 or else Subunits_Missing
10924                 or else not Expander_Active);
10925             return;
10926 
10927          --  Here for source entity
10928 
10929          else
10930             --  Here if no body to post the error message, so we post the error
10931             --  on the declaration that has no completion. This is not really
10932             --  the right place to post it, think about this later ???
10933 
10934             if No (Body_Id) then
10935                if Is_Type (E) then
10936                   Error_Msg_NE
10937                     ("missing full declaration for }", Parent (E), E);
10938                else
10939                   Error_Msg_NE ("missing body for &", Parent (E), E);
10940                end if;
10941 
10942             --  Package body has no completion for a declaration that appears
10943             --  in the corresponding spec. Post error on the body, with a
10944             --  reference to the non-completed declaration.
10945 
10946             else
10947                Error_Msg_Sloc := Sloc (E);
10948 
10949                if Is_Type (E) then
10950                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
10951 
10952                elsif Is_Overloadable (E)
10953                  and then Current_Entity_In_Scope (E) /= E
10954                then
10955                   --  It may be that the completion is mistyped and appears as
10956                   --  a distinct overloading of the entity.
10957 
10958                   declare
10959                      Candidate : constant Entity_Id :=
10960                                    Current_Entity_In_Scope (E);
10961                      Decl      : constant Node_Id :=
10962                                    Unit_Declaration_Node (Candidate);
10963 
10964                   begin
10965                      if Is_Overloadable (Candidate)
10966                        and then Ekind (Candidate) = Ekind (E)
10967                        and then Nkind (Decl) = N_Subprogram_Body
10968                        and then Acts_As_Spec (Decl)
10969                      then
10970                         Check_Type_Conformant (Candidate, E);
10971 
10972                      else
10973                         Missing_Body;
10974                      end if;
10975                   end;
10976 
10977                else
10978                   Missing_Body;
10979                end if;
10980             end if;
10981          end if;
10982       end Post_Error;
10983 
10984       --  Local variables
10985 
10986       Pack_Id : constant Entity_Id := Current_Scope;
10987 
10988    --  Start of processing for Check_Completion
10989 
10990    begin
10991       E := First_Entity (Pack_Id);
10992       while Present (E) loop
10993          if Is_Intrinsic_Subprogram (E) then
10994             null;
10995 
10996          --  The following situation requires special handling: a child unit
10997          --  that appears in the context clause of the body of its parent:
10998 
10999          --    procedure Parent.Child (...);
11000 
11001          --    with Parent.Child;
11002          --    package body Parent is
11003 
11004          --  Here Parent.Child appears as a local entity, but should not be
11005          --  flagged as requiring completion, because it is a compilation
11006          --  unit.
11007 
11008          --  Ignore missing completion for a subprogram that does not come from
11009          --  source (including the _Call primitive operation of RAS types,
11010          --  which has to have the flag Comes_From_Source for other purposes):
11011          --  we assume that the expander will provide the missing completion.
11012          --  In case of previous errors, other expansion actions that provide
11013          --  bodies for null procedures with not be invoked, so inhibit message
11014          --  in those cases.
11015 
11016          --  Note that E_Operator is not in the list that follows, because
11017          --  this kind is reserved for predefined operators, that are
11018          --  intrinsic and do not need completion.
11019 
11020          elsif Ekind_In (E, E_Function,
11021                             E_Procedure,
11022                             E_Generic_Function,
11023                             E_Generic_Procedure)
11024          then
11025             if Has_Completion (E) then
11026                null;
11027 
11028             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
11029                null;
11030 
11031             elsif Is_Subprogram (E)
11032               and then (not Comes_From_Source (E)
11033                          or else Chars (E) = Name_uCall)
11034             then
11035                null;
11036 
11037             elsif
11038                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
11039             then
11040                null;
11041 
11042             elsif Nkind (Parent (E)) = N_Procedure_Specification
11043               and then Null_Present (Parent (E))
11044               and then Serious_Errors_Detected > 0
11045             then
11046                null;
11047 
11048             else
11049                Post_Error;
11050             end if;
11051 
11052          elsif Is_Entry (E) then
11053             if not Has_Completion (E) and then
11054               (Ekind (Scope (E)) = E_Protected_Object
11055                 or else Ekind (Scope (E)) = E_Protected_Type)
11056             then
11057                Post_Error;
11058             end if;
11059 
11060          elsif Is_Package_Or_Generic_Package (E) then
11061             if Unit_Requires_Body (E) then
11062                if not Has_Completion (E)
11063                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
11064                                                        N_Compilation_Unit
11065                then
11066                   Post_Error;
11067                end if;
11068 
11069             elsif not Is_Child_Unit (E) then
11070                May_Need_Implicit_Body (E);
11071             end if;
11072 
11073          --  A formal incomplete type (Ada 2012) does not require a completion;
11074          --  other incomplete type declarations do.
11075 
11076          elsif Ekind (E) = E_Incomplete_Type
11077            and then No (Underlying_Type (E))
11078            and then not Is_Generic_Type (E)
11079          then
11080             Post_Error;
11081 
11082          elsif Ekind_In (E, E_Task_Type, E_Protected_Type)
11083            and then not Has_Completion (E)
11084          then
11085             Post_Error;
11086 
11087          --  A single task declared in the current scope is a constant, verify
11088          --  that the body of its anonymous type is in the same scope. If the
11089          --  task is defined elsewhere, this may be a renaming declaration for
11090          --  which no completion is needed.
11091 
11092          elsif Ekind (E) = E_Constant
11093            and then Ekind (Etype (E)) = E_Task_Type
11094            and then not Has_Completion (Etype (E))
11095            and then Scope (Etype (E)) = Current_Scope
11096          then
11097             Post_Error;
11098 
11099          elsif Ekind (E) = E_Protected_Object
11100            and then not Has_Completion (Etype (E))
11101          then
11102             Post_Error;
11103 
11104          elsif Ekind (E) = E_Record_Type then
11105             if Is_Tagged_Type (E) then
11106                Check_Abstract_Overriding (E);
11107                Check_Conventions (E);
11108             end if;
11109 
11110             Check_Aliased_Component_Types (E);
11111 
11112          elsif Ekind (E) = E_Array_Type then
11113             Check_Aliased_Component_Types (E);
11114 
11115          end if;
11116 
11117          Next_Entity (E);
11118       end loop;
11119    end Check_Completion;
11120 
11121    ------------------------------------
11122    -- Check_CPP_Type_Has_No_Defaults --
11123    ------------------------------------
11124 
11125    procedure Check_CPP_Type_Has_No_Defaults (T : Entity_Id) is
11126       Tdef  : constant Node_Id := Type_Definition (Declaration_Node (T));
11127       Clist : Node_Id;
11128       Comp  : Node_Id;
11129 
11130    begin
11131       --  Obtain the component list
11132 
11133       if Nkind (Tdef) = N_Record_Definition then
11134          Clist := Component_List (Tdef);
11135       else pragma Assert (Nkind (Tdef) = N_Derived_Type_Definition);
11136          Clist := Component_List (Record_Extension_Part (Tdef));
11137       end if;
11138 
11139       --  Check all components to ensure no default expressions
11140 
11141       if Present (Clist) then
11142          Comp := First (Component_Items (Clist));
11143          while Present (Comp) loop
11144             if Present (Expression (Comp)) then
11145                Error_Msg_N
11146                  ("component of imported 'C'P'P type cannot have "
11147                   & "default expression", Expression (Comp));
11148             end if;
11149 
11150             Next (Comp);
11151          end loop;
11152       end if;
11153    end Check_CPP_Type_Has_No_Defaults;
11154 
11155    ----------------------------
11156    -- Check_Delta_Expression --
11157    ----------------------------
11158 
11159    procedure Check_Delta_Expression (E : Node_Id) is
11160    begin
11161       if not (Is_Real_Type (Etype (E))) then
11162          Wrong_Type (E, Any_Real);
11163 
11164       elsif not Is_OK_Static_Expression (E) then
11165          Flag_Non_Static_Expr
11166            ("non-static expression used for delta value!", E);
11167 
11168       elsif not UR_Is_Positive (Expr_Value_R (E)) then
11169          Error_Msg_N ("delta expression must be positive", E);
11170 
11171       else
11172          return;
11173       end if;
11174 
11175       --  If any of above errors occurred, then replace the incorrect
11176       --  expression by the real 0.1, which should prevent further errors.
11177 
11178       Rewrite (E,
11179         Make_Real_Literal (Sloc (E), Ureal_Tenth));
11180       Analyze_And_Resolve (E, Standard_Float);
11181    end Check_Delta_Expression;
11182 
11183    -----------------------------
11184    -- Check_Digits_Expression --
11185    -----------------------------
11186 
11187    procedure Check_Digits_Expression (E : Node_Id) is
11188    begin
11189       if not (Is_Integer_Type (Etype (E))) then
11190          Wrong_Type (E, Any_Integer);
11191 
11192       elsif not Is_OK_Static_Expression (E) then
11193          Flag_Non_Static_Expr
11194            ("non-static expression used for digits value!", E);
11195 
11196       elsif Expr_Value (E) <= 0 then
11197          Error_Msg_N ("digits value must be greater than zero", E);
11198 
11199       else
11200          return;
11201       end if;
11202 
11203       --  If any of above errors occurred, then replace the incorrect
11204       --  expression by the integer 1, which should prevent further errors.
11205 
11206       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
11207       Analyze_And_Resolve (E, Standard_Integer);
11208 
11209    end Check_Digits_Expression;
11210 
11211    --------------------------
11212    -- Check_Initialization --
11213    --------------------------
11214 
11215    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
11216    begin
11217       --  Special processing for limited types
11218 
11219       if Is_Limited_Type (T)
11220         and then not In_Instance
11221         and then not In_Inlined_Body
11222       then
11223          if not OK_For_Limited_Init (T, Exp) then
11224 
11225             --  In GNAT mode, this is just a warning, to allow it to be evilly
11226             --  turned off. Otherwise it is a real error.
11227 
11228             if GNAT_Mode then
11229                Error_Msg_N
11230                  ("??cannot initialize entities of limited type!", Exp);
11231 
11232             elsif Ada_Version < Ada_2005 then
11233 
11234                --  The side effect removal machinery may generate illegal Ada
11235                --  code to avoid the usage of access types and 'reference in
11236                --  SPARK mode. Since this is legal code with respect to theorem
11237                --  proving, do not emit the error.
11238 
11239                if GNATprove_Mode
11240                  and then Nkind (Exp) = N_Function_Call
11241                  and then Nkind (Parent (Exp)) = N_Object_Declaration
11242                  and then not Comes_From_Source
11243                                 (Defining_Identifier (Parent (Exp)))
11244                then
11245                   null;
11246 
11247                else
11248                   Error_Msg_N
11249                     ("cannot initialize entities of limited type", Exp);
11250                   Explain_Limited_Type (T, Exp);
11251                end if;
11252 
11253             else
11254                --  Specialize error message according to kind of illegal
11255                --  initial expression.
11256 
11257                if Nkind (Exp) = N_Type_Conversion
11258                  and then Nkind (Expression (Exp)) = N_Function_Call
11259                then
11260                   Error_Msg_N
11261                     ("illegal context for call"
11262                       & " to function with limited result", Exp);
11263 
11264                else
11265                   Error_Msg_N
11266                     ("initialization of limited object requires aggregate "
11267                       & "or function call",  Exp);
11268                end if;
11269             end if;
11270          end if;
11271       end if;
11272 
11273       --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag gets
11274       --  set unless we can be sure that no range check is required.
11275 
11276       if (GNATprove_Mode or not Expander_Active)
11277         and then Is_Scalar_Type (T)
11278         and then not Is_In_Range (Exp, T, Assume_Valid => True)
11279       then
11280          Set_Do_Range_Check (Exp);
11281       end if;
11282    end Check_Initialization;
11283 
11284    ----------------------
11285    -- Check_Interfaces --
11286    ----------------------
11287 
11288    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
11289       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
11290 
11291       Iface       : Node_Id;
11292       Iface_Def   : Node_Id;
11293       Iface_Typ   : Entity_Id;
11294       Parent_Node : Node_Id;
11295 
11296       Is_Task : Boolean := False;
11297       --  Set True if parent type or any progenitor is a task interface
11298 
11299       Is_Protected : Boolean := False;
11300       --  Set True if parent type or any progenitor is a protected interface
11301 
11302       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
11303       --  Check that a progenitor is compatible with declaration. If an error
11304       --  message is output, it is posted on Error_Node.
11305 
11306       ------------------
11307       -- Check_Ifaces --
11308       ------------------
11309 
11310       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
11311          Iface_Id : constant Entity_Id :=
11312                       Defining_Identifier (Parent (Iface_Def));
11313          Type_Def : Node_Id;
11314 
11315       begin
11316          if Nkind (N) = N_Private_Extension_Declaration then
11317             Type_Def := N;
11318          else
11319             Type_Def := Type_Definition (N);
11320          end if;
11321 
11322          if Is_Task_Interface (Iface_Id) then
11323             Is_Task := True;
11324 
11325          elsif Is_Protected_Interface (Iface_Id) then
11326             Is_Protected := True;
11327          end if;
11328 
11329          if Is_Synchronized_Interface (Iface_Id) then
11330 
11331             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
11332             --  extension derived from a synchronized interface must explicitly
11333             --  be declared synchronized, because the full view will be a
11334             --  synchronized type.
11335 
11336             if Nkind (N) = N_Private_Extension_Declaration then
11337                if not Synchronized_Present (N) then
11338                   Error_Msg_NE
11339                     ("private extension of& must be explicitly synchronized",
11340                       N, Iface_Id);
11341                end if;
11342 
11343             --  However, by 3.9.4(16/2), a full type that is a record extension
11344             --  is never allowed to derive from a synchronized interface (note
11345             --  that interfaces must be excluded from this check, because those
11346             --  are represented by derived type definitions in some cases).
11347 
11348             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
11349               and then not Interface_Present (Type_Definition (N))
11350             then
11351                Error_Msg_N ("record extension cannot derive from synchronized "
11352                             & "interface", Error_Node);
11353             end if;
11354          end if;
11355 
11356          --  Check that the characteristics of the progenitor are compatible
11357          --  with the explicit qualifier in the declaration.
11358          --  The check only applies to qualifiers that come from source.
11359          --  Limited_Present also appears in the declaration of corresponding
11360          --  records, and the check does not apply to them.
11361 
11362          if Limited_Present (Type_Def)
11363            and then not
11364              Is_Concurrent_Record_Type (Defining_Identifier (N))
11365          then
11366             if Is_Limited_Interface (Parent_Type)
11367               and then not Is_Limited_Interface (Iface_Id)
11368             then
11369                Error_Msg_NE
11370                  ("progenitor & must be limited interface",
11371                    Error_Node, Iface_Id);
11372 
11373             elsif
11374               (Task_Present (Iface_Def)
11375                 or else Protected_Present (Iface_Def)
11376                 or else Synchronized_Present (Iface_Def))
11377               and then Nkind (N) /= N_Private_Extension_Declaration
11378               and then not Error_Posted (N)
11379             then
11380                Error_Msg_NE
11381                  ("progenitor & must be limited interface",
11382                    Error_Node, Iface_Id);
11383             end if;
11384 
11385          --  Protected interfaces can only inherit from limited, synchronized
11386          --  or protected interfaces.
11387 
11388          elsif Nkind (N) = N_Full_Type_Declaration
11389            and then  Protected_Present (Type_Def)
11390          then
11391             if Limited_Present (Iface_Def)
11392               or else Synchronized_Present (Iface_Def)
11393               or else Protected_Present (Iface_Def)
11394             then
11395                null;
11396 
11397             elsif Task_Present (Iface_Def) then
11398                Error_Msg_N ("(Ada 2005) protected interface cannot inherit "
11399                             & "from task interface", Error_Node);
11400 
11401             else
11402                Error_Msg_N ("(Ada 2005) protected interface cannot inherit "
11403                             & "from non-limited interface", Error_Node);
11404             end if;
11405 
11406          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
11407          --  limited and synchronized.
11408 
11409          elsif Synchronized_Present (Type_Def) then
11410             if Limited_Present (Iface_Def)
11411               or else Synchronized_Present (Iface_Def)
11412             then
11413                null;
11414 
11415             elsif Protected_Present (Iface_Def)
11416               and then Nkind (N) /= N_Private_Extension_Declaration
11417             then
11418                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
11419                             & "from protected interface", Error_Node);
11420 
11421             elsif Task_Present (Iface_Def)
11422               and then Nkind (N) /= N_Private_Extension_Declaration
11423             then
11424                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
11425                             & "from task interface", Error_Node);
11426 
11427             elsif not Is_Limited_Interface (Iface_Id) then
11428                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit "
11429                             & "from non-limited interface", Error_Node);
11430             end if;
11431 
11432          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
11433          --  synchronized or task interfaces.
11434 
11435          elsif Nkind (N) = N_Full_Type_Declaration
11436            and then Task_Present (Type_Def)
11437          then
11438             if Limited_Present (Iface_Def)
11439               or else Synchronized_Present (Iface_Def)
11440               or else Task_Present (Iface_Def)
11441             then
11442                null;
11443 
11444             elsif Protected_Present (Iface_Def) then
11445                Error_Msg_N ("(Ada 2005) task interface cannot inherit from "
11446                             & "protected interface", Error_Node);
11447 
11448             else
11449                Error_Msg_N ("(Ada 2005) task interface cannot inherit from "
11450                             & "non-limited interface", Error_Node);
11451             end if;
11452          end if;
11453       end Check_Ifaces;
11454 
11455    --  Start of processing for Check_Interfaces
11456 
11457    begin
11458       if Is_Interface (Parent_Type) then
11459          if Is_Task_Interface (Parent_Type) then
11460             Is_Task := True;
11461 
11462          elsif Is_Protected_Interface (Parent_Type) then
11463             Is_Protected := True;
11464          end if;
11465       end if;
11466 
11467       if Nkind (N) = N_Private_Extension_Declaration then
11468 
11469          --  Check that progenitors are compatible with declaration
11470 
11471          Iface := First (Interface_List (Def));
11472          while Present (Iface) loop
11473             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
11474 
11475             Parent_Node := Parent (Base_Type (Iface_Typ));
11476             Iface_Def   := Type_Definition (Parent_Node);
11477 
11478             if not Is_Interface (Iface_Typ) then
11479                Diagnose_Interface (Iface, Iface_Typ);
11480             else
11481                Check_Ifaces (Iface_Def, Iface);
11482             end if;
11483 
11484             Next (Iface);
11485          end loop;
11486 
11487          if Is_Task and Is_Protected then
11488             Error_Msg_N
11489               ("type cannot derive from task and protected interface", N);
11490          end if;
11491 
11492          return;
11493       end if;
11494 
11495       --  Full type declaration of derived type.
11496       --  Check compatibility with parent if it is interface type
11497 
11498       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
11499         and then Is_Interface (Parent_Type)
11500       then
11501          Parent_Node := Parent (Parent_Type);
11502 
11503          --  More detailed checks for interface varieties
11504 
11505          Check_Ifaces
11506            (Iface_Def  => Type_Definition (Parent_Node),
11507             Error_Node => Subtype_Indication (Type_Definition (N)));
11508       end if;
11509 
11510       Iface := First (Interface_List (Def));
11511       while Present (Iface) loop
11512          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
11513 
11514          Parent_Node := Parent (Base_Type (Iface_Typ));
11515          Iface_Def   := Type_Definition (Parent_Node);
11516 
11517          if not Is_Interface (Iface_Typ) then
11518             Diagnose_Interface (Iface, Iface_Typ);
11519 
11520          else
11521             --  "The declaration of a specific descendant of an interface
11522             --   type freezes the interface type" RM 13.14
11523 
11524             Freeze_Before (N, Iface_Typ);
11525             Check_Ifaces (Iface_Def, Error_Node => Iface);
11526          end if;
11527 
11528          Next (Iface);
11529       end loop;
11530 
11531       if Is_Task and Is_Protected then
11532          Error_Msg_N
11533            ("type cannot derive from task and protected interface", N);
11534       end if;
11535    end Check_Interfaces;
11536 
11537    ------------------------------------
11538    -- Check_Or_Process_Discriminants --
11539    ------------------------------------
11540 
11541    --  If an incomplete or private type declaration was already given for the
11542    --  type, the discriminants may have already been processed if they were
11543    --  present on the incomplete declaration. In this case a full conformance
11544    --  check has been performed in Find_Type_Name, and we then recheck here
11545    --  some properties that can't be checked on the partial view alone.
11546    --  Otherwise we call Process_Discriminants.
11547 
11548    procedure Check_Or_Process_Discriminants
11549      (N    : Node_Id;
11550       T    : Entity_Id;
11551       Prev : Entity_Id := Empty)
11552    is
11553    begin
11554       if Has_Discriminants (T) then
11555 
11556          --  Discriminants are already set on T if they were already present
11557          --  on the partial view. Make them visible to component declarations.
11558 
11559          declare
11560             D : Entity_Id;
11561             --  Discriminant on T (full view) referencing expr on partial view
11562 
11563             Prev_D : Entity_Id;
11564             --  Entity of corresponding discriminant on partial view
11565 
11566             New_D : Node_Id;
11567             --  Discriminant specification for full view, expression is
11568             --  the syntactic copy on full view (which has been checked for
11569             --  conformance with partial view), only used here to post error
11570             --  message.
11571 
11572          begin
11573             D     := First_Discriminant (T);
11574             New_D := First (Discriminant_Specifications (N));
11575             while Present (D) loop
11576                Prev_D := Current_Entity (D);
11577                Set_Current_Entity (D);
11578                Set_Is_Immediately_Visible (D);
11579                Set_Homonym (D, Prev_D);
11580 
11581                --  Handle the case where there is an untagged partial view and
11582                --  the full view is tagged: must disallow discriminants with
11583                --  defaults, unless compiling for Ada 2012, which allows a
11584                --  limited tagged type to have defaulted discriminants (see
11585                --  AI05-0214). However, suppress error here if it was already
11586                --  reported on the default expression of the partial view.
11587 
11588                if Is_Tagged_Type (T)
11589                  and then Present (Expression (Parent (D)))
11590                  and then (not Is_Limited_Type (Current_Scope)
11591                             or else Ada_Version < Ada_2012)
11592                  and then not Error_Posted (Expression (Parent (D)))
11593                then
11594                   if Ada_Version >= Ada_2012 then
11595                      Error_Msg_N
11596                        ("discriminants of nonlimited tagged type cannot have "
11597                         & "defaults",
11598                         Expression (New_D));
11599                   else
11600                      Error_Msg_N
11601                        ("discriminants of tagged type cannot have defaults",
11602                         Expression (New_D));
11603                   end if;
11604                end if;
11605 
11606                --  Ada 2005 (AI-230): Access discriminant allowed in
11607                --  non-limited record types.
11608 
11609                if Ada_Version < Ada_2005 then
11610 
11611                   --  This restriction gets applied to the full type here. It
11612                   --  has already been applied earlier to the partial view.
11613 
11614                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
11615                end if;
11616 
11617                Next_Discriminant (D);
11618                Next (New_D);
11619             end loop;
11620          end;
11621 
11622       elsif Present (Discriminant_Specifications (N)) then
11623          Process_Discriminants (N, Prev);
11624       end if;
11625    end Check_Or_Process_Discriminants;
11626 
11627    ----------------------
11628    -- Check_Real_Bound --
11629    ----------------------
11630 
11631    procedure Check_Real_Bound (Bound : Node_Id) is
11632    begin
11633       if not Is_Real_Type (Etype (Bound)) then
11634          Error_Msg_N
11635            ("bound in real type definition must be of real type", Bound);
11636 
11637       elsif not Is_OK_Static_Expression (Bound) then
11638          Flag_Non_Static_Expr
11639            ("non-static expression used for real type bound!", Bound);
11640 
11641       else
11642          return;
11643       end if;
11644 
11645       Rewrite
11646         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
11647       Analyze (Bound);
11648       Resolve (Bound, Standard_Float);
11649    end Check_Real_Bound;
11650 
11651    ------------------------------
11652    -- Complete_Private_Subtype --
11653    ------------------------------
11654 
11655    procedure Complete_Private_Subtype
11656      (Priv        : Entity_Id;
11657       Full        : Entity_Id;
11658       Full_Base   : Entity_Id;
11659       Related_Nod : Node_Id)
11660    is
11661       Save_Next_Entity : Entity_Id;
11662       Save_Homonym     : Entity_Id;
11663 
11664    begin
11665       --  Set semantic attributes for (implicit) private subtype completion.
11666       --  If the full type has no discriminants, then it is a copy of the
11667       --  full view of the base. Otherwise, it is a subtype of the base with
11668       --  a possible discriminant constraint. Save and restore the original
11669       --  Next_Entity field of full to ensure that the calls to Copy_Node do
11670       --  not corrupt the entity chain.
11671 
11672       --  Note that the type of the full view is the same entity as the type
11673       --  of the partial view. In this fashion, the subtype has access to the
11674       --  correct view of the parent.
11675 
11676       Save_Next_Entity := Next_Entity (Full);
11677       Save_Homonym     := Homonym (Priv);
11678 
11679       case Ekind (Full_Base) is
11680          when E_Record_Type    |
11681               E_Record_Subtype |
11682               Class_Wide_Kind  |
11683               Private_Kind     |
11684               Task_Kind        |
11685               Protected_Kind   =>
11686             Copy_Node (Priv, Full);
11687 
11688             Set_Has_Discriminants
11689                              (Full, Has_Discriminants (Full_Base));
11690             Set_Has_Unknown_Discriminants
11691                              (Full, Has_Unknown_Discriminants (Full_Base));
11692             Set_First_Entity (Full, First_Entity (Full_Base));
11693             Set_Last_Entity  (Full, Last_Entity (Full_Base));
11694 
11695             --  If the underlying base type is constrained, we know that the
11696             --  full view of the subtype is constrained as well (the converse
11697             --  is not necessarily true).
11698 
11699             if Is_Constrained (Full_Base) then
11700                Set_Is_Constrained (Full);
11701             end if;
11702 
11703          when others =>
11704             Copy_Node (Full_Base, Full);
11705 
11706             Set_Chars         (Full, Chars (Priv));
11707             Conditional_Delay (Full, Priv);
11708             Set_Sloc          (Full, Sloc (Priv));
11709       end case;
11710 
11711       Set_Next_Entity               (Full, Save_Next_Entity);
11712       Set_Homonym                   (Full, Save_Homonym);
11713       Set_Associated_Node_For_Itype (Full, Related_Nod);
11714 
11715       --  Set common attributes for all subtypes: kind, convention, etc.
11716 
11717       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
11718       Set_Convention (Full, Convention (Full_Base));
11719 
11720       --  The Etype of the full view is inconsistent. Gigi needs to see the
11721       --  structural full view, which is what the current scheme gives: the
11722       --  Etype of the full view is the etype of the full base. However, if the
11723       --  full base is a derived type, the full view then looks like a subtype
11724       --  of the parent, not a subtype of the full base. If instead we write:
11725 
11726       --       Set_Etype (Full, Full_Base);
11727 
11728       --  then we get inconsistencies in the front-end (confusion between
11729       --  views). Several outstanding bugs are related to this ???
11730 
11731       Set_Is_First_Subtype (Full, False);
11732       Set_Scope            (Full, Scope (Priv));
11733       Set_Size_Info        (Full, Full_Base);
11734       Set_RM_Size          (Full, RM_Size (Full_Base));
11735       Set_Is_Itype         (Full);
11736 
11737       --  A subtype of a private-type-without-discriminants, whose full-view
11738       --  has discriminants with default expressions, is not constrained.
11739 
11740       if not Has_Discriminants (Priv) then
11741          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
11742 
11743          if Has_Discriminants (Full_Base) then
11744             Set_Discriminant_Constraint
11745               (Full, Discriminant_Constraint (Full_Base));
11746 
11747             --  The partial view may have been indefinite, the full view
11748             --  might not be.
11749 
11750             Set_Has_Unknown_Discriminants
11751               (Full, Has_Unknown_Discriminants (Full_Base));
11752          end if;
11753       end if;
11754 
11755       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
11756       Set_Depends_On_Private (Full, Has_Private_Component (Full));
11757 
11758       --  Freeze the private subtype entity if its parent is delayed, and not
11759       --  already frozen. We skip this processing if the type is an anonymous
11760       --  subtype of a record component, or is the corresponding record of a
11761       --  protected type, since these are processed when the enclosing type
11762       --  is frozen.
11763 
11764       if not Is_Type (Scope (Full)) then
11765          Set_Has_Delayed_Freeze (Full,
11766            Has_Delayed_Freeze (Full_Base)
11767              and then (not Is_Frozen (Full_Base)));
11768       end if;
11769 
11770       Set_Freeze_Node (Full, Empty);
11771       Set_Is_Frozen (Full, False);
11772       Set_Full_View (Priv, Full);
11773 
11774       if Has_Discriminants (Full) then
11775          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
11776          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
11777 
11778          if Has_Unknown_Discriminants (Full) then
11779             Set_Discriminant_Constraint (Full, No_Elist);
11780          end if;
11781       end if;
11782 
11783       if Ekind (Full_Base) = E_Record_Type
11784         and then Has_Discriminants (Full_Base)
11785         and then Has_Discriminants (Priv) -- might not, if errors
11786         and then not Has_Unknown_Discriminants (Priv)
11787         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
11788       then
11789          Create_Constrained_Components
11790            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
11791 
11792       --  If the full base is itself derived from private, build a congruent
11793       --  subtype of its underlying type, for use by the back end. For a
11794       --  constrained record component, the declaration cannot be placed on
11795       --  the component list, but it must nevertheless be built an analyzed, to
11796       --  supply enough information for Gigi to compute the size of component.
11797 
11798       elsif Ekind (Full_Base) in Private_Kind
11799         and then Is_Derived_Type (Full_Base)
11800         and then Has_Discriminants (Full_Base)
11801         and then (Ekind (Current_Scope) /= E_Record_Subtype)
11802       then
11803          if not Is_Itype (Priv)
11804            and then
11805              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
11806          then
11807             Build_Underlying_Full_View
11808               (Parent (Priv), Full, Etype (Full_Base));
11809 
11810          elsif Nkind (Related_Nod) = N_Component_Declaration then
11811             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
11812          end if;
11813 
11814       elsif Is_Record_Type (Full_Base) then
11815 
11816          --  Show Full is simply a renaming of Full_Base
11817 
11818          Set_Cloned_Subtype (Full, Full_Base);
11819       end if;
11820 
11821       --  It is unsafe to share the bounds of a scalar type, because the Itype
11822       --  is elaborated on demand, and if a bound is non-static then different
11823       --  orders of elaboration in different units will lead to different
11824       --  external symbols.
11825 
11826       if Is_Scalar_Type (Full_Base) then
11827          Set_Scalar_Range (Full,
11828            Make_Range (Sloc (Related_Nod),
11829              Low_Bound  =>
11830                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
11831              High_Bound =>
11832                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
11833 
11834          --  This completion inherits the bounds of the full parent, but if
11835          --  the parent is an unconstrained floating point type, so is the
11836          --  completion.
11837 
11838          if Is_Floating_Point_Type (Full_Base) then
11839             Set_Includes_Infinities
11840              (Scalar_Range (Full), Has_Infinities (Full_Base));
11841          end if;
11842       end if;
11843 
11844       --  ??? It seems that a lot of fields are missing that should be copied
11845       --  from Full_Base to Full. Here are some that are introduced in a
11846       --  non-disruptive way but a cleanup is necessary.
11847 
11848       if Is_Tagged_Type (Full_Base) then
11849          Set_Is_Tagged_Type (Full);
11850          Set_Direct_Primitive_Operations
11851            (Full, Direct_Primitive_Operations (Full_Base));
11852          Set_No_Tagged_Streams_Pragma
11853            (Full, No_Tagged_Streams_Pragma (Full_Base));
11854 
11855          --  Inherit class_wide type of full_base in case the partial view was
11856          --  not tagged. Otherwise it has already been created when the private
11857          --  subtype was analyzed.
11858 
11859          if No (Class_Wide_Type (Full)) then
11860             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
11861          end if;
11862 
11863       --  If this is a subtype of a protected or task type, constrain its
11864       --  corresponding record, unless this is a subtype without constraints,
11865       --  i.e. a simple renaming as with an actual subtype in an instance.
11866 
11867       elsif Is_Concurrent_Type (Full_Base) then
11868          if Has_Discriminants (Full)
11869            and then Present (Corresponding_Record_Type (Full_Base))
11870            and then
11871              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
11872          then
11873             Set_Corresponding_Record_Type (Full,
11874               Constrain_Corresponding_Record
11875                 (Full, Corresponding_Record_Type (Full_Base), Related_Nod));
11876 
11877          else
11878             Set_Corresponding_Record_Type (Full,
11879               Corresponding_Record_Type (Full_Base));
11880          end if;
11881       end if;
11882 
11883       --  Link rep item chain, and also setting of Has_Predicates from private
11884       --  subtype to full subtype, since we will need these on the full subtype
11885       --  to create the predicate function. Note that the full subtype may
11886       --  already have rep items, inherited from the full view of the base
11887       --  type, so we must be sure not to overwrite these entries.
11888 
11889       declare
11890          Append    : Boolean;
11891          Item      : Node_Id;
11892          Next_Item : Node_Id;
11893 
11894       begin
11895          Item := First_Rep_Item (Full);
11896 
11897          --  If no existing rep items on full type, we can just link directly
11898          --  to the list of items on the private type, if any exist.. Same if
11899          --  the rep items are only those inherited from the base
11900 
11901          if (No (Item)
11902               or else Nkind (Item) /= N_Aspect_Specification
11903               or else Entity (Item) = Full_Base)
11904              and then Present (First_Rep_Item (Priv))
11905          then
11906             Set_First_Rep_Item (Full, First_Rep_Item (Priv));
11907 
11908          --  Otherwise, search to the end of items currently linked to the full
11909          --  subtype and append the private items to the end. However, if Priv
11910          --  and Full already have the same list of rep items, then the append
11911          --  is not done, as that would create a circularity.
11912 
11913          elsif Item /= First_Rep_Item (Priv) then
11914             Append := True;
11915             loop
11916                Next_Item := Next_Rep_Item (Item);
11917                exit when No (Next_Item);
11918                Item := Next_Item;
11919 
11920                --  If the private view has aspect specifications, the full view
11921                --  inherits them. Since these aspects may already have been
11922                --  attached to the full view during derivation, do not append
11923                --  them if already present.
11924 
11925                if Item = First_Rep_Item (Priv) then
11926                   Append := False;
11927                   exit;
11928                end if;
11929             end loop;
11930 
11931             --  And link the private type items at the end of the chain
11932 
11933             if Append then
11934                Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
11935             end if;
11936          end if;
11937       end;
11938 
11939       --  Make sure Has_Predicates is set on full type if it is set on the
11940       --  private type. Note that it may already be set on the full type and
11941       --  if so, we don't want to unset it. Similarly, propagate information
11942       --  about delayed aspects, because the corresponding pragmas must be
11943       --  analyzed when one of the views is frozen. This last step is needed
11944       --  in particular when the full type is a scalar type for which an
11945       --  anonymous base type is constructed.
11946 
11947       --  The predicate functions are generated either at the freeze point
11948       --  of the type or at the end of the visible part, and we must avoid
11949       --  generating them twice.
11950 
11951       if Has_Predicates (Priv) then
11952          Set_Has_Predicates (Full);
11953 
11954          if Present (Predicate_Function (Priv))
11955            and then No (Predicate_Function (Full))
11956          then
11957             Set_Predicate_Function (Full, Predicate_Function (Priv));
11958          end if;
11959       end if;
11960 
11961       if Has_Delayed_Aspects (Priv) then
11962          Set_Has_Delayed_Aspects (Full);
11963       end if;
11964    end Complete_Private_Subtype;
11965 
11966    ----------------------------
11967    -- Constant_Redeclaration --
11968    ----------------------------
11969 
11970    procedure Constant_Redeclaration
11971      (Id : Entity_Id;
11972       N  : Node_Id;
11973       T  : out Entity_Id)
11974    is
11975       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
11976       Obj_Def : constant Node_Id := Object_Definition (N);
11977       New_T   : Entity_Id;
11978 
11979       procedure Check_Possible_Deferred_Completion
11980         (Prev_Id      : Entity_Id;
11981          Prev_Obj_Def : Node_Id;
11982          Curr_Obj_Def : Node_Id);
11983       --  Determine whether the two object definitions describe the partial
11984       --  and the full view of a constrained deferred constant. Generate
11985       --  a subtype for the full view and verify that it statically matches
11986       --  the subtype of the partial view.
11987 
11988       procedure Check_Recursive_Declaration (Typ : Entity_Id);
11989       --  If deferred constant is an access type initialized with an allocator,
11990       --  check whether there is an illegal recursion in the definition,
11991       --  through a default value of some record subcomponent. This is normally
11992       --  detected when generating init procs, but requires this additional
11993       --  mechanism when expansion is disabled.
11994 
11995       ----------------------------------------
11996       -- Check_Possible_Deferred_Completion --
11997       ----------------------------------------
11998 
11999       procedure Check_Possible_Deferred_Completion
12000         (Prev_Id      : Entity_Id;
12001          Prev_Obj_Def : Node_Id;
12002          Curr_Obj_Def : Node_Id)
12003       is
12004       begin
12005          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
12006            and then Present (Constraint (Prev_Obj_Def))
12007            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
12008            and then Present (Constraint (Curr_Obj_Def))
12009          then
12010             declare
12011                Loc    : constant Source_Ptr := Sloc (N);
12012                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
12013                Decl   : constant Node_Id    :=
12014                           Make_Subtype_Declaration (Loc,
12015                             Defining_Identifier => Def_Id,
12016                             Subtype_Indication  =>
12017                               Relocate_Node (Curr_Obj_Def));
12018 
12019             begin
12020                Insert_Before_And_Analyze (N, Decl);
12021                Set_Etype (Id, Def_Id);
12022 
12023                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
12024                   Error_Msg_Sloc := Sloc (Prev_Id);
12025                   Error_Msg_N ("subtype does not statically match deferred "
12026                                & "declaration #", N);
12027                end if;
12028             end;
12029          end if;
12030       end Check_Possible_Deferred_Completion;
12031 
12032       ---------------------------------
12033       -- Check_Recursive_Declaration --
12034       ---------------------------------
12035 
12036       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
12037          Comp : Entity_Id;
12038 
12039       begin
12040          if Is_Record_Type (Typ) then
12041             Comp := First_Component (Typ);
12042             while Present (Comp) loop
12043                if Comes_From_Source (Comp) then
12044                   if Present (Expression (Parent (Comp)))
12045                     and then Is_Entity_Name (Expression (Parent (Comp)))
12046                     and then Entity (Expression (Parent (Comp))) = Prev
12047                   then
12048                      Error_Msg_Sloc := Sloc (Parent (Comp));
12049                      Error_Msg_NE
12050                        ("illegal circularity with declaration for & #",
12051                          N, Comp);
12052                      return;
12053 
12054                   elsif Is_Record_Type (Etype (Comp)) then
12055                      Check_Recursive_Declaration (Etype (Comp));
12056                   end if;
12057                end if;
12058 
12059                Next_Component (Comp);
12060             end loop;
12061          end if;
12062       end Check_Recursive_Declaration;
12063 
12064    --  Start of processing for Constant_Redeclaration
12065 
12066    begin
12067       if Nkind (Parent (Prev)) = N_Object_Declaration then
12068          if Nkind (Object_Definition
12069                      (Parent (Prev))) = N_Subtype_Indication
12070          then
12071             --  Find type of new declaration. The constraints of the two
12072             --  views must match statically, but there is no point in
12073             --  creating an itype for the full view.
12074 
12075             if Nkind (Obj_Def) = N_Subtype_Indication then
12076                Find_Type (Subtype_Mark (Obj_Def));
12077                New_T := Entity (Subtype_Mark (Obj_Def));
12078 
12079             else
12080                Find_Type (Obj_Def);
12081                New_T := Entity (Obj_Def);
12082             end if;
12083 
12084             T := Etype (Prev);
12085 
12086          else
12087             --  The full view may impose a constraint, even if the partial
12088             --  view does not, so construct the subtype.
12089 
12090             New_T := Find_Type_Of_Object (Obj_Def, N);
12091             T     := New_T;
12092          end if;
12093 
12094       else
12095          --  Current declaration is illegal, diagnosed below in Enter_Name
12096 
12097          T := Empty;
12098          New_T := Any_Type;
12099       end if;
12100 
12101       --  If previous full declaration or a renaming declaration exists, or if
12102       --  a homograph is present, let Enter_Name handle it, either with an
12103       --  error or with the removal of an overridden implicit subprogram.
12104       --  The previous one is a full declaration if it has an expression
12105       --  (which in the case of an aggregate is indicated by the Init flag).
12106 
12107       if Ekind (Prev) /= E_Constant
12108         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
12109         or else Present (Expression (Parent (Prev)))
12110         or else Has_Init_Expression (Parent (Prev))
12111         or else Present (Full_View (Prev))
12112       then
12113          Enter_Name (Id);
12114 
12115       --  Verify that types of both declarations match, or else that both types
12116       --  are anonymous access types whose designated subtypes statically match
12117       --  (as allowed in Ada 2005 by AI-385).
12118 
12119       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
12120         and then
12121           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
12122              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
12123              or else Is_Access_Constant (Etype (New_T)) /=
12124                      Is_Access_Constant (Etype (Prev))
12125              or else Can_Never_Be_Null (Etype (New_T)) /=
12126                      Can_Never_Be_Null (Etype (Prev))
12127              or else Null_Exclusion_Present (Parent (Prev)) /=
12128                      Null_Exclusion_Present (Parent (Id))
12129              or else not Subtypes_Statically_Match
12130                            (Designated_Type (Etype (Prev)),
12131                             Designated_Type (Etype (New_T))))
12132       then
12133          Error_Msg_Sloc := Sloc (Prev);
12134          Error_Msg_N ("type does not match declaration#", N);
12135          Set_Full_View (Prev, Id);
12136          Set_Etype (Id, Any_Type);
12137 
12138          --  A deferred constant whose type is an anonymous array is always
12139          --  illegal (unless imported). A detailed error message might be
12140          --  helpful for Ada beginners.
12141 
12142          if Nkind (Object_Definition (Parent (Prev)))
12143             = N_Constrained_Array_Definition
12144            and then Nkind (Object_Definition (N))
12145               = N_Constrained_Array_Definition
12146          then
12147             Error_Msg_N ("\each anonymous array is a distinct type", N);
12148             Error_Msg_N ("a deferred constant must have a named type",
12149               Object_Definition (Parent (Prev)));
12150          end if;
12151 
12152       elsif
12153         Null_Exclusion_Present (Parent (Prev))
12154           and then not Null_Exclusion_Present (N)
12155       then
12156          Error_Msg_Sloc := Sloc (Prev);
12157          Error_Msg_N ("null-exclusion does not match declaration#", N);
12158          Set_Full_View (Prev, Id);
12159          Set_Etype (Id, Any_Type);
12160 
12161       --  If so, process the full constant declaration
12162 
12163       else
12164          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
12165          --  the deferred declaration is constrained, then the subtype defined
12166          --  by the subtype_indication in the full declaration shall match it
12167          --  statically.
12168 
12169          Check_Possible_Deferred_Completion
12170            (Prev_Id      => Prev,
12171             Prev_Obj_Def => Object_Definition (Parent (Prev)),
12172             Curr_Obj_Def => Obj_Def);
12173 
12174          Set_Full_View (Prev, Id);
12175          Set_Is_Public (Id, Is_Public (Prev));
12176          Set_Is_Internal (Id);
12177          Append_Entity (Id, Current_Scope);
12178 
12179          --  Check ALIASED present if present before (RM 7.4(7))
12180 
12181          if Is_Aliased (Prev)
12182            and then not Aliased_Present (N)
12183          then
12184             Error_Msg_Sloc := Sloc (Prev);
12185             Error_Msg_N ("ALIASED required (see declaration #)", N);
12186          end if;
12187 
12188          --  Check that placement is in private part and that the incomplete
12189          --  declaration appeared in the visible part.
12190 
12191          if Ekind (Current_Scope) = E_Package
12192            and then not In_Private_Part (Current_Scope)
12193          then
12194             Error_Msg_Sloc := Sloc (Prev);
12195             Error_Msg_N
12196               ("full constant for declaration # must be in private part", N);
12197 
12198          elsif Ekind (Current_Scope) = E_Package
12199            and then
12200              List_Containing (Parent (Prev)) /=
12201                Visible_Declarations (Package_Specification (Current_Scope))
12202          then
12203             Error_Msg_N
12204               ("deferred constant must be declared in visible part",
12205                  Parent (Prev));
12206          end if;
12207 
12208          if Is_Access_Type (T)
12209            and then Nkind (Expression (N)) = N_Allocator
12210          then
12211             Check_Recursive_Declaration (Designated_Type (T));
12212          end if;
12213 
12214          --  A deferred constant is a visible entity. If type has invariants,
12215          --  verify that the initial value satisfies them.
12216 
12217          if Has_Invariants (T) and then Present (Invariant_Procedure (T)) then
12218             Insert_After (N,
12219               Make_Invariant_Call (New_Occurrence_Of (Prev, Sloc (N))));
12220          end if;
12221       end if;
12222    end Constant_Redeclaration;
12223 
12224    ----------------------
12225    -- Constrain_Access --
12226    ----------------------
12227 
12228    procedure Constrain_Access
12229      (Def_Id      : in out Entity_Id;
12230       S           : Node_Id;
12231       Related_Nod : Node_Id)
12232    is
12233       T             : constant Entity_Id := Entity (Subtype_Mark (S));
12234       Desig_Type    : constant Entity_Id := Designated_Type (T);
12235       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
12236       Constraint_OK : Boolean := True;
12237 
12238    begin
12239       if Is_Array_Type (Desig_Type) then
12240          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
12241 
12242       elsif (Is_Record_Type (Desig_Type)
12243               or else Is_Incomplete_Or_Private_Type (Desig_Type))
12244         and then not Is_Constrained (Desig_Type)
12245       then
12246          --  ??? The following code is a temporary bypass to ignore a
12247          --  discriminant constraint on access type if it is constraining
12248          --  the current record. Avoid creating the implicit subtype of the
12249          --  record we are currently compiling since right now, we cannot
12250          --  handle these. For now, just return the access type itself.
12251 
12252          if Desig_Type = Current_Scope
12253            and then No (Def_Id)
12254          then
12255             Set_Ekind (Desig_Subtype, E_Record_Subtype);
12256             Def_Id := Entity (Subtype_Mark (S));
12257 
12258             --  This call added to ensure that the constraint is analyzed
12259             --  (needed for a B test). Note that we still return early from
12260             --  this procedure to avoid recursive processing. ???
12261 
12262             Constrain_Discriminated_Type
12263               (Desig_Subtype, S, Related_Nod, For_Access => True);
12264             return;
12265          end if;
12266 
12267          --  Enforce rule that the constraint is illegal if there is an
12268          --  unconstrained view of the designated type. This means that the
12269          --  partial view (either a private type declaration or a derivation
12270          --  from a private type) has no discriminants. (Defect Report
12271          --  8652/0008, Technical Corrigendum 1, checked by ACATS B371001).
12272 
12273          --  Rule updated for Ada 2005: The private type is said to have
12274          --  a constrained partial view, given that objects of the type
12275          --  can be declared. Furthermore, the rule applies to all access
12276          --  types, unlike the rule concerning default discriminants (see
12277          --  RM 3.7.1(7/3))
12278 
12279          if (Ekind (T) = E_General_Access_Type or else Ada_Version >= Ada_2005)
12280            and then Has_Private_Declaration (Desig_Type)
12281            and then In_Open_Scopes (Scope (Desig_Type))
12282            and then Has_Discriminants (Desig_Type)
12283          then
12284             declare
12285                Pack  : constant Node_Id :=
12286                          Unit_Declaration_Node (Scope (Desig_Type));
12287                Decls : List_Id;
12288                Decl  : Node_Id;
12289 
12290             begin
12291                if Nkind (Pack) = N_Package_Declaration then
12292                   Decls := Visible_Declarations (Specification (Pack));
12293                   Decl := First (Decls);
12294                   while Present (Decl) loop
12295                      if (Nkind (Decl) = N_Private_Type_Declaration
12296                           and then Chars (Defining_Identifier (Decl)) =
12297                                                            Chars (Desig_Type))
12298 
12299                        or else
12300                         (Nkind (Decl) = N_Full_Type_Declaration
12301                           and then
12302                             Chars (Defining_Identifier (Decl)) =
12303                                                      Chars (Desig_Type)
12304                           and then Is_Derived_Type (Desig_Type)
12305                           and then
12306                             Has_Private_Declaration (Etype (Desig_Type)))
12307                      then
12308                         if No (Discriminant_Specifications (Decl)) then
12309                            Error_Msg_N
12310                              ("cannot constrain access type if designated "
12311                               & "type has constrained partial view", S);
12312                         end if;
12313 
12314                         exit;
12315                      end if;
12316 
12317                      Next (Decl);
12318                   end loop;
12319                end if;
12320             end;
12321          end if;
12322 
12323          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
12324            For_Access => True);
12325 
12326       elsif Is_Concurrent_Type (Desig_Type)
12327         and then not Is_Constrained (Desig_Type)
12328       then
12329          Constrain_Concurrent (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
12330 
12331       else
12332          Error_Msg_N ("invalid constraint on access type", S);
12333 
12334          --  We simply ignore an invalid constraint
12335 
12336          Desig_Subtype := Desig_Type;
12337          Constraint_OK := False;
12338       end if;
12339 
12340       if No (Def_Id) then
12341          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
12342       else
12343          Set_Ekind (Def_Id, E_Access_Subtype);
12344       end if;
12345 
12346       if Constraint_OK then
12347          Set_Etype (Def_Id, Base_Type (T));
12348 
12349          if Is_Private_Type (Desig_Type) then
12350             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
12351          end if;
12352       else
12353          Set_Etype (Def_Id, Any_Type);
12354       end if;
12355 
12356       Set_Size_Info                (Def_Id, T);
12357       Set_Is_Constrained           (Def_Id, Constraint_OK);
12358       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
12359       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
12360       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
12361 
12362       Conditional_Delay (Def_Id, T);
12363 
12364       --  AI-363 : Subtypes of general access types whose designated types have
12365       --  default discriminants are disallowed. In instances, the rule has to
12366       --  be checked against the actual, of which T is the subtype. In a
12367       --  generic body, the rule is checked assuming that the actual type has
12368       --  defaulted discriminants.
12369 
12370       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
12371          if Ekind (Base_Type (T)) = E_General_Access_Type
12372            and then Has_Defaulted_Discriminants (Desig_Type)
12373          then
12374             if Ada_Version < Ada_2005 then
12375                Error_Msg_N
12376                  ("access subtype of general access type would not " &
12377                   "be allowed in Ada 2005?y?", S);
12378             else
12379                Error_Msg_N
12380                  ("access subtype of general access type not allowed", S);
12381             end if;
12382 
12383             Error_Msg_N ("\discriminants have defaults", S);
12384 
12385          elsif Is_Access_Type (T)
12386            and then Is_Generic_Type (Desig_Type)
12387            and then Has_Discriminants (Desig_Type)
12388            and then In_Package_Body (Current_Scope)
12389          then
12390             if Ada_Version < Ada_2005 then
12391                Error_Msg_N
12392                  ("access subtype would not be allowed in generic body "
12393                   & "in Ada 2005?y?", S);
12394             else
12395                Error_Msg_N
12396                  ("access subtype not allowed in generic body", S);
12397             end if;
12398 
12399             Error_Msg_N
12400               ("\designated type is a discriminated formal", S);
12401          end if;
12402       end if;
12403    end Constrain_Access;
12404 
12405    ---------------------
12406    -- Constrain_Array --
12407    ---------------------
12408 
12409    procedure Constrain_Array
12410      (Def_Id      : in out Entity_Id;
12411       SI          : Node_Id;
12412       Related_Nod : Node_Id;
12413       Related_Id  : Entity_Id;
12414       Suffix      : Character)
12415    is
12416       C                     : constant Node_Id := Constraint (SI);
12417       Number_Of_Constraints : Nat := 0;
12418       Index                 : Node_Id;
12419       S, T                  : Entity_Id;
12420       Constraint_OK         : Boolean := True;
12421 
12422    begin
12423       T := Entity (Subtype_Mark (SI));
12424 
12425       if Is_Access_Type (T) then
12426          T := Designated_Type (T);
12427       end if;
12428 
12429       --  If an index constraint follows a subtype mark in a subtype indication
12430       --  then the type or subtype denoted by the subtype mark must not already
12431       --  impose an index constraint. The subtype mark must denote either an
12432       --  unconstrained array type or an access type whose designated type
12433       --  is such an array type... (RM 3.6.1)
12434 
12435       if Is_Constrained (T) then
12436          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
12437          Constraint_OK := False;
12438 
12439       else
12440          S := First (Constraints (C));
12441          while Present (S) loop
12442             Number_Of_Constraints := Number_Of_Constraints + 1;
12443             Next (S);
12444          end loop;
12445 
12446          --  In either case, the index constraint must provide a discrete
12447          --  range for each index of the array type and the type of each
12448          --  discrete range must be the same as that of the corresponding
12449          --  index. (RM 3.6.1)
12450 
12451          if Number_Of_Constraints /= Number_Dimensions (T) then
12452             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
12453             Constraint_OK := False;
12454 
12455          else
12456             S := First (Constraints (C));
12457             Index := First_Index (T);
12458             Analyze (Index);
12459 
12460             --  Apply constraints to each index type
12461 
12462             for J in 1 .. Number_Of_Constraints loop
12463                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
12464                Next (Index);
12465                Next (S);
12466             end loop;
12467 
12468          end if;
12469       end if;
12470 
12471       if No (Def_Id) then
12472          Def_Id :=
12473            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
12474          Set_Parent (Def_Id, Related_Nod);
12475 
12476       else
12477          Set_Ekind (Def_Id, E_Array_Subtype);
12478       end if;
12479 
12480       Set_Size_Info      (Def_Id,                (T));
12481       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
12482       Set_Etype          (Def_Id, Base_Type      (T));
12483 
12484       if Constraint_OK then
12485          Set_First_Index (Def_Id, First (Constraints (C)));
12486       else
12487          Set_First_Index (Def_Id, First_Index (T));
12488       end if;
12489 
12490       Set_Is_Constrained     (Def_Id, True);
12491       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
12492       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
12493 
12494       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
12495       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
12496 
12497       --  A subtype does not inherit the Packed_Array_Impl_Type of is parent.
12498       --  We need to initialize the attribute because if Def_Id is previously
12499       --  analyzed through a limited_with clause, it will have the attributes
12500       --  of an incomplete type, one of which is an Elist that overlaps the
12501       --  Packed_Array_Impl_Type field.
12502 
12503       Set_Packed_Array_Impl_Type (Def_Id, Empty);
12504 
12505       --  Build a freeze node if parent still needs one. Also make sure that
12506       --  the Depends_On_Private status is set because the subtype will need
12507       --  reprocessing at the time the base type does, and also we must set a
12508       --  conditional delay.
12509 
12510       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
12511       Conditional_Delay (Def_Id, T);
12512    end Constrain_Array;
12513 
12514    ------------------------------
12515    -- Constrain_Component_Type --
12516    ------------------------------
12517 
12518    function Constrain_Component_Type
12519      (Comp            : Entity_Id;
12520       Constrained_Typ : Entity_Id;
12521       Related_Node    : Node_Id;
12522       Typ             : Entity_Id;
12523       Constraints     : Elist_Id) return Entity_Id
12524    is
12525       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
12526       Compon_Type : constant Entity_Id := Etype (Comp);
12527 
12528       function Build_Constrained_Array_Type
12529         (Old_Type : Entity_Id) return Entity_Id;
12530       --  If Old_Type is an array type, one of whose indexes is constrained
12531       --  by a discriminant, build an Itype whose constraint replaces the
12532       --  discriminant with its value in the constraint.
12533 
12534       function Build_Constrained_Discriminated_Type
12535         (Old_Type : Entity_Id) return Entity_Id;
12536       --  Ditto for record components
12537 
12538       function Build_Constrained_Access_Type
12539         (Old_Type : Entity_Id) return Entity_Id;
12540       --  Ditto for access types. Makes use of previous two functions, to
12541       --  constrain designated type.
12542 
12543       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
12544       --  T is an array or discriminated type, C is a list of constraints
12545       --  that apply to T. This routine builds the constrained subtype.
12546 
12547       function Is_Discriminant (Expr : Node_Id) return Boolean;
12548       --  Returns True if Expr is a discriminant
12549 
12550       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
12551       --  Find the value of discriminant Discrim in Constraint
12552 
12553       -----------------------------------
12554       -- Build_Constrained_Access_Type --
12555       -----------------------------------
12556 
12557       function Build_Constrained_Access_Type
12558         (Old_Type : Entity_Id) return Entity_Id
12559       is
12560          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
12561          Itype         : Entity_Id;
12562          Desig_Subtype : Entity_Id;
12563          Scop          : Entity_Id;
12564 
12565       begin
12566          --  if the original access type was not embedded in the enclosing
12567          --  type definition, there is no need to produce a new access
12568          --  subtype. In fact every access type with an explicit constraint
12569          --  generates an itype whose scope is the enclosing record.
12570 
12571          if not Is_Type (Scope (Old_Type)) then
12572             return Old_Type;
12573 
12574          elsif Is_Array_Type (Desig_Type) then
12575             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
12576 
12577          elsif Has_Discriminants (Desig_Type) then
12578 
12579             --  This may be an access type to an enclosing record type for
12580             --  which we are constructing the constrained components. Return
12581             --  the enclosing record subtype. This is not always correct,
12582             --  but avoids infinite recursion. ???
12583 
12584             Desig_Subtype := Any_Type;
12585 
12586             for J in reverse 0 .. Scope_Stack.Last loop
12587                Scop := Scope_Stack.Table (J).Entity;
12588 
12589                if Is_Type (Scop)
12590                  and then Base_Type (Scop) = Base_Type (Desig_Type)
12591                then
12592                   Desig_Subtype := Scop;
12593                end if;
12594 
12595                exit when not Is_Type (Scop);
12596             end loop;
12597 
12598             if Desig_Subtype = Any_Type then
12599                Desig_Subtype :=
12600                  Build_Constrained_Discriminated_Type (Desig_Type);
12601             end if;
12602 
12603          else
12604             return Old_Type;
12605          end if;
12606 
12607          if Desig_Subtype /= Desig_Type then
12608 
12609             --  The Related_Node better be here or else we won't be able
12610             --  to attach new itypes to a node in the tree.
12611 
12612             pragma Assert (Present (Related_Node));
12613 
12614             Itype := Create_Itype (E_Access_Subtype, Related_Node);
12615 
12616             Set_Etype                    (Itype, Base_Type      (Old_Type));
12617             Set_Size_Info                (Itype,                (Old_Type));
12618             Set_Directly_Designated_Type (Itype, Desig_Subtype);
12619             Set_Depends_On_Private       (Itype, Has_Private_Component
12620                                                                 (Old_Type));
12621             Set_Is_Access_Constant       (Itype, Is_Access_Constant
12622                                                                 (Old_Type));
12623 
12624             --  The new itype needs freezing when it depends on a not frozen
12625             --  type and the enclosing subtype needs freezing.
12626 
12627             if Has_Delayed_Freeze (Constrained_Typ)
12628               and then not Is_Frozen (Constrained_Typ)
12629             then
12630                Conditional_Delay (Itype, Base_Type (Old_Type));
12631             end if;
12632 
12633             return Itype;
12634 
12635          else
12636             return Old_Type;
12637          end if;
12638       end Build_Constrained_Access_Type;
12639 
12640       ----------------------------------
12641       -- Build_Constrained_Array_Type --
12642       ----------------------------------
12643 
12644       function Build_Constrained_Array_Type
12645         (Old_Type : Entity_Id) return Entity_Id
12646       is
12647          Lo_Expr     : Node_Id;
12648          Hi_Expr     : Node_Id;
12649          Old_Index   : Node_Id;
12650          Range_Node  : Node_Id;
12651          Constr_List : List_Id;
12652 
12653          Need_To_Create_Itype : Boolean := False;
12654 
12655       begin
12656          Old_Index := First_Index (Old_Type);
12657          while Present (Old_Index) loop
12658             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
12659 
12660             if Is_Discriminant (Lo_Expr)
12661                  or else
12662                Is_Discriminant (Hi_Expr)
12663             then
12664                Need_To_Create_Itype := True;
12665             end if;
12666 
12667             Next_Index (Old_Index);
12668          end loop;
12669 
12670          if Need_To_Create_Itype then
12671             Constr_List := New_List;
12672 
12673             Old_Index := First_Index (Old_Type);
12674             while Present (Old_Index) loop
12675                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
12676 
12677                if Is_Discriminant (Lo_Expr) then
12678                   Lo_Expr := Get_Discr_Value (Lo_Expr);
12679                end if;
12680 
12681                if Is_Discriminant (Hi_Expr) then
12682                   Hi_Expr := Get_Discr_Value (Hi_Expr);
12683                end if;
12684 
12685                Range_Node :=
12686                  Make_Range
12687                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
12688 
12689                Append (Range_Node, To => Constr_List);
12690 
12691                Next_Index (Old_Index);
12692             end loop;
12693 
12694             return Build_Subtype (Old_Type, Constr_List);
12695 
12696          else
12697             return Old_Type;
12698          end if;
12699       end Build_Constrained_Array_Type;
12700 
12701       ------------------------------------------
12702       -- Build_Constrained_Discriminated_Type --
12703       ------------------------------------------
12704 
12705       function Build_Constrained_Discriminated_Type
12706         (Old_Type : Entity_Id) return Entity_Id
12707       is
12708          Expr           : Node_Id;
12709          Constr_List    : List_Id;
12710          Old_Constraint : Elmt_Id;
12711 
12712          Need_To_Create_Itype : Boolean := False;
12713 
12714       begin
12715          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
12716          while Present (Old_Constraint) loop
12717             Expr := Node (Old_Constraint);
12718 
12719             if Is_Discriminant (Expr) then
12720                Need_To_Create_Itype := True;
12721             end if;
12722 
12723             Next_Elmt (Old_Constraint);
12724          end loop;
12725 
12726          if Need_To_Create_Itype then
12727             Constr_List := New_List;
12728 
12729             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
12730             while Present (Old_Constraint) loop
12731                Expr := Node (Old_Constraint);
12732 
12733                if Is_Discriminant (Expr) then
12734                   Expr := Get_Discr_Value (Expr);
12735                end if;
12736 
12737                Append (New_Copy_Tree (Expr), To => Constr_List);
12738 
12739                Next_Elmt (Old_Constraint);
12740             end loop;
12741 
12742             return Build_Subtype (Old_Type, Constr_List);
12743 
12744          else
12745             return Old_Type;
12746          end if;
12747       end Build_Constrained_Discriminated_Type;
12748 
12749       -------------------
12750       -- Build_Subtype --
12751       -------------------
12752 
12753       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
12754          Indic       : Node_Id;
12755          Subtyp_Decl : Node_Id;
12756          Def_Id      : Entity_Id;
12757          Btyp        : Entity_Id := Base_Type (T);
12758 
12759       begin
12760          --  The Related_Node better be here or else we won't be able to
12761          --  attach new itypes to a node in the tree.
12762 
12763          pragma Assert (Present (Related_Node));
12764 
12765          --  If the view of the component's type is incomplete or private
12766          --  with unknown discriminants, then the constraint must be applied
12767          --  to the full type.
12768 
12769          if Has_Unknown_Discriminants (Btyp)
12770            and then Present (Underlying_Type (Btyp))
12771          then
12772             Btyp := Underlying_Type (Btyp);
12773          end if;
12774 
12775          Indic :=
12776            Make_Subtype_Indication (Loc,
12777              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
12778              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
12779 
12780          Def_Id := Create_Itype (Ekind (T), Related_Node);
12781 
12782          Subtyp_Decl :=
12783            Make_Subtype_Declaration (Loc,
12784              Defining_Identifier => Def_Id,
12785              Subtype_Indication  => Indic);
12786 
12787          Set_Parent (Subtyp_Decl, Parent (Related_Node));
12788 
12789          --  Itypes must be analyzed with checks off (see package Itypes)
12790 
12791          Analyze (Subtyp_Decl, Suppress => All_Checks);
12792 
12793          return Def_Id;
12794       end Build_Subtype;
12795 
12796       ---------------------
12797       -- Get_Discr_Value --
12798       ---------------------
12799 
12800       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
12801          D : Entity_Id;
12802          E : Elmt_Id;
12803 
12804       begin
12805          --  The discriminant may be declared for the type, in which case we
12806          --  find it by iterating over the list of discriminants. If the
12807          --  discriminant is inherited from a parent type, it appears as the
12808          --  corresponding discriminant of the current type. This will be the
12809          --  case when constraining an inherited component whose constraint is
12810          --  given by a discriminant of the parent.
12811 
12812          D := First_Discriminant (Typ);
12813          E := First_Elmt (Constraints);
12814 
12815          while Present (D) loop
12816             if D = Entity (Discrim)
12817               or else D = CR_Discriminant (Entity (Discrim))
12818               or else Corresponding_Discriminant (D) = Entity (Discrim)
12819             then
12820                return Node (E);
12821             end if;
12822 
12823             Next_Discriminant (D);
12824             Next_Elmt (E);
12825          end loop;
12826 
12827          --  The Corresponding_Discriminant mechanism is incomplete, because
12828          --  the correspondence between new and old discriminants is not one
12829          --  to one: one new discriminant can constrain several old ones. In
12830          --  that case, scan sequentially the stored_constraint, the list of
12831          --  discriminants of the parents, and the constraints.
12832 
12833          --  Previous code checked for the present of the Stored_Constraint
12834          --  list for the derived type, but did not use it at all. Should it
12835          --  be present when the component is a discriminated task type?
12836 
12837          if Is_Derived_Type (Typ)
12838            and then Scope (Entity (Discrim)) = Etype (Typ)
12839          then
12840             D := First_Discriminant (Etype (Typ));
12841             E := First_Elmt (Constraints);
12842             while Present (D) loop
12843                if D = Entity (Discrim) then
12844                   return Node (E);
12845                end if;
12846 
12847                Next_Discriminant (D);
12848                Next_Elmt (E);
12849             end loop;
12850          end if;
12851 
12852          --  Something is wrong if we did not find the value
12853 
12854          raise Program_Error;
12855       end Get_Discr_Value;
12856 
12857       ---------------------
12858       -- Is_Discriminant --
12859       ---------------------
12860 
12861       function Is_Discriminant (Expr : Node_Id) return Boolean is
12862          Discrim_Scope : Entity_Id;
12863 
12864       begin
12865          if Denotes_Discriminant (Expr) then
12866             Discrim_Scope := Scope (Entity (Expr));
12867 
12868             --  Either we have a reference to one of Typ's discriminants,
12869 
12870             pragma Assert (Discrim_Scope = Typ
12871 
12872                --  or to the discriminants of the parent type, in the case
12873                --  of a derivation of a tagged type with variants.
12874 
12875                or else Discrim_Scope = Etype (Typ)
12876                or else Full_View (Discrim_Scope) = Etype (Typ)
12877 
12878                --  or same as above for the case where the discriminants
12879                --  were declared in Typ's private view.
12880 
12881                or else (Is_Private_Type (Discrim_Scope)
12882                          and then Chars (Discrim_Scope) = Chars (Typ))
12883 
12884                --  or else we are deriving from the full view and the
12885                --  discriminant is declared in the private entity.
12886 
12887                or else (Is_Private_Type (Typ)
12888                          and then Chars (Discrim_Scope) = Chars (Typ))
12889 
12890                --  Or we are constrained the corresponding record of a
12891                --  synchronized type that completes a private declaration.
12892 
12893                or else (Is_Concurrent_Record_Type (Typ)
12894                          and then
12895                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
12896 
12897                --  or we have a class-wide type, in which case make sure the
12898                --  discriminant found belongs to the root type.
12899 
12900                or else (Is_Class_Wide_Type (Typ)
12901                          and then Etype (Typ) = Discrim_Scope));
12902 
12903             return True;
12904          end if;
12905 
12906          --  In all other cases we have something wrong
12907 
12908          return False;
12909       end Is_Discriminant;
12910 
12911    --  Start of processing for Constrain_Component_Type
12912 
12913    begin
12914       if Nkind (Parent (Comp)) = N_Component_Declaration
12915         and then Comes_From_Source (Parent (Comp))
12916         and then Comes_From_Source
12917           (Subtype_Indication (Component_Definition (Parent (Comp))))
12918         and then
12919           Is_Entity_Name
12920             (Subtype_Indication (Component_Definition (Parent (Comp))))
12921       then
12922          return Compon_Type;
12923 
12924       elsif Is_Array_Type (Compon_Type) then
12925          return Build_Constrained_Array_Type (Compon_Type);
12926 
12927       elsif Has_Discriminants (Compon_Type) then
12928          return Build_Constrained_Discriminated_Type (Compon_Type);
12929 
12930       elsif Is_Access_Type (Compon_Type) then
12931          return Build_Constrained_Access_Type (Compon_Type);
12932 
12933       else
12934          return Compon_Type;
12935       end if;
12936    end Constrain_Component_Type;
12937 
12938    --------------------------
12939    -- Constrain_Concurrent --
12940    --------------------------
12941 
12942    --  For concurrent types, the associated record value type carries the same
12943    --  discriminants, so when we constrain a concurrent type, we must constrain
12944    --  the corresponding record type as well.
12945 
12946    procedure Constrain_Concurrent
12947      (Def_Id      : in out Entity_Id;
12948       SI          : Node_Id;
12949       Related_Nod : Node_Id;
12950       Related_Id  : Entity_Id;
12951       Suffix      : Character)
12952    is
12953       --  Retrieve Base_Type to ensure getting to the concurrent type in the
12954       --  case of a private subtype (needed when only doing semantic analysis).
12955 
12956       T_Ent : Entity_Id := Base_Type (Entity (Subtype_Mark (SI)));
12957       T_Val : Entity_Id;
12958 
12959    begin
12960       if Is_Access_Type (T_Ent) then
12961          T_Ent := Designated_Type (T_Ent);
12962       end if;
12963 
12964       T_Val := Corresponding_Record_Type (T_Ent);
12965 
12966       if Present (T_Val) then
12967 
12968          if No (Def_Id) then
12969             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
12970 
12971             --  Elaborate itype now, as it may be used in a subsequent
12972             --  synchronized operation in another scope.
12973 
12974             if Nkind (Related_Nod) = N_Full_Type_Declaration then
12975                Build_Itype_Reference (Def_Id, Related_Nod);
12976             end if;
12977          end if;
12978 
12979          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
12980 
12981          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
12982          Set_Corresponding_Record_Type (Def_Id,
12983            Constrain_Corresponding_Record (Def_Id, T_Val, Related_Nod));
12984 
12985       else
12986          --  If there is no associated record, expansion is disabled and this
12987          --  is a generic context. Create a subtype in any case, so that
12988          --  semantic analysis can proceed.
12989 
12990          if No (Def_Id) then
12991             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
12992          end if;
12993 
12994          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
12995       end if;
12996    end Constrain_Concurrent;
12997 
12998    ------------------------------------
12999    -- Constrain_Corresponding_Record --
13000    ------------------------------------
13001 
13002    function Constrain_Corresponding_Record
13003      (Prot_Subt   : Entity_Id;
13004       Corr_Rec    : Entity_Id;
13005       Related_Nod : Node_Id) return Entity_Id
13006    is
13007       T_Sub : constant Entity_Id :=
13008                 Create_Itype (E_Record_Subtype, Related_Nod, Corr_Rec, 'C');
13009 
13010    begin
13011       Set_Etype             (T_Sub, Corr_Rec);
13012       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
13013       Set_Is_Constrained    (T_Sub, True);
13014       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
13015       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
13016 
13017       if Has_Discriminants (Prot_Subt) then -- False only if errors.
13018          Set_Discriminant_Constraint
13019            (T_Sub, Discriminant_Constraint (Prot_Subt));
13020          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
13021          Create_Constrained_Components
13022            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
13023       end if;
13024 
13025       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
13026 
13027       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
13028          Conditional_Delay (T_Sub, Corr_Rec);
13029 
13030       else
13031          --  This is a component subtype: it will be frozen in the context of
13032          --  the enclosing record's init_proc, so that discriminant references
13033          --  are resolved to discriminals. (Note: we used to skip freezing
13034          --  altogether in that case, which caused errors downstream for
13035          --  components of a bit packed array type).
13036 
13037          Set_Has_Delayed_Freeze (T_Sub);
13038       end if;
13039 
13040       return T_Sub;
13041    end Constrain_Corresponding_Record;
13042 
13043    -----------------------
13044    -- Constrain_Decimal --
13045    -----------------------
13046 
13047    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
13048       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
13049       C           : constant Node_Id    := Constraint (S);
13050       Loc         : constant Source_Ptr := Sloc (C);
13051       Range_Expr  : Node_Id;
13052       Digits_Expr : Node_Id;
13053       Digits_Val  : Uint;
13054       Bound_Val   : Ureal;
13055 
13056    begin
13057       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
13058 
13059       if Nkind (C) = N_Range_Constraint then
13060          Range_Expr := Range_Expression (C);
13061          Digits_Val := Digits_Value (T);
13062 
13063       else
13064          pragma Assert (Nkind (C) = N_Digits_Constraint);
13065 
13066          Check_SPARK_05_Restriction ("digits constraint is not allowed", S);
13067 
13068          Digits_Expr := Digits_Expression (C);
13069          Analyze_And_Resolve (Digits_Expr, Any_Integer);
13070 
13071          Check_Digits_Expression (Digits_Expr);
13072          Digits_Val := Expr_Value (Digits_Expr);
13073 
13074          if Digits_Val > Digits_Value (T) then
13075             Error_Msg_N
13076                ("digits expression is incompatible with subtype", C);
13077             Digits_Val := Digits_Value (T);
13078          end if;
13079 
13080          if Present (Range_Constraint (C)) then
13081             Range_Expr := Range_Expression (Range_Constraint (C));
13082          else
13083             Range_Expr := Empty;
13084          end if;
13085       end if;
13086 
13087       Set_Etype            (Def_Id, Base_Type        (T));
13088       Set_Size_Info        (Def_Id,                  (T));
13089       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
13090       Set_Delta_Value      (Def_Id, Delta_Value      (T));
13091       Set_Scale_Value      (Def_Id, Scale_Value      (T));
13092       Set_Small_Value      (Def_Id, Small_Value      (T));
13093       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
13094       Set_Digits_Value     (Def_Id, Digits_Val);
13095 
13096       --  Manufacture range from given digits value if no range present
13097 
13098       if No (Range_Expr) then
13099          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
13100          Range_Expr :=
13101            Make_Range (Loc,
13102              Low_Bound =>
13103                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
13104              High_Bound =>
13105                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
13106       end if;
13107 
13108       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
13109       Set_Discrete_RM_Size (Def_Id);
13110 
13111       --  Unconditionally delay the freeze, since we cannot set size
13112       --  information in all cases correctly until the freeze point.
13113 
13114       Set_Has_Delayed_Freeze (Def_Id);
13115    end Constrain_Decimal;
13116 
13117    ----------------------------------
13118    -- Constrain_Discriminated_Type --
13119    ----------------------------------
13120 
13121    procedure Constrain_Discriminated_Type
13122      (Def_Id      : Entity_Id;
13123       S           : Node_Id;
13124       Related_Nod : Node_Id;
13125       For_Access  : Boolean := False)
13126    is
13127       E : Entity_Id := Entity (Subtype_Mark (S));
13128       T : Entity_Id;
13129 
13130       procedure Fixup_Bad_Constraint;
13131       --  Called after finding a bad constraint, and after having posted an
13132       --  appropriate error message. The goal is to leave type Def_Id in as
13133       --  reasonable state as possible.
13134 
13135       --------------------------
13136       -- Fixup_Bad_Constraint --
13137       --------------------------
13138 
13139       procedure Fixup_Bad_Constraint is
13140       begin
13141          --  Set a reasonable Ekind for the entity. For an incomplete type,
13142          --  we can't do much, but for other types, we can set the proper
13143          --  corresponding subtype kind.
13144 
13145          if Ekind (T) = E_Incomplete_Type then
13146             Set_Ekind (Def_Id, Ekind (T));
13147          else
13148             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
13149          end if;
13150 
13151          --  Set Etype to the known type, to reduce chances of cascaded errors
13152 
13153          Set_Etype (Def_Id, E);
13154          Set_Error_Posted (Def_Id);
13155       end Fixup_Bad_Constraint;
13156 
13157       --  Local variables
13158 
13159       C      : Node_Id;
13160       Constr : Elist_Id := New_Elmt_List;
13161 
13162    --  Start of processing for Constrain_Discriminated_Type
13163 
13164    begin
13165       C := Constraint (S);
13166 
13167       --  A discriminant constraint is only allowed in a subtype indication,
13168       --  after a subtype mark. This subtype mark must denote either a type
13169       --  with discriminants, or an access type whose designated type is a
13170       --  type with discriminants. A discriminant constraint specifies the
13171       --  values of these discriminants (RM 3.7.2(5)).
13172 
13173       T := Base_Type (Entity (Subtype_Mark (S)));
13174 
13175       if Is_Access_Type (T) then
13176          T := Designated_Type (T);
13177       end if;
13178 
13179       --  In an instance it may be necessary to retrieve the full view of a
13180       --  type with unknown discriminants, or a full view with defaulted
13181       --  discriminants. In other contexts the constraint is illegal.
13182 
13183       if In_Instance
13184         and then Is_Private_Type (T)
13185         and then Present (Full_View (T))
13186         and then
13187           (Has_Unknown_Discriminants (T)
13188             or else
13189               (not Has_Discriminants (T)
13190                 and then Has_Discriminants (Full_View (T))
13191                 and then Present (Discriminant_Default_Value
13192                            (First_Discriminant (Full_View (T))))))
13193       then
13194          T := Full_View (T);
13195          E := Full_View (E);
13196       end if;
13197 
13198       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal. Avoid
13199       --  generating an error for access-to-incomplete subtypes.
13200 
13201       if Ada_Version >= Ada_2005
13202         and then Ekind (T) = E_Incomplete_Type
13203         and then Nkind (Parent (S)) = N_Subtype_Declaration
13204         and then not Is_Itype (Def_Id)
13205       then
13206          --  A little sanity check: emit an error message if the type has
13207          --  discriminants to begin with. Type T may be a regular incomplete
13208          --  type or imported via a limited with clause.
13209 
13210          if Has_Discriminants (T)
13211            or else (From_Limited_With (T)
13212                      and then Present (Non_Limited_View (T))
13213                      and then Nkind (Parent (Non_Limited_View (T))) =
13214                                                N_Full_Type_Declaration
13215                      and then Present (Discriminant_Specifications
13216                                          (Parent (Non_Limited_View (T)))))
13217          then
13218             Error_Msg_N
13219               ("(Ada 2005) incomplete subtype may not be constrained", C);
13220          else
13221             Error_Msg_N ("invalid constraint: type has no discriminant", C);
13222          end if;
13223 
13224          Fixup_Bad_Constraint;
13225          return;
13226 
13227       --  Check that the type has visible discriminants. The type may be
13228       --  a private type with unknown discriminants whose full view has
13229       --  discriminants which are invisible.
13230 
13231       elsif not Has_Discriminants (T)
13232         or else
13233           (Has_Unknown_Discriminants (T)
13234              and then Is_Private_Type (T))
13235       then
13236          Error_Msg_N ("invalid constraint: type has no discriminant", C);
13237          Fixup_Bad_Constraint;
13238          return;
13239 
13240       elsif Is_Constrained (E)
13241         or else (Ekind (E) = E_Class_Wide_Subtype
13242                   and then Present (Discriminant_Constraint (E)))
13243       then
13244          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
13245          Fixup_Bad_Constraint;
13246          return;
13247       end if;
13248 
13249       --  T may be an unconstrained subtype (e.g. a generic actual). Constraint
13250       --  applies to the base type.
13251 
13252       T := Base_Type (T);
13253 
13254       Constr := Build_Discriminant_Constraints (T, S);
13255 
13256       --  If the list returned was empty we had an error in building the
13257       --  discriminant constraint. We have also already signalled an error
13258       --  in the incomplete type case
13259 
13260       if Is_Empty_Elmt_List (Constr) then
13261          Fixup_Bad_Constraint;
13262          return;
13263       end if;
13264 
13265       Build_Discriminated_Subtype (T, Def_Id, Constr, Related_Nod, For_Access);
13266    end Constrain_Discriminated_Type;
13267 
13268    ---------------------------
13269    -- Constrain_Enumeration --
13270    ---------------------------
13271 
13272    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
13273       T : constant Entity_Id := Entity (Subtype_Mark (S));
13274       C : constant Node_Id   := Constraint (S);
13275 
13276    begin
13277       Set_Ekind (Def_Id, E_Enumeration_Subtype);
13278 
13279       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
13280 
13281       Set_Etype             (Def_Id, Base_Type         (T));
13282       Set_Size_Info         (Def_Id,                   (T));
13283       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
13284       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
13285 
13286       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13287 
13288       Set_Discrete_RM_Size (Def_Id);
13289    end Constrain_Enumeration;
13290 
13291    ----------------------
13292    -- Constrain_Float --
13293    ----------------------
13294 
13295    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
13296       T    : constant Entity_Id := Entity (Subtype_Mark (S));
13297       C    : Node_Id;
13298       D    : Node_Id;
13299       Rais : Node_Id;
13300 
13301    begin
13302       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
13303 
13304       Set_Etype          (Def_Id, Base_Type      (T));
13305       Set_Size_Info      (Def_Id,                (T));
13306       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
13307 
13308       --  Process the constraint
13309 
13310       C := Constraint (S);
13311 
13312       --  Digits constraint present
13313 
13314       if Nkind (C) = N_Digits_Constraint then
13315 
13316          Check_SPARK_05_Restriction ("digits constraint is not allowed", S);
13317          Check_Restriction (No_Obsolescent_Features, C);
13318 
13319          if Warn_On_Obsolescent_Feature then
13320             Error_Msg_N
13321               ("subtype digits constraint is an " &
13322                "obsolescent feature (RM J.3(8))?j?", C);
13323          end if;
13324 
13325          D := Digits_Expression (C);
13326          Analyze_And_Resolve (D, Any_Integer);
13327          Check_Digits_Expression (D);
13328          Set_Digits_Value (Def_Id, Expr_Value (D));
13329 
13330          --  Check that digits value is in range. Obviously we can do this
13331          --  at compile time, but it is strictly a runtime check, and of
13332          --  course there is an ACVC test that checks this.
13333 
13334          if Digits_Value (Def_Id) > Digits_Value (T) then
13335             Error_Msg_Uint_1 := Digits_Value (T);
13336             Error_Msg_N ("??digits value is too large, maximum is ^", D);
13337             Rais :=
13338               Make_Raise_Constraint_Error (Sloc (D),
13339                 Reason => CE_Range_Check_Failed);
13340             Insert_Action (Declaration_Node (Def_Id), Rais);
13341          end if;
13342 
13343          C := Range_Constraint (C);
13344 
13345       --  No digits constraint present
13346 
13347       else
13348          Set_Digits_Value (Def_Id, Digits_Value (T));
13349       end if;
13350 
13351       --  Range constraint present
13352 
13353       if Nkind (C) = N_Range_Constraint then
13354          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13355 
13356       --  No range constraint present
13357 
13358       else
13359          pragma Assert (No (C));
13360          Set_Scalar_Range (Def_Id, Scalar_Range (T));
13361       end if;
13362 
13363       Set_Is_Constrained (Def_Id);
13364    end Constrain_Float;
13365 
13366    ---------------------
13367    -- Constrain_Index --
13368    ---------------------
13369 
13370    procedure Constrain_Index
13371      (Index        : Node_Id;
13372       S            : Node_Id;
13373       Related_Nod  : Node_Id;
13374       Related_Id   : Entity_Id;
13375       Suffix       : Character;
13376       Suffix_Index : Nat)
13377    is
13378       Def_Id : Entity_Id;
13379       R      : Node_Id := Empty;
13380       T      : constant Entity_Id := Etype (Index);
13381 
13382    begin
13383       Def_Id :=
13384         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
13385       Set_Etype (Def_Id, Base_Type (T));
13386 
13387       if Nkind (S) = N_Range
13388         or else
13389           (Nkind (S) = N_Attribute_Reference
13390             and then Attribute_Name (S) = Name_Range)
13391       then
13392          --  A Range attribute will be transformed into N_Range by Resolve
13393 
13394          Analyze (S);
13395          Set_Etype (S, T);
13396          R := S;
13397 
13398          Process_Range_Expr_In_Decl (R, T);
13399 
13400          if not Error_Posted (S)
13401            and then
13402              (Nkind (S) /= N_Range
13403                or else not Covers (T, (Etype (Low_Bound (S))))
13404                or else not Covers (T, (Etype (High_Bound (S)))))
13405          then
13406             if Base_Type (T) /= Any_Type
13407               and then Etype (Low_Bound (S)) /= Any_Type
13408               and then Etype (High_Bound (S)) /= Any_Type
13409             then
13410                Error_Msg_N ("range expected", S);
13411             end if;
13412          end if;
13413 
13414       elsif Nkind (S) = N_Subtype_Indication then
13415 
13416          --  The parser has verified that this is a discrete indication
13417 
13418          Resolve_Discrete_Subtype_Indication (S, T);
13419          Bad_Predicated_Subtype_Use
13420            ("subtype& has predicate, not allowed in index constraint",
13421             S, Entity (Subtype_Mark (S)));
13422 
13423          R := Range_Expression (Constraint (S));
13424 
13425          --  Capture values of bounds and generate temporaries for them if
13426          --  needed, since checks may cause duplication of the expressions
13427          --  which must not be reevaluated.
13428 
13429          --  The forced evaluation removes side effects from expressions, which
13430          --  should occur also in GNATprove mode. Otherwise, we end up with
13431          --  unexpected insertions of actions at places where this is not
13432          --  supposed to occur, e.g. on default parameters of a call.
13433 
13434          if Expander_Active or GNATprove_Mode then
13435             Force_Evaluation
13436               (Low_Bound (R),  Related_Id => Def_Id, Is_Low_Bound  => True);
13437             Force_Evaluation
13438               (High_Bound (R), Related_Id => Def_Id, Is_High_Bound => True);
13439          end if;
13440 
13441       elsif Nkind (S) = N_Discriminant_Association then
13442 
13443          --  Syntactically valid in subtype indication
13444 
13445          Error_Msg_N ("invalid index constraint", S);
13446          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
13447          return;
13448 
13449       --  Subtype_Mark case, no anonymous subtypes to construct
13450 
13451       else
13452          Analyze (S);
13453 
13454          if Is_Entity_Name (S) then
13455             if not Is_Type (Entity (S)) then
13456                Error_Msg_N ("expect subtype mark for index constraint", S);
13457 
13458             elsif Base_Type (Entity (S)) /= Base_Type (T) then
13459                Wrong_Type (S, Base_Type (T));
13460 
13461             --  Check error of subtype with predicate in index constraint
13462 
13463             else
13464                Bad_Predicated_Subtype_Use
13465                  ("subtype& has predicate, not allowed in index constraint",
13466                   S, Entity (S));
13467             end if;
13468 
13469             return;
13470 
13471          else
13472             Error_Msg_N ("invalid index constraint", S);
13473             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
13474             return;
13475          end if;
13476       end if;
13477 
13478       --  Complete construction of the Itype
13479 
13480       if Is_Modular_Integer_Type (T) then
13481          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
13482 
13483       elsif Is_Integer_Type (T) then
13484          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
13485 
13486       else
13487          Set_Ekind (Def_Id, E_Enumeration_Subtype);
13488          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
13489          Set_First_Literal     (Def_Id, First_Literal (T));
13490       end if;
13491 
13492       Set_Size_Info      (Def_Id,                (T));
13493       Set_RM_Size        (Def_Id, RM_Size        (T));
13494       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
13495 
13496       Set_Scalar_Range   (Def_Id, R);
13497 
13498       Set_Etype (S, Def_Id);
13499       Set_Discrete_RM_Size (Def_Id);
13500    end Constrain_Index;
13501 
13502    -----------------------
13503    -- Constrain_Integer --
13504    -----------------------
13505 
13506    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
13507       T : constant Entity_Id := Entity (Subtype_Mark (S));
13508       C : constant Node_Id   := Constraint (S);
13509 
13510    begin
13511       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13512 
13513       if Is_Modular_Integer_Type (T) then
13514          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
13515       else
13516          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
13517       end if;
13518 
13519       Set_Etype            (Def_Id, Base_Type      (T));
13520       Set_Size_Info        (Def_Id,                (T));
13521       Set_First_Rep_Item   (Def_Id, First_Rep_Item (T));
13522       Set_Discrete_RM_Size (Def_Id);
13523    end Constrain_Integer;
13524 
13525    ------------------------------
13526    -- Constrain_Ordinary_Fixed --
13527    ------------------------------
13528 
13529    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
13530       T    : constant Entity_Id := Entity (Subtype_Mark (S));
13531       C    : Node_Id;
13532       D    : Node_Id;
13533       Rais : Node_Id;
13534 
13535    begin
13536       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
13537       Set_Etype          (Def_Id, Base_Type      (T));
13538       Set_Size_Info      (Def_Id,                (T));
13539       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
13540       Set_Small_Value    (Def_Id, Small_Value    (T));
13541 
13542       --  Process the constraint
13543 
13544       C := Constraint (S);
13545 
13546       --  Delta constraint present
13547 
13548       if Nkind (C) = N_Delta_Constraint then
13549 
13550          Check_SPARK_05_Restriction ("delta constraint is not allowed", S);
13551          Check_Restriction (No_Obsolescent_Features, C);
13552 
13553          if Warn_On_Obsolescent_Feature then
13554             Error_Msg_S
13555               ("subtype delta constraint is an " &
13556                "obsolescent feature (RM J.3(7))?j?");
13557          end if;
13558 
13559          D := Delta_Expression (C);
13560          Analyze_And_Resolve (D, Any_Real);
13561          Check_Delta_Expression (D);
13562          Set_Delta_Value (Def_Id, Expr_Value_R (D));
13563 
13564          --  Check that delta value is in range. Obviously we can do this
13565          --  at compile time, but it is strictly a runtime check, and of
13566          --  course there is an ACVC test that checks this.
13567 
13568          if Delta_Value (Def_Id) < Delta_Value (T) then
13569             Error_Msg_N ("??delta value is too small", D);
13570             Rais :=
13571               Make_Raise_Constraint_Error (Sloc (D),
13572                 Reason => CE_Range_Check_Failed);
13573             Insert_Action (Declaration_Node (Def_Id), Rais);
13574          end if;
13575 
13576          C := Range_Constraint (C);
13577 
13578       --  No delta constraint present
13579 
13580       else
13581          Set_Delta_Value (Def_Id, Delta_Value (T));
13582       end if;
13583 
13584       --  Range constraint present
13585 
13586       if Nkind (C) = N_Range_Constraint then
13587          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
13588 
13589       --  No range constraint present
13590 
13591       else
13592          pragma Assert (No (C));
13593          Set_Scalar_Range (Def_Id, Scalar_Range (T));
13594       end if;
13595 
13596       Set_Discrete_RM_Size (Def_Id);
13597 
13598       --  Unconditionally delay the freeze, since we cannot set size
13599       --  information in all cases correctly until the freeze point.
13600 
13601       Set_Has_Delayed_Freeze (Def_Id);
13602    end Constrain_Ordinary_Fixed;
13603 
13604    -----------------------
13605    -- Contain_Interface --
13606    -----------------------
13607 
13608    function Contain_Interface
13609      (Iface  : Entity_Id;
13610       Ifaces : Elist_Id) return Boolean
13611    is
13612       Iface_Elmt : Elmt_Id;
13613 
13614    begin
13615       if Present (Ifaces) then
13616          Iface_Elmt := First_Elmt (Ifaces);
13617          while Present (Iface_Elmt) loop
13618             if Node (Iface_Elmt) = Iface then
13619                return True;
13620             end if;
13621 
13622             Next_Elmt (Iface_Elmt);
13623          end loop;
13624       end if;
13625 
13626       return False;
13627    end Contain_Interface;
13628 
13629    ---------------------------
13630    -- Convert_Scalar_Bounds --
13631    ---------------------------
13632 
13633    procedure Convert_Scalar_Bounds
13634      (N            : Node_Id;
13635       Parent_Type  : Entity_Id;
13636       Derived_Type : Entity_Id;
13637       Loc          : Source_Ptr)
13638    is
13639       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
13640 
13641       Lo  : Node_Id;
13642       Hi  : Node_Id;
13643       Rng : Node_Id;
13644 
13645    begin
13646       --  Defend against previous errors
13647 
13648       if No (Scalar_Range (Derived_Type)) then
13649          Check_Error_Detected;
13650          return;
13651       end if;
13652 
13653       Lo := Build_Scalar_Bound
13654               (Type_Low_Bound (Derived_Type),
13655                Parent_Type, Implicit_Base);
13656 
13657       Hi := Build_Scalar_Bound
13658               (Type_High_Bound (Derived_Type),
13659                Parent_Type, Implicit_Base);
13660 
13661       Rng :=
13662         Make_Range (Loc,
13663           Low_Bound  => Lo,
13664           High_Bound => Hi);
13665 
13666       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
13667 
13668       Set_Parent (Rng, N);
13669       Set_Scalar_Range (Derived_Type, Rng);
13670 
13671       --  Analyze the bounds
13672 
13673       Analyze_And_Resolve (Lo, Implicit_Base);
13674       Analyze_And_Resolve (Hi, Implicit_Base);
13675 
13676       --  Analyze the range itself, except that we do not analyze it if
13677       --  the bounds are real literals, and we have a fixed-point type.
13678       --  The reason for this is that we delay setting the bounds in this
13679       --  case till we know the final Small and Size values (see circuit
13680       --  in Freeze.Freeze_Fixed_Point_Type for further details).
13681 
13682       if Is_Fixed_Point_Type (Parent_Type)
13683         and then Nkind (Lo) = N_Real_Literal
13684         and then Nkind (Hi) = N_Real_Literal
13685       then
13686          return;
13687 
13688       --  Here we do the analysis of the range
13689 
13690       --  Note: we do this manually, since if we do a normal Analyze and
13691       --  Resolve call, there are problems with the conversions used for
13692       --  the derived type range.
13693 
13694       else
13695          Set_Etype    (Rng, Implicit_Base);
13696          Set_Analyzed (Rng, True);
13697       end if;
13698    end Convert_Scalar_Bounds;
13699 
13700    -------------------
13701    -- Copy_And_Swap --
13702    -------------------
13703 
13704    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
13705    begin
13706       --  Initialize new full declaration entity by copying the pertinent
13707       --  fields of the corresponding private declaration entity.
13708 
13709       --  We temporarily set Ekind to a value appropriate for a type to
13710       --  avoid assert failures in Einfo from checking for setting type
13711       --  attributes on something that is not a type. Ekind (Priv) is an
13712       --  appropriate choice, since it allowed the attributes to be set
13713       --  in the first place. This Ekind value will be modified later.
13714 
13715       Set_Ekind (Full, Ekind (Priv));
13716 
13717       --  Also set Etype temporarily to Any_Type, again, in the absence
13718       --  of errors, it will be properly reset, and if there are errors,
13719       --  then we want a value of Any_Type to remain.
13720 
13721       Set_Etype (Full, Any_Type);
13722 
13723       --  Now start copying attributes
13724 
13725       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
13726 
13727       if Has_Discriminants (Full) then
13728          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
13729          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
13730       end if;
13731 
13732       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
13733       Set_Homonym                    (Full, Homonym                 (Priv));
13734       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
13735       Set_Is_Public                  (Full, Is_Public               (Priv));
13736       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
13737       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
13738       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
13739       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
13740       Set_Has_Pragma_Unreferenced_Objects
13741                                      (Full, Has_Pragma_Unreferenced_Objects
13742                                                                     (Priv));
13743 
13744       Conditional_Delay              (Full,                          Priv);
13745 
13746       if Is_Tagged_Type (Full) then
13747          Set_Direct_Primitive_Operations
13748            (Full, Direct_Primitive_Operations (Priv));
13749          Set_No_Tagged_Streams_Pragma
13750            (Full, No_Tagged_Streams_Pragma (Priv));
13751 
13752          if Is_Base_Type (Priv) then
13753             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
13754          end if;
13755       end if;
13756 
13757       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
13758       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
13759       Set_Scope                      (Full, Scope                   (Priv));
13760       Set_Next_Entity                (Full, Next_Entity             (Priv));
13761       Set_First_Entity               (Full, First_Entity            (Priv));
13762       Set_Last_Entity                (Full, Last_Entity             (Priv));
13763 
13764       --  If access types have been recorded for later handling, keep them in
13765       --  the full view so that they get handled when the full view freeze
13766       --  node is expanded.
13767 
13768       if Present (Freeze_Node (Priv))
13769         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
13770       then
13771          Ensure_Freeze_Node (Full);
13772          Set_Access_Types_To_Process
13773            (Freeze_Node (Full),
13774             Access_Types_To_Process (Freeze_Node (Priv)));
13775       end if;
13776 
13777       --  Swap the two entities. Now Private is the full type entity and Full
13778       --  is the private one. They will be swapped back at the end of the
13779       --  private part. This swapping ensures that the entity that is visible
13780       --  in the private part is the full declaration.
13781 
13782       Exchange_Entities (Priv, Full);
13783       Append_Entity (Full, Scope (Full));
13784    end Copy_And_Swap;
13785 
13786    -------------------------------------
13787    -- Copy_Array_Base_Type_Attributes --
13788    -------------------------------------
13789 
13790    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
13791    begin
13792       Set_Component_Alignment      (T1, Component_Alignment      (T2));
13793       Set_Component_Type           (T1, Component_Type           (T2));
13794       Set_Component_Size           (T1, Component_Size           (T2));
13795       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
13796       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
13797       Propagate_Concurrent_Flags   (T1, T2);
13798       Set_Is_Packed                (T1, Is_Packed                (T2));
13799       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
13800       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
13801       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
13802    end Copy_Array_Base_Type_Attributes;
13803 
13804    -----------------------------------
13805    -- Copy_Array_Subtype_Attributes --
13806    -----------------------------------
13807 
13808    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
13809    begin
13810       Set_Size_Info (T1, T2);
13811 
13812       Set_First_Index            (T1, First_Index            (T2));
13813       Set_Is_Aliased             (T1, Is_Aliased             (T2));
13814       Set_Is_Volatile            (T1, Is_Volatile            (T2));
13815       Set_Treat_As_Volatile      (T1, Treat_As_Volatile      (T2));
13816       Set_Is_Constrained         (T1, Is_Constrained         (T2));
13817       Set_Depends_On_Private     (T1, Has_Private_Component  (T2));
13818       Inherit_Rep_Item_Chain     (T1,                         T2);
13819       Set_Convention             (T1, Convention             (T2));
13820       Set_Is_Limited_Composite   (T1, Is_Limited_Composite   (T2));
13821       Set_Is_Private_Composite   (T1, Is_Private_Composite   (T2));
13822       Set_Packed_Array_Impl_Type (T1, Packed_Array_Impl_Type (T2));
13823    end Copy_Array_Subtype_Attributes;
13824 
13825    -----------------------------------
13826    -- Create_Constrained_Components --
13827    -----------------------------------
13828 
13829    procedure Create_Constrained_Components
13830      (Subt        : Entity_Id;
13831       Decl_Node   : Node_Id;
13832       Typ         : Entity_Id;
13833       Constraints : Elist_Id)
13834    is
13835       Loc         : constant Source_Ptr := Sloc (Subt);
13836       Comp_List   : constant Elist_Id   := New_Elmt_List;
13837       Parent_Type : constant Entity_Id  := Etype (Typ);
13838       Assoc_List  : constant List_Id    := New_List;
13839       Discr_Val   : Elmt_Id;
13840       Errors      : Boolean;
13841       New_C       : Entity_Id;
13842       Old_C       : Entity_Id;
13843       Is_Static   : Boolean := True;
13844 
13845       procedure Collect_Fixed_Components (Typ : Entity_Id);
13846       --  Collect parent type components that do not appear in a variant part
13847 
13848       procedure Create_All_Components;
13849       --  Iterate over Comp_List to create the components of the subtype
13850 
13851       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
13852       --  Creates a new component from Old_Compon, copying all the fields from
13853       --  it, including its Etype, inserts the new component in the Subt entity
13854       --  chain and returns the new component.
13855 
13856       function Is_Variant_Record (T : Entity_Id) return Boolean;
13857       --  If true, and discriminants are static, collect only components from
13858       --  variants selected by discriminant values.
13859 
13860       ------------------------------
13861       -- Collect_Fixed_Components --
13862       ------------------------------
13863 
13864       procedure Collect_Fixed_Components (Typ : Entity_Id) is
13865       begin
13866       --  Build association list for discriminants, and find components of the
13867       --  variant part selected by the values of the discriminants.
13868 
13869          Old_C := First_Discriminant (Typ);
13870          Discr_Val := First_Elmt (Constraints);
13871          while Present (Old_C) loop
13872             Append_To (Assoc_List,
13873               Make_Component_Association (Loc,
13874                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
13875                  Expression => New_Copy (Node (Discr_Val))));
13876 
13877             Next_Elmt (Discr_Val);
13878             Next_Discriminant (Old_C);
13879          end loop;
13880 
13881          --  The tag and the possible parent component are unconditionally in
13882          --  the subtype.
13883 
13884          if Is_Tagged_Type (Typ) or else Has_Controlled_Component (Typ) then
13885             Old_C := First_Component (Typ);
13886             while Present (Old_C) loop
13887                if Nam_In (Chars (Old_C), Name_uTag, Name_uParent) then
13888                   Append_Elmt (Old_C, Comp_List);
13889                end if;
13890 
13891                Next_Component (Old_C);
13892             end loop;
13893          end if;
13894       end Collect_Fixed_Components;
13895 
13896       ---------------------------
13897       -- Create_All_Components --
13898       ---------------------------
13899 
13900       procedure Create_All_Components is
13901          Comp : Elmt_Id;
13902 
13903       begin
13904          Comp := First_Elmt (Comp_List);
13905          while Present (Comp) loop
13906             Old_C := Node (Comp);
13907             New_C := Create_Component (Old_C);
13908 
13909             Set_Etype
13910               (New_C,
13911                Constrain_Component_Type
13912                  (Old_C, Subt, Decl_Node, Typ, Constraints));
13913             Set_Is_Public (New_C, Is_Public (Subt));
13914 
13915             Next_Elmt (Comp);
13916          end loop;
13917       end Create_All_Components;
13918 
13919       ----------------------
13920       -- Create_Component --
13921       ----------------------
13922 
13923       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
13924          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
13925 
13926       begin
13927          if Ekind (Old_Compon) = E_Discriminant
13928            and then Is_Completely_Hidden (Old_Compon)
13929          then
13930             --  This is a shadow discriminant created for a discriminant of
13931             --  the parent type, which needs to be present in the subtype.
13932             --  Give the shadow discriminant an internal name that cannot
13933             --  conflict with that of visible components.
13934 
13935             Set_Chars (New_Compon, New_Internal_Name ('C'));
13936          end if;
13937 
13938          --  Set the parent so we have a proper link for freezing etc. This is
13939          --  not a real parent pointer, since of course our parent does not own
13940          --  up to us and reference us, we are an illegitimate child of the
13941          --  original parent.
13942 
13943          Set_Parent (New_Compon, Parent (Old_Compon));
13944 
13945          --  If the old component's Esize was already determined and is a
13946          --  static value, then the new component simply inherits it. Otherwise
13947          --  the old component's size may require run-time determination, but
13948          --  the new component's size still might be statically determinable
13949          --  (if, for example it has a static constraint). In that case we want
13950          --  Layout_Type to recompute the component's size, so we reset its
13951          --  size and positional fields.
13952 
13953          if Frontend_Layout_On_Target
13954            and then not Known_Static_Esize (Old_Compon)
13955          then
13956             Set_Esize (New_Compon, Uint_0);
13957             Init_Normalized_First_Bit    (New_Compon);
13958             Init_Normalized_Position     (New_Compon);
13959             Init_Normalized_Position_Max (New_Compon);
13960          end if;
13961 
13962          --  We do not want this node marked as Comes_From_Source, since
13963          --  otherwise it would get first class status and a separate cross-
13964          --  reference line would be generated. Illegitimate children do not
13965          --  rate such recognition.
13966 
13967          Set_Comes_From_Source (New_Compon, False);
13968 
13969          --  But it is a real entity, and a birth certificate must be properly
13970          --  registered by entering it into the entity list.
13971 
13972          Enter_Name (New_Compon);
13973 
13974          return New_Compon;
13975       end Create_Component;
13976 
13977       -----------------------
13978       -- Is_Variant_Record --
13979       -----------------------
13980 
13981       function Is_Variant_Record (T : Entity_Id) return Boolean is
13982       begin
13983          return Nkind (Parent (T)) = N_Full_Type_Declaration
13984            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
13985            and then Present (Component_List (Type_Definition (Parent (T))))
13986            and then
13987              Present
13988                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
13989       end Is_Variant_Record;
13990 
13991    --  Start of processing for Create_Constrained_Components
13992 
13993    begin
13994       pragma Assert (Subt /= Base_Type (Subt));
13995       pragma Assert (Typ = Base_Type (Typ));
13996 
13997       Set_First_Entity (Subt, Empty);
13998       Set_Last_Entity  (Subt, Empty);
13999 
14000       --  Check whether constraint is fully static, in which case we can
14001       --  optimize the list of components.
14002 
14003       Discr_Val := First_Elmt (Constraints);
14004       while Present (Discr_Val) loop
14005          if not Is_OK_Static_Expression (Node (Discr_Val)) then
14006             Is_Static := False;
14007             exit;
14008          end if;
14009 
14010          Next_Elmt (Discr_Val);
14011       end loop;
14012 
14013       Set_Has_Static_Discriminants (Subt, Is_Static);
14014 
14015       Push_Scope (Subt);
14016 
14017       --  Inherit the discriminants of the parent type
14018 
14019       Add_Discriminants : declare
14020          Num_Disc : Nat;
14021          Num_Gird : Nat;
14022 
14023       begin
14024          Num_Disc := 0;
14025          Old_C := First_Discriminant (Typ);
14026 
14027          while Present (Old_C) loop
14028             Num_Disc := Num_Disc + 1;
14029             New_C := Create_Component (Old_C);
14030             Set_Is_Public (New_C, Is_Public (Subt));
14031             Next_Discriminant (Old_C);
14032          end loop;
14033 
14034          --  For an untagged derived subtype, the number of discriminants may
14035          --  be smaller than the number of inherited discriminants, because
14036          --  several of them may be renamed by a single new discriminant or
14037          --  constrained. In this case, add the hidden discriminants back into
14038          --  the subtype, because they need to be present if the optimizer of
14039          --  the GCC 4.x back-end decides to break apart assignments between
14040          --  objects using the parent view into member-wise assignments.
14041 
14042          Num_Gird := 0;
14043 
14044          if Is_Derived_Type (Typ)
14045            and then not Is_Tagged_Type (Typ)
14046          then
14047             Old_C := First_Stored_Discriminant (Typ);
14048 
14049             while Present (Old_C) loop
14050                Num_Gird := Num_Gird + 1;
14051                Next_Stored_Discriminant (Old_C);
14052             end loop;
14053          end if;
14054 
14055          if Num_Gird > Num_Disc then
14056 
14057             --  Find out multiple uses of new discriminants, and add hidden
14058             --  components for the extra renamed discriminants. We recognize
14059             --  multiple uses through the Corresponding_Discriminant of a
14060             --  new discriminant: if it constrains several old discriminants,
14061             --  this field points to the last one in the parent type. The
14062             --  stored discriminants of the derived type have the same name
14063             --  as those of the parent.
14064 
14065             declare
14066                Constr    : Elmt_Id;
14067                New_Discr : Entity_Id;
14068                Old_Discr : Entity_Id;
14069 
14070             begin
14071                Constr    := First_Elmt (Stored_Constraint (Typ));
14072                Old_Discr := First_Stored_Discriminant (Typ);
14073                while Present (Constr) loop
14074                   if Is_Entity_Name (Node (Constr))
14075                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
14076                   then
14077                      New_Discr := Entity (Node (Constr));
14078 
14079                      if Chars (Corresponding_Discriminant (New_Discr)) /=
14080                         Chars (Old_Discr)
14081                      then
14082                         --  The new discriminant has been used to rename a
14083                         --  subsequent old discriminant. Introduce a shadow
14084                         --  component for the current old discriminant.
14085 
14086                         New_C := Create_Component (Old_Discr);
14087                         Set_Original_Record_Component (New_C, Old_Discr);
14088                      end if;
14089 
14090                   else
14091                      --  The constraint has eliminated the old discriminant.
14092                      --  Introduce a shadow component.
14093 
14094                      New_C := Create_Component (Old_Discr);
14095                      Set_Original_Record_Component (New_C, Old_Discr);
14096                   end if;
14097 
14098                   Next_Elmt (Constr);
14099                   Next_Stored_Discriminant (Old_Discr);
14100                end loop;
14101             end;
14102          end if;
14103       end Add_Discriminants;
14104 
14105       if Is_Static
14106         and then Is_Variant_Record (Typ)
14107       then
14108          Collect_Fixed_Components (Typ);
14109 
14110          Gather_Components (
14111            Typ,
14112            Component_List (Type_Definition (Parent (Typ))),
14113            Governed_By   => Assoc_List,
14114            Into          => Comp_List,
14115            Report_Errors => Errors);
14116          pragma Assert (not Errors);
14117 
14118          Create_All_Components;
14119 
14120       --  If the subtype declaration is created for a tagged type derivation
14121       --  with constraints, we retrieve the record definition of the parent
14122       --  type to select the components of the proper variant.
14123 
14124       elsif Is_Static
14125         and then Is_Tagged_Type (Typ)
14126         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
14127         and then
14128           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
14129         and then Is_Variant_Record (Parent_Type)
14130       then
14131          Collect_Fixed_Components (Typ);
14132 
14133          Gather_Components
14134            (Typ,
14135             Component_List (Type_Definition (Parent (Parent_Type))),
14136             Governed_By   => Assoc_List,
14137             Into          => Comp_List,
14138             Report_Errors => Errors);
14139 
14140          --  Note: previously there was a check at this point that no errors
14141          --  were detected. As a consequence of AI05-220 there may be an error
14142          --  if an inherited discriminant that controls a variant has a non-
14143          --  static constraint.
14144 
14145          --  If the tagged derivation has a type extension, collect all the
14146          --  new components therein.
14147 
14148          if Present (Record_Extension_Part (Type_Definition (Parent (Typ))))
14149          then
14150             Old_C := First_Component (Typ);
14151             while Present (Old_C) loop
14152                if Original_Record_Component (Old_C) = Old_C
14153                  and then Chars (Old_C) /= Name_uTag
14154                  and then Chars (Old_C) /= Name_uParent
14155                then
14156                   Append_Elmt (Old_C, Comp_List);
14157                end if;
14158 
14159                Next_Component (Old_C);
14160             end loop;
14161          end if;
14162 
14163          Create_All_Components;
14164 
14165       else
14166          --  If discriminants are not static, or if this is a multi-level type
14167          --  extension, we have to include all components of the parent type.
14168 
14169          Old_C := First_Component (Typ);
14170          while Present (Old_C) loop
14171             New_C := Create_Component (Old_C);
14172 
14173             Set_Etype
14174               (New_C,
14175                Constrain_Component_Type
14176                  (Old_C, Subt, Decl_Node, Typ, Constraints));
14177             Set_Is_Public (New_C, Is_Public (Subt));
14178 
14179             Next_Component (Old_C);
14180          end loop;
14181       end if;
14182 
14183       End_Scope;
14184    end Create_Constrained_Components;
14185 
14186    ------------------------------------------
14187    -- Decimal_Fixed_Point_Type_Declaration --
14188    ------------------------------------------
14189 
14190    procedure Decimal_Fixed_Point_Type_Declaration
14191      (T   : Entity_Id;
14192       Def : Node_Id)
14193    is
14194       Loc           : constant Source_Ptr := Sloc (Def);
14195       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
14196       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
14197       Implicit_Base : Entity_Id;
14198       Digs_Val      : Uint;
14199       Delta_Val     : Ureal;
14200       Scale_Val     : Uint;
14201       Bound_Val     : Ureal;
14202 
14203    begin
14204       Check_SPARK_05_Restriction
14205         ("decimal fixed point type is not allowed", Def);
14206       Check_Restriction (No_Fixed_Point, Def);
14207 
14208       --  Create implicit base type
14209 
14210       Implicit_Base :=
14211         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
14212       Set_Etype (Implicit_Base, Implicit_Base);
14213 
14214       --  Analyze and process delta expression
14215 
14216       Analyze_And_Resolve (Delta_Expr, Universal_Real);
14217 
14218       Check_Delta_Expression (Delta_Expr);
14219       Delta_Val := Expr_Value_R (Delta_Expr);
14220 
14221       --  Check delta is power of 10, and determine scale value from it
14222 
14223       declare
14224          Val : Ureal;
14225 
14226       begin
14227          Scale_Val := Uint_0;
14228          Val := Delta_Val;
14229 
14230          if Val < Ureal_1 then
14231             while Val < Ureal_1 loop
14232                Val := Val * Ureal_10;
14233                Scale_Val := Scale_Val + 1;
14234             end loop;
14235 
14236             if Scale_Val > 18 then
14237                Error_Msg_N ("scale exceeds maximum value of 18", Def);
14238                Scale_Val := UI_From_Int (+18);
14239             end if;
14240 
14241          else
14242             while Val > Ureal_1 loop
14243                Val := Val / Ureal_10;
14244                Scale_Val := Scale_Val - 1;
14245             end loop;
14246 
14247             if Scale_Val < -18 then
14248                Error_Msg_N ("scale is less than minimum value of -18", Def);
14249                Scale_Val := UI_From_Int (-18);
14250             end if;
14251          end if;
14252 
14253          if Val /= Ureal_1 then
14254             Error_Msg_N ("delta expression must be a power of 10", Def);
14255             Delta_Val := Ureal_10 ** (-Scale_Val);
14256          end if;
14257       end;
14258 
14259       --  Set delta, scale and small (small = delta for decimal type)
14260 
14261       Set_Delta_Value (Implicit_Base, Delta_Val);
14262       Set_Scale_Value (Implicit_Base, Scale_Val);
14263       Set_Small_Value (Implicit_Base, Delta_Val);
14264 
14265       --  Analyze and process digits expression
14266 
14267       Analyze_And_Resolve (Digs_Expr, Any_Integer);
14268       Check_Digits_Expression (Digs_Expr);
14269       Digs_Val := Expr_Value (Digs_Expr);
14270 
14271       if Digs_Val > 18 then
14272          Digs_Val := UI_From_Int (+18);
14273          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
14274       end if;
14275 
14276       Set_Digits_Value (Implicit_Base, Digs_Val);
14277       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
14278 
14279       --  Set range of base type from digits value for now. This will be
14280       --  expanded to represent the true underlying base range by Freeze.
14281 
14282       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
14283 
14284       --  Note: We leave size as zero for now, size will be set at freeze
14285       --  time. We have to do this for ordinary fixed-point, because the size
14286       --  depends on the specified small, and we might as well do the same for
14287       --  decimal fixed-point.
14288 
14289       pragma Assert (Esize (Implicit_Base) = Uint_0);
14290 
14291       --  If there are bounds given in the declaration use them as the
14292       --  bounds of the first named subtype.
14293 
14294       if Present (Real_Range_Specification (Def)) then
14295          declare
14296             RRS      : constant Node_Id := Real_Range_Specification (Def);
14297             Low      : constant Node_Id := Low_Bound (RRS);
14298             High     : constant Node_Id := High_Bound (RRS);
14299             Low_Val  : Ureal;
14300             High_Val : Ureal;
14301 
14302          begin
14303             Analyze_And_Resolve (Low, Any_Real);
14304             Analyze_And_Resolve (High, Any_Real);
14305             Check_Real_Bound (Low);
14306             Check_Real_Bound (High);
14307             Low_Val := Expr_Value_R (Low);
14308             High_Val := Expr_Value_R (High);
14309 
14310             if Low_Val < (-Bound_Val) then
14311                Error_Msg_N
14312                  ("range low bound too small for digits value", Low);
14313                Low_Val := -Bound_Val;
14314             end if;
14315 
14316             if High_Val > Bound_Val then
14317                Error_Msg_N
14318                  ("range high bound too large for digits value", High);
14319                High_Val := Bound_Val;
14320             end if;
14321 
14322             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
14323          end;
14324 
14325       --  If no explicit range, use range that corresponds to given
14326       --  digits value. This will end up as the final range for the
14327       --  first subtype.
14328 
14329       else
14330          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
14331       end if;
14332 
14333       --  Complete entity for first subtype. The inheritance of the rep item
14334       --  chain ensures that SPARK-related pragmas are not clobbered when the
14335       --  decimal fixed point type acts as a full view of a private type.
14336 
14337       Set_Ekind              (T, E_Decimal_Fixed_Point_Subtype);
14338       Set_Etype              (T, Implicit_Base);
14339       Set_Size_Info          (T, Implicit_Base);
14340       Inherit_Rep_Item_Chain (T, Implicit_Base);
14341       Set_Digits_Value       (T, Digs_Val);
14342       Set_Delta_Value        (T, Delta_Val);
14343       Set_Small_Value        (T, Delta_Val);
14344       Set_Scale_Value        (T, Scale_Val);
14345       Set_Is_Constrained     (T);
14346    end Decimal_Fixed_Point_Type_Declaration;
14347 
14348    -----------------------------------
14349    -- Derive_Progenitor_Subprograms --
14350    -----------------------------------
14351 
14352    procedure Derive_Progenitor_Subprograms
14353      (Parent_Type : Entity_Id;
14354       Tagged_Type : Entity_Id)
14355    is
14356       E          : Entity_Id;
14357       Elmt       : Elmt_Id;
14358       Iface      : Entity_Id;
14359       Iface_Elmt : Elmt_Id;
14360       Iface_Subp : Entity_Id;
14361       New_Subp   : Entity_Id := Empty;
14362       Prim_Elmt  : Elmt_Id;
14363       Subp       : Entity_Id;
14364       Typ        : Entity_Id;
14365 
14366    begin
14367       pragma Assert (Ada_Version >= Ada_2005
14368         and then Is_Record_Type (Tagged_Type)
14369         and then Is_Tagged_Type (Tagged_Type)
14370         and then Has_Interfaces (Tagged_Type));
14371 
14372       --  Step 1: Transfer to the full-view primitives associated with the
14373       --  partial-view that cover interface primitives. Conceptually this
14374       --  work should be done later by Process_Full_View; done here to
14375       --  simplify its implementation at later stages. It can be safely
14376       --  done here because interfaces must be visible in the partial and
14377       --  private view (RM 7.3(7.3/2)).
14378 
14379       --  Small optimization: This work is only required if the parent may
14380       --  have entities whose Alias attribute reference an interface primitive.
14381       --  Such a situation may occur if the parent is an abstract type and the
14382       --  primitive has not been yet overridden or if the parent is a generic
14383       --  formal type covering interfaces.
14384 
14385       --  If the tagged type is not abstract, it cannot have abstract
14386       --  primitives (the only entities in the list of primitives of
14387       --  non-abstract tagged types that can reference abstract primitives
14388       --  through its Alias attribute are the internal entities that have
14389       --  attribute Interface_Alias, and these entities are generated later
14390       --  by Add_Internal_Interface_Entities).
14391 
14392       if In_Private_Part (Current_Scope)
14393         and then (Is_Abstract_Type (Parent_Type)
14394                     or else
14395                   Is_Generic_Type  (Parent_Type))
14396       then
14397          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
14398          while Present (Elmt) loop
14399             Subp := Node (Elmt);
14400 
14401             --  At this stage it is not possible to have entities in the list
14402             --  of primitives that have attribute Interface_Alias.
14403 
14404             pragma Assert (No (Interface_Alias (Subp)));
14405 
14406             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
14407 
14408             if Is_Interface (Typ) then
14409                E := Find_Primitive_Covering_Interface
14410                       (Tagged_Type => Tagged_Type,
14411                        Iface_Prim  => Subp);
14412 
14413                if Present (E)
14414                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
14415                then
14416                   Replace_Elmt (Elmt, E);
14417                   Remove_Homonym (Subp);
14418                end if;
14419             end if;
14420 
14421             Next_Elmt (Elmt);
14422          end loop;
14423       end if;
14424 
14425       --  Step 2: Add primitives of progenitors that are not implemented by
14426       --  parents of Tagged_Type.
14427 
14428       if Present (Interfaces (Base_Type (Tagged_Type))) then
14429          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
14430          while Present (Iface_Elmt) loop
14431             Iface := Node (Iface_Elmt);
14432 
14433             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
14434             while Present (Prim_Elmt) loop
14435                Iface_Subp := Node (Prim_Elmt);
14436 
14437                --  Exclude derivation of predefined primitives except those
14438                --  that come from source, or are inherited from one that comes
14439                --  from source. Required to catch declarations of equality
14440                --  operators of interfaces. For example:
14441 
14442                --     type Iface is interface;
14443                --     function "=" (Left, Right : Iface) return Boolean;
14444 
14445                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
14446                  or else Comes_From_Source (Ultimate_Alias (Iface_Subp))
14447                then
14448                   E := Find_Primitive_Covering_Interface
14449                          (Tagged_Type => Tagged_Type,
14450                           Iface_Prim  => Iface_Subp);
14451 
14452                   --  If not found we derive a new primitive leaving its alias
14453                   --  attribute referencing the interface primitive.
14454 
14455                   if No (E) then
14456                      Derive_Subprogram
14457                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
14458 
14459                   --  Ada 2012 (AI05-0197): If the covering primitive's name
14460                   --  differs from the name of the interface primitive then it
14461                   --  is a private primitive inherited from a parent type. In
14462                   --  such case, given that Tagged_Type covers the interface,
14463                   --  the inherited private primitive becomes visible. For such
14464                   --  purpose we add a new entity that renames the inherited
14465                   --  private primitive.
14466 
14467                   elsif Chars (E) /= Chars (Iface_Subp) then
14468                      pragma Assert (Has_Suffix (E, 'P'));
14469                      Derive_Subprogram
14470                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
14471                      Set_Alias (New_Subp, E);
14472                      Set_Is_Abstract_Subprogram (New_Subp,
14473                        Is_Abstract_Subprogram (E));
14474 
14475                   --  Propagate to the full view interface entities associated
14476                   --  with the partial view.
14477 
14478                   elsif In_Private_Part (Current_Scope)
14479                     and then Present (Alias (E))
14480                     and then Alias (E) = Iface_Subp
14481                     and then
14482                       List_Containing (Parent (E)) /=
14483                         Private_Declarations
14484                           (Specification
14485                             (Unit_Declaration_Node (Current_Scope)))
14486                   then
14487                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
14488                   end if;
14489                end if;
14490 
14491                Next_Elmt (Prim_Elmt);
14492             end loop;
14493 
14494             Next_Elmt (Iface_Elmt);
14495          end loop;
14496       end if;
14497    end Derive_Progenitor_Subprograms;
14498 
14499    -----------------------
14500    -- Derive_Subprogram --
14501    -----------------------
14502 
14503    procedure Derive_Subprogram
14504      (New_Subp     : out Entity_Id;
14505       Parent_Subp  : Entity_Id;
14506       Derived_Type : Entity_Id;
14507       Parent_Type  : Entity_Id;
14508       Actual_Subp  : Entity_Id := Empty)
14509    is
14510       Formal : Entity_Id;
14511       --  Formal parameter of parent primitive operation
14512 
14513       Formal_Of_Actual : Entity_Id;
14514       --  Formal parameter of actual operation, when the derivation is to
14515       --  create a renaming for a primitive operation of an actual in an
14516       --  instantiation.
14517 
14518       New_Formal : Entity_Id;
14519       --  Formal of inherited operation
14520 
14521       Visible_Subp : Entity_Id := Parent_Subp;
14522 
14523       function Is_Private_Overriding return Boolean;
14524       --  If Subp is a private overriding of a visible operation, the inherited
14525       --  operation derives from the overridden op (even though its body is the
14526       --  overriding one) and the inherited operation is visible now. See
14527       --  sem_disp to see the full details of the handling of the overridden
14528       --  subprogram, which is removed from the list of primitive operations of
14529       --  the type. The overridden subprogram is saved locally in Visible_Subp,
14530       --  and used to diagnose abstract operations that need overriding in the
14531       --  derived type.
14532 
14533       procedure Replace_Type (Id, New_Id : Entity_Id);
14534       --  When the type is an anonymous access type, create a new access type
14535       --  designating the derived type.
14536 
14537       procedure Set_Derived_Name;
14538       --  This procedure sets the appropriate Chars name for New_Subp. This
14539       --  is normally just a copy of the parent name. An exception arises for
14540       --  type support subprograms, where the name is changed to reflect the
14541       --  name of the derived type, e.g. if type foo is derived from type bar,
14542       --  then a procedure barDA is derived with a name fooDA.
14543 
14544       ---------------------------
14545       -- Is_Private_Overriding --
14546       ---------------------------
14547 
14548       function Is_Private_Overriding return Boolean is
14549          Prev : Entity_Id;
14550 
14551       begin
14552          --  If the parent is not a dispatching operation there is no
14553          --  need to investigate overridings
14554 
14555          if not Is_Dispatching_Operation (Parent_Subp) then
14556             return False;
14557          end if;
14558 
14559          --  The visible operation that is overridden is a homonym of the
14560          --  parent subprogram. We scan the homonym chain to find the one
14561          --  whose alias is the subprogram we are deriving.
14562 
14563          Prev := Current_Entity (Parent_Subp);
14564          while Present (Prev) loop
14565             if Ekind (Prev) = Ekind (Parent_Subp)
14566               and then Alias (Prev) = Parent_Subp
14567               and then Scope (Parent_Subp) = Scope (Prev)
14568               and then not Is_Hidden (Prev)
14569             then
14570                Visible_Subp := Prev;
14571                return True;
14572             end if;
14573 
14574             Prev := Homonym (Prev);
14575          end loop;
14576 
14577          return False;
14578       end Is_Private_Overriding;
14579 
14580       ------------------
14581       -- Replace_Type --
14582       ------------------
14583 
14584       procedure Replace_Type (Id, New_Id : Entity_Id) is
14585          Id_Type  : constant Entity_Id := Etype (Id);
14586          Acc_Type : Entity_Id;
14587          Par      : constant Node_Id := Parent (Derived_Type);
14588 
14589       begin
14590          --  When the type is an anonymous access type, create a new access
14591          --  type designating the derived type. This itype must be elaborated
14592          --  at the point of the derivation, not on subsequent calls that may
14593          --  be out of the proper scope for Gigi, so we insert a reference to
14594          --  it after the derivation.
14595 
14596          if Ekind (Id_Type) = E_Anonymous_Access_Type then
14597             declare
14598                Desig_Typ : Entity_Id := Designated_Type (Id_Type);
14599 
14600             begin
14601                if Ekind (Desig_Typ) = E_Record_Type_With_Private
14602                  and then Present (Full_View (Desig_Typ))
14603                  and then not Is_Private_Type (Parent_Type)
14604                then
14605                   Desig_Typ := Full_View (Desig_Typ);
14606                end if;
14607 
14608                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
14609 
14610                   --  Ada 2005 (AI-251): Handle also derivations of abstract
14611                   --  interface primitives.
14612 
14613                  or else (Is_Interface (Desig_Typ)
14614                            and then not Is_Class_Wide_Type (Desig_Typ))
14615                then
14616                   Acc_Type := New_Copy (Id_Type);
14617                   Set_Etype (Acc_Type, Acc_Type);
14618                   Set_Scope (Acc_Type, New_Subp);
14619 
14620                   --  Set size of anonymous access type. If we have an access
14621                   --  to an unconstrained array, this is a fat pointer, so it
14622                   --  is sizes at twice addtress size.
14623 
14624                   if Is_Array_Type (Desig_Typ)
14625                     and then not Is_Constrained (Desig_Typ)
14626                   then
14627                      Init_Size (Acc_Type, 2 * System_Address_Size);
14628 
14629                   --  Other cases use a thin pointer
14630 
14631                   else
14632                      Init_Size (Acc_Type, System_Address_Size);
14633                   end if;
14634 
14635                   --  Set remaining characterstics of anonymous access type
14636 
14637                   Init_Alignment (Acc_Type);
14638                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
14639 
14640                   Set_Etype (New_Id, Acc_Type);
14641                   Set_Scope (New_Id, New_Subp);
14642 
14643                   --  Create a reference to it
14644 
14645                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
14646 
14647                else
14648                   Set_Etype (New_Id, Id_Type);
14649                end if;
14650             end;
14651 
14652          --  In Ada2012, a formal may have an incomplete type but the type
14653          --  derivation that inherits the primitive follows the full view.
14654 
14655          elsif Base_Type (Id_Type) = Base_Type (Parent_Type)
14656            or else
14657              (Ekind (Id_Type) = E_Record_Type_With_Private
14658                and then Present (Full_View (Id_Type))
14659                and then
14660                  Base_Type (Full_View (Id_Type)) = Base_Type (Parent_Type))
14661            or else
14662              (Ada_Version >= Ada_2012
14663                and then Ekind (Id_Type) = E_Incomplete_Type
14664                and then Full_View (Id_Type) = Parent_Type)
14665          then
14666             --  Constraint checks on formals are generated during expansion,
14667             --  based on the signature of the original subprogram. The bounds
14668             --  of the derived type are not relevant, and thus we can use
14669             --  the base type for the formals. However, the return type may be
14670             --  used in a context that requires that the proper static bounds
14671             --  be used (a case statement, for example) and for those cases
14672             --  we must use the derived type (first subtype), not its base.
14673 
14674             --  If the derived_type_definition has no constraints, we know that
14675             --  the derived type has the same constraints as the first subtype
14676             --  of the parent, and we can also use it rather than its base,
14677             --  which can lead to more efficient code.
14678 
14679             if Etype (Id) = Parent_Type then
14680                if Is_Scalar_Type (Parent_Type)
14681                  and then
14682                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
14683                then
14684                   Set_Etype (New_Id, Derived_Type);
14685 
14686                elsif Nkind (Par) = N_Full_Type_Declaration
14687                  and then
14688                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
14689                  and then
14690                    Is_Entity_Name
14691                      (Subtype_Indication (Type_Definition (Par)))
14692                then
14693                   Set_Etype (New_Id, Derived_Type);
14694 
14695                else
14696                   Set_Etype (New_Id, Base_Type (Derived_Type));
14697                end if;
14698 
14699             else
14700                Set_Etype (New_Id, Base_Type (Derived_Type));
14701             end if;
14702 
14703          else
14704             Set_Etype (New_Id, Etype (Id));
14705          end if;
14706       end Replace_Type;
14707 
14708       ----------------------
14709       -- Set_Derived_Name --
14710       ----------------------
14711 
14712       procedure Set_Derived_Name is
14713          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
14714       begin
14715          if Nm = TSS_Null then
14716             Set_Chars (New_Subp, Chars (Parent_Subp));
14717          else
14718             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
14719          end if;
14720       end Set_Derived_Name;
14721 
14722    --  Start of processing for Derive_Subprogram
14723 
14724    begin
14725       New_Subp := New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
14726       Set_Ekind (New_Subp, Ekind (Parent_Subp));
14727 
14728       --  Check whether the inherited subprogram is a private operation that
14729       --  should be inherited but not yet made visible. Such subprograms can
14730       --  become visible at a later point (e.g., the private part of a public
14731       --  child unit) via Declare_Inherited_Private_Subprograms. If the
14732       --  following predicate is true, then this is not such a private
14733       --  operation and the subprogram simply inherits the name of the parent
14734       --  subprogram. Note the special check for the names of controlled
14735       --  operations, which are currently exempted from being inherited with
14736       --  a hidden name because they must be findable for generation of
14737       --  implicit run-time calls.
14738 
14739       if not Is_Hidden (Parent_Subp)
14740         or else Is_Internal (Parent_Subp)
14741         or else Is_Private_Overriding
14742         or else Is_Internal_Name (Chars (Parent_Subp))
14743         or else Nam_In (Chars (Parent_Subp), Name_Initialize,
14744                                              Name_Adjust,
14745                                              Name_Finalize)
14746       then
14747          Set_Derived_Name;
14748 
14749       --  An inherited dispatching equality will be overridden by an internally
14750       --  generated one, or by an explicit one, so preserve its name and thus
14751       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
14752       --  private operation it may become invisible if the full view has
14753       --  progenitors, and the dispatch table will be malformed.
14754       --  We check that the type is limited to handle the anomalous declaration
14755       --  of Limited_Controlled, which is derived from a non-limited type, and
14756       --  which is handled specially elsewhere as well.
14757 
14758       elsif Chars (Parent_Subp) = Name_Op_Eq
14759         and then Is_Dispatching_Operation (Parent_Subp)
14760         and then Etype (Parent_Subp) = Standard_Boolean
14761         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
14762         and then
14763           Etype (First_Formal (Parent_Subp)) =
14764             Etype (Next_Formal (First_Formal (Parent_Subp)))
14765       then
14766          Set_Derived_Name;
14767 
14768       --  If parent is hidden, this can be a regular derivation if the
14769       --  parent is immediately visible in a non-instantiating context,
14770       --  or if we are in the private part of an instance. This test
14771       --  should still be refined ???
14772 
14773       --  The test for In_Instance_Not_Visible avoids inheriting the derived
14774       --  operation as a non-visible operation in cases where the parent
14775       --  subprogram might not be visible now, but was visible within the
14776       --  original generic, so it would be wrong to make the inherited
14777       --  subprogram non-visible now. (Not clear if this test is fully
14778       --  correct; are there any cases where we should declare the inherited
14779       --  operation as not visible to avoid it being overridden, e.g., when
14780       --  the parent type is a generic actual with private primitives ???)
14781 
14782       --  (they should be treated the same as other private inherited
14783       --  subprograms, but it's not clear how to do this cleanly). ???
14784 
14785       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
14786               and then Is_Immediately_Visible (Parent_Subp)
14787               and then not In_Instance)
14788         or else In_Instance_Not_Visible
14789       then
14790          Set_Derived_Name;
14791 
14792       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
14793       --  overrides an interface primitive because interface primitives
14794       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
14795 
14796       elsif Ada_Version >= Ada_2005
14797          and then Is_Dispatching_Operation (Parent_Subp)
14798          and then Covers_Some_Interface (Parent_Subp)
14799       then
14800          Set_Derived_Name;
14801 
14802       --  Otherwise, the type is inheriting a private operation, so enter it
14803       --  with a special name so it can't be overridden.
14804 
14805       else
14806          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
14807       end if;
14808 
14809       Set_Parent (New_Subp, Parent (Derived_Type));
14810 
14811       if Present (Actual_Subp) then
14812          Replace_Type (Actual_Subp, New_Subp);
14813       else
14814          Replace_Type (Parent_Subp, New_Subp);
14815       end if;
14816 
14817       Conditional_Delay (New_Subp, Parent_Subp);
14818 
14819       --  If we are creating a renaming for a primitive operation of an
14820       --  actual of a generic derived type, we must examine the signature
14821       --  of the actual primitive, not that of the generic formal, which for
14822       --  example may be an interface. However the name and initial value
14823       --  of the inherited operation are those of the formal primitive.
14824 
14825       Formal := First_Formal (Parent_Subp);
14826 
14827       if Present (Actual_Subp) then
14828          Formal_Of_Actual := First_Formal (Actual_Subp);
14829       else
14830          Formal_Of_Actual := Empty;
14831       end if;
14832 
14833       while Present (Formal) loop
14834          New_Formal := New_Copy (Formal);
14835 
14836          --  Normally we do not go copying parents, but in the case of
14837          --  formals, we need to link up to the declaration (which is the
14838          --  parameter specification), and it is fine to link up to the
14839          --  original formal's parameter specification in this case.
14840 
14841          Set_Parent (New_Formal, Parent (Formal));
14842          Append_Entity (New_Formal, New_Subp);
14843 
14844          if Present (Formal_Of_Actual) then
14845             Replace_Type (Formal_Of_Actual, New_Formal);
14846             Next_Formal (Formal_Of_Actual);
14847          else
14848             Replace_Type (Formal, New_Formal);
14849          end if;
14850 
14851          Next_Formal (Formal);
14852       end loop;
14853 
14854       --  If this derivation corresponds to a tagged generic actual, then
14855       --  primitive operations rename those of the actual. Otherwise the
14856       --  primitive operations rename those of the parent type, If the parent
14857       --  renames an intrinsic operator, so does the new subprogram. We except
14858       --  concatenation, which is always properly typed, and does not get
14859       --  expanded as other intrinsic operations.
14860 
14861       if No (Actual_Subp) then
14862          if Is_Intrinsic_Subprogram (Parent_Subp) then
14863             Set_Is_Intrinsic_Subprogram (New_Subp);
14864 
14865             if Present (Alias (Parent_Subp))
14866               and then Chars (Parent_Subp) /= Name_Op_Concat
14867             then
14868                Set_Alias (New_Subp, Alias (Parent_Subp));
14869             else
14870                Set_Alias (New_Subp, Parent_Subp);
14871             end if;
14872 
14873          else
14874             Set_Alias (New_Subp, Parent_Subp);
14875          end if;
14876 
14877       else
14878          Set_Alias (New_Subp, Actual_Subp);
14879       end if;
14880 
14881       --  Inherit the "ghostness" from the parent subprogram
14882 
14883       if Is_Ghost_Entity (Alias (New_Subp)) then
14884          Set_Is_Ghost_Entity (New_Subp);
14885       end if;
14886 
14887       --  Derived subprograms of a tagged type must inherit the convention
14888       --  of the parent subprogram (a requirement of AI-117). Derived
14889       --  subprograms of untagged types simply get convention Ada by default.
14890 
14891       --  If the derived type is a tagged generic formal type with unknown
14892       --  discriminants, its convention is intrinsic (RM 6.3.1 (8)).
14893 
14894       --  However, if the type is derived from a generic formal, the further
14895       --  inherited subprogram has the convention of the non-generic ancestor.
14896       --  Otherwise there would be no way to override the operation.
14897       --  (This is subject to forthcoming ARG discussions).
14898 
14899       if Is_Tagged_Type (Derived_Type) then
14900          if Is_Generic_Type (Derived_Type)
14901            and then Has_Unknown_Discriminants (Derived_Type)
14902          then
14903             Set_Convention (New_Subp, Convention_Intrinsic);
14904 
14905          else
14906             if Is_Generic_Type (Parent_Type)
14907               and then Has_Unknown_Discriminants (Parent_Type)
14908             then
14909                Set_Convention (New_Subp, Convention (Alias (Parent_Subp)));
14910             else
14911                Set_Convention (New_Subp, Convention (Parent_Subp));
14912             end if;
14913          end if;
14914       end if;
14915 
14916       --  Predefined controlled operations retain their name even if the parent
14917       --  is hidden (see above), but they are not primitive operations if the
14918       --  ancestor is not visible, for example if the parent is a private
14919       --  extension completed with a controlled extension. Note that a full
14920       --  type that is controlled can break privacy: the flag Is_Controlled is
14921       --  set on both views of the type.
14922 
14923       if Is_Controlled (Parent_Type)
14924         and then Nam_In (Chars (Parent_Subp), Name_Initialize,
14925                                               Name_Adjust,
14926                                               Name_Finalize)
14927         and then Is_Hidden (Parent_Subp)
14928         and then not Is_Visibly_Controlled (Parent_Type)
14929       then
14930          Set_Is_Hidden (New_Subp);
14931       end if;
14932 
14933       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
14934       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
14935 
14936       if Ekind (Parent_Subp) = E_Procedure then
14937          Set_Is_Valued_Procedure
14938            (New_Subp, Is_Valued_Procedure (Parent_Subp));
14939       else
14940          Set_Has_Controlling_Result
14941            (New_Subp, Has_Controlling_Result (Parent_Subp));
14942       end if;
14943 
14944       --  No_Return must be inherited properly. If this is overridden in the
14945       --  case of a dispatching operation, then a check is made in Sem_Disp
14946       --  that the overriding operation is also No_Return (no such check is
14947       --  required for the case of non-dispatching operation.
14948 
14949       Set_No_Return (New_Subp, No_Return (Parent_Subp));
14950 
14951       --  A derived function with a controlling result is abstract. If the
14952       --  Derived_Type is a nonabstract formal generic derived type, then
14953       --  inherited operations are not abstract: the required check is done at
14954       --  instantiation time. If the derivation is for a generic actual, the
14955       --  function is not abstract unless the actual is.
14956 
14957       if Is_Generic_Type (Derived_Type)
14958         and then not Is_Abstract_Type (Derived_Type)
14959       then
14960          null;
14961 
14962       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
14963       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
14964 
14965       --  A subprogram subject to pragma Extensions_Visible with value False
14966       --  requires overriding if the subprogram has at least one controlling
14967       --  OUT parameter (SPARK RM 6.1.7(6)).
14968 
14969       elsif Ada_Version >= Ada_2005
14970         and then (Is_Abstract_Subprogram (Alias (New_Subp))
14971                    or else (Is_Tagged_Type (Derived_Type)
14972                              and then Etype (New_Subp) = Derived_Type
14973                              and then not Is_Null_Extension (Derived_Type))
14974                    or else (Is_Tagged_Type (Derived_Type)
14975                              and then Ekind (Etype (New_Subp)) =
14976                                                        E_Anonymous_Access_Type
14977                              and then Designated_Type (Etype (New_Subp)) =
14978                                                         Derived_Type
14979                              and then not Is_Null_Extension (Derived_Type))
14980                    or else (Comes_From_Source (Alias (New_Subp))
14981                              and then Is_EVF_Procedure (Alias (New_Subp))))
14982         and then No (Actual_Subp)
14983       then
14984          if not Is_Tagged_Type (Derived_Type)
14985            or else Is_Abstract_Type (Derived_Type)
14986            or else Is_Abstract_Subprogram (Alias (New_Subp))
14987          then
14988             Set_Is_Abstract_Subprogram (New_Subp);
14989          else
14990             Set_Requires_Overriding (New_Subp);
14991          end if;
14992 
14993       elsif Ada_Version < Ada_2005
14994         and then (Is_Abstract_Subprogram (Alias (New_Subp))
14995                    or else (Is_Tagged_Type (Derived_Type)
14996                              and then Etype (New_Subp) = Derived_Type
14997                              and then No (Actual_Subp)))
14998       then
14999          Set_Is_Abstract_Subprogram (New_Subp);
15000 
15001       --  AI05-0097 : an inherited operation that dispatches on result is
15002       --  abstract if the derived type is abstract, even if the parent type
15003       --  is concrete and the derived type is a null extension.
15004 
15005       elsif Has_Controlling_Result (Alias (New_Subp))
15006         and then Is_Abstract_Type (Etype (New_Subp))
15007       then
15008          Set_Is_Abstract_Subprogram (New_Subp);
15009 
15010       --  Finally, if the parent type is abstract we must verify that all
15011       --  inherited operations are either non-abstract or overridden, or that
15012       --  the derived type itself is abstract (this check is performed at the
15013       --  end of a package declaration, in Check_Abstract_Overriding). A
15014       --  private overriding in the parent type will not be visible in the
15015       --  derivation if we are not in an inner package or in a child unit of
15016       --  the parent type, in which case the abstractness of the inherited
15017       --  operation is carried to the new subprogram.
15018 
15019       elsif Is_Abstract_Type (Parent_Type)
15020         and then not In_Open_Scopes (Scope (Parent_Type))
15021         and then Is_Private_Overriding
15022         and then Is_Abstract_Subprogram (Visible_Subp)
15023       then
15024          if No (Actual_Subp) then
15025             Set_Alias (New_Subp, Visible_Subp);
15026             Set_Is_Abstract_Subprogram (New_Subp, True);
15027 
15028          else
15029             --  If this is a derivation for an instance of a formal derived
15030             --  type, abstractness comes from the primitive operation of the
15031             --  actual, not from the operation inherited from the ancestor.
15032 
15033             Set_Is_Abstract_Subprogram
15034               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
15035          end if;
15036       end if;
15037 
15038       New_Overloaded_Entity (New_Subp, Derived_Type);
15039 
15040       --  Check for case of a derived subprogram for the instantiation of a
15041       --  formal derived tagged type, if so mark the subprogram as dispatching
15042       --  and inherit the dispatching attributes of the actual subprogram. The
15043       --  derived subprogram is effectively renaming of the actual subprogram,
15044       --  so it needs to have the same attributes as the actual.
15045 
15046       if Present (Actual_Subp)
15047         and then Is_Dispatching_Operation (Actual_Subp)
15048       then
15049          Set_Is_Dispatching_Operation (New_Subp);
15050 
15051          if Present (DTC_Entity (Actual_Subp)) then
15052             Set_DTC_Entity (New_Subp, DTC_Entity (Actual_Subp));
15053             Set_DT_Position_Value (New_Subp, DT_Position (Actual_Subp));
15054          end if;
15055       end if;
15056 
15057       --  Indicate that a derived subprogram does not require a body and that
15058       --  it does not require processing of default expressions.
15059 
15060       Set_Has_Completion (New_Subp);
15061       Set_Default_Expressions_Processed (New_Subp);
15062 
15063       if Ekind (New_Subp) = E_Function then
15064          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
15065       end if;
15066    end Derive_Subprogram;
15067 
15068    ------------------------
15069    -- Derive_Subprograms --
15070    ------------------------
15071 
15072    procedure Derive_Subprograms
15073      (Parent_Type    : Entity_Id;
15074       Derived_Type   : Entity_Id;
15075       Generic_Actual : Entity_Id := Empty)
15076    is
15077       Op_List : constant Elist_Id :=
15078                   Collect_Primitive_Operations (Parent_Type);
15079 
15080       function Check_Derived_Type return Boolean;
15081       --  Check that all the entities derived from Parent_Type are found in
15082       --  the list of primitives of Derived_Type exactly in the same order.
15083 
15084       procedure Derive_Interface_Subprogram
15085         (New_Subp    : out Entity_Id;
15086          Subp        : Entity_Id;
15087          Actual_Subp : Entity_Id);
15088       --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
15089       --  (which is an interface primitive). If Generic_Actual is present then
15090       --  Actual_Subp is the actual subprogram corresponding with the generic
15091       --  subprogram Subp.
15092 
15093       function Check_Derived_Type return Boolean is
15094          E        : Entity_Id;
15095          Elmt     : Elmt_Id;
15096          List     : Elist_Id;
15097          New_Subp : Entity_Id;
15098          Op_Elmt  : Elmt_Id;
15099          Subp     : Entity_Id;
15100 
15101       begin
15102          --  Traverse list of entities in the current scope searching for
15103          --  an incomplete type whose full-view is derived type
15104 
15105          E := First_Entity (Scope (Derived_Type));
15106          while Present (E) and then E /= Derived_Type loop
15107             if Ekind (E) = E_Incomplete_Type
15108               and then Present (Full_View (E))
15109               and then Full_View (E) = Derived_Type
15110             then
15111                --  Disable this test if Derived_Type completes an incomplete
15112                --  type because in such case more primitives can be added
15113                --  later to the list of primitives of Derived_Type by routine
15114                --  Process_Incomplete_Dependents
15115 
15116                return True;
15117             end if;
15118 
15119             E := Next_Entity (E);
15120          end loop;
15121 
15122          List := Collect_Primitive_Operations (Derived_Type);
15123          Elmt := First_Elmt (List);
15124 
15125          Op_Elmt := First_Elmt (Op_List);
15126          while Present (Op_Elmt) loop
15127             Subp     := Node (Op_Elmt);
15128             New_Subp := Node (Elmt);
15129 
15130             --  At this early stage Derived_Type has no entities with attribute
15131             --  Interface_Alias. In addition, such primitives are always
15132             --  located at the end of the list of primitives of Parent_Type.
15133             --  Therefore, if found we can safely stop processing pending
15134             --  entities.
15135 
15136             exit when Present (Interface_Alias (Subp));
15137 
15138             --  Handle hidden entities
15139 
15140             if not Is_Predefined_Dispatching_Operation (Subp)
15141               and then Is_Hidden (Subp)
15142             then
15143                if Present (New_Subp)
15144                  and then Primitive_Names_Match (Subp, New_Subp)
15145                then
15146                   Next_Elmt (Elmt);
15147                end if;
15148 
15149             else
15150                if not Present (New_Subp)
15151                  or else Ekind (Subp) /= Ekind (New_Subp)
15152                  or else not Primitive_Names_Match (Subp, New_Subp)
15153                then
15154                   return False;
15155                end if;
15156 
15157                Next_Elmt (Elmt);
15158             end if;
15159 
15160             Next_Elmt (Op_Elmt);
15161          end loop;
15162 
15163          return True;
15164       end Check_Derived_Type;
15165 
15166       ---------------------------------
15167       -- Derive_Interface_Subprogram --
15168       ---------------------------------
15169 
15170       procedure Derive_Interface_Subprogram
15171         (New_Subp    : out Entity_Id;
15172          Subp        : Entity_Id;
15173          Actual_Subp : Entity_Id)
15174       is
15175          Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
15176          Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
15177 
15178       begin
15179          pragma Assert (Is_Interface (Iface_Type));
15180 
15181          Derive_Subprogram
15182            (New_Subp     => New_Subp,
15183             Parent_Subp  => Iface_Subp,
15184             Derived_Type => Derived_Type,
15185             Parent_Type  => Iface_Type,
15186             Actual_Subp  => Actual_Subp);
15187 
15188          --  Given that this new interface entity corresponds with a primitive
15189          --  of the parent that was not overridden we must leave it associated
15190          --  with its parent primitive to ensure that it will share the same
15191          --  dispatch table slot when overridden. We must set the Alias to Subp
15192          --  (instead of Iface_Subp), and we must fix Is_Abstract_Subprogram
15193          --  (in case we inherited Subp from Iface_Type via a nonabstract
15194          --  generic formal type).
15195 
15196          if No (Actual_Subp) then
15197             Set_Alias (New_Subp, Subp);
15198 
15199             declare
15200                T : Entity_Id := Find_Dispatching_Type (Subp);
15201             begin
15202                while Etype (T) /= T loop
15203                   if Is_Generic_Type (T) and then not Is_Abstract_Type (T) then
15204                      Set_Is_Abstract_Subprogram (New_Subp, False);
15205                      exit;
15206                   end if;
15207 
15208                   T := Etype (T);
15209                end loop;
15210             end;
15211 
15212          --  For instantiations this is not needed since the previous call to
15213          --  Derive_Subprogram leaves the entity well decorated.
15214 
15215          else
15216             pragma Assert (Alias (New_Subp) = Actual_Subp);
15217             null;
15218          end if;
15219       end Derive_Interface_Subprogram;
15220 
15221       --  Local variables
15222 
15223       Alias_Subp   : Entity_Id;
15224       Act_List     : Elist_Id;
15225       Act_Elmt     : Elmt_Id;
15226       Act_Subp     : Entity_Id := Empty;
15227       Elmt         : Elmt_Id;
15228       Need_Search  : Boolean   := False;
15229       New_Subp     : Entity_Id := Empty;
15230       Parent_Base  : Entity_Id;
15231       Subp         : Entity_Id;
15232 
15233    --  Start of processing for Derive_Subprograms
15234 
15235    begin
15236       if Ekind (Parent_Type) = E_Record_Type_With_Private
15237         and then Has_Discriminants (Parent_Type)
15238         and then Present (Full_View (Parent_Type))
15239       then
15240          Parent_Base := Full_View (Parent_Type);
15241       else
15242          Parent_Base := Parent_Type;
15243       end if;
15244 
15245       if Present (Generic_Actual) then
15246          Act_List := Collect_Primitive_Operations (Generic_Actual);
15247          Act_Elmt := First_Elmt (Act_List);
15248       else
15249          Act_List := No_Elist;
15250          Act_Elmt := No_Elmt;
15251       end if;
15252 
15253       --  Derive primitives inherited from the parent. Note that if the generic
15254       --  actual is present, this is not really a type derivation, it is a
15255       --  completion within an instance.
15256 
15257       --  Case 1: Derived_Type does not implement interfaces
15258 
15259       if not Is_Tagged_Type (Derived_Type)
15260         or else (not Has_Interfaces (Derived_Type)
15261                   and then not (Present (Generic_Actual)
15262                                  and then Has_Interfaces (Generic_Actual)))
15263       then
15264          Elmt := First_Elmt (Op_List);
15265          while Present (Elmt) loop
15266             Subp := Node (Elmt);
15267 
15268             --  Literals are derived earlier in the process of building the
15269             --  derived type, and are skipped here.
15270 
15271             if Ekind (Subp) = E_Enumeration_Literal then
15272                null;
15273 
15274             --  The actual is a direct descendant and the common primitive
15275             --  operations appear in the same order.
15276 
15277             --  If the generic parent type is present, the derived type is an
15278             --  instance of a formal derived type, and within the instance its
15279             --  operations are those of the actual. We derive from the formal
15280             --  type but make the inherited operations aliases of the
15281             --  corresponding operations of the actual.
15282 
15283             else
15284                pragma Assert (No (Node (Act_Elmt))
15285                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
15286                            and then
15287                              Type_Conformant
15288                                (Subp, Node (Act_Elmt),
15289                                 Skip_Controlling_Formals => True)));
15290 
15291                Derive_Subprogram
15292                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
15293 
15294                if Present (Act_Elmt) then
15295                   Next_Elmt (Act_Elmt);
15296                end if;
15297             end if;
15298 
15299             Next_Elmt (Elmt);
15300          end loop;
15301 
15302       --  Case 2: Derived_Type implements interfaces
15303 
15304       else
15305          --  If the parent type has no predefined primitives we remove
15306          --  predefined primitives from the list of primitives of generic
15307          --  actual to simplify the complexity of this algorithm.
15308 
15309          if Present (Generic_Actual) then
15310             declare
15311                Has_Predefined_Primitives : Boolean := False;
15312 
15313             begin
15314                --  Check if the parent type has predefined primitives
15315 
15316                Elmt := First_Elmt (Op_List);
15317                while Present (Elmt) loop
15318                   Subp := Node (Elmt);
15319 
15320                   if Is_Predefined_Dispatching_Operation (Subp)
15321                     and then not Comes_From_Source (Ultimate_Alias (Subp))
15322                   then
15323                      Has_Predefined_Primitives := True;
15324                      exit;
15325                   end if;
15326 
15327                   Next_Elmt (Elmt);
15328                end loop;
15329 
15330                --  Remove predefined primitives of Generic_Actual. We must use
15331                --  an auxiliary list because in case of tagged types the value
15332                --  returned by Collect_Primitive_Operations is the value stored
15333                --  in its Primitive_Operations attribute (and we don't want to
15334                --  modify its current contents).
15335 
15336                if not Has_Predefined_Primitives then
15337                   declare
15338                      Aux_List : constant Elist_Id := New_Elmt_List;
15339 
15340                   begin
15341                      Elmt := First_Elmt (Act_List);
15342                      while Present (Elmt) loop
15343                         Subp := Node (Elmt);
15344 
15345                         if not Is_Predefined_Dispatching_Operation (Subp)
15346                           or else Comes_From_Source (Subp)
15347                         then
15348                            Append_Elmt (Subp, Aux_List);
15349                         end if;
15350 
15351                         Next_Elmt (Elmt);
15352                      end loop;
15353 
15354                      Act_List := Aux_List;
15355                   end;
15356                end if;
15357 
15358                Act_Elmt := First_Elmt (Act_List);
15359                Act_Subp := Node (Act_Elmt);
15360             end;
15361          end if;
15362 
15363          --  Stage 1: If the generic actual is not present we derive the
15364          --  primitives inherited from the parent type. If the generic parent
15365          --  type is present, the derived type is an instance of a formal
15366          --  derived type, and within the instance its operations are those of
15367          --  the actual. We derive from the formal type but make the inherited
15368          --  operations aliases of the corresponding operations of the actual.
15369 
15370          Elmt := First_Elmt (Op_List);
15371          while Present (Elmt) loop
15372             Subp       := Node (Elmt);
15373             Alias_Subp := Ultimate_Alias (Subp);
15374 
15375             --  Do not derive internal entities of the parent that link
15376             --  interface primitives with their covering primitive. These
15377             --  entities will be added to this type when frozen.
15378 
15379             if Present (Interface_Alias (Subp)) then
15380                goto Continue;
15381             end if;
15382 
15383             --  If the generic actual is present find the corresponding
15384             --  operation in the generic actual. If the parent type is a
15385             --  direct ancestor of the derived type then, even if it is an
15386             --  interface, the operations are inherited from the primary
15387             --  dispatch table and are in the proper order. If we detect here
15388             --  that primitives are not in the same order we traverse the list
15389             --  of primitive operations of the actual to find the one that
15390             --  implements the interface primitive.
15391 
15392             if Need_Search
15393               or else
15394                 (Present (Generic_Actual)
15395                   and then Present (Act_Subp)
15396                   and then not
15397                     (Primitive_Names_Match (Subp, Act_Subp)
15398                        and then
15399                      Type_Conformant (Subp, Act_Subp,
15400                                       Skip_Controlling_Formals => True)))
15401             then
15402                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
15403                                                Use_Full_View => True));
15404 
15405                --  Remember that we need searching for all pending primitives
15406 
15407                Need_Search := True;
15408 
15409                --  Handle entities associated with interface primitives
15410 
15411                if Present (Alias_Subp)
15412                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
15413                  and then not Is_Predefined_Dispatching_Operation (Subp)
15414                then
15415                   --  Search for the primitive in the homonym chain
15416 
15417                   Act_Subp :=
15418                     Find_Primitive_Covering_Interface
15419                       (Tagged_Type => Generic_Actual,
15420                        Iface_Prim  => Alias_Subp);
15421 
15422                   --  Previous search may not locate primitives covering
15423                   --  interfaces defined in generics units or instantiations.
15424                   --  (it fails if the covering primitive has formals whose
15425                   --  type is also defined in generics or instantiations).
15426                   --  In such case we search in the list of primitives of the
15427                   --  generic actual for the internal entity that links the
15428                   --  interface primitive and the covering primitive.
15429 
15430                   if No (Act_Subp)
15431                     and then Is_Generic_Type (Parent_Type)
15432                   then
15433                      --  This code has been designed to handle only generic
15434                      --  formals that implement interfaces that are defined
15435                      --  in a generic unit or instantiation. If this code is
15436                      --  needed for other cases we must review it because
15437                      --  (given that it relies on Original_Location to locate
15438                      --  the primitive of Generic_Actual that covers the
15439                      --  interface) it could leave linked through attribute
15440                      --  Alias entities of unrelated instantiations).
15441 
15442                      pragma Assert
15443                        (Is_Generic_Unit
15444                           (Scope (Find_Dispatching_Type (Alias_Subp)))
15445                          or else
15446                            Instantiation_Depth
15447                              (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
15448 
15449                      declare
15450                         Iface_Prim_Loc : constant Source_Ptr :=
15451                                          Original_Location (Sloc (Alias_Subp));
15452 
15453                         Elmt : Elmt_Id;
15454                         Prim : Entity_Id;
15455 
15456                      begin
15457                         Elmt :=
15458                           First_Elmt (Primitive_Operations (Generic_Actual));
15459 
15460                         Search : while Present (Elmt) loop
15461                            Prim := Node (Elmt);
15462 
15463                            if Present (Interface_Alias (Prim))
15464                              and then Original_Location
15465                                         (Sloc (Interface_Alias (Prim))) =
15466                                                               Iface_Prim_Loc
15467                            then
15468                               Act_Subp := Alias (Prim);
15469                               exit Search;
15470                            end if;
15471 
15472                            Next_Elmt (Elmt);
15473                         end loop Search;
15474                      end;
15475                   end if;
15476 
15477                   pragma Assert (Present (Act_Subp)
15478                     or else Is_Abstract_Type (Generic_Actual)
15479                     or else Serious_Errors_Detected > 0);
15480 
15481                --  Handle predefined primitives plus the rest of user-defined
15482                --  primitives
15483 
15484                else
15485                   Act_Elmt := First_Elmt (Act_List);
15486                   while Present (Act_Elmt) loop
15487                      Act_Subp := Node (Act_Elmt);
15488 
15489                      exit when Primitive_Names_Match (Subp, Act_Subp)
15490                        and then Type_Conformant
15491                                   (Subp, Act_Subp,
15492                                    Skip_Controlling_Formals => True)
15493                        and then No (Interface_Alias (Act_Subp));
15494 
15495                      Next_Elmt (Act_Elmt);
15496                   end loop;
15497 
15498                   if No (Act_Elmt) then
15499                      Act_Subp := Empty;
15500                   end if;
15501                end if;
15502             end if;
15503 
15504             --   Case 1: If the parent is a limited interface then it has the
15505             --   predefined primitives of synchronized interfaces. However, the
15506             --   actual type may be a non-limited type and hence it does not
15507             --   have such primitives.
15508 
15509             if Present (Generic_Actual)
15510               and then not Present (Act_Subp)
15511               and then Is_Limited_Interface (Parent_Base)
15512               and then Is_Predefined_Interface_Primitive (Subp)
15513             then
15514                null;
15515 
15516             --  Case 2: Inherit entities associated with interfaces that were
15517             --  not covered by the parent type. We exclude here null interface
15518             --  primitives because they do not need special management.
15519 
15520             --  We also exclude interface operations that are renamings. If the
15521             --  subprogram is an explicit renaming of an interface primitive,
15522             --  it is a regular primitive operation, and the presence of its
15523             --  alias is not relevant: it has to be derived like any other
15524             --  primitive.
15525 
15526             elsif Present (Alias (Subp))
15527               and then Nkind (Unit_Declaration_Node (Subp)) /=
15528                                             N_Subprogram_Renaming_Declaration
15529               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
15530               and then not
15531                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
15532                   and then Null_Present (Parent (Alias_Subp)))
15533             then
15534                --  If this is an abstract private type then we transfer the
15535                --  derivation of the interface primitive from the partial view
15536                --  to the full view. This is safe because all the interfaces
15537                --  must be visible in the partial view. Done to avoid adding
15538                --  a new interface derivation to the private part of the
15539                --  enclosing package; otherwise this new derivation would be
15540                --  decorated as hidden when the analysis of the enclosing
15541                --  package completes.
15542 
15543                if Is_Abstract_Type (Derived_Type)
15544                  and then In_Private_Part (Current_Scope)
15545                  and then Has_Private_Declaration (Derived_Type)
15546                then
15547                   declare
15548                      Partial_View : Entity_Id;
15549                      Elmt         : Elmt_Id;
15550                      Ent          : Entity_Id;
15551 
15552                   begin
15553                      Partial_View := First_Entity (Current_Scope);
15554                      loop
15555                         exit when No (Partial_View)
15556                           or else (Has_Private_Declaration (Partial_View)
15557                                     and then
15558                                       Full_View (Partial_View) = Derived_Type);
15559 
15560                         Next_Entity (Partial_View);
15561                      end loop;
15562 
15563                      --  If the partial view was not found then the source code
15564                      --  has errors and the derivation is not needed.
15565 
15566                      if Present (Partial_View) then
15567                         Elmt :=
15568                           First_Elmt (Primitive_Operations (Partial_View));
15569                         while Present (Elmt) loop
15570                            Ent := Node (Elmt);
15571 
15572                            if Present (Alias (Ent))
15573                              and then Ultimate_Alias (Ent) = Alias (Subp)
15574                            then
15575                               Append_Elmt
15576                                 (Ent, Primitive_Operations (Derived_Type));
15577                               exit;
15578                            end if;
15579 
15580                            Next_Elmt (Elmt);
15581                         end loop;
15582 
15583                         --  If the interface primitive was not found in the
15584                         --  partial view then this interface primitive was
15585                         --  overridden. We add a derivation to activate in
15586                         --  Derive_Progenitor_Subprograms the machinery to
15587                         --  search for it.
15588 
15589                         if No (Elmt) then
15590                            Derive_Interface_Subprogram
15591                              (New_Subp    => New_Subp,
15592                               Subp        => Subp,
15593                               Actual_Subp => Act_Subp);
15594                         end if;
15595                      end if;
15596                   end;
15597                else
15598                   Derive_Interface_Subprogram
15599                     (New_Subp     => New_Subp,
15600                      Subp         => Subp,
15601                      Actual_Subp  => Act_Subp);
15602                end if;
15603 
15604             --  Case 3: Common derivation
15605 
15606             else
15607                Derive_Subprogram
15608                  (New_Subp     => New_Subp,
15609                   Parent_Subp  => Subp,
15610                   Derived_Type => Derived_Type,
15611                   Parent_Type  => Parent_Base,
15612                   Actual_Subp  => Act_Subp);
15613             end if;
15614 
15615             --  No need to update Act_Elm if we must search for the
15616             --  corresponding operation in the generic actual
15617 
15618             if not Need_Search
15619               and then Present (Act_Elmt)
15620             then
15621                Next_Elmt (Act_Elmt);
15622                Act_Subp := Node (Act_Elmt);
15623             end if;
15624 
15625             <<Continue>>
15626             Next_Elmt (Elmt);
15627          end loop;
15628 
15629          --  Inherit additional operations from progenitors. If the derived
15630          --  type is a generic actual, there are not new primitive operations
15631          --  for the type because it has those of the actual, and therefore
15632          --  nothing needs to be done. The renamings generated above are not
15633          --  primitive operations, and their purpose is simply to make the
15634          --  proper operations visible within an instantiation.
15635 
15636          if No (Generic_Actual) then
15637             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
15638          end if;
15639       end if;
15640 
15641       --  Final check: Direct descendants must have their primitives in the
15642       --  same order. We exclude from this test untagged types and instances
15643       --  of formal derived types. We skip this test if we have already
15644       --  reported serious errors in the sources.
15645 
15646       pragma Assert (not Is_Tagged_Type (Derived_Type)
15647         or else Present (Generic_Actual)
15648         or else Serious_Errors_Detected > 0
15649         or else Check_Derived_Type);
15650    end Derive_Subprograms;
15651 
15652    --------------------------------
15653    -- Derived_Standard_Character --
15654    --------------------------------
15655 
15656    procedure Derived_Standard_Character
15657      (N            : Node_Id;
15658       Parent_Type  : Entity_Id;
15659       Derived_Type : Entity_Id)
15660    is
15661       Loc           : constant Source_Ptr := Sloc (N);
15662       Def           : constant Node_Id    := Type_Definition (N);
15663       Indic         : constant Node_Id    := Subtype_Indication (Def);
15664       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
15665       Implicit_Base : constant Entity_Id  :=
15666                         Create_Itype
15667                           (E_Enumeration_Type, N, Derived_Type, 'B');
15668 
15669       Lo : Node_Id;
15670       Hi : Node_Id;
15671 
15672    begin
15673       Discard_Node (Process_Subtype (Indic, N));
15674 
15675       Set_Etype     (Implicit_Base, Parent_Base);
15676       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
15677       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
15678 
15679       Set_Is_Character_Type  (Implicit_Base, True);
15680       Set_Has_Delayed_Freeze (Implicit_Base);
15681 
15682       --  The bounds of the implicit base are the bounds of the parent base.
15683       --  Note that their type is the parent base.
15684 
15685       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
15686       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
15687 
15688       Set_Scalar_Range (Implicit_Base,
15689         Make_Range (Loc,
15690           Low_Bound  => Lo,
15691           High_Bound => Hi));
15692 
15693       Conditional_Delay (Derived_Type, Parent_Type);
15694 
15695       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
15696       Set_Etype (Derived_Type, Implicit_Base);
15697       Set_Size_Info         (Derived_Type, Parent_Type);
15698 
15699       if Unknown_RM_Size (Derived_Type) then
15700          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
15701       end if;
15702 
15703       Set_Is_Character_Type (Derived_Type, True);
15704 
15705       if Nkind (Indic) /= N_Subtype_Indication then
15706 
15707          --  If no explicit constraint, the bounds are those
15708          --  of the parent type.
15709 
15710          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
15711          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
15712          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
15713       end if;
15714 
15715       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
15716 
15717       --  Because the implicit base is used in the conversion of the bounds, we
15718       --  have to freeze it now. This is similar to what is done for numeric
15719       --  types, and it equally suspicious, but otherwise a non-static bound
15720       --  will have a reference to an unfrozen type, which is rejected by Gigi
15721       --  (???). This requires specific care for definition of stream
15722       --  attributes. For details, see comments at the end of
15723       --  Build_Derived_Numeric_Type.
15724 
15725       Freeze_Before (N, Implicit_Base);
15726    end Derived_Standard_Character;
15727 
15728    ------------------------------
15729    -- Derived_Type_Declaration --
15730    ------------------------------
15731 
15732    procedure Derived_Type_Declaration
15733      (T             : Entity_Id;
15734       N             : Node_Id;
15735       Is_Completion : Boolean)
15736    is
15737       Parent_Type  : Entity_Id;
15738 
15739       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
15740       --  Check whether the parent type is a generic formal, or derives
15741       --  directly or indirectly from one.
15742 
15743       ------------------------
15744       -- Comes_From_Generic --
15745       ------------------------
15746 
15747       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
15748       begin
15749          if Is_Generic_Type (Typ) then
15750             return True;
15751 
15752          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
15753             return True;
15754 
15755          elsif Is_Private_Type (Typ)
15756            and then Present (Full_View (Typ))
15757            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
15758          then
15759             return True;
15760 
15761          elsif Is_Generic_Actual_Type (Typ) then
15762             return True;
15763 
15764          else
15765             return False;
15766          end if;
15767       end Comes_From_Generic;
15768 
15769       --  Local variables
15770 
15771       Def          : constant Node_Id := Type_Definition (N);
15772       Iface_Def    : Node_Id;
15773       Indic        : constant Node_Id := Subtype_Indication (Def);
15774       Extension    : constant Node_Id := Record_Extension_Part (Def);
15775       Parent_Node  : Node_Id;
15776       Taggd        : Boolean;
15777 
15778    --  Start of processing for Derived_Type_Declaration
15779 
15780    begin
15781       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
15782 
15783       --  Ada 2005 (AI-251): In case of interface derivation check that the
15784       --  parent is also an interface.
15785 
15786       if Interface_Present (Def) then
15787          Check_SPARK_05_Restriction ("interface is not allowed", Def);
15788 
15789          if not Is_Interface (Parent_Type) then
15790             Diagnose_Interface (Indic, Parent_Type);
15791 
15792          else
15793             Parent_Node := Parent (Base_Type (Parent_Type));
15794             Iface_Def   := Type_Definition (Parent_Node);
15795 
15796             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
15797             --  other limited interfaces.
15798 
15799             if Limited_Present (Def) then
15800                if Limited_Present (Iface_Def) then
15801                   null;
15802 
15803                elsif Protected_Present (Iface_Def) then
15804                   Error_Msg_NE
15805                     ("descendant of & must be declared as a protected "
15806                      & "interface", N, Parent_Type);
15807 
15808                elsif Synchronized_Present (Iface_Def) then
15809                   Error_Msg_NE
15810                     ("descendant of & must be declared as a synchronized "
15811                      & "interface", N, Parent_Type);
15812 
15813                elsif Task_Present (Iface_Def) then
15814                   Error_Msg_NE
15815                     ("descendant of & must be declared as a task interface",
15816                        N, Parent_Type);
15817 
15818                else
15819                   Error_Msg_N
15820                     ("(Ada 2005) limited interface cannot inherit from "
15821                      & "non-limited interface", Indic);
15822                end if;
15823 
15824             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
15825             --  from non-limited or limited interfaces.
15826 
15827             elsif not Protected_Present (Def)
15828               and then not Synchronized_Present (Def)
15829               and then not Task_Present (Def)
15830             then
15831                if Limited_Present (Iface_Def) then
15832                   null;
15833 
15834                elsif Protected_Present (Iface_Def) then
15835                   Error_Msg_NE
15836                     ("descendant of & must be declared as a protected "
15837                      & "interface", N, Parent_Type);
15838 
15839                elsif Synchronized_Present (Iface_Def) then
15840                   Error_Msg_NE
15841                     ("descendant of & must be declared as a synchronized "
15842                      & "interface", N, Parent_Type);
15843 
15844                elsif Task_Present (Iface_Def) then
15845                   Error_Msg_NE
15846                     ("descendant of & must be declared as a task interface",
15847                        N, Parent_Type);
15848                else
15849                   null;
15850                end if;
15851             end if;
15852          end if;
15853       end if;
15854 
15855       if Is_Tagged_Type (Parent_Type)
15856         and then Is_Concurrent_Type (Parent_Type)
15857         and then not Is_Interface (Parent_Type)
15858       then
15859          Error_Msg_N
15860            ("parent type of a record extension cannot be a synchronized "
15861             & "tagged type (RM 3.9.1 (3/1))", N);
15862          Set_Etype (T, Any_Type);
15863          return;
15864       end if;
15865 
15866       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
15867       --  interfaces
15868 
15869       if Is_Tagged_Type (Parent_Type)
15870         and then Is_Non_Empty_List (Interface_List (Def))
15871       then
15872          declare
15873             Intf : Node_Id;
15874             T    : Entity_Id;
15875 
15876          begin
15877             Intf := First (Interface_List (Def));
15878             while Present (Intf) loop
15879                T := Find_Type_Of_Subtype_Indic (Intf);
15880 
15881                if not Is_Interface (T) then
15882                   Diagnose_Interface (Intf, T);
15883 
15884                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
15885                --  a limited type from having a nonlimited progenitor.
15886 
15887                elsif (Limited_Present (Def)
15888                        or else (not Is_Interface (Parent_Type)
15889                                  and then Is_Limited_Type (Parent_Type)))
15890                  and then not Is_Limited_Interface (T)
15891                then
15892                   Error_Msg_NE
15893                    ("progenitor interface& of limited type must be limited",
15894                      N, T);
15895                end if;
15896 
15897                Next (Intf);
15898             end loop;
15899          end;
15900       end if;
15901 
15902       if Parent_Type = Any_Type
15903         or else Etype (Parent_Type) = Any_Type
15904         or else (Is_Class_Wide_Type (Parent_Type)
15905                   and then Etype (Parent_Type) = T)
15906       then
15907          --  If Parent_Type is undefined or illegal, make new type into a
15908          --  subtype of Any_Type, and set a few attributes to prevent cascaded
15909          --  errors. If this is a self-definition, emit error now.
15910 
15911          if T = Parent_Type or else T = Etype (Parent_Type) then
15912             Error_Msg_N ("type cannot be used in its own definition", Indic);
15913          end if;
15914 
15915          Set_Ekind        (T, Ekind (Parent_Type));
15916          Set_Etype        (T, Any_Type);
15917          Set_Scalar_Range (T, Scalar_Range (Any_Type));
15918 
15919          if Is_Tagged_Type (T)
15920            and then Is_Record_Type (T)
15921          then
15922             Set_Direct_Primitive_Operations (T, New_Elmt_List);
15923          end if;
15924 
15925          return;
15926       end if;
15927 
15928       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
15929       --  an interface is special because the list of interfaces in the full
15930       --  view can be given in any order. For example:
15931 
15932       --     type A is interface;
15933       --     type B is interface and A;
15934       --     type D is new B with private;
15935       --   private
15936       --     type D is new A and B with null record; -- 1 --
15937 
15938       --  In this case we perform the following transformation of -1-:
15939 
15940       --     type D is new B and A with null record;
15941 
15942       --  If the parent of the full-view covers the parent of the partial-view
15943       --  we have two possible cases:
15944 
15945       --     1) They have the same parent
15946       --     2) The parent of the full-view implements some further interfaces
15947 
15948       --  In both cases we do not need to perform the transformation. In the
15949       --  first case the source program is correct and the transformation is
15950       --  not needed; in the second case the source program does not fulfill
15951       --  the no-hidden interfaces rule (AI-396) and the error will be reported
15952       --  later.
15953 
15954       --  This transformation not only simplifies the rest of the analysis of
15955       --  this type declaration but also simplifies the correct generation of
15956       --  the object layout to the expander.
15957 
15958       if In_Private_Part (Current_Scope)
15959         and then Is_Interface (Parent_Type)
15960       then
15961          declare
15962             Iface               : Node_Id;
15963             Partial_View        : Entity_Id;
15964             Partial_View_Parent : Entity_Id;
15965             New_Iface           : Node_Id;
15966 
15967          begin
15968             --  Look for the associated private type declaration
15969 
15970             Partial_View := First_Entity (Current_Scope);
15971             loop
15972                exit when No (Partial_View)
15973                  or else (Has_Private_Declaration (Partial_View)
15974                            and then Full_View (Partial_View) = T);
15975 
15976                Next_Entity (Partial_View);
15977             end loop;
15978 
15979             --  If the partial view was not found then the source code has
15980             --  errors and the transformation is not needed.
15981 
15982             if Present (Partial_View) then
15983                Partial_View_Parent := Etype (Partial_View);
15984 
15985                --  If the parent of the full-view covers the parent of the
15986                --  partial-view we have nothing else to do.
15987 
15988                if Interface_Present_In_Ancestor
15989                     (Parent_Type, Partial_View_Parent)
15990                then
15991                   null;
15992 
15993                --  Traverse the list of interfaces of the full-view to look
15994                --  for the parent of the partial-view and perform the tree
15995                --  transformation.
15996 
15997                else
15998                   Iface := First (Interface_List (Def));
15999                   while Present (Iface) loop
16000                      if Etype (Iface) = Etype (Partial_View) then
16001                         Rewrite (Subtype_Indication (Def),
16002                           New_Copy (Subtype_Indication
16003                                      (Parent (Partial_View))));
16004 
16005                         New_Iface :=
16006                           Make_Identifier (Sloc (N), Chars (Parent_Type));
16007                         Append (New_Iface, Interface_List (Def));
16008 
16009                         --  Analyze the transformed code
16010 
16011                         Derived_Type_Declaration (T, N, Is_Completion);
16012                         return;
16013                      end if;
16014 
16015                      Next (Iface);
16016                   end loop;
16017                end if;
16018             end if;
16019          end;
16020       end if;
16021 
16022       --  Only composite types other than array types are allowed to have
16023       --  discriminants.
16024 
16025       if Present (Discriminant_Specifications (N)) then
16026          if (Is_Elementary_Type (Parent_Type)
16027                or else
16028              Is_Array_Type      (Parent_Type))
16029            and then not Error_Posted (N)
16030          then
16031             Error_Msg_N
16032               ("elementary or array type cannot have discriminants",
16033                Defining_Identifier (First (Discriminant_Specifications (N))));
16034             Set_Has_Discriminants (T, False);
16035 
16036          --  The type is allowed to have discriminants
16037 
16038          else
16039             Check_SPARK_05_Restriction ("discriminant type is not allowed", N);
16040          end if;
16041       end if;
16042 
16043       --  In Ada 83, a derived type defined in a package specification cannot
16044       --  be used for further derivation until the end of its visible part.
16045       --  Note that derivation in the private part of the package is allowed.
16046 
16047       if Ada_Version = Ada_83
16048         and then Is_Derived_Type (Parent_Type)
16049         and then In_Visible_Part (Scope (Parent_Type))
16050       then
16051          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
16052             Error_Msg_N
16053               ("(Ada 83): premature use of type for derivation", Indic);
16054          end if;
16055       end if;
16056 
16057       --  Check for early use of incomplete or private type
16058 
16059       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
16060          Error_Msg_N ("premature derivation of incomplete type", Indic);
16061          return;
16062 
16063       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
16064               and then not Comes_From_Generic (Parent_Type))
16065         or else Has_Private_Component (Parent_Type)
16066       then
16067          --  The ancestor type of a formal type can be incomplete, in which
16068          --  case only the operations of the partial view are available in the
16069          --  generic. Subsequent checks may be required when the full view is
16070          --  analyzed to verify that a derivation from a tagged type has an
16071          --  extension.
16072 
16073          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
16074             null;
16075 
16076          elsif No (Underlying_Type (Parent_Type))
16077            or else Has_Private_Component (Parent_Type)
16078          then
16079             Error_Msg_N
16080               ("premature derivation of derived or private type", Indic);
16081 
16082             --  Flag the type itself as being in error, this prevents some
16083             --  nasty problems with subsequent uses of the malformed type.
16084 
16085             Set_Error_Posted (T);
16086 
16087          --  Check that within the immediate scope of an untagged partial
16088          --  view it's illegal to derive from the partial view if the
16089          --  full view is tagged. (7.3(7))
16090 
16091          --  We verify that the Parent_Type is a partial view by checking
16092          --  that it is not a Full_Type_Declaration (i.e. a private type or
16093          --  private extension declaration), to distinguish a partial view
16094          --  from  a derivation from a private type which also appears as
16095          --  E_Private_Type. If the parent base type is not declared in an
16096          --  enclosing scope there is no need to check.
16097 
16098          elsif Present (Full_View (Parent_Type))
16099            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
16100            and then not Is_Tagged_Type (Parent_Type)
16101            and then Is_Tagged_Type (Full_View (Parent_Type))
16102            and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
16103          then
16104             Error_Msg_N
16105               ("premature derivation from type with tagged full view",
16106                 Indic);
16107          end if;
16108       end if;
16109 
16110       --  Check that form of derivation is appropriate
16111 
16112       Taggd := Is_Tagged_Type (Parent_Type);
16113 
16114       --  Set the parent type to the class-wide type's specific type in this
16115       --  case to prevent cascading errors
16116 
16117       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
16118          Error_Msg_N ("parent type must not be a class-wide type", Indic);
16119          Set_Etype (T, Etype (Parent_Type));
16120          return;
16121       end if;
16122 
16123       if Present (Extension) and then not Taggd then
16124          Error_Msg_N
16125            ("type derived from untagged type cannot have extension", Indic);
16126 
16127       elsif No (Extension) and then Taggd then
16128 
16129          --  If this declaration is within a private part (or body) of a
16130          --  generic instantiation then the derivation is allowed (the parent
16131          --  type can only appear tagged in this case if it's a generic actual
16132          --  type, since it would otherwise have been rejected in the analysis
16133          --  of the generic template).
16134 
16135          if not Is_Generic_Actual_Type (Parent_Type)
16136            or else In_Visible_Part (Scope (Parent_Type))
16137          then
16138             if Is_Class_Wide_Type (Parent_Type) then
16139                Error_Msg_N
16140                  ("parent type must not be a class-wide type", Indic);
16141 
16142                --  Use specific type to prevent cascaded errors.
16143 
16144                Parent_Type := Etype (Parent_Type);
16145 
16146             else
16147                Error_Msg_N
16148                  ("type derived from tagged type must have extension", Indic);
16149             end if;
16150          end if;
16151       end if;
16152 
16153       --  AI-443: Synchronized formal derived types require a private
16154       --  extension. There is no point in checking the ancestor type or
16155       --  the progenitors since the construct is wrong to begin with.
16156 
16157       if Ada_Version >= Ada_2005
16158         and then Is_Generic_Type (T)
16159         and then Present (Original_Node (N))
16160       then
16161          declare
16162             Decl : constant Node_Id := Original_Node (N);
16163 
16164          begin
16165             if Nkind (Decl) = N_Formal_Type_Declaration
16166               and then Nkind (Formal_Type_Definition (Decl)) =
16167                                           N_Formal_Derived_Type_Definition
16168               and then Synchronized_Present (Formal_Type_Definition (Decl))
16169               and then No (Extension)
16170 
16171                --  Avoid emitting a duplicate error message
16172 
16173               and then not Error_Posted (Indic)
16174             then
16175                Error_Msg_N
16176                  ("synchronized derived type must have extension", N);
16177             end if;
16178          end;
16179       end if;
16180 
16181       if Null_Exclusion_Present (Def)
16182         and then not Is_Access_Type (Parent_Type)
16183       then
16184          Error_Msg_N ("null exclusion can only apply to an access type", N);
16185       end if;
16186 
16187       --  Avoid deriving parent primitives of underlying record views
16188 
16189       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
16190         Derive_Subps => not Is_Underlying_Record_View (T));
16191 
16192       --  AI-419: The parent type of an explicitly limited derived type must
16193       --  be a limited type or a limited interface.
16194 
16195       if Limited_Present (Def) then
16196          Set_Is_Limited_Record (T);
16197 
16198          if Is_Interface (T) then
16199             Set_Is_Limited_Interface (T);
16200          end if;
16201 
16202          if not Is_Limited_Type (Parent_Type)
16203            and then
16204              (not Is_Interface (Parent_Type)
16205                or else not Is_Limited_Interface (Parent_Type))
16206          then
16207             --  AI05-0096: a derivation in the private part of an instance is
16208             --  legal if the generic formal is untagged limited, and the actual
16209             --  is non-limited.
16210 
16211             if Is_Generic_Actual_Type (Parent_Type)
16212               and then In_Private_Part (Current_Scope)
16213               and then
16214                 not Is_Tagged_Type
16215                       (Generic_Parent_Type (Parent (Parent_Type)))
16216             then
16217                null;
16218 
16219             else
16220                Error_Msg_NE
16221                  ("parent type& of limited type must be limited",
16222                   N, Parent_Type);
16223             end if;
16224          end if;
16225       end if;
16226 
16227       --  In SPARK, there are no derived type definitions other than type
16228       --  extensions of tagged record types.
16229 
16230       if No (Extension) then
16231          Check_SPARK_05_Restriction
16232            ("derived type is not allowed", Original_Node (N));
16233       end if;
16234    end Derived_Type_Declaration;
16235 
16236    ------------------------
16237    -- Diagnose_Interface --
16238    ------------------------
16239 
16240    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
16241    begin
16242       if not Is_Interface (E) and then  E /= Any_Type then
16243          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
16244       end if;
16245    end Diagnose_Interface;
16246 
16247    ----------------------------------
16248    -- Enumeration_Type_Declaration --
16249    ----------------------------------
16250 
16251    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16252       Ev     : Uint;
16253       L      : Node_Id;
16254       R_Node : Node_Id;
16255       B_Node : Node_Id;
16256 
16257    begin
16258       --  Create identifier node representing lower bound
16259 
16260       B_Node := New_Node (N_Identifier, Sloc (Def));
16261       L := First (Literals (Def));
16262       Set_Chars (B_Node, Chars (L));
16263       Set_Entity (B_Node,  L);
16264       Set_Etype (B_Node, T);
16265       Set_Is_Static_Expression (B_Node, True);
16266 
16267       R_Node := New_Node (N_Range, Sloc (Def));
16268       Set_Low_Bound  (R_Node, B_Node);
16269 
16270       Set_Ekind (T, E_Enumeration_Type);
16271       Set_First_Literal (T, L);
16272       Set_Etype (T, T);
16273       Set_Is_Constrained (T);
16274 
16275       Ev := Uint_0;
16276 
16277       --  Loop through literals of enumeration type setting pos and rep values
16278       --  except that if the Ekind is already set, then it means the literal
16279       --  was already constructed (case of a derived type declaration and we
16280       --  should not disturb the Pos and Rep values.
16281 
16282       while Present (L) loop
16283          if Ekind (L) /= E_Enumeration_Literal then
16284             Set_Ekind (L, E_Enumeration_Literal);
16285             Set_Enumeration_Pos (L, Ev);
16286             Set_Enumeration_Rep (L, Ev);
16287             Set_Is_Known_Valid  (L, True);
16288          end if;
16289 
16290          Set_Etype (L, T);
16291          New_Overloaded_Entity (L);
16292          Generate_Definition (L);
16293          Set_Convention (L, Convention_Intrinsic);
16294 
16295          --  Case of character literal
16296 
16297          if Nkind (L) = N_Defining_Character_Literal then
16298             Set_Is_Character_Type (T, True);
16299 
16300             --  Check violation of No_Wide_Characters
16301 
16302             if Restriction_Check_Required (No_Wide_Characters) then
16303                Get_Name_String (Chars (L));
16304 
16305                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
16306                   Check_Restriction (No_Wide_Characters, L);
16307                end if;
16308             end if;
16309          end if;
16310 
16311          Ev := Ev + 1;
16312          Next (L);
16313       end loop;
16314 
16315       --  Now create a node representing upper bound
16316 
16317       B_Node := New_Node (N_Identifier, Sloc (Def));
16318       Set_Chars (B_Node, Chars (Last (Literals (Def))));
16319       Set_Entity (B_Node,  Last (Literals (Def)));
16320       Set_Etype (B_Node, T);
16321       Set_Is_Static_Expression (B_Node, True);
16322 
16323       Set_High_Bound (R_Node, B_Node);
16324 
16325       --  Initialize various fields of the type. Some of this information
16326       --  may be overwritten later through rep.clauses.
16327 
16328       Set_Scalar_Range    (T, R_Node);
16329       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
16330       Set_Enum_Esize      (T);
16331       Set_Enum_Pos_To_Rep (T, Empty);
16332 
16333       --  Set Discard_Names if configuration pragma set, or if there is
16334       --  a parameterless pragma in the current declarative region
16335 
16336       if Global_Discard_Names or else Discard_Names (Scope (T)) then
16337          Set_Discard_Names (T);
16338       end if;
16339 
16340       --  Process end label if there is one
16341 
16342       if Present (Def) then
16343          Process_End_Label (Def, 'e', T);
16344       end if;
16345    end Enumeration_Type_Declaration;
16346 
16347    ---------------------------------
16348    -- Expand_To_Stored_Constraint --
16349    ---------------------------------
16350 
16351    function Expand_To_Stored_Constraint
16352      (Typ        : Entity_Id;
16353       Constraint : Elist_Id) return Elist_Id
16354    is
16355       Explicitly_Discriminated_Type : Entity_Id;
16356       Expansion    : Elist_Id;
16357       Discriminant : Entity_Id;
16358 
16359       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
16360       --  Find the nearest type that actually specifies discriminants
16361 
16362       ---------------------------------
16363       -- Type_With_Explicit_Discrims --
16364       ---------------------------------
16365 
16366       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
16367          Typ : constant E := Base_Type (Id);
16368 
16369       begin
16370          if Ekind (Typ) in Incomplete_Or_Private_Kind then
16371             if Present (Full_View (Typ)) then
16372                return Type_With_Explicit_Discrims (Full_View (Typ));
16373             end if;
16374 
16375          else
16376             if Has_Discriminants (Typ) then
16377                return Typ;
16378             end if;
16379          end if;
16380 
16381          if Etype (Typ) = Typ then
16382             return Empty;
16383          elsif Has_Discriminants (Typ) then
16384             return Typ;
16385          else
16386             return Type_With_Explicit_Discrims (Etype (Typ));
16387          end if;
16388 
16389       end Type_With_Explicit_Discrims;
16390 
16391    --  Start of processing for Expand_To_Stored_Constraint
16392 
16393    begin
16394       if No (Constraint) or else Is_Empty_Elmt_List (Constraint) then
16395          return No_Elist;
16396       end if;
16397 
16398       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
16399 
16400       if No (Explicitly_Discriminated_Type) then
16401          return No_Elist;
16402       end if;
16403 
16404       Expansion := New_Elmt_List;
16405 
16406       Discriminant :=
16407          First_Stored_Discriminant (Explicitly_Discriminated_Type);
16408       while Present (Discriminant) loop
16409          Append_Elmt
16410            (Get_Discriminant_Value
16411               (Discriminant, Explicitly_Discriminated_Type, Constraint),
16412             To => Expansion);
16413          Next_Stored_Discriminant (Discriminant);
16414       end loop;
16415 
16416       return Expansion;
16417    end Expand_To_Stored_Constraint;
16418 
16419    ---------------------------
16420    -- Find_Hidden_Interface --
16421    ---------------------------
16422 
16423    function Find_Hidden_Interface
16424      (Src  : Elist_Id;
16425       Dest : Elist_Id) return Entity_Id
16426    is
16427       Iface      : Entity_Id;
16428       Iface_Elmt : Elmt_Id;
16429 
16430    begin
16431       if Present (Src) and then Present (Dest) then
16432          Iface_Elmt := First_Elmt (Src);
16433          while Present (Iface_Elmt) loop
16434             Iface := Node (Iface_Elmt);
16435 
16436             if Is_Interface (Iface)
16437               and then not Contain_Interface (Iface, Dest)
16438             then
16439                return Iface;
16440             end if;
16441 
16442             Next_Elmt (Iface_Elmt);
16443          end loop;
16444       end if;
16445 
16446       return Empty;
16447    end Find_Hidden_Interface;
16448 
16449    --------------------
16450    -- Find_Type_Name --
16451    --------------------
16452 
16453    function Find_Type_Name (N : Node_Id) return Entity_Id is
16454       Id       : constant Entity_Id := Defining_Identifier (N);
16455       New_Id   : Entity_Id;
16456       Prev     : Entity_Id;
16457       Prev_Par : Node_Id;
16458 
16459       procedure Check_Duplicate_Aspects;
16460       --  Check that aspects specified in a completion have not been specified
16461       --  already in the partial view.
16462 
16463       procedure Tag_Mismatch;
16464       --  Diagnose a tagged partial view whose full view is untagged. We post
16465       --  the message on the full view, with a reference to the previous
16466       --  partial view. The partial view can be private or incomplete, and
16467       --  these are handled in a different manner, so we determine the position
16468       --  of the error message from the respective slocs of both.
16469 
16470       -----------------------------
16471       -- Check_Duplicate_Aspects --
16472       -----------------------------
16473 
16474       procedure Check_Duplicate_Aspects is
16475          function Get_Partial_View_Aspect (Asp : Node_Id) return Node_Id;
16476          --  Return the corresponding aspect of the partial view which matches
16477          --  the aspect id of Asp. Return Empty is no such aspect exists.
16478 
16479          -----------------------------
16480          -- Get_Partial_View_Aspect --
16481          -----------------------------
16482 
16483          function Get_Partial_View_Aspect (Asp : Node_Id) return Node_Id is
16484             Asp_Id    : constant Aspect_Id := Get_Aspect_Id (Asp);
16485             Prev_Asps : constant List_Id   := Aspect_Specifications (Prev_Par);
16486             Prev_Asp  : Node_Id;
16487 
16488          begin
16489             if Present (Prev_Asps) then
16490                Prev_Asp := First (Prev_Asps);
16491                while Present (Prev_Asp) loop
16492                   if Get_Aspect_Id (Prev_Asp) = Asp_Id then
16493                      return Prev_Asp;
16494                   end if;
16495 
16496                   Next (Prev_Asp);
16497                end loop;
16498             end if;
16499 
16500             return Empty;
16501          end Get_Partial_View_Aspect;
16502 
16503          --  Local variables
16504 
16505          Full_Asps : constant List_Id := Aspect_Specifications (N);
16506          Full_Asp  : Node_Id;
16507          Part_Asp  : Node_Id;
16508 
16509       --  Start of processing for Check_Duplicate_Aspects
16510 
16511       begin
16512          if Present (Full_Asps) then
16513             Full_Asp := First (Full_Asps);
16514             while Present (Full_Asp) loop
16515                Part_Asp := Get_Partial_View_Aspect (Full_Asp);
16516 
16517                --  An aspect and its class-wide counterpart are two distinct
16518                --  aspects and may apply to both views of an entity.
16519 
16520                if Present (Part_Asp)
16521                  and then Class_Present (Part_Asp) = Class_Present (Full_Asp)
16522                then
16523                   Error_Msg_N
16524                     ("aspect already specified in private declaration",
16525                      Full_Asp);
16526 
16527                   Remove (Full_Asp);
16528                   return;
16529                end if;
16530 
16531                if Has_Discriminants (Prev)
16532                  and then not Has_Unknown_Discriminants (Prev)
16533                  and then Get_Aspect_Id (Full_Asp) =
16534                             Aspect_Implicit_Dereference
16535                then
16536                   Error_Msg_N
16537                     ("cannot specify aspect if partial view has known "
16538                      & "discriminants", Full_Asp);
16539                end if;
16540 
16541                Next (Full_Asp);
16542             end loop;
16543          end if;
16544       end Check_Duplicate_Aspects;
16545 
16546       ------------------
16547       -- Tag_Mismatch --
16548       ------------------
16549 
16550       procedure Tag_Mismatch is
16551       begin
16552          if Sloc (Prev) < Sloc (Id) then
16553             if Ada_Version >= Ada_2012
16554               and then Nkind (N) = N_Private_Type_Declaration
16555             then
16556                Error_Msg_NE
16557                  ("declaration of private } must be a tagged type ", Id, Prev);
16558             else
16559                Error_Msg_NE
16560                  ("full declaration of } must be a tagged type ", Id, Prev);
16561             end if;
16562 
16563          else
16564             if Ada_Version >= Ada_2012
16565               and then Nkind (N) = N_Private_Type_Declaration
16566             then
16567                Error_Msg_NE
16568                  ("declaration of private } must be a tagged type ", Prev, Id);
16569             else
16570                Error_Msg_NE
16571                  ("full declaration of } must be a tagged type ", Prev, Id);
16572             end if;
16573          end if;
16574       end Tag_Mismatch;
16575 
16576    --  Start of processing for Find_Type_Name
16577 
16578    begin
16579       --  Find incomplete declaration, if one was given
16580 
16581       Prev := Current_Entity_In_Scope (Id);
16582 
16583       --  New type declaration
16584 
16585       if No (Prev) then
16586          Enter_Name (Id);
16587          return Id;
16588 
16589       --  Previous declaration exists
16590 
16591       else
16592          Prev_Par := Parent (Prev);
16593 
16594          --  Error if not incomplete/private case except if previous
16595          --  declaration is implicit, etc. Enter_Name will emit error if
16596          --  appropriate.
16597 
16598          if not Is_Incomplete_Or_Private_Type (Prev) then
16599             Enter_Name (Id);
16600             New_Id := Id;
16601 
16602          --  Check invalid completion of private or incomplete type
16603 
16604          elsif not Nkind_In (N, N_Full_Type_Declaration,
16605                                 N_Task_Type_Declaration,
16606                                 N_Protected_Type_Declaration)
16607            and then
16608              (Ada_Version < Ada_2012
16609                or else not Is_Incomplete_Type (Prev)
16610                or else not Nkind_In (N, N_Private_Type_Declaration,
16611                                         N_Private_Extension_Declaration))
16612          then
16613             --  Completion must be a full type declarations (RM 7.3(4))
16614 
16615             Error_Msg_Sloc := Sloc (Prev);
16616             Error_Msg_NE ("invalid completion of }", Id, Prev);
16617 
16618             --  Set scope of Id to avoid cascaded errors. Entity is never
16619             --  examined again, except when saving globals in generics.
16620 
16621             Set_Scope (Id, Current_Scope);
16622             New_Id := Id;
16623 
16624             --  If this is a repeated incomplete declaration, no further
16625             --  checks are possible.
16626 
16627             if Nkind (N) = N_Incomplete_Type_Declaration then
16628                return Prev;
16629             end if;
16630 
16631          --  Case of full declaration of incomplete type
16632 
16633          elsif Ekind (Prev) = E_Incomplete_Type
16634            and then (Ada_Version < Ada_2012
16635                       or else No (Full_View (Prev))
16636                       or else not Is_Private_Type (Full_View (Prev)))
16637          then
16638             --  Indicate that the incomplete declaration has a matching full
16639             --  declaration. The defining occurrence of the incomplete
16640             --  declaration remains the visible one, and the procedure
16641             --  Get_Full_View dereferences it whenever the type is used.
16642 
16643             if Present (Full_View (Prev)) then
16644                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
16645             end if;
16646 
16647             Set_Full_View (Prev, Id);
16648             Append_Entity (Id, Current_Scope);
16649             Set_Is_Public (Id, Is_Public (Prev));
16650             Set_Is_Internal (Id);
16651             New_Id := Prev;
16652 
16653             --  If the incomplete view is tagged, a class_wide type has been
16654             --  created already. Use it for the private type as well, in order
16655             --  to prevent multiple incompatible class-wide types that may be
16656             --  created for self-referential anonymous access components.
16657 
16658             if Is_Tagged_Type (Prev)
16659               and then Present (Class_Wide_Type (Prev))
16660             then
16661                Set_Ekind (Id, Ekind (Prev));         --  will be reset later
16662                Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
16663 
16664                --  The type of the classwide type is the current Id. Previously
16665                --  this was not done for private declarations because of order-
16666                --  of elaboration issues in the back-end, but gigi now handles
16667                --  this properly.
16668 
16669                Set_Etype (Class_Wide_Type (Id), Id);
16670             end if;
16671 
16672          --  Case of full declaration of private type
16673 
16674          else
16675             --  If the private type was a completion of an incomplete type then
16676             --  update Prev to reference the private type
16677 
16678             if Ada_Version >= Ada_2012
16679               and then Ekind (Prev) = E_Incomplete_Type
16680               and then Present (Full_View (Prev))
16681               and then Is_Private_Type (Full_View (Prev))
16682             then
16683                Prev := Full_View (Prev);
16684                Prev_Par := Parent (Prev);
16685             end if;
16686 
16687             if Nkind (N) = N_Full_Type_Declaration
16688               and then Nkind_In
16689                          (Type_Definition (N), N_Record_Definition,
16690                                                N_Derived_Type_Definition)
16691               and then Interface_Present (Type_Definition (N))
16692             then
16693                Error_Msg_N
16694                  ("completion of private type cannot be an interface", N);
16695             end if;
16696 
16697             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
16698                if Etype (Prev) /= Prev then
16699 
16700                   --  Prev is a private subtype or a derived type, and needs
16701                   --  no completion.
16702 
16703                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
16704                   New_Id := Id;
16705 
16706                elsif Ekind (Prev) = E_Private_Type
16707                  and then Nkind_In (N, N_Task_Type_Declaration,
16708                                        N_Protected_Type_Declaration)
16709                then
16710                   Error_Msg_N
16711                    ("completion of nonlimited type cannot be limited", N);
16712 
16713                elsif Ekind (Prev) = E_Record_Type_With_Private
16714                  and then Nkind_In (N, N_Task_Type_Declaration,
16715                                        N_Protected_Type_Declaration)
16716                then
16717                   if not Is_Limited_Record (Prev) then
16718                      Error_Msg_N
16719                         ("completion of nonlimited type cannot be limited", N);
16720 
16721                   elsif No (Interface_List (N)) then
16722                      Error_Msg_N
16723                         ("completion of tagged private type must be tagged",
16724                          N);
16725                   end if;
16726                end if;
16727 
16728             --  Ada 2005 (AI-251): Private extension declaration of a task
16729             --  type or a protected type. This case arises when covering
16730             --  interface types.
16731 
16732             elsif Nkind_In (N, N_Task_Type_Declaration,
16733                                N_Protected_Type_Declaration)
16734             then
16735                null;
16736 
16737             elsif Nkind (N) /= N_Full_Type_Declaration
16738               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
16739             then
16740                Error_Msg_N
16741                  ("full view of private extension must be an extension", N);
16742 
16743             elsif not (Abstract_Present (Parent (Prev)))
16744               and then Abstract_Present (Type_Definition (N))
16745             then
16746                Error_Msg_N
16747                  ("full view of non-abstract extension cannot be abstract", N);
16748             end if;
16749 
16750             if not In_Private_Part (Current_Scope) then
16751                Error_Msg_N
16752                  ("declaration of full view must appear in private part", N);
16753             end if;
16754 
16755             if Ada_Version >= Ada_2012 then
16756                Check_Duplicate_Aspects;
16757             end if;
16758 
16759             Copy_And_Swap (Prev, Id);
16760             Set_Has_Private_Declaration (Prev);
16761             Set_Has_Private_Declaration (Id);
16762 
16763             --  AI12-0133: Indicate whether we have a partial view with
16764             --  unknown discriminants, in which case initialization of objects
16765             --  of the type do not receive an invariant check.
16766 
16767             Set_Partial_View_Has_Unknown_Discr
16768               (Prev, Has_Unknown_Discriminants (Id));
16769 
16770             --  Preserve aspect and iterator flags that may have been set on
16771             --  the partial view.
16772 
16773             Set_Has_Delayed_Aspects (Prev, Has_Delayed_Aspects (Id));
16774             Set_Has_Implicit_Dereference (Prev, Has_Implicit_Dereference (Id));
16775 
16776             --  If no error, propagate freeze_node from private to full view.
16777             --  It may have been generated for an early operational item.
16778 
16779             if Present (Freeze_Node (Id))
16780               and then Serious_Errors_Detected = 0
16781               and then No (Full_View (Id))
16782             then
16783                Set_Freeze_Node (Prev, Freeze_Node (Id));
16784                Set_Freeze_Node (Id, Empty);
16785                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
16786             end if;
16787 
16788             Set_Full_View (Id, Prev);
16789             New_Id := Prev;
16790          end if;
16791 
16792          --  Verify that full declaration conforms to partial one
16793 
16794          if Is_Incomplete_Or_Private_Type (Prev)
16795            and then Present (Discriminant_Specifications (Prev_Par))
16796          then
16797             if Present (Discriminant_Specifications (N)) then
16798                if Ekind (Prev) = E_Incomplete_Type then
16799                   Check_Discriminant_Conformance (N, Prev, Prev);
16800                else
16801                   Check_Discriminant_Conformance (N, Prev, Id);
16802                end if;
16803 
16804             else
16805                Error_Msg_N
16806                  ("missing discriminants in full type declaration", N);
16807 
16808                --  To avoid cascaded errors on subsequent use, share the
16809                --  discriminants of the partial view.
16810 
16811                Set_Discriminant_Specifications (N,
16812                  Discriminant_Specifications (Prev_Par));
16813             end if;
16814          end if;
16815 
16816          --  A prior untagged partial view can have an associated class-wide
16817          --  type due to use of the class attribute, and in this case the full
16818          --  type must also be tagged. This Ada 95 usage is deprecated in favor
16819          --  of incomplete tagged declarations, but we check for it.
16820 
16821          if Is_Type (Prev)
16822            and then (Is_Tagged_Type (Prev)
16823                       or else Present (Class_Wide_Type (Prev)))
16824          then
16825             --  Ada 2012 (AI05-0162): A private type may be the completion of
16826             --  an incomplete type.
16827 
16828             if Ada_Version >= Ada_2012
16829               and then Is_Incomplete_Type (Prev)
16830               and then Nkind_In (N, N_Private_Type_Declaration,
16831                                     N_Private_Extension_Declaration)
16832             then
16833                --  No need to check private extensions since they are tagged
16834 
16835                if Nkind (N) = N_Private_Type_Declaration
16836                  and then not Tagged_Present (N)
16837                then
16838                   Tag_Mismatch;
16839                end if;
16840 
16841             --  The full declaration is either a tagged type (including
16842             --  a synchronized type that implements interfaces) or a
16843             --  type extension, otherwise this is an error.
16844 
16845             elsif Nkind_In (N, N_Task_Type_Declaration,
16846                                N_Protected_Type_Declaration)
16847             then
16848                if No (Interface_List (N)) and then not Error_Posted (N) then
16849                   Tag_Mismatch;
16850                end if;
16851 
16852             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
16853 
16854                --  Indicate that the previous declaration (tagged incomplete
16855                --  or private declaration) requires the same on the full one.
16856 
16857                if not Tagged_Present (Type_Definition (N)) then
16858                   Tag_Mismatch;
16859                   Set_Is_Tagged_Type (Id);
16860                end if;
16861 
16862             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
16863                if No (Record_Extension_Part (Type_Definition (N))) then
16864                   Error_Msg_NE
16865                     ("full declaration of } must be a record extension",
16866                      Prev, Id);
16867 
16868                   --  Set some attributes to produce a usable full view
16869 
16870                   Set_Is_Tagged_Type (Id);
16871                end if;
16872 
16873             else
16874                Tag_Mismatch;
16875             end if;
16876          end if;
16877 
16878          if Present (Prev)
16879            and then Nkind (Parent (Prev)) = N_Incomplete_Type_Declaration
16880            and then Present (Premature_Use (Parent (Prev)))
16881          then
16882             Error_Msg_Sloc := Sloc (N);
16883             Error_Msg_N
16884               ("\full declaration #", Premature_Use (Parent (Prev)));
16885          end if;
16886 
16887          return New_Id;
16888       end if;
16889    end Find_Type_Name;
16890 
16891    -------------------------
16892    -- Find_Type_Of_Object --
16893    -------------------------
16894 
16895    function Find_Type_Of_Object
16896      (Obj_Def     : Node_Id;
16897       Related_Nod : Node_Id) return Entity_Id
16898    is
16899       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
16900       P        : Node_Id := Parent (Obj_Def);
16901       T        : Entity_Id;
16902       Nam      : Name_Id;
16903 
16904    begin
16905       --  If the parent is a component_definition node we climb to the
16906       --  component_declaration node
16907 
16908       if Nkind (P) = N_Component_Definition then
16909          P := Parent (P);
16910       end if;
16911 
16912       --  Case of an anonymous array subtype
16913 
16914       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
16915                              N_Unconstrained_Array_Definition)
16916       then
16917          T := Empty;
16918          Array_Type_Declaration (T, Obj_Def);
16919 
16920       --  Create an explicit subtype whenever possible
16921 
16922       elsif Nkind (P) /= N_Component_Declaration
16923         and then Def_Kind = N_Subtype_Indication
16924       then
16925          --  Base name of subtype on object name, which will be unique in
16926          --  the current scope.
16927 
16928          --  If this is a duplicate declaration, return base type, to avoid
16929          --  generating duplicate anonymous types.
16930 
16931          if Error_Posted (P) then
16932             Analyze (Subtype_Mark (Obj_Def));
16933             return Entity (Subtype_Mark (Obj_Def));
16934          end if;
16935 
16936          Nam :=
16937             New_External_Name
16938              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
16939 
16940          T := Make_Defining_Identifier (Sloc (P), Nam);
16941 
16942          Insert_Action (Obj_Def,
16943            Make_Subtype_Declaration (Sloc (P),
16944              Defining_Identifier => T,
16945              Subtype_Indication  => Relocate_Node (Obj_Def)));
16946 
16947          --  This subtype may need freezing, and this will not be done
16948          --  automatically if the object declaration is not in declarative
16949          --  part. Since this is an object declaration, the type cannot always
16950          --  be frozen here. Deferred constants do not freeze their type
16951          --  (which often enough will be private).
16952 
16953          if Nkind (P) = N_Object_Declaration
16954            and then Constant_Present (P)
16955            and then No (Expression (P))
16956          then
16957             null;
16958 
16959          --  Here we freeze the base type of object type to catch premature use
16960          --  of discriminated private type without a full view.
16961 
16962          else
16963             Insert_Actions (Obj_Def, Freeze_Entity (Base_Type (T), P));
16964          end if;
16965 
16966       --  Ada 2005 AI-406: the object definition in an object declaration
16967       --  can be an access definition.
16968 
16969       elsif Def_Kind = N_Access_Definition then
16970          T := Access_Definition (Related_Nod, Obj_Def);
16971 
16972          Set_Is_Local_Anonymous_Access
16973            (T,
16974             V => (Ada_Version < Ada_2012)
16975                    or else (Nkind (P) /= N_Object_Declaration)
16976                    or else Is_Library_Level_Entity (Defining_Identifier (P)));
16977 
16978       --  Otherwise, the object definition is just a subtype_mark
16979 
16980       else
16981          T := Process_Subtype (Obj_Def, Related_Nod);
16982 
16983          --  If expansion is disabled an object definition that is an aggregate
16984          --  will not get expanded and may lead to scoping problems in the back
16985          --  end, if the object is referenced in an inner scope. In that case
16986          --  create an itype reference for the object definition now. This
16987          --  may be redundant in some cases, but harmless.
16988 
16989          if Is_Itype (T)
16990            and then Nkind (Related_Nod) = N_Object_Declaration
16991            and then ASIS_Mode
16992          then
16993             Build_Itype_Reference (T, Related_Nod);
16994          end if;
16995       end if;
16996 
16997       return T;
16998    end Find_Type_Of_Object;
16999 
17000    --------------------------------
17001    -- Find_Type_Of_Subtype_Indic --
17002    --------------------------------
17003 
17004    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
17005       Typ : Entity_Id;
17006 
17007    begin
17008       --  Case of subtype mark with a constraint
17009 
17010       if Nkind (S) = N_Subtype_Indication then
17011          Find_Type (Subtype_Mark (S));
17012          Typ := Entity (Subtype_Mark (S));
17013 
17014          if not
17015            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
17016          then
17017             Error_Msg_N
17018               ("incorrect constraint for this kind of type", Constraint (S));
17019             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
17020          end if;
17021 
17022       --  Otherwise we have a subtype mark without a constraint
17023 
17024       elsif Error_Posted (S) then
17025          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
17026          return Any_Type;
17027 
17028       else
17029          Find_Type (S);
17030          Typ := Entity (S);
17031       end if;
17032 
17033       --  Check No_Wide_Characters restriction
17034 
17035       Check_Wide_Character_Restriction (Typ, S);
17036 
17037       return Typ;
17038    end Find_Type_Of_Subtype_Indic;
17039 
17040    -------------------------------------
17041    -- Floating_Point_Type_Declaration --
17042    -------------------------------------
17043 
17044    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
17045       Digs          : constant Node_Id := Digits_Expression (Def);
17046       Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
17047       Digs_Val      : Uint;
17048       Base_Typ      : Entity_Id;
17049       Implicit_Base : Entity_Id;
17050       Bound         : Node_Id;
17051 
17052       function Can_Derive_From (E : Entity_Id) return Boolean;
17053       --  Find if given digits value, and possibly a specified range, allows
17054       --  derivation from specified type
17055 
17056       function Find_Base_Type return Entity_Id;
17057       --  Find a predefined base type that Def can derive from, or generate
17058       --  an error and substitute Long_Long_Float if none exists.
17059 
17060       ---------------------
17061       -- Can_Derive_From --
17062       ---------------------
17063 
17064       function Can_Derive_From (E : Entity_Id) return Boolean is
17065          Spec : constant Entity_Id := Real_Range_Specification (Def);
17066 
17067       begin
17068          --  Check specified "digits" constraint
17069 
17070          if Digs_Val > Digits_Value (E) then
17071             return False;
17072          end if;
17073 
17074          --  Check for matching range, if specified
17075 
17076          if Present (Spec) then
17077             if Expr_Value_R (Type_Low_Bound (E)) >
17078                Expr_Value_R (Low_Bound (Spec))
17079             then
17080                return False;
17081             end if;
17082 
17083             if Expr_Value_R (Type_High_Bound (E)) <
17084                Expr_Value_R (High_Bound (Spec))
17085             then
17086                return False;
17087             end if;
17088          end if;
17089 
17090          return True;
17091       end Can_Derive_From;
17092 
17093       --------------------
17094       -- Find_Base_Type --
17095       --------------------
17096 
17097       function Find_Base_Type return Entity_Id is
17098          Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
17099 
17100       begin
17101          --  Iterate over the predefined types in order, returning the first
17102          --  one that Def can derive from.
17103 
17104          while Present (Choice) loop
17105             if Can_Derive_From (Node (Choice)) then
17106                return Node (Choice);
17107             end if;
17108 
17109             Next_Elmt (Choice);
17110          end loop;
17111 
17112          --  If we can't derive from any existing type, use Long_Long_Float
17113          --  and give appropriate message explaining the problem.
17114 
17115          if Digs_Val > Max_Digs_Val then
17116             --  It might be the case that there is a type with the requested
17117             --  range, just not the combination of digits and range.
17118 
17119             Error_Msg_N
17120               ("no predefined type has requested range and precision",
17121                Real_Range_Specification (Def));
17122 
17123          else
17124             Error_Msg_N
17125               ("range too large for any predefined type",
17126                Real_Range_Specification (Def));
17127          end if;
17128 
17129          return Standard_Long_Long_Float;
17130       end Find_Base_Type;
17131 
17132    --  Start of processing for Floating_Point_Type_Declaration
17133 
17134    begin
17135       Check_Restriction (No_Floating_Point, Def);
17136 
17137       --  Create an implicit base type
17138 
17139       Implicit_Base :=
17140         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
17141 
17142       --  Analyze and verify digits value
17143 
17144       Analyze_And_Resolve (Digs, Any_Integer);
17145       Check_Digits_Expression (Digs);
17146       Digs_Val := Expr_Value (Digs);
17147 
17148       --  Process possible range spec and find correct type to derive from
17149 
17150       Process_Real_Range_Specification (Def);
17151 
17152       --  Check that requested number of digits is not too high.
17153 
17154       if Digs_Val > Max_Digs_Val then
17155 
17156          --  The check for Max_Base_Digits may be somewhat expensive, as it
17157          --  requires reading System, so only do it when necessary.
17158 
17159          declare
17160             Max_Base_Digits : constant Uint :=
17161                                 Expr_Value
17162                                   (Expression
17163                                      (Parent (RTE (RE_Max_Base_Digits))));
17164 
17165          begin
17166             if Digs_Val > Max_Base_Digits then
17167                Error_Msg_Uint_1 := Max_Base_Digits;
17168                Error_Msg_N ("digits value out of range, maximum is ^", Digs);
17169 
17170             elsif No (Real_Range_Specification (Def)) then
17171                Error_Msg_Uint_1 := Max_Digs_Val;
17172                Error_Msg_N ("types with more than ^ digits need range spec "
17173                  & "(RM 3.5.7(6))", Digs);
17174             end if;
17175          end;
17176       end if;
17177 
17178       --  Find a suitable type to derive from or complain and use a substitute
17179 
17180       Base_Typ := Find_Base_Type;
17181 
17182       --  If there are bounds given in the declaration use them as the bounds
17183       --  of the type, otherwise use the bounds of the predefined base type
17184       --  that was chosen based on the Digits value.
17185 
17186       if Present (Real_Range_Specification (Def)) then
17187          Set_Scalar_Range (T, Real_Range_Specification (Def));
17188          Set_Is_Constrained (T);
17189 
17190          --  The bounds of this range must be converted to machine numbers
17191          --  in accordance with RM 4.9(38).
17192 
17193          Bound := Type_Low_Bound (T);
17194 
17195          if Nkind (Bound) = N_Real_Literal then
17196             Set_Realval
17197               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
17198             Set_Is_Machine_Number (Bound);
17199          end if;
17200 
17201          Bound := Type_High_Bound (T);
17202 
17203          if Nkind (Bound) = N_Real_Literal then
17204             Set_Realval
17205               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
17206             Set_Is_Machine_Number (Bound);
17207          end if;
17208 
17209       else
17210          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
17211       end if;
17212 
17213       --  Complete definition of implicit base and declared first subtype. The
17214       --  inheritance of the rep item chain ensures that SPARK-related pragmas
17215       --  are not clobbered when the floating point type acts as a full view of
17216       --  a private type.
17217 
17218       Set_Etype              (Implicit_Base,                 Base_Typ);
17219       Set_Scalar_Range       (Implicit_Base, Scalar_Range   (Base_Typ));
17220       Set_Size_Info          (Implicit_Base,                 Base_Typ);
17221       Set_RM_Size            (Implicit_Base, RM_Size        (Base_Typ));
17222       Set_First_Rep_Item     (Implicit_Base, First_Rep_Item (Base_Typ));
17223       Set_Digits_Value       (Implicit_Base, Digits_Value   (Base_Typ));
17224       Set_Float_Rep          (Implicit_Base, Float_Rep      (Base_Typ));
17225 
17226       Set_Ekind              (T, E_Floating_Point_Subtype);
17227       Set_Etype              (T,          Implicit_Base);
17228       Set_Size_Info          (T,          Implicit_Base);
17229       Set_RM_Size            (T, RM_Size (Implicit_Base));
17230       Inherit_Rep_Item_Chain (T,          Implicit_Base);
17231       Set_Digits_Value       (T, Digs_Val);
17232    end Floating_Point_Type_Declaration;
17233 
17234    ----------------------------
17235    -- Get_Discriminant_Value --
17236    ----------------------------
17237 
17238    --  This is the situation:
17239 
17240    --  There is a non-derived type
17241 
17242    --       type T0 (Dx, Dy, Dz...)
17243 
17244    --  There are zero or more levels of derivation, with each derivation
17245    --  either purely inheriting the discriminants, or defining its own.
17246 
17247    --       type Ti      is new Ti-1
17248    --  or
17249    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
17250    --  or
17251    --       subtype Ti is ...
17252 
17253    --  The subtype issue is avoided by the use of Original_Record_Component,
17254    --  and the fact that derived subtypes also derive the constraints.
17255 
17256    --  This chain leads back from
17257 
17258    --       Typ_For_Constraint
17259 
17260    --  Typ_For_Constraint has discriminants, and the value for each
17261    --  discriminant is given by its corresponding Elmt of Constraints.
17262 
17263    --  Discriminant is some discriminant in this hierarchy
17264 
17265    --  We need to return its value
17266 
17267    --  We do this by recursively searching each level, and looking for
17268    --  Discriminant. Once we get to the bottom, we start backing up
17269    --  returning the value for it which may in turn be a discriminant
17270    --  further up, so on the backup we continue the substitution.
17271 
17272    function Get_Discriminant_Value
17273      (Discriminant       : Entity_Id;
17274       Typ_For_Constraint : Entity_Id;
17275       Constraint         : Elist_Id) return Node_Id
17276    is
17277       function Root_Corresponding_Discriminant
17278         (Discr : Entity_Id) return Entity_Id;
17279       --  Given a discriminant, traverse the chain of inherited discriminants
17280       --  and return the topmost discriminant.
17281 
17282       function Search_Derivation_Levels
17283         (Ti                    : Entity_Id;
17284          Discrim_Values        : Elist_Id;
17285          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
17286       --  This is the routine that performs the recursive search of levels
17287       --  as described above.
17288 
17289       -------------------------------------
17290       -- Root_Corresponding_Discriminant --
17291       -------------------------------------
17292 
17293       function Root_Corresponding_Discriminant
17294         (Discr : Entity_Id) return Entity_Id
17295       is
17296          D : Entity_Id;
17297 
17298       begin
17299          D := Discr;
17300          while Present (Corresponding_Discriminant (D)) loop
17301             D := Corresponding_Discriminant (D);
17302          end loop;
17303 
17304          return D;
17305       end Root_Corresponding_Discriminant;
17306 
17307       ------------------------------
17308       -- Search_Derivation_Levels --
17309       ------------------------------
17310 
17311       function Search_Derivation_Levels
17312         (Ti                    : Entity_Id;
17313          Discrim_Values        : Elist_Id;
17314          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
17315       is
17316          Assoc          : Elmt_Id;
17317          Disc           : Entity_Id;
17318          Result         : Node_Or_Entity_Id;
17319          Result_Entity  : Node_Id;
17320 
17321       begin
17322          --  If inappropriate type, return Error, this happens only in
17323          --  cascaded error situations, and we want to avoid a blow up.
17324 
17325          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
17326             return Error;
17327          end if;
17328 
17329          --  Look deeper if possible. Use Stored_Constraints only for
17330          --  untagged types. For tagged types use the given constraint.
17331          --  This asymmetry needs explanation???
17332 
17333          if not Stored_Discrim_Values
17334            and then Present (Stored_Constraint (Ti))
17335            and then not Is_Tagged_Type (Ti)
17336          then
17337             Result :=
17338               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
17339          else
17340             declare
17341                Td : constant Entity_Id := Etype (Ti);
17342 
17343             begin
17344                if Td = Ti then
17345                   Result := Discriminant;
17346 
17347                else
17348                   if Present (Stored_Constraint (Ti)) then
17349                      Result :=
17350                         Search_Derivation_Levels
17351                           (Td, Stored_Constraint (Ti), True);
17352                   else
17353                      Result :=
17354                         Search_Derivation_Levels
17355                           (Td, Discrim_Values, Stored_Discrim_Values);
17356                   end if;
17357                end if;
17358             end;
17359          end if;
17360 
17361          --  Extra underlying places to search, if not found above. For
17362          --  concurrent types, the relevant discriminant appears in the
17363          --  corresponding record. For a type derived from a private type
17364          --  without discriminant, the full view inherits the discriminants
17365          --  of the full view of the parent.
17366 
17367          if Result = Discriminant then
17368             if Is_Concurrent_Type (Ti)
17369               and then Present (Corresponding_Record_Type (Ti))
17370             then
17371                Result :=
17372                  Search_Derivation_Levels (
17373                    Corresponding_Record_Type (Ti),
17374                    Discrim_Values,
17375                    Stored_Discrim_Values);
17376 
17377             elsif Is_Private_Type (Ti)
17378               and then not Has_Discriminants (Ti)
17379               and then Present (Full_View (Ti))
17380               and then Etype (Full_View (Ti)) /= Ti
17381             then
17382                Result :=
17383                  Search_Derivation_Levels (
17384                    Full_View (Ti),
17385                    Discrim_Values,
17386                    Stored_Discrim_Values);
17387             end if;
17388          end if;
17389 
17390          --  If Result is not a (reference to a) discriminant, return it,
17391          --  otherwise set Result_Entity to the discriminant.
17392 
17393          if Nkind (Result) = N_Defining_Identifier then
17394             pragma Assert (Result = Discriminant);
17395             Result_Entity := Result;
17396 
17397          else
17398             if not Denotes_Discriminant (Result) then
17399                return Result;
17400             end if;
17401 
17402             Result_Entity := Entity (Result);
17403          end if;
17404 
17405          --  See if this level of derivation actually has discriminants because
17406          --  tagged derivations can add them, hence the lower levels need not
17407          --  have any.
17408 
17409          if not Has_Discriminants (Ti) then
17410             return Result;
17411          end if;
17412 
17413          --  Scan Ti's discriminants for Result_Entity, and return its
17414          --  corresponding value, if any.
17415 
17416          Result_Entity := Original_Record_Component (Result_Entity);
17417 
17418          Assoc := First_Elmt (Discrim_Values);
17419 
17420          if Stored_Discrim_Values then
17421             Disc := First_Stored_Discriminant (Ti);
17422          else
17423             Disc := First_Discriminant (Ti);
17424          end if;
17425 
17426          while Present (Disc) loop
17427             pragma Assert (Present (Assoc));
17428 
17429             if Original_Record_Component (Disc) = Result_Entity then
17430                return Node (Assoc);
17431             end if;
17432 
17433             Next_Elmt (Assoc);
17434 
17435             if Stored_Discrim_Values then
17436                Next_Stored_Discriminant (Disc);
17437             else
17438                Next_Discriminant (Disc);
17439             end if;
17440          end loop;
17441 
17442          --  Could not find it
17443 
17444          return Result;
17445       end Search_Derivation_Levels;
17446 
17447       --  Local Variables
17448 
17449       Result : Node_Or_Entity_Id;
17450 
17451    --  Start of processing for Get_Discriminant_Value
17452 
17453    begin
17454       --  ??? This routine is a gigantic mess and will be deleted. For the
17455       --  time being just test for the trivial case before calling recurse.
17456 
17457       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
17458          declare
17459             D : Entity_Id;
17460             E : Elmt_Id;
17461 
17462          begin
17463             D := First_Discriminant (Typ_For_Constraint);
17464             E := First_Elmt (Constraint);
17465             while Present (D) loop
17466                if Chars (D) = Chars (Discriminant) then
17467                   return Node (E);
17468                end if;
17469 
17470                Next_Discriminant (D);
17471                Next_Elmt (E);
17472             end loop;
17473          end;
17474       end if;
17475 
17476       Result := Search_Derivation_Levels
17477         (Typ_For_Constraint, Constraint, False);
17478 
17479       --  ??? hack to disappear when this routine is gone
17480 
17481       if Nkind (Result) = N_Defining_Identifier then
17482          declare
17483             D : Entity_Id;
17484             E : Elmt_Id;
17485 
17486          begin
17487             D := First_Discriminant (Typ_For_Constraint);
17488             E := First_Elmt (Constraint);
17489             while Present (D) loop
17490                if Root_Corresponding_Discriminant (D) = Discriminant then
17491                   return Node (E);
17492                end if;
17493 
17494                Next_Discriminant (D);
17495                Next_Elmt (E);
17496             end loop;
17497          end;
17498       end if;
17499 
17500       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
17501       return Result;
17502    end Get_Discriminant_Value;
17503 
17504    --------------------------
17505    -- Has_Range_Constraint --
17506    --------------------------
17507 
17508    function Has_Range_Constraint (N : Node_Id) return Boolean is
17509       C : constant Node_Id := Constraint (N);
17510 
17511    begin
17512       if Nkind (C) = N_Range_Constraint then
17513          return True;
17514 
17515       elsif Nkind (C) = N_Digits_Constraint then
17516          return
17517             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
17518               or else Present (Range_Constraint (C));
17519 
17520       elsif Nkind (C) = N_Delta_Constraint then
17521          return Present (Range_Constraint (C));
17522 
17523       else
17524          return False;
17525       end if;
17526    end Has_Range_Constraint;
17527 
17528    ------------------------
17529    -- Inherit_Components --
17530    ------------------------
17531 
17532    function Inherit_Components
17533      (N             : Node_Id;
17534       Parent_Base   : Entity_Id;
17535       Derived_Base  : Entity_Id;
17536       Is_Tagged     : Boolean;
17537       Inherit_Discr : Boolean;
17538       Discs         : Elist_Id) return Elist_Id
17539    is
17540       Assoc_List : constant Elist_Id := New_Elmt_List;
17541 
17542       procedure Inherit_Component
17543         (Old_C          : Entity_Id;
17544          Plain_Discrim  : Boolean := False;
17545          Stored_Discrim : Boolean := False);
17546       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
17547       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
17548       --  True, Old_C is a stored discriminant. If they are both false then
17549       --  Old_C is a regular component.
17550 
17551       -----------------------
17552       -- Inherit_Component --
17553       -----------------------
17554 
17555       procedure Inherit_Component
17556         (Old_C          : Entity_Id;
17557          Plain_Discrim  : Boolean := False;
17558          Stored_Discrim : Boolean := False)
17559       is
17560          procedure Set_Anonymous_Type (Id : Entity_Id);
17561          --  Id denotes the entity of an access discriminant or anonymous
17562          --  access component. Set the type of Id to either the same type of
17563          --  Old_C or create a new one depending on whether the parent and
17564          --  the child types are in the same scope.
17565 
17566          ------------------------
17567          -- Set_Anonymous_Type --
17568          ------------------------
17569 
17570          procedure Set_Anonymous_Type (Id : Entity_Id) is
17571             Old_Typ : constant Entity_Id := Etype (Old_C);
17572 
17573          begin
17574             if Scope (Parent_Base) = Scope (Derived_Base) then
17575                Set_Etype (Id, Old_Typ);
17576 
17577             --  The parent and the derived type are in two different scopes.
17578             --  Reuse the type of the original discriminant / component by
17579             --  copying it in order to preserve all attributes.
17580 
17581             else
17582                declare
17583                   Typ : constant Entity_Id := New_Copy (Old_Typ);
17584 
17585                begin
17586                   Set_Etype (Id, Typ);
17587 
17588                   --  Since we do not generate component declarations for
17589                   --  inherited components, associate the itype with the
17590                   --  derived type.
17591 
17592                   Set_Associated_Node_For_Itype (Typ, Parent (Derived_Base));
17593                   Set_Scope                     (Typ, Derived_Base);
17594                end;
17595             end if;
17596          end Set_Anonymous_Type;
17597 
17598          --  Local variables and constants
17599 
17600          New_C : constant Entity_Id := New_Copy (Old_C);
17601 
17602          Corr_Discrim : Entity_Id;
17603          Discrim      : Entity_Id;
17604 
17605       --  Start of processing for Inherit_Component
17606 
17607       begin
17608          pragma Assert (not Is_Tagged or not Stored_Discrim);
17609 
17610          Set_Parent (New_C, Parent (Old_C));
17611 
17612          --  Regular discriminants and components must be inserted in the scope
17613          --  of the Derived_Base. Do it here.
17614 
17615          if not Stored_Discrim then
17616             Enter_Name (New_C);
17617          end if;
17618 
17619          --  For tagged types the Original_Record_Component must point to
17620          --  whatever this field was pointing to in the parent type. This has
17621          --  already been achieved by the call to New_Copy above.
17622 
17623          if not Is_Tagged then
17624             Set_Original_Record_Component (New_C, New_C);
17625          end if;
17626 
17627          --  Set the proper type of an access discriminant
17628 
17629          if Ekind (New_C) = E_Discriminant
17630            and then Ekind (Etype (New_C)) = E_Anonymous_Access_Type
17631          then
17632             Set_Anonymous_Type (New_C);
17633          end if;
17634 
17635          --  If we have inherited a component then see if its Etype contains
17636          --  references to Parent_Base discriminants. In this case, replace
17637          --  these references with the constraints given in Discs. We do not
17638          --  do this for the partial view of private types because this is
17639          --  not needed (only the components of the full view will be used
17640          --  for code generation) and cause problem. We also avoid this
17641          --  transformation in some error situations.
17642 
17643          if Ekind (New_C) = E_Component then
17644 
17645             --  Set the proper type of an anonymous access component
17646 
17647             if Ekind (Etype (New_C)) = E_Anonymous_Access_Type then
17648                Set_Anonymous_Type (New_C);
17649 
17650             elsif (Is_Private_Type (Derived_Base)
17651                     and then not Is_Generic_Type (Derived_Base))
17652               or else (Is_Empty_Elmt_List (Discs)
17653                         and then not Expander_Active)
17654             then
17655                Set_Etype (New_C, Etype (Old_C));
17656 
17657             else
17658                --  The current component introduces a circularity of the
17659                --  following kind:
17660 
17661                --     limited with Pack_2;
17662                --     package Pack_1 is
17663                --        type T_1 is tagged record
17664                --           Comp : access Pack_2.T_2;
17665                --           ...
17666                --        end record;
17667                --     end Pack_1;
17668 
17669                --     with Pack_1;
17670                --     package Pack_2 is
17671                --        type T_2 is new Pack_1.T_1 with ...;
17672                --     end Pack_2;
17673 
17674                Set_Etype
17675                  (New_C,
17676                   Constrain_Component_Type
17677                     (Old_C, Derived_Base, N, Parent_Base, Discs));
17678             end if;
17679          end if;
17680 
17681          --  In derived tagged types it is illegal to reference a non
17682          --  discriminant component in the parent type. To catch this, mark
17683          --  these components with an Ekind of E_Void. This will be reset in
17684          --  Record_Type_Definition after processing the record extension of
17685          --  the derived type.
17686 
17687          --  If the declaration is a private extension, there is no further
17688          --  record extension to process, and the components retain their
17689          --  current kind, because they are visible at this point.
17690 
17691          if Is_Tagged and then Ekind (New_C) = E_Component
17692            and then Nkind (N) /= N_Private_Extension_Declaration
17693          then
17694             Set_Ekind (New_C, E_Void);
17695          end if;
17696 
17697          if Plain_Discrim then
17698             Set_Corresponding_Discriminant (New_C, Old_C);
17699             Build_Discriminal (New_C);
17700 
17701          --  If we are explicitly inheriting a stored discriminant it will be
17702          --  completely hidden.
17703 
17704          elsif Stored_Discrim then
17705             Set_Corresponding_Discriminant (New_C, Empty);
17706             Set_Discriminal (New_C, Empty);
17707             Set_Is_Completely_Hidden (New_C);
17708 
17709             --  Set the Original_Record_Component of each discriminant in the
17710             --  derived base to point to the corresponding stored that we just
17711             --  created.
17712 
17713             Discrim := First_Discriminant (Derived_Base);
17714             while Present (Discrim) loop
17715                Corr_Discrim := Corresponding_Discriminant (Discrim);
17716 
17717                --  Corr_Discrim could be missing in an error situation
17718 
17719                if Present (Corr_Discrim)
17720                  and then Original_Record_Component (Corr_Discrim) = Old_C
17721                then
17722                   Set_Original_Record_Component (Discrim, New_C);
17723                end if;
17724 
17725                Next_Discriminant (Discrim);
17726             end loop;
17727 
17728             Append_Entity (New_C, Derived_Base);
17729          end if;
17730 
17731          if not Is_Tagged then
17732             Append_Elmt (Old_C, Assoc_List);
17733             Append_Elmt (New_C, Assoc_List);
17734          end if;
17735       end Inherit_Component;
17736 
17737       --  Variables local to Inherit_Component
17738 
17739       Loc : constant Source_Ptr := Sloc (N);
17740 
17741       Parent_Discrim : Entity_Id;
17742       Stored_Discrim : Entity_Id;
17743       D              : Entity_Id;
17744       Component      : Entity_Id;
17745 
17746    --  Start of processing for Inherit_Components
17747 
17748    begin
17749       if not Is_Tagged then
17750          Append_Elmt (Parent_Base,  Assoc_List);
17751          Append_Elmt (Derived_Base, Assoc_List);
17752       end if;
17753 
17754       --  Inherit parent discriminants if needed
17755 
17756       if Inherit_Discr then
17757          Parent_Discrim := First_Discriminant (Parent_Base);
17758          while Present (Parent_Discrim) loop
17759             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
17760             Next_Discriminant (Parent_Discrim);
17761          end loop;
17762       end if;
17763 
17764       --  Create explicit stored discrims for untagged types when necessary
17765 
17766       if not Has_Unknown_Discriminants (Derived_Base)
17767         and then Has_Discriminants (Parent_Base)
17768         and then not Is_Tagged
17769         and then
17770           (not Inherit_Discr
17771             or else First_Discriminant (Parent_Base) /=
17772                     First_Stored_Discriminant (Parent_Base))
17773       then
17774          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
17775          while Present (Stored_Discrim) loop
17776             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
17777             Next_Stored_Discriminant (Stored_Discrim);
17778          end loop;
17779       end if;
17780 
17781       --  See if we can apply the second transformation for derived types, as
17782       --  explained in point 6. in the comments above Build_Derived_Record_Type
17783       --  This is achieved by appending Derived_Base discriminants into Discs,
17784       --  which has the side effect of returning a non empty Discs list to the
17785       --  caller of Inherit_Components, which is what we want. This must be
17786       --  done for private derived types if there are explicit stored
17787       --  discriminants, to ensure that we can retrieve the values of the
17788       --  constraints provided in the ancestors.
17789 
17790       if Inherit_Discr
17791         and then Is_Empty_Elmt_List (Discs)
17792         and then Present (First_Discriminant (Derived_Base))
17793         and then
17794           (not Is_Private_Type (Derived_Base)
17795             or else Is_Completely_Hidden
17796                       (First_Stored_Discriminant (Derived_Base))
17797             or else Is_Generic_Type (Derived_Base))
17798       then
17799          D := First_Discriminant (Derived_Base);
17800          while Present (D) loop
17801             Append_Elmt (New_Occurrence_Of (D, Loc), Discs);
17802             Next_Discriminant (D);
17803          end loop;
17804       end if;
17805 
17806       --  Finally, inherit non-discriminant components unless they are not
17807       --  visible because defined or inherited from the full view of the
17808       --  parent. Don't inherit the _parent field of the parent type.
17809 
17810       Component := First_Entity (Parent_Base);
17811       while Present (Component) loop
17812 
17813          --  Ada 2005 (AI-251): Do not inherit components associated with
17814          --  secondary tags of the parent.
17815 
17816          if Ekind (Component) = E_Component
17817            and then Present (Related_Type (Component))
17818          then
17819             null;
17820 
17821          elsif Ekind (Component) /= E_Component
17822            or else Chars (Component) = Name_uParent
17823          then
17824             null;
17825 
17826          --  If the derived type is within the parent type's declarative
17827          --  region, then the components can still be inherited even though
17828          --  they aren't visible at this point. This can occur for cases
17829          --  such as within public child units where the components must
17830          --  become visible upon entering the child unit's private part.
17831 
17832          elsif not Is_Visible_Component (Component)
17833            and then not In_Open_Scopes (Scope (Parent_Base))
17834          then
17835             null;
17836 
17837          elsif Ekind_In (Derived_Base, E_Private_Type,
17838                                        E_Limited_Private_Type)
17839          then
17840             null;
17841 
17842          else
17843             Inherit_Component (Component);
17844          end if;
17845 
17846          Next_Entity (Component);
17847       end loop;
17848 
17849       --  For tagged derived types, inherited discriminants cannot be used in
17850       --  component declarations of the record extension part. To achieve this
17851       --  we mark the inherited discriminants as not visible.
17852 
17853       if Is_Tagged and then Inherit_Discr then
17854          D := First_Discriminant (Derived_Base);
17855          while Present (D) loop
17856             Set_Is_Immediately_Visible (D, False);
17857             Next_Discriminant (D);
17858          end loop;
17859       end if;
17860 
17861       return Assoc_List;
17862    end Inherit_Components;
17863 
17864    -----------------------------
17865    -- Inherit_Predicate_Flags --
17866    -----------------------------
17867 
17868    procedure Inherit_Predicate_Flags (Subt, Par : Entity_Id) is
17869    begin
17870       Set_Has_Predicates (Subt, Has_Predicates (Par));
17871       Set_Has_Static_Predicate_Aspect
17872         (Subt, Has_Static_Predicate_Aspect (Par));
17873       Set_Has_Dynamic_Predicate_Aspect
17874         (Subt, Has_Dynamic_Predicate_Aspect (Par));
17875    end Inherit_Predicate_Flags;
17876 
17877    ----------------------
17878    -- Is_EVF_Procedure --
17879    ----------------------
17880 
17881    function Is_EVF_Procedure (Subp : Entity_Id) return Boolean is
17882       Formal : Entity_Id;
17883 
17884    begin
17885       --  Examine the formals of an Extensions_Visible False procedure looking
17886       --  for a controlling OUT parameter.
17887 
17888       if Ekind (Subp) = E_Procedure
17889         and then Extensions_Visible_Status (Subp) = Extensions_Visible_False
17890       then
17891          Formal := First_Formal (Subp);
17892          while Present (Formal) loop
17893             if Ekind (Formal) = E_Out_Parameter
17894               and then Is_Controlling_Formal (Formal)
17895             then
17896                return True;
17897             end if;
17898 
17899             Next_Formal (Formal);
17900          end loop;
17901       end if;
17902 
17903       return False;
17904    end Is_EVF_Procedure;
17905 
17906    -----------------------
17907    -- Is_Null_Extension --
17908    -----------------------
17909 
17910    function Is_Null_Extension (T : Entity_Id) return Boolean is
17911       Type_Decl : constant Node_Id := Parent (Base_Type (T));
17912       Comp_List : Node_Id;
17913       Comp      : Node_Id;
17914 
17915    begin
17916       if Nkind (Type_Decl) /= N_Full_Type_Declaration
17917         or else not Is_Tagged_Type (T)
17918         or else Nkind (Type_Definition (Type_Decl)) /=
17919                                               N_Derived_Type_Definition
17920         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
17921       then
17922          return False;
17923       end if;
17924 
17925       Comp_List :=
17926         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
17927 
17928       if Present (Discriminant_Specifications (Type_Decl)) then
17929          return False;
17930 
17931       elsif Present (Comp_List)
17932         and then Is_Non_Empty_List (Component_Items (Comp_List))
17933       then
17934          Comp := First (Component_Items (Comp_List));
17935 
17936          --  Only user-defined components are relevant. The component list
17937          --  may also contain a parent component and internal components
17938          --  corresponding to secondary tags, but these do not determine
17939          --  whether this is a null extension.
17940 
17941          while Present (Comp) loop
17942             if Comes_From_Source (Comp) then
17943                return False;
17944             end if;
17945 
17946             Next (Comp);
17947          end loop;
17948 
17949          return True;
17950 
17951       else
17952          return True;
17953       end if;
17954    end Is_Null_Extension;
17955 
17956    ------------------------------
17957    -- Is_Valid_Constraint_Kind --
17958    ------------------------------
17959 
17960    function Is_Valid_Constraint_Kind
17961      (T_Kind          : Type_Kind;
17962       Constraint_Kind : Node_Kind) return Boolean
17963    is
17964    begin
17965       case T_Kind is
17966          when Enumeration_Kind |
17967               Integer_Kind =>
17968             return Constraint_Kind = N_Range_Constraint;
17969 
17970          when Decimal_Fixed_Point_Kind =>
17971             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
17972                                               N_Range_Constraint);
17973 
17974          when Ordinary_Fixed_Point_Kind =>
17975             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
17976                                               N_Range_Constraint);
17977 
17978          when Float_Kind =>
17979             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
17980                                               N_Range_Constraint);
17981 
17982          when Access_Kind       |
17983               Array_Kind        |
17984               E_Record_Type     |
17985               E_Record_Subtype  |
17986               Class_Wide_Kind   |
17987               E_Incomplete_Type |
17988               Private_Kind      |
17989               Concurrent_Kind  =>
17990             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
17991 
17992          when others =>
17993             return True; -- Error will be detected later
17994       end case;
17995    end Is_Valid_Constraint_Kind;
17996 
17997    --------------------------
17998    -- Is_Visible_Component --
17999    --------------------------
18000 
18001    function Is_Visible_Component
18002      (C : Entity_Id;
18003       N : Node_Id := Empty) return Boolean
18004    is
18005       Original_Comp : Entity_Id := Empty;
18006       Original_Type : Entity_Id;
18007       Type_Scope    : Entity_Id;
18008 
18009       function Is_Local_Type (Typ : Entity_Id) return Boolean;
18010       --  Check whether parent type of inherited component is declared locally,
18011       --  possibly within a nested package or instance. The current scope is
18012       --  the derived record itself.
18013 
18014       -------------------
18015       -- Is_Local_Type --
18016       -------------------
18017 
18018       function Is_Local_Type (Typ : Entity_Id) return Boolean is
18019          Scop : Entity_Id;
18020 
18021       begin
18022          Scop := Scope (Typ);
18023          while Present (Scop)
18024            and then Scop /= Standard_Standard
18025          loop
18026             if Scop = Scope (Current_Scope) then
18027                return True;
18028             end if;
18029 
18030             Scop := Scope (Scop);
18031          end loop;
18032 
18033          return False;
18034       end Is_Local_Type;
18035 
18036    --  Start of processing for Is_Visible_Component
18037 
18038    begin
18039       if Ekind_In (C, E_Component, E_Discriminant) then
18040          Original_Comp := Original_Record_Component (C);
18041       end if;
18042 
18043       if No (Original_Comp) then
18044 
18045          --  Premature usage, or previous error
18046 
18047          return False;
18048 
18049       else
18050          Original_Type := Scope (Original_Comp);
18051          Type_Scope    := Scope (Base_Type (Scope (C)));
18052       end if;
18053 
18054       --  This test only concerns tagged types
18055 
18056       if not Is_Tagged_Type (Original_Type) then
18057          return True;
18058 
18059       --  If it is _Parent or _Tag, there is no visibility issue
18060 
18061       elsif not Comes_From_Source (Original_Comp) then
18062          return True;
18063 
18064       --  Discriminants are visible unless the (private) type has unknown
18065       --  discriminants. If the discriminant reference is inserted for a
18066       --  discriminant check on a full view it is also visible.
18067 
18068       elsif Ekind (Original_Comp) = E_Discriminant
18069         and then
18070           (not Has_Unknown_Discriminants (Original_Type)
18071             or else (Present (N)
18072                       and then Nkind (N) = N_Selected_Component
18073                       and then Nkind (Prefix (N)) = N_Type_Conversion
18074                       and then not Comes_From_Source (Prefix (N))))
18075       then
18076          return True;
18077 
18078       --  In the body of an instantiation, no need to check for the visibility
18079       --  of a component.
18080 
18081       elsif In_Instance_Body then
18082          return True;
18083 
18084       --  If the component has been declared in an ancestor which is currently
18085       --  a private type, then it is not visible. The same applies if the
18086       --  component's containing type is not in an open scope and the original
18087       --  component's enclosing type is a visible full view of a private type
18088       --  (which can occur in cases where an attempt is being made to reference
18089       --  a component in a sibling package that is inherited from a visible
18090       --  component of a type in an ancestor package; the component in the
18091       --  sibling package should not be visible even though the component it
18092       --  inherited from is visible). This does not apply however in the case
18093       --  where the scope of the type is a private child unit, or when the
18094       --  parent comes from a local package in which the ancestor is currently
18095       --  visible. The latter suppression of visibility is needed for cases
18096       --  that are tested in B730006.
18097 
18098       elsif Is_Private_Type (Original_Type)
18099         or else
18100           (not Is_Private_Descendant (Type_Scope)
18101             and then not In_Open_Scopes (Type_Scope)
18102             and then Has_Private_Declaration (Original_Type))
18103       then
18104          --  If the type derives from an entity in a formal package, there
18105          --  are no additional visible components.
18106 
18107          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
18108             N_Formal_Package_Declaration
18109          then
18110             return False;
18111 
18112          --  if we are not in the private part of the current package, there
18113          --  are no additional visible components.
18114 
18115          elsif Ekind (Scope (Current_Scope)) = E_Package
18116            and then not In_Private_Part (Scope (Current_Scope))
18117          then
18118             return False;
18119          else
18120             return
18121               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
18122                 and then In_Open_Scopes (Scope (Original_Type))
18123                 and then Is_Local_Type (Type_Scope);
18124          end if;
18125 
18126       --  There is another weird way in which a component may be invisible when
18127       --  the private and the full view are not derived from the same ancestor.
18128       --  Here is an example :
18129 
18130       --       type A1 is tagged      record F1 : integer; end record;
18131       --       type A2 is new A1 with record F2 : integer; end record;
18132       --       type T is new A1 with private;
18133       --     private
18134       --       type T is new A2 with null record;
18135 
18136       --  In this case, the full view of T inherits F1 and F2 but the private
18137       --  view inherits only F1
18138 
18139       else
18140          declare
18141             Ancestor : Entity_Id := Scope (C);
18142 
18143          begin
18144             loop
18145                if Ancestor = Original_Type then
18146                   return True;
18147 
18148                --  The ancestor may have a partial view of the original type,
18149                --  but if the full view is in scope, as in a child body, the
18150                --  component is visible.
18151 
18152                elsif In_Private_Part (Scope (Original_Type))
18153                  and then Full_View (Ancestor) = Original_Type
18154                then
18155                   return True;
18156 
18157                elsif Ancestor = Etype (Ancestor) then
18158 
18159                   --  No further ancestors to examine
18160 
18161                   return False;
18162                end if;
18163 
18164                Ancestor := Etype (Ancestor);
18165             end loop;
18166          end;
18167       end if;
18168    end Is_Visible_Component;
18169 
18170    --------------------------
18171    -- Make_Class_Wide_Type --
18172    --------------------------
18173 
18174    procedure Make_Class_Wide_Type (T : Entity_Id) is
18175       CW_Type : Entity_Id;
18176       CW_Name : Name_Id;
18177       Next_E  : Entity_Id;
18178 
18179    begin
18180       if Present (Class_Wide_Type (T)) then
18181 
18182          --  The class-wide type is a partially decorated entity created for a
18183          --  unanalyzed tagged type referenced through a limited with clause.
18184          --  When the tagged type is analyzed, its class-wide type needs to be
18185          --  redecorated. Note that we reuse the entity created by Decorate_
18186          --  Tagged_Type in order to preserve all links.
18187 
18188          if Materialize_Entity (Class_Wide_Type (T)) then
18189             CW_Type := Class_Wide_Type (T);
18190             Set_Materialize_Entity (CW_Type, False);
18191 
18192          --  The class wide type can have been defined by the partial view, in
18193          --  which case everything is already done.
18194 
18195          else
18196             return;
18197          end if;
18198 
18199       --  Default case, we need to create a new class-wide type
18200 
18201       else
18202          CW_Type :=
18203            New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
18204       end if;
18205 
18206       --  Inherit root type characteristics
18207 
18208       CW_Name := Chars (CW_Type);
18209       Next_E  := Next_Entity (CW_Type);
18210       Copy_Node (T, CW_Type);
18211       Set_Comes_From_Source (CW_Type, False);
18212       Set_Chars (CW_Type, CW_Name);
18213       Set_Parent (CW_Type, Parent (T));
18214       Set_Next_Entity (CW_Type, Next_E);
18215 
18216       --  Ensure we have a new freeze node for the class-wide type. The partial
18217       --  view may have freeze action of its own, requiring a proper freeze
18218       --  node, and the same freeze node cannot be shared between the two
18219       --  types.
18220 
18221       Set_Has_Delayed_Freeze (CW_Type);
18222       Set_Freeze_Node (CW_Type, Empty);
18223 
18224       --  Customize the class-wide type: It has no prim. op., it cannot be
18225       --  abstract and its Etype points back to the specific root type.
18226 
18227       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
18228       Set_Is_Tagged_Type              (CW_Type, True);
18229       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
18230       Set_Is_Abstract_Type            (CW_Type, False);
18231       Set_Is_Constrained              (CW_Type, False);
18232       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
18233       Set_Default_SSO                 (CW_Type);
18234 
18235       if Ekind (T) = E_Class_Wide_Subtype then
18236          Set_Etype (CW_Type, Etype (Base_Type (T)));
18237       else
18238          Set_Etype (CW_Type, T);
18239       end if;
18240 
18241       Set_No_Tagged_Streams_Pragma (CW_Type, No_Tagged_Streams);
18242 
18243       --  If this is the class_wide type of a constrained subtype, it does
18244       --  not have discriminants.
18245 
18246       Set_Has_Discriminants (CW_Type,
18247         Has_Discriminants (T) and then not Is_Constrained (T));
18248 
18249       Set_Has_Unknown_Discriminants (CW_Type, True);
18250       Set_Class_Wide_Type (T, CW_Type);
18251       Set_Equivalent_Type (CW_Type, Empty);
18252 
18253       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
18254 
18255       Set_Class_Wide_Type (CW_Type, CW_Type);
18256 
18257       --  Inherit the "ghostness" from the root tagged type
18258 
18259       if Ghost_Mode > None or else Is_Ghost_Entity (T) then
18260          Set_Is_Ghost_Entity (CW_Type);
18261       end if;
18262    end Make_Class_Wide_Type;
18263 
18264    ----------------
18265    -- Make_Index --
18266    ----------------
18267 
18268    procedure Make_Index
18269      (N            : Node_Id;
18270       Related_Nod  : Node_Id;
18271       Related_Id   : Entity_Id := Empty;
18272       Suffix_Index : Nat       := 1;
18273       In_Iter_Schm : Boolean   := False)
18274    is
18275       R      : Node_Id;
18276       T      : Entity_Id;
18277       Def_Id : Entity_Id := Empty;
18278       Found  : Boolean := False;
18279 
18280    begin
18281       --  For a discrete range used in a constrained array definition and
18282       --  defined by a range, an implicit conversion to the predefined type
18283       --  INTEGER is assumed if each bound is either a numeric literal, a named
18284       --  number, or an attribute, and the type of both bounds (prior to the
18285       --  implicit conversion) is the type universal_integer. Otherwise, both
18286       --  bounds must be of the same discrete type, other than universal
18287       --  integer; this type must be determinable independently of the
18288       --  context, but using the fact that the type must be discrete and that
18289       --  both bounds must have the same type.
18290 
18291       --  Character literals also have a universal type in the absence of
18292       --  of additional context,  and are resolved to Standard_Character.
18293 
18294       if Nkind (N) = N_Range then
18295 
18296          --  The index is given by a range constraint. The bounds are known
18297          --  to be of a consistent type.
18298 
18299          if not Is_Overloaded (N) then
18300             T := Etype (N);
18301 
18302             --  For universal bounds, choose the specific predefined type
18303 
18304             if T = Universal_Integer then
18305                T := Standard_Integer;
18306 
18307             elsif T = Any_Character then
18308                Ambiguous_Character (Low_Bound (N));
18309 
18310                T := Standard_Character;
18311             end if;
18312 
18313          --  The node may be overloaded because some user-defined operators
18314          --  are available, but if a universal interpretation exists it is
18315          --  also the selected one.
18316 
18317          elsif Universal_Interpretation (N) = Universal_Integer then
18318             T := Standard_Integer;
18319 
18320          else
18321             T := Any_Type;
18322 
18323             declare
18324                Ind : Interp_Index;
18325                It  : Interp;
18326 
18327             begin
18328                Get_First_Interp (N, Ind, It);
18329                while Present (It.Typ) loop
18330                   if Is_Discrete_Type (It.Typ) then
18331 
18332                      if Found
18333                        and then not Covers (It.Typ, T)
18334                        and then not Covers (T, It.Typ)
18335                      then
18336                         Error_Msg_N ("ambiguous bounds in discrete range", N);
18337                         exit;
18338                      else
18339                         T := It.Typ;
18340                         Found := True;
18341                      end if;
18342                   end if;
18343 
18344                   Get_Next_Interp (Ind, It);
18345                end loop;
18346 
18347                if T = Any_Type then
18348                   Error_Msg_N ("discrete type required for range", N);
18349                   Set_Etype (N, Any_Type);
18350                   return;
18351 
18352                elsif T = Universal_Integer then
18353                   T := Standard_Integer;
18354                end if;
18355             end;
18356          end if;
18357 
18358          if not Is_Discrete_Type (T) then
18359             Error_Msg_N ("discrete type required for range", N);
18360             Set_Etype (N, Any_Type);
18361             return;
18362          end if;
18363 
18364          if Nkind (Low_Bound (N)) = N_Attribute_Reference
18365            and then Attribute_Name (Low_Bound (N)) = Name_First
18366            and then Is_Entity_Name (Prefix (Low_Bound (N)))
18367            and then Is_Type (Entity (Prefix (Low_Bound (N))))
18368            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (N))))
18369          then
18370             --  The type of the index will be the type of the prefix, as long
18371             --  as the upper bound is 'Last of the same type.
18372 
18373             Def_Id := Entity (Prefix (Low_Bound (N)));
18374 
18375             if Nkind (High_Bound (N)) /= N_Attribute_Reference
18376               or else Attribute_Name (High_Bound (N)) /= Name_Last
18377               or else not Is_Entity_Name (Prefix (High_Bound (N)))
18378               or else Entity (Prefix (High_Bound (N))) /= Def_Id
18379             then
18380                Def_Id := Empty;
18381             end if;
18382          end if;
18383 
18384          R := N;
18385          Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
18386 
18387       elsif Nkind (N) = N_Subtype_Indication then
18388 
18389          --  The index is given by a subtype with a range constraint
18390 
18391          T := Base_Type (Entity (Subtype_Mark (N)));
18392 
18393          if not Is_Discrete_Type (T) then
18394             Error_Msg_N ("discrete type required for range", N);
18395             Set_Etype (N, Any_Type);
18396             return;
18397          end if;
18398 
18399          R := Range_Expression (Constraint (N));
18400 
18401          Resolve (R, T);
18402          Process_Range_Expr_In_Decl
18403            (R, Entity (Subtype_Mark (N)), In_Iter_Schm => In_Iter_Schm);
18404 
18405       elsif Nkind (N) = N_Attribute_Reference then
18406 
18407          --  Catch beginner's error (use of attribute other than 'Range)
18408 
18409          if Attribute_Name (N) /= Name_Range then
18410             Error_Msg_N ("expect attribute ''Range", N);
18411             Set_Etype (N, Any_Type);
18412             return;
18413          end if;
18414 
18415          --  If the node denotes the range of a type mark, that is also the
18416          --  resulting type, and we do not need to create an Itype for it.
18417 
18418          if Is_Entity_Name (Prefix (N))
18419            and then Comes_From_Source (N)
18420            and then Is_Type (Entity (Prefix (N)))
18421            and then Is_Discrete_Type (Entity (Prefix (N)))
18422          then
18423             Def_Id := Entity (Prefix (N));
18424          end if;
18425 
18426          Analyze_And_Resolve (N);
18427          T := Etype (N);
18428          R := N;
18429 
18430       --  If none of the above, must be a subtype. We convert this to a
18431       --  range attribute reference because in the case of declared first
18432       --  named subtypes, the types in the range reference can be different
18433       --  from the type of the entity. A range attribute normalizes the
18434       --  reference and obtains the correct types for the bounds.
18435 
18436       --  This transformation is in the nature of an expansion, is only
18437       --  done if expansion is active. In particular, it is not done on
18438       --  formal generic types,  because we need to retain the name of the
18439       --  original index for instantiation purposes.
18440 
18441       else
18442          if not Is_Entity_Name (N) or else not Is_Type (Entity (N)) then
18443             Error_Msg_N ("invalid subtype mark in discrete range ", N);
18444             Set_Etype (N, Any_Integer);
18445             return;
18446 
18447          else
18448             --  The type mark may be that of an incomplete type. It is only
18449             --  now that we can get the full view, previous analysis does
18450             --  not look specifically for a type mark.
18451 
18452             Set_Entity (N, Get_Full_View (Entity (N)));
18453             Set_Etype  (N, Entity (N));
18454             Def_Id := Entity (N);
18455 
18456             if not Is_Discrete_Type (Def_Id) then
18457                Error_Msg_N ("discrete type required for index", N);
18458                Set_Etype (N, Any_Type);
18459                return;
18460             end if;
18461          end if;
18462 
18463          if Expander_Active then
18464             Rewrite (N,
18465               Make_Attribute_Reference (Sloc (N),
18466                 Attribute_Name => Name_Range,
18467                 Prefix         => Relocate_Node (N)));
18468 
18469             --  The original was a subtype mark that does not freeze. This
18470             --  means that the rewritten version must not freeze either.
18471 
18472             Set_Must_Not_Freeze (N);
18473             Set_Must_Not_Freeze (Prefix (N));
18474             Analyze_And_Resolve (N);
18475             T := Etype (N);
18476             R := N;
18477 
18478          --  If expander is inactive, type is legal, nothing else to construct
18479 
18480          else
18481             return;
18482          end if;
18483       end if;
18484 
18485       if not Is_Discrete_Type (T) then
18486          Error_Msg_N ("discrete type required for range", N);
18487          Set_Etype (N, Any_Type);
18488          return;
18489 
18490       elsif T = Any_Type then
18491          Set_Etype (N, Any_Type);
18492          return;
18493       end if;
18494 
18495       --  We will now create the appropriate Itype to describe the range, but
18496       --  first a check. If we originally had a subtype, then we just label
18497       --  the range with this subtype. Not only is there no need to construct
18498       --  a new subtype, but it is wrong to do so for two reasons:
18499 
18500       --    1. A legality concern, if we have a subtype, it must not freeze,
18501       --       and the Itype would cause freezing incorrectly
18502 
18503       --    2. An efficiency concern, if we created an Itype, it would not be
18504       --       recognized as the same type for the purposes of eliminating
18505       --       checks in some circumstances.
18506 
18507       --  We signal this case by setting the subtype entity in Def_Id
18508 
18509       if No (Def_Id) then
18510          Def_Id :=
18511            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
18512          Set_Etype (Def_Id, Base_Type (T));
18513 
18514          if Is_Signed_Integer_Type (T) then
18515             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
18516 
18517          elsif Is_Modular_Integer_Type (T) then
18518             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
18519 
18520          else
18521             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
18522             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
18523             Set_First_Literal     (Def_Id, First_Literal (T));
18524          end if;
18525 
18526          Set_Size_Info      (Def_Id,                  (T));
18527          Set_RM_Size        (Def_Id, RM_Size          (T));
18528          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
18529 
18530          Set_Scalar_Range   (Def_Id, R);
18531          Conditional_Delay  (Def_Id, T);
18532 
18533          if Nkind (N) = N_Subtype_Indication then
18534             Inherit_Predicate_Flags (Def_Id, Entity (Subtype_Mark (N)));
18535          end if;
18536 
18537          --  In the subtype indication case, if the immediate parent of the
18538          --  new subtype is non-static, then the subtype we create is non-
18539          --  static, even if its bounds are static.
18540 
18541          if Nkind (N) = N_Subtype_Indication
18542            and then not Is_OK_Static_Subtype (Entity (Subtype_Mark (N)))
18543          then
18544             Set_Is_Non_Static_Subtype (Def_Id);
18545          end if;
18546       end if;
18547 
18548       --  Final step is to label the index with this constructed type
18549 
18550       Set_Etype (N, Def_Id);
18551    end Make_Index;
18552 
18553    ------------------------------
18554    -- Modular_Type_Declaration --
18555    ------------------------------
18556 
18557    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
18558       Mod_Expr : constant Node_Id := Expression (Def);
18559       M_Val    : Uint;
18560 
18561       procedure Set_Modular_Size (Bits : Int);
18562       --  Sets RM_Size to Bits, and Esize to normal word size above this
18563 
18564       ----------------------
18565       -- Set_Modular_Size --
18566       ----------------------
18567 
18568       procedure Set_Modular_Size (Bits : Int) is
18569       begin
18570          Set_RM_Size (T, UI_From_Int (Bits));
18571 
18572          if Bits <= 8 then
18573             Init_Esize (T, 8);
18574 
18575          elsif Bits <= 16 then
18576             Init_Esize (T, 16);
18577 
18578          elsif Bits <= 32 then
18579             Init_Esize (T, 32);
18580 
18581          else
18582             Init_Esize (T, System_Max_Binary_Modulus_Power);
18583          end if;
18584 
18585          if not Non_Binary_Modulus (T) and then Esize (T) = RM_Size (T) then
18586             Set_Is_Known_Valid (T);
18587          end if;
18588       end Set_Modular_Size;
18589 
18590    --  Start of processing for Modular_Type_Declaration
18591 
18592    begin
18593       --  If the mod expression is (exactly) 2 * literal, where literal is
18594       --  64 or less,then almost certainly the * was meant to be **. Warn.
18595 
18596       if Warn_On_Suspicious_Modulus_Value
18597         and then Nkind (Mod_Expr) = N_Op_Multiply
18598         and then Nkind (Left_Opnd (Mod_Expr)) = N_Integer_Literal
18599         and then Intval (Left_Opnd (Mod_Expr)) = Uint_2
18600         and then Nkind (Right_Opnd (Mod_Expr)) = N_Integer_Literal
18601         and then Intval (Right_Opnd (Mod_Expr)) <= Uint_64
18602       then
18603          Error_Msg_N
18604            ("suspicious MOD value, was '*'* intended'??M?", Mod_Expr);
18605       end if;
18606 
18607       --  Proceed with analysis of mod expression
18608 
18609       Analyze_And_Resolve (Mod_Expr, Any_Integer);
18610       Set_Etype (T, T);
18611       Set_Ekind (T, E_Modular_Integer_Type);
18612       Init_Alignment (T);
18613       Set_Is_Constrained (T);
18614 
18615       if not Is_OK_Static_Expression (Mod_Expr) then
18616          Flag_Non_Static_Expr
18617            ("non-static expression used for modular type bound!", Mod_Expr);
18618          M_Val := 2 ** System_Max_Binary_Modulus_Power;
18619       else
18620          M_Val := Expr_Value (Mod_Expr);
18621       end if;
18622 
18623       if M_Val < 1 then
18624          Error_Msg_N ("modulus value must be positive", Mod_Expr);
18625          M_Val := 2 ** System_Max_Binary_Modulus_Power;
18626       end if;
18627 
18628       if M_Val > 2 ** Standard_Long_Integer_Size then
18629          Check_Restriction (No_Long_Long_Integers, Mod_Expr);
18630       end if;
18631 
18632       Set_Modulus (T, M_Val);
18633 
18634       --   Create bounds for the modular type based on the modulus given in
18635       --   the type declaration and then analyze and resolve those bounds.
18636 
18637       Set_Scalar_Range (T,
18638         Make_Range (Sloc (Mod_Expr),
18639           Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
18640           High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
18641 
18642       --  Properly analyze the literals for the range. We do this manually
18643       --  because we can't go calling Resolve, since we are resolving these
18644       --  bounds with the type, and this type is certainly not complete yet.
18645 
18646       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
18647       Set_Etype (High_Bound (Scalar_Range (T)), T);
18648       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
18649       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
18650 
18651       --  Loop through powers of two to find number of bits required
18652 
18653       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
18654 
18655          --  Binary case
18656 
18657          if M_Val = 2 ** Bits then
18658             Set_Modular_Size (Bits);
18659             return;
18660 
18661          --  Nonbinary case
18662 
18663          elsif M_Val < 2 ** Bits then
18664             Check_SPARK_05_Restriction ("modulus should be a power of 2", T);
18665             Set_Non_Binary_Modulus (T);
18666 
18667             if Bits > System_Max_Nonbinary_Modulus_Power then
18668                Error_Msg_Uint_1 :=
18669                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
18670                Error_Msg_F
18671                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
18672                Set_Modular_Size (System_Max_Binary_Modulus_Power);
18673                return;
18674 
18675             else
18676                --  In the nonbinary case, set size as per RM 13.3(55)
18677 
18678                Set_Modular_Size (Bits);
18679                return;
18680             end if;
18681          end if;
18682 
18683       end loop;
18684 
18685       --  If we fall through, then the size exceed System.Max_Binary_Modulus
18686       --  so we just signal an error and set the maximum size.
18687 
18688       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
18689       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
18690 
18691       Set_Modular_Size (System_Max_Binary_Modulus_Power);
18692       Init_Alignment (T);
18693 
18694    end Modular_Type_Declaration;
18695 
18696    --------------------------
18697    -- New_Concatenation_Op --
18698    --------------------------
18699 
18700    procedure New_Concatenation_Op (Typ : Entity_Id) is
18701       Loc : constant Source_Ptr := Sloc (Typ);
18702       Op  : Entity_Id;
18703 
18704       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
18705       --  Create abbreviated declaration for the formal of a predefined
18706       --  Operator 'Op' of type 'Typ'
18707 
18708       --------------------
18709       -- Make_Op_Formal --
18710       --------------------
18711 
18712       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
18713          Formal : Entity_Id;
18714       begin
18715          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
18716          Set_Etype (Formal, Typ);
18717          Set_Mechanism (Formal, Default_Mechanism);
18718          return Formal;
18719       end Make_Op_Formal;
18720 
18721    --  Start of processing for New_Concatenation_Op
18722 
18723    begin
18724       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
18725 
18726       Set_Ekind                   (Op, E_Operator);
18727       Set_Scope                   (Op, Current_Scope);
18728       Set_Etype                   (Op, Typ);
18729       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
18730       Set_Is_Immediately_Visible  (Op);
18731       Set_Is_Intrinsic_Subprogram (Op);
18732       Set_Has_Completion          (Op);
18733       Append_Entity               (Op, Current_Scope);
18734 
18735       Set_Name_Entity_Id (Name_Op_Concat, Op);
18736 
18737       Append_Entity (Make_Op_Formal (Typ, Op), Op);
18738       Append_Entity (Make_Op_Formal (Typ, Op), Op);
18739    end New_Concatenation_Op;
18740 
18741    -------------------------
18742    -- OK_For_Limited_Init --
18743    -------------------------
18744 
18745    --  ???Check all calls of this, and compare the conditions under which it's
18746    --  called.
18747 
18748    function OK_For_Limited_Init
18749      (Typ : Entity_Id;
18750       Exp : Node_Id) return Boolean
18751    is
18752    begin
18753       return Is_CPP_Constructor_Call (Exp)
18754         or else (Ada_Version >= Ada_2005
18755                   and then not Debug_Flag_Dot_L
18756                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
18757    end OK_For_Limited_Init;
18758 
18759    -------------------------------
18760    -- OK_For_Limited_Init_In_05 --
18761    -------------------------------
18762 
18763    function OK_For_Limited_Init_In_05
18764      (Typ : Entity_Id;
18765       Exp : Node_Id) return Boolean
18766    is
18767    begin
18768       --  An object of a limited interface type can be initialized with any
18769       --  expression of a nonlimited descendant type. However this does not
18770       --  apply if this is a view conversion of some other expression. This
18771       --  is checked below.
18772 
18773       if Is_Class_Wide_Type (Typ)
18774         and then Is_Limited_Interface (Typ)
18775         and then not Is_Limited_Type (Etype (Exp))
18776         and then Nkind (Exp) /= N_Type_Conversion
18777       then
18778          return True;
18779       end if;
18780 
18781       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
18782       --  case of limited aggregates (including extension aggregates), and
18783       --  function calls. The function call may have been given in prefixed
18784       --  notation, in which case the original node is an indexed component.
18785       --  If the function is parameterless, the original node was an explicit
18786       --  dereference. The function may also be parameterless, in which case
18787       --  the source node is just an identifier.
18788 
18789       --  A branch of a conditional expression may have been removed if the
18790       --  condition is statically known. This happens during expansion, and
18791       --  thus will not happen if previous errors were encountered. The check
18792       --  will have been performed on the chosen branch, which replaces the
18793       --  original conditional expression.
18794 
18795       if No (Exp) then
18796          return True;
18797       end if;
18798 
18799       case Nkind (Original_Node (Exp)) is
18800          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
18801             return True;
18802 
18803          when N_Identifier =>
18804             return Present (Entity (Original_Node (Exp)))
18805               and then Ekind (Entity (Original_Node (Exp))) = E_Function;
18806 
18807          when N_Qualified_Expression =>
18808             return
18809               OK_For_Limited_Init_In_05
18810                 (Typ, Expression (Original_Node (Exp)));
18811 
18812          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
18813          --  with a function call, the expander has rewritten the call into an
18814          --  N_Type_Conversion node to force displacement of the pointer to
18815          --  reference the component containing the secondary dispatch table.
18816          --  Otherwise a type conversion is not a legal context.
18817          --  A return statement for a build-in-place function returning a
18818          --  synchronized type also introduces an unchecked conversion.
18819 
18820          when N_Type_Conversion           |
18821               N_Unchecked_Type_Conversion =>
18822             return not Comes_From_Source (Exp)
18823               and then
18824                 OK_For_Limited_Init_In_05
18825                   (Typ, Expression (Original_Node (Exp)));
18826 
18827          when N_Indexed_Component     |
18828               N_Selected_Component    |
18829               N_Explicit_Dereference  =>
18830             return Nkind (Exp) = N_Function_Call;
18831 
18832          --  A use of 'Input is a function call, hence allowed. Normally the
18833          --  attribute will be changed to a call, but the attribute by itself
18834          --  can occur with -gnatc.
18835 
18836          when N_Attribute_Reference =>
18837             return Attribute_Name (Original_Node (Exp)) = Name_Input;
18838 
18839          --  For a case expression, all dependent expressions must be legal
18840 
18841          when N_Case_Expression =>
18842             declare
18843                Alt : Node_Id;
18844 
18845             begin
18846                Alt := First (Alternatives (Original_Node (Exp)));
18847                while Present (Alt) loop
18848                   if not OK_For_Limited_Init_In_05 (Typ, Expression (Alt)) then
18849                      return False;
18850                   end if;
18851 
18852                   Next (Alt);
18853                end loop;
18854 
18855                return True;
18856             end;
18857 
18858          --  For an if expression, all dependent expressions must be legal
18859 
18860          when N_If_Expression =>
18861             declare
18862                Then_Expr : constant Node_Id :=
18863                              Next (First (Expressions (Original_Node (Exp))));
18864                Else_Expr : constant Node_Id := Next (Then_Expr);
18865             begin
18866                return OK_For_Limited_Init_In_05 (Typ, Then_Expr)
18867                         and then
18868                       OK_For_Limited_Init_In_05 (Typ, Else_Expr);
18869             end;
18870 
18871          when others =>
18872             return False;
18873       end case;
18874    end OK_For_Limited_Init_In_05;
18875 
18876    -------------------------------------------
18877    -- Ordinary_Fixed_Point_Type_Declaration --
18878    -------------------------------------------
18879 
18880    procedure Ordinary_Fixed_Point_Type_Declaration
18881      (T   : Entity_Id;
18882       Def : Node_Id)
18883    is
18884       Loc           : constant Source_Ptr := Sloc (Def);
18885       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
18886       RRS           : constant Node_Id    := Real_Range_Specification (Def);
18887       Implicit_Base : Entity_Id;
18888       Delta_Val     : Ureal;
18889       Small_Val     : Ureal;
18890       Low_Val       : Ureal;
18891       High_Val      : Ureal;
18892 
18893    begin
18894       Check_Restriction (No_Fixed_Point, Def);
18895 
18896       --  Create implicit base type
18897 
18898       Implicit_Base :=
18899         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
18900       Set_Etype (Implicit_Base, Implicit_Base);
18901 
18902       --  Analyze and process delta expression
18903 
18904       Analyze_And_Resolve (Delta_Expr, Any_Real);
18905 
18906       Check_Delta_Expression (Delta_Expr);
18907       Delta_Val := Expr_Value_R (Delta_Expr);
18908 
18909       Set_Delta_Value (Implicit_Base, Delta_Val);
18910 
18911       --  Compute default small from given delta, which is the largest power
18912       --  of two that does not exceed the given delta value.
18913 
18914       declare
18915          Tmp   : Ureal;
18916          Scale : Int;
18917 
18918       begin
18919          Tmp := Ureal_1;
18920          Scale := 0;
18921 
18922          if Delta_Val < Ureal_1 then
18923             while Delta_Val < Tmp loop
18924                Tmp := Tmp / Ureal_2;
18925                Scale := Scale + 1;
18926             end loop;
18927 
18928          else
18929             loop
18930                Tmp := Tmp * Ureal_2;
18931                exit when Tmp > Delta_Val;
18932                Scale := Scale - 1;
18933             end loop;
18934          end if;
18935 
18936          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
18937       end;
18938 
18939       Set_Small_Value (Implicit_Base, Small_Val);
18940 
18941       --  If no range was given, set a dummy range
18942 
18943       if RRS <= Empty_Or_Error then
18944          Low_Val  := -Small_Val;
18945          High_Val := Small_Val;
18946 
18947       --  Otherwise analyze and process given range
18948 
18949       else
18950          declare
18951             Low  : constant Node_Id := Low_Bound  (RRS);
18952             High : constant Node_Id := High_Bound (RRS);
18953 
18954          begin
18955             Analyze_And_Resolve (Low, Any_Real);
18956             Analyze_And_Resolve (High, Any_Real);
18957             Check_Real_Bound (Low);
18958             Check_Real_Bound (High);
18959 
18960             --  Obtain and set the range
18961 
18962             Low_Val  := Expr_Value_R (Low);
18963             High_Val := Expr_Value_R (High);
18964 
18965             if Low_Val > High_Val then
18966                Error_Msg_NE ("??fixed point type& has null range", Def, T);
18967             end if;
18968          end;
18969       end if;
18970 
18971       --  The range for both the implicit base and the declared first subtype
18972       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
18973       --  set a temporary range in place. Note that the bounds of the base
18974       --  type will be widened to be symmetrical and to fill the available
18975       --  bits when the type is frozen.
18976 
18977       --  We could do this with all discrete types, and probably should, but
18978       --  we absolutely have to do it for fixed-point, since the end-points
18979       --  of the range and the size are determined by the small value, which
18980       --  could be reset before the freeze point.
18981 
18982       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
18983       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
18984 
18985       --  Complete definition of first subtype. The inheritance of the rep item
18986       --  chain ensures that SPARK-related pragmas are not clobbered when the
18987       --  ordinary fixed point type acts as a full view of a private type.
18988 
18989       Set_Ekind              (T, E_Ordinary_Fixed_Point_Subtype);
18990       Set_Etype              (T, Implicit_Base);
18991       Init_Size_Align        (T);
18992       Inherit_Rep_Item_Chain (T, Implicit_Base);
18993       Set_Small_Value        (T, Small_Val);
18994       Set_Delta_Value        (T, Delta_Val);
18995       Set_Is_Constrained     (T);
18996    end Ordinary_Fixed_Point_Type_Declaration;
18997 
18998    ----------------------------------
18999    -- Preanalyze_Assert_Expression --
19000    ----------------------------------
19001 
19002    procedure Preanalyze_Assert_Expression (N : Node_Id; T : Entity_Id) is
19003    begin
19004       In_Assertion_Expr := In_Assertion_Expr + 1;
19005       Preanalyze_Spec_Expression (N, T);
19006       In_Assertion_Expr := In_Assertion_Expr - 1;
19007    end Preanalyze_Assert_Expression;
19008 
19009    -----------------------------------
19010    -- Preanalyze_Default_Expression --
19011    -----------------------------------
19012 
19013    procedure Preanalyze_Default_Expression (N : Node_Id; T : Entity_Id) is
19014       Save_In_Default_Expr : constant Boolean := In_Default_Expr;
19015    begin
19016       In_Default_Expr := True;
19017       Preanalyze_Spec_Expression (N, T);
19018       In_Default_Expr := Save_In_Default_Expr;
19019    end Preanalyze_Default_Expression;
19020 
19021    --------------------------------
19022    -- Preanalyze_Spec_Expression --
19023    --------------------------------
19024 
19025    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
19026       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
19027    begin
19028       In_Spec_Expression := True;
19029       Preanalyze_And_Resolve (N, T);
19030       In_Spec_Expression := Save_In_Spec_Expression;
19031    end Preanalyze_Spec_Expression;
19032 
19033    ----------------------------------------
19034    -- Prepare_Private_Subtype_Completion --
19035    ----------------------------------------
19036 
19037    procedure Prepare_Private_Subtype_Completion
19038      (Id          : Entity_Id;
19039       Related_Nod : Node_Id)
19040    is
19041       Id_B   : constant Entity_Id := Base_Type (Id);
19042       Full_B : Entity_Id := Full_View (Id_B);
19043       Full   : Entity_Id;
19044 
19045    begin
19046       if Present (Full_B) then
19047 
19048          --  Get to the underlying full view if necessary
19049 
19050          if Is_Private_Type (Full_B)
19051            and then Present (Underlying_Full_View (Full_B))
19052          then
19053             Full_B := Underlying_Full_View (Full_B);
19054          end if;
19055 
19056          --  The Base_Type is already completed, we can complete the subtype
19057          --  now. We have to create a new entity with the same name, Thus we
19058          --  can't use Create_Itype.
19059 
19060          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
19061          Set_Is_Itype (Full);
19062          Set_Associated_Node_For_Itype (Full, Related_Nod);
19063          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
19064       end if;
19065 
19066       --  The parent subtype may be private, but the base might not, in some
19067       --  nested instances. In that case, the subtype does not need to be
19068       --  exchanged. It would still be nice to make private subtypes and their
19069       --  bases consistent at all times ???
19070 
19071       if Is_Private_Type (Id_B) then
19072          Append_Elmt (Id, Private_Dependents (Id_B));
19073       end if;
19074    end Prepare_Private_Subtype_Completion;
19075 
19076    ---------------------------
19077    -- Process_Discriminants --
19078    ---------------------------
19079 
19080    procedure Process_Discriminants
19081      (N    : Node_Id;
19082       Prev : Entity_Id := Empty)
19083    is
19084       Elist               : constant Elist_Id := New_Elmt_List;
19085       Id                  : Node_Id;
19086       Discr               : Node_Id;
19087       Discr_Number        : Uint;
19088       Discr_Type          : Entity_Id;
19089       Default_Present     : Boolean := False;
19090       Default_Not_Present : Boolean := False;
19091 
19092    begin
19093       --  A composite type other than an array type can have discriminants.
19094       --  On entry, the current scope is the composite type.
19095 
19096       --  The discriminants are initially entered into the scope of the type
19097       --  via Enter_Name with the default Ekind of E_Void to prevent premature
19098       --  use, as explained at the end of this procedure.
19099 
19100       Discr := First (Discriminant_Specifications (N));
19101       while Present (Discr) loop
19102          Enter_Name (Defining_Identifier (Discr));
19103 
19104          --  For navigation purposes we add a reference to the discriminant
19105          --  in the entity for the type. If the current declaration is a
19106          --  completion, place references on the partial view. Otherwise the
19107          --  type is the current scope.
19108 
19109          if Present (Prev) then
19110 
19111             --  The references go on the partial view, if present. If the
19112             --  partial view has discriminants, the references have been
19113             --  generated already.
19114 
19115             if not Has_Discriminants (Prev) then
19116                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
19117             end if;
19118          else
19119             Generate_Reference
19120               (Current_Scope, Defining_Identifier (Discr), 'd');
19121          end if;
19122 
19123          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
19124             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
19125 
19126             --  Ada 2005 (AI-254)
19127 
19128             if Present (Access_To_Subprogram_Definition
19129                          (Discriminant_Type (Discr)))
19130               and then Protected_Present (Access_To_Subprogram_Definition
19131                                            (Discriminant_Type (Discr)))
19132             then
19133                Discr_Type :=
19134                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
19135             end if;
19136 
19137          else
19138             Find_Type (Discriminant_Type (Discr));
19139             Discr_Type := Etype (Discriminant_Type (Discr));
19140 
19141             if Error_Posted (Discriminant_Type (Discr)) then
19142                Discr_Type := Any_Type;
19143             end if;
19144          end if;
19145 
19146          --  Handling of discriminants that are access types
19147 
19148          if Is_Access_Type (Discr_Type) then
19149 
19150             --  Ada 2005 (AI-230): Access discriminant allowed in non-
19151             --  limited record types
19152 
19153             if Ada_Version < Ada_2005 then
19154                Check_Access_Discriminant_Requires_Limited
19155                  (Discr, Discriminant_Type (Discr));
19156             end if;
19157 
19158             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
19159                Error_Msg_N
19160                  ("(Ada 83) access discriminant not allowed", Discr);
19161             end if;
19162 
19163          --  If not access type, must be a discrete type
19164 
19165          elsif not Is_Discrete_Type (Discr_Type) then
19166             Error_Msg_N
19167               ("discriminants must have a discrete or access type",
19168                Discriminant_Type (Discr));
19169          end if;
19170 
19171          Set_Etype (Defining_Identifier (Discr), Discr_Type);
19172 
19173          --  If a discriminant specification includes the assignment compound
19174          --  delimiter followed by an expression, the expression is the default
19175          --  expression of the discriminant; the default expression must be of
19176          --  the type of the discriminant. (RM 3.7.1) Since this expression is
19177          --  a default expression, we do the special preanalysis, since this
19178          --  expression does not freeze (see section "Handling of Default and
19179          --  Per-Object Expressions" in spec of package Sem).
19180 
19181          if Present (Expression (Discr)) then
19182             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
19183 
19184             --  Legaity checks
19185 
19186             if Nkind (N) = N_Formal_Type_Declaration then
19187                Error_Msg_N
19188                  ("discriminant defaults not allowed for formal type",
19189                   Expression (Discr));
19190 
19191             --  Flag an error for a tagged type with defaulted discriminants,
19192             --  excluding limited tagged types when compiling for Ada 2012
19193             --  (see AI05-0214).
19194 
19195             elsif Is_Tagged_Type (Current_Scope)
19196               and then (not Is_Limited_Type (Current_Scope)
19197                          or else Ada_Version < Ada_2012)
19198               and then Comes_From_Source (N)
19199             then
19200                --  Note: see similar test in Check_Or_Process_Discriminants, to
19201                --  handle the (illegal) case of the completion of an untagged
19202                --  view with discriminants with defaults by a tagged full view.
19203                --  We skip the check if Discr does not come from source, to
19204                --  account for the case of an untagged derived type providing
19205                --  defaults for a renamed discriminant from a private untagged
19206                --  ancestor with a tagged full view (ACATS B460006).
19207 
19208                if Ada_Version >= Ada_2012 then
19209                   Error_Msg_N
19210                     ("discriminants of nonlimited tagged type cannot have"
19211                        & " defaults",
19212                      Expression (Discr));
19213                else
19214                   Error_Msg_N
19215                     ("discriminants of tagged type cannot have defaults",
19216                      Expression (Discr));
19217                end if;
19218 
19219             else
19220                Default_Present := True;
19221                Append_Elmt (Expression (Discr), Elist);
19222 
19223                --  Tag the defining identifiers for the discriminants with
19224                --  their corresponding default expressions from the tree.
19225 
19226                Set_Discriminant_Default_Value
19227                  (Defining_Identifier (Discr), Expression (Discr));
19228             end if;
19229 
19230             --  In gnatc or gnatprove mode, make sure set Do_Range_Check flag
19231             --  gets set unless we can be sure that no range check is required.
19232 
19233             if (GNATprove_Mode or not Expander_Active)
19234               and then not
19235                 Is_In_Range
19236                   (Expression (Discr), Discr_Type, Assume_Valid => True)
19237             then
19238                Set_Do_Range_Check (Expression (Discr));
19239             end if;
19240 
19241          --  No default discriminant value given
19242 
19243          else
19244             Default_Not_Present := True;
19245          end if;
19246 
19247          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
19248          --  Discr_Type but with the null-exclusion attribute
19249 
19250          if Ada_Version >= Ada_2005 then
19251 
19252             --  Ada 2005 (AI-231): Static checks
19253 
19254             if Can_Never_Be_Null (Discr_Type) then
19255                Null_Exclusion_Static_Checks (Discr);
19256 
19257             elsif Is_Access_Type (Discr_Type)
19258               and then Null_Exclusion_Present (Discr)
19259 
19260                --  No need to check itypes because in their case this check
19261                --  was done at their point of creation
19262 
19263               and then not Is_Itype (Discr_Type)
19264             then
19265                if Can_Never_Be_Null (Discr_Type) then
19266                   Error_Msg_NE
19267                     ("`NOT NULL` not allowed (& already excludes null)",
19268                      Discr,
19269                      Discr_Type);
19270                end if;
19271 
19272                Set_Etype (Defining_Identifier (Discr),
19273                  Create_Null_Excluding_Itype
19274                    (T           => Discr_Type,
19275                     Related_Nod => Discr));
19276 
19277             --  Check for improper null exclusion if the type is otherwise
19278             --  legal for a discriminant.
19279 
19280             elsif Null_Exclusion_Present (Discr)
19281               and then Is_Discrete_Type (Discr_Type)
19282             then
19283                Error_Msg_N
19284                  ("null exclusion can only apply to an access type", Discr);
19285             end if;
19286 
19287             --  Ada 2005 (AI-402): access discriminants of nonlimited types
19288             --  can't have defaults. Synchronized types, or types that are
19289             --  explicitly limited are fine, but special tests apply to derived
19290             --  types in generics: in a generic body we have to assume the
19291             --  worst, and therefore defaults are not allowed if the parent is
19292             --  a generic formal private type (see ACATS B370001).
19293 
19294             if Is_Access_Type (Discr_Type) and then Default_Present then
19295                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
19296                  or else Is_Limited_Record (Current_Scope)
19297                  or else Is_Concurrent_Type (Current_Scope)
19298                  or else Is_Concurrent_Record_Type (Current_Scope)
19299                  or else Ekind (Current_Scope) = E_Limited_Private_Type
19300                then
19301                   if not Is_Derived_Type (Current_Scope)
19302                     or else not Is_Generic_Type (Etype (Current_Scope))
19303                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
19304                     or else Limited_Present
19305                               (Type_Definition (Parent (Current_Scope)))
19306                   then
19307                      null;
19308 
19309                   else
19310                      Error_Msg_N
19311                        ("access discriminants of nonlimited types cannot "
19312                         & "have defaults", Expression (Discr));
19313                   end if;
19314 
19315                elsif Present (Expression (Discr)) then
19316                   Error_Msg_N
19317                     ("(Ada 2005) access discriminants of nonlimited types "
19318                      & "cannot have defaults", Expression (Discr));
19319                end if;
19320             end if;
19321          end if;
19322 
19323          --  A discriminant cannot be effectively volatile (SPARK RM 7.1.3(6)).
19324          --  This check is relevant only when SPARK_Mode is on as it is not a
19325          --  standard Ada legality rule.
19326 
19327          if SPARK_Mode = On
19328            and then Is_Effectively_Volatile (Defining_Identifier (Discr))
19329          then
19330             Error_Msg_N ("discriminant cannot be volatile", Discr);
19331          end if;
19332 
19333          Next (Discr);
19334       end loop;
19335 
19336       --  An element list consisting of the default expressions of the
19337       --  discriminants is constructed in the above loop and used to set
19338       --  the Discriminant_Constraint attribute for the type. If an object
19339       --  is declared of this (record or task) type without any explicit
19340       --  discriminant constraint given, this element list will form the
19341       --  actual parameters for the corresponding initialization procedure
19342       --  for the type.
19343 
19344       Set_Discriminant_Constraint (Current_Scope, Elist);
19345       Set_Stored_Constraint (Current_Scope, No_Elist);
19346 
19347       --  Default expressions must be provided either for all or for none
19348       --  of the discriminants of a discriminant part. (RM 3.7.1)
19349 
19350       if Default_Present and then Default_Not_Present then
19351          Error_Msg_N
19352            ("incomplete specification of defaults for discriminants", N);
19353       end if;
19354 
19355       --  The use of the name of a discriminant is not allowed in default
19356       --  expressions of a discriminant part if the specification of the
19357       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
19358 
19359       --  To detect this, the discriminant names are entered initially with an
19360       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
19361       --  attempt to use a void entity (for example in an expression that is
19362       --  type-checked) produces the error message: premature usage. Now after
19363       --  completing the semantic analysis of the discriminant part, we can set
19364       --  the Ekind of all the discriminants appropriately.
19365 
19366       Discr := First (Discriminant_Specifications (N));
19367       Discr_Number := Uint_1;
19368       while Present (Discr) loop
19369          Id := Defining_Identifier (Discr);
19370          Set_Ekind (Id, E_Discriminant);
19371          Init_Component_Location (Id);
19372          Init_Esize (Id);
19373          Set_Discriminant_Number (Id, Discr_Number);
19374 
19375          --  Make sure this is always set, even in illegal programs
19376 
19377          Set_Corresponding_Discriminant (Id, Empty);
19378 
19379          --  Initialize the Original_Record_Component to the entity itself.
19380          --  Inherit_Components will propagate the right value to
19381          --  discriminants in derived record types.
19382 
19383          Set_Original_Record_Component (Id, Id);
19384 
19385          --  Create the discriminal for the discriminant
19386 
19387          Build_Discriminal (Id);
19388 
19389          Next (Discr);
19390          Discr_Number := Discr_Number + 1;
19391       end loop;
19392 
19393       Set_Has_Discriminants (Current_Scope);
19394    end Process_Discriminants;
19395 
19396    -----------------------
19397    -- Process_Full_View --
19398    -----------------------
19399 
19400    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
19401       procedure Collect_Implemented_Interfaces
19402         (Typ    : Entity_Id;
19403          Ifaces : Elist_Id);
19404       --  Ada 2005: Gather all the interfaces that Typ directly or
19405       --  inherently implements. Duplicate entries are not added to
19406       --  the list Ifaces.
19407 
19408       ------------------------------------
19409       -- Collect_Implemented_Interfaces --
19410       ------------------------------------
19411 
19412       procedure Collect_Implemented_Interfaces
19413         (Typ    : Entity_Id;
19414          Ifaces : Elist_Id)
19415       is
19416          Iface      : Entity_Id;
19417          Iface_Elmt : Elmt_Id;
19418 
19419       begin
19420          --  Abstract interfaces are only associated with tagged record types
19421 
19422          if not Is_Tagged_Type (Typ) or else not Is_Record_Type (Typ) then
19423             return;
19424          end if;
19425 
19426          --  Recursively climb to the ancestors
19427 
19428          if Etype (Typ) /= Typ
19429 
19430             --  Protect the frontend against wrong cyclic declarations like:
19431 
19432             --     type B is new A with private;
19433             --     type C is new A with private;
19434             --  private
19435             --     type B is new C with null record;
19436             --     type C is new B with null record;
19437 
19438            and then Etype (Typ) /= Priv_T
19439            and then Etype (Typ) /= Full_T
19440          then
19441             --  Keep separate the management of private type declarations
19442 
19443             if Ekind (Typ) = E_Record_Type_With_Private then
19444 
19445                --  Handle the following illegal usage:
19446                --      type Private_Type is tagged private;
19447                --   private
19448                --      type Private_Type is new Type_Implementing_Iface;
19449 
19450                if Present (Full_View (Typ))
19451                  and then Etype (Typ) /= Full_View (Typ)
19452                then
19453                   if Is_Interface (Etype (Typ)) then
19454                      Append_Unique_Elmt (Etype (Typ), Ifaces);
19455                   end if;
19456 
19457                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
19458                end if;
19459 
19460             --  Non-private types
19461 
19462             else
19463                if Is_Interface (Etype (Typ)) then
19464                   Append_Unique_Elmt (Etype (Typ), Ifaces);
19465                end if;
19466 
19467                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
19468             end if;
19469          end if;
19470 
19471          --  Handle entities in the list of abstract interfaces
19472 
19473          if Present (Interfaces (Typ)) then
19474             Iface_Elmt := First_Elmt (Interfaces (Typ));
19475             while Present (Iface_Elmt) loop
19476                Iface := Node (Iface_Elmt);
19477 
19478                pragma Assert (Is_Interface (Iface));
19479 
19480                if not Contain_Interface (Iface, Ifaces) then
19481                   Append_Elmt (Iface, Ifaces);
19482                   Collect_Implemented_Interfaces (Iface, Ifaces);
19483                end if;
19484 
19485                Next_Elmt (Iface_Elmt);
19486             end loop;
19487          end if;
19488       end Collect_Implemented_Interfaces;
19489 
19490       --  Local variables
19491 
19492       Full_Indic  : Node_Id;
19493       Full_Parent : Entity_Id;
19494       Priv_Parent : Entity_Id;
19495 
19496    --  Start of processing for Process_Full_View
19497 
19498    begin
19499       --  First some sanity checks that must be done after semantic
19500       --  decoration of the full view and thus cannot be placed with other
19501       --  similar checks in Find_Type_Name
19502 
19503       if not Is_Limited_Type (Priv_T)
19504         and then (Is_Limited_Type (Full_T)
19505                    or else Is_Limited_Composite (Full_T))
19506       then
19507          if In_Instance then
19508             null;
19509          else
19510             Error_Msg_N
19511               ("completion of nonlimited type cannot be limited", Full_T);
19512             Explain_Limited_Type (Full_T, Full_T);
19513          end if;
19514 
19515       elsif Is_Abstract_Type (Full_T)
19516         and then not Is_Abstract_Type (Priv_T)
19517       then
19518          Error_Msg_N
19519            ("completion of nonabstract type cannot be abstract", Full_T);
19520 
19521       elsif Is_Tagged_Type (Priv_T)
19522         and then Is_Limited_Type (Priv_T)
19523         and then not Is_Limited_Type (Full_T)
19524       then
19525          --  If pragma CPP_Class was applied to the private declaration
19526          --  propagate the limitedness to the full-view
19527 
19528          if Is_CPP_Class (Priv_T) then
19529             Set_Is_Limited_Record (Full_T);
19530 
19531          --  GNAT allow its own definition of Limited_Controlled to disobey
19532          --  this rule in order in ease the implementation. This test is safe
19533          --  because Root_Controlled is defined in a child of System that
19534          --  normal programs are not supposed to use.
19535 
19536          elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
19537             Set_Is_Limited_Composite (Full_T);
19538          else
19539             Error_Msg_N
19540               ("completion of limited tagged type must be limited", Full_T);
19541          end if;
19542 
19543       elsif Is_Generic_Type (Priv_T) then
19544          Error_Msg_N ("generic type cannot have a completion", Full_T);
19545       end if;
19546 
19547       --  Check that ancestor interfaces of private and full views are
19548       --  consistent. We omit this check for synchronized types because
19549       --  they are performed on the corresponding record type when frozen.
19550 
19551       if Ada_Version >= Ada_2005
19552         and then Is_Tagged_Type (Priv_T)
19553         and then Is_Tagged_Type (Full_T)
19554         and then not Is_Concurrent_Type (Full_T)
19555       then
19556          declare
19557             Iface         : Entity_Id;
19558             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
19559             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
19560 
19561          begin
19562             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
19563             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
19564 
19565             --  Ada 2005 (AI-251): The partial view shall be a descendant of
19566             --  an interface type if and only if the full type is descendant
19567             --  of the interface type (AARM 7.3 (7.3/2)).
19568 
19569             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
19570 
19571             if Present (Iface) then
19572                Error_Msg_NE
19573                  ("interface in partial view& not implemented by full type "
19574                   & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
19575             end if;
19576 
19577             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
19578 
19579             if Present (Iface) then
19580                Error_Msg_NE
19581                  ("interface & not implemented by partial view "
19582                   & "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
19583             end if;
19584          end;
19585       end if;
19586 
19587       if Is_Tagged_Type (Priv_T)
19588         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
19589         and then Is_Derived_Type (Full_T)
19590       then
19591          Priv_Parent := Etype (Priv_T);
19592 
19593          --  The full view of a private extension may have been transformed
19594          --  into an unconstrained derived type declaration and a subtype
19595          --  declaration (see build_derived_record_type for details).
19596 
19597          if Nkind (N) = N_Subtype_Declaration then
19598             Full_Indic  := Subtype_Indication (N);
19599             Full_Parent := Etype (Base_Type (Full_T));
19600          else
19601             Full_Indic  := Subtype_Indication (Type_Definition (N));
19602             Full_Parent := Etype (Full_T);
19603          end if;
19604 
19605          --  Check that the parent type of the full type is a descendant of
19606          --  the ancestor subtype given in the private extension. If either
19607          --  entity has an Etype equal to Any_Type then we had some previous
19608          --  error situation [7.3(8)].
19609 
19610          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
19611             return;
19612 
19613          --  Ada 2005 (AI-251): Interfaces in the full type can be given in
19614          --  any order. Therefore we don't have to check that its parent must
19615          --  be a descendant of the parent of the private type declaration.
19616 
19617          elsif Is_Interface (Priv_Parent)
19618            and then Is_Interface (Full_Parent)
19619          then
19620             null;
19621 
19622          --  Ada 2005 (AI-251): If the parent of the private type declaration
19623          --  is an interface there is no need to check that it is an ancestor
19624          --  of the associated full type declaration. The required tests for
19625          --  this case are performed by Build_Derived_Record_Type.
19626 
19627          elsif not Is_Interface (Base_Type (Priv_Parent))
19628            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
19629          then
19630             Error_Msg_N
19631               ("parent of full type must descend from parent of private "
19632                & "extension", Full_Indic);
19633 
19634          --  First check a formal restriction, and then proceed with checking
19635          --  Ada rules. Since the formal restriction is not a serious error, we
19636          --  don't prevent further error detection for this check, hence the
19637          --  ELSE.
19638 
19639          else
19640             --  In formal mode, when completing a private extension the type
19641             --  named in the private part must be exactly the same as that
19642             --  named in the visible part.
19643 
19644             if Priv_Parent /= Full_Parent then
19645                Error_Msg_Name_1 := Chars (Priv_Parent);
19646                Check_SPARK_05_Restriction ("% expected", Full_Indic);
19647             end if;
19648 
19649             --  Check the rules of 7.3(10): if the private extension inherits
19650             --  known discriminants, then the full type must also inherit those
19651             --  discriminants from the same (ancestor) type, and the parent
19652             --  subtype of the full type must be constrained if and only if
19653             --  the ancestor subtype of the private extension is constrained.
19654 
19655             if No (Discriminant_Specifications (Parent (Priv_T)))
19656               and then not Has_Unknown_Discriminants (Priv_T)
19657               and then Has_Discriminants (Base_Type (Priv_Parent))
19658             then
19659                declare
19660                   Priv_Indic  : constant Node_Id :=
19661                                   Subtype_Indication (Parent (Priv_T));
19662 
19663                   Priv_Constr : constant Boolean :=
19664                                   Is_Constrained (Priv_Parent)
19665                                     or else
19666                                       Nkind (Priv_Indic) = N_Subtype_Indication
19667                                     or else
19668                                       Is_Constrained (Entity (Priv_Indic));
19669 
19670                   Full_Constr : constant Boolean :=
19671                                   Is_Constrained (Full_Parent)
19672                                     or else
19673                                       Nkind (Full_Indic) = N_Subtype_Indication
19674                                     or else
19675                                       Is_Constrained (Entity (Full_Indic));
19676 
19677                   Priv_Discr : Entity_Id;
19678                   Full_Discr : Entity_Id;
19679 
19680                begin
19681                   Priv_Discr := First_Discriminant (Priv_Parent);
19682                   Full_Discr := First_Discriminant (Full_Parent);
19683                   while Present (Priv_Discr) and then Present (Full_Discr) loop
19684                      if Original_Record_Component (Priv_Discr) =
19685                         Original_Record_Component (Full_Discr)
19686                           or else
19687                         Corresponding_Discriminant (Priv_Discr) =
19688                         Corresponding_Discriminant (Full_Discr)
19689                      then
19690                         null;
19691                      else
19692                         exit;
19693                      end if;
19694 
19695                      Next_Discriminant (Priv_Discr);
19696                      Next_Discriminant (Full_Discr);
19697                   end loop;
19698 
19699                   if Present (Priv_Discr) or else Present (Full_Discr) then
19700                      Error_Msg_N
19701                        ("full view must inherit discriminants of the parent "
19702                         & "type used in the private extension", Full_Indic);
19703 
19704                   elsif Priv_Constr and then not Full_Constr then
19705                      Error_Msg_N
19706                        ("parent subtype of full type must be constrained",
19707                         Full_Indic);
19708 
19709                   elsif Full_Constr and then not Priv_Constr then
19710                      Error_Msg_N
19711                        ("parent subtype of full type must be unconstrained",
19712                         Full_Indic);
19713                   end if;
19714                end;
19715 
19716                --  Check the rules of 7.3(12): if a partial view has neither
19717                --  known or unknown discriminants, then the full type
19718                --  declaration shall define a definite subtype.
19719 
19720             elsif not Has_Unknown_Discriminants (Priv_T)
19721               and then not Has_Discriminants (Priv_T)
19722               and then not Is_Constrained (Full_T)
19723             then
19724                Error_Msg_N
19725                  ("full view must define a constrained type if partial view "
19726                   & "has no discriminants", Full_T);
19727             end if;
19728 
19729             --  ??????? Do we implement the following properly ?????
19730             --  If the ancestor subtype of a private extension has constrained
19731             --  discriminants, then the parent subtype of the full view shall
19732             --  impose a statically matching constraint on those discriminants
19733             --  [7.3(13)].
19734          end if;
19735 
19736       else
19737          --  For untagged types, verify that a type without discriminants is
19738          --  not completed with an unconstrained type. A separate error message
19739          --  is produced if the full type has defaulted discriminants.
19740 
19741          if Is_Definite_Subtype (Priv_T)
19742            and then not Is_Definite_Subtype (Full_T)
19743          then
19744             Error_Msg_Sloc := Sloc (Parent (Priv_T));
19745             Error_Msg_NE
19746               ("full view of& not compatible with declaration#",
19747                Full_T, Priv_T);
19748 
19749             if not Is_Tagged_Type (Full_T) then
19750                Error_Msg_N
19751                  ("\one is constrained, the other unconstrained", Full_T);
19752             end if;
19753          end if;
19754       end if;
19755 
19756       --  AI-419: verify that the use of "limited" is consistent
19757 
19758       declare
19759          Orig_Decl : constant Node_Id := Original_Node (N);
19760 
19761       begin
19762          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
19763            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
19764            and then Nkind
19765              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
19766          then
19767             if not Limited_Present (Parent (Priv_T))
19768               and then not Synchronized_Present (Parent (Priv_T))
19769               and then Limited_Present (Type_Definition (Orig_Decl))
19770             then
19771                Error_Msg_N
19772                  ("full view of non-limited extension cannot be limited", N);
19773 
19774             --  Conversely, if the partial view carries the limited keyword,
19775             --  the full view must as well, even if it may be redundant.
19776 
19777             elsif Limited_Present (Parent (Priv_T))
19778               and then not Limited_Present (Type_Definition (Orig_Decl))
19779             then
19780                Error_Msg_N
19781                  ("full view of limited extension must be explicitly limited",
19782                   N);
19783             end if;
19784          end if;
19785       end;
19786 
19787       --  Ada 2005 (AI-443): A synchronized private extension must be
19788       --  completed by a task or protected type.
19789 
19790       if Ada_Version >= Ada_2005
19791         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
19792         and then Synchronized_Present (Parent (Priv_T))
19793         and then not Is_Concurrent_Type (Full_T)
19794       then
19795          Error_Msg_N ("full view of synchronized extension must " &
19796                       "be synchronized type", N);
19797       end if;
19798 
19799       --  Ada 2005 AI-363: if the full view has discriminants with
19800       --  defaults, it is illegal to declare constrained access subtypes
19801       --  whose designated type is the current type. This allows objects
19802       --  of the type that are declared in the heap to be unconstrained.
19803 
19804       if not Has_Unknown_Discriminants (Priv_T)
19805         and then not Has_Discriminants (Priv_T)
19806         and then Has_Discriminants (Full_T)
19807         and then
19808           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
19809       then
19810          Set_Has_Constrained_Partial_View (Full_T);
19811          Set_Has_Constrained_Partial_View (Priv_T);
19812       end if;
19813 
19814       --  Create a full declaration for all its subtypes recorded in
19815       --  Private_Dependents and swap them similarly to the base type. These
19816       --  are subtypes that have been define before the full declaration of
19817       --  the private type. We also swap the entry in Private_Dependents list
19818       --  so we can properly restore the private view on exit from the scope.
19819 
19820       declare
19821          Priv_Elmt : Elmt_Id;
19822          Priv_Scop : Entity_Id;
19823          Priv      : Entity_Id;
19824          Full      : Entity_Id;
19825 
19826       begin
19827          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
19828          while Present (Priv_Elmt) loop
19829             Priv := Node (Priv_Elmt);
19830             Priv_Scop := Scope (Priv);
19831 
19832             if Ekind_In (Priv, E_Private_Subtype,
19833                                E_Limited_Private_Subtype,
19834                                E_Record_Subtype_With_Private)
19835             then
19836                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
19837                Set_Is_Itype (Full);
19838                Set_Parent (Full, Parent (Priv));
19839                Set_Associated_Node_For_Itype (Full, N);
19840 
19841                --  Now we need to complete the private subtype, but since the
19842                --  base type has already been swapped, we must also swap the
19843                --  subtypes (and thus, reverse the arguments in the call to
19844                --  Complete_Private_Subtype). Also note that we may need to
19845                --  re-establish the scope of the private subtype.
19846 
19847                Copy_And_Swap (Priv, Full);
19848 
19849                if not In_Open_Scopes (Priv_Scop) then
19850                   Push_Scope (Priv_Scop);
19851 
19852                else
19853                   --  Reset Priv_Scop to Empty to indicate no scope was pushed
19854 
19855                   Priv_Scop := Empty;
19856                end if;
19857 
19858                Complete_Private_Subtype (Full, Priv, Full_T, N);
19859 
19860                if Present (Priv_Scop) then
19861                   Pop_Scope;
19862                end if;
19863 
19864                Replace_Elmt (Priv_Elmt, Full);
19865             end if;
19866 
19867             Next_Elmt (Priv_Elmt);
19868          end loop;
19869       end;
19870 
19871       --  If the private view was tagged, copy the new primitive operations
19872       --  from the private view to the full view.
19873 
19874       if Is_Tagged_Type (Full_T) then
19875          declare
19876             Disp_Typ  : Entity_Id;
19877             Full_List : Elist_Id;
19878             Prim      : Entity_Id;
19879             Prim_Elmt : Elmt_Id;
19880             Priv_List : Elist_Id;
19881 
19882             function Contains
19883               (E : Entity_Id;
19884                L : Elist_Id) return Boolean;
19885             --  Determine whether list L contains element E
19886 
19887             --------------
19888             -- Contains --
19889             --------------
19890 
19891             function Contains
19892               (E : Entity_Id;
19893                L : Elist_Id) return Boolean
19894             is
19895                List_Elmt : Elmt_Id;
19896 
19897             begin
19898                List_Elmt := First_Elmt (L);
19899                while Present (List_Elmt) loop
19900                   if Node (List_Elmt) = E then
19901                      return True;
19902                   end if;
19903 
19904                   Next_Elmt (List_Elmt);
19905                end loop;
19906 
19907                return False;
19908             end Contains;
19909 
19910          --  Start of processing
19911 
19912          begin
19913             if Is_Tagged_Type (Priv_T) then
19914                Priv_List := Primitive_Operations (Priv_T);
19915                Prim_Elmt := First_Elmt (Priv_List);
19916 
19917                --  In the case of a concurrent type completing a private tagged
19918                --  type, primitives may have been declared in between the two
19919                --  views. These subprograms need to be wrapped the same way
19920                --  entries and protected procedures are handled because they
19921                --  cannot be directly shared by the two views.
19922 
19923                if Is_Concurrent_Type (Full_T) then
19924                   declare
19925                      Conc_Typ  : constant Entity_Id :=
19926                                    Corresponding_Record_Type (Full_T);
19927                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
19928                      Wrap_Spec : Node_Id;
19929 
19930                   begin
19931                      while Present (Prim_Elmt) loop
19932                         Prim := Node (Prim_Elmt);
19933 
19934                         if Comes_From_Source (Prim)
19935                           and then not Is_Abstract_Subprogram (Prim)
19936                         then
19937                            Wrap_Spec :=
19938                              Make_Subprogram_Declaration (Sloc (Prim),
19939                                Specification =>
19940                                  Build_Wrapper_Spec
19941                                    (Subp_Id => Prim,
19942                                     Obj_Typ => Conc_Typ,
19943                                     Formals =>
19944                                       Parameter_Specifications
19945                                         (Parent (Prim))));
19946 
19947                            Insert_After (Curr_Nod, Wrap_Spec);
19948                            Curr_Nod := Wrap_Spec;
19949 
19950                            Analyze (Wrap_Spec);
19951 
19952                            --  Remove the wrapper from visibility to avoid
19953                            --  spurious conflict with the wrapped entity.
19954 
19955                            Set_Is_Immediately_Visible
19956                              (Defining_Entity (Specification (Wrap_Spec)),
19957                               False);
19958                         end if;
19959 
19960                         Next_Elmt (Prim_Elmt);
19961                      end loop;
19962 
19963                      return;
19964                   end;
19965 
19966                --  For non-concurrent types, transfer explicit primitives, but
19967                --  omit those inherited from the parent of the private view
19968                --  since they will be re-inherited later on.
19969 
19970                else
19971                   Full_List := Primitive_Operations (Full_T);
19972 
19973                   while Present (Prim_Elmt) loop
19974                      Prim := Node (Prim_Elmt);
19975 
19976                      if Comes_From_Source (Prim)
19977                        and then not Contains (Prim, Full_List)
19978                      then
19979                         Append_Elmt (Prim, Full_List);
19980                      end if;
19981 
19982                      Next_Elmt (Prim_Elmt);
19983                   end loop;
19984                end if;
19985 
19986             --  Untagged private view
19987 
19988             else
19989                Full_List := Primitive_Operations (Full_T);
19990 
19991                --  In this case the partial view is untagged, so here we locate
19992                --  all of the earlier primitives that need to be treated as
19993                --  dispatching (those that appear between the two views). Note
19994                --  that these additional operations must all be new operations
19995                --  (any earlier operations that override inherited operations
19996                --  of the full view will already have been inserted in the
19997                --  primitives list, marked by Check_Operation_From_Private_View
19998                --  as dispatching. Note that implicit "/=" operators are
19999                --  excluded from being added to the primitives list since they
20000                --  shouldn't be treated as dispatching (tagged "/=" is handled
20001                --  specially).
20002 
20003                Prim := Next_Entity (Full_T);
20004                while Present (Prim) and then Prim /= Priv_T loop
20005                   if Ekind_In (Prim, E_Procedure, E_Function) then
20006                      Disp_Typ := Find_Dispatching_Type (Prim);
20007 
20008                      if Disp_Typ = Full_T
20009                        and then (Chars (Prim) /= Name_Op_Ne
20010                                   or else Comes_From_Source (Prim))
20011                      then
20012                         Check_Controlling_Formals (Full_T, Prim);
20013 
20014                         if not Is_Dispatching_Operation (Prim) then
20015                            Append_Elmt (Prim, Full_List);
20016                            Set_Is_Dispatching_Operation (Prim, True);
20017                            Set_DT_Position_Value (Prim, No_Uint);
20018                         end if;
20019 
20020                      elsif Is_Dispatching_Operation (Prim)
20021                        and then Disp_Typ /= Full_T
20022                      then
20023 
20024                         --  Verify that it is not otherwise controlled by a
20025                         --  formal or a return value of type T.
20026 
20027                         Check_Controlling_Formals (Disp_Typ, Prim);
20028                      end if;
20029                   end if;
20030 
20031                   Next_Entity (Prim);
20032                end loop;
20033             end if;
20034 
20035             --  For the tagged case, the two views can share the same primitive
20036             --  operations list and the same class-wide type. Update attributes
20037             --  of the class-wide type which depend on the full declaration.
20038 
20039             if Is_Tagged_Type (Priv_T) then
20040                Set_Direct_Primitive_Operations (Priv_T, Full_List);
20041                Set_Class_Wide_Type
20042                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
20043 
20044                Propagate_Concurrent_Flags (Class_Wide_Type (Priv_T), Full_T);
20045             end if;
20046          end;
20047       end if;
20048 
20049       --  Ada 2005 AI 161: Check preelaborable initialization consistency
20050 
20051       if Known_To_Have_Preelab_Init (Priv_T) then
20052 
20053          --  Case where there is a pragma Preelaborable_Initialization. We
20054          --  always allow this in predefined units, which is cheating a bit,
20055          --  but it means we don't have to struggle to meet the requirements in
20056          --  the RM for having Preelaborable Initialization. Otherwise we
20057          --  require that the type meets the RM rules. But we can't check that
20058          --  yet, because of the rule about overriding Initialize, so we simply
20059          --  set a flag that will be checked at freeze time.
20060 
20061          if not In_Predefined_Unit (Full_T) then
20062             Set_Must_Have_Preelab_Init (Full_T);
20063          end if;
20064       end if;
20065 
20066       --  If pragma CPP_Class was applied to the private type declaration,
20067       --  propagate it now to the full type declaration.
20068 
20069       if Is_CPP_Class (Priv_T) then
20070          Set_Is_CPP_Class (Full_T);
20071          Set_Convention   (Full_T, Convention_CPP);
20072 
20073          --  Check that components of imported CPP types do not have default
20074          --  expressions.
20075 
20076          Check_CPP_Type_Has_No_Defaults (Full_T);
20077       end if;
20078 
20079       --  If the private view has user specified stream attributes, then so has
20080       --  the full view.
20081 
20082       --  Why the test, how could these flags be already set in Full_T ???
20083 
20084       if Has_Specified_Stream_Read (Priv_T) then
20085          Set_Has_Specified_Stream_Read (Full_T);
20086       end if;
20087 
20088       if Has_Specified_Stream_Write (Priv_T) then
20089          Set_Has_Specified_Stream_Write (Full_T);
20090       end if;
20091 
20092       if Has_Specified_Stream_Input (Priv_T) then
20093          Set_Has_Specified_Stream_Input (Full_T);
20094       end if;
20095 
20096       if Has_Specified_Stream_Output (Priv_T) then
20097          Set_Has_Specified_Stream_Output (Full_T);
20098       end if;
20099 
20100       --  Propagate the attributes related to pragma Default_Initial_Condition
20101       --  from the private to the full view. Note that both flags are mutually
20102       --  exclusive.
20103 
20104       if Has_Default_Init_Cond (Priv_T)
20105         or else Has_Inherited_Default_Init_Cond (Priv_T)
20106       then
20107          Propagate_Default_Init_Cond_Attributes
20108            (From_Typ             => Priv_T,
20109             To_Typ               => Full_T,
20110             Private_To_Full_View => True);
20111 
20112       --  In the case where the full view is derived from another private type,
20113       --  the attributes related to pragma Default_Initial_Condition must be
20114       --  propagated from the full to the private view to maintain consistency
20115       --  of views.
20116 
20117       --    package Pack is
20118       --       type Parent_Typ is private
20119       --         with Default_Initial_Condition ...;
20120       --    private
20121       --       type Parent_Typ is ...;
20122       --    end Pack;
20123 
20124       --    with Pack; use Pack;
20125       --    package Pack_2 is
20126       --       type Deriv_Typ is private;         --  must inherit
20127       --    private
20128       --       type Deriv_Typ is new Parent_Typ;  --  must inherit
20129       --    end Pack_2;
20130 
20131       elsif Has_Default_Init_Cond (Full_T)
20132         or else Has_Inherited_Default_Init_Cond (Full_T)
20133       then
20134          Propagate_Default_Init_Cond_Attributes
20135            (From_Typ             => Full_T,
20136             To_Typ               => Priv_T,
20137             Private_To_Full_View => True);
20138       end if;
20139 
20140       if Is_Ghost_Entity (Priv_T) then
20141 
20142          --  The Ghost policy in effect at the point of declaration and at the
20143          --  point of completion must match (SPARK RM 6.9(14)).
20144 
20145          Check_Ghost_Completion (Priv_T, Full_T);
20146 
20147          --  Propagate the attributes related to pragma Ghost from the private
20148          --  to the full view.
20149 
20150          Mark_Full_View_As_Ghost (Priv_T, Full_T);
20151       end if;
20152 
20153       --  Propagate invariant-related attributes from the private view to the
20154       --  full view and its base type.
20155 
20156       Propagate_Invariant_Attributes (Full_T, From_Typ => Priv_T);
20157       Propagate_Invariant_Attributes (Base_Type (Full_T), From_Typ => Priv_T);
20158 
20159       --  AI12-0041: Detect an attempt to inherit a class-wide type invariant
20160       --  in the full view without advertising the inheritance in the partial
20161       --  view. This can only occur when the partial view has no parent type
20162       --  and the full view has an interface as a parent. Any other scenarios
20163       --  are illegal because implemented interfaces must match between the
20164       --  two views.
20165 
20166       if Is_Tagged_Type (Priv_T) and then Is_Tagged_Type (Full_T) then
20167          declare
20168             Full_Par : constant Entity_Id := Etype (Full_T);
20169             Priv_Par : constant Entity_Id := Etype (Priv_T);
20170 
20171          begin
20172             if not Is_Interface (Priv_Par)
20173               and then Is_Interface (Full_Par)
20174               and then Has_Inheritable_Invariants (Full_Par)
20175             then
20176                Error_Msg_N
20177                  ("hidden inheritance of class-wide type invariants not "
20178                   & "allowed", N);
20179             end if;
20180          end;
20181       end if;
20182 
20183       --  Propagate predicates to full type, and predicate function if already
20184       --  defined. It is not clear that this can actually happen? the partial
20185       --  view cannot be frozen yet, and the predicate function has not been
20186       --  built. Still it is a cheap check and seems safer to make it.
20187 
20188       if Has_Predicates (Priv_T) then
20189          Set_Has_Predicates (Full_T);
20190 
20191          if Present (Predicate_Function (Priv_T)) then
20192             Set_Predicate_Function (Full_T, Predicate_Function (Priv_T));
20193          end if;
20194       end if;
20195    end Process_Full_View;
20196 
20197    -----------------------------------
20198    -- Process_Incomplete_Dependents --
20199    -----------------------------------
20200 
20201    procedure Process_Incomplete_Dependents
20202      (N      : Node_Id;
20203       Full_T : Entity_Id;
20204       Inc_T  : Entity_Id)
20205    is
20206       Inc_Elmt : Elmt_Id;
20207       Priv_Dep : Entity_Id;
20208       New_Subt : Entity_Id;
20209 
20210       Disc_Constraint : Elist_Id;
20211 
20212    begin
20213       if No (Private_Dependents (Inc_T)) then
20214          return;
20215       end if;
20216 
20217       --  Itypes that may be generated by the completion of an incomplete
20218       --  subtype are not used by the back-end and not attached to the tree.
20219       --  They are created only for constraint-checking purposes.
20220 
20221       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
20222       while Present (Inc_Elmt) loop
20223          Priv_Dep := Node (Inc_Elmt);
20224 
20225          if Ekind (Priv_Dep) = E_Subprogram_Type then
20226 
20227             --  An Access_To_Subprogram type may have a return type or a
20228             --  parameter type that is incomplete. Replace with the full view.
20229 
20230             if Etype (Priv_Dep) = Inc_T then
20231                Set_Etype (Priv_Dep, Full_T);
20232             end if;
20233 
20234             declare
20235                Formal : Entity_Id;
20236 
20237             begin
20238                Formal := First_Formal (Priv_Dep);
20239                while Present (Formal) loop
20240                   if Etype (Formal) = Inc_T then
20241                      Set_Etype (Formal, Full_T);
20242                   end if;
20243 
20244                   Next_Formal (Formal);
20245                end loop;
20246             end;
20247 
20248          elsif Is_Overloadable (Priv_Dep) then
20249 
20250             --  If a subprogram in the incomplete dependents list is primitive
20251             --  for a tagged full type then mark it as a dispatching operation,
20252             --  check whether it overrides an inherited subprogram, and check
20253             --  restrictions on its controlling formals. Note that a protected
20254             --  operation is never dispatching: only its wrapper operation
20255             --  (which has convention Ada) is.
20256 
20257             if Is_Tagged_Type (Full_T)
20258               and then Is_Primitive (Priv_Dep)
20259               and then Convention (Priv_Dep) /= Convention_Protected
20260             then
20261                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
20262                Set_Is_Dispatching_Operation (Priv_Dep);
20263                Check_Controlling_Formals (Full_T, Priv_Dep);
20264             end if;
20265 
20266          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
20267 
20268             --  Can happen during processing of a body before the completion
20269             --  of a TA type. Ignore, because spec is also on dependent list.
20270 
20271             return;
20272 
20273          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
20274          --  corresponding subtype of the full view.
20275 
20276          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
20277             Set_Subtype_Indication
20278               (Parent (Priv_Dep), New_Occurrence_Of (Full_T, Sloc (Priv_Dep)));
20279             Set_Etype (Priv_Dep, Full_T);
20280             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
20281             Set_Analyzed (Parent (Priv_Dep), False);
20282 
20283             --  Reanalyze the declaration, suppressing the call to
20284             --  Enter_Name to avoid duplicate names.
20285 
20286             Analyze_Subtype_Declaration
20287               (N    => Parent (Priv_Dep),
20288                Skip => True);
20289 
20290          --  Dependent is a subtype
20291 
20292          else
20293             --  We build a new subtype indication using the full view of the
20294             --  incomplete parent. The discriminant constraints have been
20295             --  elaborated already at the point of the subtype declaration.
20296 
20297             New_Subt := Create_Itype (E_Void, N);
20298 
20299             if Has_Discriminants (Full_T) then
20300                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
20301             else
20302                Disc_Constraint := No_Elist;
20303             end if;
20304 
20305             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
20306             Set_Full_View (Priv_Dep, New_Subt);
20307          end if;
20308 
20309          Next_Elmt (Inc_Elmt);
20310       end loop;
20311    end Process_Incomplete_Dependents;
20312 
20313    --------------------------------
20314    -- Process_Range_Expr_In_Decl --
20315    --------------------------------
20316 
20317    procedure Process_Range_Expr_In_Decl
20318      (R            : Node_Id;
20319       T            : Entity_Id;
20320       Subtyp       : Entity_Id := Empty;
20321       Check_List   : List_Id   := Empty_List;
20322       R_Check_Off  : Boolean   := False;
20323       In_Iter_Schm : Boolean   := False)
20324    is
20325       Lo, Hi      : Node_Id;
20326       R_Checks    : Check_Result;
20327       Insert_Node : Node_Id;
20328       Def_Id      : Entity_Id;
20329 
20330    begin
20331       Analyze_And_Resolve (R, Base_Type (T));
20332 
20333       if Nkind (R) = N_Range then
20334 
20335          --  In SPARK, all ranges should be static, with the exception of the
20336          --  discrete type definition of a loop parameter specification.
20337 
20338          if not In_Iter_Schm
20339            and then not Is_OK_Static_Range (R)
20340          then
20341             Check_SPARK_05_Restriction ("range should be static", R);
20342          end if;
20343 
20344          Lo := Low_Bound (R);
20345          Hi := High_Bound (R);
20346 
20347          --  Validity checks on the range of a quantified expression are
20348          --  delayed until the construct is transformed into a loop.
20349 
20350          if Nkind (Parent (R)) = N_Loop_Parameter_Specification
20351            and then Nkind (Parent (Parent (R))) = N_Quantified_Expression
20352          then
20353             null;
20354 
20355          --  We need to ensure validity of the bounds here, because if we
20356          --  go ahead and do the expansion, then the expanded code will get
20357          --  analyzed with range checks suppressed and we miss the check.
20358 
20359          --  WARNING: The capture of the range bounds with xxx_FIRST/_LAST and
20360          --  the temporaries generated by routine Remove_Side_Effects by means
20361          --  of validity checks must use the same names. When a range appears
20362          --  in the parent of a generic, the range is processed with checks
20363          --  disabled as part of the generic context and with checks enabled
20364          --  for code generation purposes. This leads to link issues as the
20365          --  generic contains references to xxx_FIRST/_LAST, but the inlined
20366          --  template sees the temporaries generated by Remove_Side_Effects.
20367 
20368          else
20369             Validity_Check_Range (R, Subtyp);
20370          end if;
20371 
20372          --  If there were errors in the declaration, try and patch up some
20373          --  common mistakes in the bounds. The cases handled are literals
20374          --  which are Integer where the expected type is Real and vice versa.
20375          --  These corrections allow the compilation process to proceed further
20376          --  along since some basic assumptions of the format of the bounds
20377          --  are guaranteed.
20378 
20379          if Etype (R) = Any_Type then
20380             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
20381                Rewrite (Lo,
20382                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
20383 
20384             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
20385                Rewrite (Hi,
20386                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
20387 
20388             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
20389                Rewrite (Lo,
20390                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
20391 
20392             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
20393                Rewrite (Hi,
20394                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
20395             end if;
20396 
20397             Set_Etype (Lo, T);
20398             Set_Etype (Hi, T);
20399          end if;
20400 
20401          --  If the bounds of the range have been mistakenly given as string
20402          --  literals (perhaps in place of character literals), then an error
20403          --  has already been reported, but we rewrite the string literal as a
20404          --  bound of the range's type to avoid blowups in later processing
20405          --  that looks at static values.
20406 
20407          if Nkind (Lo) = N_String_Literal then
20408             Rewrite (Lo,
20409               Make_Attribute_Reference (Sloc (Lo),
20410                 Prefix         => New_Occurrence_Of (T, Sloc (Lo)),
20411                 Attribute_Name => Name_First));
20412             Analyze_And_Resolve (Lo);
20413          end if;
20414 
20415          if Nkind (Hi) = N_String_Literal then
20416             Rewrite (Hi,
20417               Make_Attribute_Reference (Sloc (Hi),
20418                 Prefix         => New_Occurrence_Of (T, Sloc (Hi)),
20419                 Attribute_Name => Name_First));
20420             Analyze_And_Resolve (Hi);
20421          end if;
20422 
20423          --  If bounds aren't scalar at this point then exit, avoiding
20424          --  problems with further processing of the range in this procedure.
20425 
20426          if not Is_Scalar_Type (Etype (Lo)) then
20427             return;
20428          end if;
20429 
20430          --  Resolve (actually Sem_Eval) has checked that the bounds are in
20431          --  then range of the base type. Here we check whether the bounds
20432          --  are in the range of the subtype itself. Note that if the bounds
20433          --  represent the null range the Constraint_Error exception should
20434          --  not be raised.
20435 
20436          --  ??? The following code should be cleaned up as follows
20437 
20438          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
20439          --     is done in the call to Range_Check (R, T); below
20440 
20441          --  2. The use of R_Check_Off should be investigated and possibly
20442          --     removed, this would clean up things a bit.
20443 
20444          if Is_Null_Range (Lo, Hi) then
20445             null;
20446 
20447          else
20448             --  Capture values of bounds and generate temporaries for them
20449             --  if needed, before applying checks, since checks may cause
20450             --  duplication of the expression without forcing evaluation.
20451 
20452             --  The forced evaluation removes side effects from expressions,
20453             --  which should occur also in GNATprove mode. Otherwise, we end up
20454             --  with unexpected insertions of actions at places where this is
20455             --  not supposed to occur, e.g. on default parameters of a call.
20456 
20457             if Expander_Active or GNATprove_Mode then
20458 
20459                --  Call Force_Evaluation to create declarations as needed to
20460                --  deal with side effects, and also create typ_FIRST/LAST
20461                --  entities for bounds if we have a subtype name.
20462 
20463                --  Note: we do this transformation even if expansion is not
20464                --  active if we are in GNATprove_Mode since the transformation
20465                --  is in general required to ensure that the resulting tree has
20466                --  proper Ada semantics.
20467 
20468                Force_Evaluation
20469                  (Lo, Related_Id => Subtyp, Is_Low_Bound  => True);
20470                Force_Evaluation
20471                  (Hi, Related_Id => Subtyp, Is_High_Bound => True);
20472             end if;
20473 
20474             --  We use a flag here instead of suppressing checks on the type
20475             --  because the type we check against isn't necessarily the place
20476             --  where we put the check.
20477 
20478             if not R_Check_Off then
20479                R_Checks := Get_Range_Checks (R, T);
20480 
20481                --  Look up tree to find an appropriate insertion point. We
20482                --  can't just use insert_actions because later processing
20483                --  depends on the insertion node. Prior to Ada 2012 the
20484                --  insertion point could only be a declaration or a loop, but
20485                --  quantified expressions can appear within any context in an
20486                --  expression, and the insertion point can be any statement,
20487                --  pragma, or declaration.
20488 
20489                Insert_Node := Parent (R);
20490                while Present (Insert_Node) loop
20491                   exit when
20492                     Nkind (Insert_Node) in N_Declaration
20493                     and then
20494                       not Nkind_In
20495                         (Insert_Node, N_Component_Declaration,
20496                                       N_Loop_Parameter_Specification,
20497                                       N_Function_Specification,
20498                                       N_Procedure_Specification);
20499 
20500                   exit when Nkind (Insert_Node) in N_Later_Decl_Item
20501                     or else Nkind (Insert_Node) in
20502                               N_Statement_Other_Than_Procedure_Call
20503                     or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
20504                                                    N_Pragma);
20505 
20506                   Insert_Node := Parent (Insert_Node);
20507                end loop;
20508 
20509                --  Why would Type_Decl not be present???  Without this test,
20510                --  short regression tests fail.
20511 
20512                if Present (Insert_Node) then
20513 
20514                   --  Case of loop statement. Verify that the range is part
20515                   --  of the subtype indication of the iteration scheme.
20516 
20517                   if Nkind (Insert_Node) = N_Loop_Statement then
20518                      declare
20519                         Indic : Node_Id;
20520 
20521                      begin
20522                         Indic := Parent (R);
20523                         while Present (Indic)
20524                           and then Nkind (Indic) /= N_Subtype_Indication
20525                         loop
20526                            Indic := Parent (Indic);
20527                         end loop;
20528 
20529                         if Present (Indic) then
20530                            Def_Id := Etype (Subtype_Mark (Indic));
20531 
20532                            Insert_Range_Checks
20533                              (R_Checks,
20534                               Insert_Node,
20535                               Def_Id,
20536                               Sloc (Insert_Node),
20537                               R,
20538                               Do_Before => True);
20539                         end if;
20540                      end;
20541 
20542                   --  Insertion before a declaration. If the declaration
20543                   --  includes discriminants, the list of applicable checks
20544                   --  is given by the caller.
20545 
20546                   elsif Nkind (Insert_Node) in N_Declaration then
20547                      Def_Id := Defining_Identifier (Insert_Node);
20548 
20549                      if (Ekind (Def_Id) = E_Record_Type
20550                           and then Depends_On_Discriminant (R))
20551                        or else
20552                         (Ekind (Def_Id) = E_Protected_Type
20553                           and then Has_Discriminants (Def_Id))
20554                      then
20555                         Append_Range_Checks
20556                           (R_Checks,
20557                             Check_List, Def_Id, Sloc (Insert_Node), R);
20558 
20559                      else
20560                         Insert_Range_Checks
20561                           (R_Checks,
20562                             Insert_Node, Def_Id, Sloc (Insert_Node), R);
20563 
20564                      end if;
20565 
20566                   --  Insertion before a statement. Range appears in the
20567                   --  context of a quantified expression. Insertion will
20568                   --  take place when expression is expanded.
20569 
20570                   else
20571                      null;
20572                   end if;
20573                end if;
20574             end if;
20575          end if;
20576 
20577       --  Case of other than an explicit N_Range node
20578 
20579       --  The forced evaluation removes side effects from expressions, which
20580       --  should occur also in GNATprove mode. Otherwise, we end up with
20581       --  unexpected insertions of actions at places where this is not
20582       --  supposed to occur, e.g. on default parameters of a call.
20583 
20584       elsif Expander_Active or GNATprove_Mode then
20585          Get_Index_Bounds (R, Lo, Hi);
20586          Force_Evaluation (Lo);
20587          Force_Evaluation (Hi);
20588       end if;
20589    end Process_Range_Expr_In_Decl;
20590 
20591    --------------------------------------
20592    -- Process_Real_Range_Specification --
20593    --------------------------------------
20594 
20595    procedure Process_Real_Range_Specification (Def : Node_Id) is
20596       Spec : constant Node_Id := Real_Range_Specification (Def);
20597       Lo   : Node_Id;
20598       Hi   : Node_Id;
20599       Err  : Boolean := False;
20600 
20601       procedure Analyze_Bound (N : Node_Id);
20602       --  Analyze and check one bound
20603 
20604       -------------------
20605       -- Analyze_Bound --
20606       -------------------
20607 
20608       procedure Analyze_Bound (N : Node_Id) is
20609       begin
20610          Analyze_And_Resolve (N, Any_Real);
20611 
20612          if not Is_OK_Static_Expression (N) then
20613             Flag_Non_Static_Expr
20614               ("bound in real type definition is not static!", N);
20615             Err := True;
20616          end if;
20617       end Analyze_Bound;
20618 
20619    --  Start of processing for Process_Real_Range_Specification
20620 
20621    begin
20622       if Present (Spec) then
20623          Lo := Low_Bound (Spec);
20624          Hi := High_Bound (Spec);
20625          Analyze_Bound (Lo);
20626          Analyze_Bound (Hi);
20627 
20628          --  If error, clear away junk range specification
20629 
20630          if Err then
20631             Set_Real_Range_Specification (Def, Empty);
20632          end if;
20633       end if;
20634    end Process_Real_Range_Specification;
20635 
20636    ---------------------
20637    -- Process_Subtype --
20638    ---------------------
20639 
20640    function Process_Subtype
20641      (S           : Node_Id;
20642       Related_Nod : Node_Id;
20643       Related_Id  : Entity_Id := Empty;
20644       Suffix      : Character := ' ') return Entity_Id
20645    is
20646       P               : Node_Id;
20647       Def_Id          : Entity_Id;
20648       Error_Node      : Node_Id;
20649       Full_View_Id    : Entity_Id;
20650       Subtype_Mark_Id : Entity_Id;
20651 
20652       May_Have_Null_Exclusion : Boolean;
20653 
20654       procedure Check_Incomplete (T : Node_Id);
20655       --  Called to verify that an incomplete type is not used prematurely
20656 
20657       ----------------------
20658       -- Check_Incomplete --
20659       ----------------------
20660 
20661       procedure Check_Incomplete (T : Node_Id) is
20662       begin
20663          --  Ada 2005 (AI-412): Incomplete subtypes are legal
20664 
20665          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
20666            and then
20667              not (Ada_Version >= Ada_2005
20668                    and then
20669                      (Nkind (Parent (T)) = N_Subtype_Declaration
20670                        or else (Nkind (Parent (T)) = N_Subtype_Indication
20671                                  and then Nkind (Parent (Parent (T))) =
20672                                                    N_Subtype_Declaration)))
20673          then
20674             Error_Msg_N ("invalid use of type before its full declaration", T);
20675          end if;
20676       end Check_Incomplete;
20677 
20678    --  Start of processing for Process_Subtype
20679 
20680    begin
20681       --  Case of no constraints present
20682 
20683       if Nkind (S) /= N_Subtype_Indication then
20684          Find_Type (S);
20685          Check_Incomplete (S);
20686          P := Parent (S);
20687 
20688          --  Ada 2005 (AI-231): Static check
20689 
20690          if Ada_Version >= Ada_2005
20691            and then Present (P)
20692            and then Null_Exclusion_Present (P)
20693            and then Nkind (P) /= N_Access_To_Object_Definition
20694            and then not Is_Access_Type (Entity (S))
20695          then
20696             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
20697          end if;
20698 
20699          --  The following is ugly, can't we have a range or even a flag???
20700 
20701          May_Have_Null_Exclusion :=
20702            Nkind_In (P, N_Access_Definition,
20703                         N_Access_Function_Definition,
20704                         N_Access_Procedure_Definition,
20705                         N_Access_To_Object_Definition,
20706                         N_Allocator,
20707                         N_Component_Definition)
20708              or else
20709            Nkind_In (P, N_Derived_Type_Definition,
20710                         N_Discriminant_Specification,
20711                         N_Formal_Object_Declaration,
20712                         N_Object_Declaration,
20713                         N_Object_Renaming_Declaration,
20714                         N_Parameter_Specification,
20715                         N_Subtype_Declaration);
20716 
20717          --  Create an Itype that is a duplicate of Entity (S) but with the
20718          --  null-exclusion attribute.
20719 
20720          if May_Have_Null_Exclusion
20721            and then Is_Access_Type (Entity (S))
20722            and then Null_Exclusion_Present (P)
20723 
20724             --  No need to check the case of an access to object definition.
20725             --  It is correct to define double not-null pointers.
20726 
20727             --  Example:
20728             --     type Not_Null_Int_Ptr is not null access Integer;
20729             --     type Acc is not null access Not_Null_Int_Ptr;
20730 
20731            and then Nkind (P) /= N_Access_To_Object_Definition
20732          then
20733             if Can_Never_Be_Null (Entity (S)) then
20734                case Nkind (Related_Nod) is
20735                   when N_Full_Type_Declaration =>
20736                      if Nkind (Type_Definition (Related_Nod))
20737                        in N_Array_Type_Definition
20738                      then
20739                         Error_Node :=
20740                           Subtype_Indication
20741                             (Component_Definition
20742                              (Type_Definition (Related_Nod)));
20743                      else
20744                         Error_Node :=
20745                           Subtype_Indication (Type_Definition (Related_Nod));
20746                      end if;
20747 
20748                   when N_Subtype_Declaration =>
20749                      Error_Node := Subtype_Indication (Related_Nod);
20750 
20751                   when N_Object_Declaration =>
20752                      Error_Node := Object_Definition (Related_Nod);
20753 
20754                   when N_Component_Declaration =>
20755                      Error_Node :=
20756                        Subtype_Indication (Component_Definition (Related_Nod));
20757 
20758                   when N_Allocator =>
20759                      Error_Node := Expression (Related_Nod);
20760 
20761                   when others =>
20762                      pragma Assert (False);
20763                      Error_Node := Related_Nod;
20764                end case;
20765 
20766                Error_Msg_NE
20767                  ("`NOT NULL` not allowed (& already excludes null)",
20768                   Error_Node,
20769                   Entity (S));
20770             end if;
20771 
20772             Set_Etype  (S,
20773               Create_Null_Excluding_Itype
20774                 (T           => Entity (S),
20775                  Related_Nod => P));
20776             Set_Entity (S, Etype (S));
20777          end if;
20778 
20779          return Entity (S);
20780 
20781       --  Case of constraint present, so that we have an N_Subtype_Indication
20782       --  node (this node is created only if constraints are present).
20783 
20784       else
20785          Find_Type (Subtype_Mark (S));
20786 
20787          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
20788            and then not
20789             (Nkind (Parent (S)) = N_Subtype_Declaration
20790               and then Is_Itype (Defining_Identifier (Parent (S))))
20791          then
20792             Check_Incomplete (Subtype_Mark (S));
20793          end if;
20794 
20795          P := Parent (S);
20796          Subtype_Mark_Id := Entity (Subtype_Mark (S));
20797 
20798          --  Explicit subtype declaration case
20799 
20800          if Nkind (P) = N_Subtype_Declaration then
20801             Def_Id := Defining_Identifier (P);
20802 
20803          --  Explicit derived type definition case
20804 
20805          elsif Nkind (P) = N_Derived_Type_Definition then
20806             Def_Id := Defining_Identifier (Parent (P));
20807 
20808          --  Implicit case, the Def_Id must be created as an implicit type.
20809          --  The one exception arises in the case of concurrent types, array
20810          --  and access types, where other subsidiary implicit types may be
20811          --  created and must appear before the main implicit type. In these
20812          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
20813          --  has not yet been called to create Def_Id.
20814 
20815          else
20816             if Is_Array_Type (Subtype_Mark_Id)
20817               or else Is_Concurrent_Type (Subtype_Mark_Id)
20818               or else Is_Access_Type (Subtype_Mark_Id)
20819             then
20820                Def_Id := Empty;
20821 
20822             --  For the other cases, we create a new unattached Itype,
20823             --  and set the indication to ensure it gets attached later.
20824 
20825             else
20826                Def_Id :=
20827                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
20828             end if;
20829          end if;
20830 
20831          --  If the kind of constraint is invalid for this kind of type,
20832          --  then give an error, and then pretend no constraint was given.
20833 
20834          if not Is_Valid_Constraint_Kind
20835                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
20836          then
20837             Error_Msg_N
20838               ("incorrect constraint for this kind of type", Constraint (S));
20839 
20840             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
20841 
20842             --  Set Ekind of orphan itype, to prevent cascaded errors
20843 
20844             if Present (Def_Id) then
20845                Set_Ekind (Def_Id, Ekind (Any_Type));
20846             end if;
20847 
20848             --  Make recursive call, having got rid of the bogus constraint
20849 
20850             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
20851          end if;
20852 
20853          --  Remaining processing depends on type. Select on Base_Type kind to
20854          --  ensure getting to the concrete type kind in the case of a private
20855          --  subtype (needed when only doing semantic analysis).
20856 
20857          case Ekind (Base_Type (Subtype_Mark_Id)) is
20858             when Access_Kind =>
20859 
20860                --  If this is a constraint on a class-wide type, discard it.
20861                --  There is currently no way to express a partial discriminant
20862                --  constraint on a type with unknown discriminants. This is
20863                --  a pathology that the ACATS wisely decides not to test.
20864 
20865                if Is_Class_Wide_Type (Designated_Type (Subtype_Mark_Id)) then
20866                   if Comes_From_Source (S) then
20867                      Error_Msg_N
20868                        ("constraint on class-wide type ignored??",
20869                         Constraint (S));
20870                   end if;
20871 
20872                   if Nkind (P) = N_Subtype_Declaration then
20873                      Set_Subtype_Indication (P,
20874                         New_Occurrence_Of (Subtype_Mark_Id, Sloc (S)));
20875                   end if;
20876 
20877                   return Subtype_Mark_Id;
20878                end if;
20879 
20880                Constrain_Access (Def_Id, S, Related_Nod);
20881 
20882                if Expander_Active
20883                  and then  Is_Itype (Designated_Type (Def_Id))
20884                  and then Nkind (Related_Nod) = N_Subtype_Declaration
20885                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
20886                then
20887                   Build_Itype_Reference
20888                     (Designated_Type (Def_Id), Related_Nod);
20889                end if;
20890 
20891             when Array_Kind =>
20892                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
20893 
20894             when Decimal_Fixed_Point_Kind =>
20895                Constrain_Decimal (Def_Id, S);
20896 
20897             when Enumeration_Kind =>
20898                Constrain_Enumeration (Def_Id, S);
20899                Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
20900 
20901             when Ordinary_Fixed_Point_Kind =>
20902                Constrain_Ordinary_Fixed (Def_Id, S);
20903 
20904             when Float_Kind =>
20905                Constrain_Float (Def_Id, S);
20906 
20907             when Integer_Kind =>
20908                Constrain_Integer (Def_Id, S);
20909                Inherit_Predicate_Flags (Def_Id, Subtype_Mark_Id);
20910 
20911             when E_Record_Type     |
20912                  E_Record_Subtype  |
20913                  Class_Wide_Kind   |
20914                  E_Incomplete_Type =>
20915                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
20916 
20917                if Ekind (Def_Id) = E_Incomplete_Type then
20918                   Set_Private_Dependents (Def_Id, New_Elmt_List);
20919                end if;
20920 
20921             when Private_Kind =>
20922                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
20923 
20924                --  The base type may be private but Def_Id may be a full view
20925                --  in an instance.
20926 
20927                if Is_Private_Type (Def_Id) then
20928                   Set_Private_Dependents (Def_Id, New_Elmt_List);
20929                end if;
20930 
20931                --  In case of an invalid constraint prevent further processing
20932                --  since the type constructed is missing expected fields.
20933 
20934                if Etype (Def_Id) = Any_Type then
20935                   return Def_Id;
20936                end if;
20937 
20938                --  If the full view is that of a task with discriminants,
20939                --  we must constrain both the concurrent type and its
20940                --  corresponding record type. Otherwise we will just propagate
20941                --  the constraint to the full view, if available.
20942 
20943                if Present (Full_View (Subtype_Mark_Id))
20944                  and then Has_Discriminants (Subtype_Mark_Id)
20945                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
20946                then
20947                   Full_View_Id :=
20948                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
20949 
20950                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
20951                   Constrain_Concurrent (Full_View_Id, S,
20952                     Related_Nod, Related_Id, Suffix);
20953                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
20954                   Set_Full_View (Def_Id, Full_View_Id);
20955 
20956                   --  Introduce an explicit reference to the private subtype,
20957                   --  to prevent scope anomalies in gigi if first use appears
20958                   --  in a nested context, e.g. a later function body.
20959                   --  Should this be generated in other contexts than a full
20960                   --  type declaration?
20961 
20962                   if Is_Itype (Def_Id)
20963                     and then
20964                       Nkind (Parent (P)) = N_Full_Type_Declaration
20965                   then
20966                      Build_Itype_Reference (Def_Id, Parent (P));
20967                   end if;
20968 
20969                else
20970                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
20971                end if;
20972 
20973             when Concurrent_Kind  =>
20974                Constrain_Concurrent (Def_Id, S,
20975                  Related_Nod, Related_Id, Suffix);
20976 
20977             when others =>
20978                Error_Msg_N ("invalid subtype mark in subtype indication", S);
20979          end case;
20980 
20981          --  Size and Convention are always inherited from the base type
20982 
20983          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
20984          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
20985 
20986          return Def_Id;
20987       end if;
20988    end Process_Subtype;
20989 
20990    --------------------------------------------
20991    -- Propagate_Default_Init_Cond_Attributes --
20992    --------------------------------------------
20993 
20994    procedure Propagate_Default_Init_Cond_Attributes
20995      (From_Typ             : Entity_Id;
20996       To_Typ               : Entity_Id;
20997       Parent_To_Derivation : Boolean := False;
20998       Private_To_Full_View : Boolean := False)
20999    is
21000       procedure Remove_Default_Init_Cond_Procedure (Typ : Entity_Id);
21001       --  Remove the default initial condition procedure (if any) from the
21002       --  Subprograms_For_Type chain of type Typ.
21003 
21004       ----------------------------------------
21005       -- Remove_Default_Init_Cond_Procedure --
21006       ----------------------------------------
21007 
21008       procedure Remove_Default_Init_Cond_Procedure (Typ : Entity_Id) is
21009          Subps     : constant Elist_Id := Subprograms_For_Type (Typ);
21010          Subp_Elmt : Elmt_Id;
21011          Subp_Id   : Entity_Id;
21012 
21013       begin
21014          if Present (Subps) then
21015             Subp_Elmt := First_Elmt (Subps);
21016             while Present (Subp_Elmt) loop
21017                Subp_Id := Node (Subp_Elmt);
21018 
21019                if Is_Default_Init_Cond_Procedure (Subp_Id) then
21020                   Remove_Elmt (Subps, Subp_Elmt);
21021                   exit;
21022                end if;
21023 
21024                Next_Elmt (Subp_Elmt);
21025             end loop;
21026          end if;
21027       end Remove_Default_Init_Cond_Procedure;
21028 
21029       --  Local variables
21030 
21031       Inherit_Procedure : Boolean := False;
21032 
21033    --  Start of processing for Propagate_Default_Init_Cond_Attributes
21034 
21035    begin
21036       if Has_Default_Init_Cond (From_Typ) then
21037 
21038          --  A derived type inherits the attributes from its parent type
21039 
21040          if Parent_To_Derivation then
21041             Set_Has_Inherited_Default_Init_Cond (To_Typ);
21042 
21043          --  A full view shares the attributes with its private view
21044 
21045          else
21046             Set_Has_Default_Init_Cond (To_Typ);
21047          end if;
21048 
21049          Inherit_Procedure := True;
21050 
21051          --  Due to the order of expansion, a derived private type is processed
21052          --  by two routines which both attempt to set the attributes related
21053          --  to pragma Default_Initial_Condition - Build_Derived_Type and then
21054          --  Process_Full_View.
21055 
21056          --    package Pack is
21057          --       type Parent_Typ is private
21058          --         with Default_Initial_Condition ...;
21059          --    private
21060          --       type Parent_Typ is ...;
21061          --    end Pack;
21062 
21063          --    with Pack; use Pack;
21064          --    package Pack_2 is
21065          --       type Deriv_Typ is private
21066          --         with Default_Initial_Condition ...;
21067          --    private
21068          --       type Deriv_Typ is new Parent_Typ;
21069          --    end Pack_2;
21070 
21071          --  When Build_Derived_Type operates, it sets the attributes on the
21072          --  full view without taking into account that the private view may
21073          --  define its own default initial condition procedure. This becomes
21074          --  apparent in Process_Full_View which must undo some of the work by
21075          --  Build_Derived_Type and propagate the attributes from the private
21076          --  to the full view.
21077 
21078          if Private_To_Full_View then
21079             Set_Has_Inherited_Default_Init_Cond (To_Typ, False);
21080             Remove_Default_Init_Cond_Procedure (To_Typ);
21081          end if;
21082 
21083       --  A type must inherit the default initial condition procedure from a
21084       --  parent type when the parent itself is inheriting the procedure or
21085       --  when it is defining one. This circuitry is also used when dealing
21086       --  with the private / full view of a type.
21087 
21088       elsif Has_Inherited_Default_Init_Cond (From_Typ)
21089         or (Parent_To_Derivation
21090               and Present (Get_Pragma
21091                     (From_Typ, Pragma_Default_Initial_Condition)))
21092       then
21093          Set_Has_Inherited_Default_Init_Cond (To_Typ);
21094          Inherit_Procedure := True;
21095       end if;
21096 
21097       if Inherit_Procedure
21098         and then No (Default_Init_Cond_Procedure (To_Typ))
21099       then
21100          Set_Default_Init_Cond_Procedure
21101            (To_Typ, Default_Init_Cond_Procedure (From_Typ));
21102       end if;
21103    end Propagate_Default_Init_Cond_Attributes;
21104 
21105    -----------------------------
21106    -- Record_Type_Declaration --
21107    -----------------------------
21108 
21109    procedure Record_Type_Declaration
21110      (T    : Entity_Id;
21111       N    : Node_Id;
21112       Prev : Entity_Id)
21113    is
21114       Def       : constant Node_Id := Type_Definition (N);
21115       Is_Tagged : Boolean;
21116       Tag_Comp  : Entity_Id;
21117 
21118    begin
21119       --  These flags must be initialized before calling Process_Discriminants
21120       --  because this routine makes use of them.
21121 
21122       Set_Ekind             (T, E_Record_Type);
21123       Set_Etype             (T, T);
21124       Init_Size_Align       (T);
21125       Set_Interfaces        (T, No_Elist);
21126       Set_Stored_Constraint (T, No_Elist);
21127       Set_Default_SSO       (T);
21128 
21129       --  Normal case
21130 
21131       if Ada_Version < Ada_2005 or else not Interface_Present (Def) then
21132          if Limited_Present (Def) then
21133             Check_SPARK_05_Restriction ("limited is not allowed", N);
21134          end if;
21135 
21136          if Abstract_Present (Def) then
21137             Check_SPARK_05_Restriction ("abstract is not allowed", N);
21138          end if;
21139 
21140          --  The flag Is_Tagged_Type might have already been set by
21141          --  Find_Type_Name if it detected an error for declaration T. This
21142          --  arises in the case of private tagged types where the full view
21143          --  omits the word tagged.
21144 
21145          Is_Tagged :=
21146            Tagged_Present (Def)
21147              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
21148 
21149          Set_Is_Limited_Record (T, Limited_Present (Def));
21150 
21151          if Is_Tagged then
21152             Set_Is_Tagged_Type (T, True);
21153             Set_No_Tagged_Streams_Pragma (T, No_Tagged_Streams);
21154          end if;
21155 
21156          --  Type is abstract if full declaration carries keyword, or if
21157          --  previous partial view did.
21158 
21159          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
21160                                       or else Abstract_Present (Def));
21161 
21162       else
21163          Check_SPARK_05_Restriction ("interface is not allowed", N);
21164 
21165          Is_Tagged := True;
21166          Analyze_Interface_Declaration (T, Def);
21167 
21168          if Present (Discriminant_Specifications (N)) then
21169             Error_Msg_N
21170               ("interface types cannot have discriminants",
21171                 Defining_Identifier
21172                   (First (Discriminant_Specifications (N))));
21173          end if;
21174       end if;
21175 
21176       --  First pass: if there are self-referential access components,
21177       --  create the required anonymous access type declarations, and if
21178       --  need be an incomplete type declaration for T itself.
21179 
21180       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
21181 
21182       if Ada_Version >= Ada_2005
21183         and then Present (Interface_List (Def))
21184       then
21185          Check_Interfaces (N, Def);
21186 
21187          declare
21188             Ifaces_List : Elist_Id;
21189 
21190          begin
21191             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
21192             --  already in the parents.
21193 
21194             Collect_Interfaces
21195               (T               => T,
21196                Ifaces_List     => Ifaces_List,
21197                Exclude_Parents => True);
21198 
21199             Set_Interfaces (T, Ifaces_List);
21200          end;
21201       end if;
21202 
21203       --  Records constitute a scope for the component declarations within.
21204       --  The scope is created prior to the processing of these declarations.
21205       --  Discriminants are processed first, so that they are visible when
21206       --  processing the other components. The Ekind of the record type itself
21207       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
21208 
21209       --  Enter record scope
21210 
21211       Push_Scope (T);
21212 
21213       --  If an incomplete or private type declaration was already given for
21214       --  the type, then this scope already exists, and the discriminants have
21215       --  been declared within. We must verify that the full declaration
21216       --  matches the incomplete one.
21217 
21218       Check_Or_Process_Discriminants (N, T, Prev);
21219 
21220       Set_Is_Constrained     (T, not Has_Discriminants (T));
21221       Set_Has_Delayed_Freeze (T, True);
21222 
21223       --  For tagged types add a manually analyzed component corresponding
21224       --  to the component _tag, the corresponding piece of tree will be
21225       --  expanded as part of the freezing actions if it is not a CPP_Class.
21226 
21227       if Is_Tagged then
21228 
21229          --  Do not add the tag unless we are in expansion mode
21230 
21231          if Expander_Active then
21232             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
21233             Enter_Name (Tag_Comp);
21234 
21235             Set_Ekind                     (Tag_Comp, E_Component);
21236             Set_Is_Tag                    (Tag_Comp);
21237             Set_Is_Aliased                (Tag_Comp);
21238             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
21239             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
21240             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
21241             Init_Component_Location       (Tag_Comp);
21242 
21243             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
21244             --  implemented interfaces.
21245 
21246             if Has_Interfaces (T) then
21247                Add_Interface_Tag_Components (N, T);
21248             end if;
21249          end if;
21250 
21251          Make_Class_Wide_Type (T);
21252          Set_Direct_Primitive_Operations (T, New_Elmt_List);
21253       end if;
21254 
21255       --  We must suppress range checks when processing record components in
21256       --  the presence of discriminants, since we don't want spurious checks to
21257       --  be generated during their analysis, but Suppress_Range_Checks flags
21258       --  must be reset the after processing the record definition.
21259 
21260       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
21261       --  couldn't we just use the normal range check suppression method here.
21262       --  That would seem cleaner ???
21263 
21264       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
21265          Set_Kill_Range_Checks (T, True);
21266          Record_Type_Definition (Def, Prev);
21267          Set_Kill_Range_Checks (T, False);
21268       else
21269          Record_Type_Definition (Def, Prev);
21270       end if;
21271 
21272       --  Exit from record scope
21273 
21274       End_Scope;
21275 
21276       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
21277       --  the implemented interfaces and associate them an aliased entity.
21278 
21279       if Is_Tagged
21280         and then not Is_Empty_List (Interface_List (Def))
21281       then
21282          Derive_Progenitor_Subprograms (T, T);
21283       end if;
21284 
21285       Check_Function_Writable_Actuals (N);
21286    end Record_Type_Declaration;
21287 
21288    ----------------------------
21289    -- Record_Type_Definition --
21290    ----------------------------
21291 
21292    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
21293       Component          : Entity_Id;
21294       Ctrl_Components    : Boolean := False;
21295       Final_Storage_Only : Boolean;
21296       T                  : Entity_Id;
21297 
21298    begin
21299       if Ekind (Prev_T) = E_Incomplete_Type then
21300          T := Full_View (Prev_T);
21301       else
21302          T := Prev_T;
21303       end if;
21304 
21305       --  In SPARK, tagged types and type extensions may only be declared in
21306       --  the specification of library unit packages.
21307 
21308       if Present (Def) and then Is_Tagged_Type (T) then
21309          declare
21310             Typ  : Node_Id;
21311             Ctxt : Node_Id;
21312 
21313          begin
21314             if Nkind (Parent (Def)) = N_Full_Type_Declaration then
21315                Typ := Parent (Def);
21316             else
21317                pragma Assert
21318                  (Nkind (Parent (Def)) = N_Derived_Type_Definition);
21319                Typ := Parent (Parent (Def));
21320             end if;
21321 
21322             Ctxt := Parent (Typ);
21323 
21324             if Nkind (Ctxt) = N_Package_Body
21325               and then Nkind (Parent (Ctxt)) = N_Compilation_Unit
21326             then
21327                Check_SPARK_05_Restriction
21328                  ("type should be defined in package specification", Typ);
21329 
21330             elsif Nkind (Ctxt) /= N_Package_Specification
21331               or else Nkind (Parent (Parent (Ctxt))) /= N_Compilation_Unit
21332             then
21333                Check_SPARK_05_Restriction
21334                  ("type should be defined in library unit package", Typ);
21335             end if;
21336          end;
21337       end if;
21338 
21339       Final_Storage_Only := not Is_Controlled_Active (T);
21340 
21341       --  Ada 2005: Check whether an explicit Limited is present in a derived
21342       --  type declaration.
21343 
21344       if Nkind (Parent (Def)) = N_Derived_Type_Definition
21345         and then Limited_Present (Parent (Def))
21346       then
21347          Set_Is_Limited_Record (T);
21348       end if;
21349 
21350       --  If the component list of a record type is defined by the reserved
21351       --  word null and there is no discriminant part, then the record type has
21352       --  no components and all records of the type are null records (RM 3.7)
21353       --  This procedure is also called to process the extension part of a
21354       --  record extension, in which case the current scope may have inherited
21355       --  components.
21356 
21357       if No (Def)
21358         or else No (Component_List (Def))
21359         or else Null_Present (Component_List (Def))
21360       then
21361          if not Is_Tagged_Type (T) then
21362             Check_SPARK_05_Restriction ("untagged record cannot be null", Def);
21363          end if;
21364 
21365       else
21366          Analyze_Declarations (Component_Items (Component_List (Def)));
21367 
21368          if Present (Variant_Part (Component_List (Def))) then
21369             Check_SPARK_05_Restriction ("variant part is not allowed", Def);
21370             Analyze (Variant_Part (Component_List (Def)));
21371          end if;
21372       end if;
21373 
21374       --  After completing the semantic analysis of the record definition,
21375       --  record components, both new and inherited, are accessible. Set their
21376       --  kind accordingly. Exclude malformed itypes from illegal declarations,
21377       --  whose Ekind may be void.
21378 
21379       Component := First_Entity (Current_Scope);
21380       while Present (Component) loop
21381          if Ekind (Component) = E_Void
21382            and then not Is_Itype (Component)
21383          then
21384             Set_Ekind (Component, E_Component);
21385             Init_Component_Location (Component);
21386          end if;
21387 
21388          Propagate_Concurrent_Flags (T, Etype (Component));
21389 
21390          if Ekind (Component) /= E_Component then
21391             null;
21392 
21393          --  Do not set Has_Controlled_Component on a class-wide equivalent
21394          --  type. See Make_CW_Equivalent_Type.
21395 
21396          elsif not Is_Class_Wide_Equivalent_Type (T)
21397            and then (Has_Controlled_Component (Etype (Component))
21398                       or else (Chars (Component) /= Name_uParent
21399                                 and then Is_Controlled_Active
21400                                            (Etype (Component))))
21401          then
21402             Set_Has_Controlled_Component (T, True);
21403             Final_Storage_Only :=
21404               Final_Storage_Only
21405                 and then Finalize_Storage_Only (Etype (Component));
21406             Ctrl_Components := True;
21407          end if;
21408 
21409          Next_Entity (Component);
21410       end loop;
21411 
21412       --  A Type is Finalize_Storage_Only only if all its controlled components
21413       --  are also.
21414 
21415       if Ctrl_Components then
21416          Set_Finalize_Storage_Only (T, Final_Storage_Only);
21417       end if;
21418 
21419       --  Place reference to end record on the proper entity, which may
21420       --  be a partial view.
21421 
21422       if Present (Def) then
21423          Process_End_Label (Def, 'e', Prev_T);
21424       end if;
21425    end Record_Type_Definition;
21426 
21427    ------------------------
21428    -- Replace_Components --
21429    ------------------------
21430 
21431    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
21432       function Process (N : Node_Id) return Traverse_Result;
21433 
21434       -------------
21435       -- Process --
21436       -------------
21437 
21438       function Process (N : Node_Id) return Traverse_Result is
21439          Comp : Entity_Id;
21440 
21441       begin
21442          if Nkind (N) = N_Discriminant_Specification then
21443             Comp := First_Discriminant (Typ);
21444             while Present (Comp) loop
21445                if Chars (Comp) = Chars (Defining_Identifier (N)) then
21446                   Set_Defining_Identifier (N, Comp);
21447                   exit;
21448                end if;
21449 
21450                Next_Discriminant (Comp);
21451             end loop;
21452 
21453          elsif Nkind (N) = N_Component_Declaration then
21454             Comp := First_Component (Typ);
21455             while Present (Comp) loop
21456                if Chars (Comp) = Chars (Defining_Identifier (N)) then
21457                   Set_Defining_Identifier (N, Comp);
21458                   exit;
21459                end if;
21460 
21461                Next_Component (Comp);
21462             end loop;
21463          end if;
21464 
21465          return OK;
21466       end Process;
21467 
21468       procedure Replace is new Traverse_Proc (Process);
21469 
21470    --  Start of processing for Replace_Components
21471 
21472    begin
21473       Replace (Decl);
21474    end Replace_Components;
21475 
21476    -------------------------------
21477    -- Set_Completion_Referenced --
21478    -------------------------------
21479 
21480    procedure Set_Completion_Referenced (E : Entity_Id) is
21481    begin
21482       --  If in main unit, mark entity that is a completion as referenced,
21483       --  warnings go on the partial view when needed.
21484 
21485       if In_Extended_Main_Source_Unit (E) then
21486          Set_Referenced (E);
21487       end if;
21488    end Set_Completion_Referenced;
21489 
21490    ---------------------
21491    -- Set_Default_SSO --
21492    ---------------------
21493 
21494    procedure Set_Default_SSO (T : Entity_Id) is
21495    begin
21496       case Opt.Default_SSO is
21497          when ' ' =>
21498             null;
21499          when 'L' =>
21500             Set_SSO_Set_Low_By_Default (T, True);
21501          when 'H' =>
21502             Set_SSO_Set_High_By_Default (T, True);
21503          when others =>
21504             raise Program_Error;
21505       end case;
21506    end Set_Default_SSO;
21507 
21508    ---------------------
21509    -- Set_Fixed_Range --
21510    ---------------------
21511 
21512    --  The range for fixed-point types is complicated by the fact that we
21513    --  do not know the exact end points at the time of the declaration. This
21514    --  is true for three reasons:
21515 
21516    --     A size clause may affect the fudging of the end-points.
21517    --     A small clause may affect the values of the end-points.
21518    --     We try to include the end-points if it does not affect the size.
21519 
21520    --  This means that the actual end-points must be established at the
21521    --  point when the type is frozen. Meanwhile, we first narrow the range
21522    --  as permitted (so that it will fit if necessary in a small specified
21523    --  size), and then build a range subtree with these narrowed bounds.
21524    --  Set_Fixed_Range constructs the range from real literal values, and
21525    --  sets the range as the Scalar_Range of the given fixed-point type entity.
21526 
21527    --  The parent of this range is set to point to the entity so that it is
21528    --  properly hooked into the tree (unlike normal Scalar_Range entries for
21529    --  other scalar types, which are just pointers to the range in the
21530    --  original tree, this would otherwise be an orphan).
21531 
21532    --  The tree is left unanalyzed. When the type is frozen, the processing
21533    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
21534    --  analyzed, and uses this as an indication that it should complete
21535    --  work on the range (it will know the final small and size values).
21536 
21537    procedure Set_Fixed_Range
21538      (E   : Entity_Id;
21539       Loc : Source_Ptr;
21540       Lo  : Ureal;
21541       Hi  : Ureal)
21542    is
21543       S : constant Node_Id :=
21544             Make_Range (Loc,
21545               Low_Bound  => Make_Real_Literal (Loc, Lo),
21546               High_Bound => Make_Real_Literal (Loc, Hi));
21547    begin
21548       Set_Scalar_Range (E, S);
21549       Set_Parent (S, E);
21550 
21551       --  Before the freeze point, the bounds of a fixed point are universal
21552       --  and carry the corresponding type.
21553 
21554       Set_Etype (Low_Bound (S),  Universal_Real);
21555       Set_Etype (High_Bound (S), Universal_Real);
21556    end Set_Fixed_Range;
21557 
21558    ----------------------------------
21559    -- Set_Scalar_Range_For_Subtype --
21560    ----------------------------------
21561 
21562    procedure Set_Scalar_Range_For_Subtype
21563      (Def_Id : Entity_Id;
21564       R      : Node_Id;
21565       Subt   : Entity_Id)
21566    is
21567       Kind : constant Entity_Kind := Ekind (Def_Id);
21568 
21569    begin
21570       --  Defend against previous error
21571 
21572       if Nkind (R) = N_Error then
21573          return;
21574       end if;
21575 
21576       Set_Scalar_Range (Def_Id, R);
21577 
21578       --  We need to link the range into the tree before resolving it so
21579       --  that types that are referenced, including importantly the subtype
21580       --  itself, are properly frozen (Freeze_Expression requires that the
21581       --  expression be properly linked into the tree). Of course if it is
21582       --  already linked in, then we do not disturb the current link.
21583 
21584       if No (Parent (R)) then
21585          Set_Parent (R, Def_Id);
21586       end if;
21587 
21588       --  Reset the kind of the subtype during analysis of the range, to
21589       --  catch possible premature use in the bounds themselves.
21590 
21591       Set_Ekind (Def_Id, E_Void);
21592       Process_Range_Expr_In_Decl (R, Subt, Subtyp => Def_Id);
21593       Set_Ekind (Def_Id, Kind);
21594    end Set_Scalar_Range_For_Subtype;
21595 
21596    --------------------------------------------------------
21597    -- Set_Stored_Constraint_From_Discriminant_Constraint --
21598    --------------------------------------------------------
21599 
21600    procedure Set_Stored_Constraint_From_Discriminant_Constraint
21601      (E : Entity_Id)
21602    is
21603    begin
21604       --  Make sure set if encountered during Expand_To_Stored_Constraint
21605 
21606       Set_Stored_Constraint (E, No_Elist);
21607 
21608       --  Give it the right value
21609 
21610       if Is_Constrained (E) and then Has_Discriminants (E) then
21611          Set_Stored_Constraint (E,
21612            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
21613       end if;
21614    end Set_Stored_Constraint_From_Discriminant_Constraint;
21615 
21616    -------------------------------------
21617    -- Signed_Integer_Type_Declaration --
21618    -------------------------------------
21619 
21620    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
21621       Implicit_Base : Entity_Id;
21622       Base_Typ      : Entity_Id;
21623       Lo_Val        : Uint;
21624       Hi_Val        : Uint;
21625       Errs          : Boolean := False;
21626       Lo            : Node_Id;
21627       Hi            : Node_Id;
21628 
21629       function Can_Derive_From (E : Entity_Id) return Boolean;
21630       --  Determine whether given bounds allow derivation from specified type
21631 
21632       procedure Check_Bound (Expr : Node_Id);
21633       --  Check bound to make sure it is integral and static. If not, post
21634       --  appropriate error message and set Errs flag
21635 
21636       ---------------------
21637       -- Can_Derive_From --
21638       ---------------------
21639 
21640       --  Note we check both bounds against both end values, to deal with
21641       --  strange types like ones with a range of 0 .. -12341234.
21642 
21643       function Can_Derive_From (E : Entity_Id) return Boolean is
21644          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
21645          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
21646       begin
21647          return Lo <= Lo_Val and then Lo_Val <= Hi
21648                   and then
21649                 Lo <= Hi_Val and then Hi_Val <= Hi;
21650       end Can_Derive_From;
21651 
21652       -----------------
21653       -- Check_Bound --
21654       -----------------
21655 
21656       procedure Check_Bound (Expr : Node_Id) is
21657       begin
21658          --  If a range constraint is used as an integer type definition, each
21659          --  bound of the range must be defined by a static expression of some
21660          --  integer type, but the two bounds need not have the same integer
21661          --  type (Negative bounds are allowed.) (RM 3.5.4)
21662 
21663          if not Is_Integer_Type (Etype (Expr)) then
21664             Error_Msg_N
21665               ("integer type definition bounds must be of integer type", Expr);
21666             Errs := True;
21667 
21668          elsif not Is_OK_Static_Expression (Expr) then
21669             Flag_Non_Static_Expr
21670               ("non-static expression used for integer type bound!", Expr);
21671             Errs := True;
21672 
21673          --  The bounds are folded into literals, and we set their type to be
21674          --  universal, to avoid typing difficulties: we cannot set the type
21675          --  of the literal to the new type, because this would be a forward
21676          --  reference for the back end,  and if the original type is user-
21677          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
21678 
21679          else
21680             if Is_Entity_Name (Expr) then
21681                Fold_Uint (Expr, Expr_Value (Expr), True);
21682             end if;
21683 
21684             Set_Etype (Expr, Universal_Integer);
21685          end if;
21686       end Check_Bound;
21687 
21688    --  Start of processing for Signed_Integer_Type_Declaration
21689 
21690    begin
21691       --  Create an anonymous base type
21692 
21693       Implicit_Base :=
21694         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
21695 
21696       --  Analyze and check the bounds, they can be of any integer type
21697 
21698       Lo := Low_Bound (Def);
21699       Hi := High_Bound (Def);
21700 
21701       --  Arbitrarily use Integer as the type if either bound had an error
21702 
21703       if Hi = Error or else Lo = Error then
21704          Base_Typ := Any_Integer;
21705          Set_Error_Posted (T, True);
21706 
21707       --  Here both bounds are OK expressions
21708 
21709       else
21710          Analyze_And_Resolve (Lo, Any_Integer);
21711          Analyze_And_Resolve (Hi, Any_Integer);
21712 
21713          Check_Bound (Lo);
21714          Check_Bound (Hi);
21715 
21716          if Errs then
21717             Hi := Type_High_Bound (Standard_Long_Long_Integer);
21718             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
21719          end if;
21720 
21721          --  Find type to derive from
21722 
21723          Lo_Val := Expr_Value (Lo);
21724          Hi_Val := Expr_Value (Hi);
21725 
21726          if Can_Derive_From (Standard_Short_Short_Integer) then
21727             Base_Typ := Base_Type (Standard_Short_Short_Integer);
21728 
21729          elsif Can_Derive_From (Standard_Short_Integer) then
21730             Base_Typ := Base_Type (Standard_Short_Integer);
21731 
21732          elsif Can_Derive_From (Standard_Integer) then
21733             Base_Typ := Base_Type (Standard_Integer);
21734 
21735          elsif Can_Derive_From (Standard_Long_Integer) then
21736             Base_Typ := Base_Type (Standard_Long_Integer);
21737 
21738          elsif Can_Derive_From (Standard_Long_Long_Integer) then
21739             Check_Restriction (No_Long_Long_Integers, Def);
21740             Base_Typ := Base_Type (Standard_Long_Long_Integer);
21741 
21742          else
21743             Base_Typ := Base_Type (Standard_Long_Long_Integer);
21744             Error_Msg_N ("integer type definition bounds out of range", Def);
21745             Hi := Type_High_Bound (Standard_Long_Long_Integer);
21746             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
21747          end if;
21748       end if;
21749 
21750       --  Complete both implicit base and declared first subtype entities. The
21751       --  inheritance of the rep item chain ensures that SPARK-related pragmas
21752       --  are not clobbered when the signed integer type acts as a full view of
21753       --  a private type.
21754 
21755       Set_Etype          (Implicit_Base,                 Base_Typ);
21756       Set_Size_Info      (Implicit_Base,                 Base_Typ);
21757       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
21758       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
21759       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
21760 
21761       Set_Ekind              (T, E_Signed_Integer_Subtype);
21762       Set_Etype              (T, Implicit_Base);
21763       Set_Size_Info          (T, Implicit_Base);
21764       Inherit_Rep_Item_Chain (T, Implicit_Base);
21765       Set_Scalar_Range       (T, Def);
21766       Set_RM_Size            (T, UI_From_Int (Minimum_Size (T)));
21767       Set_Is_Constrained     (T);
21768    end Signed_Integer_Type_Declaration;
21769 
21770 end Sem_Ch3;