OSDN Git Service

89583ddf14724fd242d7cbf160fb74e42103273b
[pf3gnuchains/gcc-fork.git] / gcc / ada / 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-2011, 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 Atree;    use Atree;
27 with Checks;   use Checks;
28 with Debug;    use Debug;
29 with Elists;   use Elists;
30 with Einfo;    use Einfo;
31 with Errout;   use Errout;
32 with Eval_Fat; use Eval_Fat;
33 with Exp_Ch3;  use Exp_Ch3;
34 with Exp_Ch9;  use Exp_Ch9;
35 with Exp_Disp; use Exp_Disp;
36 with Exp_Dist; use Exp_Dist;
37 with Exp_Tss;  use Exp_Tss;
38 with Exp_Util; use Exp_Util;
39 with Fname;    use Fname;
40 with Freeze;   use Freeze;
41 with Itypes;   use Itypes;
42 with Layout;   use Layout;
43 with Lib;      use Lib;
44 with Lib.Xref; use Lib.Xref;
45 with Namet;    use Namet;
46 with Nmake;    use Nmake;
47 with Opt;      use Opt;
48 with Restrict; use Restrict;
49 with Rident;   use Rident;
50 with Rtsfind;  use Rtsfind;
51 with Sem;      use Sem;
52 with Sem_Aux;  use Sem_Aux;
53 with Sem_Case; use Sem_Case;
54 with Sem_Cat;  use Sem_Cat;
55 with Sem_Ch6;  use Sem_Ch6;
56 with Sem_Ch7;  use Sem_Ch7;
57 with Sem_Ch8;  use Sem_Ch8;
58 with Sem_Ch13; use Sem_Ch13;
59 with Sem_Disp; use Sem_Disp;
60 with Sem_Dist; use Sem_Dist;
61 with Sem_Elim; use Sem_Elim;
62 with Sem_Eval; use Sem_Eval;
63 with Sem_Mech; use Sem_Mech;
64 with Sem_Prag; use Sem_Prag;
65 with Sem_Res;  use Sem_Res;
66 with Sem_Smem; use Sem_Smem;
67 with Sem_Type; use Sem_Type;
68 with Sem_Util; use Sem_Util;
69 with Sem_Warn; use Sem_Warn;
70 with Stand;    use Stand;
71 with Sinfo;    use Sinfo;
72 with Sinput;   use Sinput;
73 with Snames;   use Snames;
74 with Targparm; use Targparm;
75 with Tbuild;   use Tbuild;
76 with Ttypes;   use Ttypes;
77 with Uintp;    use Uintp;
78 with Urealp;   use Urealp;
79
80 package body Sem_Ch3 is
81
82    -----------------------
83    -- Local Subprograms --
84    -----------------------
85
86    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
87    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
88    --  abstract interface types implemented by a record type or a derived
89    --  record type.
90
91    procedure Build_Derived_Type
92      (N             : Node_Id;
93       Parent_Type   : Entity_Id;
94       Derived_Type  : Entity_Id;
95       Is_Completion : Boolean;
96       Derive_Subps  : Boolean := True);
97    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
98    --  the N_Full_Type_Declaration node containing the derived type definition.
99    --  Parent_Type is the entity for the parent type in the derived type
100    --  definition and Derived_Type the actual derived type. Is_Completion must
101    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
102    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
103    --  completion of a private type declaration. If Is_Completion is set to
104    --  True, N is the completion of a private type declaration and Derived_Type
105    --  is different from the defining identifier inside N (i.e. Derived_Type /=
106    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
107    --  subprograms should be derived. The only case where this parameter is
108    --  False is when Build_Derived_Type is recursively called to process an
109    --  implicit derived full type for a type derived from a private type (in
110    --  that case the subprograms must only be derived for the private view of
111    --  the type).
112    --
113    --  ??? These flags need a bit of re-examination and re-documentation:
114    --  ???  are they both necessary (both seem related to the recursion)?
115
116    procedure Build_Derived_Access_Type
117      (N            : Node_Id;
118       Parent_Type  : Entity_Id;
119       Derived_Type : Entity_Id);
120    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
121    --  create an implicit base if the parent type is constrained or if the
122    --  subtype indication has a constraint.
123
124    procedure Build_Derived_Array_Type
125      (N            : Node_Id;
126       Parent_Type  : Entity_Id;
127       Derived_Type : Entity_Id);
128    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
129    --  create an implicit base if the parent type is constrained or if the
130    --  subtype indication has a constraint.
131
132    procedure Build_Derived_Concurrent_Type
133      (N            : Node_Id;
134       Parent_Type  : Entity_Id;
135       Derived_Type : Entity_Id);
136    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
137    --  protected type, inherit entries and protected subprograms, check
138    --  legality of discriminant constraints if any.
139
140    procedure Build_Derived_Enumeration_Type
141      (N            : Node_Id;
142       Parent_Type  : Entity_Id;
143       Derived_Type : Entity_Id);
144    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
145    --  type, we must create a new list of literals. Types derived from
146    --  Character and [Wide_]Wide_Character are special-cased.
147
148    procedure Build_Derived_Numeric_Type
149      (N            : Node_Id;
150       Parent_Type  : Entity_Id;
151       Derived_Type : Entity_Id);
152    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
153    --  an anonymous base type, and propagate constraint to subtype if needed.
154
155    procedure Build_Derived_Private_Type
156      (N             : Node_Id;
157       Parent_Type   : Entity_Id;
158       Derived_Type  : Entity_Id;
159       Is_Completion : Boolean;
160       Derive_Subps  : Boolean := True);
161    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
162    --  because the parent may or may not have a completion, and the derivation
163    --  may itself be a completion.
164
165    procedure Build_Derived_Record_Type
166      (N            : Node_Id;
167       Parent_Type  : Entity_Id;
168       Derived_Type : Entity_Id;
169       Derive_Subps : Boolean := True);
170    --  Subsidiary procedure for Build_Derived_Type and
171    --  Analyze_Private_Extension_Declaration used for tagged and untagged
172    --  record types. All parameters are as in Build_Derived_Type except that
173    --  N, in addition to being an N_Full_Type_Declaration node, can also be an
174    --  N_Private_Extension_Declaration node. See the definition of this routine
175    --  for much more info. Derive_Subps indicates whether subprograms should
176    --  be derived from the parent type. The only case where Derive_Subps is
177    --  False is for an implicit derived full type for a type derived from a
178    --  private type (see Build_Derived_Type).
179
180    procedure Build_Discriminal (Discrim : Entity_Id);
181    --  Create the discriminal corresponding to discriminant Discrim, that is
182    --  the parameter corresponding to Discrim to be used in initialization
183    --  procedures for the type where Discrim is a discriminant. Discriminals
184    --  are not used during semantic analysis, and are not fully defined
185    --  entities until expansion. Thus they are not given a scope until
186    --  initialization procedures are built.
187
188    function Build_Discriminant_Constraints
189      (T           : Entity_Id;
190       Def         : Node_Id;
191       Derived_Def : Boolean := False) return Elist_Id;
192    --  Validate discriminant constraints and return the list of the constraints
193    --  in order of discriminant declarations, where T is the discriminated
194    --  unconstrained type. Def is the N_Subtype_Indication node where the
195    --  discriminants constraints for T are specified. Derived_Def is True
196    --  when building the discriminant constraints in a derived type definition
197    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
198    --  type and Def is the constraint "(xxx)" on T and this routine sets the
199    --  Corresponding_Discriminant field of the discriminants in the derived
200    --  type D to point to the corresponding discriminants in the parent type T.
201
202    procedure Build_Discriminated_Subtype
203      (T           : Entity_Id;
204       Def_Id      : Entity_Id;
205       Elist       : Elist_Id;
206       Related_Nod : Node_Id;
207       For_Access  : Boolean := False);
208    --  Subsidiary procedure to Constrain_Discriminated_Type and to
209    --  Process_Incomplete_Dependents. Given
210    --
211    --     T (a possibly discriminated base type)
212    --     Def_Id (a very partially built subtype for T),
213    --
214    --  the call completes Def_Id to be the appropriate E_*_Subtype.
215    --
216    --  The Elist is the list of discriminant constraints if any (it is set
217    --  to No_Elist if T is not a discriminated type, and to an empty list if
218    --  T has discriminants but there are no discriminant constraints). The
219    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
220    --  The For_Access says whether or not this subtype is really constraining
221    --  an access type. That is its sole purpose is the designated type of an
222    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
223    --  is built to avoid freezing T when the access subtype is frozen.
224
225    function Build_Scalar_Bound
226      (Bound : Node_Id;
227       Par_T : Entity_Id;
228       Der_T : Entity_Id) return Node_Id;
229    --  The bounds of a derived scalar type are conversions of the bounds of
230    --  the parent type. Optimize the representation if the bounds are literals.
231    --  Needs a more complete spec--what are the parameters exactly, and what
232    --  exactly is the returned value, and how is Bound affected???
233
234    procedure Build_Underlying_Full_View
235      (N   : Node_Id;
236       Typ : Entity_Id;
237       Par : Entity_Id);
238    --  If the completion of a private type is itself derived from a private
239    --  type, or if the full view of a private subtype is itself private, the
240    --  back-end has no way to compute the actual size of this type. We build
241    --  an internal subtype declaration of the proper parent type to convey
242    --  this information. This extra mechanism is needed because a full
243    --  view cannot itself have a full view (it would get clobbered during
244    --  view exchanges).
245
246    procedure Check_Access_Discriminant_Requires_Limited
247      (D   : Node_Id;
248       Loc : Node_Id);
249    --  Check the restriction that the type to which an access discriminant
250    --  belongs must be a concurrent type or a descendant of a type with
251    --  the reserved word 'limited' in its declaration.
252
253    procedure Check_Anonymous_Access_Components
254       (Typ_Decl  : Node_Id;
255        Typ       : Entity_Id;
256        Prev      : Entity_Id;
257        Comp_List : Node_Id);
258    --  Ada 2005 AI-382: an access component in a record definition can refer to
259    --  the enclosing record, in which case it denotes the type itself, and not
260    --  the current instance of the type. We create an anonymous access type for
261    --  the component, and flag it as an access to a component, so accessibility
262    --  checks are properly performed on it. The declaration of the access type
263    --  is placed ahead of that of the record to prevent order-of-elaboration
264    --  circularity issues in Gigi. We create an incomplete type for the record
265    --  declaration, which is the designated type of the anonymous access.
266
267    procedure Check_Delta_Expression (E : Node_Id);
268    --  Check that the expression represented by E is suitable for use as a
269    --  delta expression, i.e. it is of real type and is static.
270
271    procedure Check_Digits_Expression (E : Node_Id);
272    --  Check that the expression represented by E is suitable for use as a
273    --  digits expression, i.e. it is of integer type, positive and static.
274
275    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
276    --  Validate the initialization of an object declaration. T is the required
277    --  type, and Exp is the initialization expression.
278
279    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
280    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
281
282    procedure Check_Or_Process_Discriminants
283      (N    : Node_Id;
284       T    : Entity_Id;
285       Prev : Entity_Id := Empty);
286    --  If N is the full declaration of the completion T of an incomplete or
287    --  private type, check its discriminants (which are already known to be
288    --  conformant with those of the partial view, see Find_Type_Name),
289    --  otherwise process them. Prev is the entity of the partial declaration,
290    --  if any.
291
292    procedure Check_Real_Bound (Bound : Node_Id);
293    --  Check given bound for being of real type and static. If not, post an
294    --  appropriate message, and rewrite the bound with the real literal zero.
295
296    procedure Constant_Redeclaration
297      (Id : Entity_Id;
298       N  : Node_Id;
299       T  : out Entity_Id);
300    --  Various checks on legality of full declaration of deferred constant.
301    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
302    --  node. The caller has not yet set any attributes of this entity.
303
304    function Contain_Interface
305      (Iface  : Entity_Id;
306       Ifaces : Elist_Id) return Boolean;
307    --  Ada 2005: Determine whether Iface is present in the list Ifaces
308
309    procedure Convert_Scalar_Bounds
310      (N            : Node_Id;
311       Parent_Type  : Entity_Id;
312       Derived_Type : Entity_Id;
313       Loc          : Source_Ptr);
314    --  For derived scalar types, convert the bounds in the type definition to
315    --  the derived type, and complete their analysis. Given a constraint of the
316    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
317    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
318    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
319    --  subtype are conversions of those bounds to the derived_type, so that
320    --  their typing is consistent.
321
322    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
323    --  Copies attributes from array base type T2 to array base type T1. Copies
324    --  only attributes that apply to base types, but not subtypes.
325
326    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
327    --  Copies attributes from array subtype T2 to array subtype T1. Copies
328    --  attributes that apply to both subtypes and base types.
329
330    procedure Create_Constrained_Components
331      (Subt        : Entity_Id;
332       Decl_Node   : Node_Id;
333       Typ         : Entity_Id;
334       Constraints : Elist_Id);
335    --  Build the list of entities for a constrained discriminated record
336    --  subtype. If a component depends on a discriminant, replace its subtype
337    --  using the discriminant values in the discriminant constraint. Subt
338    --  is the defining identifier for the subtype whose list of constrained
339    --  entities we will create. Decl_Node is the type declaration node where
340    --  we will attach all the itypes created. Typ is the base discriminated
341    --  type for the subtype Subt. Constraints is the list of discriminant
342    --  constraints for Typ.
343
344    function Constrain_Component_Type
345      (Comp            : Entity_Id;
346       Constrained_Typ : Entity_Id;
347       Related_Node    : Node_Id;
348       Typ             : Entity_Id;
349       Constraints     : Elist_Id) return Entity_Id;
350    --  Given a discriminated base type Typ, a list of discriminant constraint
351    --  Constraints for Typ and a component of Typ, with type Compon_Type,
352    --  create and return the type corresponding to Compon_type where all
353    --  discriminant references are replaced with the corresponding constraint.
354    --  If no discriminant references occur in Compon_Typ then return it as is.
355    --  Constrained_Typ is the final constrained subtype to which the
356    --  constrained Compon_Type belongs. Related_Node is the node where we will
357    --  attach all the itypes created.
358    --
359    --  Above description is confused, what is Compon_Type???
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;
413       Related_Id  : Entity_Id) return Entity_Id;
414    --  When constraining a protected type or task type with discriminants,
415    --  constrain the corresponding record with the same discriminant values.
416
417    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
418    --  Constrain a decimal fixed point type with a digits constraint and/or a
419    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
420
421    procedure Constrain_Discriminated_Type
422      (Def_Id      : Entity_Id;
423       S           : Node_Id;
424       Related_Nod : Node_Id;
425       For_Access  : Boolean := False);
426    --  Process discriminant constraints of composite type. Verify that values
427    --  have been provided for all discriminants, that the original type is
428    --  unconstrained, and that the types of the supplied expressions match
429    --  the discriminant types. The first three parameters are like in routine
430    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
431    --  of For_Access.
432
433    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
434    --  Constrain an enumeration type with a range constraint. This is identical
435    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
436
437    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
438    --  Constrain a floating point type with either a digits constraint
439    --  and/or a range constraint, building a E_Floating_Point_Subtype.
440
441    procedure Constrain_Index
442      (Index        : Node_Id;
443       S            : Node_Id;
444       Related_Nod  : Node_Id;
445       Related_Id   : Entity_Id;
446       Suffix       : Character;
447       Suffix_Index : Nat);
448    --  Process an index constraint S in a constrained array declaration. The
449    --  constraint can be a subtype name, or a range with or without an explicit
450    --  subtype mark. The index is the corresponding index of the unconstrained
451    --  array. The Related_Id and Suffix parameters are used to build the
452    --  associated Implicit type name.
453
454    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
455    --  Build subtype of a signed or modular integer type
456
457    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
458    --  Constrain an ordinary fixed point type with a range constraint, and
459    --  build an E_Ordinary_Fixed_Point_Subtype entity.
460
461    procedure Copy_And_Swap (Priv, Full : Entity_Id);
462    --  Copy the Priv entity into the entity of its full declaration then swap
463    --  the two entities in such a manner that the former private type is now
464    --  seen as a full type.
465
466    procedure Decimal_Fixed_Point_Type_Declaration
467      (T   : Entity_Id;
468       Def : Node_Id);
469    --  Create a new decimal fixed point type, and apply the constraint to
470    --  obtain a subtype of this new type.
471
472    procedure Complete_Private_Subtype
473      (Priv        : Entity_Id;
474       Full        : Entity_Id;
475       Full_Base   : Entity_Id;
476       Related_Nod : Node_Id);
477    --  Complete the implicit full view of a private subtype by setting the
478    --  appropriate semantic fields. If the full view of the parent is a record
479    --  type, build constrained components of subtype.
480
481    procedure Derive_Progenitor_Subprograms
482      (Parent_Type : Entity_Id;
483       Tagged_Type : Entity_Id);
484    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
485    --  operations of progenitors of Tagged_Type, and replace the subsidiary
486    --  subtypes with Tagged_Type, to build the specs of the inherited interface
487    --  primitives. The derived primitives are aliased to those of the
488    --  interface. This routine takes care also of transferring to the full view
489    --  subprograms associated with the partial view of Tagged_Type that cover
490    --  interface primitives.
491
492    procedure Derived_Standard_Character
493      (N             : Node_Id;
494       Parent_Type   : Entity_Id;
495       Derived_Type  : Entity_Id);
496    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
497    --  derivations from types Standard.Character and Standard.Wide_Character.
498
499    procedure Derived_Type_Declaration
500      (T             : Entity_Id;
501       N             : Node_Id;
502       Is_Completion : Boolean);
503    --  Process a derived type declaration. Build_Derived_Type is invoked
504    --  to process the actual derived type definition. Parameters N and
505    --  Is_Completion have the same meaning as in Build_Derived_Type.
506    --  T is the N_Defining_Identifier for the entity defined in the
507    --  N_Full_Type_Declaration node N, that is T is the derived type.
508
509    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
510    --  Insert each literal in symbol table, as an overloadable identifier. Each
511    --  enumeration type is mapped into a sequence of integers, and each literal
512    --  is defined as a constant with integer value. If any of the literals are
513    --  character literals, the type is a character type, which means that
514    --  strings are legal aggregates for arrays of components of the type.
515
516    function Expand_To_Stored_Constraint
517      (Typ        : Entity_Id;
518       Constraint : Elist_Id) return Elist_Id;
519    --  Given a constraint (i.e. a list of expressions) on the discriminants of
520    --  Typ, expand it into a constraint on the stored discriminants and return
521    --  the new list of expressions constraining the stored discriminants.
522
523    function Find_Type_Of_Object
524      (Obj_Def     : Node_Id;
525       Related_Nod : Node_Id) return Entity_Id;
526    --  Get type entity for object referenced by Obj_Def, attaching the
527    --  implicit types generated to Related_Nod
528
529    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
530    --  Create a new float and apply the constraint to obtain subtype of it
531
532    function Has_Range_Constraint (N : Node_Id) return Boolean;
533    --  Given an N_Subtype_Indication node N, return True if a range constraint
534    --  is present, either directly, or as part of a digits or delta constraint.
535    --  In addition, a digits constraint in the decimal case returns True, since
536    --  it establishes a default range if no explicit range is present.
537
538    function Inherit_Components
539      (N             : Node_Id;
540       Parent_Base   : Entity_Id;
541       Derived_Base  : Entity_Id;
542       Is_Tagged     : Boolean;
543       Inherit_Discr : Boolean;
544       Discs         : Elist_Id) return Elist_Id;
545    --  Called from Build_Derived_Record_Type to inherit the components of
546    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
547    --  For more information on derived types and component inheritance please
548    --  consult the comment above the body of Build_Derived_Record_Type.
549    --
550    --    N is the original derived type declaration
551    --
552    --    Is_Tagged is set if we are dealing with tagged types
553    --
554    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
555    --    Parent_Base, otherwise no discriminants are inherited.
556    --
557    --    Discs gives the list of constraints that apply to Parent_Base in the
558    --    derived type declaration. If Discs is set to No_Elist, then we have
559    --    the following situation:
560    --
561    --      type Parent (D1..Dn : ..) is [tagged] record ...;
562    --      type Derived is new Parent [with ...];
563    --
564    --    which gets treated as
565    --
566    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
567    --
568    --  For untagged types the returned value is an association list. The list
569    --  starts from the association (Parent_Base => Derived_Base), and then it
570    --  contains a sequence of the associations of the form
571    --
572    --    (Old_Component => New_Component),
573    --
574    --  where Old_Component is the Entity_Id of a component in Parent_Base and
575    --  New_Component is the Entity_Id of the corresponding component in
576    --  Derived_Base. For untagged records, this association list is needed when
577    --  copying the record declaration for the derived base. In the tagged case
578    --  the value returned is irrelevant.
579
580    function Is_Valid_Constraint_Kind
581      (T_Kind          : Type_Kind;
582       Constraint_Kind : Node_Kind) return Boolean;
583    --  Returns True if it is legal to apply the given kind of constraint to the
584    --  given kind of type (index constraint to an array type, for example).
585
586    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
587    --  Create new modular type. Verify that modulus is in bounds
588
589    procedure New_Concatenation_Op (Typ : Entity_Id);
590    --  Create an abbreviated declaration for an operator in order to
591    --  materialize concatenation on array types.
592
593    procedure Ordinary_Fixed_Point_Type_Declaration
594      (T   : Entity_Id;
595       Def : Node_Id);
596    --  Create a new ordinary fixed point type, and apply the constraint to
597    --  obtain subtype of it.
598
599    procedure Prepare_Private_Subtype_Completion
600      (Id          : Entity_Id;
601       Related_Nod : Node_Id);
602    --  Id is a subtype of some private type. Creates the full declaration
603    --  associated with Id whenever possible, i.e. when the full declaration
604    --  of the base type is already known. Records each subtype into
605    --  Private_Dependents of the base type.
606
607    procedure Process_Incomplete_Dependents
608      (N      : Node_Id;
609       Full_T : Entity_Id;
610       Inc_T  : Entity_Id);
611    --  Process all entities that depend on an incomplete type. There include
612    --  subtypes, subprogram types that mention the incomplete type in their
613    --  profiles, and subprogram with access parameters that designate the
614    --  incomplete type.
615
616    --  Inc_T is the defining identifier of an incomplete type declaration, its
617    --  Ekind is E_Incomplete_Type.
618    --
619    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
620    --
621    --    Full_T is N's defining identifier.
622    --
623    --  Subtypes of incomplete types with discriminants are completed when the
624    --  parent type is. This is simpler than private subtypes, because they can
625    --  only appear in the same scope, and there is no need to exchange views.
626    --  Similarly, access_to_subprogram types may have a parameter or a return
627    --  type that is an incomplete type, and that must be replaced with the
628    --  full type.
629    --
630    --  If the full type is tagged, subprogram with access parameters that
631    --  designated the incomplete may be primitive operations of the full type,
632    --  and have to be processed accordingly.
633
634    procedure Process_Real_Range_Specification (Def : Node_Id);
635    --  Given the type definition for a real type, this procedure processes and
636    --  checks the real range specification of this type definition if one is
637    --  present. If errors are found, error messages are posted, and the
638    --  Real_Range_Specification of Def is reset to Empty.
639
640    procedure Record_Type_Declaration
641      (T    : Entity_Id;
642       N    : Node_Id;
643       Prev : Entity_Id);
644    --  Process a record type declaration (for both untagged and tagged
645    --  records). Parameters T and N are exactly like in procedure
646    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
647    --  for this routine. If this is the completion of an incomplete type
648    --  declaration, Prev is the entity of the incomplete declaration, used for
649    --  cross-referencing. Otherwise Prev = T.
650
651    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
652    --  This routine is used to process the actual record type definition (both
653    --  for untagged and tagged records). Def is a record type definition node.
654    --  This procedure analyzes the components in this record type definition.
655    --  Prev_T is the entity for the enclosing record type. It is provided so
656    --  that its Has_Task flag can be set if any of the component have Has_Task
657    --  set. If the declaration is the completion of an incomplete type
658    --  declaration, Prev_T is the original incomplete type, whose full view is
659    --  the record type.
660
661    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
662    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
663    --  build a copy of the declaration tree of the parent, and we create
664    --  independently the list of components for the derived type. Semantic
665    --  information uses the component entities, but record representation
666    --  clauses are validated on the declaration tree. This procedure replaces
667    --  discriminants and components in the declaration with those that have
668    --  been created by Inherit_Components.
669
670    procedure Set_Fixed_Range
671      (E   : Entity_Id;
672       Loc : Source_Ptr;
673       Lo  : Ureal;
674       Hi  : Ureal);
675    --  Build a range node with the given bounds and set it as the Scalar_Range
676    --  of the given fixed-point type entity. Loc is the source location used
677    --  for the constructed range. See body for further details.
678
679    procedure Set_Scalar_Range_For_Subtype
680      (Def_Id : Entity_Id;
681       R      : Node_Id;
682       Subt   : Entity_Id);
683    --  This routine is used to set the scalar range field for a subtype given
684    --  Def_Id, the entity for the subtype, and R, the range expression for the
685    --  scalar range. Subt provides the parent subtype to be used to analyze,
686    --  resolve, and check the given range.
687
688    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
689    --  Create a new signed integer entity, and apply the constraint to obtain
690    --  the required first named subtype of this type.
691
692    procedure Set_Stored_Constraint_From_Discriminant_Constraint
693      (E : Entity_Id);
694    --  E is some record type. This routine computes E's Stored_Constraint
695    --  from its Discriminant_Constraint.
696
697    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
698    --  Check that an entity in a list of progenitors is an interface,
699    --  emit error otherwise.
700
701    -----------------------
702    -- Access_Definition --
703    -----------------------
704
705    function Access_Definition
706      (Related_Nod : Node_Id;
707       N           : Node_Id) return Entity_Id
708    is
709       Loc                 : constant Source_Ptr := Sloc (Related_Nod);
710       Anon_Type           : Entity_Id;
711       Anon_Scope          : Entity_Id;
712       Desig_Type          : Entity_Id;
713       Decl                : Entity_Id;
714       Enclosing_Prot_Type : Entity_Id := Empty;
715
716    begin
717       Check_SPARK_Restriction ("access type is not allowed", N);
718
719       if Is_Entry (Current_Scope)
720         and then Is_Task_Type (Etype (Scope (Current_Scope)))
721       then
722          Error_Msg_N ("task entries cannot have access parameters", N);
723          return Empty;
724       end if;
725
726       --  Ada 2005: for an object declaration the corresponding anonymous
727       --  type is declared in the current scope.
728
729       --  If the access definition is the return type of another access to
730       --  function, scope is the current one, because it is the one of the
731       --  current type declaration.
732
733       if Nkind_In (Related_Nod, N_Object_Declaration,
734                                 N_Access_Function_Definition)
735       then
736          Anon_Scope := Current_Scope;
737
738       --  For the anonymous function result case, retrieve the scope of the
739       --  function specification's associated entity rather than using the
740       --  current scope. The current scope will be the function itself if the
741       --  formal part is currently being analyzed, but will be the parent scope
742       --  in the case of a parameterless function, and we always want to use
743       --  the function's parent scope. Finally, if the function is a child
744       --  unit, we must traverse the tree to retrieve the proper entity.
745
746       elsif Nkind (Related_Nod) = N_Function_Specification
747         and then Nkind (Parent (N)) /= N_Parameter_Specification
748       then
749          --  If the current scope is a protected type, the anonymous access
750          --  is associated with one of the protected operations, and must
751          --  be available in the scope that encloses the protected declaration.
752          --  Otherwise the type is in the scope enclosing the subprogram.
753
754          --  If the function has formals, The return type of a subprogram
755          --  declaration is analyzed in the scope of the subprogram (see
756          --  Process_Formals) and thus the protected type, if present, is
757          --  the scope of the current function scope.
758
759          if Ekind (Current_Scope) = E_Protected_Type then
760             Enclosing_Prot_Type := Current_Scope;
761
762          elsif Ekind (Current_Scope) = E_Function
763            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
764          then
765             Enclosing_Prot_Type := Scope (Current_Scope);
766          end if;
767
768          if Present (Enclosing_Prot_Type) then
769             Anon_Scope := Scope (Enclosing_Prot_Type);
770
771          else
772             Anon_Scope := Scope (Defining_Entity (Related_Nod));
773          end if;
774
775       else
776          --  For access formals, access components, and access discriminants,
777          --  the scope is that of the enclosing declaration,
778
779          Anon_Scope := Scope (Current_Scope);
780       end if;
781
782       Anon_Type :=
783         Create_Itype
784           (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
785
786       if All_Present (N)
787         and then Ada_Version >= Ada_2005
788       then
789          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
790       end if;
791
792       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
793       --  the corresponding semantic routine
794
795       if Present (Access_To_Subprogram_Definition (N)) then
796
797          --  Compiler runtime units are compiled in Ada 2005 mode when building
798          --  the runtime library but must also be compilable in Ada 95 mode
799          --  (when bootstrapping the compiler).
800
801          Check_Compiler_Unit (N);
802
803          Access_Subprogram_Declaration
804            (T_Name => Anon_Type,
805             T_Def  => Access_To_Subprogram_Definition (N));
806
807          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
808             Set_Ekind
809               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
810          else
811             Set_Ekind
812               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
813          end if;
814
815          Set_Can_Use_Internal_Rep
816            (Anon_Type, not Always_Compatible_Rep_On_Target);
817
818          --  If the anonymous access is associated with a protected operation
819          --  create a reference to it after the enclosing protected definition
820          --  because the itype will be used in the subsequent bodies.
821
822          if Ekind (Current_Scope) = E_Protected_Type then
823             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
824          end if;
825
826          return Anon_Type;
827       end if;
828
829       Find_Type (Subtype_Mark (N));
830       Desig_Type := Entity (Subtype_Mark (N));
831
832       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
833       Set_Etype (Anon_Type, Anon_Type);
834
835       --  Make sure the anonymous access type has size and alignment fields
836       --  set, as required by gigi. This is necessary in the case of the
837       --  Task_Body_Procedure.
838
839       if not Has_Private_Component (Desig_Type) then
840          Layout_Type (Anon_Type);
841       end if;
842
843       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
844       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
845       --  the null value is allowed. In Ada 95 the null value is never allowed.
846
847       if Ada_Version >= Ada_2005 then
848          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
849       else
850          Set_Can_Never_Be_Null (Anon_Type, True);
851       end if;
852
853       --  The anonymous access type is as public as the discriminated type or
854       --  subprogram that defines it. It is imported (for back-end purposes)
855       --  if the designated type is.
856
857       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
858
859       --  Ada 2005 (AI-231): Propagate the access-constant attribute
860
861       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
862
863       --  The context is either a subprogram declaration, object declaration,
864       --  or an access discriminant, in a private or a full type declaration.
865       --  In the case of a subprogram, if the designated type is incomplete,
866       --  the operation will be a primitive operation of the full type, to be
867       --  updated subsequently. If the type is imported through a limited_with
868       --  clause, the subprogram is not a primitive operation of the type
869       --  (which is declared elsewhere in some other scope).
870
871       if Ekind (Desig_Type) = E_Incomplete_Type
872         and then not From_With_Type (Desig_Type)
873         and then Is_Overloadable (Current_Scope)
874       then
875          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
876          Set_Has_Delayed_Freeze (Current_Scope);
877       end if;
878
879       --  Ada 2005: if the designated type is an interface that may contain
880       --  tasks, create a Master entity for the declaration. This must be done
881       --  before expansion of the full declaration, because the declaration may
882       --  include an expression that is an allocator, whose expansion needs the
883       --  proper Master for the created tasks.
884
885       if Nkind (Related_Nod) = N_Object_Declaration
886          and then Expander_Active
887       then
888          if Is_Interface (Desig_Type)
889            and then Is_Limited_Record (Desig_Type)
890          then
891             Build_Class_Wide_Master (Anon_Type);
892
893          --  Similarly, if the type is an anonymous access that designates
894          --  tasks, create a master entity for it in the current context.
895
896          elsif Has_Task (Desig_Type)
897            and then Comes_From_Source (Related_Nod)
898            and then not Restriction_Active (No_Task_Hierarchy)
899          then
900             if not Has_Master_Entity (Current_Scope) then
901                Decl :=
902                  Make_Object_Declaration (Loc,
903                    Defining_Identifier =>
904                      Make_Defining_Identifier (Loc, Name_uMaster),
905                    Constant_Present => True,
906                    Object_Definition =>
907                      New_Reference_To (RTE (RE_Master_Id), Loc),
908                    Expression =>
909                      Make_Explicit_Dereference (Loc,
910                        New_Reference_To (RTE (RE_Current_Master), Loc)));
911
912                Insert_Before (Related_Nod, Decl);
913                Analyze (Decl);
914
915                Set_Master_Id (Anon_Type, Defining_Identifier (Decl));
916                Set_Has_Master_Entity (Current_Scope);
917             else
918                Build_Master_Renaming (Related_Nod, Anon_Type);
919             end if;
920          end if;
921       end if;
922
923       --  For a private component of a protected type, it is imperative that
924       --  the back-end elaborate the type immediately after the protected
925       --  declaration, because this type will be used in the declarations
926       --  created for the component within each protected body, so we must
927       --  create an itype reference for it now.
928
929       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
930          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
931
932       --  Similarly, if the access definition is the return result of a
933       --  function, create an itype reference for it because it will be used
934       --  within the function body. For a regular function that is not a
935       --  compilation unit, insert reference after the declaration. For a
936       --  protected operation, insert it after the enclosing protected type
937       --  declaration. In either case, do not create a reference for a type
938       --  obtained through a limited_with clause, because this would introduce
939       --  semantic dependencies.
940
941       --  Similarly, do not create a reference if the designated type is a
942       --  generic formal, because no use of it will reach the backend.
943
944       elsif Nkind (Related_Nod) = N_Function_Specification
945         and then not From_With_Type (Desig_Type)
946         and then not Is_Generic_Type (Desig_Type)
947       then
948          if Present (Enclosing_Prot_Type) then
949             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
950
951          elsif Is_List_Member (Parent (Related_Nod))
952            and then Nkind (Parent (N)) /= N_Parameter_Specification
953          then
954             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
955          end if;
956
957       --  Finally, create an itype reference for an object declaration of an
958       --  anonymous access type. This is strictly necessary only for deferred
959       --  constants, but in any case will avoid out-of-scope problems in the
960       --  back-end.
961
962       elsif Nkind (Related_Nod) = N_Object_Declaration then
963          Build_Itype_Reference (Anon_Type, Related_Nod);
964       end if;
965
966       return Anon_Type;
967    end Access_Definition;
968
969    -----------------------------------
970    -- Access_Subprogram_Declaration --
971    -----------------------------------
972
973    procedure Access_Subprogram_Declaration
974      (T_Name : Entity_Id;
975       T_Def  : Node_Id)
976    is
977
978       procedure Check_For_Premature_Usage (Def : Node_Id);
979       --  Check that type T_Name is not used, directly or recursively, as a
980       --  parameter or a return type in Def. Def is either a subtype, an
981       --  access_definition, or an access_to_subprogram_definition.
982
983       -------------------------------
984       -- Check_For_Premature_Usage --
985       -------------------------------
986
987       procedure Check_For_Premature_Usage (Def : Node_Id) is
988          Param : Node_Id;
989
990       begin
991          --  Check for a subtype mark
992
993          if Nkind (Def) in N_Has_Etype then
994             if Etype (Def) = T_Name then
995                Error_Msg_N
996                  ("type& cannot be used before end of its declaration", Def);
997             end if;
998
999          --  If this is not a subtype, then this is an access_definition
1000
1001          elsif Nkind (Def) = N_Access_Definition then
1002             if Present (Access_To_Subprogram_Definition (Def)) then
1003                Check_For_Premature_Usage
1004                  (Access_To_Subprogram_Definition (Def));
1005             else
1006                Check_For_Premature_Usage (Subtype_Mark (Def));
1007             end if;
1008
1009          --  The only cases left are N_Access_Function_Definition and
1010          --  N_Access_Procedure_Definition.
1011
1012          else
1013             if Present (Parameter_Specifications (Def)) then
1014                Param := First (Parameter_Specifications (Def));
1015                while Present (Param) loop
1016                   Check_For_Premature_Usage (Parameter_Type (Param));
1017                   Param := Next (Param);
1018                end loop;
1019             end if;
1020
1021             if Nkind (Def) = N_Access_Function_Definition then
1022                Check_For_Premature_Usage (Result_Definition (Def));
1023             end if;
1024          end if;
1025       end Check_For_Premature_Usage;
1026
1027       --  Local variables
1028
1029       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1030       Formal     : Entity_Id;
1031       D_Ityp     : Node_Id;
1032       Desig_Type : constant Entity_Id :=
1033                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1034
1035    --  Start of processing for Access_Subprogram_Declaration
1036
1037    begin
1038       Check_SPARK_Restriction ("access type is not allowed", T_Def);
1039
1040       --  Associate the Itype node with the inner full-type declaration or
1041       --  subprogram spec or entry body. This is required to handle nested
1042       --  anonymous declarations. For example:
1043
1044       --      procedure P
1045       --       (X : access procedure
1046       --                     (Y : access procedure
1047       --                                   (Z : access T)))
1048
1049       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1050       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1051                                    N_Private_Type_Declaration,
1052                                    N_Private_Extension_Declaration,
1053                                    N_Procedure_Specification,
1054                                    N_Function_Specification,
1055                                    N_Entry_Body)
1056
1057                    or else
1058                  Nkind_In (D_Ityp, N_Object_Declaration,
1059                                    N_Object_Renaming_Declaration,
1060                                    N_Formal_Object_Declaration,
1061                                    N_Formal_Type_Declaration,
1062                                    N_Task_Type_Declaration,
1063                                    N_Protected_Type_Declaration))
1064       loop
1065          D_Ityp := Parent (D_Ityp);
1066          pragma Assert (D_Ityp /= Empty);
1067       end loop;
1068
1069       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1070
1071       if Nkind_In (D_Ityp, N_Procedure_Specification,
1072                            N_Function_Specification)
1073       then
1074          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1075
1076       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1077                               N_Object_Declaration,
1078                               N_Object_Renaming_Declaration,
1079                               N_Formal_Type_Declaration)
1080       then
1081          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1082       end if;
1083
1084       if Nkind (T_Def) = N_Access_Function_Definition then
1085          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1086             declare
1087                Acc : constant Node_Id := Result_Definition (T_Def);
1088
1089             begin
1090                if Present (Access_To_Subprogram_Definition (Acc))
1091                  and then
1092                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1093                then
1094                   Set_Etype
1095                     (Desig_Type,
1096                        Replace_Anonymous_Access_To_Protected_Subprogram
1097                          (T_Def));
1098
1099                else
1100                   Set_Etype
1101                     (Desig_Type,
1102                        Access_Definition (T_Def, Result_Definition (T_Def)));
1103                end if;
1104             end;
1105
1106          else
1107             Analyze (Result_Definition (T_Def));
1108
1109             declare
1110                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1111
1112             begin
1113                --  If a null exclusion is imposed on the result type, then
1114                --  create a null-excluding itype (an access subtype) and use
1115                --  it as the function's Etype.
1116
1117                if Is_Access_Type (Typ)
1118                  and then Null_Exclusion_In_Return_Present (T_Def)
1119                then
1120                   Set_Etype  (Desig_Type,
1121                     Create_Null_Excluding_Itype
1122                       (T           => Typ,
1123                        Related_Nod => T_Def,
1124                        Scope_Id    => Current_Scope));
1125
1126                else
1127                   if From_With_Type (Typ) then
1128
1129                      --  AI05-151: Incomplete types are allowed in all basic
1130                      --  declarations, including access to subprograms.
1131
1132                      if Ada_Version >= Ada_2012 then
1133                         null;
1134
1135                      else
1136                         Error_Msg_NE
1137                          ("illegal use of incomplete type&",
1138                             Result_Definition (T_Def), Typ);
1139                      end if;
1140
1141                   elsif Ekind (Current_Scope) = E_Package
1142                     and then In_Private_Part (Current_Scope)
1143                   then
1144                      if Ekind (Typ) = E_Incomplete_Type then
1145                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1146
1147                      elsif Is_Class_Wide_Type (Typ)
1148                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1149                      then
1150                         Append_Elmt
1151                           (Desig_Type, Private_Dependents (Etype (Typ)));
1152                      end if;
1153                   end if;
1154
1155                   Set_Etype (Desig_Type, Typ);
1156                end if;
1157             end;
1158          end if;
1159
1160          if not (Is_Type (Etype (Desig_Type))) then
1161             Error_Msg_N
1162               ("expect type in function specification",
1163                Result_Definition (T_Def));
1164          end if;
1165
1166       else
1167          Set_Etype (Desig_Type, Standard_Void_Type);
1168       end if;
1169
1170       if Present (Formals) then
1171          Push_Scope (Desig_Type);
1172
1173          --  A bit of a kludge here. These kludges will be removed when Itypes
1174          --  have proper parent pointers to their declarations???
1175
1176          --  Kludge 1) Link defining_identifier of formals. Required by
1177          --  First_Formal to provide its functionality.
1178
1179          declare
1180             F : Node_Id;
1181
1182          begin
1183             F := First (Formals);
1184
1185             --  In ASIS mode, the access_to_subprogram may be analyzed twice,
1186             --  when it is part of an unconstrained type and subtype expansion
1187             --  is disabled. To avoid back-end problems with shared profiles,
1188             --  use previous subprogram type as the designated type.
1189
1190             if ASIS_Mode
1191               and then Present (Scope (Defining_Identifier (F)))
1192             then
1193                Set_Etype                    (T_Name, T_Name);
1194                Init_Size_Align              (T_Name);
1195                Set_Directly_Designated_Type (T_Name,
1196                  Scope (Defining_Identifier (F)));
1197                return;
1198             end if;
1199
1200             while Present (F) loop
1201                if No (Parent (Defining_Identifier (F))) then
1202                   Set_Parent (Defining_Identifier (F), F);
1203                end if;
1204
1205                Next (F);
1206             end loop;
1207          end;
1208
1209          Process_Formals (Formals, Parent (T_Def));
1210
1211          --  Kludge 2) End_Scope requires that the parent pointer be set to
1212          --  something reasonable, but Itypes don't have parent pointers. So
1213          --  we set it and then unset it ???
1214
1215          Set_Parent (Desig_Type, T_Name);
1216          End_Scope;
1217          Set_Parent (Desig_Type, Empty);
1218       end if;
1219
1220       --  Check for premature usage of the type being defined
1221
1222       Check_For_Premature_Usage (T_Def);
1223
1224       --  The return type and/or any parameter type may be incomplete. Mark
1225       --  the subprogram_type as depending on the incomplete type, so that
1226       --  it can be updated when the full type declaration is seen. This
1227       --  only applies to incomplete types declared in some enclosing scope,
1228       --  not to limited views from other packages.
1229
1230       if Present (Formals) then
1231          Formal := First_Formal (Desig_Type);
1232          while Present (Formal) loop
1233             if Ekind (Formal) /= E_In_Parameter
1234               and then Nkind (T_Def) = N_Access_Function_Definition
1235             then
1236                Error_Msg_N ("functions can only have IN parameters", Formal);
1237             end if;
1238
1239             if Ekind (Etype (Formal)) = E_Incomplete_Type
1240               and then In_Open_Scopes (Scope (Etype (Formal)))
1241             then
1242                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1243                Set_Has_Delayed_Freeze (Desig_Type);
1244             end if;
1245
1246             Next_Formal (Formal);
1247          end loop;
1248       end if;
1249
1250       --  If the return type is incomplete, this is legal as long as the
1251       --  type is declared in the current scope and will be completed in
1252       --  it (rather than being part of limited view).
1253
1254       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1255         and then not Has_Delayed_Freeze (Desig_Type)
1256         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1257       then
1258          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1259          Set_Has_Delayed_Freeze (Desig_Type);
1260       end if;
1261
1262       Check_Delayed_Subprogram (Desig_Type);
1263
1264       if Protected_Present (T_Def) then
1265          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1266          Set_Convention (Desig_Type, Convention_Protected);
1267       else
1268          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1269       end if;
1270
1271       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1272
1273       Set_Etype                    (T_Name, T_Name);
1274       Init_Size_Align              (T_Name);
1275       Set_Directly_Designated_Type (T_Name, Desig_Type);
1276
1277       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1278
1279       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1280
1281       Check_Restriction (No_Access_Subprograms, T_Def);
1282    end Access_Subprogram_Declaration;
1283
1284    ----------------------------
1285    -- Access_Type_Declaration --
1286    ----------------------------
1287
1288    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1289       P : constant Node_Id := Parent (Def);
1290       S : constant Node_Id := Subtype_Indication (Def);
1291
1292       Full_Desig : Entity_Id;
1293
1294    begin
1295       Check_SPARK_Restriction ("access type is not allowed", Def);
1296
1297       --  Check for permissible use of incomplete type
1298
1299       if Nkind (S) /= N_Subtype_Indication then
1300          Analyze (S);
1301
1302          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1303             Set_Directly_Designated_Type (T, Entity (S));
1304          else
1305             Set_Directly_Designated_Type (T,
1306               Process_Subtype (S, P, T, 'P'));
1307          end if;
1308
1309       else
1310          Set_Directly_Designated_Type (T,
1311            Process_Subtype (S, P, T, 'P'));
1312       end if;
1313
1314       if All_Present (Def) or Constant_Present (Def) then
1315          Set_Ekind (T, E_General_Access_Type);
1316       else
1317          Set_Ekind (T, E_Access_Type);
1318       end if;
1319
1320       Full_Desig := Designated_Type (T);
1321
1322       if Base_Type (Full_Desig) = T then
1323          Error_Msg_N ("access type cannot designate itself", S);
1324
1325       --  In Ada 2005, the type may have a limited view through some unit
1326       --  in its own context, allowing the following circularity that cannot
1327       --  be detected earlier
1328
1329       elsif Is_Class_Wide_Type (Full_Desig)
1330         and then Etype (Full_Desig) = T
1331       then
1332          Error_Msg_N
1333            ("access type cannot designate its own classwide type", S);
1334
1335          --  Clean up indication of tagged status to prevent cascaded errors
1336
1337          Set_Is_Tagged_Type (T, False);
1338       end if;
1339
1340       Set_Etype (T, T);
1341
1342       --  If the type has appeared already in a with_type clause, it is
1343       --  frozen and the pointer size is already set. Else, initialize.
1344
1345       if not From_With_Type (T) then
1346          Init_Size_Align (T);
1347       end if;
1348
1349       --  Note that Has_Task is always false, since the access type itself
1350       --  is not a task type. See Einfo for more description on this point.
1351       --  Exactly the same consideration applies to Has_Controlled_Component.
1352
1353       Set_Has_Task (T, False);
1354       Set_Has_Controlled_Component (T, False);
1355
1356       --  Initialize Associated_Collection explicitly to Empty, to avoid
1357       --  problems where an incomplete view of this entity has been previously
1358       --  established by a limited with and an overlaid version of this field
1359       --  (Stored_Constraint) was initialized for the incomplete view.
1360
1361       --  This reset is performed in most cases except where the access type
1362       --  has been created for the purposes of allocating or deallocating a
1363       --  build-in-place object. Such access types have explicitly set pools
1364       --  and collections.
1365
1366       if No (Associated_Storage_Pool (T)) then
1367          Set_Associated_Collection (T, Empty);
1368       end if;
1369
1370       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1371       --  attributes
1372
1373       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1374       Set_Is_Access_Constant (T, Constant_Present (Def));
1375    end Access_Type_Declaration;
1376
1377    ----------------------------------
1378    -- Add_Interface_Tag_Components --
1379    ----------------------------------
1380
1381    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1382       Loc      : constant Source_Ptr := Sloc (N);
1383       L        : List_Id;
1384       Last_Tag : Node_Id;
1385
1386       procedure Add_Tag (Iface : Entity_Id);
1387       --  Add tag for one of the progenitor interfaces
1388
1389       -------------
1390       -- Add_Tag --
1391       -------------
1392
1393       procedure Add_Tag (Iface : Entity_Id) is
1394          Decl   : Node_Id;
1395          Def    : Node_Id;
1396          Tag    : Entity_Id;
1397          Offset : Entity_Id;
1398
1399       begin
1400          pragma Assert (Is_Tagged_Type (Iface)
1401            and then Is_Interface (Iface));
1402
1403          --  This is a reasonable place to propagate predicates
1404
1405          if Has_Predicates (Iface) then
1406             Set_Has_Predicates (Typ);
1407          end if;
1408
1409          Def :=
1410            Make_Component_Definition (Loc,
1411              Aliased_Present    => True,
1412              Subtype_Indication =>
1413                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1414
1415          Tag := Make_Temporary (Loc, 'V');
1416
1417          Decl :=
1418            Make_Component_Declaration (Loc,
1419              Defining_Identifier  => Tag,
1420              Component_Definition => Def);
1421
1422          Analyze_Component_Declaration (Decl);
1423
1424          Set_Analyzed (Decl);
1425          Set_Ekind               (Tag, E_Component);
1426          Set_Is_Tag              (Tag);
1427          Set_Is_Aliased          (Tag);
1428          Set_Related_Type        (Tag, Iface);
1429          Init_Component_Location (Tag);
1430
1431          pragma Assert (Is_Frozen (Iface));
1432
1433          Set_DT_Entry_Count    (Tag,
1434            DT_Entry_Count (First_Entity (Iface)));
1435
1436          if No (Last_Tag) then
1437             Prepend (Decl, L);
1438          else
1439             Insert_After (Last_Tag, Decl);
1440          end if;
1441
1442          Last_Tag := Decl;
1443
1444          --  If the ancestor has discriminants we need to give special support
1445          --  to store the offset_to_top value of the secondary dispatch tables.
1446          --  For this purpose we add a supplementary component just after the
1447          --  field that contains the tag associated with each secondary DT.
1448
1449          if Typ /= Etype (Typ)
1450            and then Has_Discriminants (Etype (Typ))
1451          then
1452             Def :=
1453               Make_Component_Definition (Loc,
1454                 Subtype_Indication =>
1455                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1456
1457             Offset := Make_Temporary (Loc, 'V');
1458
1459             Decl :=
1460               Make_Component_Declaration (Loc,
1461                 Defining_Identifier  => Offset,
1462                 Component_Definition => Def);
1463
1464             Analyze_Component_Declaration (Decl);
1465
1466             Set_Analyzed (Decl);
1467             Set_Ekind               (Offset, E_Component);
1468             Set_Is_Aliased          (Offset);
1469             Set_Related_Type        (Offset, Iface);
1470             Init_Component_Location (Offset);
1471             Insert_After (Last_Tag, Decl);
1472             Last_Tag := Decl;
1473          end if;
1474       end Add_Tag;
1475
1476       --  Local variables
1477
1478       Elmt : Elmt_Id;
1479       Ext  : Node_Id;
1480       Comp : Node_Id;
1481
1482    --  Start of processing for Add_Interface_Tag_Components
1483
1484    begin
1485       if not RTE_Available (RE_Interface_Tag) then
1486          Error_Msg
1487            ("(Ada 2005) interface types not supported by this run-time!",
1488             Sloc (N));
1489          return;
1490       end if;
1491
1492       if Ekind (Typ) /= E_Record_Type
1493         or else (Is_Concurrent_Record_Type (Typ)
1494                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1495         or else (not Is_Concurrent_Record_Type (Typ)
1496                   and then No (Interfaces (Typ))
1497                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1498       then
1499          return;
1500       end if;
1501
1502       --  Find the current last tag
1503
1504       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1505          Ext := Record_Extension_Part (Type_Definition (N));
1506       else
1507          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1508          Ext := Type_Definition (N);
1509       end if;
1510
1511       Last_Tag := Empty;
1512
1513       if not (Present (Component_List (Ext))) then
1514          Set_Null_Present (Ext, False);
1515          L := New_List;
1516          Set_Component_List (Ext,
1517            Make_Component_List (Loc,
1518              Component_Items => L,
1519              Null_Present => False));
1520       else
1521          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1522             L := Component_Items
1523                    (Component_List
1524                      (Record_Extension_Part
1525                        (Type_Definition (N))));
1526          else
1527             L := Component_Items
1528                    (Component_List
1529                      (Type_Definition (N)));
1530          end if;
1531
1532          --  Find the last tag component
1533
1534          Comp := First (L);
1535          while Present (Comp) loop
1536             if Nkind (Comp) = N_Component_Declaration
1537               and then Is_Tag (Defining_Identifier (Comp))
1538             then
1539                Last_Tag := Comp;
1540             end if;
1541
1542             Next (Comp);
1543          end loop;
1544       end if;
1545
1546       --  At this point L references the list of components and Last_Tag
1547       --  references the current last tag (if any). Now we add the tag
1548       --  corresponding with all the interfaces that are not implemented
1549       --  by the parent.
1550
1551       if Present (Interfaces (Typ)) then
1552          Elmt := First_Elmt (Interfaces (Typ));
1553          while Present (Elmt) loop
1554             Add_Tag (Node (Elmt));
1555             Next_Elmt (Elmt);
1556          end loop;
1557       end if;
1558    end Add_Interface_Tag_Components;
1559
1560    -------------------------------------
1561    -- Add_Internal_Interface_Entities --
1562    -------------------------------------
1563
1564    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1565       Elmt          : Elmt_Id;
1566       Iface         : Entity_Id;
1567       Iface_Elmt    : Elmt_Id;
1568       Iface_Prim    : Entity_Id;
1569       Ifaces_List   : Elist_Id;
1570       New_Subp      : Entity_Id := Empty;
1571       Prim          : Entity_Id;
1572       Restore_Scope : Boolean := False;
1573
1574    begin
1575       pragma Assert (Ada_Version >= Ada_2005
1576         and then Is_Record_Type (Tagged_Type)
1577         and then Is_Tagged_Type (Tagged_Type)
1578         and then Has_Interfaces (Tagged_Type)
1579         and then not Is_Interface (Tagged_Type));
1580
1581       --  Ensure that the internal entities are added to the scope of the type
1582
1583       if Scope (Tagged_Type) /= Current_Scope then
1584          Push_Scope (Scope (Tagged_Type));
1585          Restore_Scope := True;
1586       end if;
1587
1588       Collect_Interfaces (Tagged_Type, Ifaces_List);
1589
1590       Iface_Elmt := First_Elmt (Ifaces_List);
1591       while Present (Iface_Elmt) loop
1592          Iface := Node (Iface_Elmt);
1593
1594          --  Originally we excluded here from this processing interfaces that
1595          --  are parents of Tagged_Type because their primitives are located
1596          --  in the primary dispatch table (and hence no auxiliary internal
1597          --  entities are required to handle secondary dispatch tables in such
1598          --  case). However, these auxiliary entities are also required to
1599          --  handle derivations of interfaces in formals of generics (see
1600          --  Derive_Subprograms).
1601
1602          Elmt := First_Elmt (Primitive_Operations (Iface));
1603          while Present (Elmt) loop
1604             Iface_Prim := Node (Elmt);
1605
1606             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1607                Prim :=
1608                  Find_Primitive_Covering_Interface
1609                    (Tagged_Type => Tagged_Type,
1610                     Iface_Prim  => Iface_Prim);
1611
1612                pragma Assert (Present (Prim));
1613
1614                --  Ada 2012 (AI05-0197): If the name of the covering primitive
1615                --  differs from the name of the interface primitive then it is
1616                --  a private primitive inherited from a parent type. In such
1617                --  case, given that Tagged_Type covers the interface, the
1618                --  inherited private primitive becomes visible. For such
1619                --  purpose we add a new entity that renames the inherited
1620                --  private primitive.
1621
1622                if Chars (Prim) /= Chars (Iface_Prim) then
1623                   pragma Assert (Has_Suffix (Prim, 'P'));
1624                   Derive_Subprogram
1625                     (New_Subp     => New_Subp,
1626                      Parent_Subp  => Iface_Prim,
1627                      Derived_Type => Tagged_Type,
1628                      Parent_Type  => Iface);
1629                   Set_Alias (New_Subp, Prim);
1630                   Set_Is_Abstract_Subprogram
1631                     (New_Subp, Is_Abstract_Subprogram (Prim));
1632                end if;
1633
1634                Derive_Subprogram
1635                  (New_Subp     => New_Subp,
1636                   Parent_Subp  => Iface_Prim,
1637                   Derived_Type => Tagged_Type,
1638                   Parent_Type  => Iface);
1639
1640                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1641                --  associated with interface types. These entities are
1642                --  only registered in the list of primitives of its
1643                --  corresponding tagged type because they are only used
1644                --  to fill the contents of the secondary dispatch tables.
1645                --  Therefore they are removed from the homonym chains.
1646
1647                Set_Is_Hidden (New_Subp);
1648                Set_Is_Internal (New_Subp);
1649                Set_Alias (New_Subp, Prim);
1650                Set_Is_Abstract_Subprogram
1651                  (New_Subp, Is_Abstract_Subprogram (Prim));
1652                Set_Interface_Alias (New_Subp, Iface_Prim);
1653
1654                --  Internal entities associated with interface types are
1655                --  only registered in the list of primitives of the tagged
1656                --  type. They are only used to fill the contents of the
1657                --  secondary dispatch tables. Therefore they are not needed
1658                --  in the homonym chains.
1659
1660                Remove_Homonym (New_Subp);
1661
1662                --  Hidden entities associated with interfaces must have set
1663                --  the Has_Delay_Freeze attribute to ensure that, in case of
1664                --  locally defined tagged types (or compiling with static
1665                --  dispatch tables generation disabled) the corresponding
1666                --  entry of the secondary dispatch table is filled when
1667                --  such an entity is frozen.
1668
1669                Set_Has_Delayed_Freeze (New_Subp);
1670             end if;
1671
1672             Next_Elmt (Elmt);
1673          end loop;
1674
1675          Next_Elmt (Iface_Elmt);
1676       end loop;
1677
1678       if Restore_Scope then
1679          Pop_Scope;
1680       end if;
1681    end Add_Internal_Interface_Entities;
1682
1683    -----------------------------------
1684    -- Analyze_Component_Declaration --
1685    -----------------------------------
1686
1687    procedure Analyze_Component_Declaration (N : Node_Id) is
1688       Id  : constant Entity_Id := Defining_Identifier (N);
1689       E   : constant Node_Id   := Expression (N);
1690       Typ : constant Node_Id   :=
1691               Subtype_Indication (Component_Definition (N));
1692       T   : Entity_Id;
1693       P   : Entity_Id;
1694
1695       function Contains_POC (Constr : Node_Id) return Boolean;
1696       --  Determines whether a constraint uses the discriminant of a record
1697       --  type thus becoming a per-object constraint (POC).
1698
1699       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1700       --  Typ is the type of the current component, check whether this type is
1701       --  a limited type. Used to validate declaration against that of
1702       --  enclosing record.
1703
1704       ------------------
1705       -- Contains_POC --
1706       ------------------
1707
1708       function Contains_POC (Constr : Node_Id) return Boolean is
1709       begin
1710          --  Prevent cascaded errors
1711
1712          if Error_Posted (Constr) then
1713             return False;
1714          end if;
1715
1716          case Nkind (Constr) is
1717             when N_Attribute_Reference =>
1718                return
1719                  Attribute_Name (Constr) = Name_Access
1720                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1721
1722             when N_Discriminant_Association =>
1723                return Denotes_Discriminant (Expression (Constr));
1724
1725             when N_Identifier =>
1726                return Denotes_Discriminant (Constr);
1727
1728             when N_Index_Or_Discriminant_Constraint =>
1729                declare
1730                   IDC : Node_Id;
1731
1732                begin
1733                   IDC := First (Constraints (Constr));
1734                   while Present (IDC) loop
1735
1736                      --  One per-object constraint is sufficient
1737
1738                      if Contains_POC (IDC) then
1739                         return True;
1740                      end if;
1741
1742                      Next (IDC);
1743                   end loop;
1744
1745                   return False;
1746                end;
1747
1748             when N_Range =>
1749                return Denotes_Discriminant (Low_Bound (Constr))
1750                         or else
1751                       Denotes_Discriminant (High_Bound (Constr));
1752
1753             when N_Range_Constraint =>
1754                return Denotes_Discriminant (Range_Expression (Constr));
1755
1756             when others =>
1757                return False;
1758
1759          end case;
1760       end Contains_POC;
1761
1762       ----------------------
1763       -- Is_Known_Limited --
1764       ----------------------
1765
1766       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1767          P : constant Entity_Id := Etype (Typ);
1768          R : constant Entity_Id := Root_Type (Typ);
1769
1770       begin
1771          if Is_Limited_Record (Typ) then
1772             return True;
1773
1774          --  If the root type is limited (and not a limited interface)
1775          --  so is the current type
1776
1777          elsif Is_Limited_Record (R)
1778            and then
1779              (not Is_Interface (R)
1780                or else not Is_Limited_Interface (R))
1781          then
1782             return True;
1783
1784          --  Else the type may have a limited interface progenitor, but a
1785          --  limited record parent.
1786
1787          elsif R /= P
1788            and then Is_Limited_Record (P)
1789          then
1790             return True;
1791
1792          else
1793             return False;
1794          end if;
1795       end Is_Known_Limited;
1796
1797    --  Start of processing for Analyze_Component_Declaration
1798
1799    begin
1800       Generate_Definition (Id);
1801       Enter_Name (Id);
1802
1803       if Present (Typ) then
1804          T := Find_Type_Of_Object
1805                 (Subtype_Indication (Component_Definition (N)), N);
1806
1807          if not Nkind_In (Typ, N_Identifier, N_Expanded_Name) then
1808             Check_SPARK_Restriction ("subtype mark required", Typ);
1809          end if;
1810
1811       --  Ada 2005 (AI-230): Access Definition case
1812
1813       else
1814          pragma Assert (Present
1815                           (Access_Definition (Component_Definition (N))));
1816
1817          T := Access_Definition
1818                 (Related_Nod => N,
1819                  N => Access_Definition (Component_Definition (N)));
1820          Set_Is_Local_Anonymous_Access (T);
1821
1822          --  Ada 2005 (AI-254)
1823
1824          if Present (Access_To_Subprogram_Definition
1825                       (Access_Definition (Component_Definition (N))))
1826            and then Protected_Present (Access_To_Subprogram_Definition
1827                                         (Access_Definition
1828                                           (Component_Definition (N))))
1829          then
1830             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1831          end if;
1832       end if;
1833
1834       --  If the subtype is a constrained subtype of the enclosing record,
1835       --  (which must have a partial view) the back-end does not properly
1836       --  handle the recursion. Rewrite the component declaration with an
1837       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1838       --  the tree directly because side effects have already been removed from
1839       --  discriminant constraints.
1840
1841       if Ekind (T) = E_Access_Subtype
1842         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1843         and then Comes_From_Source (T)
1844         and then Nkind (Parent (T)) = N_Subtype_Declaration
1845         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1846       then
1847          Rewrite
1848            (Subtype_Indication (Component_Definition (N)),
1849              New_Copy_Tree (Subtype_Indication (Parent (T))));
1850          T := Find_Type_Of_Object
1851                  (Subtype_Indication (Component_Definition (N)), N);
1852       end if;
1853
1854       --  If the component declaration includes a default expression, then we
1855       --  check that the component is not of a limited type (RM 3.7(5)),
1856       --  and do the special preanalysis of the expression (see section on
1857       --  "Handling of Default and Per-Object Expressions" in the spec of
1858       --  package Sem).
1859
1860       if Present (E) then
1861          Check_SPARK_Restriction ("default expression is not allowed", E);
1862          Preanalyze_Spec_Expression (E, T);
1863          Check_Initialization (T, E);
1864
1865          if Ada_Version >= Ada_2005
1866            and then Ekind (T) = E_Anonymous_Access_Type
1867            and then Etype (E) /= Any_Type
1868          then
1869             --  Check RM 3.9.2(9): "if the expected type for an expression is
1870             --  an anonymous access-to-specific tagged type, then the object
1871             --  designated by the expression shall not be dynamically tagged
1872             --  unless it is a controlling operand in a call on a dispatching
1873             --  operation"
1874
1875             if Is_Tagged_Type (Directly_Designated_Type (T))
1876               and then
1877                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1878               and then
1879                 Ekind (Directly_Designated_Type (Etype (E))) =
1880                   E_Class_Wide_Type
1881             then
1882                Error_Msg_N
1883                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1884             end if;
1885
1886             --  (Ada 2005: AI-230): Accessibility check for anonymous
1887             --  components
1888
1889             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1890                Error_Msg_N
1891                  ("expression has deeper access level than component " &
1892                   "(RM 3.10.2 (12.2))", E);
1893             end if;
1894
1895             --  The initialization expression is a reference to an access
1896             --  discriminant. The type of the discriminant is always deeper
1897             --  than any access type.
1898
1899             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1900               and then Is_Entity_Name (E)
1901               and then Ekind (Entity (E)) = E_In_Parameter
1902               and then Present (Discriminal_Link (Entity (E)))
1903             then
1904                Error_Msg_N
1905                  ("discriminant has deeper accessibility level than target",
1906                   E);
1907             end if;
1908          end if;
1909       end if;
1910
1911       --  The parent type may be a private view with unknown discriminants,
1912       --  and thus unconstrained. Regular components must be constrained.
1913
1914       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1915          if Is_Class_Wide_Type (T) then
1916             Error_Msg_N
1917                ("class-wide subtype with unknown discriminants" &
1918                  " in component declaration",
1919                  Subtype_Indication (Component_Definition (N)));
1920          else
1921             Error_Msg_N
1922               ("unconstrained subtype in component declaration",
1923                Subtype_Indication (Component_Definition (N)));
1924          end if;
1925
1926       --  Components cannot be abstract, except for the special case of
1927       --  the _Parent field (case of extending an abstract tagged type)
1928
1929       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1930          Error_Msg_N ("type of a component cannot be abstract", N);
1931       end if;
1932
1933       Set_Etype (Id, T);
1934       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1935
1936       --  The component declaration may have a per-object constraint, set
1937       --  the appropriate flag in the defining identifier of the subtype.
1938
1939       if Present (Subtype_Indication (Component_Definition (N))) then
1940          declare
1941             Sindic : constant Node_Id :=
1942                        Subtype_Indication (Component_Definition (N));
1943          begin
1944             if Nkind (Sindic) = N_Subtype_Indication
1945               and then Present (Constraint (Sindic))
1946               and then Contains_POC (Constraint (Sindic))
1947             then
1948                Set_Has_Per_Object_Constraint (Id);
1949             end if;
1950          end;
1951       end if;
1952
1953       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1954       --  out some static checks.
1955
1956       if Ada_Version >= Ada_2005
1957         and then Can_Never_Be_Null (T)
1958       then
1959          Null_Exclusion_Static_Checks (N);
1960       end if;
1961
1962       --  If this component is private (or depends on a private type), flag the
1963       --  record type to indicate that some operations are not available.
1964
1965       P := Private_Component (T);
1966
1967       if Present (P) then
1968
1969          --  Check for circular definitions
1970
1971          if P = Any_Type then
1972             Set_Etype (Id, Any_Type);
1973
1974          --  There is a gap in the visibility of operations only if the
1975          --  component type is not defined in the scope of the record type.
1976
1977          elsif Scope (P) = Scope (Current_Scope) then
1978             null;
1979
1980          elsif Is_Limited_Type (P) then
1981             Set_Is_Limited_Composite (Current_Scope);
1982
1983          else
1984             Set_Is_Private_Composite (Current_Scope);
1985          end if;
1986       end if;
1987
1988       if P /= Any_Type
1989         and then Is_Limited_Type (T)
1990         and then Chars (Id) /= Name_uParent
1991         and then Is_Tagged_Type (Current_Scope)
1992       then
1993          if Is_Derived_Type (Current_Scope)
1994            and then not Is_Known_Limited (Current_Scope)
1995          then
1996             Error_Msg_N
1997               ("extension of nonlimited type cannot have limited components",
1998                N);
1999
2000             if Is_Interface (Root_Type (Current_Scope)) then
2001                Error_Msg_N
2002                  ("\limitedness is not inherited from limited interface", N);
2003                Error_Msg_N ("\add LIMITED to type indication", N);
2004             end if;
2005
2006             Explain_Limited_Type (T, N);
2007             Set_Etype (Id, Any_Type);
2008             Set_Is_Limited_Composite (Current_Scope, False);
2009
2010          elsif not Is_Derived_Type (Current_Scope)
2011            and then not Is_Limited_Record (Current_Scope)
2012            and then not Is_Concurrent_Type (Current_Scope)
2013          then
2014             Error_Msg_N
2015               ("nonlimited tagged type cannot have limited components", N);
2016             Explain_Limited_Type (T, N);
2017             Set_Etype (Id, Any_Type);
2018             Set_Is_Limited_Composite (Current_Scope, False);
2019          end if;
2020       end if;
2021
2022       Set_Original_Record_Component (Id, Id);
2023
2024       if Has_Aspects (N) then
2025          Analyze_Aspect_Specifications (N, Id);
2026       end if;
2027    end Analyze_Component_Declaration;
2028
2029    --------------------------
2030    -- Analyze_Declarations --
2031    --------------------------
2032
2033    procedure Analyze_Declarations (L : List_Id) is
2034       D           : Node_Id;
2035       Freeze_From : Entity_Id := Empty;
2036       Next_Node   : Node_Id;
2037
2038       procedure Adjust_D;
2039       --  Adjust D not to include implicit label declarations, since these
2040       --  have strange Sloc values that result in elaboration check problems.
2041       --  (They have the sloc of the label as found in the source, and that
2042       --  is ahead of the current declarative part).
2043
2044       --------------
2045       -- Adjust_D --
2046       --------------
2047
2048       procedure Adjust_D is
2049       begin
2050          while Present (Prev (D))
2051            and then Nkind (D) = N_Implicit_Label_Declaration
2052          loop
2053             Prev (D);
2054          end loop;
2055       end Adjust_D;
2056
2057    --  Start of processing for Analyze_Declarations
2058
2059    begin
2060       if Restriction_Check_Required (SPARK) then
2061          Check_Later_Vs_Basic_Declarations (L, During_Parsing => False);
2062       end if;
2063
2064       D := First (L);
2065       while Present (D) loop
2066
2067          --  Package spec cannot contain a package declaration in SPARK
2068
2069          if Nkind (D) = N_Package_Declaration
2070            and then Nkind (Parent (L)) = N_Package_Specification
2071          then
2072             Check_SPARK_Restriction
2073               ("package specification cannot contain a package declaration",
2074                D);
2075          end if;
2076
2077          --  Complete analysis of declaration
2078
2079          Analyze (D);
2080          Next_Node := Next (D);
2081
2082          if No (Freeze_From) then
2083             Freeze_From := First_Entity (Current_Scope);
2084          end if;
2085
2086          --  At the end of a declarative part, freeze remaining entities
2087          --  declared in it. The end of the visible declarations of package
2088          --  specification is not the end of a declarative part if private
2089          --  declarations are present. The end of a package declaration is a
2090          --  freezing point only if it a library package. A task definition or
2091          --  protected type definition is not a freeze point either. Finally,
2092          --  we do not freeze entities in generic scopes, because there is no
2093          --  code generated for them and freeze nodes will be generated for
2094          --  the instance.
2095
2096          --  The end of a package instantiation is not a freeze point, but
2097          --  for now we make it one, because the generic body is inserted
2098          --  (currently) immediately after. Generic instantiations will not
2099          --  be a freeze point once delayed freezing of bodies is implemented.
2100          --  (This is needed in any case for early instantiations ???).
2101
2102          if No (Next_Node) then
2103             if Nkind_In (Parent (L), N_Component_List,
2104                                      N_Task_Definition,
2105                                      N_Protected_Definition)
2106             then
2107                null;
2108
2109             elsif Nkind (Parent (L)) /= N_Package_Specification then
2110                if Nkind (Parent (L)) = N_Package_Body then
2111                   Freeze_From := First_Entity (Current_Scope);
2112                end if;
2113
2114                Adjust_D;
2115                Freeze_All (Freeze_From, D);
2116                Freeze_From := Last_Entity (Current_Scope);
2117
2118             elsif Scope (Current_Scope) /= Standard_Standard
2119               and then not Is_Child_Unit (Current_Scope)
2120               and then No (Generic_Parent (Parent (L)))
2121             then
2122                null;
2123
2124             elsif L /= Visible_Declarations (Parent (L))
2125                or else No (Private_Declarations (Parent (L)))
2126                or else Is_Empty_List (Private_Declarations (Parent (L)))
2127             then
2128                Adjust_D;
2129                Freeze_All (Freeze_From, D);
2130                Freeze_From := Last_Entity (Current_Scope);
2131             end if;
2132
2133          --  If next node is a body then freeze all types before the body.
2134          --  An exception occurs for some expander-generated bodies. If these
2135          --  are generated at places where in general language rules would not
2136          --  allow a freeze point, then we assume that the expander has
2137          --  explicitly checked that all required types are properly frozen,
2138          --  and we do not cause general freezing here. This special circuit
2139          --  is used when the encountered body is marked as having already
2140          --  been analyzed.
2141
2142          --  In all other cases (bodies that come from source, and expander
2143          --  generated bodies that have not been analyzed yet), freeze all
2144          --  types now. Note that in the latter case, the expander must take
2145          --  care to attach the bodies at a proper place in the tree so as to
2146          --  not cause unwanted freezing at that point.
2147
2148          elsif not Analyzed (Next_Node)
2149            and then (Nkind_In (Next_Node, N_Subprogram_Body,
2150                                           N_Entry_Body,
2151                                           N_Package_Body,
2152                                           N_Protected_Body,
2153                                           N_Task_Body)
2154                        or else
2155                      Nkind (Next_Node) in N_Body_Stub)
2156          then
2157             Adjust_D;
2158             Freeze_All (Freeze_From, D);
2159             Freeze_From := Last_Entity (Current_Scope);
2160          end if;
2161
2162          D := Next_Node;
2163       end loop;
2164
2165       --  One more thing to do, we need to scan the declarations to check
2166       --  for any precondition/postcondition pragmas (Pre/Post aspects have
2167       --  by this stage been converted into corresponding pragmas). It is
2168       --  at this point that we analyze the expressions in such pragmas,
2169       --  to implement the delayed visibility requirement.
2170
2171       declare
2172          Decl : Node_Id;
2173          Spec : Node_Id;
2174          Sent : Entity_Id;
2175          Prag : Node_Id;
2176
2177       begin
2178          Decl := First (L);
2179          while Present (Decl) loop
2180             if Nkind (Original_Node (Decl)) = N_Subprogram_Declaration then
2181                Spec := Specification (Original_Node (Decl));
2182                Sent := Defining_Unit_Name (Spec);
2183
2184                Prag := Spec_PPC_List (Contract (Sent));
2185                while Present (Prag) loop
2186                   Analyze_PPC_In_Decl_Part (Prag, Sent);
2187                   Prag := Next_Pragma (Prag);
2188                end loop;
2189
2190                Prag := Spec_TC_List (Contract (Sent));
2191                while Present (Prag) loop
2192                   Analyze_TC_In_Decl_Part (Prag, Sent);
2193                   Prag := Next_Pragma (Prag);
2194                end loop;
2195             end if;
2196
2197             Next (Decl);
2198          end loop;
2199       end;
2200    end Analyze_Declarations;
2201
2202    -----------------------------------
2203    -- Analyze_Full_Type_Declaration --
2204    -----------------------------------
2205
2206    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2207       Def    : constant Node_Id   := Type_Definition (N);
2208       Def_Id : constant Entity_Id := Defining_Identifier (N);
2209       T      : Entity_Id;
2210       Prev   : Entity_Id;
2211
2212       Is_Remote : constant Boolean :=
2213                     (Is_Remote_Types (Current_Scope)
2214                        or else Is_Remote_Call_Interface (Current_Scope))
2215                     and then not (In_Private_Part (Current_Scope)
2216                                     or else In_Package_Body (Current_Scope));
2217
2218       procedure Check_Ops_From_Incomplete_Type;
2219       --  If there is a tagged incomplete partial view of the type, traverse
2220       --  the primitives of the incomplete view and change the type of any
2221       --  controlling formals and result to indicate the full view. The
2222       --  primitives will be added to the full type's primitive operations
2223       --  list later in Sem_Disp.Check_Operation_From_Incomplete_Type (which
2224       --  is called from Process_Incomplete_Dependents).
2225
2226       ------------------------------------
2227       -- Check_Ops_From_Incomplete_Type --
2228       ------------------------------------
2229
2230       procedure Check_Ops_From_Incomplete_Type is
2231          Elmt   : Elmt_Id;
2232          Formal : Entity_Id;
2233          Op     : Entity_Id;
2234
2235       begin
2236          if Prev /= T
2237            and then Ekind (Prev) = E_Incomplete_Type
2238            and then Is_Tagged_Type (Prev)
2239            and then Is_Tagged_Type (T)
2240          then
2241             Elmt := First_Elmt (Primitive_Operations (Prev));
2242             while Present (Elmt) loop
2243                Op := Node (Elmt);
2244
2245                Formal := First_Formal (Op);
2246                while Present (Formal) loop
2247                   if Etype (Formal) = Prev then
2248                      Set_Etype (Formal, T);
2249                   end if;
2250
2251                   Next_Formal (Formal);
2252                end loop;
2253
2254                if Etype (Op) = Prev then
2255                   Set_Etype (Op, T);
2256                end if;
2257
2258                Next_Elmt (Elmt);
2259             end loop;
2260          end if;
2261       end Check_Ops_From_Incomplete_Type;
2262
2263    --  Start of processing for Analyze_Full_Type_Declaration
2264
2265    begin
2266       Prev := Find_Type_Name (N);
2267
2268       --  The full view, if present, now points to the current type
2269
2270       --  Ada 2005 (AI-50217): If the type was previously decorated when
2271       --  imported through a LIMITED WITH clause, it appears as incomplete
2272       --  but has no full view.
2273
2274       if Ekind (Prev) = E_Incomplete_Type
2275         and then Present (Full_View (Prev))
2276       then
2277          T := Full_View (Prev);
2278       else
2279          T := Prev;
2280       end if;
2281
2282       Set_Is_Pure (T, Is_Pure (Current_Scope));
2283
2284       --  We set the flag Is_First_Subtype here. It is needed to set the
2285       --  corresponding flag for the Implicit class-wide-type created
2286       --  during tagged types processing.
2287
2288       Set_Is_First_Subtype (T, True);
2289
2290       --  Only composite types other than array types are allowed to have
2291       --  discriminants.
2292
2293       case Nkind (Def) is
2294
2295          --  For derived types, the rule will be checked once we've figured
2296          --  out the parent type.
2297
2298          when N_Derived_Type_Definition =>
2299             null;
2300
2301          --  For record types, discriminants are allowed, unless we are in
2302          --  SPARK.
2303
2304          when N_Record_Definition =>
2305             if Present (Discriminant_Specifications (N)) then
2306                Check_SPARK_Restriction
2307                  ("discriminant type is not allowed",
2308                   Defining_Identifier
2309                     (First (Discriminant_Specifications (N))));
2310             end if;
2311
2312          when others =>
2313             if Present (Discriminant_Specifications (N)) then
2314                Error_Msg_N
2315                  ("elementary or array type cannot have discriminants",
2316                   Defining_Identifier
2317                     (First (Discriminant_Specifications (N))));
2318             end if;
2319       end case;
2320
2321       --  Elaborate the type definition according to kind, and generate
2322       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2323       --  already done (this happens during the reanalysis that follows a call
2324       --  to the high level optimizer).
2325
2326       if not Analyzed (T) then
2327          Set_Analyzed (T);
2328
2329          case Nkind (Def) is
2330
2331             when N_Access_To_Subprogram_Definition =>
2332                Access_Subprogram_Declaration (T, Def);
2333
2334                --  If this is a remote access to subprogram, we must create the
2335                --  equivalent fat pointer type, and related subprograms.
2336
2337                if Is_Remote then
2338                   Process_Remote_AST_Declaration (N);
2339                end if;
2340
2341                --  Validate categorization rule against access type declaration
2342                --  usually a violation in Pure unit, Shared_Passive unit.
2343
2344                Validate_Access_Type_Declaration (T, N);
2345
2346             when N_Access_To_Object_Definition =>
2347                Access_Type_Declaration (T, Def);
2348
2349                --  Validate categorization rule against access type declaration
2350                --  usually a violation in Pure unit, Shared_Passive unit.
2351
2352                Validate_Access_Type_Declaration (T, N);
2353
2354                --  If we are in a Remote_Call_Interface package and define a
2355                --  RACW, then calling stubs and specific stream attributes
2356                --  must be added.
2357
2358                if Is_Remote
2359                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2360                then
2361                   Add_RACW_Features (Def_Id);
2362                end if;
2363
2364                --  Set no strict aliasing flag if config pragma seen
2365
2366                if Opt.No_Strict_Aliasing then
2367                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
2368                end if;
2369
2370             when N_Array_Type_Definition =>
2371                Array_Type_Declaration (T, Def);
2372
2373             when N_Derived_Type_Definition =>
2374                Derived_Type_Declaration (T, N, T /= Def_Id);
2375
2376             when N_Enumeration_Type_Definition =>
2377                Enumeration_Type_Declaration (T, Def);
2378
2379             when N_Floating_Point_Definition =>
2380                Floating_Point_Type_Declaration (T, Def);
2381
2382             when N_Decimal_Fixed_Point_Definition =>
2383                Decimal_Fixed_Point_Type_Declaration (T, Def);
2384
2385             when N_Ordinary_Fixed_Point_Definition =>
2386                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2387
2388             when N_Signed_Integer_Type_Definition =>
2389                Signed_Integer_Type_Declaration (T, Def);
2390
2391             when N_Modular_Type_Definition =>
2392                Modular_Type_Declaration (T, Def);
2393
2394             when N_Record_Definition =>
2395                Record_Type_Declaration (T, N, Prev);
2396
2397             --  If declaration has a parse error, nothing to elaborate.
2398
2399             when N_Error =>
2400                null;
2401
2402             when others =>
2403                raise Program_Error;
2404
2405          end case;
2406       end if;
2407
2408       if Etype (T) = Any_Type then
2409          return;
2410       end if;
2411
2412       --  Controlled type is not allowed in SPARK
2413
2414       if Is_Visibly_Controlled (T) then
2415          Check_SPARK_Restriction ("controlled type is not allowed", N);
2416       end if;
2417
2418       --  Some common processing for all types
2419
2420       Set_Depends_On_Private (T, Has_Private_Component (T));
2421       Check_Ops_From_Incomplete_Type;
2422
2423       --  Both the declared entity, and its anonymous base type if one
2424       --  was created, need freeze nodes allocated.
2425
2426       declare
2427          B : constant Entity_Id := Base_Type (T);
2428
2429       begin
2430          --  In the case where the base type differs from the first subtype, we
2431          --  pre-allocate a freeze node, and set the proper link to the first
2432          --  subtype. Freeze_Entity will use this preallocated freeze node when
2433          --  it freezes the entity.
2434
2435          --  This does not apply if the base type is a generic type, whose
2436          --  declaration is independent of the current derived definition.
2437
2438          if B /= T and then not Is_Generic_Type (B) then
2439             Ensure_Freeze_Node (B);
2440             Set_First_Subtype_Link (Freeze_Node (B), T);
2441          end if;
2442
2443          --  A type that is imported through a limited_with clause cannot
2444          --  generate any code, and thus need not be frozen. However, an access
2445          --  type with an imported designated type needs a finalization list,
2446          --  which may be referenced in some other package that has non-limited
2447          --  visibility on the designated type. Thus we must create the
2448          --  finalization list at the point the access type is frozen, to
2449          --  prevent unsatisfied references at link time.
2450
2451          if not From_With_Type (T) or else Is_Access_Type (T) then
2452             Set_Has_Delayed_Freeze (T);
2453          end if;
2454       end;
2455
2456       --  Case where T is the full declaration of some private type which has
2457       --  been swapped in Defining_Identifier (N).
2458
2459       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2460          Process_Full_View (N, T, Def_Id);
2461
2462          --  Record the reference. The form of this is a little strange, since
2463          --  the full declaration has been swapped in. So the first parameter
2464          --  here represents the entity to which a reference is made which is
2465          --  the "real" entity, i.e. the one swapped in, and the second
2466          --  parameter provides the reference location.
2467
2468          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2469          --  since we don't want a complaint about the full type being an
2470          --  unwanted reference to the private type
2471
2472          declare
2473             B : constant Boolean := Has_Pragma_Unreferenced (T);
2474          begin
2475             Set_Has_Pragma_Unreferenced (T, False);
2476             Generate_Reference (T, T, 'c');
2477             Set_Has_Pragma_Unreferenced (T, B);
2478          end;
2479
2480          Set_Completion_Referenced (Def_Id);
2481
2482       --  For completion of incomplete type, process incomplete dependents
2483       --  and always mark the full type as referenced (it is the incomplete
2484       --  type that we get for any real reference).
2485
2486       elsif Ekind (Prev) = E_Incomplete_Type then
2487          Process_Incomplete_Dependents (N, T, Prev);
2488          Generate_Reference (Prev, Def_Id, 'c');
2489          Set_Completion_Referenced (Def_Id);
2490
2491       --  If not private type or incomplete type completion, this is a real
2492       --  definition of a new entity, so record it.
2493
2494       else
2495          Generate_Definition (Def_Id);
2496       end if;
2497
2498       if Chars (Scope (Def_Id)) = Name_System
2499         and then Chars (Def_Id) = Name_Address
2500         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2501       then
2502          Set_Is_Descendent_Of_Address (Def_Id);
2503          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2504          Set_Is_Descendent_Of_Address (Prev);
2505       end if;
2506
2507       Set_Optimize_Alignment_Flags (Def_Id);
2508       Check_Eliminated (Def_Id);
2509
2510       --  If the declaration is a completion and aspects are present, apply
2511       --  them to the entity for the type which is currently the partial
2512       --  view, but which is the one that will be frozen.
2513
2514       if Has_Aspects (N) then
2515          if Prev /= Def_Id then
2516             Analyze_Aspect_Specifications (N, Prev);
2517          else
2518             Analyze_Aspect_Specifications (N, Def_Id);
2519          end if;
2520       end if;
2521    end Analyze_Full_Type_Declaration;
2522
2523    ----------------------------------
2524    -- Analyze_Incomplete_Type_Decl --
2525    ----------------------------------
2526
2527    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2528       F : constant Boolean := Is_Pure (Current_Scope);
2529       T : Entity_Id;
2530
2531    begin
2532       Check_SPARK_Restriction ("incomplete type is not allowed", N);
2533
2534       Generate_Definition (Defining_Identifier (N));
2535
2536       --  Process an incomplete declaration. The identifier must not have been
2537       --  declared already in the scope. However, an incomplete declaration may
2538       --  appear in the private part of a package, for a private type that has
2539       --  already been declared.
2540
2541       --  In this case, the discriminants (if any) must match
2542
2543       T := Find_Type_Name (N);
2544
2545       Set_Ekind (T, E_Incomplete_Type);
2546       Init_Size_Align (T);
2547       Set_Is_First_Subtype (T, True);
2548       Set_Etype (T, T);
2549
2550       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2551       --  incomplete types.
2552
2553       if Tagged_Present (N) then
2554          Set_Is_Tagged_Type (T);
2555          Make_Class_Wide_Type (T);
2556          Set_Direct_Primitive_Operations (T, New_Elmt_List);
2557       end if;
2558
2559       Push_Scope (T);
2560
2561       Set_Stored_Constraint (T, No_Elist);
2562
2563       if Present (Discriminant_Specifications (N)) then
2564          Process_Discriminants (N);
2565       end if;
2566
2567       End_Scope;
2568
2569       --  If the type has discriminants, non-trivial subtypes may be
2570       --  declared before the full view of the type. The full views of those
2571       --  subtypes will be built after the full view of the type.
2572
2573       Set_Private_Dependents (T, New_Elmt_List);
2574       Set_Is_Pure            (T, F);
2575    end Analyze_Incomplete_Type_Decl;
2576
2577    -----------------------------------
2578    -- Analyze_Interface_Declaration --
2579    -----------------------------------
2580
2581    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2582       CW : constant Entity_Id := Class_Wide_Type (T);
2583
2584    begin
2585       Set_Is_Tagged_Type (T);
2586
2587       Set_Is_Limited_Record (T, Limited_Present (Def)
2588                                   or else Task_Present (Def)
2589                                   or else Protected_Present (Def)
2590                                   or else Synchronized_Present (Def));
2591
2592       --  Type is abstract if full declaration carries keyword, or if previous
2593       --  partial view did.
2594
2595       Set_Is_Abstract_Type (T);
2596       Set_Is_Interface (T);
2597
2598       --  Type is a limited interface if it includes the keyword limited, task,
2599       --  protected, or synchronized.
2600
2601       Set_Is_Limited_Interface
2602         (T, Limited_Present (Def)
2603               or else Protected_Present (Def)
2604               or else Synchronized_Present (Def)
2605               or else Task_Present (Def));
2606
2607       Set_Interfaces (T, New_Elmt_List);
2608       Set_Direct_Primitive_Operations (T, New_Elmt_List);
2609
2610       --  Complete the decoration of the class-wide entity if it was already
2611       --  built (i.e. during the creation of the limited view)
2612
2613       if Present (CW) then
2614          Set_Is_Interface (CW);
2615          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2616       end if;
2617
2618       --  Check runtime support for synchronized interfaces
2619
2620       if VM_Target = No_VM
2621         and then (Is_Task_Interface (T)
2622                     or else Is_Protected_Interface (T)
2623                     or else Is_Synchronized_Interface (T))
2624         and then not RTE_Available (RE_Select_Specific_Data)
2625       then
2626          Error_Msg_CRT ("synchronized interfaces", T);
2627       end if;
2628    end Analyze_Interface_Declaration;
2629
2630    -----------------------------
2631    -- Analyze_Itype_Reference --
2632    -----------------------------
2633
2634    --  Nothing to do. This node is placed in the tree only for the benefit of
2635    --  back end processing, and has no effect on the semantic processing.
2636
2637    procedure Analyze_Itype_Reference (N : Node_Id) is
2638    begin
2639       pragma Assert (Is_Itype (Itype (N)));
2640       null;
2641    end Analyze_Itype_Reference;
2642
2643    --------------------------------
2644    -- Analyze_Number_Declaration --
2645    --------------------------------
2646
2647    procedure Analyze_Number_Declaration (N : Node_Id) is
2648       Id    : constant Entity_Id := Defining_Identifier (N);
2649       E     : constant Node_Id   := Expression (N);
2650       T     : Entity_Id;
2651       Index : Interp_Index;
2652       It    : Interp;
2653
2654    begin
2655       Generate_Definition (Id);
2656       Enter_Name (Id);
2657
2658       --  This is an optimization of a common case of an integer literal
2659
2660       if Nkind (E) = N_Integer_Literal then
2661          Set_Is_Static_Expression (E, True);
2662          Set_Etype                (E, Universal_Integer);
2663
2664          Set_Etype     (Id, Universal_Integer);
2665          Set_Ekind     (Id, E_Named_Integer);
2666          Set_Is_Frozen (Id, True);
2667          return;
2668       end if;
2669
2670       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2671
2672       --  Process expression, replacing error by integer zero, to avoid
2673       --  cascaded errors or aborts further along in the processing
2674
2675       --  Replace Error by integer zero, which seems least likely to
2676       --  cause cascaded errors.
2677
2678       if E = Error then
2679          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2680          Set_Error_Posted (E);
2681       end if;
2682
2683       Analyze (E);
2684
2685       --  Verify that the expression is static and numeric. If
2686       --  the expression is overloaded, we apply the preference
2687       --  rule that favors root numeric types.
2688
2689       if not Is_Overloaded (E) then
2690          T := Etype (E);
2691
2692       else
2693          T := Any_Type;
2694
2695          Get_First_Interp (E, Index, It);
2696          while Present (It.Typ) loop
2697             if (Is_Integer_Type (It.Typ)
2698                  or else Is_Real_Type (It.Typ))
2699               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2700             then
2701                if T = Any_Type then
2702                   T := It.Typ;
2703
2704                elsif It.Typ = Universal_Real
2705                  or else It.Typ = Universal_Integer
2706                then
2707                   --  Choose universal interpretation over any other
2708
2709                   T := It.Typ;
2710                   exit;
2711                end if;
2712             end if;
2713
2714             Get_Next_Interp (Index, It);
2715          end loop;
2716       end if;
2717
2718       if Is_Integer_Type (T)  then
2719          Resolve (E, T);
2720          Set_Etype (Id, Universal_Integer);
2721          Set_Ekind (Id, E_Named_Integer);
2722
2723       elsif Is_Real_Type (T) then
2724
2725          --  Because the real value is converted to universal_real, this is a
2726          --  legal context for a universal fixed expression.
2727
2728          if T = Universal_Fixed then
2729             declare
2730                Loc  : constant Source_Ptr := Sloc (N);
2731                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2732                         Subtype_Mark =>
2733                           New_Occurrence_Of (Universal_Real, Loc),
2734                         Expression => Relocate_Node (E));
2735
2736             begin
2737                Rewrite (E, Conv);
2738                Analyze (E);
2739             end;
2740
2741          elsif T = Any_Fixed then
2742             Error_Msg_N ("illegal context for mixed mode operation", E);
2743
2744             --  Expression is of the form : universal_fixed * integer. Try to
2745             --  resolve as universal_real.
2746
2747             T := Universal_Real;
2748             Set_Etype (E, T);
2749          end if;
2750
2751          Resolve (E, T);
2752          Set_Etype (Id, Universal_Real);
2753          Set_Ekind (Id, E_Named_Real);
2754
2755       else
2756          Wrong_Type (E, Any_Numeric);
2757          Resolve (E, T);
2758
2759          Set_Etype               (Id, T);
2760          Set_Ekind               (Id, E_Constant);
2761          Set_Never_Set_In_Source (Id, True);
2762          Set_Is_True_Constant    (Id, True);
2763          return;
2764       end if;
2765
2766       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2767          Set_Etype (E, Etype (Id));
2768       end if;
2769
2770       if not Is_OK_Static_Expression (E) then
2771          Flag_Non_Static_Expr
2772            ("non-static expression used in number declaration!", E);
2773          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2774          Set_Etype (E, Any_Type);
2775       end if;
2776    end Analyze_Number_Declaration;
2777
2778    --------------------------------
2779    -- Analyze_Object_Declaration --
2780    --------------------------------
2781
2782    procedure Analyze_Object_Declaration (N : Node_Id) is
2783       Loc   : constant Source_Ptr := Sloc (N);
2784       Id    : constant Entity_Id  := Defining_Identifier (N);
2785       T     : Entity_Id;
2786       Act_T : Entity_Id;
2787
2788       E : Node_Id := Expression (N);
2789       --  E is set to Expression (N) throughout this routine. When
2790       --  Expression (N) is modified, E is changed accordingly.
2791
2792       Prev_Entity : Entity_Id := Empty;
2793
2794       function Count_Tasks (T : Entity_Id) return Uint;
2795       --  This function is called when a non-generic library level object of a
2796       --  task type is declared. Its function is to count the static number of
2797       --  tasks declared within the type (it is only called if Has_Tasks is set
2798       --  for T). As a side effect, if an array of tasks with non-static bounds
2799       --  or a variant record type is encountered, Check_Restrictions is called
2800       --  indicating the count is unknown.
2801
2802       -----------------
2803       -- Count_Tasks --
2804       -----------------
2805
2806       function Count_Tasks (T : Entity_Id) return Uint is
2807          C : Entity_Id;
2808          X : Node_Id;
2809          V : Uint;
2810
2811       begin
2812          if Is_Task_Type (T) then
2813             return Uint_1;
2814
2815          elsif Is_Record_Type (T) then
2816             if Has_Discriminants (T) then
2817                Check_Restriction (Max_Tasks, N);
2818                return Uint_0;
2819
2820             else
2821                V := Uint_0;
2822                C := First_Component (T);
2823                while Present (C) loop
2824                   V := V + Count_Tasks (Etype (C));
2825                   Next_Component (C);
2826                end loop;
2827
2828                return V;
2829             end if;
2830
2831          elsif Is_Array_Type (T) then
2832             X := First_Index (T);
2833             V := Count_Tasks (Component_Type (T));
2834             while Present (X) loop
2835                C := Etype (X);
2836
2837                if not Is_Static_Subtype (C) then
2838                   Check_Restriction (Max_Tasks, N);
2839                   return Uint_0;
2840                else
2841                   V := V * (UI_Max (Uint_0,
2842                                     Expr_Value (Type_High_Bound (C)) -
2843                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2844                end if;
2845
2846                Next_Index (X);
2847             end loop;
2848
2849             return V;
2850
2851          else
2852             return Uint_0;
2853          end if;
2854       end Count_Tasks;
2855
2856    --  Start of processing for Analyze_Object_Declaration
2857
2858    begin
2859       --  There are three kinds of implicit types generated by an
2860       --  object declaration:
2861
2862       --   1. Those generated by the original Object Definition
2863
2864       --   2. Those generated by the Expression
2865
2866       --   3. Those used to constrained the Object Definition with the
2867       --       expression constraints when it is unconstrained
2868
2869       --  They must be generated in this order to avoid order of elaboration
2870       --  issues. Thus the first step (after entering the name) is to analyze
2871       --  the object definition.
2872
2873       if Constant_Present (N) then
2874          Prev_Entity := Current_Entity_In_Scope (Id);
2875
2876          if Present (Prev_Entity)
2877            and then
2878              --  If the homograph is an implicit subprogram, it is overridden
2879              --  by the current declaration.
2880
2881              ((Is_Overloadable (Prev_Entity)
2882                 and then Is_Inherited_Operation (Prev_Entity))
2883
2884                --  The current object is a discriminal generated for an entry
2885                --  family index. Even though the index is a constant, in this
2886                --  particular context there is no true constant redeclaration.
2887                --  Enter_Name will handle the visibility.
2888
2889                or else
2890                 (Is_Discriminal (Id)
2891                    and then Ekind (Discriminal_Link (Id)) =
2892                               E_Entry_Index_Parameter)
2893
2894                --  The current object is the renaming for a generic declared
2895                --  within the instance.
2896
2897                or else
2898                 (Ekind (Prev_Entity) = E_Package
2899                   and then Nkind (Parent (Prev_Entity)) =
2900                                          N_Package_Renaming_Declaration
2901                   and then not Comes_From_Source (Prev_Entity)
2902                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
2903          then
2904             Prev_Entity := Empty;
2905          end if;
2906       end if;
2907
2908       if Present (Prev_Entity) then
2909          Constant_Redeclaration (Id, N, T);
2910
2911          Generate_Reference (Prev_Entity, Id, 'c');
2912          Set_Completion_Referenced (Id);
2913
2914          if Error_Posted (N) then
2915
2916             --  Type mismatch or illegal redeclaration, Do not analyze
2917             --  expression to avoid cascaded errors.
2918
2919             T := Find_Type_Of_Object (Object_Definition (N), N);
2920             Set_Etype (Id, T);
2921             Set_Ekind (Id, E_Variable);
2922             goto Leave;
2923          end if;
2924
2925       --  In the normal case, enter identifier at the start to catch premature
2926       --  usage in the initialization expression.
2927
2928       else
2929          Generate_Definition (Id);
2930          Enter_Name (Id);
2931
2932          Mark_Coextensions (N, Object_Definition (N));
2933
2934          T := Find_Type_Of_Object (Object_Definition (N), N);
2935
2936          if Nkind (Object_Definition (N)) = N_Access_Definition
2937            and then Present
2938              (Access_To_Subprogram_Definition (Object_Definition (N)))
2939            and then Protected_Present
2940              (Access_To_Subprogram_Definition (Object_Definition (N)))
2941          then
2942             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2943          end if;
2944
2945          if Error_Posted (Id) then
2946             Set_Etype (Id, T);
2947             Set_Ekind (Id, E_Variable);
2948             goto Leave;
2949          end if;
2950       end if;
2951
2952       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2953       --  out some static checks
2954
2955       if Ada_Version >= Ada_2005
2956         and then Can_Never_Be_Null (T)
2957       then
2958          --  In case of aggregates we must also take care of the correct
2959          --  initialization of nested aggregates bug this is done at the
2960          --  point of the analysis of the aggregate (see sem_aggr.adb)
2961
2962          if Present (Expression (N))
2963            and then Nkind (Expression (N)) = N_Aggregate
2964          then
2965             null;
2966
2967          else
2968             declare
2969                Save_Typ : constant Entity_Id := Etype (Id);
2970             begin
2971                Set_Etype (Id, T); --  Temp. decoration for static checks
2972                Null_Exclusion_Static_Checks (N);
2973                Set_Etype (Id, Save_Typ);
2974             end;
2975          end if;
2976       end if;
2977
2978       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2979
2980       --  If deferred constant, make sure context is appropriate. We detect
2981       --  a deferred constant as a constant declaration with no expression.
2982       --  A deferred constant can appear in a package body if its completion
2983       --  is by means of an interface pragma.
2984
2985       if Constant_Present (N)
2986         and then No (E)
2987       then
2988          --  A deferred constant may appear in the declarative part of the
2989          --  following constructs:
2990
2991          --     blocks
2992          --     entry bodies
2993          --     extended return statements
2994          --     package specs
2995          --     package bodies
2996          --     subprogram bodies
2997          --     task bodies
2998
2999          --  When declared inside a package spec, a deferred constant must be
3000          --  completed by a full constant declaration or pragma Import. In all
3001          --  other cases, the only proper completion is pragma Import. Extended
3002          --  return statements are flagged as invalid contexts because they do
3003          --  not have a declarative part and so cannot accommodate the pragma.
3004
3005          if Ekind (Current_Scope) = E_Return_Statement then
3006             Error_Msg_N
3007               ("invalid context for deferred constant declaration (RM 7.4)",
3008                N);
3009             Error_Msg_N
3010               ("\declaration requires an initialization expression",
3011                 N);
3012             Set_Constant_Present (N, False);
3013
3014          --  In Ada 83, deferred constant must be of private type
3015
3016          elsif not Is_Private_Type (T) then
3017             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
3018                Error_Msg_N
3019                  ("(Ada 83) deferred constant must be private type", N);
3020             end if;
3021          end if;
3022
3023       --  If not a deferred constant, then object declaration freezes its type
3024
3025       else
3026          Check_Fully_Declared (T, N);
3027          Freeze_Before (N, T);
3028       end if;
3029
3030       --  If the object was created by a constrained array definition, then
3031       --  set the link in both the anonymous base type and anonymous subtype
3032       --  that are built to represent the array type to point to the object.
3033
3034       if Nkind (Object_Definition (Declaration_Node (Id))) =
3035                         N_Constrained_Array_Definition
3036       then
3037          Set_Related_Array_Object (T, Id);
3038          Set_Related_Array_Object (Base_Type (T), Id);
3039       end if;
3040
3041       --  Special checks for protected objects not at library level
3042
3043       if Is_Protected_Type (T)
3044         and then not Is_Library_Level_Entity (Id)
3045       then
3046          Check_Restriction (No_Local_Protected_Objects, Id);
3047
3048          --  Protected objects with interrupt handlers must be at library level
3049
3050          --  Ada 2005: this test is not needed (and the corresponding clause
3051          --  in the RM is removed) because accessibility checks are sufficient
3052          --  to make handlers not at the library level illegal.
3053
3054          if Has_Interrupt_Handler (T)
3055            and then Ada_Version < Ada_2005
3056          then
3057             Error_Msg_N
3058               ("interrupt object can only be declared at library level", Id);
3059          end if;
3060       end if;
3061
3062       --  The actual subtype of the object is the nominal subtype, unless
3063       --  the nominal one is unconstrained and obtained from the expression.
3064
3065       Act_T := T;
3066
3067       --  These checks should be performed before the initialization expression
3068       --  is considered, so that the Object_Definition node is still the same
3069       --  as in source code.
3070
3071       --  In SPARK, the nominal subtype shall be given by a subtype mark and
3072       --  shall not be unconstrained. (The only exception to this is the
3073       --  admission of declarations of constants of type String.)
3074
3075       if not
3076         Nkind_In (Object_Definition (N), N_Identifier, N_Expanded_Name)
3077       then
3078          Check_SPARK_Restriction
3079            ("subtype mark required", Object_Definition (N));
3080
3081       elsif Is_Array_Type (T)
3082         and then not Is_Constrained (T)
3083         and then T /= Standard_String
3084       then
3085          Check_SPARK_Restriction
3086            ("subtype mark of constrained type expected",
3087             Object_Definition (N));
3088       end if;
3089
3090       --  There are no aliased objects in SPARK
3091
3092       if Aliased_Present (N) then
3093          Check_SPARK_Restriction ("aliased object is not allowed", N);
3094       end if;
3095
3096       --  Process initialization expression if present and not in error
3097
3098       if Present (E) and then E /= Error then
3099
3100          --  Generate an error in case of CPP class-wide object initialization.
3101          --  Required because otherwise the expansion of the class-wide
3102          --  assignment would try to use 'size to initialize the object
3103          --  (primitive that is not available in CPP tagged types).
3104
3105          if Is_Class_Wide_Type (Act_T)
3106            and then
3107              (Is_CPP_Class (Root_Type (Etype (Act_T)))
3108                or else
3109                  (Present (Full_View (Root_Type (Etype (Act_T))))
3110                    and then
3111                      Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
3112          then
3113             Error_Msg_N
3114               ("predefined assignment not available for 'C'P'P tagged types",
3115                E);
3116          end if;
3117
3118          Mark_Coextensions (N, E);
3119          Analyze (E);
3120
3121          --  In case of errors detected in the analysis of the expression,
3122          --  decorate it with the expected type to avoid cascaded errors
3123
3124          if No (Etype (E)) then
3125             Set_Etype (E, T);
3126          end if;
3127
3128          --  If an initialization expression is present, then we set the
3129          --  Is_True_Constant flag. It will be reset if this is a variable
3130          --  and it is indeed modified.
3131
3132          Set_Is_True_Constant (Id, True);
3133
3134          --  If we are analyzing a constant declaration, set its completion
3135          --  flag after analyzing and resolving the expression.
3136
3137          if Constant_Present (N) then
3138             Set_Has_Completion (Id);
3139          end if;
3140
3141          --  Set type and resolve (type may be overridden later on)
3142
3143          Set_Etype (Id, T);
3144          Resolve (E, T);
3145
3146          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3147          --  node (which was marked already-analyzed), we need to set the type
3148          --  to something other than Any_Access in order to keep gigi happy.
3149
3150          if Etype (E) = Any_Access then
3151             Set_Etype (E, T);
3152          end if;
3153
3154          --  If the object is an access to variable, the initialization
3155          --  expression cannot be an access to constant.
3156
3157          if Is_Access_Type (T)
3158            and then not Is_Access_Constant (T)
3159            and then Is_Access_Type (Etype (E))
3160            and then Is_Access_Constant (Etype (E))
3161          then
3162             Error_Msg_N
3163               ("access to variable cannot be initialized "
3164                & "with an access-to-constant expression", E);
3165          end if;
3166
3167          if not Assignment_OK (N) then
3168             Check_Initialization (T, E);
3169          end if;
3170
3171          Check_Unset_Reference (E);
3172
3173          --  If this is a variable, then set current value. If this is a
3174          --  declared constant of a scalar type with a static expression,
3175          --  indicate that it is always valid.
3176
3177          if not Constant_Present (N) then
3178             if Compile_Time_Known_Value (E) then
3179                Set_Current_Value (Id, E);
3180             end if;
3181
3182          elsif Is_Scalar_Type (T)
3183            and then Is_OK_Static_Expression (E)
3184          then
3185             Set_Is_Known_Valid (Id);
3186          end if;
3187
3188          --  Deal with setting of null flags
3189
3190          if Is_Access_Type (T) then
3191             if Known_Non_Null (E) then
3192                Set_Is_Known_Non_Null (Id, True);
3193             elsif Known_Null (E)
3194               and then not Can_Never_Be_Null (Id)
3195             then
3196                Set_Is_Known_Null (Id, True);
3197             end if;
3198          end if;
3199
3200          --  Check incorrect use of dynamically tagged expressions.
3201
3202          if Is_Tagged_Type (T) then
3203             Check_Dynamically_Tagged_Expression
3204               (Expr        => E,
3205                Typ         => T,
3206                Related_Nod => N);
3207          end if;
3208
3209          Apply_Scalar_Range_Check (E, T);
3210          Apply_Static_Length_Check (E, T);
3211
3212          if Nkind (Original_Node (N)) = N_Object_Declaration
3213            and then Comes_From_Source (Original_Node (N))
3214
3215            --  Only call test if needed
3216
3217            and then Restriction_Check_Required (SPARK)
3218            and then not Is_SPARK_Initialization_Expr (E)
3219          then
3220             Check_SPARK_Restriction
3221               ("initialization expression is not appropriate", E);
3222          end if;
3223       end if;
3224
3225       --  If the No_Streams restriction is set, check that the type of the
3226       --  object is not, and does not contain, any subtype derived from
3227       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3228       --  Has_Stream just for efficiency reasons. There is no point in
3229       --  spending time on a Has_Stream check if the restriction is not set.
3230
3231       if Restriction_Check_Required (No_Streams) then
3232          if Has_Stream (T) then
3233             Check_Restriction (No_Streams, N);
3234          end if;
3235       end if;
3236
3237       --  Deal with predicate check before we start to do major rewriting.
3238       --  it is OK to initialize and then check the initialized value, since
3239       --  the object goes out of scope if we get a predicate failure. Note
3240       --  that we do this in the analyzer and not the expander because the
3241       --  analyzer does some substantial rewriting in some cases.
3242
3243       --  We need a predicate check if the type has predicates, and if either
3244       --  there is an initializing expression, or for default initialization
3245       --  when we have at least one case of an explicit default initial value.
3246
3247       if not Suppress_Assignment_Checks (N)
3248         and then Present (Predicate_Function (T))
3249         and then
3250           (Present (E)
3251             or else
3252               Is_Partially_Initialized_Type (T, Include_Implicit => False))
3253       then
3254          Insert_After (N,
3255            Make_Predicate_Check (T, New_Occurrence_Of (Id, Loc)));
3256       end if;
3257
3258       --  Case of unconstrained type
3259
3260       if Is_Indefinite_Subtype (T) then
3261
3262          --  Nothing to do in deferred constant case
3263
3264          if Constant_Present (N) and then No (E) then
3265             null;
3266
3267          --  Case of no initialization present
3268
3269          elsif No (E) then
3270             if No_Initialization (N) then
3271                null;
3272
3273             elsif Is_Class_Wide_Type (T) then
3274                Error_Msg_N
3275                  ("initialization required in class-wide declaration ", N);
3276
3277             else
3278                Error_Msg_N
3279                  ("unconstrained subtype not allowed (need initialization)",
3280                   Object_Definition (N));
3281
3282                if Is_Record_Type (T) and then Has_Discriminants (T) then
3283                   Error_Msg_N
3284                     ("\provide initial value or explicit discriminant values",
3285                      Object_Definition (N));
3286
3287                   Error_Msg_NE
3288                     ("\or give default discriminant values for type&",
3289                      Object_Definition (N), T);
3290
3291                elsif Is_Array_Type (T) then
3292                   Error_Msg_N
3293                     ("\provide initial value or explicit array bounds",
3294                      Object_Definition (N));
3295                end if;
3296             end if;
3297
3298          --  Case of initialization present but in error. Set initial
3299          --  expression as absent (but do not make above complaints)
3300
3301          elsif E = Error then
3302             Set_Expression (N, Empty);
3303             E := Empty;
3304
3305          --  Case of initialization present
3306
3307          else
3308             --  Not allowed in Ada 83
3309
3310             if not Constant_Present (N) then
3311                if Ada_Version = Ada_83
3312                  and then Comes_From_Source (Object_Definition (N))
3313                then
3314                   Error_Msg_N
3315                     ("(Ada 83) unconstrained variable not allowed",
3316                      Object_Definition (N));
3317                end if;
3318             end if;
3319
3320             --  Now we constrain the variable from the initializing expression
3321
3322             --  If the expression is an aggregate, it has been expanded into
3323             --  individual assignments. Retrieve the actual type from the
3324             --  expanded construct.
3325
3326             if Is_Array_Type (T)
3327               and then No_Initialization (N)
3328               and then Nkind (Original_Node (E)) = N_Aggregate
3329             then
3330                Act_T := Etype (E);
3331
3332             --  In case of class-wide interface object declarations we delay
3333             --  the generation of the equivalent record type declarations until
3334             --  its expansion because there are cases in they are not required.
3335
3336             elsif Is_Interface (T) then
3337                null;
3338
3339             else
3340                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3341                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3342             end if;
3343
3344             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3345
3346             if Aliased_Present (N) then
3347                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3348             end if;
3349
3350             Freeze_Before (N, Act_T);
3351             Freeze_Before (N, T);
3352          end if;
3353
3354       elsif Is_Array_Type (T)
3355         and then No_Initialization (N)
3356         and then Nkind (Original_Node (E)) = N_Aggregate
3357       then
3358          if not Is_Entity_Name (Object_Definition (N)) then
3359             Act_T := Etype (E);
3360             Check_Compile_Time_Size (Act_T);
3361
3362             if Aliased_Present (N) then
3363                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3364             end if;
3365          end if;
3366
3367          --  When the given object definition and the aggregate are specified
3368          --  independently, and their lengths might differ do a length check.
3369          --  This cannot happen if the aggregate is of the form (others =>...)
3370
3371          if not Is_Constrained (T) then
3372             null;
3373
3374          elsif Nkind (E) = N_Raise_Constraint_Error then
3375
3376             --  Aggregate is statically illegal. Place back in declaration
3377
3378             Set_Expression (N, E);
3379             Set_No_Initialization (N, False);
3380
3381          elsif T = Etype (E) then
3382             null;
3383
3384          elsif Nkind (E) = N_Aggregate
3385            and then Present (Component_Associations (E))
3386            and then Present (Choices (First (Component_Associations (E))))
3387            and then Nkind (First
3388             (Choices (First (Component_Associations (E))))) = N_Others_Choice
3389          then
3390             null;
3391
3392          else
3393             Apply_Length_Check (E, T);
3394          end if;
3395
3396       --  If the type is limited unconstrained with defaulted discriminants and
3397       --  there is no expression, then the object is constrained by the
3398       --  defaults, so it is worthwhile building the corresponding subtype.
3399
3400       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
3401         and then not Is_Constrained (T)
3402         and then Has_Discriminants (T)
3403       then
3404          if No (E) then
3405             Act_T := Build_Default_Subtype (T, N);
3406          else
3407             --  Ada 2005:  a limited object may be initialized by means of an
3408             --  aggregate. If the type has default discriminants it has an
3409             --  unconstrained nominal type, Its actual subtype will be obtained
3410             --  from the aggregate, and not from the default discriminants.
3411
3412             Act_T := Etype (E);
3413          end if;
3414
3415          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
3416
3417       elsif Present (Underlying_Type (T))
3418         and then not Is_Constrained (Underlying_Type (T))
3419         and then Has_Discriminants (Underlying_Type (T))
3420         and then Nkind (E) = N_Function_Call
3421         and then Constant_Present (N)
3422       then
3423          --  The back-end has problems with constants of a discriminated type
3424          --  with defaults, if the initial value is a function call. We
3425          --  generate an intermediate temporary for the result of the call.
3426          --  It is unclear why this should make it acceptable to gcc. ???
3427
3428          Remove_Side_Effects (E);
3429
3430       --  If this is a constant declaration of an unconstrained type and
3431       --  the initialization is an aggregate, we can use the subtype of the
3432       --  aggregate for the declared entity because it is immutable.
3433
3434       elsif not Is_Constrained (T)
3435         and then Has_Discriminants (T)
3436         and then Constant_Present (N)
3437         and then not Has_Unchecked_Union (T)
3438         and then Nkind (E) = N_Aggregate
3439       then
3440          Act_T := Etype (E);
3441       end if;
3442
3443       --  Check No_Wide_Characters restriction
3444
3445       Check_Wide_Character_Restriction (T, Object_Definition (N));
3446
3447       --  Indicate this is not set in source. Certainly true for constants, and
3448       --  true for variables so far (will be reset for a variable if and when
3449       --  we encounter a modification in the source).
3450
3451       Set_Never_Set_In_Source (Id, True);
3452
3453       --  Now establish the proper kind and type of the object
3454
3455       if Constant_Present (N) then
3456          Set_Ekind            (Id, E_Constant);
3457          Set_Is_True_Constant (Id, True);
3458
3459       else
3460          Set_Ekind (Id, E_Variable);
3461
3462          --  A variable is set as shared passive if it appears in a shared
3463          --  passive package, and is at the outer level. This is not done for
3464          --  entities generated during expansion, because those are always
3465          --  manipulated locally.
3466
3467          if Is_Shared_Passive (Current_Scope)
3468            and then Is_Library_Level_Entity (Id)
3469            and then Comes_From_Source (Id)
3470          then
3471             Set_Is_Shared_Passive (Id);
3472             Check_Shared_Var (Id, T, N);
3473          end if;
3474
3475          --  Set Has_Initial_Value if initializing expression present. Note
3476          --  that if there is no initializing expression, we leave the state
3477          --  of this flag unchanged (usually it will be False, but notably in
3478          --  the case of exception choice variables, it will already be true).
3479
3480          if Present (E) then
3481             Set_Has_Initial_Value (Id, True);
3482          end if;
3483       end if;
3484
3485       --  Initialize alignment and size and capture alignment setting
3486
3487       Init_Alignment               (Id);
3488       Init_Esize                   (Id);
3489       Set_Optimize_Alignment_Flags (Id);
3490
3491       --  Deal with aliased case
3492
3493       if Aliased_Present (N) then
3494          Set_Is_Aliased (Id);
3495
3496          --  If the object is aliased and the type is unconstrained with
3497          --  defaulted discriminants and there is no expression, then the
3498          --  object is constrained by the defaults, so it is worthwhile
3499          --  building the corresponding subtype.
3500
3501          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3502          --  unconstrained, then only establish an actual subtype if the
3503          --  nominal subtype is indefinite. In definite cases the object is
3504          --  unconstrained in Ada 2005.
3505
3506          if No (E)
3507            and then Is_Record_Type (T)
3508            and then not Is_Constrained (T)
3509            and then Has_Discriminants (T)
3510            and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
3511          then
3512             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3513          end if;
3514       end if;
3515
3516       --  Now we can set the type of the object
3517
3518       Set_Etype (Id, Act_T);
3519
3520       --  Deal with controlled types
3521
3522       if Has_Controlled_Component (Etype (Id))
3523         or else Is_Controlled (Etype (Id))
3524       then
3525          if not Is_Library_Level_Entity (Id) then
3526             Check_Restriction (No_Nested_Finalization, N);
3527          else
3528             Validate_Controlled_Object (Id);
3529          end if;
3530
3531          --  Generate a warning when an initialization causes an obvious ABE
3532          --  violation. If the init expression is a simple aggregate there
3533          --  shouldn't be any initialize/adjust call generated. This will be
3534          --  true as soon as aggregates are built in place when possible.
3535
3536          --  ??? at the moment we do not generate warnings for temporaries
3537          --  created for those aggregates although Program_Error might be
3538          --  generated if compiled with -gnato.
3539
3540          if Is_Controlled (Etype (Id))
3541             and then Comes_From_Source (Id)
3542          then
3543             declare
3544                BT : constant Entity_Id := Base_Type (Etype (Id));
3545
3546                Implicit_Call : Entity_Id;
3547                pragma Warnings (Off, Implicit_Call);
3548                --  ??? what is this for (never referenced!)
3549
3550                function Is_Aggr (N : Node_Id) return Boolean;
3551                --  Check that N is an aggregate
3552
3553                -------------
3554                -- Is_Aggr --
3555                -------------
3556
3557                function Is_Aggr (N : Node_Id) return Boolean is
3558                begin
3559                   case Nkind (Original_Node (N)) is
3560                      when N_Aggregate | N_Extension_Aggregate =>
3561                         return True;
3562
3563                      when N_Qualified_Expression |
3564                           N_Type_Conversion      |
3565                           N_Unchecked_Type_Conversion =>
3566                         return Is_Aggr (Expression (Original_Node (N)));
3567
3568                      when others =>
3569                         return False;
3570                   end case;
3571                end Is_Aggr;
3572
3573             begin
3574                --  If no underlying type, we already are in an error situation.
3575                --  Do not try to add a warning since we do not have access to
3576                --  prim-op list.
3577
3578                if No (Underlying_Type (BT)) then
3579                   Implicit_Call := Empty;
3580
3581                --  A generic type does not have usable primitive operators.
3582                --  Initialization calls are built for instances.
3583
3584                elsif Is_Generic_Type (BT) then
3585                   Implicit_Call := Empty;
3586
3587                --  If the init expression is not an aggregate, an adjust call
3588                --  will be generated
3589
3590                elsif Present (E) and then not Is_Aggr (E) then
3591                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
3592
3593                --  If no init expression and we are not in the deferred
3594                --  constant case, an Initialize call will be generated
3595
3596                elsif No (E) and then not Constant_Present (N) then
3597                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
3598
3599                else
3600                   Implicit_Call := Empty;
3601                end if;
3602             end;
3603          end if;
3604       end if;
3605
3606       if Has_Task (Etype (Id)) then
3607          Check_Restriction (No_Tasking, N);
3608
3609          --  Deal with counting max tasks
3610
3611          --  Nothing to do if inside a generic
3612
3613          if Inside_A_Generic then
3614             null;
3615
3616          --  If library level entity, then count tasks
3617
3618          elsif Is_Library_Level_Entity (Id) then
3619             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3620
3621          --  If not library level entity, then indicate we don't know max
3622          --  tasks and also check task hierarchy restriction and blocking
3623          --  operation (since starting a task is definitely blocking!)
3624
3625          else
3626             Check_Restriction (Max_Tasks, N);
3627             Check_Restriction (No_Task_Hierarchy, N);
3628             Check_Potentially_Blocking_Operation (N);
3629          end if;
3630
3631          --  A rather specialized test. If we see two tasks being declared
3632          --  of the same type in the same object declaration, and the task
3633          --  has an entry with an address clause, we know that program error
3634          --  will be raised at run time since we can't have two tasks with
3635          --  entries at the same address.
3636
3637          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3638             declare
3639                E : Entity_Id;
3640
3641             begin
3642                E := First_Entity (Etype (Id));
3643                while Present (E) loop
3644                   if Ekind (E) = E_Entry
3645                     and then Present (Get_Attribute_Definition_Clause
3646                                         (E, Attribute_Address))
3647                   then
3648                      Error_Msg_N
3649                        ("?more than one task with same entry address", N);
3650                      Error_Msg_N
3651                        ("\?Program_Error will be raised at run time", N);
3652                      Insert_Action (N,
3653                        Make_Raise_Program_Error (Loc,
3654                          Reason => PE_Duplicated_Entry_Address));
3655                      exit;
3656                   end if;
3657
3658                   Next_Entity (E);
3659                end loop;
3660             end;
3661          end if;
3662       end if;
3663
3664       --  Some simple constant-propagation: if the expression is a constant
3665       --  string initialized with a literal, share the literal. This avoids
3666       --  a run-time copy.
3667
3668       if Present (E)
3669         and then Is_Entity_Name (E)
3670         and then Ekind (Entity (E)) = E_Constant
3671         and then Base_Type (Etype (E)) = Standard_String
3672       then
3673          declare
3674             Val : constant Node_Id := Constant_Value (Entity (E));
3675          begin
3676             if Present (Val)
3677               and then Nkind (Val) = N_String_Literal
3678             then
3679                Rewrite (E, New_Copy (Val));
3680             end if;
3681          end;
3682       end if;
3683
3684       --  Another optimization: if the nominal subtype is unconstrained and
3685       --  the expression is a function call that returns an unconstrained
3686       --  type, rewrite the declaration as a renaming of the result of the
3687       --  call. The exceptions below are cases where the copy is expected,
3688       --  either by the back end (Aliased case) or by the semantics, as for
3689       --  initializing controlled types or copying tags for classwide types.
3690
3691       if Present (E)
3692         and then Nkind (E) = N_Explicit_Dereference
3693         and then Nkind (Original_Node (E)) = N_Function_Call
3694         and then not Is_Library_Level_Entity (Id)
3695         and then not Is_Constrained (Underlying_Type (T))
3696         and then not Is_Aliased (Id)
3697         and then not Is_Class_Wide_Type (T)
3698         and then not Is_Controlled (T)
3699         and then not Has_Controlled_Component (Base_Type (T))
3700         and then Expander_Active
3701       then
3702          Rewrite (N,
3703            Make_Object_Renaming_Declaration (Loc,
3704              Defining_Identifier => Id,
3705              Access_Definition   => Empty,
3706              Subtype_Mark        => New_Occurrence_Of
3707                                       (Base_Type (Etype (Id)), Loc),
3708              Name                => E));
3709
3710          Set_Renamed_Object (Id, E);
3711
3712          --  Force generation of debugging information for the constant and for
3713          --  the renamed function call.
3714
3715          Set_Debug_Info_Needed (Id);
3716          Set_Debug_Info_Needed (Entity (Prefix (E)));
3717       end if;
3718
3719       if Present (Prev_Entity)
3720         and then Is_Frozen (Prev_Entity)
3721         and then not Error_Posted (Id)
3722       then
3723          Error_Msg_N ("full constant declaration appears too late", N);
3724       end if;
3725
3726       Check_Eliminated (Id);
3727
3728       --  Deal with setting In_Private_Part flag if in private part
3729
3730       if Ekind (Scope (Id)) = E_Package
3731         and then In_Private_Part (Scope (Id))
3732       then
3733          Set_In_Private_Part (Id);
3734       end if;
3735
3736       --  Check for violation of No_Local_Timing_Events
3737
3738       if Restriction_Check_Required (No_Local_Timing_Events)
3739         and then not Is_Library_Level_Entity (Id)
3740         and then Is_RTE (Etype (Id), RE_Timing_Event)
3741       then
3742          Check_Restriction (No_Local_Timing_Events, N);
3743       end if;
3744
3745    <<Leave>>
3746       if Has_Aspects (N) then
3747          Analyze_Aspect_Specifications (N, Id);
3748       end if;
3749    end Analyze_Object_Declaration;
3750
3751    ---------------------------
3752    -- Analyze_Others_Choice --
3753    ---------------------------
3754
3755    --  Nothing to do for the others choice node itself, the semantic analysis
3756    --  of the others choice will occur as part of the processing of the parent
3757
3758    procedure Analyze_Others_Choice (N : Node_Id) is
3759       pragma Warnings (Off, N);
3760    begin
3761       null;
3762    end Analyze_Others_Choice;
3763
3764    -------------------------------------------
3765    -- Analyze_Private_Extension_Declaration --
3766    -------------------------------------------
3767
3768    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3769       T           : constant Entity_Id := Defining_Identifier (N);
3770       Indic       : constant Node_Id   := Subtype_Indication (N);
3771       Parent_Type : Entity_Id;
3772       Parent_Base : Entity_Id;
3773
3774    begin
3775       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3776
3777       if Is_Non_Empty_List (Interface_List (N)) then
3778          declare
3779             Intf : Node_Id;
3780             T    : Entity_Id;
3781
3782          begin
3783             Intf := First (Interface_List (N));
3784             while Present (Intf) loop
3785                T := Find_Type_Of_Subtype_Indic (Intf);
3786
3787                Diagnose_Interface (Intf, T);
3788                Next (Intf);
3789             end loop;
3790          end;
3791       end if;
3792
3793       Generate_Definition (T);
3794
3795       --  For other than Ada 2012, just enter the name in the current scope
3796
3797       if Ada_Version < Ada_2012 then
3798          Enter_Name (T);
3799
3800       --  Ada 2012 (AI05-0162): Enter the name in the current scope handling
3801       --  case of private type that completes an incomplete type.
3802
3803       else
3804          declare
3805             Prev : Entity_Id;
3806
3807          begin
3808             Prev := Find_Type_Name (N);
3809
3810             pragma Assert (Prev = T
3811               or else (Ekind (Prev) = E_Incomplete_Type
3812                          and then Present (Full_View (Prev))
3813                          and then Full_View (Prev) = T));
3814          end;
3815       end if;
3816
3817       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3818       Parent_Base := Base_Type (Parent_Type);
3819
3820       if Parent_Type = Any_Type
3821         or else Etype (Parent_Type) = Any_Type
3822       then
3823          Set_Ekind (T, Ekind (Parent_Type));
3824          Set_Etype (T, Any_Type);
3825          goto Leave;
3826
3827       elsif not Is_Tagged_Type (Parent_Type) then
3828          Error_Msg_N
3829            ("parent of type extension must be a tagged type ", Indic);
3830          goto Leave;
3831
3832       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3833          Error_Msg_N ("premature derivation of incomplete type", Indic);
3834          goto Leave;
3835
3836       elsif Is_Concurrent_Type (Parent_Type) then
3837          Error_Msg_N
3838            ("parent type of a private extension cannot be "
3839             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3840
3841          Set_Etype              (T, Any_Type);
3842          Set_Ekind              (T, E_Limited_Private_Type);
3843          Set_Private_Dependents (T, New_Elmt_List);
3844          Set_Error_Posted       (T);
3845          goto Leave;
3846       end if;
3847
3848       --  Perhaps the parent type should be changed to the class-wide type's
3849       --  specific type in this case to prevent cascading errors ???
3850
3851       if Is_Class_Wide_Type (Parent_Type) then
3852          Error_Msg_N
3853            ("parent of type extension must not be a class-wide type", Indic);
3854          goto Leave;
3855       end if;
3856
3857       if (not Is_Package_Or_Generic_Package (Current_Scope)
3858            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3859         or else In_Private_Part (Current_Scope)
3860
3861       then
3862          Error_Msg_N ("invalid context for private extension", N);
3863       end if;
3864
3865       --  Set common attributes
3866
3867       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3868       Set_Scope            (T, Current_Scope);
3869       Set_Ekind            (T, E_Record_Type_With_Private);
3870       Init_Size_Align      (T);
3871
3872       Set_Etype            (T,            Parent_Base);
3873       Set_Has_Task         (T, Has_Task  (Parent_Base));
3874
3875       Set_Convention       (T, Convention     (Parent_Type));
3876       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3877       Set_Is_First_Subtype (T);
3878       Make_Class_Wide_Type (T);
3879
3880       if Unknown_Discriminants_Present (N) then
3881          Set_Discriminant_Constraint (T, No_Elist);
3882       end if;
3883
3884       Build_Derived_Record_Type (N, Parent_Type, T);
3885
3886       --  Propagate inherited invariant information. The new type has
3887       --  invariants, if the parent type has inheritable invariants,
3888       --  and these invariants can in turn be inherited.
3889
3890       if Has_Inheritable_Invariants (Parent_Type) then
3891          Set_Has_Inheritable_Invariants (T);
3892          Set_Has_Invariants (T);
3893       end if;
3894
3895       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3896       --  synchronized formal derived type.
3897
3898       if Ada_Version >= Ada_2005
3899         and then Synchronized_Present (N)
3900       then
3901          Set_Is_Limited_Record (T);
3902
3903          --  Formal derived type case
3904
3905          if Is_Generic_Type (T) then
3906
3907             --  The parent must be a tagged limited type or a synchronized
3908             --  interface.
3909
3910             if (not Is_Tagged_Type (Parent_Type)
3911                   or else not Is_Limited_Type (Parent_Type))
3912               and then
3913                (not Is_Interface (Parent_Type)
3914                   or else not Is_Synchronized_Interface (Parent_Type))
3915             then
3916                Error_Msg_NE ("parent type of & must be tagged limited " &
3917                              "or synchronized", N, T);
3918             end if;
3919
3920             --  The progenitors (if any) must be limited or synchronized
3921             --  interfaces.
3922
3923             if Present (Interfaces (T)) then
3924                declare
3925                   Iface      : Entity_Id;
3926                   Iface_Elmt : Elmt_Id;
3927
3928                begin
3929                   Iface_Elmt := First_Elmt (Interfaces (T));
3930                   while Present (Iface_Elmt) loop
3931                      Iface := Node (Iface_Elmt);
3932
3933                      if not Is_Limited_Interface (Iface)
3934                        and then not Is_Synchronized_Interface (Iface)
3935                      then
3936                         Error_Msg_NE ("progenitor & must be limited " &
3937                                       "or synchronized", N, Iface);
3938                      end if;
3939
3940                      Next_Elmt (Iface_Elmt);
3941                   end loop;
3942                end;
3943             end if;
3944
3945          --  Regular derived extension, the parent must be a limited or
3946          --  synchronized interface.
3947
3948          else
3949             if not Is_Interface (Parent_Type)
3950               or else (not Is_Limited_Interface (Parent_Type)
3951                          and then
3952                        not Is_Synchronized_Interface (Parent_Type))
3953             then
3954                Error_Msg_NE
3955                  ("parent type of & must be limited interface", N, T);
3956             end if;
3957          end if;
3958
3959       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
3960       --  extension with a synchronized parent must be explicitly declared
3961       --  synchronized, because the full view will be a synchronized type.
3962       --  This must be checked before the check for limited types below,
3963       --  to ensure that types declared limited are not allowed to extend
3964       --  synchronized interfaces.
3965
3966       elsif Is_Interface (Parent_Type)
3967         and then Is_Synchronized_Interface (Parent_Type)
3968         and then not Synchronized_Present (N)
3969       then
3970          Error_Msg_NE
3971            ("private extension of& must be explicitly synchronized",
3972              N, Parent_Type);
3973
3974       elsif Limited_Present (N) then
3975          Set_Is_Limited_Record (T);
3976
3977          if not Is_Limited_Type (Parent_Type)
3978            and then
3979              (not Is_Interface (Parent_Type)
3980                or else not Is_Limited_Interface (Parent_Type))
3981          then
3982             Error_Msg_NE ("parent type& of limited extension must be limited",
3983               N, Parent_Type);
3984          end if;
3985       end if;
3986
3987    <<Leave>>
3988       if Has_Aspects (N) then
3989          Analyze_Aspect_Specifications (N, T);
3990       end if;
3991    end Analyze_Private_Extension_Declaration;
3992
3993    ---------------------------------
3994    -- Analyze_Subtype_Declaration --
3995    ---------------------------------
3996
3997    procedure Analyze_Subtype_Declaration
3998      (N    : Node_Id;
3999       Skip : Boolean := False)
4000    is
4001       Id       : constant Entity_Id := Defining_Identifier (N);
4002       T        : Entity_Id;
4003       R_Checks : Check_Result;
4004
4005    begin
4006       Generate_Definition (Id);
4007       Set_Is_Pure (Id, Is_Pure (Current_Scope));
4008       Init_Size_Align (Id);
4009
4010       --  The following guard condition on Enter_Name is to handle cases where
4011       --  the defining identifier has already been entered into the scope but
4012       --  the declaration as a whole needs to be analyzed.
4013
4014       --  This case in particular happens for derived enumeration types. The
4015       --  derived enumeration type is processed as an inserted enumeration type
4016       --  declaration followed by a rewritten subtype declaration. The defining
4017       --  identifier, however, is entered into the name scope very early in the
4018       --  processing of the original type declaration and therefore needs to be
4019       --  avoided here, when the created subtype declaration is analyzed. (See
4020       --  Build_Derived_Types)
4021
4022       --  This also happens when the full view of a private type is derived
4023       --  type with constraints. In this case the entity has been introduced
4024       --  in the private declaration.
4025
4026       if Skip
4027         or else (Present (Etype (Id))
4028                   and then (Is_Private_Type (Etype (Id))
4029                              or else Is_Task_Type (Etype (Id))
4030                              or else Is_Rewrite_Substitution (N)))
4031       then
4032          null;
4033
4034       else
4035          Enter_Name (Id);
4036       end if;
4037
4038       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
4039
4040       --  Inherit common attributes
4041
4042       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
4043       Set_Is_Volatile       (Id, Is_Volatile       (T));
4044       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
4045       Set_Is_Atomic         (Id, Is_Atomic         (T));
4046       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
4047       Set_Is_Ada_2012_Only  (Id, Is_Ada_2012_Only  (T));
4048       Set_Convention        (Id, Convention        (T));
4049
4050       --  If ancestor has predicates then so does the subtype, and in addition
4051       --  we must delay the freeze to properly arrange predicate inheritance.
4052
4053       --  The Ancestor_Type test is a big kludge, there seem to be cases in
4054       --  which T = ID, so the above tests and assignments do nothing???
4055
4056       if Has_Predicates (T)
4057         or else (Present (Ancestor_Subtype (T))
4058                   and then Has_Predicates (Ancestor_Subtype (T)))
4059       then
4060          Set_Has_Predicates (Id);
4061          Set_Has_Delayed_Freeze (Id);
4062       end if;
4063
4064       --  Subtype of Boolean cannot have a constraint in SPARK
4065
4066       if Is_Boolean_Type (T)
4067         and then Nkind (Subtype_Indication (N)) = N_Subtype_Indication
4068       then
4069          Check_SPARK_Restriction
4070            ("subtype of Boolean cannot have constraint", N);
4071       end if;
4072
4073       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4074          declare
4075             Cstr     : constant Node_Id := Constraint (Subtype_Indication (N));
4076             One_Cstr : Node_Id;
4077             Low      : Node_Id;
4078             High     : Node_Id;
4079
4080          begin
4081             if Nkind (Cstr) = N_Index_Or_Discriminant_Constraint then
4082                One_Cstr := First (Constraints (Cstr));
4083                while Present (One_Cstr) loop
4084
4085                   --  Index or discriminant constraint in SPARK must be a
4086                   --  subtype mark.
4087
4088                   if not
4089                     Nkind_In (One_Cstr, N_Identifier, N_Expanded_Name)
4090                   then
4091                      Check_SPARK_Restriction
4092                        ("subtype mark required", One_Cstr);
4093
4094                   --  String subtype must have a lower bound of 1 in SPARK.
4095                   --  Note that we do not need to test for the non-static case
4096                   --  here, since that was already taken care of in
4097                   --  Process_Range_Expr_In_Decl.
4098
4099                   elsif Base_Type (T) = Standard_String then
4100                      Get_Index_Bounds (One_Cstr, Low, High);
4101
4102                      if Is_OK_Static_Expression (Low)
4103                        and then Expr_Value (Low) /= 1
4104                      then
4105                         Check_SPARK_Restriction
4106                           ("String subtype must have lower bound of 1", N);
4107                      end if;
4108                   end if;
4109
4110                   Next (One_Cstr);
4111                end loop;
4112             end if;
4113          end;
4114       end if;
4115
4116       --  In the case where there is no constraint given in the subtype
4117       --  indication, Process_Subtype just returns the Subtype_Mark, so its
4118       --  semantic attributes must be established here.
4119
4120       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
4121          Set_Etype (Id, Base_Type (T));
4122
4123          --  Subtype of unconstrained array without constraint is not allowed
4124          --  in SPARK.
4125
4126          if Is_Array_Type (T)
4127            and then not Is_Constrained (T)
4128          then
4129             Check_SPARK_Restriction
4130               ("subtype of unconstrained array must have constraint", N);
4131          end if;
4132
4133          case Ekind (T) is
4134             when Array_Kind =>
4135                Set_Ekind                       (Id, E_Array_Subtype);
4136                Copy_Array_Subtype_Attributes   (Id, T);
4137
4138             when Decimal_Fixed_Point_Kind =>
4139                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
4140                Set_Digits_Value         (Id, Digits_Value       (T));
4141                Set_Delta_Value          (Id, Delta_Value        (T));
4142                Set_Scale_Value          (Id, Scale_Value        (T));
4143                Set_Small_Value          (Id, Small_Value        (T));
4144                Set_Scalar_Range         (Id, Scalar_Range       (T));
4145                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
4146                Set_Is_Constrained       (Id, Is_Constrained     (T));
4147                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4148                Set_RM_Size              (Id, RM_Size            (T));
4149
4150             when Enumeration_Kind =>
4151                Set_Ekind                (Id, E_Enumeration_Subtype);
4152                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
4153                Set_Scalar_Range         (Id, Scalar_Range       (T));
4154                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
4155                Set_Is_Constrained       (Id, Is_Constrained     (T));
4156                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4157                Set_RM_Size              (Id, RM_Size            (T));
4158
4159             when Ordinary_Fixed_Point_Kind =>
4160                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
4161                Set_Scalar_Range         (Id, Scalar_Range       (T));
4162                Set_Small_Value          (Id, Small_Value        (T));
4163                Set_Delta_Value          (Id, Delta_Value        (T));
4164                Set_Is_Constrained       (Id, Is_Constrained     (T));
4165                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4166                Set_RM_Size              (Id, RM_Size            (T));
4167
4168             when Float_Kind =>
4169                Set_Ekind                (Id, E_Floating_Point_Subtype);
4170                Set_Scalar_Range         (Id, Scalar_Range       (T));
4171                Set_Digits_Value         (Id, Digits_Value       (T));
4172                Set_Is_Constrained       (Id, Is_Constrained     (T));
4173
4174             when Signed_Integer_Kind =>
4175                Set_Ekind                (Id, E_Signed_Integer_Subtype);
4176                Set_Scalar_Range         (Id, Scalar_Range       (T));
4177                Set_Is_Constrained       (Id, Is_Constrained     (T));
4178                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4179                Set_RM_Size              (Id, RM_Size            (T));
4180
4181             when Modular_Integer_Kind =>
4182                Set_Ekind                (Id, E_Modular_Integer_Subtype);
4183                Set_Scalar_Range         (Id, Scalar_Range       (T));
4184                Set_Is_Constrained       (Id, Is_Constrained     (T));
4185                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
4186                Set_RM_Size              (Id, RM_Size            (T));
4187
4188             when Class_Wide_Kind =>
4189                Set_Ekind                (Id, E_Class_Wide_Subtype);
4190                Set_First_Entity         (Id, First_Entity       (T));
4191                Set_Last_Entity          (Id, Last_Entity        (T));
4192                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
4193                Set_Cloned_Subtype       (Id, T);
4194                Set_Is_Tagged_Type       (Id, True);
4195                Set_Has_Unknown_Discriminants
4196                                         (Id, True);
4197
4198                if Ekind (T) = E_Class_Wide_Subtype then
4199                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
4200                end if;
4201
4202             when E_Record_Type | E_Record_Subtype =>
4203                Set_Ekind                (Id, E_Record_Subtype);
4204
4205                if Ekind (T) = E_Record_Subtype
4206                  and then Present (Cloned_Subtype (T))
4207                then
4208                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
4209                else
4210                   Set_Cloned_Subtype    (Id, T);
4211                end if;
4212
4213                Set_First_Entity         (Id, First_Entity       (T));
4214                Set_Last_Entity          (Id, Last_Entity        (T));
4215                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
4216                Set_Is_Constrained       (Id, Is_Constrained     (T));
4217                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
4218                Set_Has_Unknown_Discriminants
4219                                         (Id, Has_Unknown_Discriminants (T));
4220
4221                if Has_Discriminants (T) then
4222                   Set_Discriminant_Constraint
4223                                         (Id, Discriminant_Constraint (T));
4224                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4225
4226                elsif Has_Unknown_Discriminants (Id) then
4227                   Set_Discriminant_Constraint (Id, No_Elist);
4228                end if;
4229
4230                if Is_Tagged_Type (T) then
4231                   Set_Is_Tagged_Type    (Id);
4232                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
4233                   Set_Direct_Primitive_Operations
4234                                         (Id, Direct_Primitive_Operations (T));
4235                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
4236
4237                   if Is_Interface (T) then
4238                      Set_Is_Interface (Id);
4239                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
4240                   end if;
4241                end if;
4242
4243             when Private_Kind =>
4244                Set_Ekind              (Id, Subtype_Kind (Ekind   (T)));
4245                Set_Has_Discriminants  (Id, Has_Discriminants     (T));
4246                Set_Is_Constrained     (Id, Is_Constrained        (T));
4247                Set_First_Entity       (Id, First_Entity          (T));
4248                Set_Last_Entity        (Id, Last_Entity           (T));
4249                Set_Private_Dependents (Id, New_Elmt_List);
4250                Set_Is_Limited_Record  (Id, Is_Limited_Record     (T));
4251                Set_Has_Unknown_Discriminants
4252                                       (Id, Has_Unknown_Discriminants (T));
4253                Set_Known_To_Have_Preelab_Init
4254                                       (Id, Known_To_Have_Preelab_Init (T));
4255
4256                if Is_Tagged_Type (T) then
4257                   Set_Is_Tagged_Type              (Id);
4258                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
4259                   Set_Class_Wide_Type             (Id, Class_Wide_Type (T));
4260                   Set_Direct_Primitive_Operations (Id,
4261                     Direct_Primitive_Operations (T));
4262                end if;
4263
4264                --  In general the attributes of the subtype of a private type
4265                --  are the attributes of the partial view of parent. However,
4266                --  the full view may be a discriminated type, and the subtype
4267                --  must share the discriminant constraint to generate correct
4268                --  calls to initialization procedures.
4269
4270                if Has_Discriminants (T) then
4271                   Set_Discriminant_Constraint
4272                                      (Id, Discriminant_Constraint (T));
4273                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4274
4275                elsif Present (Full_View (T))
4276                  and then Has_Discriminants (Full_View (T))
4277                then
4278                   Set_Discriminant_Constraint
4279                                (Id, Discriminant_Constraint (Full_View (T)));
4280                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4281
4282                   --  This would seem semantically correct, but apparently
4283                   --  confuses the back-end. To be explained and checked with
4284                   --  current version ???
4285
4286                   --  Set_Has_Discriminants (Id);
4287                end if;
4288
4289                Prepare_Private_Subtype_Completion (Id, N);
4290
4291             when Access_Kind =>
4292                Set_Ekind             (Id, E_Access_Subtype);
4293                Set_Is_Constrained    (Id, Is_Constrained        (T));
4294                Set_Is_Access_Constant
4295                                      (Id, Is_Access_Constant    (T));
4296                Set_Directly_Designated_Type
4297                                      (Id, Designated_Type       (T));
4298                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4299
4300                --  A Pure library_item must not contain the declaration of a
4301                --  named access type, except within a subprogram, generic
4302                --  subprogram, task unit, or protected unit, or if it has
4303                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4304
4305                if Comes_From_Source (Id)
4306                  and then In_Pure_Unit
4307                  and then not In_Subprogram_Task_Protected_Unit
4308                  and then not No_Pool_Assigned (Id)
4309                then
4310                   Error_Msg_N
4311                     ("named access types not allowed in pure unit", N);
4312                end if;
4313
4314             when Concurrent_Kind =>
4315                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4316                Set_Corresponding_Record_Type (Id,
4317                                          Corresponding_Record_Type (T));
4318                Set_First_Entity         (Id, First_Entity          (T));
4319                Set_First_Private_Entity (Id, First_Private_Entity  (T));
4320                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4321                Set_Is_Constrained       (Id, Is_Constrained        (T));
4322                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4323                Set_Last_Entity          (Id, Last_Entity           (T));
4324
4325                if Has_Discriminants (T) then
4326                   Set_Discriminant_Constraint (Id,
4327                                            Discriminant_Constraint (T));
4328                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4329                end if;
4330
4331             when E_Incomplete_Type =>
4332                if Ada_Version >= Ada_2005 then
4333                   Set_Ekind (Id, E_Incomplete_Subtype);
4334
4335                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
4336                   --  of an incomplete type visible through a limited
4337                   --  with clause.
4338
4339                   if From_With_Type (T)
4340                     and then Present (Non_Limited_View (T))
4341                   then
4342                      Set_From_With_Type   (Id);
4343                      Set_Non_Limited_View (Id, Non_Limited_View (T));
4344
4345                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
4346                   --  to the private dependents of the original incomplete
4347                   --  type for future transformation.
4348
4349                   else
4350                      Append_Elmt (Id, Private_Dependents (T));
4351                   end if;
4352
4353                --  If the subtype name denotes an incomplete type an error
4354                --  was already reported by Process_Subtype.
4355
4356                else
4357                   Set_Etype (Id, Any_Type);
4358                end if;
4359
4360             when others =>
4361                raise Program_Error;
4362          end case;
4363       end if;
4364
4365       if Etype (Id) = Any_Type then
4366          goto Leave;
4367       end if;
4368
4369       --  Some common processing on all types
4370
4371       Set_Size_Info      (Id,                 T);
4372       Set_First_Rep_Item (Id, First_Rep_Item (T));
4373
4374       T := Etype (Id);
4375
4376       Set_Is_Immediately_Visible   (Id, True);
4377       Set_Depends_On_Private       (Id, Has_Private_Component (T));
4378       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
4379
4380       if Is_Interface (T) then
4381          Set_Is_Interface (Id);
4382       end if;
4383
4384       if Present (Generic_Parent_Type (N))
4385         and then
4386           (Nkind
4387             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
4388             or else Nkind
4389               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
4390                 /= N_Formal_Private_Type_Definition)
4391       then
4392          if Is_Tagged_Type (Id) then
4393
4394             --  If this is a generic actual subtype for a synchronized type,
4395             --  the primitive operations are those of the corresponding record
4396             --  for which there is a separate subtype declaration.
4397
4398             if Is_Concurrent_Type (Id) then
4399                null;
4400             elsif Is_Class_Wide_Type (Id) then
4401                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
4402             else
4403                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
4404             end if;
4405
4406          elsif Scope (Etype (Id)) /= Standard_Standard then
4407             Derive_Subprograms (Generic_Parent_Type (N), Id);
4408          end if;
4409       end if;
4410
4411       if Is_Private_Type (T)
4412         and then Present (Full_View (T))
4413       then
4414          Conditional_Delay (Id, Full_View (T));
4415
4416       --  The subtypes of components or subcomponents of protected types
4417       --  do not need freeze nodes, which would otherwise appear in the
4418       --  wrong scope (before the freeze node for the protected type). The
4419       --  proper subtypes are those of the subcomponents of the corresponding
4420       --  record.
4421
4422       elsif Ekind (Scope (Id)) /= E_Protected_Type
4423         and then Present (Scope (Scope (Id))) -- error defense!
4424         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
4425       then
4426          Conditional_Delay (Id, T);
4427       end if;
4428
4429       --  Check that Constraint_Error is raised for a scalar subtype indication
4430       --  when the lower or upper bound of a non-null range lies outside the
4431       --  range of the type mark.
4432
4433       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4434          if Is_Scalar_Type (Etype (Id))
4435             and then Scalar_Range (Id) /=
4436                      Scalar_Range (Etype (Subtype_Mark
4437                                            (Subtype_Indication (N))))
4438          then
4439             Apply_Range_Check
4440               (Scalar_Range (Id),
4441                Etype (Subtype_Mark (Subtype_Indication (N))));
4442
4443          --  In the array case, check compatibility for each index
4444
4445          elsif Is_Array_Type (Etype (Id))
4446            and then Present (First_Index (Id))
4447          then
4448             --  This really should be a subprogram that finds the indications
4449             --  to check???
4450
4451             declare
4452                Subt_Index   : Node_Id := First_Index (Id);
4453                Target_Index : Node_Id :=
4454                                 First_Index (Etype
4455                                   (Subtype_Mark (Subtype_Indication (N))));
4456                Has_Dyn_Chk  : Boolean := Has_Dynamic_Range_Check (N);
4457
4458             begin
4459                while Present (Subt_Index) loop
4460                   if ((Nkind (Subt_Index) = N_Identifier
4461                          and then Ekind (Entity (Subt_Index)) in Scalar_Kind)
4462                        or else Nkind (Subt_Index) = N_Subtype_Indication)
4463                     and then
4464                       Nkind (Scalar_Range (Etype (Subt_Index))) = N_Range
4465                   then
4466                      declare
4467                         Target_Typ : constant Entity_Id :=
4468                                        Etype (Target_Index);
4469                      begin
4470                         R_Checks :=
4471                           Get_Range_Checks
4472                             (Scalar_Range (Etype (Subt_Index)),
4473                              Target_Typ,
4474                              Etype (Subt_Index),
4475                              Defining_Identifier (N));
4476
4477                         --  Reset Has_Dynamic_Range_Check on the subtype to
4478                         --  prevent elision of the index check due to a dynamic
4479                         --  check generated for a preceding index (needed since
4480                         --  Insert_Range_Checks tries to avoid generating
4481                         --  redundant checks on a given declaration).
4482
4483                         Set_Has_Dynamic_Range_Check (N, False);
4484
4485                         Insert_Range_Checks
4486                           (R_Checks,
4487                            N,
4488                            Target_Typ,
4489                            Sloc (Defining_Identifier (N)));
4490
4491                         --  Record whether this index involved a dynamic check
4492
4493                         Has_Dyn_Chk :=
4494                           Has_Dyn_Chk or else Has_Dynamic_Range_Check (N);
4495                      end;
4496                   end if;
4497
4498                   Next_Index (Subt_Index);
4499                   Next_Index (Target_Index);
4500                end loop;
4501
4502                --  Finally, mark whether the subtype involves dynamic checks
4503
4504                Set_Has_Dynamic_Range_Check (N, Has_Dyn_Chk);
4505             end;
4506          end if;
4507       end if;
4508
4509       --  Make sure that generic actual types are properly frozen. The subtype
4510       --  is marked as a generic actual type when the enclosing instance is
4511       --  analyzed, so here we identify the subtype from the tree structure.
4512
4513       if Expander_Active
4514         and then Is_Generic_Actual_Type (Id)
4515         and then In_Instance
4516         and then not Comes_From_Source (N)
4517         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
4518         and then Is_Frozen (T)
4519       then
4520          Freeze_Before (N, Id);
4521       end if;
4522
4523       Set_Optimize_Alignment_Flags (Id);
4524       Check_Eliminated (Id);
4525
4526    <<Leave>>
4527       if Has_Aspects (N) then
4528          Analyze_Aspect_Specifications (N, Id);
4529       end if;
4530    end Analyze_Subtype_Declaration;
4531
4532    --------------------------------
4533    -- Analyze_Subtype_Indication --
4534    --------------------------------
4535
4536    procedure Analyze_Subtype_Indication (N : Node_Id) is
4537       T : constant Entity_Id := Subtype_Mark (N);
4538       R : constant Node_Id   := Range_Expression (Constraint (N));
4539
4540    begin
4541       Analyze (T);
4542
4543       if R /= Error then
4544          Analyze (R);
4545          Set_Etype (N, Etype (R));
4546          Resolve (R, Entity (T));
4547       else
4548          Set_Error_Posted (R);
4549          Set_Error_Posted (T);
4550       end if;
4551    end Analyze_Subtype_Indication;
4552
4553    --------------------------
4554    -- Analyze_Variant_Part --
4555    --------------------------
4556
4557    procedure Analyze_Variant_Part (N : Node_Id) is
4558
4559       procedure Non_Static_Choice_Error (Choice : Node_Id);
4560       --  Error routine invoked by the generic instantiation below when the
4561       --  variant part has a non static choice.
4562
4563       procedure Process_Declarations (Variant : Node_Id);
4564       --  Analyzes all the declarations associated with a Variant. Needed by
4565       --  the generic instantiation below.
4566
4567       package Variant_Choices_Processing is new
4568         Generic_Choices_Processing
4569           (Get_Alternatives          => Variants,
4570            Get_Choices               => Discrete_Choices,
4571            Process_Empty_Choice      => No_OP,
4572            Process_Non_Static_Choice => Non_Static_Choice_Error,
4573            Process_Associated_Node   => Process_Declarations);
4574       use Variant_Choices_Processing;
4575       --  Instantiation of the generic choice processing package
4576
4577       -----------------------------
4578       -- Non_Static_Choice_Error --
4579       -----------------------------
4580
4581       procedure Non_Static_Choice_Error (Choice : Node_Id) is
4582       begin
4583          Flag_Non_Static_Expr
4584            ("choice given in variant part is not static!", Choice);
4585       end Non_Static_Choice_Error;
4586
4587       --------------------------
4588       -- Process_Declarations --
4589       --------------------------
4590
4591       procedure Process_Declarations (Variant : Node_Id) is
4592       begin
4593          if not Null_Present (Component_List (Variant)) then
4594             Analyze_Declarations (Component_Items (Component_List (Variant)));
4595
4596             if Present (Variant_Part (Component_List (Variant))) then
4597                Analyze (Variant_Part (Component_List (Variant)));
4598             end if;
4599          end if;
4600       end Process_Declarations;
4601
4602       --  Local Variables
4603
4604       Discr_Name : Node_Id;
4605       Discr_Type : Entity_Id;
4606
4607       Dont_Care      : Boolean;
4608       Others_Present : Boolean := False;
4609
4610       pragma Warnings (Off, Dont_Care);
4611       pragma Warnings (Off, Others_Present);
4612       --  We don't care about the assigned values of any of these
4613
4614    --  Start of processing for Analyze_Variant_Part
4615
4616    begin
4617       Discr_Name := Name (N);
4618       Analyze (Discr_Name);
4619
4620       --  If Discr_Name bad, get out (prevent cascaded errors)
4621
4622       if Etype (Discr_Name) = Any_Type then
4623          return;
4624       end if;
4625
4626       --  Check invalid discriminant in variant part
4627
4628       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4629          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4630       end if;
4631
4632       Discr_Type := Etype (Entity (Discr_Name));
4633
4634       if not Is_Discrete_Type (Discr_Type) then
4635          Error_Msg_N
4636            ("discriminant in a variant part must be of a discrete type",
4637              Name (N));
4638          return;
4639       end if;
4640
4641       --  Call the instantiated Analyze_Choices which does the rest of the work
4642
4643       Analyze_Choices (N, Discr_Type, Dont_Care, Others_Present);
4644    end Analyze_Variant_Part;
4645
4646    ----------------------------
4647    -- Array_Type_Declaration --
4648    ----------------------------
4649
4650    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4651       Component_Def : constant Node_Id := Component_Definition (Def);
4652       Component_Typ : constant Node_Id := Subtype_Indication (Component_Def);
4653       Element_Type  : Entity_Id;
4654       Implicit_Base : Entity_Id;
4655       Index         : Node_Id;
4656       Related_Id    : Entity_Id := Empty;
4657       Nb_Index      : Nat;
4658       P             : constant Node_Id := Parent (Def);
4659       Priv          : Entity_Id;
4660
4661    begin
4662       if Nkind (Def) = N_Constrained_Array_Definition then
4663          Index := First (Discrete_Subtype_Definitions (Def));
4664       else
4665          Index := First (Subtype_Marks (Def));
4666       end if;
4667
4668       --  Find proper names for the implicit types which may be public. In case
4669       --  of anonymous arrays we use the name of the first object of that type
4670       --  as prefix.
4671
4672       if No (T) then
4673          Related_Id := Defining_Identifier (P);
4674       else
4675          Related_Id := T;
4676       end if;
4677
4678       Nb_Index := 1;
4679       while Present (Index) loop
4680          Analyze (Index);
4681
4682          if not Nkind_In (Index, N_Identifier, N_Expanded_Name) then
4683             Check_SPARK_Restriction ("subtype mark required", Index);
4684          end if;
4685
4686          --  Add a subtype declaration for each index of private array type
4687          --  declaration whose etype is also private. For example:
4688
4689          --     package Pkg is
4690          --        type Index is private;
4691          --     private
4692          --        type Table is array (Index) of ...
4693          --     end;
4694
4695          --  This is currently required by the expander for the internally
4696          --  generated equality subprogram of records with variant parts in
4697          --  which the etype of some component is such private type.
4698
4699          if Ekind (Current_Scope) = E_Package
4700            and then In_Private_Part (Current_Scope)
4701            and then Has_Private_Declaration (Etype (Index))
4702          then
4703             declare
4704                Loc   : constant Source_Ptr := Sloc (Def);
4705                New_E : Entity_Id;
4706                Decl  : Entity_Id;
4707
4708             begin
4709                New_E := Make_Temporary (Loc, 'T');
4710                Set_Is_Internal (New_E);
4711
4712                Decl :=
4713                  Make_Subtype_Declaration (Loc,
4714                    Defining_Identifier => New_E,
4715                    Subtype_Indication  =>
4716                      New_Occurrence_Of (Etype (Index), Loc));
4717
4718                Insert_Before (Parent (Def), Decl);
4719                Analyze (Decl);
4720                Set_Etype (Index, New_E);
4721
4722                --  If the index is a range the Entity attribute is not
4723                --  available. Example:
4724
4725                --     package Pkg is
4726                --        type T is private;
4727                --     private
4728                --        type T is new Natural;
4729                --        Table : array (T(1) .. T(10)) of Boolean;
4730                --     end Pkg;
4731
4732                if Nkind (Index) /= N_Range then
4733                   Set_Entity (Index, New_E);
4734                end if;
4735             end;
4736          end if;
4737
4738          Make_Index (Index, P, Related_Id, Nb_Index);
4739
4740          --  Check error of subtype with predicate for index type
4741
4742          Bad_Predicated_Subtype_Use
4743            ("subtype& has predicate, not allowed as index subtype",
4744             Index, Etype (Index));
4745
4746          --  Move to next index
4747
4748          Next_Index (Index);
4749          Nb_Index := Nb_Index + 1;
4750       end loop;
4751
4752       --  Process subtype indication if one is present
4753
4754       if Present (Component_Typ) then
4755          Element_Type := Process_Subtype (Component_Typ, P, Related_Id, 'C');
4756
4757          if not Nkind_In (Component_Typ, N_Identifier, N_Expanded_Name) then
4758             Check_SPARK_Restriction ("subtype mark required", Component_Typ);
4759          end if;
4760
4761       --  Ada 2005 (AI-230): Access Definition case
4762
4763       else pragma Assert (Present (Access_Definition (Component_Def)));
4764
4765          --  Indicate that the anonymous access type is created by the
4766          --  array type declaration.
4767
4768          Element_Type := Access_Definition
4769                            (Related_Nod => P,
4770                             N           => Access_Definition (Component_Def));
4771          Set_Is_Local_Anonymous_Access (Element_Type);
4772
4773          --  Propagate the parent. This field is needed if we have to generate
4774          --  the master_id associated with an anonymous access to task type
4775          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4776
4777          Set_Parent (Element_Type, Parent (T));
4778
4779          --  Ada 2005 (AI-230): In case of components that are anonymous access
4780          --  types the level of accessibility depends on the enclosing type
4781          --  declaration
4782
4783          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4784
4785          --  Ada 2005 (AI-254)
4786
4787          declare
4788             CD : constant Node_Id :=
4789                    Access_To_Subprogram_Definition
4790                      (Access_Definition (Component_Def));
4791          begin
4792             if Present (CD) and then Protected_Present (CD) then
4793                Element_Type :=
4794                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4795             end if;
4796          end;
4797       end if;
4798
4799       --  Constrained array case
4800
4801       if No (T) then
4802          T := Create_Itype (E_Void, P, Related_Id, 'T');
4803       end if;
4804
4805       if Nkind (Def) = N_Constrained_Array_Definition then
4806
4807          --  Establish Implicit_Base as unconstrained base type
4808
4809          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4810
4811          Set_Etype              (Implicit_Base, Implicit_Base);
4812          Set_Scope              (Implicit_Base, Current_Scope);
4813          Set_Has_Delayed_Freeze (Implicit_Base);
4814
4815          --  The constrained array type is a subtype of the unconstrained one
4816
4817          Set_Ekind          (T, E_Array_Subtype);
4818          Init_Size_Align    (T);
4819          Set_Etype          (T, Implicit_Base);
4820          Set_Scope          (T, Current_Scope);
4821          Set_Is_Constrained (T, True);
4822          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4823          Set_Has_Delayed_Freeze (T);
4824
4825          --  Complete setup of implicit base type
4826
4827          Set_First_Index       (Implicit_Base, First_Index (T));
4828          Set_Component_Type    (Implicit_Base, Element_Type);
4829          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4830          Set_Component_Size    (Implicit_Base, Uint_0);
4831          Set_Packed_Array_Type (Implicit_Base, Empty);
4832          Set_Has_Controlled_Component
4833                                (Implicit_Base, Has_Controlled_Component
4834                                                         (Element_Type)
4835                                                  or else Is_Controlled
4836                                                         (Element_Type));
4837          Set_Finalize_Storage_Only
4838                                (Implicit_Base, Finalize_Storage_Only
4839                                                         (Element_Type));
4840
4841       --  Unconstrained array case
4842
4843       else
4844          Set_Ekind                    (T, E_Array_Type);
4845          Init_Size_Align              (T);
4846          Set_Etype                    (T, T);
4847          Set_Scope                    (T, Current_Scope);
4848          Set_Component_Size           (T, Uint_0);
4849          Set_Is_Constrained           (T, False);
4850          Set_First_Index              (T, First (Subtype_Marks (Def)));
4851          Set_Has_Delayed_Freeze       (T, True);
4852          Set_Has_Task                 (T, Has_Task      (Element_Type));
4853          Set_Has_Controlled_Component (T, Has_Controlled_Component
4854                                                         (Element_Type)
4855                                             or else
4856                                           Is_Controlled (Element_Type));
4857          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4858                                                         (Element_Type));
4859       end if;
4860
4861       --  Common attributes for both cases
4862
4863       Set_Component_Type (Base_Type (T), Element_Type);
4864       Set_Packed_Array_Type (T, Empty);
4865
4866       if Aliased_Present (Component_Definition (Def)) then
4867          Check_SPARK_Restriction
4868            ("aliased is not allowed", Component_Definition (Def));
4869          Set_Has_Aliased_Components (Etype (T));
4870       end if;
4871
4872       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4873       --  array type to ensure that objects of this type are initialized.
4874
4875       if Ada_Version >= Ada_2005
4876         and then Can_Never_Be_Null (Element_Type)
4877       then
4878          Set_Can_Never_Be_Null (T);
4879
4880          if Null_Exclusion_Present (Component_Definition (Def))
4881
4882             --  No need to check itypes because in their case this check was
4883             --  done at their point of creation
4884
4885            and then not Is_Itype (Element_Type)
4886          then
4887             Error_Msg_N
4888               ("`NOT NULL` not allowed (null already excluded)",
4889                Subtype_Indication (Component_Definition (Def)));
4890          end if;
4891       end if;
4892
4893       Priv := Private_Component (Element_Type);
4894
4895       if Present (Priv) then
4896
4897          --  Check for circular definitions
4898
4899          if Priv = Any_Type then
4900             Set_Component_Type (Etype (T), Any_Type);
4901
4902          --  There is a gap in the visibility of operations on the composite
4903          --  type only if the component type is defined in a different scope.
4904
4905          elsif Scope (Priv) = Current_Scope then
4906             null;
4907
4908          elsif Is_Limited_Type (Priv) then
4909             Set_Is_Limited_Composite (Etype (T));
4910             Set_Is_Limited_Composite (T);
4911          else
4912             Set_Is_Private_Composite (Etype (T));
4913             Set_Is_Private_Composite (T);
4914          end if;
4915       end if;
4916
4917       --  A syntax error in the declaration itself may lead to an empty index
4918       --  list, in which case do a minimal patch.
4919
4920       if No (First_Index (T)) then
4921          Error_Msg_N ("missing index definition in array type declaration", T);
4922
4923          declare
4924             Indexes : constant List_Id :=
4925                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4926          begin
4927             Set_Discrete_Subtype_Definitions (Def, Indexes);
4928             Set_First_Index (T, First (Indexes));
4929             return;
4930          end;
4931       end if;
4932
4933       --  Create a concatenation operator for the new type. Internal array
4934       --  types created for packed entities do not need such, they are
4935       --  compatible with the user-defined type.
4936
4937       if Number_Dimensions (T) = 1
4938          and then not Is_Packed_Array_Type (T)
4939       then
4940          New_Concatenation_Op (T);
4941       end if;
4942
4943       --  In the case of an unconstrained array the parser has already verified
4944       --  that all the indexes are unconstrained but we still need to make sure
4945       --  that the element type is constrained.
4946
4947       if Is_Indefinite_Subtype (Element_Type) then
4948          Error_Msg_N
4949            ("unconstrained element type in array declaration",
4950             Subtype_Indication (Component_Def));
4951
4952       elsif Is_Abstract_Type (Element_Type) then
4953          Error_Msg_N
4954            ("the type of a component cannot be abstract",
4955             Subtype_Indication (Component_Def));
4956       end if;
4957    end Array_Type_Declaration;
4958
4959    ------------------------------------------------------
4960    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4961    ------------------------------------------------------
4962
4963    function Replace_Anonymous_Access_To_Protected_Subprogram
4964      (N : Node_Id) return Entity_Id
4965    is
4966       Loc : constant Source_Ptr := Sloc (N);
4967
4968       Curr_Scope : constant Scope_Stack_Entry :=
4969                      Scope_Stack.Table (Scope_Stack.Last);
4970
4971       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
4972       Acc  : Node_Id;
4973       Comp : Node_Id;
4974       Decl : Node_Id;
4975       P    : Node_Id;
4976
4977    begin
4978       Set_Is_Internal (Anon);
4979
4980       case Nkind (N) is
4981          when N_Component_Declaration       |
4982            N_Unconstrained_Array_Definition |
4983            N_Constrained_Array_Definition   =>
4984             Comp := Component_Definition (N);
4985             Acc  := Access_Definition (Comp);
4986
4987          when N_Discriminant_Specification =>
4988             Comp := Discriminant_Type (N);
4989             Acc  := Comp;
4990
4991          when N_Parameter_Specification =>
4992             Comp := Parameter_Type (N);
4993             Acc  := Comp;
4994
4995          when N_Access_Function_Definition  =>
4996             Comp := Result_Definition (N);
4997             Acc  := Comp;
4998
4999          when N_Object_Declaration  =>
5000             Comp := Object_Definition (N);
5001             Acc  := Comp;
5002
5003          when N_Function_Specification =>
5004             Comp := Result_Definition (N);
5005             Acc  := Comp;
5006
5007          when others =>
5008             raise Program_Error;
5009       end case;
5010
5011       Decl := Make_Full_Type_Declaration (Loc,
5012                 Defining_Identifier => Anon,
5013                 Type_Definition   =>
5014                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
5015
5016       Mark_Rewrite_Insertion (Decl);
5017
5018       --  Insert the new declaration in the nearest enclosing scope. If the
5019       --  node is a body and N is its return type, the declaration belongs in
5020       --  the enclosing scope.
5021
5022       P := Parent (N);
5023
5024       if Nkind (P) = N_Subprogram_Body
5025         and then Nkind (N) = N_Function_Specification
5026       then
5027          P := Parent (P);
5028       end if;
5029
5030       while Present (P) and then not Has_Declarations (P) loop
5031          P := Parent (P);
5032       end loop;
5033
5034       pragma Assert (Present (P));
5035
5036       if Nkind (P) = N_Package_Specification then
5037          Prepend (Decl, Visible_Declarations (P));
5038       else
5039          Prepend (Decl, Declarations (P));
5040       end if;
5041
5042       --  Replace the anonymous type with an occurrence of the new declaration.
5043       --  In all cases the rewritten node does not have the null-exclusion
5044       --  attribute because (if present) it was already inherited by the
5045       --  anonymous entity (Anon). Thus, in case of components we do not
5046       --  inherit this attribute.
5047
5048       if Nkind (N) = N_Parameter_Specification then
5049          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5050          Set_Etype (Defining_Identifier (N), Anon);
5051          Set_Null_Exclusion_Present (N, False);
5052
5053       elsif Nkind (N) = N_Object_Declaration then
5054          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5055          Set_Etype (Defining_Identifier (N), Anon);
5056
5057       elsif Nkind (N) = N_Access_Function_Definition then
5058          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5059
5060       elsif Nkind (N) = N_Function_Specification then
5061          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
5062          Set_Etype (Defining_Unit_Name (N), Anon);
5063
5064       else
5065          Rewrite (Comp,
5066            Make_Component_Definition (Loc,
5067              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
5068       end if;
5069
5070       Mark_Rewrite_Insertion (Comp);
5071
5072       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
5073          Analyze (Decl);
5074
5075       else
5076          --  Temporarily remove the current scope (record or subprogram) from
5077          --  the stack to add the new declarations to the enclosing scope.
5078
5079          Scope_Stack.Decrement_Last;
5080          Analyze (Decl);
5081          Set_Is_Itype (Anon);
5082          Scope_Stack.Append (Curr_Scope);
5083       end if;
5084
5085       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
5086       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
5087       return Anon;
5088    end Replace_Anonymous_Access_To_Protected_Subprogram;
5089
5090    -------------------------------
5091    -- Build_Derived_Access_Type --
5092    -------------------------------
5093
5094    procedure Build_Derived_Access_Type
5095      (N            : Node_Id;
5096       Parent_Type  : Entity_Id;
5097       Derived_Type : Entity_Id)
5098    is
5099       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
5100
5101       Desig_Type      : Entity_Id;
5102       Discr           : Entity_Id;
5103       Discr_Con_Elist : Elist_Id;
5104       Discr_Con_El    : Elmt_Id;
5105       Subt            : Entity_Id;
5106
5107    begin
5108       --  Set the designated type so it is available in case this is an access
5109       --  to a self-referential type, e.g. a standard list type with a next
5110       --  pointer. Will be reset after subtype is built.
5111
5112       Set_Directly_Designated_Type
5113         (Derived_Type, Designated_Type (Parent_Type));
5114
5115       Subt := Process_Subtype (S, N);
5116
5117       if Nkind (S) /= N_Subtype_Indication
5118         and then Subt /= Base_Type (Subt)
5119       then
5120          Set_Ekind (Derived_Type, E_Access_Subtype);
5121       end if;
5122
5123       if Ekind (Derived_Type) = E_Access_Subtype then
5124          declare
5125             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
5126             Ibase      : constant Entity_Id :=
5127                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
5128             Svg_Chars  : constant Name_Id   := Chars (Ibase);
5129             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
5130
5131          begin
5132             Copy_Node (Pbase, Ibase);
5133
5134             Set_Chars             (Ibase, Svg_Chars);
5135             Set_Next_Entity       (Ibase, Svg_Next_E);
5136             Set_Sloc              (Ibase, Sloc (Derived_Type));
5137             Set_Scope             (Ibase, Scope (Derived_Type));
5138             Set_Freeze_Node       (Ibase, Empty);
5139             Set_Is_Frozen         (Ibase, False);
5140             Set_Comes_From_Source (Ibase, False);
5141             Set_Is_First_Subtype  (Ibase, False);
5142
5143             Set_Etype (Ibase, Pbase);
5144             Set_Etype (Derived_Type, Ibase);
5145          end;
5146       end if;
5147
5148       Set_Directly_Designated_Type
5149         (Derived_Type, Designated_Type (Subt));
5150
5151       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
5152       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
5153       Set_Size_Info          (Derived_Type,                     Parent_Type);
5154       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
5155       Set_Depends_On_Private (Derived_Type,
5156                               Has_Private_Component (Derived_Type));
5157       Conditional_Delay      (Derived_Type, Subt);
5158
5159       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
5160       --  that it is not redundant.
5161
5162       if Null_Exclusion_Present (Type_Definition (N)) then
5163          Set_Can_Never_Be_Null (Derived_Type);
5164
5165          if Can_Never_Be_Null (Parent_Type)
5166            and then False
5167          then
5168             Error_Msg_NE
5169               ("`NOT NULL` not allowed (& already excludes null)",
5170                 N, Parent_Type);
5171          end if;
5172
5173       elsif Can_Never_Be_Null (Parent_Type) then
5174          Set_Can_Never_Be_Null (Derived_Type);
5175       end if;
5176
5177       --  Note: we do not copy the Storage_Size_Variable, since we always go to
5178       --  the root type for this information.
5179
5180       --  Apply range checks to discriminants for derived record case
5181       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
5182
5183       Desig_Type := Designated_Type (Derived_Type);
5184       if Is_Composite_Type (Desig_Type)
5185         and then (not Is_Array_Type (Desig_Type))
5186         and then Has_Discriminants (Desig_Type)
5187         and then Base_Type (Desig_Type) /= Desig_Type
5188       then
5189          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
5190          Discr_Con_El := First_Elmt (Discr_Con_Elist);
5191
5192          Discr := First_Discriminant (Base_Type (Desig_Type));
5193          while Present (Discr_Con_El) loop
5194             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
5195             Next_Elmt (Discr_Con_El);
5196             Next_Discriminant (Discr);
5197          end loop;
5198       end if;
5199    end Build_Derived_Access_Type;
5200
5201    ------------------------------
5202    -- Build_Derived_Array_Type --
5203    ------------------------------
5204
5205    procedure Build_Derived_Array_Type
5206      (N            : Node_Id;
5207       Parent_Type  : Entity_Id;
5208       Derived_Type : Entity_Id)
5209    is
5210       Loc           : constant Source_Ptr := Sloc (N);
5211       Tdef          : constant Node_Id    := Type_Definition (N);
5212       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5213       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5214       Implicit_Base : Entity_Id;
5215       New_Indic     : Node_Id;
5216
5217       procedure Make_Implicit_Base;
5218       --  If the parent subtype is constrained, the derived type is a subtype
5219       --  of an implicit base type derived from the parent base.
5220
5221       ------------------------
5222       -- Make_Implicit_Base --
5223       ------------------------
5224
5225       procedure Make_Implicit_Base is
5226       begin
5227          Implicit_Base :=
5228            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5229
5230          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
5231          Set_Etype (Implicit_Base, Parent_Base);
5232
5233          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
5234          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
5235
5236          Set_Has_Delayed_Freeze (Implicit_Base, True);
5237       end Make_Implicit_Base;
5238
5239    --  Start of processing for Build_Derived_Array_Type
5240
5241    begin
5242       if not Is_Constrained (Parent_Type) then
5243          if Nkind (Indic) /= N_Subtype_Indication then
5244             Set_Ekind (Derived_Type, E_Array_Type);
5245
5246             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
5247             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
5248
5249             Set_Has_Delayed_Freeze (Derived_Type, True);
5250
5251          else
5252             Make_Implicit_Base;
5253             Set_Etype (Derived_Type, Implicit_Base);
5254
5255             New_Indic :=
5256               Make_Subtype_Declaration (Loc,
5257                 Defining_Identifier => Derived_Type,
5258                 Subtype_Indication  =>
5259                   Make_Subtype_Indication (Loc,
5260                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
5261                     Constraint => Constraint (Indic)));
5262
5263             Rewrite (N, New_Indic);
5264             Analyze (N);
5265          end if;
5266
5267       else
5268          if Nkind (Indic) /= N_Subtype_Indication then
5269             Make_Implicit_Base;
5270
5271             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
5272             Set_Etype             (Derived_Type, Implicit_Base);
5273             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
5274
5275          else
5276             Error_Msg_N ("illegal constraint on constrained type", Indic);
5277          end if;
5278       end if;
5279
5280       --  If parent type is not a derived type itself, and is declared in
5281       --  closed scope (e.g. a subprogram), then we must explicitly introduce
5282       --  the new type's concatenation operator since Derive_Subprograms
5283       --  will not inherit the parent's operator. If the parent type is
5284       --  unconstrained, the operator is of the unconstrained base type.
5285
5286       if Number_Dimensions (Parent_Type) = 1
5287         and then not Is_Limited_Type (Parent_Type)
5288         and then not Is_Derived_Type (Parent_Type)
5289         and then not Is_Package_Or_Generic_Package
5290                        (Scope (Base_Type (Parent_Type)))
5291       then
5292          if not Is_Constrained (Parent_Type)
5293            and then Is_Constrained (Derived_Type)
5294          then
5295             New_Concatenation_Op (Implicit_Base);
5296          else
5297             New_Concatenation_Op (Derived_Type);
5298          end if;
5299       end if;
5300    end Build_Derived_Array_Type;
5301
5302    -----------------------------------
5303    -- Build_Derived_Concurrent_Type --
5304    -----------------------------------
5305
5306    procedure Build_Derived_Concurrent_Type
5307      (N            : Node_Id;
5308       Parent_Type  : Entity_Id;
5309       Derived_Type : Entity_Id)
5310    is
5311       Loc : constant Source_Ptr := Sloc (N);
5312
5313       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
5314       Corr_Decl        : Node_Id;
5315       Corr_Decl_Needed : Boolean;
5316       --  If the derived type has fewer discriminants than its parent, the
5317       --  corresponding record is also a derived type, in order to account for
5318       --  the bound discriminants. We create a full type declaration for it in
5319       --  this case.
5320
5321       Constraint_Present : constant Boolean :=
5322                              Nkind (Subtype_Indication (Type_Definition (N))) =
5323                                                           N_Subtype_Indication;
5324
5325       D_Constraint   : Node_Id;
5326       New_Constraint : Elist_Id;
5327       Old_Disc       : Entity_Id;
5328       New_Disc       : Entity_Id;
5329       New_N          : Node_Id;
5330
5331    begin
5332       Set_Stored_Constraint (Derived_Type, No_Elist);
5333       Corr_Decl_Needed := False;
5334       Old_Disc := Empty;
5335
5336       if Present (Discriminant_Specifications (N))
5337         and then Constraint_Present
5338       then
5339          Old_Disc := First_Discriminant (Parent_Type);
5340          New_Disc := First (Discriminant_Specifications (N));
5341          while Present (New_Disc) and then Present (Old_Disc) loop
5342             Next_Discriminant (Old_Disc);
5343             Next (New_Disc);
5344          end loop;
5345       end if;
5346
5347       if Present (Old_Disc) and then Expander_Active then
5348
5349          --  The new type has fewer discriminants, so we need to create a new
5350          --  corresponding record, which is derived from the corresponding
5351          --  record of the parent, and has a stored constraint that captures
5352          --  the values of the discriminant constraints. The corresponding
5353          --  record is needed only if expander is active and code generation is
5354          --  enabled.
5355
5356          --  The type declaration for the derived corresponding record has the
5357          --  same discriminant part and constraints as the current declaration.
5358          --  Copy the unanalyzed tree to build declaration.
5359
5360          Corr_Decl_Needed := True;
5361          New_N := Copy_Separate_Tree (N);
5362
5363          Corr_Decl :=
5364            Make_Full_Type_Declaration (Loc,
5365              Defining_Identifier         => Corr_Record,
5366              Discriminant_Specifications =>
5367                 Discriminant_Specifications (New_N),
5368              Type_Definition             =>
5369                Make_Derived_Type_Definition (Loc,
5370                  Subtype_Indication =>
5371                    Make_Subtype_Indication (Loc,
5372                      Subtype_Mark =>
5373                         New_Occurrence_Of
5374                           (Corresponding_Record_Type (Parent_Type), Loc),
5375                      Constraint   =>
5376                        Constraint
5377                          (Subtype_Indication (Type_Definition (New_N))))));
5378       end if;
5379
5380       --  Copy Storage_Size and Relative_Deadline variables if task case
5381
5382       if Is_Task_Type (Parent_Type) then
5383          Set_Storage_Size_Variable (Derived_Type,
5384            Storage_Size_Variable (Parent_Type));
5385          Set_Relative_Deadline_Variable (Derived_Type,
5386            Relative_Deadline_Variable (Parent_Type));
5387       end if;
5388
5389       if Present (Discriminant_Specifications (N)) then
5390          Push_Scope (Derived_Type);
5391          Check_Or_Process_Discriminants (N, Derived_Type);
5392
5393          if Constraint_Present then
5394             New_Constraint :=
5395               Expand_To_Stored_Constraint
5396                 (Parent_Type,
5397                  Build_Discriminant_Constraints
5398                    (Parent_Type,
5399                     Subtype_Indication (Type_Definition (N)), True));
5400          end if;
5401
5402          End_Scope;
5403
5404       elsif Constraint_Present then
5405
5406          --  Build constrained subtype and derive from it
5407
5408          declare
5409             Loc  : constant Source_Ptr := Sloc (N);
5410             Anon : constant Entity_Id :=
5411                      Make_Defining_Identifier (Loc,
5412                        Chars => New_External_Name (Chars (Derived_Type), 'T'));
5413             Decl : Node_Id;
5414
5415          begin
5416             Decl :=
5417               Make_Subtype_Declaration (Loc,
5418                 Defining_Identifier => Anon,
5419                 Subtype_Indication =>
5420                   Subtype_Indication (Type_Definition (N)));
5421             Insert_Before (N, Decl);
5422             Analyze (Decl);
5423
5424             Rewrite (Subtype_Indication (Type_Definition (N)),
5425               New_Occurrence_Of (Anon, Loc));
5426             Set_Analyzed (Derived_Type, False);
5427             Analyze (N);
5428             return;
5429          end;
5430       end if;
5431
5432       --  By default, operations and private data are inherited from parent.
5433       --  However, in the presence of bound discriminants, a new corresponding
5434       --  record will be created, see below.
5435
5436       Set_Has_Discriminants
5437         (Derived_Type, Has_Discriminants         (Parent_Type));
5438       Set_Corresponding_Record_Type
5439         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5440
5441       --  Is_Constrained is set according the parent subtype, but is set to
5442       --  False if the derived type is declared with new discriminants.
5443
5444       Set_Is_Constrained
5445         (Derived_Type,
5446          (Is_Constrained (Parent_Type) or else Constraint_Present)
5447            and then not Present (Discriminant_Specifications (N)));
5448
5449       if Constraint_Present then
5450          if not Has_Discriminants (Parent_Type) then
5451             Error_Msg_N ("untagged parent must have discriminants", N);
5452
5453          elsif Present (Discriminant_Specifications (N)) then
5454
5455             --  Verify that new discriminants are used to constrain old ones
5456
5457             D_Constraint :=
5458               First
5459                 (Constraints
5460                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5461
5462             Old_Disc := First_Discriminant (Parent_Type);
5463
5464             while Present (D_Constraint) loop
5465                if Nkind (D_Constraint) /= N_Discriminant_Association then
5466
5467                   --  Positional constraint. If it is a reference to a new
5468                   --  discriminant, it constrains the corresponding old one.
5469
5470                   if Nkind (D_Constraint) = N_Identifier then
5471                      New_Disc := First_Discriminant (Derived_Type);
5472                      while Present (New_Disc) loop
5473                         exit when Chars (New_Disc) = Chars (D_Constraint);
5474                         Next_Discriminant (New_Disc);
5475                      end loop;
5476
5477                      if Present (New_Disc) then
5478                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5479                      end if;
5480                   end if;
5481
5482                   Next_Discriminant (Old_Disc);
5483
5484                   --  if this is a named constraint, search by name for the old
5485                   --  discriminants constrained by the new one.
5486
5487                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5488
5489                   --  Find new discriminant with that name
5490
5491                   New_Disc := First_Discriminant (Derived_Type);
5492                   while Present (New_Disc) loop
5493                      exit when
5494                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5495                      Next_Discriminant (New_Disc);
5496                   end loop;
5497
5498                   if Present (New_Disc) then
5499
5500                      --  Verify that new discriminant renames some discriminant
5501                      --  of the parent type, and associate the new discriminant
5502                      --  with one or more old ones that it renames.
5503
5504                      declare
5505                         Selector : Node_Id;
5506
5507                      begin
5508                         Selector := First (Selector_Names (D_Constraint));
5509                         while Present (Selector) loop
5510                            Old_Disc := First_Discriminant (Parent_Type);
5511                            while Present (Old_Disc) loop
5512                               exit when Chars (Old_Disc) = Chars (Selector);
5513                               Next_Discriminant (Old_Disc);
5514                            end loop;
5515
5516                            if Present (Old_Disc) then
5517                               Set_Corresponding_Discriminant
5518                                 (New_Disc, Old_Disc);
5519                            end if;
5520
5521                            Next (Selector);
5522                         end loop;
5523                      end;
5524                   end if;
5525                end if;
5526
5527                Next (D_Constraint);
5528             end loop;
5529
5530             New_Disc := First_Discriminant (Derived_Type);
5531             while Present (New_Disc) loop
5532                if No (Corresponding_Discriminant (New_Disc)) then
5533                   Error_Msg_NE
5534                     ("new discriminant& must constrain old one", N, New_Disc);
5535
5536                elsif not
5537                  Subtypes_Statically_Compatible
5538                    (Etype (New_Disc),
5539                     Etype (Corresponding_Discriminant (New_Disc)))
5540                then
5541                   Error_Msg_NE
5542                     ("& not statically compatible with parent discriminant",
5543                       N, New_Disc);
5544                end if;
5545
5546                Next_Discriminant (New_Disc);
5547             end loop;
5548          end if;
5549
5550       elsif Present (Discriminant_Specifications (N)) then
5551          Error_Msg_N
5552            ("missing discriminant constraint in untagged derivation", N);
5553       end if;
5554
5555       --  The entity chain of the derived type includes the new discriminants
5556       --  but shares operations with the parent.
5557
5558       if Present (Discriminant_Specifications (N)) then
5559          Old_Disc := First_Discriminant (Parent_Type);
5560          while Present (Old_Disc) loop
5561             if No (Next_Entity (Old_Disc))
5562               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5563             then
5564                Set_Next_Entity
5565                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5566                exit;
5567             end if;
5568
5569             Next_Discriminant (Old_Disc);
5570          end loop;
5571
5572       else
5573          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5574          if Has_Discriminants (Parent_Type) then
5575             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5576             Set_Discriminant_Constraint (
5577               Derived_Type, Discriminant_Constraint (Parent_Type));
5578          end if;
5579       end if;
5580
5581       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5582
5583       Set_Has_Completion (Derived_Type);
5584
5585       if Corr_Decl_Needed then
5586          Set_Stored_Constraint (Derived_Type, New_Constraint);
5587          Insert_After (N, Corr_Decl);
5588          Analyze (Corr_Decl);
5589          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5590       end if;
5591    end Build_Derived_Concurrent_Type;
5592
5593    ------------------------------------
5594    -- Build_Derived_Enumeration_Type --
5595    ------------------------------------
5596
5597    procedure Build_Derived_Enumeration_Type
5598      (N            : Node_Id;
5599       Parent_Type  : Entity_Id;
5600       Derived_Type : Entity_Id)
5601    is
5602       Loc           : constant Source_Ptr := Sloc (N);
5603       Def           : constant Node_Id    := Type_Definition (N);
5604       Indic         : constant Node_Id    := Subtype_Indication (Def);
5605       Implicit_Base : Entity_Id;
5606       Literal       : Entity_Id;
5607       New_Lit       : Entity_Id;
5608       Literals_List : List_Id;
5609       Type_Decl     : Node_Id;
5610       Hi, Lo        : Node_Id;
5611       Rang_Expr     : Node_Id;
5612
5613    begin
5614       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5615       --  not have explicit literals lists we need to process types derived
5616       --  from them specially. This is handled by Derived_Standard_Character.
5617       --  If the parent type is a generic type, there are no literals either,
5618       --  and we construct the same skeletal representation as for the generic
5619       --  parent type.
5620
5621       if Is_Standard_Character_Type (Parent_Type) then
5622          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5623
5624       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5625          declare
5626             Lo : Node_Id;
5627             Hi : Node_Id;
5628
5629          begin
5630             if Nkind (Indic) /= N_Subtype_Indication then
5631                Lo :=
5632                   Make_Attribute_Reference (Loc,
5633                     Attribute_Name => Name_First,
5634                     Prefix         => New_Reference_To (Derived_Type, Loc));
5635                Set_Etype (Lo, Derived_Type);
5636
5637                Hi :=
5638                   Make_Attribute_Reference (Loc,
5639                     Attribute_Name => Name_Last,
5640                     Prefix         => New_Reference_To (Derived_Type, Loc));
5641                Set_Etype (Hi, Derived_Type);
5642
5643                Set_Scalar_Range (Derived_Type,
5644                   Make_Range (Loc,
5645                     Low_Bound  => Lo,
5646                     High_Bound => Hi));
5647             else
5648
5649                --   Analyze subtype indication and verify compatibility
5650                --   with parent type.
5651
5652                if Base_Type (Process_Subtype (Indic, N)) /=
5653                   Base_Type (Parent_Type)
5654                then
5655                   Error_Msg_N
5656                     ("illegal constraint for formal discrete type", N);
5657                end if;
5658             end if;
5659          end;
5660
5661       else
5662          --  If a constraint is present, analyze the bounds to catch
5663          --  premature usage of the derived literals.
5664
5665          if Nkind (Indic) = N_Subtype_Indication
5666            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5667          then
5668             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5669             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5670          end if;
5671
5672          --  Introduce an implicit base type for the derived type even if there
5673          --  is no constraint attached to it, since this seems closer to the
5674          --  Ada semantics. Build a full type declaration tree for the derived
5675          --  type using the implicit base type as the defining identifier. The
5676          --  build a subtype declaration tree which applies the constraint (if
5677          --  any) have it replace the derived type declaration.
5678
5679          Literal := First_Literal (Parent_Type);
5680          Literals_List := New_List;
5681          while Present (Literal)
5682            and then Ekind (Literal) = E_Enumeration_Literal
5683          loop
5684             --  Literals of the derived type have the same representation as
5685             --  those of the parent type, but this representation can be
5686             --  overridden by an explicit representation clause. Indicate
5687             --  that there is no explicit representation given yet. These
5688             --  derived literals are implicit operations of the new type,
5689             --  and can be overridden by explicit ones.
5690
5691             if Nkind (Literal) = N_Defining_Character_Literal then
5692                New_Lit :=
5693                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5694             else
5695                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5696             end if;
5697
5698             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5699             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5700             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5701             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5702             Set_Alias                (New_Lit, Literal);
5703             Set_Is_Known_Valid       (New_Lit, True);
5704
5705             Append (New_Lit, Literals_List);
5706             Next_Literal (Literal);
5707          end loop;
5708
5709          Implicit_Base :=
5710            Make_Defining_Identifier (Sloc (Derived_Type),
5711              Chars => New_External_Name (Chars (Derived_Type), 'B'));
5712
5713          --  Indicate the proper nature of the derived type. This must be done
5714          --  before analysis of the literals, to recognize cases when a literal
5715          --  may be hidden by a previous explicit function definition (cf.
5716          --  c83031a).
5717
5718          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5719          Set_Etype (Derived_Type, Implicit_Base);
5720
5721          Type_Decl :=
5722            Make_Full_Type_Declaration (Loc,
5723              Defining_Identifier => Implicit_Base,
5724              Discriminant_Specifications => No_List,
5725              Type_Definition =>
5726                Make_Enumeration_Type_Definition (Loc, Literals_List));
5727
5728          Mark_Rewrite_Insertion (Type_Decl);
5729          Insert_Before (N, Type_Decl);
5730          Analyze (Type_Decl);
5731
5732          --  After the implicit base is analyzed its Etype needs to be changed
5733          --  to reflect the fact that it is derived from the parent type which
5734          --  was ignored during analysis. We also set the size at this point.
5735
5736          Set_Etype (Implicit_Base, Parent_Type);
5737
5738          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5739          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5740          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5741
5742          --  Copy other flags from parent type
5743
5744          Set_Has_Non_Standard_Rep
5745                             (Implicit_Base, Has_Non_Standard_Rep
5746                                                            (Parent_Type));
5747          Set_Has_Pragma_Ordered
5748                             (Implicit_Base, Has_Pragma_Ordered
5749                                                            (Parent_Type));
5750          Set_Has_Delayed_Freeze (Implicit_Base);
5751
5752          --  Process the subtype indication including a validation check on the
5753          --  constraint, if any. If a constraint is given, its bounds must be
5754          --  implicitly converted to the new type.
5755
5756          if Nkind (Indic) = N_Subtype_Indication then
5757             declare
5758                R : constant Node_Id :=
5759                      Range_Expression (Constraint (Indic));
5760
5761             begin
5762                if Nkind (R) = N_Range then
5763                   Hi := Build_Scalar_Bound
5764                           (High_Bound (R), Parent_Type, Implicit_Base);
5765                   Lo := Build_Scalar_Bound
5766                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5767
5768                else
5769                   --  Constraint is a Range attribute. Replace with explicit
5770                   --  mention of the bounds of the prefix, which must be a
5771                   --  subtype.
5772
5773                   Analyze (Prefix (R));
5774                   Hi :=
5775                     Convert_To (Implicit_Base,
5776                       Make_Attribute_Reference (Loc,
5777                         Attribute_Name => Name_Last,
5778                         Prefix =>
5779                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5780
5781                   Lo :=
5782                     Convert_To (Implicit_Base,
5783                       Make_Attribute_Reference (Loc,
5784                         Attribute_Name => Name_First,
5785                         Prefix =>
5786                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5787                end if;
5788             end;
5789
5790          else
5791             Hi :=
5792               Build_Scalar_Bound
5793                 (Type_High_Bound (Parent_Type),
5794                  Parent_Type, Implicit_Base);
5795             Lo :=
5796                Build_Scalar_Bound
5797                  (Type_Low_Bound (Parent_Type),
5798                   Parent_Type, Implicit_Base);
5799          end if;
5800
5801          Rang_Expr :=
5802            Make_Range (Loc,
5803              Low_Bound  => Lo,
5804              High_Bound => Hi);
5805
5806          --  If we constructed a default range for the case where no range
5807          --  was given, then the expressions in the range must not freeze
5808          --  since they do not correspond to expressions in the source.
5809
5810          if Nkind (Indic) /= N_Subtype_Indication then
5811             Set_Must_Not_Freeze (Lo);
5812             Set_Must_Not_Freeze (Hi);
5813             Set_Must_Not_Freeze (Rang_Expr);
5814          end if;
5815
5816          Rewrite (N,
5817            Make_Subtype_Declaration (Loc,
5818              Defining_Identifier => Derived_Type,
5819              Subtype_Indication =>
5820                Make_Subtype_Indication (Loc,
5821                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
5822                  Constraint =>
5823                    Make_Range_Constraint (Loc,
5824                      Range_Expression => Rang_Expr))));
5825
5826          Analyze (N);
5827
5828          --  If pragma Discard_Names applies on the first subtype of the parent
5829          --  type, then it must be applied on this subtype as well.
5830
5831          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
5832             Set_Discard_Names (Derived_Type);
5833          end if;
5834
5835          --  Apply a range check. Since this range expression doesn't have an
5836          --  Etype, we have to specifically pass the Source_Typ parameter. Is
5837          --  this right???
5838
5839          if Nkind (Indic) = N_Subtype_Indication then
5840             Apply_Range_Check (Range_Expression (Constraint (Indic)),
5841                                Parent_Type,
5842                                Source_Typ => Entity (Subtype_Mark (Indic)));
5843          end if;
5844       end if;
5845    end Build_Derived_Enumeration_Type;
5846
5847    --------------------------------
5848    -- Build_Derived_Numeric_Type --
5849    --------------------------------
5850
5851    procedure Build_Derived_Numeric_Type
5852      (N            : Node_Id;
5853       Parent_Type  : Entity_Id;
5854       Derived_Type : Entity_Id)
5855    is
5856       Loc           : constant Source_Ptr := Sloc (N);
5857       Tdef          : constant Node_Id    := Type_Definition (N);
5858       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5859       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5860       No_Constraint : constant Boolean    := Nkind (Indic) /=
5861                                                   N_Subtype_Indication;
5862       Implicit_Base : Entity_Id;
5863
5864       Lo : Node_Id;
5865       Hi : Node_Id;
5866
5867    begin
5868       --  Process the subtype indication including a validation check on
5869       --  the constraint if any.
5870
5871       Discard_Node (Process_Subtype (Indic, N));
5872
5873       --  Introduce an implicit base type for the derived type even if there
5874       --  is no constraint attached to it, since this seems closer to the Ada
5875       --  semantics.
5876
5877       Implicit_Base :=
5878         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5879
5880       Set_Etype          (Implicit_Base, Parent_Base);
5881       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
5882       Set_Size_Info      (Implicit_Base,                 Parent_Base);
5883       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
5884       Set_Parent         (Implicit_Base, Parent (Derived_Type));
5885       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
5886
5887       --  Set RM Size for discrete type or decimal fixed-point type
5888       --  Ordinary fixed-point is excluded, why???
5889
5890       if Is_Discrete_Type (Parent_Base)
5891         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
5892       then
5893          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
5894       end if;
5895
5896       Set_Has_Delayed_Freeze (Implicit_Base);
5897
5898       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
5899       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
5900
5901       Set_Scalar_Range (Implicit_Base,
5902         Make_Range (Loc,
5903           Low_Bound  => Lo,
5904           High_Bound => Hi));
5905
5906       if Has_Infinities (Parent_Base) then
5907          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
5908       end if;
5909
5910       --  The Derived_Type, which is the entity of the declaration, is a
5911       --  subtype of the implicit base. Its Ekind is a subtype, even in the
5912       --  absence of an explicit constraint.
5913
5914       Set_Etype (Derived_Type, Implicit_Base);
5915
5916       --  If we did not have a constraint, then the Ekind is set from the
5917       --  parent type (otherwise Process_Subtype has set the bounds)
5918
5919       if No_Constraint then
5920          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
5921       end if;
5922
5923       --  If we did not have a range constraint, then set the range from the
5924       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
5925
5926       if No_Constraint
5927         or else not Has_Range_Constraint (Indic)
5928       then
5929          Set_Scalar_Range (Derived_Type,
5930            Make_Range (Loc,
5931              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
5932              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
5933          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5934
5935          if Has_Infinities (Parent_Type) then
5936             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5937          end if;
5938
5939          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
5940       end if;
5941
5942       Set_Is_Descendent_Of_Address (Derived_Type,
5943         Is_Descendent_Of_Address (Parent_Type));
5944       Set_Is_Descendent_Of_Address (Implicit_Base,
5945         Is_Descendent_Of_Address (Parent_Type));
5946
5947       --  Set remaining type-specific fields, depending on numeric type
5948
5949       if Is_Modular_Integer_Type (Parent_Type) then
5950          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5951
5952          Set_Non_Binary_Modulus
5953            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5954
5955          Set_Is_Known_Valid
5956            (Implicit_Base, Is_Known_Valid (Parent_Base));
5957
5958       elsif Is_Floating_Point_Type (Parent_Type) then
5959
5960          --  Digits of base type is always copied from the digits value of
5961          --  the parent base type, but the digits of the derived type will
5962          --  already have been set if there was a constraint present.
5963
5964          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5965          Set_Float_Rep    (Implicit_Base, Float_Rep    (Parent_Base));
5966
5967          if No_Constraint then
5968             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5969          end if;
5970
5971       elsif Is_Fixed_Point_Type (Parent_Type) then
5972
5973          --  Small of base type and derived type are always copied from the
5974          --  parent base type, since smalls never change. The delta of the
5975          --  base type is also copied from the parent base type. However the
5976          --  delta of the derived type will have been set already if a
5977          --  constraint was present.
5978
5979          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5980          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5981          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5982
5983          if No_Constraint then
5984             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5985          end if;
5986
5987          --  The scale and machine radix in the decimal case are always
5988          --  copied from the parent base type.
5989
5990          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
5991             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
5992             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
5993
5994             Set_Machine_Radix_10
5995               (Derived_Type,  Machine_Radix_10 (Parent_Base));
5996             Set_Machine_Radix_10
5997               (Implicit_Base, Machine_Radix_10 (Parent_Base));
5998
5999             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
6000
6001             if No_Constraint then
6002                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
6003
6004             else
6005                --  the analysis of the subtype_indication sets the
6006                --  digits value of the derived type.
6007
6008                null;
6009             end if;
6010          end if;
6011       end if;
6012
6013       --  The type of the bounds is that of the parent type, and they
6014       --  must be converted to the derived type.
6015
6016       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
6017
6018       --  The implicit_base should be frozen when the derived type is frozen,
6019       --  but note that it is used in the conversions of the bounds. For fixed
6020       --  types we delay the determination of the bounds until the proper
6021       --  freezing point. For other numeric types this is rejected by GCC, for
6022       --  reasons that are currently unclear (???), so we choose to freeze the
6023       --  implicit base now. In the case of integers and floating point types
6024       --  this is harmless because subsequent representation clauses cannot
6025       --  affect anything, but it is still baffling that we cannot use the
6026       --  same mechanism for all derived numeric types.
6027
6028       --  There is a further complication: actually *some* representation
6029       --  clauses can affect the implicit base type. Namely, attribute
6030       --  definition clauses for stream-oriented attributes need to set the
6031       --  corresponding TSS entries on the base type, and this normally cannot
6032       --  be done after the base type is frozen, so the circuitry in
6033       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
6034       --  not use Set_TSS in this case.
6035
6036       if Is_Fixed_Point_Type (Parent_Type) then
6037          Conditional_Delay (Implicit_Base, Parent_Type);
6038       else
6039          Freeze_Before (N, Implicit_Base);
6040       end if;
6041    end Build_Derived_Numeric_Type;
6042
6043    --------------------------------
6044    -- Build_Derived_Private_Type --
6045    --------------------------------
6046
6047    procedure Build_Derived_Private_Type
6048      (N             : Node_Id;
6049       Parent_Type   : Entity_Id;
6050       Derived_Type  : Entity_Id;
6051       Is_Completion : Boolean;
6052       Derive_Subps  : Boolean := True)
6053    is
6054       Loc         : constant Source_Ptr := Sloc (N);
6055       Der_Base    : Entity_Id;
6056       Discr       : Entity_Id;
6057       Full_Decl   : Node_Id := Empty;
6058       Full_Der    : Entity_Id;
6059       Full_P      : Entity_Id;
6060       Last_Discr  : Entity_Id;
6061       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
6062       Swapped     : Boolean := False;
6063
6064       procedure Copy_And_Build;
6065       --  Copy derived type declaration, replace parent with its full view,
6066       --  and analyze new declaration.
6067
6068       --------------------
6069       -- Copy_And_Build --
6070       --------------------
6071
6072       procedure Copy_And_Build is
6073          Full_N : Node_Id;
6074
6075       begin
6076          if Ekind (Parent_Type) in Record_Kind
6077            or else
6078              (Ekind (Parent_Type) in Enumeration_Kind
6079                and then not Is_Standard_Character_Type (Parent_Type)
6080                and then not Is_Generic_Type (Root_Type (Parent_Type)))
6081          then
6082             Full_N := New_Copy_Tree (N);
6083             Insert_After (N, Full_N);
6084             Build_Derived_Type (
6085               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
6086
6087          else
6088             Build_Derived_Type (
6089               N, Parent_Type, Full_Der, True, Derive_Subps => False);
6090          end if;
6091       end Copy_And_Build;
6092
6093    --  Start of processing for Build_Derived_Private_Type
6094
6095    begin
6096       if Is_Tagged_Type (Parent_Type) then
6097          Full_P := Full_View (Parent_Type);
6098
6099          --  A type extension of a type with unknown discriminants is an
6100          --  indefinite type that the back-end cannot handle directly.
6101          --  We treat it as a private type, and build a completion that is
6102          --  derived from the full view of the parent, and hopefully has
6103          --  known discriminants.
6104
6105          --  If the full view of the parent type has an underlying record view,
6106          --  use it to generate the underlying record view of this derived type
6107          --  (required for chains of derivations with unknown discriminants).
6108
6109          --  Minor optimization: we avoid the generation of useless underlying
6110          --  record view entities if the private type declaration has unknown
6111          --  discriminants but its corresponding full view has no
6112          --  discriminants.
6113
6114          if Has_Unknown_Discriminants (Parent_Type)
6115            and then Present (Full_P)
6116            and then (Has_Discriminants (Full_P)
6117                       or else Present (Underlying_Record_View (Full_P)))
6118            and then not In_Open_Scopes (Par_Scope)
6119            and then Expander_Active
6120          then
6121             declare
6122                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
6123                New_Ext  : constant Node_Id :=
6124                             Copy_Separate_Tree
6125                               (Record_Extension_Part (Type_Definition (N)));
6126                Decl     : Node_Id;
6127
6128             begin
6129                Build_Derived_Record_Type
6130                  (N, Parent_Type, Derived_Type, Derive_Subps);
6131
6132                --  Build anonymous completion, as a derivation from the full
6133                --  view of the parent. This is not a completion in the usual
6134                --  sense, because the current type is not private.
6135
6136                Decl :=
6137                  Make_Full_Type_Declaration (Loc,
6138                    Defining_Identifier => Full_Der,
6139                    Type_Definition     =>
6140                      Make_Derived_Type_Definition (Loc,
6141                        Subtype_Indication =>
6142                          New_Copy_Tree
6143                            (Subtype_Indication (Type_Definition (N))),
6144                        Record_Extension_Part => New_Ext));
6145
6146                --  If the parent type has an underlying record view, use it
6147                --  here to build the new underlying record view.
6148
6149                if Present (Underlying_Record_View (Full_P)) then
6150                   pragma Assert
6151                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
6152                        = N_Identifier);
6153                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
6154                     Underlying_Record_View (Full_P));
6155                end if;
6156
6157                Install_Private_Declarations (Par_Scope);
6158                Install_Visible_Declarations (Par_Scope);
6159                Insert_Before (N, Decl);
6160
6161                --  Mark entity as an underlying record view before analysis,
6162                --  to avoid generating the list of its primitive operations
6163                --  (which is not really required for this entity) and thus
6164                --  prevent spurious errors associated with missing overriding
6165                --  of abstract primitives (overridden only for Derived_Type).
6166
6167                Set_Ekind (Full_Der, E_Record_Type);
6168                Set_Is_Underlying_Record_View (Full_Der);
6169
6170                Analyze (Decl);
6171
6172                pragma Assert (Has_Discriminants (Full_Der)
6173                  and then not Has_Unknown_Discriminants (Full_Der));
6174
6175                Uninstall_Declarations (Par_Scope);
6176
6177                --  Freeze the underlying record view, to prevent generation of
6178                --  useless dispatching information, which is simply shared with
6179                --  the real derived type.
6180
6181                Set_Is_Frozen (Full_Der);
6182
6183                --  Set up links between real entity and underlying record view
6184
6185                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
6186                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
6187             end;
6188
6189          --  If discriminants are known, build derived record
6190
6191          else
6192             Build_Derived_Record_Type
6193               (N, Parent_Type, Derived_Type, Derive_Subps);
6194          end if;
6195
6196          return;
6197
6198       elsif Has_Discriminants (Parent_Type) then
6199          if Present (Full_View (Parent_Type)) then
6200             if not Is_Completion then
6201
6202                --  Copy declaration for subsequent analysis, to provide a
6203                --  completion for what is a private declaration. Indicate that
6204                --  the full type is internally generated.
6205
6206                Full_Decl := New_Copy_Tree (N);
6207                Full_Der  := New_Copy (Derived_Type);
6208                Set_Comes_From_Source (Full_Decl, False);
6209                Set_Comes_From_Source (Full_Der, False);
6210                Set_Parent (Full_Der, Full_Decl);
6211
6212                Insert_After (N, Full_Decl);
6213
6214             else
6215                --  If this is a completion, the full view being built is itself
6216                --  private. We build a subtype of the parent with the same
6217                --  constraints as this full view, to convey to the back end the
6218                --  constrained components and the size of this subtype. If the
6219                --  parent is constrained, its full view can serve as the
6220                --  underlying full view of the derived type.
6221
6222                if No (Discriminant_Specifications (N)) then
6223                   if Nkind (Subtype_Indication (Type_Definition (N))) =
6224                                                         N_Subtype_Indication
6225                   then
6226                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
6227
6228                   elsif Is_Constrained (Full_View (Parent_Type)) then
6229                      Set_Underlying_Full_View
6230                        (Derived_Type, Full_View (Parent_Type));
6231                   end if;
6232
6233                else
6234                   --  If there are new discriminants, the parent subtype is
6235                   --  constrained by them, but it is not clear how to build
6236                   --  the Underlying_Full_View in this case???
6237
6238                   null;
6239                end if;
6240             end if;
6241          end if;
6242
6243          --  Build partial view of derived type from partial view of parent
6244
6245          Build_Derived_Record_Type
6246            (N, Parent_Type, Derived_Type, Derive_Subps);
6247
6248          if Present (Full_View (Parent_Type)) and then not Is_Completion then
6249             if not In_Open_Scopes (Par_Scope)
6250               or else not In_Same_Source_Unit (N, Parent_Type)
6251             then
6252                --  Swap partial and full views temporarily
6253
6254                Install_Private_Declarations (Par_Scope);
6255                Install_Visible_Declarations (Par_Scope);
6256                Swapped := True;
6257             end if;
6258
6259             --  Build full view of derived type from full view of parent which
6260             --  is now installed. Subprograms have been derived on the partial
6261             --  view, the completion does not derive them anew.
6262
6263             if not Is_Tagged_Type (Parent_Type) then
6264
6265                --  If the parent is itself derived from another private type,
6266                --  installing the private declarations has not affected its
6267                --  privacy status, so use its own full view explicitly.
6268
6269                if Is_Private_Type (Parent_Type) then
6270                   Build_Derived_Record_Type
6271                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
6272                else
6273                   Build_Derived_Record_Type
6274                     (Full_Decl, Parent_Type, Full_Der, False);
6275                end if;
6276
6277             else
6278                --  If full view of parent is tagged, the completion inherits
6279                --  the proper primitive operations.
6280
6281                Set_Defining_Identifier (Full_Decl, Full_Der);
6282                Build_Derived_Record_Type
6283                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
6284             end if;
6285
6286             --  The full declaration has been introduced into the tree and
6287             --  processed in the step above. It should not be analyzed again
6288             --  (when encountered later in the current list of declarations)
6289             --  to prevent spurious name conflicts. The full entity remains
6290             --  invisible.
6291
6292             Set_Analyzed (Full_Decl);
6293
6294             if Swapped then
6295                Uninstall_Declarations (Par_Scope);
6296
6297                if In_Open_Scopes (Par_Scope) then
6298                   Install_Visible_Declarations (Par_Scope);
6299                end if;
6300             end if;
6301
6302             Der_Base := Base_Type (Derived_Type);
6303             Set_Full_View (Derived_Type, Full_Der);
6304             Set_Full_View (Der_Base, Base_Type (Full_Der));
6305
6306             --  Copy the discriminant list from full view to the partial views
6307             --  (base type and its subtype). Gigi requires that the partial and
6308             --  full views have the same discriminants.
6309
6310             --  Note that since the partial view is pointing to discriminants
6311             --  in the full view, their scope will be that of the full view.
6312             --  This might cause some front end problems and need adjustment???
6313
6314             Discr := First_Discriminant (Base_Type (Full_Der));
6315             Set_First_Entity (Der_Base, Discr);
6316
6317             loop
6318                Last_Discr := Discr;
6319                Next_Discriminant (Discr);
6320                exit when No (Discr);
6321             end loop;
6322
6323             Set_Last_Entity (Der_Base, Last_Discr);
6324
6325             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
6326             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
6327             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
6328
6329          else
6330             --  If this is a completion, the derived type stays private and
6331             --  there is no need to create a further full view, except in the
6332             --  unusual case when the derivation is nested within a child unit,
6333             --  see below.
6334
6335             null;
6336          end if;
6337
6338       elsif Present (Full_View (Parent_Type))
6339         and then  Has_Discriminants (Full_View (Parent_Type))
6340       then
6341          if Has_Unknown_Discriminants (Parent_Type)
6342            and then Nkind (Subtype_Indication (Type_Definition (N))) =
6343                                                          N_Subtype_Indication
6344          then
6345             Error_Msg_N
6346               ("cannot constrain type with unknown discriminants",
6347                Subtype_Indication (Type_Definition (N)));
6348             return;
6349          end if;
6350
6351          --  If full view of parent is a record type, build full view as a
6352          --  derivation from the parent's full view. Partial view remains
6353          --  private. For code generation and linking, the full view must have
6354          --  the same public status as the partial one. This full view is only
6355          --  needed if the parent type is in an enclosing scope, so that the
6356          --  full view may actually become visible, e.g. in a child unit. This
6357          --  is both more efficient, and avoids order of freezing problems with
6358          --  the added entities.
6359
6360          if not Is_Private_Type (Full_View (Parent_Type))
6361            and then (In_Open_Scopes (Scope (Parent_Type)))
6362          then
6363             Full_Der :=
6364               Make_Defining_Identifier
6365                 (Sloc (Derived_Type), Chars (Derived_Type));
6366             Set_Is_Itype (Full_Der);
6367             Set_Has_Private_Declaration (Full_Der);
6368             Set_Has_Private_Declaration (Derived_Type);
6369             Set_Associated_Node_For_Itype (Full_Der, N);
6370             Set_Parent (Full_Der, Parent (Derived_Type));
6371             Set_Full_View (Derived_Type, Full_Der);
6372             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6373             Full_P := Full_View (Parent_Type);
6374             Exchange_Declarations (Parent_Type);
6375             Copy_And_Build;
6376             Exchange_Declarations (Full_P);
6377
6378          else
6379             Build_Derived_Record_Type
6380               (N, Full_View (Parent_Type), Derived_Type,
6381                 Derive_Subps => False);
6382          end if;
6383
6384          --  In any case, the primitive operations are inherited from the
6385          --  parent type, not from the internal full view.
6386
6387          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6388
6389          if Derive_Subps then
6390             Derive_Subprograms (Parent_Type, Derived_Type);
6391          end if;
6392
6393       else
6394          --  Untagged type, No discriminants on either view
6395
6396          if Nkind (Subtype_Indication (Type_Definition (N))) =
6397                                                    N_Subtype_Indication
6398          then
6399             Error_Msg_N
6400               ("illegal constraint on type without discriminants", N);
6401          end if;
6402
6403          if Present (Discriminant_Specifications (N))
6404            and then Present (Full_View (Parent_Type))
6405            and then not Is_Tagged_Type (Full_View (Parent_Type))
6406          then
6407             Error_Msg_N ("cannot add discriminants to untagged type", N);
6408          end if;
6409
6410          Set_Stored_Constraint (Derived_Type, No_Elist);
6411          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6412          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6413          Set_Has_Controlled_Component
6414                                (Derived_Type, Has_Controlled_Component
6415                                                              (Parent_Type));
6416
6417          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6418
6419          if not Is_Controlled  (Parent_Type) then
6420             Set_Finalize_Storage_Only
6421               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6422          end if;
6423
6424          --  Construct the implicit full view by deriving from full view of the
6425          --  parent type. In order to get proper visibility, we install the
6426          --  parent scope and its declarations.
6427
6428          --  ??? If the parent is untagged private and its completion is
6429          --  tagged, this mechanism will not work because we cannot derive from
6430          --  the tagged full view unless we have an extension.
6431
6432          if Present (Full_View (Parent_Type))
6433            and then not Is_Tagged_Type (Full_View (Parent_Type))
6434            and then not Is_Completion
6435          then
6436             Full_Der :=
6437               Make_Defining_Identifier
6438                 (Sloc (Derived_Type), Chars (Derived_Type));
6439             Set_Is_Itype (Full_Der);
6440             Set_Has_Private_Declaration (Full_Der);
6441             Set_Has_Private_Declaration (Derived_Type);
6442             Set_Associated_Node_For_Itype (Full_Der, N);
6443             Set_Parent (Full_Der, Parent (Derived_Type));
6444             Set_Full_View (Derived_Type, Full_Der);
6445
6446             if not In_Open_Scopes (Par_Scope) then
6447                Install_Private_Declarations (Par_Scope);
6448                Install_Visible_Declarations (Par_Scope);
6449                Copy_And_Build;
6450                Uninstall_Declarations (Par_Scope);
6451
6452             --  If parent scope is open and in another unit, and parent has a
6453             --  completion, then the derivation is taking place in the visible
6454             --  part of a child unit. In that case retrieve the full view of
6455             --  the parent momentarily.
6456
6457             elsif not In_Same_Source_Unit (N, Parent_Type) then
6458                Full_P := Full_View (Parent_Type);
6459                Exchange_Declarations (Parent_Type);
6460                Copy_And_Build;
6461                Exchange_Declarations (Full_P);
6462
6463             --  Otherwise it is a local derivation
6464
6465             else
6466                Copy_And_Build;
6467             end if;
6468
6469             Set_Scope                (Full_Der, Current_Scope);
6470             Set_Is_First_Subtype     (Full_Der,
6471                                        Is_First_Subtype (Derived_Type));
6472             Set_Has_Size_Clause      (Full_Der, False);
6473             Set_Has_Alignment_Clause (Full_Der, False);
6474             Set_Next_Entity          (Full_Der, Empty);
6475             Set_Has_Delayed_Freeze   (Full_Der);
6476             Set_Is_Frozen            (Full_Der, False);
6477             Set_Freeze_Node          (Full_Der, Empty);
6478             Set_Depends_On_Private   (Full_Der,
6479                                        Has_Private_Component (Full_Der));
6480             Set_Public_Status        (Full_Der);
6481          end if;
6482       end if;
6483
6484       Set_Has_Unknown_Discriminants (Derived_Type,
6485         Has_Unknown_Discriminants (Parent_Type));
6486
6487       if Is_Private_Type (Derived_Type) then
6488          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6489       end if;
6490
6491       if Is_Private_Type (Parent_Type)
6492         and then Base_Type (Parent_Type) = Parent_Type
6493         and then In_Open_Scopes (Scope (Parent_Type))
6494       then
6495          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6496
6497          if Is_Child_Unit (Scope (Current_Scope))
6498            and then Is_Completion
6499            and then In_Private_Part (Current_Scope)
6500            and then Scope (Parent_Type) /= Current_Scope
6501          then
6502             --  This is the unusual case where a type completed by a private
6503             --  derivation occurs within a package nested in a child unit, and
6504             --  the parent is declared in an ancestor. In this case, the full
6505             --  view of the parent type will become visible in the body of
6506             --  the enclosing child, and only then will the current type be
6507             --  possibly non-private. We build a underlying full view that
6508             --  will be installed when the enclosing child body is compiled.
6509
6510             Full_Der :=
6511               Make_Defining_Identifier
6512                 (Sloc (Derived_Type), Chars (Derived_Type));
6513             Set_Is_Itype (Full_Der);
6514             Build_Itype_Reference (Full_Der, N);
6515
6516             --  The full view will be used to swap entities on entry/exit to
6517             --  the body, and must appear in the entity list for the package.
6518
6519             Append_Entity (Full_Der, Scope (Derived_Type));
6520             Set_Has_Private_Declaration (Full_Der);
6521             Set_Has_Private_Declaration (Derived_Type);
6522             Set_Associated_Node_For_Itype (Full_Der, N);
6523             Set_Parent (Full_Der, Parent (Derived_Type));
6524             Full_P := Full_View (Parent_Type);
6525             Exchange_Declarations (Parent_Type);
6526             Copy_And_Build;
6527             Exchange_Declarations (Full_P);
6528             Set_Underlying_Full_View (Derived_Type, Full_Der);
6529          end if;
6530       end if;
6531    end Build_Derived_Private_Type;
6532
6533    -------------------------------
6534    -- Build_Derived_Record_Type --
6535    -------------------------------
6536
6537    --  1. INTRODUCTION
6538
6539    --  Ideally we would like to use the same model of type derivation for
6540    --  tagged and untagged record types. Unfortunately this is not quite
6541    --  possible because the semantics of representation clauses is different
6542    --  for tagged and untagged records under inheritance. Consider the
6543    --  following:
6544
6545    --     type R (...) is [tagged] record ... end record;
6546    --     type T (...) is new R (...) [with ...];
6547
6548    --  The representation clauses for T can specify a completely different
6549    --  record layout from R's. Hence the same component can be placed in two
6550    --  very different positions in objects of type T and R. If R and T are
6551    --  tagged types, representation clauses for T can only specify the layout
6552    --  of non inherited components, thus components that are common in R and T
6553    --  have the same position in objects of type R and T.
6554
6555    --  This has two implications. The first is that the entire tree for R's
6556    --  declaration needs to be copied for T in the untagged case, so that T
6557    --  can be viewed as a record type of its own with its own representation
6558    --  clauses. The second implication is the way we handle discriminants.
6559    --  Specifically, in the untagged case we need a way to communicate to Gigi
6560    --  what are the real discriminants in the record, while for the semantics
6561    --  we need to consider those introduced by the user to rename the
6562    --  discriminants in the parent type. This is handled by introducing the
6563    --  notion of stored discriminants. See below for more.
6564
6565    --  Fortunately the way regular components are inherited can be handled in
6566    --  the same way in tagged and untagged types.
6567
6568    --  To complicate things a bit more the private view of a private extension
6569    --  cannot be handled in the same way as the full view (for one thing the
6570    --  semantic rules are somewhat different). We will explain what differs
6571    --  below.
6572
6573    --  2. DISCRIMINANTS UNDER INHERITANCE
6574
6575    --  The semantic rules governing the discriminants of derived types are
6576    --  quite subtle.
6577
6578    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6579    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6580
6581    --  If parent type has discriminants, then the discriminants that are
6582    --  declared in the derived type are [3.4 (11)]:
6583
6584    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6585    --    there is one;
6586
6587    --  o Otherwise, each discriminant of the parent type (implicitly declared
6588    --    in the same order with the same specifications). In this case, the
6589    --    discriminants are said to be "inherited", or if unknown in the parent
6590    --    are also unknown in the derived type.
6591
6592    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6593
6594    --  o The parent subtype shall be constrained;
6595
6596    --  o If the parent type is not a tagged type, then each discriminant of
6597    --    the derived type shall be used in the constraint defining a parent
6598    --    subtype. [Implementation note: This ensures that the new discriminant
6599    --    can share storage with an existing discriminant.]
6600
6601    --  For the derived type each discriminant of the parent type is either
6602    --  inherited, constrained to equal some new discriminant of the derived
6603    --  type, or constrained to the value of an expression.
6604
6605    --  When inherited or constrained to equal some new discriminant, the
6606    --  parent discriminant and the discriminant of the derived type are said
6607    --  to "correspond".
6608
6609    --  If a discriminant of the parent type is constrained to a specific value
6610    --  in the derived type definition, then the discriminant is said to be
6611    --  "specified" by that derived type definition.
6612
6613    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6614
6615    --  We have spoken about stored discriminants in point 1 (introduction)
6616    --  above. There are two sort of stored discriminants: implicit and
6617    --  explicit. As long as the derived type inherits the same discriminants as
6618    --  the root record type, stored discriminants are the same as regular
6619    --  discriminants, and are said to be implicit. However, if any discriminant
6620    --  in the root type was renamed in the derived type, then the derived
6621    --  type will contain explicit stored discriminants. Explicit stored
6622    --  discriminants are discriminants in addition to the semantically visible
6623    --  discriminants defined for the derived type. Stored discriminants are
6624    --  used by Gigi to figure out what are the physical discriminants in
6625    --  objects of the derived type (see precise definition in einfo.ads).
6626    --  As an example, consider the following:
6627
6628    --           type R  (D1, D2, D3 : Int) is record ... end record;
6629    --           type T1 is new R;
6630    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6631    --           type T3 is new T2;
6632    --           type T4 (Y : Int) is new T3 (Y, 99);
6633
6634    --  The following table summarizes the discriminants and stored
6635    --  discriminants in R and T1 through T4.
6636
6637    --   Type      Discrim     Stored Discrim  Comment
6638    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6639    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6640    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6641    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6642    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6643
6644    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6645    --  find the corresponding discriminant in the parent type, while
6646    --  Original_Record_Component (abbreviated ORC below), the actual physical
6647    --  component that is renamed. Finally the field Is_Completely_Hidden
6648    --  (abbreviated ICH below) is set for all explicit stored discriminants
6649    --  (see einfo.ads for more info). For the above example this gives:
6650
6651    --                 Discrim     CD        ORC     ICH
6652    --                 ^^^^^^^     ^^        ^^^     ^^^
6653    --                 D1 in R    empty     itself    no
6654    --                 D2 in R    empty     itself    no
6655    --                 D3 in R    empty     itself    no
6656
6657    --                 D1 in T1  D1 in R    itself    no
6658    --                 D2 in T1  D2 in R    itself    no
6659    --                 D3 in T1  D3 in R    itself    no
6660
6661    --                 X1 in T2  D3 in T1  D3 in T2   no
6662    --                 X2 in T2  D1 in T1  D1 in T2   no
6663    --                 D1 in T2   empty    itself    yes
6664    --                 D2 in T2   empty    itself    yes
6665    --                 D3 in T2   empty    itself    yes
6666
6667    --                 X1 in T3  X1 in T2  D3 in T3   no
6668    --                 X2 in T3  X2 in T2  D1 in T3   no
6669    --                 D1 in T3   empty    itself    yes
6670    --                 D2 in T3   empty    itself    yes
6671    --                 D3 in T3   empty    itself    yes
6672
6673    --                 Y  in T4  X1 in T3  D3 in T3   no
6674    --                 D1 in T3   empty    itself    yes
6675    --                 D2 in T3   empty    itself    yes
6676    --                 D3 in T3   empty    itself    yes
6677
6678    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6679
6680    --  Type derivation for tagged types is fairly straightforward. If no
6681    --  discriminants are specified by the derived type, these are inherited
6682    --  from the parent. No explicit stored discriminants are ever necessary.
6683    --  The only manipulation that is done to the tree is that of adding a
6684    --  _parent field with parent type and constrained to the same constraint
6685    --  specified for the parent in the derived type definition. For instance:
6686
6687    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6688    --           type T1 is new R with null record;
6689    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6690
6691    --  are changed into:
6692
6693    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6694    --              _parent : R (D1, D2, D3);
6695    --           end record;
6696
6697    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6698    --              _parent : T1 (X2, 88, X1);
6699    --           end record;
6700
6701    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6702    --  ORC and ICH fields are:
6703
6704    --                 Discrim     CD        ORC     ICH
6705    --                 ^^^^^^^     ^^        ^^^     ^^^
6706    --                 D1 in R    empty     itself    no
6707    --                 D2 in R    empty     itself    no
6708    --                 D3 in R    empty     itself    no
6709
6710    --                 D1 in T1  D1 in R    D1 in R   no
6711    --                 D2 in T1  D2 in R    D2 in R   no
6712    --                 D3 in T1  D3 in R    D3 in R   no
6713
6714    --                 X1 in T2  D3 in T1   D3 in R   no
6715    --                 X2 in T2  D1 in T1   D1 in R   no
6716
6717    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6718    --
6719    --  Regardless of whether we dealing with a tagged or untagged type
6720    --  we will transform all derived type declarations of the form
6721    --
6722    --               type T is new R (...) [with ...];
6723    --  or
6724    --               subtype S is R (...);
6725    --               type T is new S [with ...];
6726    --  into
6727    --               type BT is new R [with ...];
6728    --               subtype T is BT (...);
6729    --
6730    --  That is, the base derived type is constrained only if it has no
6731    --  discriminants. The reason for doing this is that GNAT's semantic model
6732    --  assumes that a base type with discriminants is unconstrained.
6733    --
6734    --  Note that, strictly speaking, the above transformation is not always
6735    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6736    --
6737    --       procedure B34011A is
6738    --          type REC (D : integer := 0) is record
6739    --             I : Integer;
6740    --          end record;
6741
6742    --          package P is
6743    --             type T6 is new Rec;
6744    --             function F return T6;
6745    --          end P;
6746
6747    --          use P;
6748    --          package Q6 is
6749    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6750    --          end Q6;
6751    --
6752    --  The definition of Q6.U is illegal. However transforming Q6.U into
6753
6754    --             type BaseU is new T6;
6755    --             subtype U is BaseU (Q6.F.I)
6756
6757    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6758    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6759    --  the transformation described above.
6760
6761    --  There is another instance where the above transformation is incorrect.
6762    --  Consider:
6763
6764    --          package Pack is
6765    --             type Base (D : Integer) is tagged null record;
6766    --             procedure P (X : Base);
6767
6768    --             type Der is new Base (2) with null record;
6769    --             procedure P (X : Der);
6770    --          end Pack;
6771
6772    --  Then the above transformation turns this into
6773
6774    --             type Der_Base is new Base with null record;
6775    --             --  procedure P (X : Base) is implicitly inherited here
6776    --             --  as procedure P (X : Der_Base).
6777
6778    --             subtype Der is Der_Base (2);
6779    --             procedure P (X : Der);
6780    --             --  The overriding of P (X : Der_Base) is illegal since we
6781    --             --  have a parameter conformance problem.
6782
6783    --  To get around this problem, after having semantically processed Der_Base
6784    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6785    --  Discriminant_Constraint from Der so that when parameter conformance is
6786    --  checked when P is overridden, no semantic errors are flagged.
6787
6788    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6789
6790    --  Regardless of whether we are dealing with a tagged or untagged type
6791    --  we will transform all derived type declarations of the form
6792
6793    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6794    --               type T is new R [with ...];
6795    --  into
6796    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6797
6798    --  The reason for such transformation is that it allows us to implement a
6799    --  very clean form of component inheritance as explained below.
6800
6801    --  Note that this transformation is not achieved by direct tree rewriting
6802    --  and manipulation, but rather by redoing the semantic actions that the
6803    --  above transformation will entail. This is done directly in routine
6804    --  Inherit_Components.
6805
6806    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
6807
6808    --  In both tagged and untagged derived types, regular non discriminant
6809    --  components are inherited in the derived type from the parent type. In
6810    --  the absence of discriminants component, inheritance is straightforward
6811    --  as components can simply be copied from the parent.
6812
6813    --  If the parent has discriminants, inheriting components constrained with
6814    --  these discriminants requires caution. Consider the following example:
6815
6816    --      type R  (D1, D2 : Positive) is [tagged] record
6817    --         S : String (D1 .. D2);
6818    --      end record;
6819
6820    --      type T1                is new R        [with null record];
6821    --      type T2 (X : positive) is new R (1, X) [with null record];
6822
6823    --  As explained in 6. above, T1 is rewritten as
6824    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
6825    --  which makes the treatment for T1 and T2 identical.
6826
6827    --  What we want when inheriting S, is that references to D1 and D2 in R are
6828    --  replaced with references to their correct constraints, i.e. D1 and D2 in
6829    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
6830    --  with either discriminant references in the derived type or expressions.
6831    --  This replacement is achieved as follows: before inheriting R's
6832    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
6833    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
6834    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
6835    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
6836    --  by String (1 .. X).
6837
6838    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
6839
6840    --  We explain here the rules governing private type extensions relevant to
6841    --  type derivation. These rules are explained on the following example:
6842
6843    --      type D [(...)] is new A [(...)] with private;      <-- partial view
6844    --      type D [(...)] is new P [(...)] with null record;  <-- full view
6845
6846    --  Type A is called the ancestor subtype of the private extension.
6847    --  Type P is the parent type of the full view of the private extension. It
6848    --  must be A or a type derived from A.
6849
6850    --  The rules concerning the discriminants of private type extensions are
6851    --  [7.3(10-13)]:
6852
6853    --  o If a private extension inherits known discriminants from the ancestor
6854    --    subtype, then the full view shall also inherit its discriminants from
6855    --    the ancestor subtype and the parent subtype of the full view shall be
6856    --    constrained if and only if the ancestor subtype is constrained.
6857
6858    --  o If a partial view has unknown discriminants, then the full view may
6859    --    define a definite or an indefinite subtype, with or without
6860    --    discriminants.
6861
6862    --  o If a partial view has neither known nor unknown discriminants, then
6863    --    the full view shall define a definite subtype.
6864
6865    --  o If the ancestor subtype of a private extension has constrained
6866    --    discriminants, then the parent subtype of the full view shall impose a
6867    --    statically matching constraint on those discriminants.
6868
6869    --  This means that only the following forms of private extensions are
6870    --  allowed:
6871
6872    --      type D is new A with private;      <-- partial view
6873    --      type D is new P with null record;  <-- full view
6874
6875    --  If A has no discriminants than P has no discriminants, otherwise P must
6876    --  inherit A's discriminants.
6877
6878    --      type D is new A (...) with private;      <-- partial view
6879    --      type D is new P (:::) with null record;  <-- full view
6880
6881    --  P must inherit A's discriminants and (...) and (:::) must statically
6882    --  match.
6883
6884    --      subtype A is R (...);
6885    --      type D is new A with private;      <-- partial view
6886    --      type D is new P with null record;  <-- full view
6887
6888    --  P must have inherited R's discriminants and must be derived from A or
6889    --  any of its subtypes.
6890
6891    --      type D (..) is new A with private;              <-- partial view
6892    --      type D (..) is new P [(:::)] with null record;  <-- full view
6893
6894    --  No specific constraints on P's discriminants or constraint (:::).
6895    --  Note that A can be unconstrained, but the parent subtype P must either
6896    --  be constrained or (:::) must be present.
6897
6898    --      type D (..) is new A [(...)] with private;      <-- partial view
6899    --      type D (..) is new P [(:::)] with null record;  <-- full view
6900
6901    --  P's constraints on A's discriminants must statically match those
6902    --  imposed by (...).
6903
6904    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
6905
6906    --  The full view of a private extension is handled exactly as described
6907    --  above. The model chose for the private view of a private extension is
6908    --  the same for what concerns discriminants (i.e. they receive the same
6909    --  treatment as in the tagged case). However, the private view of the
6910    --  private extension always inherits the components of the parent base,
6911    --  without replacing any discriminant reference. Strictly speaking this is
6912    --  incorrect. However, Gigi never uses this view to generate code so this
6913    --  is a purely semantic issue. In theory, a set of transformations similar
6914    --  to those given in 5. and 6. above could be applied to private views of
6915    --  private extensions to have the same model of component inheritance as
6916    --  for non private extensions. However, this is not done because it would
6917    --  further complicate private type processing. Semantically speaking, this
6918    --  leaves us in an uncomfortable situation. As an example consider:
6919
6920    --          package Pack is
6921    --             type R (D : integer) is tagged record
6922    --                S : String (1 .. D);
6923    --             end record;
6924    --             procedure P (X : R);
6925    --             type T is new R (1) with private;
6926    --          private
6927    --             type T is new R (1) with null record;
6928    --          end;
6929
6930    --  This is transformed into:
6931
6932    --          package Pack is
6933    --             type R (D : integer) is tagged record
6934    --                S : String (1 .. D);
6935    --             end record;
6936    --             procedure P (X : R);
6937    --             type T is new R (1) with private;
6938    --          private
6939    --             type BaseT is new R with null record;
6940    --             subtype  T is BaseT (1);
6941    --          end;
6942
6943    --  (strictly speaking the above is incorrect Ada)
6944
6945    --  From the semantic standpoint the private view of private extension T
6946    --  should be flagged as constrained since one can clearly have
6947    --
6948    --             Obj : T;
6949    --
6950    --  in a unit withing Pack. However, when deriving subprograms for the
6951    --  private view of private extension T, T must be seen as unconstrained
6952    --  since T has discriminants (this is a constraint of the current
6953    --  subprogram derivation model). Thus, when processing the private view of
6954    --  a private extension such as T, we first mark T as unconstrained, we
6955    --  process it, we perform program derivation and just before returning from
6956    --  Build_Derived_Record_Type we mark T as constrained.
6957
6958    --  ??? Are there are other uncomfortable cases that we will have to
6959    --      deal with.
6960
6961    --  10. RECORD_TYPE_WITH_PRIVATE complications
6962
6963    --  Types that are derived from a visible record type and have a private
6964    --  extension present other peculiarities. They behave mostly like private
6965    --  types, but if they have primitive operations defined, these will not
6966    --  have the proper signatures for further inheritance, because other
6967    --  primitive operations will use the implicit base that we define for
6968    --  private derivations below. This affect subprogram inheritance (see
6969    --  Derive_Subprograms for details). We also derive the implicit base from
6970    --  the base type of the full view, so that the implicit base is a record
6971    --  type and not another private type, This avoids infinite loops.
6972
6973    procedure Build_Derived_Record_Type
6974      (N            : Node_Id;
6975       Parent_Type  : Entity_Id;
6976       Derived_Type : Entity_Id;
6977       Derive_Subps : Boolean := True)
6978    is
6979       Discriminant_Specs : constant Boolean :=
6980                              Present (Discriminant_Specifications (N));
6981       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
6982       Loc                : constant Source_Ptr := Sloc (N);
6983       Private_Extension  : constant Boolean :=
6984                              Nkind (N) = N_Private_Extension_Declaration;
6985       Assoc_List         : Elist_Id;
6986       Constraint_Present : Boolean;
6987       Constrs            : Elist_Id;
6988       Discrim            : Entity_Id;
6989       Indic              : Node_Id;
6990       Inherit_Discrims   : Boolean := False;
6991       Last_Discrim       : Entity_Id;
6992       New_Base           : Entity_Id;
6993       New_Decl           : Node_Id;
6994       New_Discrs         : Elist_Id;
6995       New_Indic          : Node_Id;
6996       Parent_Base        : Entity_Id;
6997       Save_Etype         : Entity_Id;
6998       Save_Discr_Constr  : Elist_Id;
6999       Save_Next_Entity   : Entity_Id;
7000       Type_Def           : Node_Id;
7001
7002       Discs : Elist_Id := New_Elmt_List;
7003       --  An empty Discs list means that there were no constraints in the
7004       --  subtype indication or that there was an error processing it.
7005
7006    begin
7007       if Ekind (Parent_Type) = E_Record_Type_With_Private
7008         and then Present (Full_View (Parent_Type))
7009         and then Has_Discriminants (Parent_Type)
7010       then
7011          Parent_Base := Base_Type (Full_View (Parent_Type));
7012       else
7013          Parent_Base := Base_Type (Parent_Type);
7014       end if;
7015
7016       --  AI05-0115 : if this is a derivation from a private type in some
7017       --  other scope that may lead to invisible components for the derived
7018       --  type, mark it accordingly.
7019
7020       if Is_Private_Type (Parent_Type) then
7021          if Scope (Parent_Type) = Scope (Derived_Type) then
7022             null;
7023
7024          elsif In_Open_Scopes (Scope (Parent_Type))
7025            and then In_Private_Part (Scope (Parent_Type))
7026          then
7027             null;
7028
7029          else
7030             Set_Has_Private_Ancestor (Derived_Type);
7031          end if;
7032
7033       else
7034          Set_Has_Private_Ancestor
7035            (Derived_Type, Has_Private_Ancestor (Parent_Type));
7036       end if;
7037
7038       --  Before we start the previously documented transformations, here is
7039       --  little fix for size and alignment of tagged types. Normally when we
7040       --  derive type D from type P, we copy the size and alignment of P as the
7041       --  default for D, and in the absence of explicit representation clauses
7042       --  for D, the size and alignment are indeed the same as the parent.
7043
7044       --  But this is wrong for tagged types, since fields may be added, and
7045       --  the default size may need to be larger, and the default alignment may
7046       --  need to be larger.
7047
7048       --  We therefore reset the size and alignment fields in the tagged case.
7049       --  Note that the size and alignment will in any case be at least as
7050       --  large as the parent type (since the derived type has a copy of the
7051       --  parent type in the _parent field)
7052
7053       --  The type is also marked as being tagged here, which is needed when
7054       --  processing components with a self-referential anonymous access type
7055       --  in the call to Check_Anonymous_Access_Components below. Note that
7056       --  this flag is also set later on for completeness.
7057
7058       if Is_Tagged then
7059          Set_Is_Tagged_Type (Derived_Type);
7060          Init_Size_Align    (Derived_Type);
7061       end if;
7062
7063       --  STEP 0a: figure out what kind of derived type declaration we have
7064
7065       if Private_Extension then
7066          Type_Def := N;
7067          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
7068
7069       else
7070          Type_Def := Type_Definition (N);
7071
7072          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7073          --  Parent_Base can be a private type or private extension. However,
7074          --  for tagged types with an extension the newly added fields are
7075          --  visible and hence the Derived_Type is always an E_Record_Type.
7076          --  (except that the parent may have its own private fields).
7077          --  For untagged types we preserve the Ekind of the Parent_Base.
7078
7079          if Present (Record_Extension_Part (Type_Def)) then
7080             Set_Ekind (Derived_Type, E_Record_Type);
7081
7082             --  Create internal access types for components with anonymous
7083             --  access types.
7084
7085             if Ada_Version >= Ada_2005 then
7086                Check_Anonymous_Access_Components
7087                  (N, Derived_Type, Derived_Type,
7088                    Component_List (Record_Extension_Part (Type_Def)));
7089             end if;
7090
7091          else
7092             Set_Ekind (Derived_Type, Ekind (Parent_Base));
7093          end if;
7094       end if;
7095
7096       --  Indic can either be an N_Identifier if the subtype indication
7097       --  contains no constraint or an N_Subtype_Indication if the subtype
7098       --  indication has a constraint.
7099
7100       Indic := Subtype_Indication (Type_Def);
7101       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
7102
7103       --  Check that the type has visible discriminants. The type may be
7104       --  a private type with unknown discriminants whose full view has
7105       --  discriminants which are invisible.
7106
7107       if Constraint_Present then
7108          if not Has_Discriminants (Parent_Base)
7109            or else
7110              (Has_Unknown_Discriminants (Parent_Base)
7111                 and then Is_Private_Type (Parent_Base))
7112          then
7113             Error_Msg_N
7114               ("invalid constraint: type has no discriminant",
7115                  Constraint (Indic));
7116
7117             Constraint_Present := False;
7118             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7119
7120          elsif Is_Constrained (Parent_Type) then
7121             Error_Msg_N
7122                ("invalid constraint: parent type is already constrained",
7123                   Constraint (Indic));
7124
7125             Constraint_Present := False;
7126             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
7127          end if;
7128       end if;
7129
7130       --  STEP 0b: If needed, apply transformation given in point 5. above
7131
7132       if not Private_Extension
7133         and then Has_Discriminants (Parent_Type)
7134         and then not Discriminant_Specs
7135         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
7136       then
7137          --  First, we must analyze the constraint (see comment in point 5.)
7138
7139          if Constraint_Present then
7140             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
7141
7142             if Has_Discriminants (Derived_Type)
7143               and then Has_Private_Declaration (Derived_Type)
7144               and then Present (Discriminant_Constraint (Derived_Type))
7145             then
7146                --  Verify that constraints of the full view statically match
7147                --  those given in the partial view.
7148
7149                declare
7150                   C1, C2 : Elmt_Id;
7151
7152                begin
7153                   C1 := First_Elmt (New_Discrs);
7154                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
7155                   while Present (C1) and then Present (C2) loop
7156                      if Fully_Conformant_Expressions (Node (C1), Node (C2))
7157                        or else
7158                          (Is_OK_Static_Expression (Node (C1))
7159                             and then
7160                           Is_OK_Static_Expression (Node (C2))
7161                             and then
7162                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
7163                      then
7164                         null;
7165
7166                      else
7167                         Error_Msg_N (
7168                           "constraint not conformant to previous declaration",
7169                              Node (C1));
7170                      end if;
7171
7172                      Next_Elmt (C1);
7173                      Next_Elmt (C2);
7174                   end loop;
7175                end;
7176             end if;
7177          end if;
7178
7179          --  Insert and analyze the declaration for the unconstrained base type
7180
7181          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
7182
7183          New_Decl :=
7184            Make_Full_Type_Declaration (Loc,
7185               Defining_Identifier => New_Base,
7186               Type_Definition     =>
7187                 Make_Derived_Type_Definition (Loc,
7188                   Abstract_Present      => Abstract_Present (Type_Def),
7189                   Limited_Present       => Limited_Present (Type_Def),
7190                   Subtype_Indication    =>
7191                     New_Occurrence_Of (Parent_Base, Loc),
7192                   Record_Extension_Part =>
7193                     Relocate_Node (Record_Extension_Part (Type_Def)),
7194                   Interface_List        => Interface_List (Type_Def)));
7195
7196          Set_Parent (New_Decl, Parent (N));
7197          Mark_Rewrite_Insertion (New_Decl);
7198          Insert_Before (N, New_Decl);
7199
7200          --  In the extension case, make sure ancestor is frozen appropriately
7201          --  (see also non-discriminated case below).
7202
7203          if Present (Record_Extension_Part (Type_Def))
7204            or else Is_Interface (Parent_Base)
7205          then
7206             Freeze_Before (New_Decl, Parent_Type);
7207          end if;
7208
7209          --  Note that this call passes False for the Derive_Subps parameter
7210          --  because subprogram derivation is deferred until after creating
7211          --  the subtype (see below).
7212
7213          Build_Derived_Type
7214            (New_Decl, Parent_Base, New_Base,
7215             Is_Completion => True, Derive_Subps => False);
7216
7217          --  ??? This needs re-examination to determine whether the
7218          --  above call can simply be replaced by a call to Analyze.
7219
7220          Set_Analyzed (New_Decl);
7221
7222          --  Insert and analyze the declaration for the constrained subtype
7223
7224          if Constraint_Present then
7225             New_Indic :=
7226               Make_Subtype_Indication (Loc,
7227                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7228                 Constraint   => Relocate_Node (Constraint (Indic)));
7229
7230          else
7231             declare
7232                Constr_List : constant List_Id := New_List;
7233                C           : Elmt_Id;
7234                Expr        : Node_Id;
7235
7236             begin
7237                C := First_Elmt (Discriminant_Constraint (Parent_Type));
7238                while Present (C) loop
7239                   Expr := Node (C);
7240
7241                   --  It is safe here to call New_Copy_Tree since
7242                   --  Force_Evaluation was called on each constraint in
7243                   --  Build_Discriminant_Constraints.
7244
7245                   Append (New_Copy_Tree (Expr), To => Constr_List);
7246
7247                   Next_Elmt (C);
7248                end loop;
7249
7250                New_Indic :=
7251                  Make_Subtype_Indication (Loc,
7252                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
7253                    Constraint   =>
7254                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
7255             end;
7256          end if;
7257
7258          Rewrite (N,
7259            Make_Subtype_Declaration (Loc,
7260              Defining_Identifier => Derived_Type,
7261              Subtype_Indication  => New_Indic));
7262
7263          Analyze (N);
7264
7265          --  Derivation of subprograms must be delayed until the full subtype
7266          --  has been established, to ensure proper overriding of subprograms
7267          --  inherited by full types. If the derivations occurred as part of
7268          --  the call to Build_Derived_Type above, then the check for type
7269          --  conformance would fail because earlier primitive subprograms
7270          --  could still refer to the full type prior the change to the new
7271          --  subtype and hence would not match the new base type created here.
7272          --  Subprograms are not derived, however, when Derive_Subps is False
7273          --  (since otherwise there could be redundant derivations).
7274
7275          if Derive_Subps then
7276             Derive_Subprograms (Parent_Type, Derived_Type);
7277          end if;
7278
7279          --  For tagged types the Discriminant_Constraint of the new base itype
7280          --  is inherited from the first subtype so that no subtype conformance
7281          --  problem arise when the first subtype overrides primitive
7282          --  operations inherited by the implicit base type.
7283
7284          if Is_Tagged then
7285             Set_Discriminant_Constraint
7286               (New_Base, Discriminant_Constraint (Derived_Type));
7287          end if;
7288
7289          return;
7290       end if;
7291
7292       --  If we get here Derived_Type will have no discriminants or it will be
7293       --  a discriminated unconstrained base type.
7294
7295       --  STEP 1a: perform preliminary actions/checks for derived tagged types
7296
7297       if Is_Tagged then
7298
7299          --  The parent type is frozen for non-private extensions (RM 13.14(7))
7300          --  The declaration of a specific descendant of an interface type
7301          --  freezes the interface type (RM 13.14).
7302
7303          if not Private_Extension or else Is_Interface (Parent_Base) then
7304             Freeze_Before (N, Parent_Type);
7305          end if;
7306
7307          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
7308          --  cannot be declared at a deeper level than its parent type is
7309          --  removed. The check on derivation within a generic body is also
7310          --  relaxed, but there's a restriction that a derived tagged type
7311          --  cannot be declared in a generic body if it's derived directly
7312          --  or indirectly from a formal type of that generic.
7313
7314          if Ada_Version >= Ada_2005 then
7315             if Present (Enclosing_Generic_Body (Derived_Type)) then
7316                declare
7317                   Ancestor_Type : Entity_Id;
7318
7319                begin
7320                   --  Check to see if any ancestor of the derived type is a
7321                   --  formal type.
7322
7323                   Ancestor_Type := Parent_Type;
7324                   while not Is_Generic_Type (Ancestor_Type)
7325                     and then Etype (Ancestor_Type) /= Ancestor_Type
7326                   loop
7327                      Ancestor_Type := Etype (Ancestor_Type);
7328                   end loop;
7329
7330                   --  If the derived type does have a formal type as an
7331                   --  ancestor, then it's an error if the derived type is
7332                   --  declared within the body of the generic unit that
7333                   --  declares the formal type in its generic formal part. It's
7334                   --  sufficient to check whether the ancestor type is declared
7335                   --  inside the same generic body as the derived type (such as
7336                   --  within a nested generic spec), in which case the
7337                   --  derivation is legal. If the formal type is declared
7338                   --  outside of that generic body, then it's guaranteed that
7339                   --  the derived type is declared within the generic body of
7340                   --  the generic unit declaring the formal type.
7341
7342                   if Is_Generic_Type (Ancestor_Type)
7343                     and then Enclosing_Generic_Body (Ancestor_Type) /=
7344                                Enclosing_Generic_Body (Derived_Type)
7345                   then
7346                      Error_Msg_NE
7347                        ("parent type of& must not be descendant of formal type"
7348                           & " of an enclosing generic body",
7349                             Indic, Derived_Type);
7350                   end if;
7351                end;
7352             end if;
7353
7354          elsif Type_Access_Level (Derived_Type) /=
7355                  Type_Access_Level (Parent_Type)
7356            and then not Is_Generic_Type (Derived_Type)
7357          then
7358             if Is_Controlled (Parent_Type) then
7359                Error_Msg_N
7360                  ("controlled type must be declared at the library level",
7361                   Indic);
7362             else
7363                Error_Msg_N
7364                  ("type extension at deeper accessibility level than parent",
7365                   Indic);
7366             end if;
7367
7368          else
7369             declare
7370                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
7371
7372             begin
7373                if Present (GB)
7374                  and then GB /= Enclosing_Generic_Body (Parent_Base)
7375                then
7376                   Error_Msg_NE
7377                     ("parent type of& must not be outside generic body"
7378                        & " (RM 3.9.1(4))",
7379                          Indic, Derived_Type);
7380                end if;
7381             end;
7382          end if;
7383       end if;
7384
7385       --  Ada 2005 (AI-251)
7386
7387       if Ada_Version >= Ada_2005 and then Is_Tagged then
7388
7389          --  "The declaration of a specific descendant of an interface type
7390          --  freezes the interface type" (RM 13.14).
7391
7392          declare
7393             Iface : Node_Id;
7394          begin
7395             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7396                Iface := First (Interface_List (Type_Def));
7397                while Present (Iface) loop
7398                   Freeze_Before (N, Etype (Iface));
7399                   Next (Iface);
7400                end loop;
7401             end if;
7402          end;
7403       end if;
7404
7405       --  STEP 1b : preliminary cleanup of the full view of private types
7406
7407       --  If the type is already marked as having discriminants, then it's the
7408       --  completion of a private type or private extension and we need to
7409       --  retain the discriminants from the partial view if the current
7410       --  declaration has Discriminant_Specifications so that we can verify
7411       --  conformance. However, we must remove any existing components that
7412       --  were inherited from the parent (and attached in Copy_And_Swap)
7413       --  because the full type inherits all appropriate components anyway, and
7414       --  we do not want the partial view's components interfering.
7415
7416       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7417          Discrim := First_Discriminant (Derived_Type);
7418          loop
7419             Last_Discrim := Discrim;
7420             Next_Discriminant (Discrim);
7421             exit when No (Discrim);
7422          end loop;
7423
7424          Set_Last_Entity (Derived_Type, Last_Discrim);
7425
7426       --  In all other cases wipe out the list of inherited components (even
7427       --  inherited discriminants), it will be properly rebuilt here.
7428
7429       else
7430          Set_First_Entity (Derived_Type, Empty);
7431          Set_Last_Entity  (Derived_Type, Empty);
7432       end if;
7433
7434       --  STEP 1c: Initialize some flags for the Derived_Type
7435
7436       --  The following flags must be initialized here so that
7437       --  Process_Discriminants can check that discriminants of tagged types do
7438       --  not have a default initial value and that access discriminants are
7439       --  only specified for limited records. For completeness, these flags are
7440       --  also initialized along with all the other flags below.
7441
7442       --  AI-419: Limitedness is not inherited from an interface parent, so to
7443       --  be limited in that case the type must be explicitly declared as
7444       --  limited. However, task and protected interfaces are always limited.
7445
7446       if Limited_Present (Type_Def) then
7447          Set_Is_Limited_Record (Derived_Type);
7448
7449       elsif Is_Limited_Record (Parent_Type)
7450         or else (Present (Full_View (Parent_Type))
7451                    and then Is_Limited_Record (Full_View (Parent_Type)))
7452       then
7453          if not Is_Interface (Parent_Type)
7454            or else Is_Synchronized_Interface (Parent_Type)
7455            or else Is_Protected_Interface (Parent_Type)
7456            or else Is_Task_Interface (Parent_Type)
7457          then
7458             Set_Is_Limited_Record (Derived_Type);
7459          end if;
7460       end if;
7461
7462       --  STEP 2a: process discriminants of derived type if any
7463
7464       Push_Scope (Derived_Type);
7465
7466       if Discriminant_Specs then
7467          Set_Has_Unknown_Discriminants (Derived_Type, False);
7468
7469          --  The following call initializes fields Has_Discriminants and
7470          --  Discriminant_Constraint, unless we are processing the completion
7471          --  of a private type declaration.
7472
7473          Check_Or_Process_Discriminants (N, Derived_Type);
7474
7475          --  For untagged types, the constraint on the Parent_Type must be
7476          --  present and is used to rename the discriminants.
7477
7478          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7479             Error_Msg_N ("untagged parent must have discriminants", Indic);
7480
7481          elsif not Is_Tagged and then not Constraint_Present then
7482             Error_Msg_N
7483               ("discriminant constraint needed for derived untagged records",
7484                Indic);
7485
7486          --  Otherwise the parent subtype must be constrained unless we have a
7487          --  private extension.
7488
7489          elsif not Constraint_Present
7490            and then not Private_Extension
7491            and then not Is_Constrained (Parent_Type)
7492          then
7493             Error_Msg_N
7494               ("unconstrained type not allowed in this context", Indic);
7495
7496          elsif Constraint_Present then
7497             --  The following call sets the field Corresponding_Discriminant
7498             --  for the discriminants in the Derived_Type.
7499
7500             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7501
7502             --  For untagged types all new discriminants must rename
7503             --  discriminants in the parent. For private extensions new
7504             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7505
7506             Discrim := First_Discriminant (Derived_Type);
7507             while Present (Discrim) loop
7508                if not Is_Tagged
7509                  and then No (Corresponding_Discriminant (Discrim))
7510                then
7511                   Error_Msg_N
7512                     ("new discriminants must constrain old ones", Discrim);
7513
7514                elsif Private_Extension
7515                  and then Present (Corresponding_Discriminant (Discrim))
7516                then
7517                   Error_Msg_N
7518                     ("only static constraints allowed for parent"
7519                      & " discriminants in the partial view", Indic);
7520                   exit;
7521                end if;
7522
7523                --  If a new discriminant is used in the constraint, then its
7524                --  subtype must be statically compatible with the parent
7525                --  discriminant's subtype (3.7(15)).
7526
7527                if Present (Corresponding_Discriminant (Discrim))
7528                  and then
7529                    not Subtypes_Statically_Compatible
7530                          (Etype (Discrim),
7531                           Etype (Corresponding_Discriminant (Discrim)))
7532                then
7533                   Error_Msg_N
7534                     ("subtype must be compatible with parent discriminant",
7535                      Discrim);
7536                end if;
7537
7538                Next_Discriminant (Discrim);
7539             end loop;
7540
7541             --  Check whether the constraints of the full view statically
7542             --  match those imposed by the parent subtype [7.3(13)].
7543
7544             if Present (Stored_Constraint (Derived_Type)) then
7545                declare
7546                   C1, C2 : Elmt_Id;
7547
7548                begin
7549                   C1 := First_Elmt (Discs);
7550                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7551                   while Present (C1) and then Present (C2) loop
7552                      if not
7553                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7554                      then
7555                         Error_Msg_N
7556                           ("not conformant with previous declaration",
7557                            Node (C1));
7558                      end if;
7559
7560                      Next_Elmt (C1);
7561                      Next_Elmt (C2);
7562                   end loop;
7563                end;
7564             end if;
7565          end if;
7566
7567       --  STEP 2b: No new discriminants, inherit discriminants if any
7568
7569       else
7570          if Private_Extension then
7571             Set_Has_Unknown_Discriminants
7572               (Derived_Type,
7573                Has_Unknown_Discriminants (Parent_Type)
7574                  or else Unknown_Discriminants_Present (N));
7575
7576          --  The partial view of the parent may have unknown discriminants,
7577          --  but if the full view has discriminants and the parent type is
7578          --  in scope they must be inherited.
7579
7580          elsif Has_Unknown_Discriminants (Parent_Type)
7581            and then
7582             (not Has_Discriminants (Parent_Type)
7583               or else not In_Open_Scopes (Scope (Parent_Type)))
7584          then
7585             Set_Has_Unknown_Discriminants (Derived_Type);
7586          end if;
7587
7588          if not Has_Unknown_Discriminants (Derived_Type)
7589            and then not Has_Unknown_Discriminants (Parent_Base)
7590            and then Has_Discriminants (Parent_Type)
7591          then
7592             Inherit_Discrims := True;
7593             Set_Has_Discriminants
7594               (Derived_Type, True);
7595             Set_Discriminant_Constraint
7596               (Derived_Type, Discriminant_Constraint (Parent_Base));
7597          end if;
7598
7599          --  The following test is true for private types (remember
7600          --  transformation 5. is not applied to those) and in an error
7601          --  situation.
7602
7603          if Constraint_Present then
7604             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7605          end if;
7606
7607          --  For now mark a new derived type as constrained only if it has no
7608          --  discriminants. At the end of Build_Derived_Record_Type we properly
7609          --  set this flag in the case of private extensions. See comments in
7610          --  point 9. just before body of Build_Derived_Record_Type.
7611
7612          Set_Is_Constrained
7613            (Derived_Type,
7614             not (Inherit_Discrims
7615                    or else Has_Unknown_Discriminants (Derived_Type)));
7616       end if;
7617
7618       --  STEP 3: initialize fields of derived type
7619
7620       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7621       Set_Stored_Constraint (Derived_Type, No_Elist);
7622
7623       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7624       --  but cannot be interfaces
7625
7626       if not Private_Extension
7627          and then Ekind (Derived_Type) /= E_Private_Type
7628          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7629       then
7630          if Interface_Present (Type_Def) then
7631             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7632          end if;
7633
7634          Set_Interfaces (Derived_Type, No_Elist);
7635       end if;
7636
7637       --  Fields inherited from the Parent_Type
7638
7639       Set_Discard_Names
7640         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
7641       Set_Has_Specified_Layout
7642         (Derived_Type, Has_Specified_Layout (Parent_Type));
7643       Set_Is_Limited_Composite
7644         (Derived_Type, Is_Limited_Composite (Parent_Type));
7645       Set_Is_Private_Composite
7646         (Derived_Type, Is_Private_Composite (Parent_Type));
7647
7648       --  Fields inherited from the Parent_Base
7649
7650       Set_Has_Controlled_Component
7651         (Derived_Type, Has_Controlled_Component (Parent_Base));
7652       Set_Has_Non_Standard_Rep
7653         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7654       Set_Has_Primitive_Operations
7655         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7656
7657       --  Fields inherited from the Parent_Base in the non-private case
7658
7659       if Ekind (Derived_Type) = E_Record_Type then
7660          Set_Has_Complex_Representation
7661            (Derived_Type, Has_Complex_Representation (Parent_Base));
7662       end if;
7663
7664       --  Fields inherited from the Parent_Base for record types
7665
7666       if Is_Record_Type (Derived_Type) then
7667
7668          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7669          --  Parent_Base can be a private type or private extension.
7670
7671          if Present (Full_View (Parent_Base)) then
7672             Set_OK_To_Reorder_Components
7673               (Derived_Type,
7674                OK_To_Reorder_Components (Full_View (Parent_Base)));
7675             Set_Reverse_Bit_Order
7676               (Derived_Type, Reverse_Bit_Order (Full_View (Parent_Base)));
7677          else
7678             Set_OK_To_Reorder_Components
7679               (Derived_Type, OK_To_Reorder_Components (Parent_Base));
7680             Set_Reverse_Bit_Order
7681               (Derived_Type, Reverse_Bit_Order (Parent_Base));
7682          end if;
7683       end if;
7684
7685       --  Direct controlled types do not inherit Finalize_Storage_Only flag
7686
7687       if not Is_Controlled (Parent_Type) then
7688          Set_Finalize_Storage_Only
7689            (Derived_Type, Finalize_Storage_Only (Parent_Type));
7690       end if;
7691
7692       --  Set fields for private derived types
7693
7694       if Is_Private_Type (Derived_Type) then
7695          Set_Depends_On_Private (Derived_Type, True);
7696          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7697
7698       --  Inherit fields from non private record types. If this is the
7699       --  completion of a derivation from a private type, the parent itself
7700       --  is private, and the attributes come from its full view, which must
7701       --  be present.
7702
7703       else
7704          if Is_Private_Type (Parent_Base)
7705            and then not Is_Record_Type (Parent_Base)
7706          then
7707             Set_Component_Alignment
7708               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7709             Set_C_Pass_By_Copy
7710               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7711          else
7712             Set_Component_Alignment
7713               (Derived_Type, Component_Alignment (Parent_Base));
7714             Set_C_Pass_By_Copy
7715               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7716          end if;
7717       end if;
7718
7719       --  Set fields for tagged types
7720
7721       if Is_Tagged then
7722          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
7723
7724          --  All tagged types defined in Ada.Finalization are controlled
7725
7726          if Chars (Scope (Derived_Type)) = Name_Finalization
7727            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7728            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7729          then
7730             Set_Is_Controlled (Derived_Type);
7731          else
7732             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7733          end if;
7734
7735          --  Minor optimization: there is no need to generate the class-wide
7736          --  entity associated with an underlying record view.
7737
7738          if not Is_Underlying_Record_View (Derived_Type) then
7739             Make_Class_Wide_Type (Derived_Type);
7740          end if;
7741
7742          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7743
7744          if Has_Discriminants (Derived_Type)
7745            and then Constraint_Present
7746          then
7747             Set_Stored_Constraint
7748               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7749          end if;
7750
7751          if Ada_Version >= Ada_2005 then
7752             declare
7753                Ifaces_List : Elist_Id;
7754
7755             begin
7756                --  Checks rules 3.9.4 (13/2 and 14/2)
7757
7758                if Comes_From_Source (Derived_Type)
7759                  and then not Is_Private_Type (Derived_Type)
7760                  and then Is_Interface (Parent_Type)
7761                  and then not Is_Interface (Derived_Type)
7762                then
7763                   if Is_Task_Interface (Parent_Type) then
7764                      Error_Msg_N
7765                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
7766                         Derived_Type);
7767
7768                   elsif Is_Protected_Interface (Parent_Type) then
7769                      Error_Msg_N
7770                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
7771                         Derived_Type);
7772                   end if;
7773                end if;
7774
7775                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
7776
7777                Check_Interfaces (N, Type_Def);
7778
7779                --  Ada 2005 (AI-251): Collect the list of progenitors that are
7780                --  not already in the parents.
7781
7782                Collect_Interfaces
7783                  (T               => Derived_Type,
7784                   Ifaces_List     => Ifaces_List,
7785                   Exclude_Parents => True);
7786
7787                Set_Interfaces (Derived_Type, Ifaces_List);
7788
7789                --  If the derived type is the anonymous type created for
7790                --  a declaration whose parent has a constraint, propagate
7791                --  the interface list to the source type. This must be done
7792                --  prior to the completion of the analysis of the source type
7793                --  because the components in the extension may contain current
7794                --  instances whose legality depends on some ancestor.
7795
7796                if Is_Itype (Derived_Type) then
7797                   declare
7798                      Def : constant Node_Id :=
7799                        Associated_Node_For_Itype (Derived_Type);
7800                   begin
7801                      if Present (Def)
7802                        and then Nkind (Def) = N_Full_Type_Declaration
7803                      then
7804                         Set_Interfaces
7805                           (Defining_Identifier (Def), Ifaces_List);
7806                      end if;
7807                   end;
7808                end if;
7809             end;
7810          end if;
7811
7812       else
7813          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
7814          Set_Has_Non_Standard_Rep
7815                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
7816       end if;
7817
7818       --  STEP 4: Inherit components from the parent base and constrain them.
7819       --          Apply the second transformation described in point 6. above.
7820
7821       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
7822         or else not Has_Discriminants (Parent_Type)
7823         or else not Is_Constrained (Parent_Type)
7824       then
7825          Constrs := Discs;
7826       else
7827          Constrs := Discriminant_Constraint (Parent_Type);
7828       end if;
7829
7830       Assoc_List :=
7831         Inherit_Components
7832           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
7833
7834       --  STEP 5a: Copy the parent record declaration for untagged types
7835
7836       if not Is_Tagged then
7837
7838          --  Discriminant_Constraint (Derived_Type) has been properly
7839          --  constructed. Save it and temporarily set it to Empty because we
7840          --  do not want the call to New_Copy_Tree below to mess this list.
7841
7842          if Has_Discriminants (Derived_Type) then
7843             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
7844             Set_Discriminant_Constraint (Derived_Type, No_Elist);
7845          else
7846             Save_Discr_Constr := No_Elist;
7847          end if;
7848
7849          --  Save the Etype field of Derived_Type. It is correctly set now,
7850          --  but the call to New_Copy tree may remap it to point to itself,
7851          --  which is not what we want. Ditto for the Next_Entity field.
7852
7853          Save_Etype       := Etype (Derived_Type);
7854          Save_Next_Entity := Next_Entity (Derived_Type);
7855
7856          --  Assoc_List maps all stored discriminants in the Parent_Base to
7857          --  stored discriminants in the Derived_Type. It is fundamental that
7858          --  no types or itypes with discriminants other than the stored
7859          --  discriminants appear in the entities declared inside
7860          --  Derived_Type, since the back end cannot deal with it.
7861
7862          New_Decl :=
7863            New_Copy_Tree
7864              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
7865
7866          --  Restore the fields saved prior to the New_Copy_Tree call
7867          --  and compute the stored constraint.
7868
7869          Set_Etype       (Derived_Type, Save_Etype);
7870          Set_Next_Entity (Derived_Type, Save_Next_Entity);
7871
7872          if Has_Discriminants (Derived_Type) then
7873             Set_Discriminant_Constraint
7874               (Derived_Type, Save_Discr_Constr);
7875             Set_Stored_Constraint
7876               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
7877             Replace_Components (Derived_Type, New_Decl);
7878          end if;
7879
7880          --  Insert the new derived type declaration
7881
7882          Rewrite (N, New_Decl);
7883
7884       --  STEP 5b: Complete the processing for record extensions in generics
7885
7886       --  There is no completion for record extensions declared in the
7887       --  parameter part of a generic, so we need to complete processing for
7888       --  these generic record extensions here. The Record_Type_Definition call
7889       --  will change the Ekind of the components from E_Void to E_Component.
7890
7891       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
7892          Record_Type_Definition (Empty, Derived_Type);
7893
7894       --  STEP 5c: Process the record extension for non private tagged types
7895
7896       elsif not Private_Extension then
7897
7898          --  Add the _parent field in the derived type
7899
7900          Expand_Record_Extension (Derived_Type, Type_Def);
7901
7902          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
7903          --  implemented interfaces if we are in expansion mode
7904
7905          if Expander_Active
7906            and then Has_Interfaces (Derived_Type)
7907          then
7908             Add_Interface_Tag_Components (N, Derived_Type);
7909          end if;
7910
7911          --  Analyze the record extension
7912
7913          Record_Type_Definition
7914            (Record_Extension_Part (Type_Def), Derived_Type);
7915       end if;
7916
7917       End_Scope;
7918
7919       --  Nothing else to do if there is an error in the derivation.
7920       --  An unusual case: the full view may be derived from a type in an
7921       --  instance, when the partial view was used illegally as an actual
7922       --  in that instance, leading to a circular definition.
7923
7924       if Etype (Derived_Type) = Any_Type
7925         or else Etype (Parent_Type) = Derived_Type
7926       then
7927          return;
7928       end if;
7929
7930       --  Set delayed freeze and then derive subprograms, we need to do
7931       --  this in this order so that derived subprograms inherit the
7932       --  derived freeze if necessary.
7933
7934       Set_Has_Delayed_Freeze (Derived_Type);
7935
7936       if Derive_Subps then
7937          Derive_Subprograms (Parent_Type, Derived_Type);
7938       end if;
7939
7940       --  If we have a private extension which defines a constrained derived
7941       --  type mark as constrained here after we have derived subprograms. See
7942       --  comment on point 9. just above the body of Build_Derived_Record_Type.
7943
7944       if Private_Extension and then Inherit_Discrims then
7945          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
7946             Set_Is_Constrained          (Derived_Type, True);
7947             Set_Discriminant_Constraint (Derived_Type, Discs);
7948
7949          elsif Is_Constrained (Parent_Type) then
7950             Set_Is_Constrained
7951               (Derived_Type, True);
7952             Set_Discriminant_Constraint
7953               (Derived_Type, Discriminant_Constraint (Parent_Type));
7954          end if;
7955       end if;
7956
7957       --  Update the class-wide type, which shares the now-completed entity
7958       --  list with its specific type. In case of underlying record views,
7959       --  we do not generate the corresponding class wide entity.
7960
7961       if Is_Tagged
7962         and then not Is_Underlying_Record_View (Derived_Type)
7963       then
7964          Set_First_Entity
7965            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
7966          Set_Last_Entity
7967            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
7968       end if;
7969
7970       --  Update the scope of anonymous access types of discriminants and other
7971       --  components, to prevent scope anomalies in gigi, when the derivation
7972       --  appears in a scope nested within that of the parent.
7973
7974       declare
7975          D : Entity_Id;
7976
7977       begin
7978          D := First_Entity (Derived_Type);
7979          while Present (D) loop
7980             if Ekind_In (D, E_Discriminant, E_Component) then
7981                if Is_Itype (Etype (D))
7982                   and then Ekind (Etype (D)) = E_Anonymous_Access_Type
7983                then
7984                   Set_Scope (Etype (D), Current_Scope);
7985                end if;
7986             end if;
7987
7988             Next_Entity (D);
7989          end loop;
7990       end;
7991    end Build_Derived_Record_Type;
7992
7993    ------------------------
7994    -- Build_Derived_Type --
7995    ------------------------
7996
7997    procedure Build_Derived_Type
7998      (N             : Node_Id;
7999       Parent_Type   : Entity_Id;
8000       Derived_Type  : Entity_Id;
8001       Is_Completion : Boolean;
8002       Derive_Subps  : Boolean := True)
8003    is
8004       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
8005
8006    begin
8007       --  Set common attributes
8008
8009       Set_Scope          (Derived_Type, Current_Scope);
8010
8011       Set_Ekind          (Derived_Type, Ekind    (Parent_Base));
8012       Set_Etype          (Derived_Type,           Parent_Base);
8013       Set_Has_Task       (Derived_Type, Has_Task (Parent_Base));
8014
8015       Set_Size_Info      (Derived_Type,                 Parent_Type);
8016       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
8017       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
8018       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
8019
8020       --  If the parent type is a private subtype, the convention on the base
8021       --  type may be set in the private part, and not propagated to the
8022       --  subtype until later, so we obtain the convention from the base type.
8023
8024       Set_Convention     (Derived_Type, Convention     (Parent_Base));
8025
8026       --  Propagate invariant information. The new type has invariants if
8027       --  they are inherited from the parent type, and these invariants can
8028       --  be further inherited, so both flags are set.
8029
8030       if Has_Inheritable_Invariants (Parent_Type) then
8031          Set_Has_Inheritable_Invariants (Derived_Type);
8032          Set_Has_Invariants (Derived_Type);
8033       end if;
8034
8035       --  We similarly inherit predicates
8036
8037       if Has_Predicates (Parent_Type) then
8038          Set_Has_Predicates (Derived_Type);
8039       end if;
8040
8041       --  The derived type inherits the representation clauses of the parent.
8042       --  However, for a private type that is completed by a derivation, there
8043       --  may be operation attributes that have been specified already (stream
8044       --  attributes and External_Tag) and those must be provided. Finally,
8045       --  if the partial view is a private extension, the representation items
8046       --  of the parent have been inherited already, and should not be chained
8047       --  twice to the derived type.
8048
8049       if Is_Tagged_Type (Parent_Type)
8050         and then Present (First_Rep_Item (Derived_Type))
8051       then
8052          --  The existing items are either operational items or items inherited
8053          --  from a private extension declaration.
8054
8055          declare
8056             Rep : Node_Id;
8057             --  Used to iterate over representation items of the derived type
8058
8059             Last_Rep : Node_Id;
8060             --  Last representation item of the (non-empty) representation
8061             --  item list of the derived type.
8062
8063             Found : Boolean := False;
8064
8065          begin
8066             Rep      := First_Rep_Item (Derived_Type);
8067             Last_Rep := Rep;
8068             while Present (Rep) loop
8069                if Rep = First_Rep_Item (Parent_Type) then
8070                   Found := True;
8071                   exit;
8072
8073                else
8074                   Rep := Next_Rep_Item (Rep);
8075
8076                   if Present (Rep) then
8077                      Last_Rep := Rep;
8078                   end if;
8079                end if;
8080             end loop;
8081
8082             --  Here if we either encountered the parent type's first rep
8083             --  item on the derived type's rep item list (in which case
8084             --  Found is True, and we have nothing else to do), or if we
8085             --  reached the last rep item of the derived type, which is
8086             --  Last_Rep, in which case we further chain the parent type's
8087             --  rep items to those of the derived type.
8088
8089             if not Found then
8090                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
8091             end if;
8092          end;
8093
8094       else
8095          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
8096       end if;
8097
8098       case Ekind (Parent_Type) is
8099          when Numeric_Kind =>
8100             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
8101
8102          when Array_Kind =>
8103             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
8104
8105          when E_Record_Type
8106             | E_Record_Subtype
8107             | Class_Wide_Kind  =>
8108             Build_Derived_Record_Type
8109               (N, Parent_Type, Derived_Type, Derive_Subps);
8110             return;
8111
8112          when Enumeration_Kind =>
8113             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
8114
8115          when Access_Kind =>
8116             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
8117
8118          when Incomplete_Or_Private_Kind =>
8119             Build_Derived_Private_Type
8120               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
8121
8122             --  For discriminated types, the derivation includes deriving
8123             --  primitive operations. For others it is done below.
8124
8125             if Is_Tagged_Type (Parent_Type)
8126               or else Has_Discriminants (Parent_Type)
8127               or else (Present (Full_View (Parent_Type))
8128                         and then Has_Discriminants (Full_View (Parent_Type)))
8129             then
8130                return;
8131             end if;
8132
8133          when Concurrent_Kind =>
8134             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
8135
8136          when others =>
8137             raise Program_Error;
8138       end case;
8139
8140       if Etype (Derived_Type) = Any_Type then
8141          return;
8142       end if;
8143
8144       --  Set delayed freeze and then derive subprograms, we need to do this
8145       --  in this order so that derived subprograms inherit the derived freeze
8146       --  if necessary.
8147
8148       Set_Has_Delayed_Freeze (Derived_Type);
8149       if Derive_Subps then
8150          Derive_Subprograms (Parent_Type, Derived_Type);
8151       end if;
8152
8153       Set_Has_Primitive_Operations
8154         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
8155    end Build_Derived_Type;
8156
8157    -----------------------
8158    -- Build_Discriminal --
8159    -----------------------
8160
8161    procedure Build_Discriminal (Discrim : Entity_Id) is
8162       D_Minal : Entity_Id;
8163       CR_Disc : Entity_Id;
8164
8165    begin
8166       --  A discriminal has the same name as the discriminant
8167
8168       D_Minal := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
8169
8170       Set_Ekind     (D_Minal, E_In_Parameter);
8171       Set_Mechanism (D_Minal, Default_Mechanism);
8172       Set_Etype     (D_Minal, Etype (Discrim));
8173       Set_Scope     (D_Minal, Current_Scope);
8174
8175       Set_Discriminal (Discrim, D_Minal);
8176       Set_Discriminal_Link (D_Minal, Discrim);
8177
8178       --  For task types, build at once the discriminants of the corresponding
8179       --  record, which are needed if discriminants are used in entry defaults
8180       --  and in family bounds.
8181
8182       if Is_Concurrent_Type (Current_Scope)
8183         or else Is_Limited_Type (Current_Scope)
8184       then
8185          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
8186
8187          Set_Ekind            (CR_Disc, E_In_Parameter);
8188          Set_Mechanism        (CR_Disc, Default_Mechanism);
8189          Set_Etype            (CR_Disc, Etype (Discrim));
8190          Set_Scope            (CR_Disc, Current_Scope);
8191          Set_Discriminal_Link (CR_Disc, Discrim);
8192          Set_CR_Discriminant  (Discrim, CR_Disc);
8193       end if;
8194    end Build_Discriminal;
8195
8196    ------------------------------------
8197    -- Build_Discriminant_Constraints --
8198    ------------------------------------
8199
8200    function Build_Discriminant_Constraints
8201      (T           : Entity_Id;
8202       Def         : Node_Id;
8203       Derived_Def : Boolean := False) return Elist_Id
8204    is
8205       C        : constant Node_Id := Constraint (Def);
8206       Nb_Discr : constant Nat     := Number_Discriminants (T);
8207
8208       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
8209       --  Saves the expression corresponding to a given discriminant in T
8210
8211       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
8212       --  Return the Position number within array Discr_Expr of a discriminant
8213       --  D within the discriminant list of the discriminated type T.
8214
8215       ------------------
8216       -- Pos_Of_Discr --
8217       ------------------
8218
8219       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
8220          Disc : Entity_Id;
8221
8222       begin
8223          Disc := First_Discriminant (T);
8224          for J in Discr_Expr'Range loop
8225             if Disc = D then
8226                return J;
8227             end if;
8228
8229             Next_Discriminant (Disc);
8230          end loop;
8231
8232          --  Note: Since this function is called on discriminants that are
8233          --  known to belong to the discriminated type, falling through the
8234          --  loop with no match signals an internal compiler error.
8235
8236          raise Program_Error;
8237       end Pos_Of_Discr;
8238
8239       --  Declarations local to Build_Discriminant_Constraints
8240
8241       Discr : Entity_Id;
8242       E     : Entity_Id;
8243       Elist : constant Elist_Id := New_Elmt_List;
8244
8245       Constr   : Node_Id;
8246       Expr     : Node_Id;
8247       Id       : Node_Id;
8248       Position : Nat;
8249       Found    : Boolean;
8250
8251       Discrim_Present : Boolean := False;
8252
8253    --  Start of processing for Build_Discriminant_Constraints
8254
8255    begin
8256       --  The following loop will process positional associations only.
8257       --  For a positional association, the (single) discriminant is
8258       --  implicitly specified by position, in textual order (RM 3.7.2).
8259
8260       Discr  := First_Discriminant (T);
8261       Constr := First (Constraints (C));
8262       for D in Discr_Expr'Range loop
8263          exit when Nkind (Constr) = N_Discriminant_Association;
8264
8265          if No (Constr) then
8266             Error_Msg_N ("too few discriminants given in constraint", C);
8267             return New_Elmt_List;
8268
8269          elsif Nkind (Constr) = N_Range
8270            or else (Nkind (Constr) = N_Attribute_Reference
8271                      and then
8272                     Attribute_Name (Constr) = Name_Range)
8273          then
8274             Error_Msg_N
8275               ("a range is not a valid discriminant constraint", Constr);
8276             Discr_Expr (D) := Error;
8277
8278          else
8279             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
8280             Discr_Expr (D) := Constr;
8281          end if;
8282
8283          Next_Discriminant (Discr);
8284          Next (Constr);
8285       end loop;
8286
8287       if No (Discr) and then Present (Constr) then
8288          Error_Msg_N ("too many discriminants given in constraint", Constr);
8289          return New_Elmt_List;
8290       end if;
8291
8292       --  Named associations can be given in any order, but if both positional
8293       --  and named associations are used in the same discriminant constraint,
8294       --  then positional associations must occur first, at their normal
8295       --  position. Hence once a named association is used, the rest of the
8296       --  discriminant constraint must use only named associations.
8297
8298       while Present (Constr) loop
8299
8300          --  Positional association forbidden after a named association
8301
8302          if Nkind (Constr) /= N_Discriminant_Association then
8303             Error_Msg_N ("positional association follows named one", Constr);
8304             return New_Elmt_List;
8305
8306          --  Otherwise it is a named association
8307
8308          else
8309             --  E records the type of the discriminants in the named
8310             --  association. All the discriminants specified in the same name
8311             --  association must have the same type.
8312
8313             E := Empty;
8314
8315             --  Search the list of discriminants in T to see if the simple name
8316             --  given in the constraint matches any of them.
8317
8318             Id := First (Selector_Names (Constr));
8319             while Present (Id) loop
8320                Found := False;
8321
8322                --  If Original_Discriminant is present, we are processing a
8323                --  generic instantiation and this is an instance node. We need
8324                --  to find the name of the corresponding discriminant in the
8325                --  actual record type T and not the name of the discriminant in
8326                --  the generic formal. Example:
8327
8328                --    generic
8329                --       type G (D : int) is private;
8330                --    package P is
8331                --       subtype W is G (D => 1);
8332                --    end package;
8333                --    type Rec (X : int) is record ... end record;
8334                --    package Q is new P (G => Rec);
8335
8336                --  At the point of the instantiation, formal type G is Rec
8337                --  and therefore when reanalyzing "subtype W is G (D => 1);"
8338                --  which really looks like "subtype W is Rec (D => 1);" at
8339                --  the point of instantiation, we want to find the discriminant
8340                --  that corresponds to D in Rec, i.e. X.
8341
8342                if Present (Original_Discriminant (Id))
8343                  and then In_Instance
8344                then
8345                   Discr := Find_Corresponding_Discriminant (Id, T);
8346                   Found := True;
8347
8348                else
8349                   Discr := First_Discriminant (T);
8350                   while Present (Discr) loop
8351                      if Chars (Discr) = Chars (Id) then
8352                         Found := True;
8353                         exit;
8354                      end if;
8355
8356                      Next_Discriminant (Discr);
8357                   end loop;
8358
8359                   if not Found then
8360                      Error_Msg_N ("& does not match any discriminant", Id);
8361                      return New_Elmt_List;
8362
8363                   --  If the parent type is a generic formal, preserve the
8364                   --  name of the discriminant for subsequent instances.
8365                   --  see comment at the beginning of this if statement.
8366
8367                   elsif Is_Generic_Type (Root_Type (T)) then
8368                      Set_Original_Discriminant (Id, Discr);
8369                   end if;
8370                end if;
8371
8372                Position := Pos_Of_Discr (T, Discr);
8373
8374                if Present (Discr_Expr (Position)) then
8375                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
8376
8377                else
8378                   --  Each discriminant specified in the same named association
8379                   --  must be associated with a separate copy of the
8380                   --  corresponding expression.
8381
8382                   if Present (Next (Id)) then
8383                      Expr := New_Copy_Tree (Expression (Constr));
8384                      Set_Parent (Expr, Parent (Expression (Constr)));
8385                   else
8386                      Expr := Expression (Constr);
8387                   end if;
8388
8389                   Discr_Expr (Position) := Expr;
8390                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
8391                end if;
8392
8393                --  A discriminant association with more than one discriminant
8394                --  name is only allowed if the named discriminants are all of
8395                --  the same type (RM 3.7.1(8)).
8396
8397                if E = Empty then
8398                   E := Base_Type (Etype (Discr));
8399
8400                elsif Base_Type (Etype (Discr)) /= E then
8401                   Error_Msg_N
8402                     ("all discriminants in an association " &
8403                      "must have the same type", Id);
8404                end if;
8405
8406                Next (Id);
8407             end loop;
8408          end if;
8409
8410          Next (Constr);
8411       end loop;
8412
8413       --  A discriminant constraint must provide exactly one value for each
8414       --  discriminant of the type (RM 3.7.1(8)).
8415
8416       for J in Discr_Expr'Range loop
8417          if No (Discr_Expr (J)) then
8418             Error_Msg_N ("too few discriminants given in constraint", C);
8419             return New_Elmt_List;
8420          end if;
8421       end loop;
8422
8423       --  Determine if there are discriminant expressions in the constraint
8424
8425       for J in Discr_Expr'Range loop
8426          if Denotes_Discriminant
8427               (Discr_Expr (J), Check_Concurrent => True)
8428          then
8429             Discrim_Present := True;
8430          end if;
8431       end loop;
8432
8433       --  Build an element list consisting of the expressions given in the
8434       --  discriminant constraint and apply the appropriate checks. The list
8435       --  is constructed after resolving any named discriminant associations
8436       --  and therefore the expressions appear in the textual order of the
8437       --  discriminants.
8438
8439       Discr := First_Discriminant (T);
8440       for J in Discr_Expr'Range loop
8441          if Discr_Expr (J) /= Error then
8442             Append_Elmt (Discr_Expr (J), Elist);
8443
8444             --  If any of the discriminant constraints is given by a
8445             --  discriminant and we are in a derived type declaration we
8446             --  have a discriminant renaming. Establish link between new
8447             --  and old discriminant.
8448
8449             if Denotes_Discriminant (Discr_Expr (J)) then
8450                if Derived_Def then
8451                   Set_Corresponding_Discriminant
8452                     (Entity (Discr_Expr (J)), Discr);
8453                end if;
8454
8455             --  Force the evaluation of non-discriminant expressions.
8456             --  If we have found a discriminant in the constraint 3.4(26)
8457             --  and 3.8(18) demand that no range checks are performed are
8458             --  after evaluation. If the constraint is for a component
8459             --  definition that has a per-object constraint, expressions are
8460             --  evaluated but not checked either. In all other cases perform
8461             --  a range check.
8462
8463             else
8464                if Discrim_Present then
8465                   null;
8466
8467                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8468                  and then
8469                    Has_Per_Object_Constraint
8470                      (Defining_Identifier (Parent (Parent (Def))))
8471                then
8472                   null;
8473
8474                elsif Is_Access_Type (Etype (Discr)) then
8475                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8476
8477                else
8478                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8479                end if;
8480
8481                Force_Evaluation (Discr_Expr (J));
8482             end if;
8483
8484             --  Check that the designated type of an access discriminant's
8485             --  expression is not a class-wide type unless the discriminant's
8486             --  designated type is also class-wide.
8487
8488             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8489               and then not Is_Class_Wide_Type
8490                          (Designated_Type (Etype (Discr)))
8491               and then Etype (Discr_Expr (J)) /= Any_Type
8492               and then Is_Class_Wide_Type
8493                          (Designated_Type (Etype (Discr_Expr (J))))
8494             then
8495                Wrong_Type (Discr_Expr (J), Etype (Discr));
8496
8497             elsif Is_Access_Type (Etype (Discr))
8498               and then not Is_Access_Constant (Etype (Discr))
8499               and then Is_Access_Type (Etype (Discr_Expr (J)))
8500               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8501             then
8502                Error_Msg_NE
8503                  ("constraint for discriminant& must be access to variable",
8504                     Def, Discr);
8505             end if;
8506          end if;
8507
8508          Next_Discriminant (Discr);
8509       end loop;
8510
8511       return Elist;
8512    end Build_Discriminant_Constraints;
8513
8514    ---------------------------------
8515    -- Build_Discriminated_Subtype --
8516    ---------------------------------
8517
8518    procedure Build_Discriminated_Subtype
8519      (T           : Entity_Id;
8520       Def_Id      : Entity_Id;
8521       Elist       : Elist_Id;
8522       Related_Nod : Node_Id;
8523       For_Access  : Boolean := False)
8524    is
8525       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8526       Constrained : constant Boolean :=
8527                       (Has_Discrs
8528                          and then not Is_Empty_Elmt_List (Elist)
8529                          and then not Is_Class_Wide_Type (T))
8530                         or else Is_Constrained (T);
8531
8532    begin
8533       if Ekind (T) = E_Record_Type then
8534          if For_Access then
8535             Set_Ekind (Def_Id, E_Private_Subtype);
8536             Set_Is_For_Access_Subtype (Def_Id, True);
8537          else
8538             Set_Ekind (Def_Id, E_Record_Subtype);
8539          end if;
8540
8541          --  Inherit preelaboration flag from base, for types for which it
8542          --  may have been set: records, private types, protected types.
8543
8544          Set_Known_To_Have_Preelab_Init
8545            (Def_Id, Known_To_Have_Preelab_Init (T));
8546
8547       elsif Ekind (T) = E_Task_Type then
8548          Set_Ekind (Def_Id, E_Task_Subtype);
8549
8550       elsif Ekind (T) = E_Protected_Type then
8551          Set_Ekind (Def_Id, E_Protected_Subtype);
8552          Set_Known_To_Have_Preelab_Init
8553            (Def_Id, Known_To_Have_Preelab_Init (T));
8554
8555       elsif Is_Private_Type (T) then
8556          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8557          Set_Known_To_Have_Preelab_Init
8558            (Def_Id, Known_To_Have_Preelab_Init (T));
8559
8560       elsif Is_Class_Wide_Type (T) then
8561          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8562
8563       else
8564          --  Incomplete type. Attach subtype to list of dependents, to be
8565          --  completed with full view of parent type,  unless is it the
8566          --  designated subtype of a record component within an init_proc.
8567          --  This last case arises for a component of an access type whose
8568          --  designated type is incomplete (e.g. a Taft Amendment type).
8569          --  The designated subtype is within an inner scope, and needs no
8570          --  elaboration, because only the access type is needed in the
8571          --  initialization procedure.
8572
8573          Set_Ekind (Def_Id, Ekind (T));
8574
8575          if For_Access and then Within_Init_Proc then
8576             null;
8577          else
8578             Append_Elmt (Def_Id, Private_Dependents (T));
8579          end if;
8580       end if;
8581
8582       Set_Etype             (Def_Id, T);
8583       Init_Size_Align       (Def_Id);
8584       Set_Has_Discriminants (Def_Id, Has_Discrs);
8585       Set_Is_Constrained    (Def_Id, Constrained);
8586
8587       Set_First_Entity      (Def_Id, First_Entity   (T));
8588       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8589
8590       --  If the subtype is the completion of a private declaration, there may
8591       --  have been representation clauses for the partial view, and they must
8592       --  be preserved. Build_Derived_Type chains the inherited clauses with
8593       --  the ones appearing on the extension. If this comes from a subtype
8594       --  declaration, all clauses are inherited.
8595
8596       if No (First_Rep_Item (Def_Id)) then
8597          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8598       end if;
8599
8600       if Is_Tagged_Type (T) then
8601          Set_Is_Tagged_Type (Def_Id);
8602          Make_Class_Wide_Type (Def_Id);
8603       end if;
8604
8605       Set_Stored_Constraint (Def_Id, No_Elist);
8606
8607       if Has_Discrs then
8608          Set_Discriminant_Constraint (Def_Id, Elist);
8609          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8610       end if;
8611
8612       if Is_Tagged_Type (T) then
8613
8614          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8615          --  concurrent record type (which has the list of primitive
8616          --  operations).
8617
8618          if Ada_Version >= Ada_2005
8619            and then Is_Concurrent_Type (T)
8620          then
8621             Set_Corresponding_Record_Type (Def_Id,
8622                Corresponding_Record_Type (T));
8623          else
8624             Set_Direct_Primitive_Operations (Def_Id,
8625               Direct_Primitive_Operations (T));
8626          end if;
8627
8628          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8629       end if;
8630
8631       --  Subtypes introduced by component declarations do not need to be
8632       --  marked as delayed, and do not get freeze nodes, because the semantics
8633       --  verifies that the parents of the subtypes are frozen before the
8634       --  enclosing record is frozen.
8635
8636       if not Is_Type (Scope (Def_Id)) then
8637          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8638
8639          if Is_Private_Type (T)
8640            and then Present (Full_View (T))
8641          then
8642             Conditional_Delay (Def_Id, Full_View (T));
8643          else
8644             Conditional_Delay (Def_Id, T);
8645          end if;
8646       end if;
8647
8648       if Is_Record_Type (T) then
8649          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8650
8651          if Has_Discrs
8652             and then not Is_Empty_Elmt_List (Elist)
8653             and then not For_Access
8654          then
8655             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8656          elsif not For_Access then
8657             Set_Cloned_Subtype (Def_Id, T);
8658          end if;
8659       end if;
8660    end Build_Discriminated_Subtype;
8661
8662    ---------------------------
8663    -- Build_Itype_Reference --
8664    ---------------------------
8665
8666    procedure Build_Itype_Reference
8667      (Ityp : Entity_Id;
8668       Nod  : Node_Id)
8669    is
8670       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8671    begin
8672
8673       --  Itype references are only created for use by the back-end
8674
8675       if Inside_A_Generic then
8676          return;
8677       else
8678          Set_Itype (IR, Ityp);
8679          Insert_After (Nod, IR);
8680       end if;
8681    end Build_Itype_Reference;
8682
8683    ------------------------
8684    -- Build_Scalar_Bound --
8685    ------------------------
8686
8687    function Build_Scalar_Bound
8688      (Bound : Node_Id;
8689       Par_T : Entity_Id;
8690       Der_T : Entity_Id) return Node_Id
8691    is
8692       New_Bound : Entity_Id;
8693
8694    begin
8695       --  Note: not clear why this is needed, how can the original bound
8696       --  be unanalyzed at this point? and if it is, what business do we
8697       --  have messing around with it? and why is the base type of the
8698       --  parent type the right type for the resolution. It probably is
8699       --  not! It is OK for the new bound we are creating, but not for
8700       --  the old one??? Still if it never happens, no problem!
8701
8702       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8703
8704       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8705          New_Bound := New_Copy (Bound);
8706          Set_Etype (New_Bound, Der_T);
8707          Set_Analyzed (New_Bound);
8708
8709       elsif Is_Entity_Name (Bound) then
8710          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8711
8712       --  The following is almost certainly wrong. What business do we have
8713       --  relocating a node (Bound) that is presumably still attached to
8714       --  the tree elsewhere???
8715
8716       else
8717          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8718       end if;
8719
8720       Set_Etype (New_Bound, Der_T);
8721       return New_Bound;
8722    end Build_Scalar_Bound;
8723
8724    --------------------------------
8725    -- Build_Underlying_Full_View --
8726    --------------------------------
8727
8728    procedure Build_Underlying_Full_View
8729      (N   : Node_Id;
8730       Typ : Entity_Id;
8731       Par : Entity_Id)
8732    is
8733       Loc  : constant Source_Ptr := Sloc (N);
8734       Subt : constant Entity_Id :=
8735                Make_Defining_Identifier
8736                  (Loc, New_External_Name (Chars (Typ), 'S'));
8737
8738       Constr : Node_Id;
8739       Indic  : Node_Id;
8740       C      : Node_Id;
8741       Id     : Node_Id;
8742
8743       procedure Set_Discriminant_Name (Id : Node_Id);
8744       --  If the derived type has discriminants, they may rename discriminants
8745       --  of the parent. When building the full view of the parent, we need to
8746       --  recover the names of the original discriminants if the constraint is
8747       --  given by named associations.
8748
8749       ---------------------------
8750       -- Set_Discriminant_Name --
8751       ---------------------------
8752
8753       procedure Set_Discriminant_Name (Id : Node_Id) is
8754          Disc : Entity_Id;
8755
8756       begin
8757          Set_Original_Discriminant (Id, Empty);
8758
8759          if Has_Discriminants (Typ) then
8760             Disc := First_Discriminant (Typ);
8761             while Present (Disc) loop
8762                if Chars (Disc) = Chars (Id)
8763                  and then Present (Corresponding_Discriminant (Disc))
8764                then
8765                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
8766                end if;
8767                Next_Discriminant (Disc);
8768             end loop;
8769          end if;
8770       end Set_Discriminant_Name;
8771
8772    --  Start of processing for Build_Underlying_Full_View
8773
8774    begin
8775       if Nkind (N) = N_Full_Type_Declaration then
8776          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
8777
8778       elsif Nkind (N) = N_Subtype_Declaration then
8779          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
8780
8781       elsif Nkind (N) = N_Component_Declaration then
8782          Constr :=
8783            New_Copy_Tree
8784              (Constraint (Subtype_Indication (Component_Definition (N))));
8785
8786       else
8787          raise Program_Error;
8788       end if;
8789
8790       C := First (Constraints (Constr));
8791       while Present (C) loop
8792          if Nkind (C) = N_Discriminant_Association then
8793             Id := First (Selector_Names (C));
8794             while Present (Id) loop
8795                Set_Discriminant_Name (Id);
8796                Next (Id);
8797             end loop;
8798          end if;
8799
8800          Next (C);
8801       end loop;
8802
8803       Indic :=
8804         Make_Subtype_Declaration (Loc,
8805           Defining_Identifier => Subt,
8806           Subtype_Indication  =>
8807             Make_Subtype_Indication (Loc,
8808               Subtype_Mark => New_Reference_To (Par, Loc),
8809               Constraint   => New_Copy_Tree (Constr)));
8810
8811       --  If this is a component subtype for an outer itype, it is not
8812       --  a list member, so simply set the parent link for analysis: if
8813       --  the enclosing type does not need to be in a declarative list,
8814       --  neither do the components.
8815
8816       if Is_List_Member (N)
8817         and then Nkind (N) /= N_Component_Declaration
8818       then
8819          Insert_Before (N, Indic);
8820       else
8821          Set_Parent (Indic, Parent (N));
8822       end if;
8823
8824       Analyze (Indic);
8825       Set_Underlying_Full_View (Typ, Full_View (Subt));
8826    end Build_Underlying_Full_View;
8827
8828    -------------------------------
8829    -- Check_Abstract_Overriding --
8830    -------------------------------
8831
8832    procedure Check_Abstract_Overriding (T : Entity_Id) is
8833       Alias_Subp : Entity_Id;
8834       Elmt       : Elmt_Id;
8835       Op_List    : Elist_Id;
8836       Subp       : Entity_Id;
8837       Type_Def   : Node_Id;
8838
8839       procedure Check_Pragma_Implemented (Subp : Entity_Id);
8840       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
8841       --  which has pragma Implemented already set. Check whether Subp's entity
8842       --  kind conforms to the implementation kind of the overridden routine.
8843
8844       procedure Check_Pragma_Implemented
8845         (Subp       : Entity_Id;
8846          Iface_Subp : Entity_Id);
8847       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
8848       --  Iface_Subp and both entities have pragma Implemented already set on
8849       --  them. Check whether the two implementation kinds are conforming.
8850
8851       procedure Inherit_Pragma_Implemented
8852         (Subp       : Entity_Id;
8853          Iface_Subp : Entity_Id);
8854       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
8855       --  subprogram Iface_Subp which has been marked by pragma Implemented.
8856       --  Propagate the implementation kind of Iface_Subp to Subp.
8857
8858       ------------------------------
8859       -- Check_Pragma_Implemented --
8860       ------------------------------
8861
8862       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
8863          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
8864          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
8865          Contr_Typ   : Entity_Id;
8866
8867       begin
8868          --  Subp must have an alias since it is a hidden entity used to link
8869          --  an interface subprogram to its overriding counterpart.
8870
8871          pragma Assert (Present (Alias (Subp)));
8872
8873          --  Extract the type of the controlling formal
8874
8875          Contr_Typ := Etype (First_Formal (Alias (Subp)));
8876
8877          if Is_Concurrent_Record_Type (Contr_Typ) then
8878             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
8879          end if;
8880
8881          --  An interface subprogram whose implementation kind is By_Entry must
8882          --  be implemented by an entry.
8883
8884          if Impl_Kind = Name_By_Entry
8885            and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Entry
8886          then
8887             Error_Msg_Node_2 := Iface_Alias;
8888             Error_Msg_NE
8889               ("type & must implement abstract subprogram & with an entry",
8890                Alias (Subp), Contr_Typ);
8891
8892          elsif Impl_Kind = Name_By_Protected_Procedure then
8893
8894             --  An interface subprogram whose implementation kind is By_
8895             --  Protected_Procedure cannot be implemented by a primitive
8896             --  procedure of a task type.
8897
8898             if Ekind (Contr_Typ) /= E_Protected_Type then
8899                Error_Msg_Node_2 := Contr_Typ;
8900                Error_Msg_NE
8901                  ("interface subprogram & cannot be implemented by a " &
8902                   "primitive procedure of task type &", Alias (Subp),
8903                   Iface_Alias);
8904
8905             --  An interface subprogram whose implementation kind is By_
8906             --  Protected_Procedure must be implemented by a procedure.
8907
8908             elsif Is_Primitive_Wrapper (Alias (Subp))
8909               and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Procedure
8910             then
8911                Error_Msg_Node_2 := Iface_Alias;
8912                Error_Msg_NE
8913                  ("type & must implement abstract subprogram & with a " &
8914                   "procedure", Alias (Subp), Contr_Typ);
8915             end if;
8916          end if;
8917       end Check_Pragma_Implemented;
8918
8919       ------------------------------
8920       -- Check_Pragma_Implemented --
8921       ------------------------------
8922
8923       procedure Check_Pragma_Implemented
8924         (Subp       : Entity_Id;
8925          Iface_Subp : Entity_Id)
8926       is
8927          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
8928          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
8929
8930       begin
8931          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
8932          --  and overriding subprogram are different. In general this is an
8933          --  error except when the implementation kind of the overridden
8934          --  subprograms is By_Any.
8935
8936          if Iface_Kind /= Subp_Kind
8937            and then Iface_Kind /= Name_By_Any
8938          then
8939             if Iface_Kind = Name_By_Entry then
8940                Error_Msg_N
8941                  ("incompatible implementation kind, overridden subprogram " &
8942                   "is marked By_Entry", Subp);
8943             else
8944                Error_Msg_N
8945                  ("incompatible implementation kind, overridden subprogram " &
8946                   "is marked By_Protected_Procedure", Subp);
8947             end if;
8948          end if;
8949       end Check_Pragma_Implemented;
8950
8951       --------------------------------
8952       -- Inherit_Pragma_Implemented --
8953       --------------------------------
8954
8955       procedure Inherit_Pragma_Implemented
8956         (Subp       : Entity_Id;
8957          Iface_Subp : Entity_Id)
8958       is
8959          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
8960          Loc        : constant Source_Ptr := Sloc (Subp);
8961          Impl_Prag  : Node_Id;
8962
8963       begin
8964          --  Since the implementation kind is stored as a representation item
8965          --  rather than a flag, create a pragma node.
8966
8967          Impl_Prag :=
8968            Make_Pragma (Loc,
8969              Chars => Name_Implemented,
8970              Pragma_Argument_Associations => New_List (
8971                Make_Pragma_Argument_Association (Loc,
8972                  Expression =>
8973                    New_Reference_To (Subp, Loc)),
8974
8975                Make_Pragma_Argument_Association (Loc,
8976                  Expression => Make_Identifier (Loc, Iface_Kind))));
8977
8978          --  The pragma doesn't need to be analyzed because it is internally
8979          --  build. It is safe to directly register it as a rep item since we
8980          --  are only interested in the characters of the implementation kind.
8981
8982          Record_Rep_Item (Subp, Impl_Prag);
8983       end Inherit_Pragma_Implemented;
8984
8985    --  Start of processing for Check_Abstract_Overriding
8986
8987    begin
8988       Op_List := Primitive_Operations (T);
8989
8990       --  Loop to check primitive operations
8991
8992       Elmt := First_Elmt (Op_List);
8993       while Present (Elmt) loop
8994          Subp := Node (Elmt);
8995          Alias_Subp := Alias (Subp);
8996
8997          --  Inherited subprograms are identified by the fact that they do not
8998          --  come from source, and the associated source location is the
8999          --  location of the first subtype of the derived type.
9000
9001          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
9002          --  subprograms that "require overriding".
9003
9004          --  Special exception, do not complain about failure to override the
9005          --  stream routines _Input and _Output, as well as the primitive
9006          --  operations used in dispatching selects since we always provide
9007          --  automatic overridings for these subprograms.
9008
9009          --  Also ignore this rule for convention CIL since .NET libraries
9010          --  do bizarre things with interfaces???
9011
9012          --  The partial view of T may have been a private extension, for
9013          --  which inherited functions dispatching on result are abstract.
9014          --  If the full view is a null extension, there is no need for
9015          --  overriding in Ada2005, but wrappers need to be built for them
9016          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
9017
9018          if Is_Null_Extension (T)
9019            and then Has_Controlling_Result (Subp)
9020            and then Ada_Version >= Ada_2005
9021            and then Present (Alias_Subp)
9022            and then not Comes_From_Source (Subp)
9023            and then not Is_Abstract_Subprogram (Alias_Subp)
9024            and then not Is_Access_Type (Etype (Subp))
9025          then
9026             null;
9027
9028          --  Ada 2005 (AI-251): Internal entities of interfaces need no
9029          --  processing because this check is done with the aliased
9030          --  entity
9031
9032          elsif Present (Interface_Alias (Subp)) then
9033             null;
9034
9035          elsif (Is_Abstract_Subprogram (Subp)
9036                  or else Requires_Overriding (Subp)
9037                  or else
9038                    (Has_Controlling_Result (Subp)
9039                      and then Present (Alias_Subp)
9040                      and then not Comes_From_Source (Subp)
9041                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
9042            and then not Is_TSS (Subp, TSS_Stream_Input)
9043            and then not Is_TSS (Subp, TSS_Stream_Output)
9044            and then not Is_Abstract_Type (T)
9045            and then Convention (T) /= Convention_CIL
9046            and then not Is_Predefined_Interface_Primitive (Subp)
9047
9048             --  Ada 2005 (AI-251): Do not consider hidden entities associated
9049             --  with abstract interface types because the check will be done
9050             --  with the aliased entity (otherwise we generate a duplicated
9051             --  error message).
9052
9053            and then not Present (Interface_Alias (Subp))
9054          then
9055             if Present (Alias_Subp) then
9056
9057                --  Only perform the check for a derived subprogram when the
9058                --  type has an explicit record extension. This avoids incorrect
9059                --  flagging of abstract subprograms for the case of a type
9060                --  without an extension that is derived from a formal type
9061                --  with a tagged actual (can occur within a private part).
9062
9063                --  Ada 2005 (AI-391): In the case of an inherited function with
9064                --  a controlling result of the type, the rule does not apply if
9065                --  the type is a null extension (unless the parent function
9066                --  itself is abstract, in which case the function must still be
9067                --  be overridden). The expander will generate an overriding
9068                --  wrapper function calling the parent subprogram (see
9069                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
9070
9071                Type_Def := Type_Definition (Parent (T));
9072
9073                if Nkind (Type_Def) = N_Derived_Type_Definition
9074                  and then Present (Record_Extension_Part (Type_Def))
9075                  and then
9076                    (Ada_Version < Ada_2005
9077                       or else not Is_Null_Extension (T)
9078                       or else Ekind (Subp) = E_Procedure
9079                       or else not Has_Controlling_Result (Subp)
9080                       or else Is_Abstract_Subprogram (Alias_Subp)
9081                       or else Requires_Overriding (Subp)
9082                       or else Is_Access_Type (Etype (Subp)))
9083                then
9084                   --  Avoid reporting error in case of abstract predefined
9085                   --  primitive inherited from interface type because the
9086                   --  body of internally generated predefined primitives
9087                   --  of tagged types are generated later by Freeze_Type
9088
9089                   if Is_Interface (Root_Type (T))
9090                     and then Is_Abstract_Subprogram (Subp)
9091                     and then Is_Predefined_Dispatching_Operation (Subp)
9092                     and then not Comes_From_Source (Ultimate_Alias (Subp))
9093                   then
9094                      null;
9095
9096                   else
9097                      Error_Msg_NE
9098                        ("type must be declared abstract or & overridden",
9099                         T, Subp);
9100
9101                      --  Traverse the whole chain of aliased subprograms to
9102                      --  complete the error notification. This is especially
9103                      --  useful for traceability of the chain of entities when
9104                      --  the subprogram corresponds with an interface
9105                      --  subprogram (which may be defined in another package).
9106
9107                      if Present (Alias_Subp) then
9108                         declare
9109                            E : Entity_Id;
9110
9111                         begin
9112                            E := Subp;
9113                            while Present (Alias (E)) loop
9114                               Error_Msg_Sloc := Sloc (E);
9115                               Error_Msg_NE
9116                                 ("\& has been inherited #", T, Subp);
9117                               E := Alias (E);
9118                            end loop;
9119
9120                            Error_Msg_Sloc := Sloc (E);
9121
9122                            --  AI05-0068: report if there is an overriding
9123                            --  non-abstract subprogram that is invisible.
9124
9125                            if Is_Hidden (E)
9126                              and then not Is_Abstract_Subprogram (E)
9127                            then
9128                               Error_Msg_NE
9129                                 ("\& subprogram# is not visible",
9130                                  T, Subp);
9131
9132                            else
9133                               Error_Msg_NE
9134                                 ("\& has been inherited from subprogram #",
9135                                  T, Subp);
9136                            end if;
9137                         end;
9138                      end if;
9139                   end if;
9140
9141                --  Ada 2005 (AI-345): Protected or task type implementing
9142                --  abstract interfaces.
9143
9144                elsif Is_Concurrent_Record_Type (T)
9145                  and then Present (Interfaces (T))
9146                then
9147                   --  The controlling formal of Subp must be of mode "out",
9148                   --  "in out" or an access-to-variable to be overridden.
9149
9150                   --  Error message below needs rewording (remember comma
9151                   --  in -gnatj mode) ???
9152
9153                   if Ekind (First_Formal (Subp)) = E_In_Parameter
9154                     and then Ekind (Subp) /= E_Function
9155                   then
9156                      if not Is_Predefined_Dispatching_Operation (Subp) then
9157                         Error_Msg_NE
9158                           ("first formal of & must be of mode `OUT`, " &
9159                            "`IN OUT` or access-to-variable", T, Subp);
9160                         Error_Msg_N
9161                           ("\to be overridden by protected procedure or " &
9162                            "entry (RM 9.4(11.9/2))", T);
9163                      end if;
9164
9165                   --  Some other kind of overriding failure
9166
9167                   else
9168                      Error_Msg_NE
9169                        ("interface subprogram & must be overridden",
9170                         T, Subp);
9171
9172                      --  Examine primitive operations of synchronized type,
9173                      --  to find homonyms that have the wrong profile.
9174
9175                      declare
9176                         Prim : Entity_Id;
9177
9178                      begin
9179                         Prim :=
9180                           First_Entity (Corresponding_Concurrent_Type (T));
9181                         while Present (Prim) loop
9182                            if Chars (Prim) = Chars (Subp) then
9183                               Error_Msg_NE
9184                                 ("profile is not type conformant with "
9185                                    & "prefixed view profile of "
9186                                    & "inherited operation&", Prim, Subp);
9187                            end if;
9188
9189                            Next_Entity (Prim);
9190                         end loop;
9191                      end;
9192                   end if;
9193                end if;
9194
9195             else
9196                Error_Msg_Node_2 := T;
9197                Error_Msg_N
9198                  ("abstract subprogram& not allowed for type&", Subp);
9199
9200                --  Also post unconditional warning on the type (unconditional
9201                --  so that if there are more than one of these cases, we get
9202                --  them all, and not just the first one).
9203
9204                Error_Msg_Node_2 := Subp;
9205                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
9206             end if;
9207          end if;
9208
9209          --  Ada 2012 (AI05-0030): Perform some checks related to pragma
9210          --  Implemented
9211
9212          --  Subp is an expander-generated procedure which maps an interface
9213          --  alias to a protected wrapper. The interface alias is flagged by
9214          --  pragma Implemented. Ensure that Subp is a procedure when the
9215          --  implementation kind is By_Protected_Procedure or an entry when
9216          --  By_Entry.
9217
9218          if Ada_Version >= Ada_2012
9219            and then Is_Hidden (Subp)
9220            and then Present (Interface_Alias (Subp))
9221            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
9222          then
9223             Check_Pragma_Implemented (Subp);
9224          end if;
9225
9226          --  Subp is an interface primitive which overrides another interface
9227          --  primitive marked with pragma Implemented.
9228
9229          if Ada_Version >= Ada_2012
9230            and then Present (Overridden_Operation (Subp))
9231            and then Has_Rep_Pragma
9232                       (Overridden_Operation (Subp), Name_Implemented)
9233          then
9234             --  If the overriding routine is also marked by Implemented, check
9235             --  that the two implementation kinds are conforming.
9236
9237             if Has_Rep_Pragma (Subp, Name_Implemented) then
9238                Check_Pragma_Implemented
9239                  (Subp       => Subp,
9240                   Iface_Subp => Overridden_Operation (Subp));
9241
9242             --  Otherwise the overriding routine inherits the implementation
9243             --  kind from the overridden subprogram.
9244
9245             else
9246                Inherit_Pragma_Implemented
9247                  (Subp       => Subp,
9248                   Iface_Subp => Overridden_Operation (Subp));
9249             end if;
9250          end if;
9251
9252          Next_Elmt (Elmt);
9253       end loop;
9254    end Check_Abstract_Overriding;
9255
9256    ------------------------------------------------
9257    -- Check_Access_Discriminant_Requires_Limited --
9258    ------------------------------------------------
9259
9260    procedure Check_Access_Discriminant_Requires_Limited
9261      (D   : Node_Id;
9262       Loc : Node_Id)
9263    is
9264    begin
9265       --  A discriminant_specification for an access discriminant shall appear
9266       --  only in the declaration for a task or protected type, or for a type
9267       --  with the reserved word 'limited' in its definition or in one of its
9268       --  ancestors (RM 3.7(10)).
9269
9270       --  AI-0063: The proper condition is that type must be immutably limited,
9271       --  or else be a partial view.
9272
9273       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
9274          if Is_Immutably_Limited_Type (Current_Scope)
9275            or else
9276              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
9277                and then Limited_Present (Parent (Current_Scope)))
9278          then
9279             null;
9280
9281          else
9282             Error_Msg_N
9283               ("access discriminants allowed only for limited types", Loc);
9284          end if;
9285       end if;
9286    end Check_Access_Discriminant_Requires_Limited;
9287
9288    -----------------------------------
9289    -- Check_Aliased_Component_Types --
9290    -----------------------------------
9291
9292    procedure Check_Aliased_Component_Types (T : Entity_Id) is
9293       C : Entity_Id;
9294
9295    begin
9296       --  ??? Also need to check components of record extensions, but not
9297       --  components of protected types (which are always limited).
9298
9299       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
9300       --  types to be unconstrained. This is safe because it is illegal to
9301       --  create access subtypes to such types with explicit discriminant
9302       --  constraints.
9303
9304       if not Is_Limited_Type (T) then
9305          if Ekind (T) = E_Record_Type then
9306             C := First_Component (T);
9307             while Present (C) loop
9308                if Is_Aliased (C)
9309                  and then Has_Discriminants (Etype (C))
9310                  and then not Is_Constrained (Etype (C))
9311                  and then not In_Instance_Body
9312                  and then Ada_Version < Ada_2005
9313                then
9314                   Error_Msg_N
9315                     ("aliased component must be constrained (RM 3.6(11))",
9316                       C);
9317                end if;
9318
9319                Next_Component (C);
9320             end loop;
9321
9322          elsif Ekind (T) = E_Array_Type then
9323             if Has_Aliased_Components (T)
9324               and then Has_Discriminants (Component_Type (T))
9325               and then not Is_Constrained (Component_Type (T))
9326               and then not In_Instance_Body
9327               and then Ada_Version < Ada_2005
9328             then
9329                Error_Msg_N
9330                  ("aliased component type must be constrained (RM 3.6(11))",
9331                     T);
9332             end if;
9333          end if;
9334       end if;
9335    end Check_Aliased_Component_Types;
9336
9337    ----------------------
9338    -- Check_Completion --
9339    ----------------------
9340
9341    procedure Check_Completion (Body_Id : Node_Id := Empty) is
9342       E : Entity_Id;
9343
9344       procedure Post_Error;
9345       --  Post error message for lack of completion for entity E
9346
9347       ----------------
9348       -- Post_Error --
9349       ----------------
9350
9351       procedure Post_Error is
9352
9353          procedure Missing_Body;
9354          --  Output missing body message
9355
9356          ------------------
9357          -- Missing_Body --
9358          ------------------
9359
9360          procedure Missing_Body is
9361          begin
9362             --  Spec is in same unit, so we can post on spec
9363
9364             if In_Same_Source_Unit (Body_Id, E) then
9365                Error_Msg_N ("missing body for &", E);
9366
9367             --  Spec is in a separate unit, so we have to post on the body
9368
9369             else
9370                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
9371             end if;
9372          end Missing_Body;
9373
9374       --  Start of processing for Post_Error
9375
9376       begin
9377          if not Comes_From_Source (E) then
9378
9379             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
9380                --  It may be an anonymous protected type created for a
9381                --  single variable. Post error on variable, if present.
9382
9383                declare
9384                   Var : Entity_Id;
9385
9386                begin
9387                   Var := First_Entity (Current_Scope);
9388                   while Present (Var) loop
9389                      exit when Etype (Var) = E
9390                        and then Comes_From_Source (Var);
9391
9392                      Next_Entity (Var);
9393                   end loop;
9394
9395                   if Present (Var) then
9396                      E := Var;
9397                   end if;
9398                end;
9399             end if;
9400          end if;
9401
9402          --  If a generated entity has no completion, then either previous
9403          --  semantic errors have disabled the expansion phase, or else we had
9404          --  missing subunits, or else we are compiling without expansion,
9405          --  or else something is very wrong.
9406
9407          if not Comes_From_Source (E) then
9408             pragma Assert
9409               (Serious_Errors_Detected > 0
9410                 or else Configurable_Run_Time_Violations > 0
9411                 or else Subunits_Missing
9412                 or else not Expander_Active);
9413             return;
9414
9415          --  Here for source entity
9416
9417          else
9418             --  Here if no body to post the error message, so we post the error
9419             --  on the declaration that has no completion. This is not really
9420             --  the right place to post it, think about this later ???
9421
9422             if No (Body_Id) then
9423                if Is_Type (E) then
9424                   Error_Msg_NE
9425                     ("missing full declaration for }", Parent (E), E);
9426                else
9427                   Error_Msg_NE ("missing body for &", Parent (E), E);
9428                end if;
9429
9430             --  Package body has no completion for a declaration that appears
9431             --  in the corresponding spec. Post error on the body, with a
9432             --  reference to the non-completed declaration.
9433
9434             else
9435                Error_Msg_Sloc := Sloc (E);
9436
9437                if Is_Type (E) then
9438                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
9439
9440                elsif Is_Overloadable (E)
9441                  and then Current_Entity_In_Scope (E) /= E
9442                then
9443                   --  It may be that the completion is mistyped and appears as
9444                   --  a distinct overloading of the entity.
9445
9446                   declare
9447                      Candidate : constant Entity_Id :=
9448                                    Current_Entity_In_Scope (E);
9449                      Decl      : constant Node_Id :=
9450                                    Unit_Declaration_Node (Candidate);
9451
9452                   begin
9453                      if Is_Overloadable (Candidate)
9454                        and then Ekind (Candidate) = Ekind (E)
9455                        and then Nkind (Decl) = N_Subprogram_Body
9456                        and then Acts_As_Spec (Decl)
9457                      then
9458                         Check_Type_Conformant (Candidate, E);
9459
9460                      else
9461                         Missing_Body;
9462                      end if;
9463                   end;
9464
9465                else
9466                   Missing_Body;
9467                end if;
9468             end if;
9469          end if;
9470       end Post_Error;
9471
9472    --  Start of processing for Check_Completion
9473
9474    begin
9475       E := First_Entity (Current_Scope);
9476       while Present (E) loop
9477          if Is_Intrinsic_Subprogram (E) then
9478             null;
9479
9480          --  The following situation requires special handling: a child unit
9481          --  that appears in the context clause of the body of its parent:
9482
9483          --    procedure Parent.Child (...);
9484
9485          --    with Parent.Child;
9486          --    package body Parent is
9487
9488          --  Here Parent.Child appears as a local entity, but should not be
9489          --  flagged as requiring completion, because it is a compilation
9490          --  unit.
9491
9492          --  Ignore missing completion for a subprogram that does not come from
9493          --  source (including the _Call primitive operation of RAS types,
9494          --  which has to have the flag Comes_From_Source for other purposes):
9495          --  we assume that the expander will provide the missing completion.
9496          --  In case of previous errors, other expansion actions that provide
9497          --  bodies for null procedures with not be invoked, so inhibit message
9498          --  in those cases.
9499          --  Note that E_Operator is not in the list that follows, because
9500          --  this kind is reserved for predefined operators, that are
9501          --  intrinsic and do not need completion.
9502
9503          elsif     Ekind (E) = E_Function
9504            or else Ekind (E) = E_Procedure
9505            or else Ekind (E) = E_Generic_Function
9506            or else Ekind (E) = E_Generic_Procedure
9507          then
9508             if Has_Completion (E) then
9509                null;
9510
9511             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
9512                null;
9513
9514             elsif Is_Subprogram (E)
9515               and then (not Comes_From_Source (E)
9516                           or else Chars (E) = Name_uCall)
9517             then
9518                null;
9519
9520             elsif
9521                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
9522             then
9523                null;
9524
9525             elsif Nkind (Parent (E)) = N_Procedure_Specification
9526               and then Null_Present (Parent (E))
9527               and then Serious_Errors_Detected > 0
9528             then
9529                null;
9530
9531             else
9532                Post_Error;
9533             end if;
9534
9535          elsif Is_Entry (E) then
9536             if not Has_Completion (E) and then
9537               (Ekind (Scope (E)) = E_Protected_Object
9538                 or else Ekind (Scope (E)) = E_Protected_Type)
9539             then
9540                Post_Error;
9541             end if;
9542
9543          elsif Is_Package_Or_Generic_Package (E) then
9544             if Unit_Requires_Body (E) then
9545                if not Has_Completion (E)
9546                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
9547                                                        N_Compilation_Unit
9548                then
9549                   Post_Error;
9550                end if;
9551
9552             elsif not Is_Child_Unit (E) then
9553                May_Need_Implicit_Body (E);
9554             end if;
9555
9556          elsif Ekind (E) = E_Incomplete_Type
9557            and then No (Underlying_Type (E))
9558          then
9559             Post_Error;
9560
9561          elsif (Ekind (E) = E_Task_Type or else
9562                 Ekind (E) = E_Protected_Type)
9563            and then not Has_Completion (E)
9564          then
9565             Post_Error;
9566
9567          --  A single task declared in the current scope is a constant, verify
9568          --  that the body of its anonymous type is in the same scope. If the
9569          --  task is defined elsewhere, this may be a renaming declaration for
9570          --  which no completion is needed.
9571
9572          elsif Ekind (E) = E_Constant
9573            and then Ekind (Etype (E)) = E_Task_Type
9574            and then not Has_Completion (Etype (E))
9575            and then Scope (Etype (E)) = Current_Scope
9576          then
9577             Post_Error;
9578
9579          elsif Ekind (E) = E_Protected_Object
9580            and then not Has_Completion (Etype (E))
9581          then
9582             Post_Error;
9583
9584          elsif Ekind (E) = E_Record_Type then
9585             if Is_Tagged_Type (E) then
9586                Check_Abstract_Overriding (E);
9587                Check_Conventions (E);
9588             end if;
9589
9590             Check_Aliased_Component_Types (E);
9591
9592          elsif Ekind (E) = E_Array_Type then
9593             Check_Aliased_Component_Types (E);
9594
9595          end if;
9596
9597          Next_Entity (E);
9598       end loop;
9599    end Check_Completion;
9600
9601    ----------------------------
9602    -- Check_Delta_Expression --
9603    ----------------------------
9604
9605    procedure Check_Delta_Expression (E : Node_Id) is
9606    begin
9607       if not (Is_Real_Type (Etype (E))) then
9608          Wrong_Type (E, Any_Real);
9609
9610       elsif not Is_OK_Static_Expression (E) then
9611          Flag_Non_Static_Expr
9612            ("non-static expression used for delta value!", E);
9613
9614       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9615          Error_Msg_N ("delta expression must be positive", E);
9616
9617       else
9618          return;
9619       end if;
9620
9621       --  If any of above errors occurred, then replace the incorrect
9622       --  expression by the real 0.1, which should prevent further errors.
9623
9624       Rewrite (E,
9625         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9626       Analyze_And_Resolve (E, Standard_Float);
9627    end Check_Delta_Expression;
9628
9629    -----------------------------
9630    -- Check_Digits_Expression --
9631    -----------------------------
9632
9633    procedure Check_Digits_Expression (E : Node_Id) is
9634    begin
9635       if not (Is_Integer_Type (Etype (E))) then
9636          Wrong_Type (E, Any_Integer);
9637
9638       elsif not Is_OK_Static_Expression (E) then
9639          Flag_Non_Static_Expr
9640            ("non-static expression used for digits value!", E);
9641
9642       elsif Expr_Value (E) <= 0 then
9643          Error_Msg_N ("digits value must be greater than zero", E);
9644
9645       else
9646          return;
9647       end if;
9648
9649       --  If any of above errors occurred, then replace the incorrect
9650       --  expression by the integer 1, which should prevent further errors.
9651
9652       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9653       Analyze_And_Resolve (E, Standard_Integer);
9654
9655    end Check_Digits_Expression;
9656
9657    --------------------------
9658    -- Check_Initialization --
9659    --------------------------
9660
9661    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9662    begin
9663       if Is_Limited_Type (T)
9664         and then not In_Instance
9665         and then not In_Inlined_Body
9666       then
9667          if not OK_For_Limited_Init (T, Exp) then
9668
9669             --  In GNAT mode, this is just a warning, to allow it to be evilly
9670             --  turned off. Otherwise it is a real error.
9671
9672             if GNAT_Mode then
9673                Error_Msg_N
9674                  ("?cannot initialize entities of limited type!", Exp);
9675
9676             elsif Ada_Version < Ada_2005 then
9677                Error_Msg_N
9678                  ("cannot initialize entities of limited type", Exp);
9679                Explain_Limited_Type (T, Exp);
9680
9681             else
9682                --  Specialize error message according to kind of illegal
9683                --  initial expression.
9684
9685                if Nkind (Exp) = N_Type_Conversion
9686                  and then Nkind (Expression (Exp)) = N_Function_Call
9687                then
9688                   Error_Msg_N
9689                     ("illegal context for call"
9690                       & " to function with limited result", Exp);
9691
9692                else
9693                   Error_Msg_N
9694                     ("initialization of limited object requires aggregate "
9695                       & "or function call",  Exp);
9696                end if;
9697             end if;
9698          end if;
9699       end if;
9700    end Check_Initialization;
9701
9702    ----------------------
9703    -- Check_Interfaces --
9704    ----------------------
9705
9706    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
9707       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
9708
9709       Iface       : Node_Id;
9710       Iface_Def   : Node_Id;
9711       Iface_Typ   : Entity_Id;
9712       Parent_Node : Node_Id;
9713
9714       Is_Task : Boolean := False;
9715       --  Set True if parent type or any progenitor is a task interface
9716
9717       Is_Protected : Boolean := False;
9718       --  Set True if parent type or any progenitor is a protected interface
9719
9720       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
9721       --  Check that a progenitor is compatible with declaration.
9722       --  Error is posted on Error_Node.
9723
9724       ------------------
9725       -- Check_Ifaces --
9726       ------------------
9727
9728       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
9729          Iface_Id : constant Entity_Id :=
9730                       Defining_Identifier (Parent (Iface_Def));
9731          Type_Def : Node_Id;
9732
9733       begin
9734          if Nkind (N) = N_Private_Extension_Declaration then
9735             Type_Def := N;
9736          else
9737             Type_Def := Type_Definition (N);
9738          end if;
9739
9740          if Is_Task_Interface (Iface_Id) then
9741             Is_Task := True;
9742
9743          elsif Is_Protected_Interface (Iface_Id) then
9744             Is_Protected := True;
9745          end if;
9746
9747          if Is_Synchronized_Interface (Iface_Id) then
9748
9749             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
9750             --  extension derived from a synchronized interface must explicitly
9751             --  be declared synchronized, because the full view will be a
9752             --  synchronized type.
9753
9754             if Nkind (N) = N_Private_Extension_Declaration then
9755                if not Synchronized_Present (N) then
9756                   Error_Msg_NE
9757                     ("private extension of& must be explicitly synchronized",
9758                       N, Iface_Id);
9759                end if;
9760
9761             --  However, by 3.9.4(16/2), a full type that is a record extension
9762             --  is never allowed to derive from a synchronized interface (note
9763             --  that interfaces must be excluded from this check, because those
9764             --  are represented by derived type definitions in some cases).
9765
9766             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9767               and then not Interface_Present (Type_Definition (N))
9768             then
9769                Error_Msg_N ("record extension cannot derive from synchronized"
9770                              & " interface", Error_Node);
9771             end if;
9772          end if;
9773
9774          --  Check that the characteristics of the progenitor are compatible
9775          --  with the explicit qualifier in the declaration.
9776          --  The check only applies to qualifiers that come from source.
9777          --  Limited_Present also appears in the declaration of corresponding
9778          --  records, and the check does not apply to them.
9779
9780          if Limited_Present (Type_Def)
9781            and then not
9782              Is_Concurrent_Record_Type (Defining_Identifier (N))
9783          then
9784             if Is_Limited_Interface (Parent_Type)
9785               and then not Is_Limited_Interface (Iface_Id)
9786             then
9787                Error_Msg_NE
9788                  ("progenitor& must be limited interface",
9789                    Error_Node, Iface_Id);
9790
9791             elsif
9792               (Task_Present (Iface_Def)
9793                 or else Protected_Present (Iface_Def)
9794                 or else Synchronized_Present (Iface_Def))
9795               and then Nkind (N) /= N_Private_Extension_Declaration
9796               and then not Error_Posted (N)
9797             then
9798                Error_Msg_NE
9799                  ("progenitor& must be limited interface",
9800                    Error_Node, Iface_Id);
9801             end if;
9802
9803          --  Protected interfaces can only inherit from limited, synchronized
9804          --  or protected interfaces.
9805
9806          elsif Nkind (N) = N_Full_Type_Declaration
9807            and then  Protected_Present (Type_Def)
9808          then
9809             if Limited_Present (Iface_Def)
9810               or else Synchronized_Present (Iface_Def)
9811               or else Protected_Present (Iface_Def)
9812             then
9813                null;
9814
9815             elsif Task_Present (Iface_Def) then
9816                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9817                             & " from task interface", Error_Node);
9818
9819             else
9820                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9821                             & " from non-limited interface", Error_Node);
9822             end if;
9823
9824          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
9825          --  limited and synchronized.
9826
9827          elsif Synchronized_Present (Type_Def) then
9828             if Limited_Present (Iface_Def)
9829               or else Synchronized_Present (Iface_Def)
9830             then
9831                null;
9832
9833             elsif Protected_Present (Iface_Def)
9834               and then Nkind (N) /= N_Private_Extension_Declaration
9835             then
9836                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9837                             & " from protected interface", Error_Node);
9838
9839             elsif Task_Present (Iface_Def)
9840               and then Nkind (N) /= N_Private_Extension_Declaration
9841             then
9842                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9843                             & " from task interface", Error_Node);
9844
9845             elsif not Is_Limited_Interface (Iface_Id) then
9846                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9847                             & " from non-limited interface", Error_Node);
9848             end if;
9849
9850          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
9851          --  synchronized or task interfaces.
9852
9853          elsif Nkind (N) = N_Full_Type_Declaration
9854            and then Task_Present (Type_Def)
9855          then
9856             if Limited_Present (Iface_Def)
9857               or else Synchronized_Present (Iface_Def)
9858               or else Task_Present (Iface_Def)
9859             then
9860                null;
9861
9862             elsif Protected_Present (Iface_Def) then
9863                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9864                             & " protected interface", Error_Node);
9865
9866             else
9867                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9868                             & " non-limited interface", Error_Node);
9869             end if;
9870          end if;
9871       end Check_Ifaces;
9872
9873    --  Start of processing for Check_Interfaces
9874
9875    begin
9876       if Is_Interface (Parent_Type) then
9877          if Is_Task_Interface (Parent_Type) then
9878             Is_Task := True;
9879
9880          elsif Is_Protected_Interface (Parent_Type) then
9881             Is_Protected := True;
9882          end if;
9883       end if;
9884
9885       if Nkind (N) = N_Private_Extension_Declaration then
9886
9887          --  Check that progenitors are compatible with declaration
9888
9889          Iface := First (Interface_List (Def));
9890          while Present (Iface) loop
9891             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9892
9893             Parent_Node := Parent (Base_Type (Iface_Typ));
9894             Iface_Def   := Type_Definition (Parent_Node);
9895
9896             if not Is_Interface (Iface_Typ) then
9897                Diagnose_Interface (Iface, Iface_Typ);
9898
9899             else
9900                Check_Ifaces (Iface_Def, Iface);
9901             end if;
9902
9903             Next (Iface);
9904          end loop;
9905
9906          if Is_Task and Is_Protected then
9907             Error_Msg_N
9908               ("type cannot derive from task and protected interface", N);
9909          end if;
9910
9911          return;
9912       end if;
9913
9914       --  Full type declaration of derived type.
9915       --  Check compatibility with parent if it is interface type
9916
9917       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9918         and then Is_Interface (Parent_Type)
9919       then
9920          Parent_Node := Parent (Parent_Type);
9921
9922          --  More detailed checks for interface varieties
9923
9924          Check_Ifaces
9925            (Iface_Def  => Type_Definition (Parent_Node),
9926             Error_Node => Subtype_Indication (Type_Definition (N)));
9927       end if;
9928
9929       Iface := First (Interface_List (Def));
9930       while Present (Iface) loop
9931          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9932
9933          Parent_Node := Parent (Base_Type (Iface_Typ));
9934          Iface_Def   := Type_Definition (Parent_Node);
9935
9936          if not Is_Interface (Iface_Typ) then
9937             Diagnose_Interface (Iface, Iface_Typ);
9938
9939          else
9940             --  "The declaration of a specific descendant of an interface
9941             --   type freezes the interface type" RM 13.14
9942
9943             Freeze_Before (N, Iface_Typ);
9944             Check_Ifaces (Iface_Def, Error_Node => Iface);
9945          end if;
9946
9947          Next (Iface);
9948       end loop;
9949
9950       if Is_Task and Is_Protected then
9951          Error_Msg_N
9952            ("type cannot derive from task and protected interface", N);
9953       end if;
9954    end Check_Interfaces;
9955
9956    ------------------------------------
9957    -- Check_Or_Process_Discriminants --
9958    ------------------------------------
9959
9960    --  If an incomplete or private type declaration was already given for the
9961    --  type, the discriminants may have already been processed if they were
9962    --  present on the incomplete declaration. In this case a full conformance
9963    --  check has been performed in Find_Type_Name, and we then recheck here
9964    --  some properties that can't be checked on the partial view alone.
9965    --  Otherwise we call Process_Discriminants.
9966
9967    procedure Check_Or_Process_Discriminants
9968      (N    : Node_Id;
9969       T    : Entity_Id;
9970       Prev : Entity_Id := Empty)
9971    is
9972    begin
9973       if Has_Discriminants (T) then
9974
9975          --  Discriminants are already set on T if they were already present
9976          --  on the partial view. Make them visible to component declarations.
9977
9978          declare
9979             D : Entity_Id;
9980             --  Discriminant on T (full view) referencing expr on partial view
9981
9982             Prev_D : Entity_Id;
9983             --  Entity of corresponding discriminant on partial view
9984
9985             New_D : Node_Id;
9986             --  Discriminant specification for full view, expression is the
9987             --  syntactic copy on full view (which has been checked for
9988             --  conformance with partial view), only used here to post error
9989             --  message.
9990
9991          begin
9992             D     := First_Discriminant (T);
9993             New_D := First (Discriminant_Specifications (N));
9994             while Present (D) loop
9995                Prev_D := Current_Entity (D);
9996                Set_Current_Entity (D);
9997                Set_Is_Immediately_Visible (D);
9998                Set_Homonym (D, Prev_D);
9999
10000                --  Handle the case where there is an untagged partial view and
10001                --  the full view is tagged: must disallow discriminants with
10002                --  defaults, unless compiling for Ada 2012, which allows a
10003                --  limited tagged type to have defaulted discriminants (see
10004                --  AI05-0214). However, suppress the error here if it was
10005                --  already reported on the default expression of the partial
10006                --  view.
10007
10008                if Is_Tagged_Type (T)
10009                     and then Present (Expression (Parent (D)))
10010                     and then (not Is_Limited_Type (Current_Scope)
10011                                or else Ada_Version < Ada_2012)
10012                     and then not Error_Posted (Expression (Parent (D)))
10013                then
10014                   if Ada_Version >= Ada_2012 then
10015                      Error_Msg_N
10016                        ("discriminants of nonlimited tagged type cannot have"
10017                           & " defaults",
10018                         Expression (New_D));
10019                   else
10020                      Error_Msg_N
10021                        ("discriminants of tagged type cannot have defaults",
10022                         Expression (New_D));
10023                   end if;
10024                end if;
10025
10026                --  Ada 2005 (AI-230): Access discriminant allowed in
10027                --  non-limited record types.
10028
10029                if Ada_Version < Ada_2005 then
10030
10031                   --  This restriction gets applied to the full type here. It
10032                   --  has already been applied earlier to the partial view.
10033
10034                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
10035                end if;
10036
10037                Next_Discriminant (D);
10038                Next (New_D);
10039             end loop;
10040          end;
10041
10042       elsif Present (Discriminant_Specifications (N)) then
10043          Process_Discriminants (N, Prev);
10044       end if;
10045    end Check_Or_Process_Discriminants;
10046
10047    ----------------------
10048    -- Check_Real_Bound --
10049    ----------------------
10050
10051    procedure Check_Real_Bound (Bound : Node_Id) is
10052    begin
10053       if not Is_Real_Type (Etype (Bound)) then
10054          Error_Msg_N
10055            ("bound in real type definition must be of real type", Bound);
10056
10057       elsif not Is_OK_Static_Expression (Bound) then
10058          Flag_Non_Static_Expr
10059            ("non-static expression used for real type bound!", Bound);
10060
10061       else
10062          return;
10063       end if;
10064
10065       Rewrite
10066         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
10067       Analyze (Bound);
10068       Resolve (Bound, Standard_Float);
10069    end Check_Real_Bound;
10070
10071    ------------------------------
10072    -- Complete_Private_Subtype --
10073    ------------------------------
10074
10075    procedure Complete_Private_Subtype
10076      (Priv        : Entity_Id;
10077       Full        : Entity_Id;
10078       Full_Base   : Entity_Id;
10079       Related_Nod : Node_Id)
10080    is
10081       Save_Next_Entity : Entity_Id;
10082       Save_Homonym     : Entity_Id;
10083
10084    begin
10085       --  Set semantic attributes for (implicit) private subtype completion.
10086       --  If the full type has no discriminants, then it is a copy of the full
10087       --  view of the base. Otherwise, it is a subtype of the base with a
10088       --  possible discriminant constraint. Save and restore the original
10089       --  Next_Entity field of full to ensure that the calls to Copy_Node
10090       --  do not corrupt the entity chain.
10091
10092       --  Note that the type of the full view is the same entity as the type of
10093       --  the partial view. In this fashion, the subtype has access to the
10094       --  correct view of the parent.
10095
10096       Save_Next_Entity := Next_Entity (Full);
10097       Save_Homonym     := Homonym (Priv);
10098
10099       case Ekind (Full_Base) is
10100          when E_Record_Type    |
10101               E_Record_Subtype |
10102               Class_Wide_Kind  |
10103               Private_Kind     |
10104               Task_Kind        |
10105               Protected_Kind   =>
10106             Copy_Node (Priv, Full);
10107
10108             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
10109             Set_First_Entity       (Full, First_Entity (Full_Base));
10110             Set_Last_Entity        (Full, Last_Entity (Full_Base));
10111
10112          when others =>
10113             Copy_Node (Full_Base, Full);
10114             Set_Chars          (Full, Chars (Priv));
10115             Conditional_Delay  (Full, Priv);
10116             Set_Sloc           (Full, Sloc (Priv));
10117       end case;
10118
10119       Set_Next_Entity (Full, Save_Next_Entity);
10120       Set_Homonym     (Full, Save_Homonym);
10121       Set_Associated_Node_For_Itype (Full, Related_Nod);
10122
10123       --  Set common attributes for all subtypes: kind, convention, etc.
10124
10125       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
10126       Set_Convention (Full, Convention (Full_Base));
10127
10128       --  The Etype of the full view is inconsistent. Gigi needs to see the
10129       --  structural full view,  which is what the current scheme gives:
10130       --  the Etype of the full view is the etype of the full base. However,
10131       --  if the full base is a derived type, the full view then looks like
10132       --  a subtype of the parent, not a subtype of the full base. If instead
10133       --  we write:
10134
10135       --       Set_Etype (Full, Full_Base);
10136
10137       --  then we get inconsistencies in the front-end (confusion between
10138       --  views). Several outstanding bugs are related to this ???
10139
10140       Set_Is_First_Subtype (Full, False);
10141       Set_Scope            (Full, Scope (Priv));
10142       Set_Size_Info        (Full, Full_Base);
10143       Set_RM_Size          (Full, RM_Size (Full_Base));
10144       Set_Is_Itype         (Full);
10145
10146       --  A subtype of a private-type-without-discriminants, whose full-view
10147       --  has discriminants with default expressions, is not constrained!
10148
10149       if not Has_Discriminants (Priv) then
10150          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
10151
10152          if Has_Discriminants (Full_Base) then
10153             Set_Discriminant_Constraint
10154               (Full, Discriminant_Constraint (Full_Base));
10155
10156             --  The partial view may have been indefinite, the full view
10157             --  might not be.
10158
10159             Set_Has_Unknown_Discriminants
10160               (Full, Has_Unknown_Discriminants (Full_Base));
10161          end if;
10162       end if;
10163
10164       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
10165       Set_Depends_On_Private (Full, Has_Private_Component (Full));
10166
10167       --  Freeze the private subtype entity if its parent is delayed, and not
10168       --  already frozen. We skip this processing if the type is an anonymous
10169       --  subtype of a record component, or is the corresponding record of a
10170       --  protected type, since ???
10171
10172       if not Is_Type (Scope (Full)) then
10173          Set_Has_Delayed_Freeze (Full,
10174            Has_Delayed_Freeze (Full_Base)
10175              and then (not Is_Frozen (Full_Base)));
10176       end if;
10177
10178       Set_Freeze_Node (Full, Empty);
10179       Set_Is_Frozen (Full, False);
10180       Set_Full_View (Priv, Full);
10181
10182       if Has_Discriminants (Full) then
10183          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
10184          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
10185
10186          if Has_Unknown_Discriminants (Full) then
10187             Set_Discriminant_Constraint (Full, No_Elist);
10188          end if;
10189       end if;
10190
10191       if Ekind (Full_Base) = E_Record_Type
10192         and then Has_Discriminants (Full_Base)
10193         and then Has_Discriminants (Priv) -- might not, if errors
10194         and then not Has_Unknown_Discriminants (Priv)
10195         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
10196       then
10197          Create_Constrained_Components
10198            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
10199
10200       --  If the full base is itself derived from private, build a congruent
10201       --  subtype of its underlying type, for use by the back end. For a
10202       --  constrained record component, the declaration cannot be placed on
10203       --  the component list, but it must nevertheless be built an analyzed, to
10204       --  supply enough information for Gigi to compute the size of component.
10205
10206       elsif Ekind (Full_Base) in Private_Kind
10207         and then Is_Derived_Type (Full_Base)
10208         and then Has_Discriminants (Full_Base)
10209         and then (Ekind (Current_Scope) /= E_Record_Subtype)
10210       then
10211          if not Is_Itype (Priv)
10212            and then
10213              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
10214          then
10215             Build_Underlying_Full_View
10216               (Parent (Priv), Full, Etype (Full_Base));
10217
10218          elsif Nkind (Related_Nod) = N_Component_Declaration then
10219             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
10220          end if;
10221
10222       elsif Is_Record_Type (Full_Base) then
10223
10224          --  Show Full is simply a renaming of Full_Base
10225
10226          Set_Cloned_Subtype (Full, Full_Base);
10227       end if;
10228
10229       --  It is unsafe to share to bounds of a scalar type, because the Itype
10230       --  is elaborated on demand, and if a bound is non-static then different
10231       --  orders of elaboration in different units will lead to different
10232       --  external symbols.
10233
10234       if Is_Scalar_Type (Full_Base) then
10235          Set_Scalar_Range (Full,
10236            Make_Range (Sloc (Related_Nod),
10237              Low_Bound  =>
10238                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
10239              High_Bound =>
10240                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
10241
10242          --  This completion inherits the bounds of the full parent, but if
10243          --  the parent is an unconstrained floating point type, so is the
10244          --  completion.
10245
10246          if Is_Floating_Point_Type (Full_Base) then
10247             Set_Includes_Infinities
10248              (Scalar_Range (Full), Has_Infinities (Full_Base));
10249          end if;
10250       end if;
10251
10252       --  ??? It seems that a lot of fields are missing that should be copied
10253       --  from Full_Base to Full. Here are some that are introduced in a
10254       --  non-disruptive way but a cleanup is necessary.
10255
10256       if Is_Tagged_Type (Full_Base) then
10257          Set_Is_Tagged_Type (Full);
10258          Set_Direct_Primitive_Operations (Full,
10259            Direct_Primitive_Operations (Full_Base));
10260
10261          --  Inherit class_wide type of full_base in case the partial view was
10262          --  not tagged. Otherwise it has already been created when the private
10263          --  subtype was analyzed.
10264
10265          if No (Class_Wide_Type (Full)) then
10266             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
10267          end if;
10268
10269       --  If this is a subtype of a protected or task type, constrain its
10270       --  corresponding record, unless this is a subtype without constraints,
10271       --  i.e. a simple renaming as with an actual subtype in an instance.
10272
10273       elsif Is_Concurrent_Type (Full_Base) then
10274          if Has_Discriminants (Full)
10275            and then Present (Corresponding_Record_Type (Full_Base))
10276            and then
10277              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
10278          then
10279             Set_Corresponding_Record_Type (Full,
10280               Constrain_Corresponding_Record
10281                 (Full, Corresponding_Record_Type (Full_Base),
10282                   Related_Nod, Full_Base));
10283
10284          else
10285             Set_Corresponding_Record_Type (Full,
10286               Corresponding_Record_Type (Full_Base));
10287          end if;
10288       end if;
10289
10290       --  Link rep item chain, and also setting of Has_Predicates from private
10291       --  subtype to full subtype, since we will need these on the full subtype
10292       --  to create the predicate function. Note that the full subtype may
10293       --  already have rep items, inherited from the full view of the base
10294       --  type, so we must be sure not to overwrite these entries.
10295
10296       declare
10297          Item      : Node_Id;
10298          Next_Item : Node_Id;
10299
10300       begin
10301          Item := First_Rep_Item (Full);
10302
10303          --  If no existing rep items on full type, we can just link directly
10304          --  to the list of items on the private type.
10305
10306          if No (Item) then
10307             Set_First_Rep_Item (Full, First_Rep_Item (Priv));
10308
10309          --  Otherwise, search to the end of items currently linked to the full
10310          --  subtype and append the private items to the end. However, if Priv
10311          --  and Full already have the same list of rep items, then the append
10312          --  is not done, as that would create a circularity.
10313
10314          elsif Item /= First_Rep_Item (Priv) then
10315             loop
10316                Next_Item := Next_Rep_Item (Item);
10317                exit when No (Next_Item);
10318                Item := Next_Item;
10319             end loop;
10320
10321             --  And link the private type items at the end of the chain
10322
10323             Set_Next_Rep_Item (Item, First_Rep_Item (Priv));
10324          end if;
10325       end;
10326
10327       --  Make sure Has_Predicates is set on full type if it is set on the
10328       --  private type. Note that it may already be set on the full type and
10329       --  if so, we don't want to unset it.
10330
10331       if Has_Predicates (Priv) then
10332          Set_Has_Predicates (Full);
10333       end if;
10334    end Complete_Private_Subtype;
10335
10336    ----------------------------
10337    -- Constant_Redeclaration --
10338    ----------------------------
10339
10340    procedure Constant_Redeclaration
10341      (Id : Entity_Id;
10342       N  : Node_Id;
10343       T  : out Entity_Id)
10344    is
10345       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
10346       Obj_Def : constant Node_Id := Object_Definition (N);
10347       New_T   : Entity_Id;
10348
10349       procedure Check_Possible_Deferred_Completion
10350         (Prev_Id      : Entity_Id;
10351          Prev_Obj_Def : Node_Id;
10352          Curr_Obj_Def : Node_Id);
10353       --  Determine whether the two object definitions describe the partial
10354       --  and the full view of a constrained deferred constant. Generate
10355       --  a subtype for the full view and verify that it statically matches
10356       --  the subtype of the partial view.
10357
10358       procedure Check_Recursive_Declaration (Typ : Entity_Id);
10359       --  If deferred constant is an access type initialized with an allocator,
10360       --  check whether there is an illegal recursion in the definition,
10361       --  through a default value of some record subcomponent. This is normally
10362       --  detected when generating init procs, but requires this additional
10363       --  mechanism when expansion is disabled.
10364
10365       ----------------------------------------
10366       -- Check_Possible_Deferred_Completion --
10367       ----------------------------------------
10368
10369       procedure Check_Possible_Deferred_Completion
10370         (Prev_Id      : Entity_Id;
10371          Prev_Obj_Def : Node_Id;
10372          Curr_Obj_Def : Node_Id)
10373       is
10374       begin
10375          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
10376            and then Present (Constraint (Prev_Obj_Def))
10377            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
10378            and then Present (Constraint (Curr_Obj_Def))
10379          then
10380             declare
10381                Loc    : constant Source_Ptr := Sloc (N);
10382                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
10383                Decl   : constant Node_Id    :=
10384                           Make_Subtype_Declaration (Loc,
10385                             Defining_Identifier => Def_Id,
10386                             Subtype_Indication  =>
10387                               Relocate_Node (Curr_Obj_Def));
10388
10389             begin
10390                Insert_Before_And_Analyze (N, Decl);
10391                Set_Etype (Id, Def_Id);
10392
10393                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
10394                   Error_Msg_Sloc := Sloc (Prev_Id);
10395                   Error_Msg_N ("subtype does not statically match deferred " &
10396                                "declaration#", N);
10397                end if;
10398             end;
10399          end if;
10400       end Check_Possible_Deferred_Completion;
10401
10402       ---------------------------------
10403       -- Check_Recursive_Declaration --
10404       ---------------------------------
10405
10406       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
10407          Comp : Entity_Id;
10408
10409       begin
10410          if Is_Record_Type (Typ) then
10411             Comp := First_Component (Typ);
10412             while Present (Comp) loop
10413                if Comes_From_Source (Comp) then
10414                   if Present (Expression (Parent (Comp)))
10415                     and then Is_Entity_Name (Expression (Parent (Comp)))
10416                     and then Entity (Expression (Parent (Comp))) = Prev
10417                   then
10418                      Error_Msg_Sloc := Sloc (Parent (Comp));
10419                      Error_Msg_NE
10420                        ("illegal circularity with declaration for&#",
10421                          N, Comp);
10422                      return;
10423
10424                   elsif Is_Record_Type (Etype (Comp)) then
10425                      Check_Recursive_Declaration (Etype (Comp));
10426                   end if;
10427                end if;
10428
10429                Next_Component (Comp);
10430             end loop;
10431          end if;
10432       end Check_Recursive_Declaration;
10433
10434    --  Start of processing for Constant_Redeclaration
10435
10436    begin
10437       if Nkind (Parent (Prev)) = N_Object_Declaration then
10438          if Nkind (Object_Definition
10439                      (Parent (Prev))) = N_Subtype_Indication
10440          then
10441             --  Find type of new declaration. The constraints of the two
10442             --  views must match statically, but there is no point in
10443             --  creating an itype for the full view.
10444
10445             if Nkind (Obj_Def) = N_Subtype_Indication then
10446                Find_Type (Subtype_Mark (Obj_Def));
10447                New_T := Entity (Subtype_Mark (Obj_Def));
10448
10449             else
10450                Find_Type (Obj_Def);
10451                New_T := Entity (Obj_Def);
10452             end if;
10453
10454             T := Etype (Prev);
10455
10456          else
10457             --  The full view may impose a constraint, even if the partial
10458             --  view does not, so construct the subtype.
10459
10460             New_T := Find_Type_Of_Object (Obj_Def, N);
10461             T     := New_T;
10462          end if;
10463
10464       else
10465          --  Current declaration is illegal, diagnosed below in Enter_Name
10466
10467          T := Empty;
10468          New_T := Any_Type;
10469       end if;
10470
10471       --  If previous full declaration or a renaming declaration exists, or if
10472       --  a homograph is present, let Enter_Name handle it, either with an
10473       --  error or with the removal of an overridden implicit subprogram.
10474
10475       if Ekind (Prev) /= E_Constant
10476         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
10477         or else Present (Expression (Parent (Prev)))
10478         or else Present (Full_View (Prev))
10479       then
10480          Enter_Name (Id);
10481
10482       --  Verify that types of both declarations match, or else that both types
10483       --  are anonymous access types whose designated subtypes statically match
10484       --  (as allowed in Ada 2005 by AI-385).
10485
10486       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
10487         and then
10488           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
10489              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
10490              or else Is_Access_Constant (Etype (New_T)) /=
10491                      Is_Access_Constant (Etype (Prev))
10492              or else Can_Never_Be_Null (Etype (New_T)) /=
10493                      Can_Never_Be_Null (Etype (Prev))
10494              or else Null_Exclusion_Present (Parent (Prev)) /=
10495                      Null_Exclusion_Present (Parent (Id))
10496              or else not Subtypes_Statically_Match
10497                            (Designated_Type (Etype (Prev)),
10498                             Designated_Type (Etype (New_T))))
10499       then
10500          Error_Msg_Sloc := Sloc (Prev);
10501          Error_Msg_N ("type does not match declaration#", N);
10502          Set_Full_View (Prev, Id);
10503          Set_Etype (Id, Any_Type);
10504
10505       elsif
10506         Null_Exclusion_Present (Parent (Prev))
10507           and then not Null_Exclusion_Present (N)
10508       then
10509          Error_Msg_Sloc := Sloc (Prev);
10510          Error_Msg_N ("null-exclusion does not match declaration#", N);
10511          Set_Full_View (Prev, Id);
10512          Set_Etype (Id, Any_Type);
10513
10514       --  If so, process the full constant declaration
10515
10516       else
10517          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
10518          --  the deferred declaration is constrained, then the subtype defined
10519          --  by the subtype_indication in the full declaration shall match it
10520          --  statically.
10521
10522          Check_Possible_Deferred_Completion
10523            (Prev_Id      => Prev,
10524             Prev_Obj_Def => Object_Definition (Parent (Prev)),
10525             Curr_Obj_Def => Obj_Def);
10526
10527          Set_Full_View (Prev, Id);
10528          Set_Is_Public (Id, Is_Public (Prev));
10529          Set_Is_Internal (Id);
10530          Append_Entity (Id, Current_Scope);
10531
10532          --  Check ALIASED present if present before (RM 7.4(7))
10533
10534          if Is_Aliased (Prev)
10535            and then not Aliased_Present (N)
10536          then
10537             Error_Msg_Sloc := Sloc (Prev);
10538             Error_Msg_N ("ALIASED required (see declaration#)", N);
10539          end if;
10540
10541          --  Check that placement is in private part and that the incomplete
10542          --  declaration appeared in the visible part.
10543
10544          if Ekind (Current_Scope) = E_Package
10545            and then not In_Private_Part (Current_Scope)
10546          then
10547             Error_Msg_Sloc := Sloc (Prev);
10548             Error_Msg_N
10549               ("full constant for declaration#"
10550                & " must be in private part", N);
10551
10552          elsif Ekind (Current_Scope) = E_Package
10553            and then
10554              List_Containing (Parent (Prev)) /=
10555                Visible_Declarations
10556                  (Specification (Unit_Declaration_Node (Current_Scope)))
10557          then
10558             Error_Msg_N
10559               ("deferred constant must be declared in visible part",
10560                  Parent (Prev));
10561          end if;
10562
10563          if Is_Access_Type (T)
10564            and then Nkind (Expression (N)) = N_Allocator
10565          then
10566             Check_Recursive_Declaration (Designated_Type (T));
10567          end if;
10568       end if;
10569    end Constant_Redeclaration;
10570
10571    ----------------------
10572    -- Constrain_Access --
10573    ----------------------
10574
10575    procedure Constrain_Access
10576      (Def_Id      : in out Entity_Id;
10577       S           : Node_Id;
10578       Related_Nod : Node_Id)
10579    is
10580       T             : constant Entity_Id := Entity (Subtype_Mark (S));
10581       Desig_Type    : constant Entity_Id := Designated_Type (T);
10582       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
10583       Constraint_OK : Boolean := True;
10584
10585       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
10586       --  Simple predicate to test for defaulted discriminants
10587       --  Shouldn't this be in sem_util???
10588
10589       ---------------------------------
10590       -- Has_Defaulted_Discriminants --
10591       ---------------------------------
10592
10593       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
10594       begin
10595          return Has_Discriminants (Typ)
10596           and then Present (First_Discriminant (Typ))
10597           and then Present
10598             (Discriminant_Default_Value (First_Discriminant (Typ)));
10599       end Has_Defaulted_Discriminants;
10600
10601    --  Start of processing for Constrain_Access
10602
10603    begin
10604       if Is_Array_Type (Desig_Type) then
10605          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
10606
10607       elsif (Is_Record_Type (Desig_Type)
10608               or else Is_Incomplete_Or_Private_Type (Desig_Type))
10609         and then not Is_Constrained (Desig_Type)
10610       then
10611          --  ??? The following code is a temporary kludge to ignore a
10612          --  discriminant constraint on access type if it is constraining
10613          --  the current record. Avoid creating the implicit subtype of the
10614          --  record we are currently compiling since right now, we cannot
10615          --  handle these. For now, just return the access type itself.
10616
10617          if Desig_Type = Current_Scope
10618            and then No (Def_Id)
10619          then
10620             Set_Ekind (Desig_Subtype, E_Record_Subtype);
10621             Def_Id := Entity (Subtype_Mark (S));
10622
10623             --  This call added to ensure that the constraint is analyzed
10624             --  (needed for a B test). Note that we still return early from
10625             --  this procedure to avoid recursive processing. ???
10626
10627             Constrain_Discriminated_Type
10628               (Desig_Subtype, S, Related_Nod, For_Access => True);
10629             return;
10630          end if;
10631
10632          if (Ekind (T) = E_General_Access_Type
10633               or else Ada_Version >= Ada_2005)
10634            and then Has_Private_Declaration (Desig_Type)
10635            and then In_Open_Scopes (Scope (Desig_Type))
10636            and then Has_Discriminants (Desig_Type)
10637          then
10638             --  Enforce rule that the constraint is illegal if there is
10639             --  an unconstrained view of the designated type. This means
10640             --  that the partial view (either a private type declaration or
10641             --  a derivation from a private type) has no discriminants.
10642             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
10643             --  by ACATS B371001).
10644
10645             --  Rule updated for Ada 2005: the private type is said to have
10646             --  a constrained partial view, given that objects of the type
10647             --  can be declared. Furthermore, the rule applies to all access
10648             --  types, unlike the rule concerning default discriminants.
10649
10650             declare
10651                Pack  : constant Node_Id :=
10652                          Unit_Declaration_Node (Scope (Desig_Type));
10653                Decls : List_Id;
10654                Decl  : Node_Id;
10655
10656             begin
10657                if Nkind (Pack) = N_Package_Declaration then
10658                   Decls := Visible_Declarations (Specification (Pack));
10659                   Decl := First (Decls);
10660                   while Present (Decl) loop
10661                      if (Nkind (Decl) = N_Private_Type_Declaration
10662                           and then
10663                             Chars (Defining_Identifier (Decl)) =
10664                                                      Chars (Desig_Type))
10665
10666                        or else
10667                         (Nkind (Decl) = N_Full_Type_Declaration
10668                           and then
10669                             Chars (Defining_Identifier (Decl)) =
10670                                                      Chars (Desig_Type)
10671                           and then Is_Derived_Type (Desig_Type)
10672                           and then
10673                             Has_Private_Declaration (Etype (Desig_Type)))
10674                      then
10675                         if No (Discriminant_Specifications (Decl)) then
10676                            Error_Msg_N
10677                             ("cannot constrain general access type if " &
10678                                "designated type has constrained partial view",
10679                                 S);
10680                         end if;
10681
10682                         exit;
10683                      end if;
10684
10685                      Next (Decl);
10686                   end loop;
10687                end if;
10688             end;
10689          end if;
10690
10691          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
10692            For_Access => True);
10693
10694       elsif (Is_Task_Type (Desig_Type)
10695               or else Is_Protected_Type (Desig_Type))
10696         and then not Is_Constrained (Desig_Type)
10697       then
10698          Constrain_Concurrent
10699            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
10700
10701       else
10702          Error_Msg_N ("invalid constraint on access type", S);
10703          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
10704          Constraint_OK := False;
10705       end if;
10706
10707       if No (Def_Id) then
10708          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
10709       else
10710          Set_Ekind (Def_Id, E_Access_Subtype);
10711       end if;
10712
10713       if Constraint_OK then
10714          Set_Etype (Def_Id, Base_Type (T));
10715
10716          if Is_Private_Type (Desig_Type) then
10717             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
10718          end if;
10719       else
10720          Set_Etype (Def_Id, Any_Type);
10721       end if;
10722
10723       Set_Size_Info                (Def_Id, T);
10724       Set_Is_Constrained           (Def_Id, Constraint_OK);
10725       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
10726       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
10727       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
10728
10729       Conditional_Delay (Def_Id, T);
10730
10731       --  AI-363 : Subtypes of general access types whose designated types have
10732       --  default discriminants are disallowed. In instances, the rule has to
10733       --  be checked against the actual, of which T is the subtype. In a
10734       --  generic body, the rule is checked assuming that the actual type has
10735       --  defaulted discriminants.
10736
10737       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
10738          if Ekind (Base_Type (T)) = E_General_Access_Type
10739            and then Has_Defaulted_Discriminants (Desig_Type)
10740          then
10741             if Ada_Version < Ada_2005 then
10742                Error_Msg_N
10743                  ("access subtype of general access type would not " &
10744                   "be allowed in Ada 2005?", S);
10745             else
10746                Error_Msg_N
10747                  ("access subtype of general access type not allowed", S);
10748             end if;
10749
10750             Error_Msg_N ("\discriminants have defaults", S);
10751
10752          elsif Is_Access_Type (T)
10753            and then Is_Generic_Type (Desig_Type)
10754            and then Has_Discriminants (Desig_Type)
10755            and then In_Package_Body (Current_Scope)
10756          then
10757             if Ada_Version < Ada_2005 then
10758                Error_Msg_N
10759                  ("access subtype would not be allowed in generic body " &
10760                   "in Ada 2005?", S);
10761             else
10762                Error_Msg_N
10763                  ("access subtype not allowed in generic body", S);
10764             end if;
10765
10766             Error_Msg_N
10767               ("\designated type is a discriminated formal", S);
10768          end if;
10769       end if;
10770    end Constrain_Access;
10771
10772    ---------------------
10773    -- Constrain_Array --
10774    ---------------------
10775
10776    procedure Constrain_Array
10777      (Def_Id      : in out Entity_Id;
10778       SI          : Node_Id;
10779       Related_Nod : Node_Id;
10780       Related_Id  : Entity_Id;
10781       Suffix      : Character)
10782    is
10783       C                     : constant Node_Id := Constraint (SI);
10784       Number_Of_Constraints : Nat := 0;
10785       Index                 : Node_Id;
10786       S, T                  : Entity_Id;
10787       Constraint_OK         : Boolean := True;
10788
10789    begin
10790       T := Entity (Subtype_Mark (SI));
10791
10792       if Ekind (T) in Access_Kind then
10793          T := Designated_Type (T);
10794       end if;
10795
10796       --  If an index constraint follows a subtype mark in a subtype indication
10797       --  then the type or subtype denoted by the subtype mark must not already
10798       --  impose an index constraint. The subtype mark must denote either an
10799       --  unconstrained array type or an access type whose designated type
10800       --  is such an array type... (RM 3.6.1)
10801
10802       if Is_Constrained (T) then
10803          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
10804          Constraint_OK := False;
10805
10806       else
10807          S := First (Constraints (C));
10808          while Present (S) loop
10809             Number_Of_Constraints := Number_Of_Constraints + 1;
10810             Next (S);
10811          end loop;
10812
10813          --  In either case, the index constraint must provide a discrete
10814          --  range for each index of the array type and the type of each
10815          --  discrete range must be the same as that of the corresponding
10816          --  index. (RM 3.6.1)
10817
10818          if Number_Of_Constraints /= Number_Dimensions (T) then
10819             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
10820             Constraint_OK := False;
10821
10822          else
10823             S := First (Constraints (C));
10824             Index := First_Index (T);
10825             Analyze (Index);
10826
10827             --  Apply constraints to each index type
10828
10829             for J in 1 .. Number_Of_Constraints loop
10830                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
10831                Next (Index);
10832                Next (S);
10833             end loop;
10834
10835          end if;
10836       end if;
10837
10838       if No (Def_Id) then
10839          Def_Id :=
10840            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
10841          Set_Parent (Def_Id, Related_Nod);
10842
10843       else
10844          Set_Ekind (Def_Id, E_Array_Subtype);
10845       end if;
10846
10847       Set_Size_Info      (Def_Id,                (T));
10848       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10849       Set_Etype          (Def_Id, Base_Type      (T));
10850
10851       if Constraint_OK then
10852          Set_First_Index (Def_Id, First (Constraints (C)));
10853       else
10854          Set_First_Index (Def_Id, First_Index (T));
10855       end if;
10856
10857       Set_Is_Constrained     (Def_Id, True);
10858       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
10859       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10860
10861       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
10862       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
10863
10864       --  A subtype does not inherit the packed_array_type of is parent. We
10865       --  need to initialize the attribute because if Def_Id is previously
10866       --  analyzed through a limited_with clause, it will have the attributes
10867       --  of an incomplete type, one of which is an Elist that overlaps the
10868       --  Packed_Array_Type field.
10869
10870       Set_Packed_Array_Type (Def_Id, Empty);
10871
10872       --  Build a freeze node if parent still needs one. Also make sure that
10873       --  the Depends_On_Private status is set because the subtype will need
10874       --  reprocessing at the time the base type does, and also we must set a
10875       --  conditional delay.
10876
10877       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
10878       Conditional_Delay (Def_Id, T);
10879    end Constrain_Array;
10880
10881    ------------------------------
10882    -- Constrain_Component_Type --
10883    ------------------------------
10884
10885    function Constrain_Component_Type
10886      (Comp            : Entity_Id;
10887       Constrained_Typ : Entity_Id;
10888       Related_Node    : Node_Id;
10889       Typ             : Entity_Id;
10890       Constraints     : Elist_Id) return Entity_Id
10891    is
10892       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
10893       Compon_Type : constant Entity_Id := Etype (Comp);
10894
10895       function Build_Constrained_Array_Type
10896         (Old_Type : Entity_Id) return Entity_Id;
10897       --  If Old_Type is an array type, one of whose indexes is constrained
10898       --  by a discriminant, build an Itype whose constraint replaces the
10899       --  discriminant with its value in the constraint.
10900
10901       function Build_Constrained_Discriminated_Type
10902         (Old_Type : Entity_Id) return Entity_Id;
10903       --  Ditto for record components
10904
10905       function Build_Constrained_Access_Type
10906         (Old_Type : Entity_Id) return Entity_Id;
10907       --  Ditto for access types. Makes use of previous two functions, to
10908       --  constrain designated type.
10909
10910       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
10911       --  T is an array or discriminated type, C is a list of constraints
10912       --  that apply to T. This routine builds the constrained subtype.
10913
10914       function Is_Discriminant (Expr : Node_Id) return Boolean;
10915       --  Returns True if Expr is a discriminant
10916
10917       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
10918       --  Find the value of discriminant Discrim in Constraint
10919
10920       -----------------------------------
10921       -- Build_Constrained_Access_Type --
10922       -----------------------------------
10923
10924       function Build_Constrained_Access_Type
10925         (Old_Type : Entity_Id) return Entity_Id
10926       is
10927          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
10928          Itype         : Entity_Id;
10929          Desig_Subtype : Entity_Id;
10930          Scop          : Entity_Id;
10931
10932       begin
10933          --  if the original access type was not embedded in the enclosing
10934          --  type definition, there is no need to produce a new access
10935          --  subtype. In fact every access type with an explicit constraint
10936          --  generates an itype whose scope is the enclosing record.
10937
10938          if not Is_Type (Scope (Old_Type)) then
10939             return Old_Type;
10940
10941          elsif Is_Array_Type (Desig_Type) then
10942             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
10943
10944          elsif Has_Discriminants (Desig_Type) then
10945
10946             --  This may be an access type to an enclosing record type for
10947             --  which we are constructing the constrained components. Return
10948             --  the enclosing record subtype. This is not always correct,
10949             --  but avoids infinite recursion. ???
10950
10951             Desig_Subtype := Any_Type;
10952
10953             for J in reverse 0 .. Scope_Stack.Last loop
10954                Scop := Scope_Stack.Table (J).Entity;
10955
10956                if Is_Type (Scop)
10957                  and then Base_Type (Scop) = Base_Type (Desig_Type)
10958                then
10959                   Desig_Subtype := Scop;
10960                end if;
10961
10962                exit when not Is_Type (Scop);
10963             end loop;
10964
10965             if Desig_Subtype = Any_Type then
10966                Desig_Subtype :=
10967                  Build_Constrained_Discriminated_Type (Desig_Type);
10968             end if;
10969
10970          else
10971             return Old_Type;
10972          end if;
10973
10974          if Desig_Subtype /= Desig_Type then
10975
10976             --  The Related_Node better be here or else we won't be able
10977             --  to attach new itypes to a node in the tree.
10978
10979             pragma Assert (Present (Related_Node));
10980
10981             Itype := Create_Itype (E_Access_Subtype, Related_Node);
10982
10983             Set_Etype                    (Itype, Base_Type      (Old_Type));
10984             Set_Size_Info                (Itype,                (Old_Type));
10985             Set_Directly_Designated_Type (Itype, Desig_Subtype);
10986             Set_Depends_On_Private       (Itype, Has_Private_Component
10987                                                                 (Old_Type));
10988             Set_Is_Access_Constant       (Itype, Is_Access_Constant
10989                                                                 (Old_Type));
10990
10991             --  The new itype needs freezing when it depends on a not frozen
10992             --  type and the enclosing subtype needs freezing.
10993
10994             if Has_Delayed_Freeze (Constrained_Typ)
10995               and then not Is_Frozen (Constrained_Typ)
10996             then
10997                Conditional_Delay (Itype, Base_Type (Old_Type));
10998             end if;
10999
11000             return Itype;
11001
11002          else
11003             return Old_Type;
11004          end if;
11005       end Build_Constrained_Access_Type;
11006
11007       ----------------------------------
11008       -- Build_Constrained_Array_Type --
11009       ----------------------------------
11010
11011       function Build_Constrained_Array_Type
11012         (Old_Type : Entity_Id) return Entity_Id
11013       is
11014          Lo_Expr     : Node_Id;
11015          Hi_Expr     : Node_Id;
11016          Old_Index   : Node_Id;
11017          Range_Node  : Node_Id;
11018          Constr_List : List_Id;
11019
11020          Need_To_Create_Itype : Boolean := False;
11021
11022       begin
11023          Old_Index := First_Index (Old_Type);
11024          while Present (Old_Index) loop
11025             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
11026
11027             if Is_Discriminant (Lo_Expr)
11028               or else Is_Discriminant (Hi_Expr)
11029             then
11030                Need_To_Create_Itype := True;
11031             end if;
11032
11033             Next_Index (Old_Index);
11034          end loop;
11035
11036          if Need_To_Create_Itype then
11037             Constr_List := New_List;
11038
11039             Old_Index := First_Index (Old_Type);
11040             while Present (Old_Index) loop
11041                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
11042
11043                if Is_Discriminant (Lo_Expr) then
11044                   Lo_Expr := Get_Discr_Value (Lo_Expr);
11045                end if;
11046
11047                if Is_Discriminant (Hi_Expr) then
11048                   Hi_Expr := Get_Discr_Value (Hi_Expr);
11049                end if;
11050
11051                Range_Node :=
11052                  Make_Range
11053                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
11054
11055                Append (Range_Node, To => Constr_List);
11056
11057                Next_Index (Old_Index);
11058             end loop;
11059
11060             return Build_Subtype (Old_Type, Constr_List);
11061
11062          else
11063             return Old_Type;
11064          end if;
11065       end Build_Constrained_Array_Type;
11066
11067       ------------------------------------------
11068       -- Build_Constrained_Discriminated_Type --
11069       ------------------------------------------
11070
11071       function Build_Constrained_Discriminated_Type
11072         (Old_Type : Entity_Id) return Entity_Id
11073       is
11074          Expr           : Node_Id;
11075          Constr_List    : List_Id;
11076          Old_Constraint : Elmt_Id;
11077
11078          Need_To_Create_Itype : Boolean := False;
11079
11080       begin
11081          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
11082          while Present (Old_Constraint) loop
11083             Expr := Node (Old_Constraint);
11084
11085             if Is_Discriminant (Expr) then
11086                Need_To_Create_Itype := True;
11087             end if;
11088
11089             Next_Elmt (Old_Constraint);
11090          end loop;
11091
11092          if Need_To_Create_Itype then
11093             Constr_List := New_List;
11094
11095             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
11096             while Present (Old_Constraint) loop
11097                Expr := Node (Old_Constraint);
11098
11099                if Is_Discriminant (Expr) then
11100                   Expr := Get_Discr_Value (Expr);
11101                end if;
11102
11103                Append (New_Copy_Tree (Expr), To => Constr_List);
11104
11105                Next_Elmt (Old_Constraint);
11106             end loop;
11107
11108             return Build_Subtype (Old_Type, Constr_List);
11109
11110          else
11111             return Old_Type;
11112          end if;
11113       end Build_Constrained_Discriminated_Type;
11114
11115       -------------------
11116       -- Build_Subtype --
11117       -------------------
11118
11119       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
11120          Indic       : Node_Id;
11121          Subtyp_Decl : Node_Id;
11122          Def_Id      : Entity_Id;
11123          Btyp        : Entity_Id := Base_Type (T);
11124
11125       begin
11126          --  The Related_Node better be here or else we won't be able to
11127          --  attach new itypes to a node in the tree.
11128
11129          pragma Assert (Present (Related_Node));
11130
11131          --  If the view of the component's type is incomplete or private
11132          --  with unknown discriminants, then the constraint must be applied
11133          --  to the full type.
11134
11135          if Has_Unknown_Discriminants (Btyp)
11136            and then Present (Underlying_Type (Btyp))
11137          then
11138             Btyp := Underlying_Type (Btyp);
11139          end if;
11140
11141          Indic :=
11142            Make_Subtype_Indication (Loc,
11143              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
11144              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
11145
11146          Def_Id := Create_Itype (Ekind (T), Related_Node);
11147
11148          Subtyp_Decl :=
11149            Make_Subtype_Declaration (Loc,
11150              Defining_Identifier => Def_Id,
11151              Subtype_Indication  => Indic);
11152
11153          Set_Parent (Subtyp_Decl, Parent (Related_Node));
11154
11155          --  Itypes must be analyzed with checks off (see package Itypes)
11156
11157          Analyze (Subtyp_Decl, Suppress => All_Checks);
11158
11159          return Def_Id;
11160       end Build_Subtype;
11161
11162       ---------------------
11163       -- Get_Discr_Value --
11164       ---------------------
11165
11166       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
11167          D : Entity_Id;
11168          E : Elmt_Id;
11169
11170       begin
11171          --  The discriminant may be declared for the type, in which case we
11172          --  find it by iterating over the list of discriminants. If the
11173          --  discriminant is inherited from a parent type, it appears as the
11174          --  corresponding discriminant of the current type. This will be the
11175          --  case when constraining an inherited component whose constraint is
11176          --  given by a discriminant of the parent.
11177
11178          D := First_Discriminant (Typ);
11179          E := First_Elmt (Constraints);
11180
11181          while Present (D) loop
11182             if D = Entity (Discrim)
11183               or else D = CR_Discriminant (Entity (Discrim))
11184               or else Corresponding_Discriminant (D) = Entity (Discrim)
11185             then
11186                return Node (E);
11187             end if;
11188
11189             Next_Discriminant (D);
11190             Next_Elmt (E);
11191          end loop;
11192
11193          --  The Corresponding_Discriminant mechanism is incomplete, because
11194          --  the correspondence between new and old discriminants is not one
11195          --  to one: one new discriminant can constrain several old ones. In
11196          --  that case, scan sequentially the stored_constraint, the list of
11197          --  discriminants of the parents, and the constraints.
11198          --  Previous code checked for the present of the Stored_Constraint
11199          --  list for the derived type, but did not use it at all. Should it
11200          --  be present when the component is a discriminated task type?
11201
11202          if Is_Derived_Type (Typ)
11203            and then Scope (Entity (Discrim)) = Etype (Typ)
11204          then
11205             D := First_Discriminant (Etype (Typ));
11206             E := First_Elmt (Constraints);
11207             while Present (D) loop
11208                if D = Entity (Discrim) then
11209                   return Node (E);
11210                end if;
11211
11212                Next_Discriminant (D);
11213                Next_Elmt (E);
11214             end loop;
11215          end if;
11216
11217          --  Something is wrong if we did not find the value
11218
11219          raise Program_Error;
11220       end Get_Discr_Value;
11221
11222       ---------------------
11223       -- Is_Discriminant --
11224       ---------------------
11225
11226       function Is_Discriminant (Expr : Node_Id) return Boolean is
11227          Discrim_Scope : Entity_Id;
11228
11229       begin
11230          if Denotes_Discriminant (Expr) then
11231             Discrim_Scope := Scope (Entity (Expr));
11232
11233             --  Either we have a reference to one of Typ's discriminants,
11234
11235             pragma Assert (Discrim_Scope = Typ
11236
11237                --  or to the discriminants of the parent type, in the case
11238                --  of a derivation of a tagged type with variants.
11239
11240                or else Discrim_Scope = Etype (Typ)
11241                or else Full_View (Discrim_Scope) = Etype (Typ)
11242
11243                --  or same as above for the case where the discriminants
11244                --  were declared in Typ's private view.
11245
11246                or else (Is_Private_Type (Discrim_Scope)
11247                         and then Chars (Discrim_Scope) = Chars (Typ))
11248
11249                --  or else we are deriving from the full view and the
11250                --  discriminant is declared in the private entity.
11251
11252                or else (Is_Private_Type (Typ)
11253                          and then Chars (Discrim_Scope) = Chars (Typ))
11254
11255                --  Or we are constrained the corresponding record of a
11256                --  synchronized type that completes a private declaration.
11257
11258                or else (Is_Concurrent_Record_Type (Typ)
11259                          and then
11260                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
11261
11262                --  or we have a class-wide type, in which case make sure the
11263                --  discriminant found belongs to the root type.
11264
11265                or else (Is_Class_Wide_Type (Typ)
11266                          and then Etype (Typ) = Discrim_Scope));
11267
11268             return True;
11269          end if;
11270
11271          --  In all other cases we have something wrong
11272
11273          return False;
11274       end Is_Discriminant;
11275
11276    --  Start of processing for Constrain_Component_Type
11277
11278    begin
11279       if Nkind (Parent (Comp)) = N_Component_Declaration
11280         and then Comes_From_Source (Parent (Comp))
11281         and then Comes_From_Source
11282           (Subtype_Indication (Component_Definition (Parent (Comp))))
11283         and then
11284           Is_Entity_Name
11285             (Subtype_Indication (Component_Definition (Parent (Comp))))
11286       then
11287          return Compon_Type;
11288
11289       elsif Is_Array_Type (Compon_Type) then
11290          return Build_Constrained_Array_Type (Compon_Type);
11291
11292       elsif Has_Discriminants (Compon_Type) then
11293          return Build_Constrained_Discriminated_Type (Compon_Type);
11294
11295       elsif Is_Access_Type (Compon_Type) then
11296          return Build_Constrained_Access_Type (Compon_Type);
11297
11298       else
11299          return Compon_Type;
11300       end if;
11301    end Constrain_Component_Type;
11302
11303    --------------------------
11304    -- Constrain_Concurrent --
11305    --------------------------
11306
11307    --  For concurrent types, the associated record value type carries the same
11308    --  discriminants, so when we constrain a concurrent type, we must constrain
11309    --  the corresponding record type as well.
11310
11311    procedure Constrain_Concurrent
11312      (Def_Id      : in out Entity_Id;
11313       SI          : Node_Id;
11314       Related_Nod : Node_Id;
11315       Related_Id  : Entity_Id;
11316       Suffix      : Character)
11317    is
11318       T_Ent : Entity_Id := Entity (Subtype_Mark (SI));
11319       T_Val : Entity_Id;
11320
11321    begin
11322       if Ekind (T_Ent) in Access_Kind then
11323          T_Ent := Designated_Type (T_Ent);
11324       end if;
11325
11326       T_Val := Corresponding_Record_Type (T_Ent);
11327
11328       if Present (T_Val) then
11329
11330          if No (Def_Id) then
11331             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11332          end if;
11333
11334          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11335
11336          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
11337          Set_Corresponding_Record_Type (Def_Id,
11338            Constrain_Corresponding_Record
11339              (Def_Id, T_Val, Related_Nod, Related_Id));
11340
11341       else
11342          --  If there is no associated record, expansion is disabled and this
11343          --  is a generic context. Create a subtype in any case, so that
11344          --  semantic analysis can proceed.
11345
11346          if No (Def_Id) then
11347             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
11348          end if;
11349
11350          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
11351       end if;
11352    end Constrain_Concurrent;
11353
11354    ------------------------------------
11355    -- Constrain_Corresponding_Record --
11356    ------------------------------------
11357
11358    function Constrain_Corresponding_Record
11359      (Prot_Subt   : Entity_Id;
11360       Corr_Rec    : Entity_Id;
11361       Related_Nod : Node_Id;
11362       Related_Id  : Entity_Id) return Entity_Id
11363    is
11364       T_Sub : constant Entity_Id :=
11365                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
11366
11367    begin
11368       Set_Etype             (T_Sub, Corr_Rec);
11369       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
11370       Set_Is_Constrained    (T_Sub, True);
11371       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
11372       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
11373
11374       --  As elsewhere, we do not want to create a freeze node for this itype
11375       --  if it is created for a constrained component of an enclosing record
11376       --  because references to outer discriminants will appear out of scope.
11377
11378       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
11379          Conditional_Delay (T_Sub, Corr_Rec);
11380       else
11381          Set_Is_Frozen (T_Sub);
11382       end if;
11383
11384       if Has_Discriminants (Prot_Subt) then -- False only if errors.
11385          Set_Discriminant_Constraint
11386            (T_Sub, Discriminant_Constraint (Prot_Subt));
11387          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
11388          Create_Constrained_Components
11389            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
11390       end if;
11391
11392       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
11393
11394       return T_Sub;
11395    end Constrain_Corresponding_Record;
11396
11397    -----------------------
11398    -- Constrain_Decimal --
11399    -----------------------
11400
11401    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
11402       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
11403       C           : constant Node_Id    := Constraint (S);
11404       Loc         : constant Source_Ptr := Sloc (C);
11405       Range_Expr  : Node_Id;
11406       Digits_Expr : Node_Id;
11407       Digits_Val  : Uint;
11408       Bound_Val   : Ureal;
11409
11410    begin
11411       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
11412
11413       if Nkind (C) = N_Range_Constraint then
11414          Range_Expr := Range_Expression (C);
11415          Digits_Val := Digits_Value (T);
11416
11417       else
11418          pragma Assert (Nkind (C) = N_Digits_Constraint);
11419
11420          Check_SPARK_Restriction ("digits constraint is not allowed", S);
11421
11422          Digits_Expr := Digits_Expression (C);
11423          Analyze_And_Resolve (Digits_Expr, Any_Integer);
11424
11425          Check_Digits_Expression (Digits_Expr);
11426          Digits_Val := Expr_Value (Digits_Expr);
11427
11428          if Digits_Val > Digits_Value (T) then
11429             Error_Msg_N
11430                ("digits expression is incompatible with subtype", C);
11431             Digits_Val := Digits_Value (T);
11432          end if;
11433
11434          if Present (Range_Constraint (C)) then
11435             Range_Expr := Range_Expression (Range_Constraint (C));
11436          else
11437             Range_Expr := Empty;
11438          end if;
11439       end if;
11440
11441       Set_Etype            (Def_Id, Base_Type        (T));
11442       Set_Size_Info        (Def_Id,                  (T));
11443       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11444       Set_Delta_Value      (Def_Id, Delta_Value      (T));
11445       Set_Scale_Value      (Def_Id, Scale_Value      (T));
11446       Set_Small_Value      (Def_Id, Small_Value      (T));
11447       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
11448       Set_Digits_Value     (Def_Id, Digits_Val);
11449
11450       --  Manufacture range from given digits value if no range present
11451
11452       if No (Range_Expr) then
11453          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
11454          Range_Expr :=
11455            Make_Range (Loc,
11456              Low_Bound =>
11457                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
11458              High_Bound =>
11459                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
11460       end if;
11461
11462       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
11463       Set_Discrete_RM_Size (Def_Id);
11464
11465       --  Unconditionally delay the freeze, since we cannot set size
11466       --  information in all cases correctly until the freeze point.
11467
11468       Set_Has_Delayed_Freeze (Def_Id);
11469    end Constrain_Decimal;
11470
11471    ----------------------------------
11472    -- Constrain_Discriminated_Type --
11473    ----------------------------------
11474
11475    procedure Constrain_Discriminated_Type
11476      (Def_Id      : Entity_Id;
11477       S           : Node_Id;
11478       Related_Nod : Node_Id;
11479       For_Access  : Boolean := False)
11480    is
11481       E     : constant Entity_Id := Entity (Subtype_Mark (S));
11482       T     : Entity_Id;
11483       C     : Node_Id;
11484       Elist : Elist_Id := New_Elmt_List;
11485
11486       procedure Fixup_Bad_Constraint;
11487       --  This is called after finding a bad constraint, and after having
11488       --  posted an appropriate error message. The mission is to leave the
11489       --  entity T in as reasonable state as possible!
11490
11491       --------------------------
11492       -- Fixup_Bad_Constraint --
11493       --------------------------
11494
11495       procedure Fixup_Bad_Constraint is
11496       begin
11497          --  Set a reasonable Ekind for the entity. For an incomplete type,
11498          --  we can't do much, but for other types, we can set the proper
11499          --  corresponding subtype kind.
11500
11501          if Ekind (T) = E_Incomplete_Type then
11502             Set_Ekind (Def_Id, Ekind (T));
11503          else
11504             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
11505          end if;
11506
11507          --  Set Etype to the known type, to reduce chances of cascaded errors
11508
11509          Set_Etype (Def_Id, E);
11510          Set_Error_Posted (Def_Id);
11511       end Fixup_Bad_Constraint;
11512
11513    --  Start of processing for Constrain_Discriminated_Type
11514
11515    begin
11516       C := Constraint (S);
11517
11518       --  A discriminant constraint is only allowed in a subtype indication,
11519       --  after a subtype mark. This subtype mark must denote either a type
11520       --  with discriminants, or an access type whose designated type is a
11521       --  type with discriminants. A discriminant constraint specifies the
11522       --  values of these discriminants (RM 3.7.2(5)).
11523
11524       T := Base_Type (Entity (Subtype_Mark (S)));
11525
11526       if Ekind (T) in Access_Kind then
11527          T := Designated_Type (T);
11528       end if;
11529
11530       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
11531       --  Avoid generating an error for access-to-incomplete subtypes.
11532
11533       if Ada_Version >= Ada_2005
11534         and then Ekind (T) = E_Incomplete_Type
11535         and then Nkind (Parent (S)) = N_Subtype_Declaration
11536         and then not Is_Itype (Def_Id)
11537       then
11538          --  A little sanity check, emit an error message if the type
11539          --  has discriminants to begin with. Type T may be a regular
11540          --  incomplete type or imported via a limited with clause.
11541
11542          if Has_Discriminants (T)
11543            or else
11544              (From_With_Type (T)
11545                 and then Present (Non_Limited_View (T))
11546                 and then Nkind (Parent (Non_Limited_View (T))) =
11547                            N_Full_Type_Declaration
11548                 and then Present (Discriminant_Specifications
11549                           (Parent (Non_Limited_View (T)))))
11550          then
11551             Error_Msg_N
11552               ("(Ada 2005) incomplete subtype may not be constrained", C);
11553          else
11554             Error_Msg_N ("invalid constraint: type has no discriminant", C);
11555          end if;
11556
11557          Fixup_Bad_Constraint;
11558          return;
11559
11560       --  Check that the type has visible discriminants. The type may be
11561       --  a private type with unknown discriminants whose full view has
11562       --  discriminants which are invisible.
11563
11564       elsif not Has_Discriminants (T)
11565         or else
11566           (Has_Unknown_Discriminants (T)
11567              and then Is_Private_Type (T))
11568       then
11569          Error_Msg_N ("invalid constraint: type has no discriminant", C);
11570          Fixup_Bad_Constraint;
11571          return;
11572
11573       elsif Is_Constrained (E)
11574         or else (Ekind (E) = E_Class_Wide_Subtype
11575                   and then Present (Discriminant_Constraint (E)))
11576       then
11577          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
11578          Fixup_Bad_Constraint;
11579          return;
11580       end if;
11581
11582       --  T may be an unconstrained subtype (e.g. a generic actual).
11583       --  Constraint applies to the base type.
11584
11585       T := Base_Type (T);
11586
11587       Elist := Build_Discriminant_Constraints (T, S);
11588
11589       --  If the list returned was empty we had an error in building the
11590       --  discriminant constraint. We have also already signalled an error
11591       --  in the incomplete type case
11592
11593       if Is_Empty_Elmt_List (Elist) then
11594          Fixup_Bad_Constraint;
11595          return;
11596       end if;
11597
11598       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
11599    end Constrain_Discriminated_Type;
11600
11601    ---------------------------
11602    -- Constrain_Enumeration --
11603    ---------------------------
11604
11605    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
11606       T : constant Entity_Id := Entity (Subtype_Mark (S));
11607       C : constant Node_Id   := Constraint (S);
11608
11609    begin
11610       Set_Ekind (Def_Id, E_Enumeration_Subtype);
11611
11612       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
11613
11614       Set_Etype             (Def_Id, Base_Type         (T));
11615       Set_Size_Info         (Def_Id,                   (T));
11616       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
11617       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11618
11619       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11620
11621       Set_Discrete_RM_Size (Def_Id);
11622    end Constrain_Enumeration;
11623
11624    ----------------------
11625    -- Constrain_Float --
11626    ----------------------
11627
11628    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
11629       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11630       C    : Node_Id;
11631       D    : Node_Id;
11632       Rais : Node_Id;
11633
11634    begin
11635       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
11636
11637       Set_Etype          (Def_Id, Base_Type      (T));
11638       Set_Size_Info      (Def_Id,                (T));
11639       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11640
11641       --  Process the constraint
11642
11643       C := Constraint (S);
11644
11645       --  Digits constraint present
11646
11647       if Nkind (C) = N_Digits_Constraint then
11648
11649          Check_SPARK_Restriction ("digits constraint is not allowed", S);
11650          Check_Restriction (No_Obsolescent_Features, C);
11651
11652          if Warn_On_Obsolescent_Feature then
11653             Error_Msg_N
11654               ("subtype digits constraint is an " &
11655                "obsolescent feature (RM J.3(8))?", C);
11656          end if;
11657
11658          D := Digits_Expression (C);
11659          Analyze_And_Resolve (D, Any_Integer);
11660          Check_Digits_Expression (D);
11661          Set_Digits_Value (Def_Id, Expr_Value (D));
11662
11663          --  Check that digits value is in range. Obviously we can do this
11664          --  at compile time, but it is strictly a runtime check, and of
11665          --  course there is an ACVC test that checks this!
11666
11667          if Digits_Value (Def_Id) > Digits_Value (T) then
11668             Error_Msg_Uint_1 := Digits_Value (T);
11669             Error_Msg_N ("?digits value is too large, maximum is ^", D);
11670             Rais :=
11671               Make_Raise_Constraint_Error (Sloc (D),
11672                 Reason => CE_Range_Check_Failed);
11673             Insert_Action (Declaration_Node (Def_Id), Rais);
11674          end if;
11675
11676          C := Range_Constraint (C);
11677
11678       --  No digits constraint present
11679
11680       else
11681          Set_Digits_Value (Def_Id, Digits_Value (T));
11682       end if;
11683
11684       --  Range constraint present
11685
11686       if Nkind (C) = N_Range_Constraint then
11687          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11688
11689       --  No range constraint present
11690
11691       else
11692          pragma Assert (No (C));
11693          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11694       end if;
11695
11696       Set_Is_Constrained (Def_Id);
11697    end Constrain_Float;
11698
11699    ---------------------
11700    -- Constrain_Index --
11701    ---------------------
11702
11703    procedure Constrain_Index
11704      (Index        : Node_Id;
11705       S            : Node_Id;
11706       Related_Nod  : Node_Id;
11707       Related_Id   : Entity_Id;
11708       Suffix       : Character;
11709       Suffix_Index : Nat)
11710    is
11711       Def_Id : Entity_Id;
11712       R      : Node_Id := Empty;
11713       T      : constant Entity_Id := Etype (Index);
11714
11715    begin
11716       if Nkind (S) = N_Range
11717         or else
11718           (Nkind (S) = N_Attribute_Reference
11719             and then Attribute_Name (S) = Name_Range)
11720       then
11721          --  A Range attribute will be transformed into N_Range by Resolve
11722
11723          Analyze (S);
11724          Set_Etype (S, T);
11725          R := S;
11726
11727          Process_Range_Expr_In_Decl (R, T, Empty_List);
11728
11729          if not Error_Posted (S)
11730            and then
11731              (Nkind (S) /= N_Range
11732                or else not Covers (T, (Etype (Low_Bound (S))))
11733                or else not Covers (T, (Etype (High_Bound (S)))))
11734          then
11735             if Base_Type (T) /= Any_Type
11736               and then Etype (Low_Bound (S)) /= Any_Type
11737               and then Etype (High_Bound (S)) /= Any_Type
11738             then
11739                Error_Msg_N ("range expected", S);
11740             end if;
11741          end if;
11742
11743       elsif Nkind (S) = N_Subtype_Indication then
11744
11745          --  The parser has verified that this is a discrete indication
11746
11747          Resolve_Discrete_Subtype_Indication (S, T);
11748          R := Range_Expression (Constraint (S));
11749
11750          --  Capture values of bounds and generate temporaries for them if
11751          --  needed, since checks may cause duplication of the expressions
11752          --  which must not be reevaluated.
11753
11754          if Expander_Active then
11755             Force_Evaluation (Low_Bound (R));
11756             Force_Evaluation (High_Bound (R));
11757          end if;
11758
11759       elsif Nkind (S) = N_Discriminant_Association then
11760
11761          --  Syntactically valid in subtype indication
11762
11763          Error_Msg_N ("invalid index constraint", S);
11764          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11765          return;
11766
11767       --  Subtype_Mark case, no anonymous subtypes to construct
11768
11769       else
11770          Analyze (S);
11771
11772          if Is_Entity_Name (S) then
11773             if not Is_Type (Entity (S)) then
11774                Error_Msg_N ("expect subtype mark for index constraint", S);
11775
11776             elsif Base_Type (Entity (S)) /= Base_Type (T) then
11777                Wrong_Type (S, Base_Type (T));
11778
11779             --  Check error of subtype with predicate in index constraint
11780
11781             else
11782                Bad_Predicated_Subtype_Use
11783                  ("subtype& has predicate, not allowed in index constraint",
11784                   S, Entity (S));
11785             end if;
11786
11787             return;
11788
11789          else
11790             Error_Msg_N ("invalid index constraint", S);
11791             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11792             return;
11793          end if;
11794       end if;
11795
11796       Def_Id :=
11797         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
11798
11799       Set_Etype (Def_Id, Base_Type (T));
11800
11801       if Is_Modular_Integer_Type (T) then
11802          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11803
11804       elsif Is_Integer_Type (T) then
11805          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11806
11807       else
11808          Set_Ekind (Def_Id, E_Enumeration_Subtype);
11809          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11810          Set_First_Literal     (Def_Id, First_Literal (T));
11811       end if;
11812
11813       Set_Size_Info      (Def_Id,                (T));
11814       Set_RM_Size        (Def_Id, RM_Size        (T));
11815       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11816
11817       Set_Scalar_Range   (Def_Id, R);
11818
11819       Set_Etype (S, Def_Id);
11820       Set_Discrete_RM_Size (Def_Id);
11821    end Constrain_Index;
11822
11823    -----------------------
11824    -- Constrain_Integer --
11825    -----------------------
11826
11827    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
11828       T : constant Entity_Id := Entity (Subtype_Mark (S));
11829       C : constant Node_Id   := Constraint (S);
11830
11831    begin
11832       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11833
11834       if Is_Modular_Integer_Type (T) then
11835          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11836       else
11837          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11838       end if;
11839
11840       Set_Etype            (Def_Id, Base_Type        (T));
11841       Set_Size_Info        (Def_Id,                  (T));
11842       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11843       Set_Discrete_RM_Size (Def_Id);
11844    end Constrain_Integer;
11845
11846    ------------------------------
11847    -- Constrain_Ordinary_Fixed --
11848    ------------------------------
11849
11850    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
11851       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11852       C    : Node_Id;
11853       D    : Node_Id;
11854       Rais : Node_Id;
11855
11856    begin
11857       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
11858       Set_Etype          (Def_Id, Base_Type        (T));
11859       Set_Size_Info      (Def_Id,                  (T));
11860       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
11861       Set_Small_Value    (Def_Id, Small_Value      (T));
11862
11863       --  Process the constraint
11864
11865       C := Constraint (S);
11866
11867       --  Delta constraint present
11868
11869       if Nkind (C) = N_Delta_Constraint then
11870
11871          Check_SPARK_Restriction ("delta constraint is not allowed", S);
11872          Check_Restriction (No_Obsolescent_Features, C);
11873
11874          if Warn_On_Obsolescent_Feature then
11875             Error_Msg_S
11876               ("subtype delta constraint is an " &
11877                "obsolescent feature (RM J.3(7))?");
11878          end if;
11879
11880          D := Delta_Expression (C);
11881          Analyze_And_Resolve (D, Any_Real);
11882          Check_Delta_Expression (D);
11883          Set_Delta_Value (Def_Id, Expr_Value_R (D));
11884
11885          --  Check that delta value is in range. Obviously we can do this
11886          --  at compile time, but it is strictly a runtime check, and of
11887          --  course there is an ACVC test that checks this!
11888
11889          if Delta_Value (Def_Id) < Delta_Value (T) then
11890             Error_Msg_N ("?delta value is too small", D);
11891             Rais :=
11892               Make_Raise_Constraint_Error (Sloc (D),
11893                 Reason => CE_Range_Check_Failed);
11894             Insert_Action (Declaration_Node (Def_Id), Rais);
11895          end if;
11896
11897          C := Range_Constraint (C);
11898
11899       --  No delta constraint present
11900
11901       else
11902          Set_Delta_Value (Def_Id, Delta_Value (T));
11903       end if;
11904
11905       --  Range constraint present
11906
11907       if Nkind (C) = N_Range_Constraint then
11908          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11909
11910       --  No range constraint present
11911
11912       else
11913          pragma Assert (No (C));
11914          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11915
11916       end if;
11917
11918       Set_Discrete_RM_Size (Def_Id);
11919
11920       --  Unconditionally delay the freeze, since we cannot set size
11921       --  information in all cases correctly until the freeze point.
11922
11923       Set_Has_Delayed_Freeze (Def_Id);
11924    end Constrain_Ordinary_Fixed;
11925
11926    -----------------------
11927    -- Contain_Interface --
11928    -----------------------
11929
11930    function Contain_Interface
11931      (Iface  : Entity_Id;
11932       Ifaces : Elist_Id) return Boolean
11933    is
11934       Iface_Elmt : Elmt_Id;
11935
11936    begin
11937       if Present (Ifaces) then
11938          Iface_Elmt := First_Elmt (Ifaces);
11939          while Present (Iface_Elmt) loop
11940             if Node (Iface_Elmt) = Iface then
11941                return True;
11942             end if;
11943
11944             Next_Elmt (Iface_Elmt);
11945          end loop;
11946       end if;
11947
11948       return False;
11949    end Contain_Interface;
11950
11951    ---------------------------
11952    -- Convert_Scalar_Bounds --
11953    ---------------------------
11954
11955    procedure Convert_Scalar_Bounds
11956      (N            : Node_Id;
11957       Parent_Type  : Entity_Id;
11958       Derived_Type : Entity_Id;
11959       Loc          : Source_Ptr)
11960    is
11961       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
11962
11963       Lo  : Node_Id;
11964       Hi  : Node_Id;
11965       Rng : Node_Id;
11966
11967    begin
11968       --  Defend against previous errors
11969
11970       if No (Scalar_Range (Derived_Type)) then
11971          return;
11972       end if;
11973
11974       Lo := Build_Scalar_Bound
11975               (Type_Low_Bound (Derived_Type),
11976                Parent_Type, Implicit_Base);
11977
11978       Hi := Build_Scalar_Bound
11979               (Type_High_Bound (Derived_Type),
11980                Parent_Type, Implicit_Base);
11981
11982       Rng :=
11983         Make_Range (Loc,
11984           Low_Bound  => Lo,
11985           High_Bound => Hi);
11986
11987       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
11988
11989       Set_Parent (Rng, N);
11990       Set_Scalar_Range (Derived_Type, Rng);
11991
11992       --  Analyze the bounds
11993
11994       Analyze_And_Resolve (Lo, Implicit_Base);
11995       Analyze_And_Resolve (Hi, Implicit_Base);
11996
11997       --  Analyze the range itself, except that we do not analyze it if
11998       --  the bounds are real literals, and we have a fixed-point type.
11999       --  The reason for this is that we delay setting the bounds in this
12000       --  case till we know the final Small and Size values (see circuit
12001       --  in Freeze.Freeze_Fixed_Point_Type for further details).
12002
12003       if Is_Fixed_Point_Type (Parent_Type)
12004         and then Nkind (Lo) = N_Real_Literal
12005         and then Nkind (Hi) = N_Real_Literal
12006       then
12007          return;
12008
12009       --  Here we do the analysis of the range
12010
12011       --  Note: we do this manually, since if we do a normal Analyze and
12012       --  Resolve call, there are problems with the conversions used for
12013       --  the derived type range.
12014
12015       else
12016          Set_Etype    (Rng, Implicit_Base);
12017          Set_Analyzed (Rng, True);
12018       end if;
12019    end Convert_Scalar_Bounds;
12020
12021    -------------------
12022    -- Copy_And_Swap --
12023    -------------------
12024
12025    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
12026    begin
12027       --  Initialize new full declaration entity by copying the pertinent
12028       --  fields of the corresponding private declaration entity.
12029
12030       --  We temporarily set Ekind to a value appropriate for a type to
12031       --  avoid assert failures in Einfo from checking for setting type
12032       --  attributes on something that is not a type. Ekind (Priv) is an
12033       --  appropriate choice, since it allowed the attributes to be set
12034       --  in the first place. This Ekind value will be modified later.
12035
12036       Set_Ekind (Full, Ekind (Priv));
12037
12038       --  Also set Etype temporarily to Any_Type, again, in the absence
12039       --  of errors, it will be properly reset, and if there are errors,
12040       --  then we want a value of Any_Type to remain.
12041
12042       Set_Etype (Full, Any_Type);
12043
12044       --  Now start copying attributes
12045
12046       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
12047
12048       if Has_Discriminants (Full) then
12049          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
12050          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
12051       end if;
12052
12053       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
12054       Set_Homonym                    (Full, Homonym                 (Priv));
12055       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
12056       Set_Is_Public                  (Full, Is_Public               (Priv));
12057       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
12058       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
12059       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
12060       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
12061       Set_Has_Pragma_Unreferenced_Objects
12062                                      (Full, Has_Pragma_Unreferenced_Objects
12063                                                                     (Priv));
12064
12065       Conditional_Delay              (Full,                          Priv);
12066
12067       if Is_Tagged_Type (Full) then
12068          Set_Direct_Primitive_Operations (Full,
12069            Direct_Primitive_Operations (Priv));
12070
12071          if Is_Base_Type (Priv) then
12072             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
12073          end if;
12074       end if;
12075
12076       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
12077       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
12078       Set_Scope                      (Full, Scope                   (Priv));
12079       Set_Next_Entity                (Full, Next_Entity             (Priv));
12080       Set_First_Entity               (Full, First_Entity            (Priv));
12081       Set_Last_Entity                (Full, Last_Entity             (Priv));
12082
12083       --  If access types have been recorded for later handling, keep them in
12084       --  the full view so that they get handled when the full view freeze
12085       --  node is expanded.
12086
12087       if Present (Freeze_Node (Priv))
12088         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
12089       then
12090          Ensure_Freeze_Node (Full);
12091          Set_Access_Types_To_Process
12092            (Freeze_Node (Full),
12093             Access_Types_To_Process (Freeze_Node (Priv)));
12094       end if;
12095
12096       --  Swap the two entities. Now Private is the full type entity and Full
12097       --  is the private one. They will be swapped back at the end of the
12098       --  private part. This swapping ensures that the entity that is visible
12099       --  in the private part is the full declaration.
12100
12101       Exchange_Entities (Priv, Full);
12102       Append_Entity (Full, Scope (Full));
12103    end Copy_And_Swap;
12104
12105    -------------------------------------
12106    -- Copy_Array_Base_Type_Attributes --
12107    -------------------------------------
12108
12109    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
12110    begin
12111       Set_Component_Alignment      (T1, Component_Alignment      (T2));
12112       Set_Component_Type           (T1, Component_Type           (T2));
12113       Set_Component_Size           (T1, Component_Size           (T2));
12114       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
12115       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
12116       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
12117       Set_Has_Task                 (T1, Has_Task                 (T2));
12118       Set_Is_Packed                (T1, Is_Packed                (T2));
12119       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
12120       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
12121       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
12122    end Copy_Array_Base_Type_Attributes;
12123
12124    -----------------------------------
12125    -- Copy_Array_Subtype_Attributes --
12126    -----------------------------------
12127
12128    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
12129    begin
12130       Set_Size_Info (T1, T2);
12131
12132       Set_First_Index          (T1, First_Index           (T2));
12133       Set_Is_Aliased           (T1, Is_Aliased            (T2));
12134       Set_Is_Atomic            (T1, Is_Atomic             (T2));
12135       Set_Is_Volatile          (T1, Is_Volatile           (T2));
12136       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
12137       Set_Is_Constrained       (T1, Is_Constrained        (T2));
12138       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
12139       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
12140       Set_Convention           (T1, Convention            (T2));
12141       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
12142       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
12143       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
12144    end Copy_Array_Subtype_Attributes;
12145
12146    -----------------------------------
12147    -- Create_Constrained_Components --
12148    -----------------------------------
12149
12150    procedure Create_Constrained_Components
12151      (Subt        : Entity_Id;
12152       Decl_Node   : Node_Id;
12153       Typ         : Entity_Id;
12154       Constraints : Elist_Id)
12155    is
12156       Loc         : constant Source_Ptr := Sloc (Subt);
12157       Comp_List   : constant Elist_Id   := New_Elmt_List;
12158       Parent_Type : constant Entity_Id  := Etype (Typ);
12159       Assoc_List  : constant List_Id    := New_List;
12160       Discr_Val   : Elmt_Id;
12161       Errors      : Boolean;
12162       New_C       : Entity_Id;
12163       Old_C       : Entity_Id;
12164       Is_Static   : Boolean := True;
12165
12166       procedure Collect_Fixed_Components (Typ : Entity_Id);
12167       --  Collect parent type components that do not appear in a variant part
12168
12169       procedure Create_All_Components;
12170       --  Iterate over Comp_List to create the components of the subtype
12171
12172       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
12173       --  Creates a new component from Old_Compon, copying all the fields from
12174       --  it, including its Etype, inserts the new component in the Subt entity
12175       --  chain and returns the new component.
12176
12177       function Is_Variant_Record (T : Entity_Id) return Boolean;
12178       --  If true, and discriminants are static, collect only components from
12179       --  variants selected by discriminant values.
12180
12181       ------------------------------
12182       -- Collect_Fixed_Components --
12183       ------------------------------
12184
12185       procedure Collect_Fixed_Components (Typ : Entity_Id) is
12186       begin
12187       --  Build association list for discriminants, and find components of the
12188       --  variant part selected by the values of the discriminants.
12189
12190          Old_C := First_Discriminant (Typ);
12191          Discr_Val := First_Elmt (Constraints);
12192          while Present (Old_C) loop
12193             Append_To (Assoc_List,
12194               Make_Component_Association (Loc,
12195                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
12196                  Expression => New_Copy (Node (Discr_Val))));
12197
12198             Next_Elmt (Discr_Val);
12199             Next_Discriminant (Old_C);
12200          end loop;
12201
12202          --  The tag and the possible parent component are unconditionally in
12203          --  the subtype.
12204
12205          if Is_Tagged_Type (Typ)
12206            or else Has_Controlled_Component (Typ)
12207          then
12208             Old_C := First_Component (Typ);
12209             while Present (Old_C) loop
12210                if Chars ((Old_C)) = Name_uTag
12211                  or else Chars ((Old_C)) = Name_uParent
12212                then
12213                   Append_Elmt (Old_C, Comp_List);
12214                end if;
12215
12216                Next_Component (Old_C);
12217             end loop;
12218          end if;
12219       end Collect_Fixed_Components;
12220
12221       ---------------------------
12222       -- Create_All_Components --
12223       ---------------------------
12224
12225       procedure Create_All_Components is
12226          Comp : Elmt_Id;
12227
12228       begin
12229          Comp := First_Elmt (Comp_List);
12230          while Present (Comp) loop
12231             Old_C := Node (Comp);
12232             New_C := Create_Component (Old_C);
12233
12234             Set_Etype
12235               (New_C,
12236                Constrain_Component_Type
12237                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12238             Set_Is_Public (New_C, Is_Public (Subt));
12239
12240             Next_Elmt (Comp);
12241          end loop;
12242       end Create_All_Components;
12243
12244       ----------------------
12245       -- Create_Component --
12246       ----------------------
12247
12248       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
12249          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
12250
12251       begin
12252          if Ekind (Old_Compon) = E_Discriminant
12253            and then Is_Completely_Hidden (Old_Compon)
12254          then
12255             --  This is a shadow discriminant created for a discriminant of
12256             --  the parent type, which needs to be present in the subtype.
12257             --  Give the shadow discriminant an internal name that cannot
12258             --  conflict with that of visible components.
12259
12260             Set_Chars (New_Compon, New_Internal_Name ('C'));
12261          end if;
12262
12263          --  Set the parent so we have a proper link for freezing etc. This is
12264          --  not a real parent pointer, since of course our parent does not own
12265          --  up to us and reference us, we are an illegitimate child of the
12266          --  original parent!
12267
12268          Set_Parent (New_Compon, Parent (Old_Compon));
12269
12270          --  If the old component's Esize was already determined and is a
12271          --  static value, then the new component simply inherits it. Otherwise
12272          --  the old component's size may require run-time determination, but
12273          --  the new component's size still might be statically determinable
12274          --  (if, for example it has a static constraint). In that case we want
12275          --  Layout_Type to recompute the component's size, so we reset its
12276          --  size and positional fields.
12277
12278          if Frontend_Layout_On_Target
12279            and then not Known_Static_Esize (Old_Compon)
12280          then
12281             Set_Esize (New_Compon, Uint_0);
12282             Init_Normalized_First_Bit    (New_Compon);
12283             Init_Normalized_Position     (New_Compon);
12284             Init_Normalized_Position_Max (New_Compon);
12285          end if;
12286
12287          --  We do not want this node marked as Comes_From_Source, since
12288          --  otherwise it would get first class status and a separate cross-
12289          --  reference line would be generated. Illegitimate children do not
12290          --  rate such recognition.
12291
12292          Set_Comes_From_Source (New_Compon, False);
12293
12294          --  But it is a real entity, and a birth certificate must be properly
12295          --  registered by entering it into the entity list.
12296
12297          Enter_Name (New_Compon);
12298
12299          return New_Compon;
12300       end Create_Component;
12301
12302       -----------------------
12303       -- Is_Variant_Record --
12304       -----------------------
12305
12306       function Is_Variant_Record (T : Entity_Id) return Boolean is
12307       begin
12308          return Nkind (Parent (T)) = N_Full_Type_Declaration
12309            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
12310            and then Present (Component_List (Type_Definition (Parent (T))))
12311            and then
12312              Present
12313                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
12314       end Is_Variant_Record;
12315
12316    --  Start of processing for Create_Constrained_Components
12317
12318    begin
12319       pragma Assert (Subt /= Base_Type (Subt));
12320       pragma Assert (Typ = Base_Type (Typ));
12321
12322       Set_First_Entity (Subt, Empty);
12323       Set_Last_Entity  (Subt, Empty);
12324
12325       --  Check whether constraint is fully static, in which case we can
12326       --  optimize the list of components.
12327
12328       Discr_Val := First_Elmt (Constraints);
12329       while Present (Discr_Val) loop
12330          if not Is_OK_Static_Expression (Node (Discr_Val)) then
12331             Is_Static := False;
12332             exit;
12333          end if;
12334
12335          Next_Elmt (Discr_Val);
12336       end loop;
12337
12338       Set_Has_Static_Discriminants (Subt, Is_Static);
12339
12340       Push_Scope (Subt);
12341
12342       --  Inherit the discriminants of the parent type
12343
12344       Add_Discriminants : declare
12345          Num_Disc : Int;
12346          Num_Gird : Int;
12347
12348       begin
12349          Num_Disc := 0;
12350          Old_C := First_Discriminant (Typ);
12351
12352          while Present (Old_C) loop
12353             Num_Disc := Num_Disc + 1;
12354             New_C := Create_Component (Old_C);
12355             Set_Is_Public (New_C, Is_Public (Subt));
12356             Next_Discriminant (Old_C);
12357          end loop;
12358
12359          --  For an untagged derived subtype, the number of discriminants may
12360          --  be smaller than the number of inherited discriminants, because
12361          --  several of them may be renamed by a single new discriminant or
12362          --  constrained. In this case, add the hidden discriminants back into
12363          --  the subtype, because they need to be present if the optimizer of
12364          --  the GCC 4.x back-end decides to break apart assignments between
12365          --  objects using the parent view into member-wise assignments.
12366
12367          Num_Gird := 0;
12368
12369          if Is_Derived_Type (Typ)
12370            and then not Is_Tagged_Type (Typ)
12371          then
12372             Old_C := First_Stored_Discriminant (Typ);
12373
12374             while Present (Old_C) loop
12375                Num_Gird := Num_Gird + 1;
12376                Next_Stored_Discriminant (Old_C);
12377             end loop;
12378          end if;
12379
12380          if Num_Gird > Num_Disc then
12381
12382             --  Find out multiple uses of new discriminants, and add hidden
12383             --  components for the extra renamed discriminants. We recognize
12384             --  multiple uses through the Corresponding_Discriminant of a
12385             --  new discriminant: if it constrains several old discriminants,
12386             --  this field points to the last one in the parent type. The
12387             --  stored discriminants of the derived type have the same name
12388             --  as those of the parent.
12389
12390             declare
12391                Constr    : Elmt_Id;
12392                New_Discr : Entity_Id;
12393                Old_Discr : Entity_Id;
12394
12395             begin
12396                Constr    := First_Elmt (Stored_Constraint (Typ));
12397                Old_Discr := First_Stored_Discriminant (Typ);
12398                while Present (Constr) loop
12399                   if Is_Entity_Name (Node (Constr))
12400                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
12401                   then
12402                      New_Discr := Entity (Node (Constr));
12403
12404                      if Chars (Corresponding_Discriminant (New_Discr)) /=
12405                         Chars (Old_Discr)
12406                      then
12407                         --  The new discriminant has been used to rename a
12408                         --  subsequent old discriminant. Introduce a shadow
12409                         --  component for the current old discriminant.
12410
12411                         New_C := Create_Component (Old_Discr);
12412                         Set_Original_Record_Component (New_C, Old_Discr);
12413                      end if;
12414
12415                   else
12416                      --  The constraint has eliminated the old discriminant.
12417                      --  Introduce a shadow component.
12418
12419                      New_C := Create_Component (Old_Discr);
12420                      Set_Original_Record_Component (New_C, Old_Discr);
12421                   end if;
12422
12423                   Next_Elmt (Constr);
12424                   Next_Stored_Discriminant (Old_Discr);
12425                end loop;
12426             end;
12427          end if;
12428       end Add_Discriminants;
12429
12430       if Is_Static
12431         and then Is_Variant_Record (Typ)
12432       then
12433          Collect_Fixed_Components (Typ);
12434
12435          Gather_Components (
12436            Typ,
12437            Component_List (Type_Definition (Parent (Typ))),
12438            Governed_By   => Assoc_List,
12439            Into          => Comp_List,
12440            Report_Errors => Errors);
12441          pragma Assert (not Errors);
12442
12443          Create_All_Components;
12444
12445       --  If the subtype declaration is created for a tagged type derivation
12446       --  with constraints, we retrieve the record definition of the parent
12447       --  type to select the components of the proper variant.
12448
12449       elsif Is_Static
12450         and then Is_Tagged_Type (Typ)
12451         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
12452         and then
12453           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
12454         and then Is_Variant_Record (Parent_Type)
12455       then
12456          Collect_Fixed_Components (Typ);
12457
12458          Gather_Components (
12459            Typ,
12460            Component_List (Type_Definition (Parent (Parent_Type))),
12461            Governed_By   => Assoc_List,
12462            Into          => Comp_List,
12463            Report_Errors => Errors);
12464          pragma Assert (not Errors);
12465
12466          --  If the tagged derivation has a type extension, collect all the
12467          --  new components therein.
12468
12469          if Present
12470               (Record_Extension_Part (Type_Definition (Parent (Typ))))
12471          then
12472             Old_C := First_Component (Typ);
12473             while Present (Old_C) loop
12474                if Original_Record_Component (Old_C) = Old_C
12475                 and then Chars (Old_C) /= Name_uTag
12476                 and then Chars (Old_C) /= Name_uParent
12477                then
12478                   Append_Elmt (Old_C, Comp_List);
12479                end if;
12480
12481                Next_Component (Old_C);
12482             end loop;
12483          end if;
12484
12485          Create_All_Components;
12486
12487       else
12488          --  If discriminants are not static, or if this is a multi-level type
12489          --  extension, we have to include all components of the parent type.
12490
12491          Old_C := First_Component (Typ);
12492          while Present (Old_C) loop
12493             New_C := Create_Component (Old_C);
12494
12495             Set_Etype
12496               (New_C,
12497                Constrain_Component_Type
12498                  (Old_C, Subt, Decl_Node, Typ, Constraints));
12499             Set_Is_Public (New_C, Is_Public (Subt));
12500
12501             Next_Component (Old_C);
12502          end loop;
12503       end if;
12504
12505       End_Scope;
12506    end Create_Constrained_Components;
12507
12508    ------------------------------------------
12509    -- Decimal_Fixed_Point_Type_Declaration --
12510    ------------------------------------------
12511
12512    procedure Decimal_Fixed_Point_Type_Declaration
12513      (T   : Entity_Id;
12514       Def : Node_Id)
12515    is
12516       Loc           : constant Source_Ptr := Sloc (Def);
12517       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
12518       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
12519       Implicit_Base : Entity_Id;
12520       Digs_Val      : Uint;
12521       Delta_Val     : Ureal;
12522       Scale_Val     : Uint;
12523       Bound_Val     : Ureal;
12524
12525    begin
12526       Check_SPARK_Restriction
12527         ("decimal fixed point type is not allowed", Def);
12528       Check_Restriction (No_Fixed_Point, Def);
12529
12530       --  Create implicit base type
12531
12532       Implicit_Base :=
12533         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
12534       Set_Etype (Implicit_Base, Implicit_Base);
12535
12536       --  Analyze and process delta expression
12537
12538       Analyze_And_Resolve (Delta_Expr, Universal_Real);
12539
12540       Check_Delta_Expression (Delta_Expr);
12541       Delta_Val := Expr_Value_R (Delta_Expr);
12542
12543       --  Check delta is power of 10, and determine scale value from it
12544
12545       declare
12546          Val : Ureal;
12547
12548       begin
12549          Scale_Val := Uint_0;
12550          Val := Delta_Val;
12551
12552          if Val < Ureal_1 then
12553             while Val < Ureal_1 loop
12554                Val := Val * Ureal_10;
12555                Scale_Val := Scale_Val + 1;
12556             end loop;
12557
12558             if Scale_Val > 18 then
12559                Error_Msg_N ("scale exceeds maximum value of 18", Def);
12560                Scale_Val := UI_From_Int (+18);
12561             end if;
12562
12563          else
12564             while Val > Ureal_1 loop
12565                Val := Val / Ureal_10;
12566                Scale_Val := Scale_Val - 1;
12567             end loop;
12568
12569             if Scale_Val < -18 then
12570                Error_Msg_N ("scale is less than minimum value of -18", Def);
12571                Scale_Val := UI_From_Int (-18);
12572             end if;
12573          end if;
12574
12575          if Val /= Ureal_1 then
12576             Error_Msg_N ("delta expression must be a power of 10", Def);
12577             Delta_Val := Ureal_10 ** (-Scale_Val);
12578          end if;
12579       end;
12580
12581       --  Set delta, scale and small (small = delta for decimal type)
12582
12583       Set_Delta_Value (Implicit_Base, Delta_Val);
12584       Set_Scale_Value (Implicit_Base, Scale_Val);
12585       Set_Small_Value (Implicit_Base, Delta_Val);
12586
12587       --  Analyze and process digits expression
12588
12589       Analyze_And_Resolve (Digs_Expr, Any_Integer);
12590       Check_Digits_Expression (Digs_Expr);
12591       Digs_Val := Expr_Value (Digs_Expr);
12592
12593       if Digs_Val > 18 then
12594          Digs_Val := UI_From_Int (+18);
12595          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
12596       end if;
12597
12598       Set_Digits_Value (Implicit_Base, Digs_Val);
12599       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
12600
12601       --  Set range of base type from digits value for now. This will be
12602       --  expanded to represent the true underlying base range by Freeze.
12603
12604       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
12605
12606       --  Note: We leave size as zero for now, size will be set at freeze
12607       --  time. We have to do this for ordinary fixed-point, because the size
12608       --  depends on the specified small, and we might as well do the same for
12609       --  decimal fixed-point.
12610
12611       pragma Assert (Esize (Implicit_Base) = Uint_0);
12612
12613       --  If there are bounds given in the declaration use them as the
12614       --  bounds of the first named subtype.
12615
12616       if Present (Real_Range_Specification (Def)) then
12617          declare
12618             RRS      : constant Node_Id := Real_Range_Specification (Def);
12619             Low      : constant Node_Id := Low_Bound (RRS);
12620             High     : constant Node_Id := High_Bound (RRS);
12621             Low_Val  : Ureal;
12622             High_Val : Ureal;
12623
12624          begin
12625             Analyze_And_Resolve (Low, Any_Real);
12626             Analyze_And_Resolve (High, Any_Real);
12627             Check_Real_Bound (Low);
12628             Check_Real_Bound (High);
12629             Low_Val := Expr_Value_R (Low);
12630             High_Val := Expr_Value_R (High);
12631
12632             if Low_Val < (-Bound_Val) then
12633                Error_Msg_N
12634                  ("range low bound too small for digits value", Low);
12635                Low_Val := -Bound_Val;
12636             end if;
12637
12638             if High_Val > Bound_Val then
12639                Error_Msg_N
12640                  ("range high bound too large for digits value", High);
12641                High_Val := Bound_Val;
12642             end if;
12643
12644             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
12645          end;
12646
12647       --  If no explicit range, use range that corresponds to given
12648       --  digits value. This will end up as the final range for the
12649       --  first subtype.
12650
12651       else
12652          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
12653       end if;
12654
12655       --  Complete entity for first subtype
12656
12657       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
12658       Set_Etype          (T, Implicit_Base);
12659       Set_Size_Info      (T, Implicit_Base);
12660       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
12661       Set_Digits_Value   (T, Digs_Val);
12662       Set_Delta_Value    (T, Delta_Val);
12663       Set_Small_Value    (T, Delta_Val);
12664       Set_Scale_Value    (T, Scale_Val);
12665       Set_Is_Constrained (T);
12666    end Decimal_Fixed_Point_Type_Declaration;
12667
12668    -----------------------------------
12669    -- Derive_Progenitor_Subprograms --
12670    -----------------------------------
12671
12672    procedure Derive_Progenitor_Subprograms
12673      (Parent_Type : Entity_Id;
12674       Tagged_Type : Entity_Id)
12675    is
12676       E          : Entity_Id;
12677       Elmt       : Elmt_Id;
12678       Iface      : Entity_Id;
12679       Iface_Elmt : Elmt_Id;
12680       Iface_Subp : Entity_Id;
12681       New_Subp   : Entity_Id := Empty;
12682       Prim_Elmt  : Elmt_Id;
12683       Subp       : Entity_Id;
12684       Typ        : Entity_Id;
12685
12686    begin
12687       pragma Assert (Ada_Version >= Ada_2005
12688         and then Is_Record_Type (Tagged_Type)
12689         and then Is_Tagged_Type (Tagged_Type)
12690         and then Has_Interfaces (Tagged_Type));
12691
12692       --  Step 1: Transfer to the full-view primitives associated with the
12693       --  partial-view that cover interface primitives. Conceptually this
12694       --  work should be done later by Process_Full_View; done here to
12695       --  simplify its implementation at later stages. It can be safely
12696       --  done here because interfaces must be visible in the partial and
12697       --  private view (RM 7.3(7.3/2)).
12698
12699       --  Small optimization: This work is only required if the parent is
12700       --  abstract. If the tagged type is not abstract, it cannot have
12701       --  abstract primitives (the only entities in the list of primitives of
12702       --  non-abstract tagged types that can reference abstract primitives
12703       --  through its Alias attribute are the internal entities that have
12704       --  attribute Interface_Alias, and these entities are generated later
12705       --  by Add_Internal_Interface_Entities).
12706
12707       if In_Private_Part (Current_Scope)
12708         and then Is_Abstract_Type (Parent_Type)
12709       then
12710          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
12711          while Present (Elmt) loop
12712             Subp := Node (Elmt);
12713
12714             --  At this stage it is not possible to have entities in the list
12715             --  of primitives that have attribute Interface_Alias
12716
12717             pragma Assert (No (Interface_Alias (Subp)));
12718
12719             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
12720
12721             if Is_Interface (Typ) then
12722                E := Find_Primitive_Covering_Interface
12723                       (Tagged_Type => Tagged_Type,
12724                        Iface_Prim  => Subp);
12725
12726                if Present (E)
12727                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
12728                then
12729                   Replace_Elmt (Elmt, E);
12730                   Remove_Homonym (Subp);
12731                end if;
12732             end if;
12733
12734             Next_Elmt (Elmt);
12735          end loop;
12736       end if;
12737
12738       --  Step 2: Add primitives of progenitors that are not implemented by
12739       --  parents of Tagged_Type
12740
12741       if Present (Interfaces (Base_Type (Tagged_Type))) then
12742          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
12743          while Present (Iface_Elmt) loop
12744             Iface := Node (Iface_Elmt);
12745
12746             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
12747             while Present (Prim_Elmt) loop
12748                Iface_Subp := Node (Prim_Elmt);
12749
12750                --  Exclude derivation of predefined primitives except those
12751                --  that come from source. Required to catch declarations of
12752                --  equality operators of interfaces. For example:
12753
12754                --     type Iface is interface;
12755                --     function "=" (Left, Right : Iface) return Boolean;
12756
12757                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
12758                  or else Comes_From_Source (Iface_Subp)
12759                then
12760                   E := Find_Primitive_Covering_Interface
12761                          (Tagged_Type => Tagged_Type,
12762                           Iface_Prim  => Iface_Subp);
12763
12764                   --  If not found we derive a new primitive leaving its alias
12765                   --  attribute referencing the interface primitive
12766
12767                   if No (E) then
12768                      Derive_Subprogram
12769                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12770
12771                   --  Ada 2012 (AI05-0197): If the covering primitive's name
12772                   --  differs from the name of the interface primitive then it
12773                   --  is a private primitive inherited from a parent type. In
12774                   --  such case, given that Tagged_Type covers the interface,
12775                   --  the inherited private primitive becomes visible. For such
12776                   --  purpose we add a new entity that renames the inherited
12777                   --  private primitive.
12778
12779                   elsif Chars (E) /= Chars (Iface_Subp) then
12780                      pragma Assert (Has_Suffix (E, 'P'));
12781                      Derive_Subprogram
12782                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12783                      Set_Alias (New_Subp, E);
12784                      Set_Is_Abstract_Subprogram (New_Subp,
12785                        Is_Abstract_Subprogram (E));
12786
12787                   --  Propagate to the full view interface entities associated
12788                   --  with the partial view
12789
12790                   elsif In_Private_Part (Current_Scope)
12791                     and then Present (Alias (E))
12792                     and then Alias (E) = Iface_Subp
12793                     and then
12794                       List_Containing (Parent (E)) /=
12795                         Private_Declarations
12796                           (Specification
12797                             (Unit_Declaration_Node (Current_Scope)))
12798                   then
12799                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
12800                   end if;
12801                end if;
12802
12803                Next_Elmt (Prim_Elmt);
12804             end loop;
12805
12806             Next_Elmt (Iface_Elmt);
12807          end loop;
12808       end if;
12809    end Derive_Progenitor_Subprograms;
12810
12811    -----------------------
12812    -- Derive_Subprogram --
12813    -----------------------
12814
12815    procedure Derive_Subprogram
12816      (New_Subp     : in out Entity_Id;
12817       Parent_Subp  : Entity_Id;
12818       Derived_Type : Entity_Id;
12819       Parent_Type  : Entity_Id;
12820       Actual_Subp  : Entity_Id := Empty)
12821    is
12822       Formal : Entity_Id;
12823       --  Formal parameter of parent primitive operation
12824
12825       Formal_Of_Actual : Entity_Id;
12826       --  Formal parameter of actual operation, when the derivation is to
12827       --  create a renaming for a primitive operation of an actual in an
12828       --  instantiation.
12829
12830       New_Formal : Entity_Id;
12831       --  Formal of inherited operation
12832
12833       Visible_Subp : Entity_Id := Parent_Subp;
12834
12835       function Is_Private_Overriding return Boolean;
12836       --  If Subp is a private overriding of a visible operation, the inherited
12837       --  operation derives from the overridden op (even though its body is the
12838       --  overriding one) and the inherited operation is visible now. See
12839       --  sem_disp to see the full details of the handling of the overridden
12840       --  subprogram, which is removed from the list of primitive operations of
12841       --  the type. The overridden subprogram is saved locally in Visible_Subp,
12842       --  and used to diagnose abstract operations that need overriding in the
12843       --  derived type.
12844
12845       procedure Replace_Type (Id, New_Id : Entity_Id);
12846       --  When the type is an anonymous access type, create a new access type
12847       --  designating the derived type.
12848
12849       procedure Set_Derived_Name;
12850       --  This procedure sets the appropriate Chars name for New_Subp. This
12851       --  is normally just a copy of the parent name. An exception arises for
12852       --  type support subprograms, where the name is changed to reflect the
12853       --  name of the derived type, e.g. if type foo is derived from type bar,
12854       --  then a procedure barDA is derived with a name fooDA.
12855
12856       ---------------------------
12857       -- Is_Private_Overriding --
12858       ---------------------------
12859
12860       function Is_Private_Overriding return Boolean is
12861          Prev : Entity_Id;
12862
12863       begin
12864          --  If the parent is not a dispatching operation there is no
12865          --  need to investigate overridings
12866
12867          if not Is_Dispatching_Operation (Parent_Subp) then
12868             return False;
12869          end if;
12870
12871          --  The visible operation that is overridden is a homonym of the
12872          --  parent subprogram. We scan the homonym chain to find the one
12873          --  whose alias is the subprogram we are deriving.
12874
12875          Prev := Current_Entity (Parent_Subp);
12876          while Present (Prev) loop
12877             if Ekind (Prev) = Ekind (Parent_Subp)
12878               and then Alias (Prev) = Parent_Subp
12879               and then Scope (Parent_Subp) = Scope (Prev)
12880               and then not Is_Hidden (Prev)
12881             then
12882                Visible_Subp := Prev;
12883                return True;
12884             end if;
12885
12886             Prev := Homonym (Prev);
12887          end loop;
12888
12889          return False;
12890       end Is_Private_Overriding;
12891
12892       ------------------
12893       -- Replace_Type --
12894       ------------------
12895
12896       procedure Replace_Type (Id, New_Id : Entity_Id) is
12897          Acc_Type : Entity_Id;
12898          Par      : constant Node_Id := Parent (Derived_Type);
12899
12900       begin
12901          --  When the type is an anonymous access type, create a new access
12902          --  type designating the derived type. This itype must be elaborated
12903          --  at the point of the derivation, not on subsequent calls that may
12904          --  be out of the proper scope for Gigi, so we insert a reference to
12905          --  it after the derivation.
12906
12907          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
12908             declare
12909                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
12910
12911             begin
12912                if Ekind (Desig_Typ) = E_Record_Type_With_Private
12913                  and then Present (Full_View (Desig_Typ))
12914                  and then not Is_Private_Type (Parent_Type)
12915                then
12916                   Desig_Typ := Full_View (Desig_Typ);
12917                end if;
12918
12919                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
12920
12921                   --  Ada 2005 (AI-251): Handle also derivations of abstract
12922                   --  interface primitives.
12923
12924                  or else (Is_Interface (Desig_Typ)
12925                           and then not Is_Class_Wide_Type (Desig_Typ))
12926                then
12927                   Acc_Type := New_Copy (Etype (Id));
12928                   Set_Etype (Acc_Type, Acc_Type);
12929                   Set_Scope (Acc_Type, New_Subp);
12930
12931                   --  Compute size of anonymous access type
12932
12933                   if Is_Array_Type (Desig_Typ)
12934                     and then not Is_Constrained (Desig_Typ)
12935                   then
12936                      Init_Size (Acc_Type, 2 * System_Address_Size);
12937                   else
12938                      Init_Size (Acc_Type, System_Address_Size);
12939                   end if;
12940
12941                   Init_Alignment (Acc_Type);
12942                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
12943
12944                   Set_Etype (New_Id, Acc_Type);
12945                   Set_Scope (New_Id, New_Subp);
12946
12947                   --  Create a reference to it
12948                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
12949
12950                else
12951                   Set_Etype (New_Id, Etype (Id));
12952                end if;
12953             end;
12954
12955          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
12956            or else
12957              (Ekind (Etype (Id)) = E_Record_Type_With_Private
12958                and then Present (Full_View (Etype (Id)))
12959                and then
12960                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
12961          then
12962             --  Constraint checks on formals are generated during expansion,
12963             --  based on the signature of the original subprogram. The bounds
12964             --  of the derived type are not relevant, and thus we can use
12965             --  the base type for the formals. However, the return type may be
12966             --  used in a context that requires that the proper static bounds
12967             --  be used (a case statement, for example)  and for those cases
12968             --  we must use the derived type (first subtype), not its base.
12969
12970             --  If the derived_type_definition has no constraints, we know that
12971             --  the derived type has the same constraints as the first subtype
12972             --  of the parent, and we can also use it rather than its base,
12973             --  which can lead to more efficient code.
12974
12975             if Etype (Id) = Parent_Type then
12976                if Is_Scalar_Type (Parent_Type)
12977                  and then
12978                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
12979                then
12980                   Set_Etype (New_Id, Derived_Type);
12981
12982                elsif Nkind (Par) = N_Full_Type_Declaration
12983                  and then
12984                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
12985                  and then
12986                    Is_Entity_Name
12987                      (Subtype_Indication (Type_Definition (Par)))
12988                then
12989                   Set_Etype (New_Id, Derived_Type);
12990
12991                else
12992                   Set_Etype (New_Id, Base_Type (Derived_Type));
12993                end if;
12994
12995             else
12996                Set_Etype (New_Id, Base_Type (Derived_Type));
12997             end if;
12998
12999          else
13000             Set_Etype (New_Id, Etype (Id));
13001          end if;
13002       end Replace_Type;
13003
13004       ----------------------
13005       -- Set_Derived_Name --
13006       ----------------------
13007
13008       procedure Set_Derived_Name is
13009          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
13010       begin
13011          if Nm = TSS_Null then
13012             Set_Chars (New_Subp, Chars (Parent_Subp));
13013          else
13014             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
13015          end if;
13016       end Set_Derived_Name;
13017
13018    --  Start of processing for Derive_Subprogram
13019
13020    begin
13021       New_Subp :=
13022          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
13023       Set_Ekind (New_Subp, Ekind (Parent_Subp));
13024       Set_Contract (New_Subp, Make_Contract (Sloc (New_Subp)));
13025
13026       --  Check whether the inherited subprogram is a private operation that
13027       --  should be inherited but not yet made visible. Such subprograms can
13028       --  become visible at a later point (e.g., the private part of a public
13029       --  child unit) via Declare_Inherited_Private_Subprograms. If the
13030       --  following predicate is true, then this is not such a private
13031       --  operation and the subprogram simply inherits the name of the parent
13032       --  subprogram. Note the special check for the names of controlled
13033       --  operations, which are currently exempted from being inherited with
13034       --  a hidden name because they must be findable for generation of
13035       --  implicit run-time calls.
13036
13037       if not Is_Hidden (Parent_Subp)
13038         or else Is_Internal (Parent_Subp)
13039         or else Is_Private_Overriding
13040         or else Is_Internal_Name (Chars (Parent_Subp))
13041         or else Chars (Parent_Subp) = Name_Initialize
13042         or else Chars (Parent_Subp) = Name_Adjust
13043         or else Chars (Parent_Subp) = Name_Finalize
13044       then
13045          Set_Derived_Name;
13046
13047       --  An inherited dispatching equality will be overridden by an internally
13048       --  generated one, or by an explicit one, so preserve its name and thus
13049       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
13050       --  private operation it may become invisible if the full view has
13051       --  progenitors, and the dispatch table will be malformed.
13052       --  We check that the type is limited to handle the anomalous declaration
13053       --  of Limited_Controlled, which is derived from a non-limited type, and
13054       --  which is handled specially elsewhere as well.
13055
13056       elsif Chars (Parent_Subp) = Name_Op_Eq
13057         and then Is_Dispatching_Operation (Parent_Subp)
13058         and then Etype (Parent_Subp) = Standard_Boolean
13059         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
13060         and then
13061           Etype (First_Formal (Parent_Subp)) =
13062             Etype (Next_Formal (First_Formal (Parent_Subp)))
13063       then
13064          Set_Derived_Name;
13065
13066       --  If parent is hidden, this can be a regular derivation if the
13067       --  parent is immediately visible in a non-instantiating context,
13068       --  or if we are in the private part of an instance. This test
13069       --  should still be refined ???
13070
13071       --  The test for In_Instance_Not_Visible avoids inheriting the derived
13072       --  operation as a non-visible operation in cases where the parent
13073       --  subprogram might not be visible now, but was visible within the
13074       --  original generic, so it would be wrong to make the inherited
13075       --  subprogram non-visible now. (Not clear if this test is fully
13076       --  correct; are there any cases where we should declare the inherited
13077       --  operation as not visible to avoid it being overridden, e.g., when
13078       --  the parent type is a generic actual with private primitives ???)
13079
13080       --  (they should be treated the same as other private inherited
13081       --  subprograms, but it's not clear how to do this cleanly). ???
13082
13083       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
13084               and then Is_Immediately_Visible (Parent_Subp)
13085               and then not In_Instance)
13086         or else In_Instance_Not_Visible
13087       then
13088          Set_Derived_Name;
13089
13090       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
13091       --  overrides an interface primitive because interface primitives
13092       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
13093
13094       elsif Ada_Version >= Ada_2005
13095          and then Is_Dispatching_Operation (Parent_Subp)
13096          and then Covers_Some_Interface (Parent_Subp)
13097       then
13098          Set_Derived_Name;
13099
13100       --  Otherwise, the type is inheriting a private operation, so enter
13101       --  it with a special name so it can't be overridden.
13102
13103       else
13104          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
13105       end if;
13106
13107       Set_Parent (New_Subp, Parent (Derived_Type));
13108
13109       if Present (Actual_Subp) then
13110          Replace_Type (Actual_Subp, New_Subp);
13111       else
13112          Replace_Type (Parent_Subp, New_Subp);
13113       end if;
13114
13115       Conditional_Delay (New_Subp, Parent_Subp);
13116
13117       --  If we are creating a renaming for a primitive operation of an
13118       --  actual of a generic derived type, we must examine the signature
13119       --  of the actual primitive, not that of the generic formal, which for
13120       --  example may be an interface. However the name and initial value
13121       --  of the inherited operation are those of the formal primitive.
13122
13123       Formal := First_Formal (Parent_Subp);
13124
13125       if Present (Actual_Subp) then
13126          Formal_Of_Actual := First_Formal (Actual_Subp);
13127       else
13128          Formal_Of_Actual := Empty;
13129       end if;
13130
13131       while Present (Formal) loop
13132          New_Formal := New_Copy (Formal);
13133
13134          --  Normally we do not go copying parents, but in the case of
13135          --  formals, we need to link up to the declaration (which is the
13136          --  parameter specification), and it is fine to link up to the
13137          --  original formal's parameter specification in this case.
13138
13139          Set_Parent (New_Formal, Parent (Formal));
13140          Append_Entity (New_Formal, New_Subp);
13141
13142          if Present (Formal_Of_Actual) then
13143             Replace_Type (Formal_Of_Actual, New_Formal);
13144             Next_Formal (Formal_Of_Actual);
13145          else
13146             Replace_Type (Formal, New_Formal);
13147          end if;
13148
13149          Next_Formal (Formal);
13150       end loop;
13151
13152       --  If this derivation corresponds to a tagged generic actual, then
13153       --  primitive operations rename those of the actual. Otherwise the
13154       --  primitive operations rename those of the parent type, If the parent
13155       --  renames an intrinsic operator, so does the new subprogram. We except
13156       --  concatenation, which is always properly typed, and does not get
13157       --  expanded as other intrinsic operations.
13158
13159       if No (Actual_Subp) then
13160          if Is_Intrinsic_Subprogram (Parent_Subp) then
13161             Set_Is_Intrinsic_Subprogram (New_Subp);
13162
13163             if Present (Alias (Parent_Subp))
13164               and then Chars (Parent_Subp) /= Name_Op_Concat
13165             then
13166                Set_Alias (New_Subp, Alias (Parent_Subp));
13167             else
13168                Set_Alias (New_Subp, Parent_Subp);
13169             end if;
13170
13171          else
13172             Set_Alias (New_Subp, Parent_Subp);
13173          end if;
13174
13175       else
13176          Set_Alias (New_Subp, Actual_Subp);
13177       end if;
13178
13179       --  Derived subprograms of a tagged type must inherit the convention
13180       --  of the parent subprogram (a requirement of AI-117). Derived
13181       --  subprograms of untagged types simply get convention Ada by default.
13182
13183       if Is_Tagged_Type (Derived_Type) then
13184          Set_Convention (New_Subp, Convention (Parent_Subp));
13185       end if;
13186
13187       --  Predefined controlled operations retain their name even if the parent
13188       --  is hidden (see above), but they are not primitive operations if the
13189       --  ancestor is not visible, for example if the parent is a private
13190       --  extension completed with a controlled extension. Note that a full
13191       --  type that is controlled can break privacy: the flag Is_Controlled is
13192       --  set on both views of the type.
13193
13194       if Is_Controlled (Parent_Type)
13195         and then
13196           (Chars (Parent_Subp) = Name_Initialize
13197             or else Chars (Parent_Subp) = Name_Adjust
13198             or else Chars (Parent_Subp) = Name_Finalize)
13199         and then Is_Hidden (Parent_Subp)
13200         and then not Is_Visibly_Controlled (Parent_Type)
13201       then
13202          Set_Is_Hidden (New_Subp);
13203       end if;
13204
13205       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
13206       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
13207
13208       if Ekind (Parent_Subp) = E_Procedure then
13209          Set_Is_Valued_Procedure
13210            (New_Subp, Is_Valued_Procedure (Parent_Subp));
13211       else
13212          Set_Has_Controlling_Result
13213            (New_Subp, Has_Controlling_Result (Parent_Subp));
13214       end if;
13215
13216       --  No_Return must be inherited properly. If this is overridden in the
13217       --  case of a dispatching operation, then a check is made in Sem_Disp
13218       --  that the overriding operation is also No_Return (no such check is
13219       --  required for the case of non-dispatching operation.
13220
13221       Set_No_Return (New_Subp, No_Return (Parent_Subp));
13222
13223       --  A derived function with a controlling result is abstract. If the
13224       --  Derived_Type is a nonabstract formal generic derived type, then
13225       --  inherited operations are not abstract: the required check is done at
13226       --  instantiation time. If the derivation is for a generic actual, the
13227       --  function is not abstract unless the actual is.
13228
13229       if Is_Generic_Type (Derived_Type)
13230         and then not Is_Abstract_Type (Derived_Type)
13231       then
13232          null;
13233
13234       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
13235       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
13236
13237       elsif Ada_Version >= Ada_2005
13238         and then (Is_Abstract_Subprogram (Alias (New_Subp))
13239                    or else (Is_Tagged_Type (Derived_Type)
13240                             and then Etype (New_Subp) = Derived_Type
13241                             and then not Is_Null_Extension (Derived_Type))
13242                    or else (Is_Tagged_Type (Derived_Type)
13243                             and then Ekind (Etype (New_Subp)) =
13244                                                        E_Anonymous_Access_Type
13245                             and then Designated_Type (Etype (New_Subp)) =
13246                                                        Derived_Type
13247                             and then not Is_Null_Extension (Derived_Type)))
13248         and then No (Actual_Subp)
13249       then
13250          if not Is_Tagged_Type (Derived_Type)
13251            or else Is_Abstract_Type (Derived_Type)
13252            or else Is_Abstract_Subprogram (Alias (New_Subp))
13253          then
13254             Set_Is_Abstract_Subprogram (New_Subp);
13255          else
13256             Set_Requires_Overriding (New_Subp);
13257          end if;
13258
13259       elsif Ada_Version < Ada_2005
13260         and then (Is_Abstract_Subprogram (Alias (New_Subp))
13261                    or else (Is_Tagged_Type (Derived_Type)
13262                              and then Etype (New_Subp) = Derived_Type
13263                              and then No (Actual_Subp)))
13264       then
13265          Set_Is_Abstract_Subprogram (New_Subp);
13266
13267       --  AI05-0097 : an inherited operation that dispatches on result is
13268       --  abstract if the derived type is abstract, even if the parent type
13269       --  is concrete and the derived type is a null extension.
13270
13271       elsif Has_Controlling_Result (Alias (New_Subp))
13272         and then Is_Abstract_Type (Etype (New_Subp))
13273       then
13274          Set_Is_Abstract_Subprogram (New_Subp);
13275
13276       --  Finally, if the parent type is abstract we must verify that all
13277       --  inherited operations are either non-abstract or overridden, or that
13278       --  the derived type itself is abstract (this check is performed at the
13279       --  end of a package declaration, in Check_Abstract_Overriding). A
13280       --  private overriding in the parent type will not be visible in the
13281       --  derivation if we are not in an inner package or in a child unit of
13282       --  the parent type, in which case the abstractness of the inherited
13283       --  operation is carried to the new subprogram.
13284
13285       elsif Is_Abstract_Type (Parent_Type)
13286         and then not In_Open_Scopes (Scope (Parent_Type))
13287         and then Is_Private_Overriding
13288         and then Is_Abstract_Subprogram (Visible_Subp)
13289       then
13290          if No (Actual_Subp) then
13291             Set_Alias (New_Subp, Visible_Subp);
13292             Set_Is_Abstract_Subprogram (New_Subp, True);
13293
13294          else
13295             --  If this is a derivation for an instance of a formal derived
13296             --  type, abstractness comes from the primitive operation of the
13297             --  actual, not from the operation inherited from the ancestor.
13298
13299             Set_Is_Abstract_Subprogram
13300               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
13301          end if;
13302       end if;
13303
13304       New_Overloaded_Entity (New_Subp, Derived_Type);
13305
13306       --  Check for case of a derived subprogram for the instantiation of a
13307       --  formal derived tagged type, if so mark the subprogram as dispatching
13308       --  and inherit the dispatching attributes of the parent subprogram. The
13309       --  derived subprogram is effectively renaming of the actual subprogram,
13310       --  so it needs to have the same attributes as the actual.
13311
13312       if Present (Actual_Subp)
13313         and then Is_Dispatching_Operation (Parent_Subp)
13314       then
13315          Set_Is_Dispatching_Operation (New_Subp);
13316
13317          if Present (DTC_Entity (Parent_Subp)) then
13318             Set_DTC_Entity (New_Subp, DTC_Entity (Parent_Subp));
13319             Set_DT_Position (New_Subp, DT_Position (Parent_Subp));
13320          end if;
13321       end if;
13322
13323       --  Indicate that a derived subprogram does not require a body and that
13324       --  it does not require processing of default expressions.
13325
13326       Set_Has_Completion (New_Subp);
13327       Set_Default_Expressions_Processed (New_Subp);
13328
13329       if Ekind (New_Subp) = E_Function then
13330          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
13331       end if;
13332    end Derive_Subprogram;
13333
13334    ------------------------
13335    -- Derive_Subprograms --
13336    ------------------------
13337
13338    procedure Derive_Subprograms
13339      (Parent_Type    : Entity_Id;
13340       Derived_Type   : Entity_Id;
13341       Generic_Actual : Entity_Id := Empty)
13342    is
13343       Op_List : constant Elist_Id :=
13344                   Collect_Primitive_Operations (Parent_Type);
13345
13346       function Check_Derived_Type return Boolean;
13347       --  Check that all the entities derived from Parent_Type are found in
13348       --  the list of primitives of Derived_Type exactly in the same order.
13349
13350       procedure Derive_Interface_Subprogram
13351         (New_Subp    : in out Entity_Id;
13352          Subp        : Entity_Id;
13353          Actual_Subp : Entity_Id);
13354       --  Derive New_Subp from the ultimate alias of the parent subprogram Subp
13355       --  (which is an interface primitive). If Generic_Actual is present then
13356       --  Actual_Subp is the actual subprogram corresponding with the generic
13357       --  subprogram Subp.
13358
13359       function Check_Derived_Type return Boolean is
13360          E        : Entity_Id;
13361          Elmt     : Elmt_Id;
13362          List     : Elist_Id;
13363          New_Subp : Entity_Id;
13364          Op_Elmt  : Elmt_Id;
13365          Subp     : Entity_Id;
13366
13367       begin
13368          --  Traverse list of entities in the current scope searching for
13369          --  an incomplete type whose full-view is derived type
13370
13371          E := First_Entity (Scope (Derived_Type));
13372          while Present (E)
13373            and then E /= Derived_Type
13374          loop
13375             if Ekind (E) = E_Incomplete_Type
13376               and then Present (Full_View (E))
13377               and then Full_View (E) = Derived_Type
13378             then
13379                --  Disable this test if Derived_Type completes an incomplete
13380                --  type because in such case more primitives can be added
13381                --  later to the list of primitives of Derived_Type by routine
13382                --  Process_Incomplete_Dependents
13383
13384                return True;
13385             end if;
13386
13387             E := Next_Entity (E);
13388          end loop;
13389
13390          List := Collect_Primitive_Operations (Derived_Type);
13391          Elmt := First_Elmt (List);
13392
13393          Op_Elmt := First_Elmt (Op_List);
13394          while Present (Op_Elmt) loop
13395             Subp     := Node (Op_Elmt);
13396             New_Subp := Node (Elmt);
13397
13398             --  At this early stage Derived_Type has no entities with attribute
13399             --  Interface_Alias. In addition, such primitives are always
13400             --  located at the end of the list of primitives of Parent_Type.
13401             --  Therefore, if found we can safely stop processing pending
13402             --  entities.
13403
13404             exit when Present (Interface_Alias (Subp));
13405
13406             --  Handle hidden entities
13407
13408             if not Is_Predefined_Dispatching_Operation (Subp)
13409               and then Is_Hidden (Subp)
13410             then
13411                if Present (New_Subp)
13412                  and then Primitive_Names_Match (Subp, New_Subp)
13413                then
13414                   Next_Elmt (Elmt);
13415                end if;
13416
13417             else
13418                if not Present (New_Subp)
13419                  or else Ekind (Subp) /= Ekind (New_Subp)
13420                  or else not Primitive_Names_Match (Subp, New_Subp)
13421                then
13422                   return False;
13423                end if;
13424
13425                Next_Elmt (Elmt);
13426             end if;
13427
13428             Next_Elmt (Op_Elmt);
13429          end loop;
13430
13431          return True;
13432       end Check_Derived_Type;
13433
13434       ---------------------------------
13435       -- Derive_Interface_Subprogram --
13436       ---------------------------------
13437
13438       procedure Derive_Interface_Subprogram
13439         (New_Subp    : in out Entity_Id;
13440          Subp        : Entity_Id;
13441          Actual_Subp : Entity_Id)
13442       is
13443          Iface_Subp : constant Entity_Id := Ultimate_Alias (Subp);
13444          Iface_Type : constant Entity_Id := Find_Dispatching_Type (Iface_Subp);
13445
13446       begin
13447          pragma Assert (Is_Interface (Iface_Type));
13448
13449          Derive_Subprogram
13450            (New_Subp     => New_Subp,
13451             Parent_Subp  => Iface_Subp,
13452             Derived_Type => Derived_Type,
13453             Parent_Type  => Iface_Type,
13454             Actual_Subp  => Actual_Subp);
13455
13456          --  Given that this new interface entity corresponds with a primitive
13457          --  of the parent that was not overridden we must leave it associated
13458          --  with its parent primitive to ensure that it will share the same
13459          --  dispatch table slot when overridden.
13460
13461          if No (Actual_Subp) then
13462             Set_Alias (New_Subp, Subp);
13463
13464          --  For instantiations this is not needed since the previous call to
13465          --  Derive_Subprogram leaves the entity well decorated.
13466
13467          else
13468             pragma Assert (Alias (New_Subp) = Actual_Subp);
13469             null;
13470          end if;
13471       end Derive_Interface_Subprogram;
13472
13473       --  Local variables
13474
13475       Alias_Subp   : Entity_Id;
13476       Act_List     : Elist_Id;
13477       Act_Elmt     : Elmt_Id   := No_Elmt;
13478       Act_Subp     : Entity_Id := Empty;
13479       Elmt         : Elmt_Id;
13480       Need_Search  : Boolean   := False;
13481       New_Subp     : Entity_Id := Empty;
13482       Parent_Base  : Entity_Id;
13483       Subp         : Entity_Id;
13484
13485    --  Start of processing for Derive_Subprograms
13486
13487    begin
13488       if Ekind (Parent_Type) = E_Record_Type_With_Private
13489         and then Has_Discriminants (Parent_Type)
13490         and then Present (Full_View (Parent_Type))
13491       then
13492          Parent_Base := Full_View (Parent_Type);
13493       else
13494          Parent_Base := Parent_Type;
13495       end if;
13496
13497       if Present (Generic_Actual) then
13498          Act_List := Collect_Primitive_Operations (Generic_Actual);
13499          Act_Elmt := First_Elmt (Act_List);
13500       end if;
13501
13502       --  Derive primitives inherited from the parent. Note that if the generic
13503       --  actual is present, this is not really a type derivation, it is a
13504       --  completion within an instance.
13505
13506       --  Case 1: Derived_Type does not implement interfaces
13507
13508       if not Is_Tagged_Type (Derived_Type)
13509         or else (not Has_Interfaces (Derived_Type)
13510                   and then not (Present (Generic_Actual)
13511                                   and then
13512                                 Has_Interfaces (Generic_Actual)))
13513       then
13514          Elmt := First_Elmt (Op_List);
13515          while Present (Elmt) loop
13516             Subp := Node (Elmt);
13517
13518             --  Literals are derived earlier in the process of building the
13519             --  derived type, and are skipped here.
13520
13521             if Ekind (Subp) = E_Enumeration_Literal then
13522                null;
13523
13524             --  The actual is a direct descendant and the common primitive
13525             --  operations appear in the same order.
13526
13527             --  If the generic parent type is present, the derived type is an
13528             --  instance of a formal derived type, and within the instance its
13529             --  operations are those of the actual. We derive from the formal
13530             --  type but make the inherited operations aliases of the
13531             --  corresponding operations of the actual.
13532
13533             else
13534                pragma Assert (No (Node (Act_Elmt))
13535                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
13536                             and then
13537                           Type_Conformant (Subp, Node (Act_Elmt),
13538                                            Skip_Controlling_Formals => True)));
13539
13540                Derive_Subprogram
13541                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
13542
13543                if Present (Act_Elmt) then
13544                   Next_Elmt (Act_Elmt);
13545                end if;
13546             end if;
13547
13548             Next_Elmt (Elmt);
13549          end loop;
13550
13551       --  Case 2: Derived_Type implements interfaces
13552
13553       else
13554          --  If the parent type has no predefined primitives we remove
13555          --  predefined primitives from the list of primitives of generic
13556          --  actual to simplify the complexity of this algorithm.
13557
13558          if Present (Generic_Actual) then
13559             declare
13560                Has_Predefined_Primitives : Boolean := False;
13561
13562             begin
13563                --  Check if the parent type has predefined primitives
13564
13565                Elmt := First_Elmt (Op_List);
13566                while Present (Elmt) loop
13567                   Subp := Node (Elmt);
13568
13569                   if Is_Predefined_Dispatching_Operation (Subp)
13570                     and then not Comes_From_Source (Ultimate_Alias (Subp))
13571                   then
13572                      Has_Predefined_Primitives := True;
13573                      exit;
13574                   end if;
13575
13576                   Next_Elmt (Elmt);
13577                end loop;
13578
13579                --  Remove predefined primitives of Generic_Actual. We must use
13580                --  an auxiliary list because in case of tagged types the value
13581                --  returned by Collect_Primitive_Operations is the value stored
13582                --  in its Primitive_Operations attribute (and we don't want to
13583                --  modify its current contents).
13584
13585                if not Has_Predefined_Primitives then
13586                   declare
13587                      Aux_List : constant Elist_Id := New_Elmt_List;
13588
13589                   begin
13590                      Elmt := First_Elmt (Act_List);
13591                      while Present (Elmt) loop
13592                         Subp := Node (Elmt);
13593
13594                         if not Is_Predefined_Dispatching_Operation (Subp)
13595                           or else Comes_From_Source (Subp)
13596                         then
13597                            Append_Elmt (Subp, Aux_List);
13598                         end if;
13599
13600                         Next_Elmt (Elmt);
13601                      end loop;
13602
13603                      Act_List := Aux_List;
13604                   end;
13605                end if;
13606
13607                Act_Elmt := First_Elmt (Act_List);
13608                Act_Subp := Node (Act_Elmt);
13609             end;
13610          end if;
13611
13612          --  Stage 1: If the generic actual is not present we derive the
13613          --  primitives inherited from the parent type. If the generic parent
13614          --  type is present, the derived type is an instance of a formal
13615          --  derived type, and within the instance its operations are those of
13616          --  the actual. We derive from the formal type but make the inherited
13617          --  operations aliases of the corresponding operations of the actual.
13618
13619          Elmt := First_Elmt (Op_List);
13620          while Present (Elmt) loop
13621             Subp       := Node (Elmt);
13622             Alias_Subp := Ultimate_Alias (Subp);
13623
13624             --  Do not derive internal entities of the parent that link
13625             --  interface primitives with their covering primitive. These
13626             --  entities will be added to this type when frozen.
13627
13628             if Present (Interface_Alias (Subp)) then
13629                goto Continue;
13630             end if;
13631
13632             --  If the generic actual is present find the corresponding
13633             --  operation in the generic actual. If the parent type is a
13634             --  direct ancestor of the derived type then, even if it is an
13635             --  interface, the operations are inherited from the primary
13636             --  dispatch table and are in the proper order. If we detect here
13637             --  that primitives are not in the same order we traverse the list
13638             --  of primitive operations of the actual to find the one that
13639             --  implements the interface primitive.
13640
13641             if Need_Search
13642               or else
13643                 (Present (Generic_Actual)
13644                   and then Present (Act_Subp)
13645                   and then not
13646                     (Primitive_Names_Match (Subp, Act_Subp)
13647                        and then
13648                      Type_Conformant (Subp, Act_Subp,
13649                                       Skip_Controlling_Formals => True)))
13650             then
13651                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual,
13652                                                Use_Full_View => True));
13653
13654                --  Remember that we need searching for all pending primitives
13655
13656                Need_Search := True;
13657
13658                --  Handle entities associated with interface primitives
13659
13660                if Present (Alias_Subp)
13661                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13662                  and then not Is_Predefined_Dispatching_Operation (Subp)
13663                then
13664                   --  Search for the primitive in the homonym chain
13665
13666                   Act_Subp :=
13667                     Find_Primitive_Covering_Interface
13668                       (Tagged_Type => Generic_Actual,
13669                        Iface_Prim  => Alias_Subp);
13670
13671                   --  Previous search may not locate primitives covering
13672                   --  interfaces defined in generics units or instantiations.
13673                   --  (it fails if the covering primitive has formals whose
13674                   --  type is also defined in generics or instantiations).
13675                   --  In such case we search in the list of primitives of the
13676                   --  generic actual for the internal entity that links the
13677                   --  interface primitive and the covering primitive.
13678
13679                   if No (Act_Subp)
13680                     and then Is_Generic_Type (Parent_Type)
13681                   then
13682                      --  This code has been designed to handle only generic
13683                      --  formals that implement interfaces that are defined
13684                      --  in a generic unit or instantiation. If this code is
13685                      --  needed for other cases we must review it because
13686                      --  (given that it relies on Original_Location to locate
13687                      --  the primitive of Generic_Actual that covers the
13688                      --  interface) it could leave linked through attribute
13689                      --  Alias entities of unrelated instantiations).
13690
13691                      pragma Assert
13692                        (Is_Generic_Unit
13693                           (Scope (Find_Dispatching_Type (Alias_Subp)))
13694                        or else
13695                         Instantiation_Depth
13696                           (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
13697
13698                      declare
13699                         Iface_Prim_Loc : constant Source_Ptr :=
13700                                          Original_Location (Sloc (Alias_Subp));
13701                         Elmt      : Elmt_Id;
13702                         Prim      : Entity_Id;
13703                      begin
13704                         Elmt :=
13705                           First_Elmt (Primitive_Operations (Generic_Actual));
13706
13707                         Search : while Present (Elmt) loop
13708                            Prim := Node (Elmt);
13709
13710                            if Present (Interface_Alias (Prim))
13711                              and then Original_Location
13712                                         (Sloc (Interface_Alias (Prim)))
13713                                        = Iface_Prim_Loc
13714                            then
13715                               Act_Subp := Alias (Prim);
13716                               exit Search;
13717                            end if;
13718
13719                            Next_Elmt (Elmt);
13720                         end loop Search;
13721                      end;
13722                   end if;
13723
13724                   pragma Assert (Present (Act_Subp)
13725                     or else Is_Abstract_Type (Generic_Actual)
13726                     or else Serious_Errors_Detected > 0);
13727
13728                --  Handle predefined primitives plus the rest of user-defined
13729                --  primitives
13730
13731                else
13732                   Act_Elmt := First_Elmt (Act_List);
13733                   while Present (Act_Elmt) loop
13734                      Act_Subp := Node (Act_Elmt);
13735
13736                      exit when Primitive_Names_Match (Subp, Act_Subp)
13737                        and then Type_Conformant
13738                                   (Subp, Act_Subp,
13739                                    Skip_Controlling_Formals => True)
13740                        and then No (Interface_Alias (Act_Subp));
13741
13742                      Next_Elmt (Act_Elmt);
13743                   end loop;
13744
13745                   if No (Act_Elmt) then
13746                      Act_Subp := Empty;
13747                   end if;
13748                end if;
13749             end if;
13750
13751             --   Case 1: If the parent is a limited interface then it has the
13752             --   predefined primitives of synchronized interfaces. However, the
13753             --   actual type may be a non-limited type and hence it does not
13754             --   have such primitives.
13755
13756             if Present (Generic_Actual)
13757               and then not Present (Act_Subp)
13758               and then Is_Limited_Interface (Parent_Base)
13759               and then Is_Predefined_Interface_Primitive (Subp)
13760             then
13761                null;
13762
13763             --  Case 2: Inherit entities associated with interfaces that were
13764             --  not covered by the parent type. We exclude here null interface
13765             --  primitives because they do not need special management.
13766
13767             --  We also exclude interface operations that are renamings. If the
13768             --  subprogram is an explicit renaming of an interface primitive,
13769             --  it is a regular primitive operation, and the presence of its
13770             --  alias is not relevant: it has to be derived like any other
13771             --  primitive.
13772
13773             elsif Present (Alias (Subp))
13774               and then Nkind (Unit_Declaration_Node (Subp)) /=
13775                                             N_Subprogram_Renaming_Declaration
13776               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13777               and then not
13778                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
13779                   and then Null_Present (Parent (Alias_Subp)))
13780             then
13781                --  If this is an abstract private type then we transfer the
13782                --  derivation of the interface primitive from the partial view
13783                --  to the full view. This is safe because all the interfaces
13784                --  must be visible in the partial view. Done to avoid adding
13785                --  a new interface derivation to the private part of the
13786                --  enclosing package; otherwise this new derivation would be
13787                --  decorated as hidden when the analysis of the enclosing
13788                --  package completes.
13789
13790                if Is_Abstract_Type (Derived_Type)
13791                  and then In_Private_Part (Current_Scope)
13792                  and then Has_Private_Declaration (Derived_Type)
13793                then
13794                   declare
13795                      Partial_View : Entity_Id;
13796                      Elmt         : Elmt_Id;
13797                      Ent          : Entity_Id;
13798
13799                   begin
13800                      Partial_View := First_Entity (Current_Scope);
13801                      loop
13802                         exit when No (Partial_View)
13803                           or else (Has_Private_Declaration (Partial_View)
13804                                      and then
13805                                    Full_View (Partial_View) = Derived_Type);
13806
13807                         Next_Entity (Partial_View);
13808                      end loop;
13809
13810                      --  If the partial view was not found then the source code
13811                      --  has errors and the derivation is not needed.
13812
13813                      if Present (Partial_View) then
13814                         Elmt :=
13815                           First_Elmt (Primitive_Operations (Partial_View));
13816                         while Present (Elmt) loop
13817                            Ent := Node (Elmt);
13818
13819                            if Present (Alias (Ent))
13820                              and then Ultimate_Alias (Ent) = Alias (Subp)
13821                            then
13822                               Append_Elmt
13823                                 (Ent, Primitive_Operations (Derived_Type));
13824                               exit;
13825                            end if;
13826
13827                            Next_Elmt (Elmt);
13828                         end loop;
13829
13830                         --  If the interface primitive was not found in the
13831                         --  partial view then this interface primitive was
13832                         --  overridden. We add a derivation to activate in
13833                         --  Derive_Progenitor_Subprograms the machinery to
13834                         --  search for it.
13835
13836                         if No (Elmt) then
13837                            Derive_Interface_Subprogram
13838                              (New_Subp    => New_Subp,
13839                               Subp        => Subp,
13840                               Actual_Subp => Act_Subp);
13841                         end if;
13842                      end if;
13843                   end;
13844                else
13845                   Derive_Interface_Subprogram
13846                     (New_Subp     => New_Subp,
13847                      Subp         => Subp,
13848                      Actual_Subp  => Act_Subp);
13849                end if;
13850
13851             --  Case 3: Common derivation
13852
13853             else
13854                Derive_Subprogram
13855                  (New_Subp     => New_Subp,
13856                   Parent_Subp  => Subp,
13857                   Derived_Type => Derived_Type,
13858                   Parent_Type  => Parent_Base,
13859                   Actual_Subp  => Act_Subp);
13860             end if;
13861
13862             --  No need to update Act_Elm if we must search for the
13863             --  corresponding operation in the generic actual
13864
13865             if not Need_Search
13866               and then Present (Act_Elmt)
13867             then
13868                Next_Elmt (Act_Elmt);
13869                Act_Subp := Node (Act_Elmt);
13870             end if;
13871
13872             <<Continue>>
13873             Next_Elmt (Elmt);
13874          end loop;
13875
13876          --  Inherit additional operations from progenitors. If the derived
13877          --  type is a generic actual, there are not new primitive operations
13878          --  for the type because it has those of the actual, and therefore
13879          --  nothing needs to be done. The renamings generated above are not
13880          --  primitive operations, and their purpose is simply to make the
13881          --  proper operations visible within an instantiation.
13882
13883          if No (Generic_Actual) then
13884             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
13885          end if;
13886       end if;
13887
13888       --  Final check: Direct descendants must have their primitives in the
13889       --  same order. We exclude from this test untagged types and instances
13890       --  of formal derived types. We skip this test if we have already
13891       --  reported serious errors in the sources.
13892
13893       pragma Assert (not Is_Tagged_Type (Derived_Type)
13894         or else Present (Generic_Actual)
13895         or else Serious_Errors_Detected > 0
13896         or else Check_Derived_Type);
13897    end Derive_Subprograms;
13898
13899    --------------------------------
13900    -- Derived_Standard_Character --
13901    --------------------------------
13902
13903    procedure Derived_Standard_Character
13904      (N            : Node_Id;
13905       Parent_Type  : Entity_Id;
13906       Derived_Type : Entity_Id)
13907    is
13908       Loc           : constant Source_Ptr := Sloc (N);
13909       Def           : constant Node_Id    := Type_Definition (N);
13910       Indic         : constant Node_Id    := Subtype_Indication (Def);
13911       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
13912       Implicit_Base : constant Entity_Id  :=
13913                         Create_Itype
13914                           (E_Enumeration_Type, N, Derived_Type, 'B');
13915
13916       Lo : Node_Id;
13917       Hi : Node_Id;
13918
13919    begin
13920       Discard_Node (Process_Subtype (Indic, N));
13921
13922       Set_Etype     (Implicit_Base, Parent_Base);
13923       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
13924       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
13925
13926       Set_Is_Character_Type  (Implicit_Base, True);
13927       Set_Has_Delayed_Freeze (Implicit_Base);
13928
13929       --  The bounds of the implicit base are the bounds of the parent base.
13930       --  Note that their type is the parent base.
13931
13932       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
13933       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
13934
13935       Set_Scalar_Range (Implicit_Base,
13936         Make_Range (Loc,
13937           Low_Bound  => Lo,
13938           High_Bound => Hi));
13939
13940       Conditional_Delay (Derived_Type, Parent_Type);
13941
13942       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
13943       Set_Etype (Derived_Type, Implicit_Base);
13944       Set_Size_Info         (Derived_Type, Parent_Type);
13945
13946       if Unknown_RM_Size (Derived_Type) then
13947          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
13948       end if;
13949
13950       Set_Is_Character_Type (Derived_Type, True);
13951
13952       if Nkind (Indic) /= N_Subtype_Indication then
13953
13954          --  If no explicit constraint, the bounds are those
13955          --  of the parent type.
13956
13957          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
13958          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
13959          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
13960       end if;
13961
13962       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
13963
13964       --  Because the implicit base is used in the conversion of the bounds, we
13965       --  have to freeze it now. This is similar to what is done for numeric
13966       --  types, and it equally suspicious, but otherwise a non-static bound
13967       --  will have a reference to an unfrozen type, which is rejected by Gigi
13968       --  (???). This requires specific care for definition of stream
13969       --  attributes. For details, see comments at the end of
13970       --  Build_Derived_Numeric_Type.
13971
13972       Freeze_Before (N, Implicit_Base);
13973    end Derived_Standard_Character;
13974
13975    ------------------------------
13976    -- Derived_Type_Declaration --
13977    ------------------------------
13978
13979    procedure Derived_Type_Declaration
13980      (T             : Entity_Id;
13981       N             : Node_Id;
13982       Is_Completion : Boolean)
13983    is
13984       Parent_Type  : Entity_Id;
13985
13986       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
13987       --  Check whether the parent type is a generic formal, or derives
13988       --  directly or indirectly from one.
13989
13990       ------------------------
13991       -- Comes_From_Generic --
13992       ------------------------
13993
13994       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
13995       begin
13996          if Is_Generic_Type (Typ) then
13997             return True;
13998
13999          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
14000             return True;
14001
14002          elsif Is_Private_Type (Typ)
14003            and then Present (Full_View (Typ))
14004            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
14005          then
14006             return True;
14007
14008          elsif Is_Generic_Actual_Type (Typ) then
14009             return True;
14010
14011          else
14012             return False;
14013          end if;
14014       end Comes_From_Generic;
14015
14016       --  Local variables
14017
14018       Def          : constant Node_Id := Type_Definition (N);
14019       Iface_Def    : Node_Id;
14020       Indic        : constant Node_Id := Subtype_Indication (Def);
14021       Extension    : constant Node_Id := Record_Extension_Part (Def);
14022       Parent_Node  : Node_Id;
14023       Taggd        : Boolean;
14024
14025    --  Start of processing for Derived_Type_Declaration
14026
14027    begin
14028       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
14029
14030       --  Ada 2005 (AI-251): In case of interface derivation check that the
14031       --  parent is also an interface.
14032
14033       if Interface_Present (Def) then
14034          Check_SPARK_Restriction ("interface is not allowed", Def);
14035
14036          if not Is_Interface (Parent_Type) then
14037             Diagnose_Interface (Indic, Parent_Type);
14038
14039          else
14040             Parent_Node := Parent (Base_Type (Parent_Type));
14041             Iface_Def   := Type_Definition (Parent_Node);
14042
14043             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
14044             --  other limited interfaces.
14045
14046             if Limited_Present (Def) then
14047                if Limited_Present (Iface_Def) then
14048                   null;
14049
14050                elsif Protected_Present (Iface_Def) then
14051                   Error_Msg_NE
14052                     ("descendant of& must be declared"
14053                        & " as a protected interface",
14054                          N, Parent_Type);
14055
14056                elsif Synchronized_Present (Iface_Def) then
14057                   Error_Msg_NE
14058                     ("descendant of& must be declared"
14059                        & " as a synchronized interface",
14060                          N, Parent_Type);
14061
14062                elsif Task_Present (Iface_Def) then
14063                   Error_Msg_NE
14064                     ("descendant of& must be declared as a task interface",
14065                        N, Parent_Type);
14066
14067                else
14068                   Error_Msg_N
14069                     ("(Ada 2005) limited interface cannot "
14070                      & "inherit from non-limited interface", Indic);
14071                end if;
14072
14073             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
14074             --  from non-limited or limited interfaces.
14075
14076             elsif not Protected_Present (Def)
14077               and then not Synchronized_Present (Def)
14078               and then not Task_Present (Def)
14079             then
14080                if Limited_Present (Iface_Def) then
14081                   null;
14082
14083                elsif Protected_Present (Iface_Def) then
14084                   Error_Msg_NE
14085                     ("descendant of& must be declared"
14086                        & " as a protected interface",
14087                          N, Parent_Type);
14088
14089                elsif Synchronized_Present (Iface_Def) then
14090                   Error_Msg_NE
14091                     ("descendant of& must be declared"
14092                        & " as a synchronized interface",
14093                          N, Parent_Type);
14094
14095                elsif Task_Present (Iface_Def) then
14096                   Error_Msg_NE
14097                     ("descendant of& must be declared as a task interface",
14098                        N, Parent_Type);
14099                else
14100                   null;
14101                end if;
14102             end if;
14103          end if;
14104       end if;
14105
14106       if Is_Tagged_Type (Parent_Type)
14107         and then Is_Concurrent_Type (Parent_Type)
14108         and then not Is_Interface (Parent_Type)
14109       then
14110          Error_Msg_N
14111            ("parent type of a record extension cannot be "
14112             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
14113          Set_Etype (T, Any_Type);
14114          return;
14115       end if;
14116
14117       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
14118       --  interfaces
14119
14120       if Is_Tagged_Type (Parent_Type)
14121         and then Is_Non_Empty_List (Interface_List (Def))
14122       then
14123          declare
14124             Intf : Node_Id;
14125             T    : Entity_Id;
14126
14127          begin
14128             Intf := First (Interface_List (Def));
14129             while Present (Intf) loop
14130                T := Find_Type_Of_Subtype_Indic (Intf);
14131
14132                if not Is_Interface (T) then
14133                   Diagnose_Interface (Intf, T);
14134
14135                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
14136                --  a limited type from having a nonlimited progenitor.
14137
14138                elsif (Limited_Present (Def)
14139                        or else (not Is_Interface (Parent_Type)
14140                                  and then Is_Limited_Type (Parent_Type)))
14141                  and then not Is_Limited_Interface (T)
14142                then
14143                   Error_Msg_NE
14144                    ("progenitor interface& of limited type must be limited",
14145                      N, T);
14146                end if;
14147
14148                Next (Intf);
14149             end loop;
14150          end;
14151       end if;
14152
14153       if Parent_Type = Any_Type
14154         or else Etype (Parent_Type) = Any_Type
14155         or else (Is_Class_Wide_Type (Parent_Type)
14156                    and then Etype (Parent_Type) = T)
14157       then
14158          --  If Parent_Type is undefined or illegal, make new type into a
14159          --  subtype of Any_Type, and set a few attributes to prevent cascaded
14160          --  errors. If this is a self-definition, emit error now.
14161
14162          if T = Parent_Type
14163            or else T = Etype (Parent_Type)
14164          then
14165             Error_Msg_N ("type cannot be used in its own definition", Indic);
14166          end if;
14167
14168          Set_Ekind        (T, Ekind (Parent_Type));
14169          Set_Etype        (T, Any_Type);
14170          Set_Scalar_Range (T, Scalar_Range (Any_Type));
14171
14172          if Is_Tagged_Type (T)
14173            and then Is_Record_Type (T)
14174          then
14175             Set_Direct_Primitive_Operations (T, New_Elmt_List);
14176          end if;
14177
14178          return;
14179       end if;
14180
14181       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
14182       --  an interface is special because the list of interfaces in the full
14183       --  view can be given in any order. For example:
14184
14185       --     type A is interface;
14186       --     type B is interface and A;
14187       --     type D is new B with private;
14188       --   private
14189       --     type D is new A and B with null record; -- 1 --
14190
14191       --  In this case we perform the following transformation of -1-:
14192
14193       --     type D is new B and A with null record;
14194
14195       --  If the parent of the full-view covers the parent of the partial-view
14196       --  we have two possible cases:
14197
14198       --     1) They have the same parent
14199       --     2) The parent of the full-view implements some further interfaces
14200
14201       --  In both cases we do not need to perform the transformation. In the
14202       --  first case the source program is correct and the transformation is
14203       --  not needed; in the second case the source program does not fulfill
14204       --  the no-hidden interfaces rule (AI-396) and the error will be reported
14205       --  later.
14206
14207       --  This transformation not only simplifies the rest of the analysis of
14208       --  this type declaration but also simplifies the correct generation of
14209       --  the object layout to the expander.
14210
14211       if In_Private_Part (Current_Scope)
14212         and then Is_Interface (Parent_Type)
14213       then
14214          declare
14215             Iface               : Node_Id;
14216             Partial_View        : Entity_Id;
14217             Partial_View_Parent : Entity_Id;
14218             New_Iface           : Node_Id;
14219
14220          begin
14221             --  Look for the associated private type declaration
14222
14223             Partial_View := First_Entity (Current_Scope);
14224             loop
14225                exit when No (Partial_View)
14226                  or else (Has_Private_Declaration (Partial_View)
14227                            and then Full_View (Partial_View) = T);
14228
14229                Next_Entity (Partial_View);
14230             end loop;
14231
14232             --  If the partial view was not found then the source code has
14233             --  errors and the transformation is not needed.
14234
14235             if Present (Partial_View) then
14236                Partial_View_Parent := Etype (Partial_View);
14237
14238                --  If the parent of the full-view covers the parent of the
14239                --  partial-view we have nothing else to do.
14240
14241                if Interface_Present_In_Ancestor
14242                     (Parent_Type, Partial_View_Parent)
14243                then
14244                   null;
14245
14246                --  Traverse the list of interfaces of the full-view to look
14247                --  for the parent of the partial-view and perform the tree
14248                --  transformation.
14249
14250                else
14251                   Iface := First (Interface_List (Def));
14252                   while Present (Iface) loop
14253                      if Etype (Iface) = Etype (Partial_View) then
14254                         Rewrite (Subtype_Indication (Def),
14255                           New_Copy (Subtype_Indication
14256                                      (Parent (Partial_View))));
14257
14258                         New_Iface :=
14259                           Make_Identifier (Sloc (N), Chars (Parent_Type));
14260                         Append (New_Iface, Interface_List (Def));
14261
14262                         --  Analyze the transformed code
14263
14264                         Derived_Type_Declaration (T, N, Is_Completion);
14265                         return;
14266                      end if;
14267
14268                      Next (Iface);
14269                   end loop;
14270                end if;
14271             end if;
14272          end;
14273       end if;
14274
14275       --  Only composite types other than array types are allowed to have
14276       --  discriminants. In SPARK, no types are allowed to have discriminants.
14277
14278       if Present (Discriminant_Specifications (N)) then
14279          if (Is_Elementary_Type (Parent_Type)
14280               or else Is_Array_Type (Parent_Type))
14281            and then not Error_Posted (N)
14282          then
14283             Error_Msg_N
14284               ("elementary or array type cannot have discriminants",
14285                Defining_Identifier (First (Discriminant_Specifications (N))));
14286             Set_Has_Discriminants (T, False);
14287          else
14288             Check_SPARK_Restriction ("discriminant type is not allowed", N);
14289          end if;
14290       end if;
14291
14292       --  In Ada 83, a derived type defined in a package specification cannot
14293       --  be used for further derivation until the end of its visible part.
14294       --  Note that derivation in the private part of the package is allowed.
14295
14296       if Ada_Version = Ada_83
14297         and then Is_Derived_Type (Parent_Type)
14298         and then In_Visible_Part (Scope (Parent_Type))
14299       then
14300          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
14301             Error_Msg_N
14302               ("(Ada 83): premature use of type for derivation", Indic);
14303          end if;
14304       end if;
14305
14306       --  Check for early use of incomplete or private type
14307
14308       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
14309          Error_Msg_N ("premature derivation of incomplete type", Indic);
14310          return;
14311
14312       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
14313               and then not Comes_From_Generic (Parent_Type))
14314         or else Has_Private_Component (Parent_Type)
14315       then
14316          --  The ancestor type of a formal type can be incomplete, in which
14317          --  case only the operations of the partial view are available in the
14318          --  generic. Subsequent checks may be required when the full view is
14319          --  analyzed to verify that a derivation from a tagged type has an
14320          --  extension.
14321
14322          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
14323             null;
14324
14325          elsif No (Underlying_Type (Parent_Type))
14326            or else Has_Private_Component (Parent_Type)
14327          then
14328             Error_Msg_N
14329               ("premature derivation of derived or private type", Indic);
14330
14331             --  Flag the type itself as being in error, this prevents some
14332             --  nasty problems with subsequent uses of the malformed type.
14333
14334             Set_Error_Posted (T);
14335
14336          --  Check that within the immediate scope of an untagged partial
14337          --  view it's illegal to derive from the partial view if the
14338          --  full view is tagged. (7.3(7))
14339
14340          --  We verify that the Parent_Type is a partial view by checking
14341          --  that it is not a Full_Type_Declaration (i.e. a private type or
14342          --  private extension declaration), to distinguish a partial view
14343          --  from  a derivation from a private type which also appears as
14344          --  E_Private_Type. If the parent base type is not declared in an
14345          --  enclosing scope there is no need to check.
14346
14347          elsif Present (Full_View (Parent_Type))
14348            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
14349            and then not Is_Tagged_Type (Parent_Type)
14350            and then Is_Tagged_Type (Full_View (Parent_Type))
14351            and then In_Open_Scopes (Scope (Base_Type (Parent_Type)))
14352          then
14353             Error_Msg_N
14354               ("premature derivation from type with tagged full view",
14355                 Indic);
14356          end if;
14357       end if;
14358
14359       --  Check that form of derivation is appropriate
14360
14361       Taggd := Is_Tagged_Type (Parent_Type);
14362
14363       --  Perhaps the parent type should be changed to the class-wide type's
14364       --  specific type in this case to prevent cascading errors ???
14365
14366       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
14367          Error_Msg_N ("parent type must not be a class-wide type", Indic);
14368          return;
14369       end if;
14370
14371       if Present (Extension) and then not Taggd then
14372          Error_Msg_N
14373            ("type derived from untagged type cannot have extension", Indic);
14374
14375       elsif No (Extension) and then Taggd then
14376
14377          --  If this declaration is within a private part (or body) of a
14378          --  generic instantiation then the derivation is allowed (the parent
14379          --  type can only appear tagged in this case if it's a generic actual
14380          --  type, since it would otherwise have been rejected in the analysis
14381          --  of the generic template).
14382
14383          if not Is_Generic_Actual_Type (Parent_Type)
14384            or else In_Visible_Part (Scope (Parent_Type))
14385          then
14386             if Is_Class_Wide_Type (Parent_Type) then
14387                Error_Msg_N
14388                  ("parent type must not be a class-wide type", Indic);
14389
14390                --  Use specific type to prevent cascaded errors.
14391
14392                Parent_Type := Etype (Parent_Type);
14393
14394             else
14395                Error_Msg_N
14396                  ("type derived from tagged type must have extension", Indic);
14397             end if;
14398          end if;
14399       end if;
14400
14401       --  AI-443: Synchronized formal derived types require a private
14402       --  extension. There is no point in checking the ancestor type or
14403       --  the progenitors since the construct is wrong to begin with.
14404
14405       if Ada_Version >= Ada_2005
14406         and then Is_Generic_Type (T)
14407         and then Present (Original_Node (N))
14408       then
14409          declare
14410             Decl : constant Node_Id := Original_Node (N);
14411
14412          begin
14413             if Nkind (Decl) = N_Formal_Type_Declaration
14414               and then Nkind (Formal_Type_Definition (Decl)) =
14415                          N_Formal_Derived_Type_Definition
14416               and then Synchronized_Present (Formal_Type_Definition (Decl))
14417               and then No (Extension)
14418
14419                --  Avoid emitting a duplicate error message
14420
14421               and then not Error_Posted (Indic)
14422             then
14423                Error_Msg_N
14424                  ("synchronized derived type must have extension", N);
14425             end if;
14426          end;
14427       end if;
14428
14429       if Null_Exclusion_Present (Def)
14430         and then not Is_Access_Type (Parent_Type)
14431       then
14432          Error_Msg_N ("null exclusion can only apply to an access type", N);
14433       end if;
14434
14435       --  Avoid deriving parent primitives of underlying record views
14436
14437       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
14438         Derive_Subps => not Is_Underlying_Record_View (T));
14439
14440       --  AI-419: The parent type of an explicitly limited derived type must
14441       --  be a limited type or a limited interface.
14442
14443       if Limited_Present (Def) then
14444          Set_Is_Limited_Record (T);
14445
14446          if Is_Interface (T) then
14447             Set_Is_Limited_Interface (T);
14448          end if;
14449
14450          if not Is_Limited_Type (Parent_Type)
14451            and then
14452              (not Is_Interface (Parent_Type)
14453                or else not Is_Limited_Interface (Parent_Type))
14454          then
14455             --  AI05-0096: a derivation in the private part of an instance is
14456             --  legal if the generic formal is untagged limited, and the actual
14457             --  is non-limited.
14458
14459             if Is_Generic_Actual_Type (Parent_Type)
14460               and then In_Private_Part (Current_Scope)
14461               and then
14462                 not Is_Tagged_Type
14463                       (Generic_Parent_Type (Parent (Parent_Type)))
14464             then
14465                null;
14466
14467             else
14468                Error_Msg_NE
14469                  ("parent type& of limited type must be limited",
14470                   N, Parent_Type);
14471             end if;
14472          end if;
14473       end if;
14474
14475       --  In SPARK, there are no derived type definitions other than type
14476       --  extensions of tagged record types.
14477
14478       if No (Extension) then
14479          Check_SPARK_Restriction ("derived type is not allowed", N);
14480       end if;
14481    end Derived_Type_Declaration;
14482
14483    ------------------------
14484    -- Diagnose_Interface --
14485    ------------------------
14486
14487    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
14488    begin
14489       if not Is_Interface (E)
14490         and then  E /= Any_Type
14491       then
14492          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
14493       end if;
14494    end Diagnose_Interface;
14495
14496    ----------------------------------
14497    -- Enumeration_Type_Declaration --
14498    ----------------------------------
14499
14500    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14501       Ev     : Uint;
14502       L      : Node_Id;
14503       R_Node : Node_Id;
14504       B_Node : Node_Id;
14505
14506    begin
14507       --  Create identifier node representing lower bound
14508
14509       B_Node := New_Node (N_Identifier, Sloc (Def));
14510       L := First (Literals (Def));
14511       Set_Chars (B_Node, Chars (L));
14512       Set_Entity (B_Node,  L);
14513       Set_Etype (B_Node, T);
14514       Set_Is_Static_Expression (B_Node, True);
14515
14516       R_Node := New_Node (N_Range, Sloc (Def));
14517       Set_Low_Bound  (R_Node, B_Node);
14518
14519       Set_Ekind (T, E_Enumeration_Type);
14520       Set_First_Literal (T, L);
14521       Set_Etype (T, T);
14522       Set_Is_Constrained (T);
14523
14524       Ev := Uint_0;
14525
14526       --  Loop through literals of enumeration type setting pos and rep values
14527       --  except that if the Ekind is already set, then it means the literal
14528       --  was already constructed (case of a derived type declaration and we
14529       --  should not disturb the Pos and Rep values.
14530
14531       while Present (L) loop
14532          if Ekind (L) /= E_Enumeration_Literal then
14533             Set_Ekind (L, E_Enumeration_Literal);
14534             Set_Enumeration_Pos (L, Ev);
14535             Set_Enumeration_Rep (L, Ev);
14536             Set_Is_Known_Valid  (L, True);
14537          end if;
14538
14539          Set_Etype (L, T);
14540          New_Overloaded_Entity (L);
14541          Generate_Definition (L);
14542          Set_Convention (L, Convention_Intrinsic);
14543
14544          --  Case of character literal
14545
14546          if Nkind (L) = N_Defining_Character_Literal then
14547             Set_Is_Character_Type (T, True);
14548
14549             --  Check violation of No_Wide_Characters
14550
14551             if Restriction_Check_Required (No_Wide_Characters) then
14552                Get_Name_String (Chars (L));
14553
14554                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
14555                   Check_Restriction (No_Wide_Characters, L);
14556                end if;
14557             end if;
14558          end if;
14559
14560          Ev := Ev + 1;
14561          Next (L);
14562       end loop;
14563
14564       --  Now create a node representing upper bound
14565
14566       B_Node := New_Node (N_Identifier, Sloc (Def));
14567       Set_Chars (B_Node, Chars (Last (Literals (Def))));
14568       Set_Entity (B_Node,  Last (Literals (Def)));
14569       Set_Etype (B_Node, T);
14570       Set_Is_Static_Expression (B_Node, True);
14571
14572       Set_High_Bound (R_Node, B_Node);
14573
14574       --  Initialize various fields of the type. Some of this information
14575       --  may be overwritten later through rep.clauses.
14576
14577       Set_Scalar_Range    (T, R_Node);
14578       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
14579       Set_Enum_Esize      (T);
14580       Set_Enum_Pos_To_Rep (T, Empty);
14581
14582       --  Set Discard_Names if configuration pragma set, or if there is
14583       --  a parameterless pragma in the current declarative region
14584
14585       if Global_Discard_Names
14586         or else Discard_Names (Scope (T))
14587       then
14588          Set_Discard_Names (T);
14589       end if;
14590
14591       --  Process end label if there is one
14592
14593       if Present (Def) then
14594          Process_End_Label (Def, 'e', T);
14595       end if;
14596    end Enumeration_Type_Declaration;
14597
14598    ---------------------------------
14599    -- Expand_To_Stored_Constraint --
14600    ---------------------------------
14601
14602    function Expand_To_Stored_Constraint
14603      (Typ        : Entity_Id;
14604       Constraint : Elist_Id) return Elist_Id
14605    is
14606       Explicitly_Discriminated_Type : Entity_Id;
14607       Expansion    : Elist_Id;
14608       Discriminant : Entity_Id;
14609
14610       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
14611       --  Find the nearest type that actually specifies discriminants
14612
14613       ---------------------------------
14614       -- Type_With_Explicit_Discrims --
14615       ---------------------------------
14616
14617       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
14618          Typ : constant E := Base_Type (Id);
14619
14620       begin
14621          if Ekind (Typ) in Incomplete_Or_Private_Kind then
14622             if Present (Full_View (Typ)) then
14623                return Type_With_Explicit_Discrims (Full_View (Typ));
14624             end if;
14625
14626          else
14627             if Has_Discriminants (Typ) then
14628                return Typ;
14629             end if;
14630          end if;
14631
14632          if Etype (Typ) = Typ then
14633             return Empty;
14634          elsif Has_Discriminants (Typ) then
14635             return Typ;
14636          else
14637             return Type_With_Explicit_Discrims (Etype (Typ));
14638          end if;
14639
14640       end Type_With_Explicit_Discrims;
14641
14642    --  Start of processing for Expand_To_Stored_Constraint
14643
14644    begin
14645       if No (Constraint)
14646         or else Is_Empty_Elmt_List (Constraint)
14647       then
14648          return No_Elist;
14649       end if;
14650
14651       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
14652
14653       if No (Explicitly_Discriminated_Type) then
14654          return No_Elist;
14655       end if;
14656
14657       Expansion := New_Elmt_List;
14658
14659       Discriminant :=
14660          First_Stored_Discriminant (Explicitly_Discriminated_Type);
14661       while Present (Discriminant) loop
14662          Append_Elmt (
14663            Get_Discriminant_Value (
14664              Discriminant, Explicitly_Discriminated_Type, Constraint),
14665            Expansion);
14666          Next_Stored_Discriminant (Discriminant);
14667       end loop;
14668
14669       return Expansion;
14670    end Expand_To_Stored_Constraint;
14671
14672    ---------------------------
14673    -- Find_Hidden_Interface --
14674    ---------------------------
14675
14676    function Find_Hidden_Interface
14677      (Src  : Elist_Id;
14678       Dest : Elist_Id) return Entity_Id
14679    is
14680       Iface      : Entity_Id;
14681       Iface_Elmt : Elmt_Id;
14682
14683    begin
14684       if Present (Src) and then Present (Dest) then
14685          Iface_Elmt := First_Elmt (Src);
14686          while Present (Iface_Elmt) loop
14687             Iface := Node (Iface_Elmt);
14688
14689             if Is_Interface (Iface)
14690               and then not Contain_Interface (Iface, Dest)
14691             then
14692                return Iface;
14693             end if;
14694
14695             Next_Elmt (Iface_Elmt);
14696          end loop;
14697       end if;
14698
14699       return Empty;
14700    end Find_Hidden_Interface;
14701
14702    --------------------
14703    -- Find_Type_Name --
14704    --------------------
14705
14706    function Find_Type_Name (N : Node_Id) return Entity_Id is
14707       Id       : constant Entity_Id := Defining_Identifier (N);
14708       Prev     : Entity_Id;
14709       New_Id   : Entity_Id;
14710       Prev_Par : Node_Id;
14711
14712       procedure Tag_Mismatch;
14713       --  Diagnose a tagged partial view whose full view is untagged.
14714       --  We post the message on the full view, with a reference to
14715       --  the previous partial view. The partial view can be private
14716       --  or incomplete, and these are handled in a different manner,
14717       --  so we determine the position of the error message from the
14718       --  respective slocs of both.
14719
14720       ------------------
14721       -- Tag_Mismatch --
14722       ------------------
14723
14724       procedure Tag_Mismatch is
14725       begin
14726          if Sloc (Prev) < Sloc (Id) then
14727             if Ada_Version >= Ada_2012
14728               and then Nkind (N) = N_Private_Type_Declaration
14729             then
14730                Error_Msg_NE
14731                  ("declaration of private } must be a tagged type ", Id, Prev);
14732             else
14733                Error_Msg_NE
14734                  ("full declaration of } must be a tagged type ", Id, Prev);
14735             end if;
14736          else
14737             if Ada_Version >= Ada_2012
14738               and then Nkind (N) = N_Private_Type_Declaration
14739             then
14740                Error_Msg_NE
14741                  ("declaration of private } must be a tagged type ", Prev, Id);
14742             else
14743                Error_Msg_NE
14744                  ("full declaration of } must be a tagged type ", Prev, Id);
14745             end if;
14746          end if;
14747       end Tag_Mismatch;
14748
14749    --  Start of processing for Find_Type_Name
14750
14751    begin
14752       --  Find incomplete declaration, if one was given
14753
14754       Prev := Current_Entity_In_Scope (Id);
14755
14756       --  New type declaration
14757
14758       if No (Prev) then
14759          Enter_Name (Id);
14760          return Id;
14761
14762       --  Previous declaration exists
14763
14764       else
14765          Prev_Par := Parent (Prev);
14766
14767          --  Error if not incomplete/private case except if previous
14768          --  declaration is implicit, etc. Enter_Name will emit error if
14769          --  appropriate.
14770
14771          if not Is_Incomplete_Or_Private_Type (Prev) then
14772             Enter_Name (Id);
14773             New_Id := Id;
14774
14775          --  Check invalid completion of private or incomplete type
14776
14777          elsif not Nkind_In (N, N_Full_Type_Declaration,
14778                                 N_Task_Type_Declaration,
14779                                 N_Protected_Type_Declaration)
14780            and then
14781              (Ada_Version < Ada_2012
14782                 or else not Is_Incomplete_Type (Prev)
14783                 or else not Nkind_In (N, N_Private_Type_Declaration,
14784                                          N_Private_Extension_Declaration))
14785          then
14786             --  Completion must be a full type declarations (RM 7.3(4))
14787
14788             Error_Msg_Sloc := Sloc (Prev);
14789             Error_Msg_NE ("invalid completion of }", Id, Prev);
14790
14791             --  Set scope of Id to avoid cascaded errors. Entity is never
14792             --  examined again, except when saving globals in generics.
14793
14794             Set_Scope (Id, Current_Scope);
14795             New_Id := Id;
14796
14797             --  If this is a repeated incomplete declaration, no further
14798             --  checks are possible.
14799
14800             if Nkind (N) = N_Incomplete_Type_Declaration then
14801                return Prev;
14802             end if;
14803
14804          --  Case of full declaration of incomplete type
14805
14806          elsif Ekind (Prev) = E_Incomplete_Type
14807            and then (Ada_Version < Ada_2012
14808                       or else No (Full_View (Prev))
14809                       or else not Is_Private_Type (Full_View (Prev)))
14810          then
14811
14812             --  Indicate that the incomplete declaration has a matching full
14813             --  declaration. The defining occurrence of the incomplete
14814             --  declaration remains the visible one, and the procedure
14815             --  Get_Full_View dereferences it whenever the type is used.
14816
14817             if Present (Full_View (Prev)) then
14818                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14819             end if;
14820
14821             Set_Full_View (Prev, Id);
14822             Append_Entity (Id, Current_Scope);
14823             Set_Is_Public (Id, Is_Public (Prev));
14824             Set_Is_Internal (Id);
14825             New_Id := Prev;
14826
14827             --  If the incomplete view is tagged, a class_wide type has been
14828             --  created already. Use it for the private type as well, in order
14829             --  to prevent multiple incompatible class-wide types that may be
14830             --  created for self-referential anonymous access components.
14831
14832             if Is_Tagged_Type (Prev)
14833               and then Present (Class_Wide_Type (Prev))
14834             then
14835                Set_Ekind (Id, Ekind (Prev));         --  will be reset later
14836                Set_Class_Wide_Type (Id, Class_Wide_Type (Prev));
14837                Set_Etype (Class_Wide_Type (Id), Id);
14838             end if;
14839
14840          --  Case of full declaration of private type
14841
14842          else
14843             --  If the private type was a completion of an incomplete type then
14844             --  update Prev to reference the private type
14845
14846             if Ada_Version >= Ada_2012
14847               and then Ekind (Prev) = E_Incomplete_Type
14848               and then Present (Full_View (Prev))
14849               and then Is_Private_Type (Full_View (Prev))
14850             then
14851                Prev := Full_View (Prev);
14852                Prev_Par := Parent (Prev);
14853             end if;
14854
14855             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
14856                if Etype (Prev) /= Prev then
14857
14858                   --  Prev is a private subtype or a derived type, and needs
14859                   --  no completion.
14860
14861                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14862                   New_Id := Id;
14863
14864                elsif Ekind (Prev) = E_Private_Type
14865                  and then Nkind_In (N, N_Task_Type_Declaration,
14866                                        N_Protected_Type_Declaration)
14867                then
14868                   Error_Msg_N
14869                    ("completion of nonlimited type cannot be limited", N);
14870
14871                elsif Ekind (Prev) = E_Record_Type_With_Private
14872                  and then Nkind_In (N, N_Task_Type_Declaration,
14873                                        N_Protected_Type_Declaration)
14874                then
14875                   if not Is_Limited_Record (Prev) then
14876                      Error_Msg_N
14877                         ("completion of nonlimited type cannot be limited", N);
14878
14879                   elsif No (Interface_List (N)) then
14880                      Error_Msg_N
14881                         ("completion of tagged private type must be tagged",
14882                          N);
14883                   end if;
14884
14885                elsif Nkind (N) = N_Full_Type_Declaration
14886                  and then
14887                    Nkind (Type_Definition (N)) = N_Record_Definition
14888                  and then Interface_Present (Type_Definition (N))
14889                then
14890                   Error_Msg_N
14891                     ("completion of private type cannot be an interface", N);
14892                end if;
14893
14894             --  Ada 2005 (AI-251): Private extension declaration of a task
14895             --  type or a protected type. This case arises when covering
14896             --  interface types.
14897
14898             elsif Nkind_In (N, N_Task_Type_Declaration,
14899                                N_Protected_Type_Declaration)
14900             then
14901                null;
14902
14903             elsif Nkind (N) /= N_Full_Type_Declaration
14904               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
14905             then
14906                Error_Msg_N
14907                  ("full view of private extension must be an extension", N);
14908
14909             elsif not (Abstract_Present (Parent (Prev)))
14910               and then Abstract_Present (Type_Definition (N))
14911             then
14912                Error_Msg_N
14913                  ("full view of non-abstract extension cannot be abstract", N);
14914             end if;
14915
14916             if not In_Private_Part (Current_Scope) then
14917                Error_Msg_N
14918                  ("declaration of full view must appear in private part", N);
14919             end if;
14920
14921             Copy_And_Swap (Prev, Id);
14922             Set_Has_Private_Declaration (Prev);
14923             Set_Has_Private_Declaration (Id);
14924
14925             --  If no error, propagate freeze_node from private to full view.
14926             --  It may have been generated for an early operational item.
14927
14928             if Present (Freeze_Node (Id))
14929               and then Serious_Errors_Detected = 0
14930               and then No (Full_View (Id))
14931             then
14932                Set_Freeze_Node (Prev, Freeze_Node (Id));
14933                Set_Freeze_Node (Id, Empty);
14934                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
14935             end if;
14936
14937             Set_Full_View (Id, Prev);
14938             New_Id := Prev;
14939          end if;
14940
14941          --  Verify that full declaration conforms to partial one
14942
14943          if Is_Incomplete_Or_Private_Type (Prev)
14944            and then Present (Discriminant_Specifications (Prev_Par))
14945          then
14946             if Present (Discriminant_Specifications (N)) then
14947                if Ekind (Prev) = E_Incomplete_Type then
14948                   Check_Discriminant_Conformance (N, Prev, Prev);
14949                else
14950                   Check_Discriminant_Conformance (N, Prev, Id);
14951                end if;
14952
14953             else
14954                Error_Msg_N
14955                  ("missing discriminants in full type declaration", N);
14956
14957                --  To avoid cascaded errors on subsequent use, share the
14958                --  discriminants of the partial view.
14959
14960                Set_Discriminant_Specifications (N,
14961                  Discriminant_Specifications (Prev_Par));
14962             end if;
14963          end if;
14964
14965          --  A prior untagged partial view can have an associated class-wide
14966          --  type due to use of the class attribute, and in this case the full
14967          --  type must also be tagged. This Ada 95 usage is deprecated in favor
14968          --  of incomplete tagged declarations, but we check for it.
14969
14970          if Is_Type (Prev)
14971            and then (Is_Tagged_Type (Prev)
14972                        or else Present (Class_Wide_Type (Prev)))
14973          then
14974             --  Ada 2012 (AI05-0162): A private type may be the completion of
14975             --  an incomplete type
14976
14977             if Ada_Version >= Ada_2012
14978               and then Is_Incomplete_Type (Prev)
14979               and then Nkind_In (N, N_Private_Type_Declaration,
14980                                     N_Private_Extension_Declaration)
14981             then
14982                --  No need to check private extensions since they are tagged
14983
14984                if Nkind (N) = N_Private_Type_Declaration
14985                  and then not Tagged_Present (N)
14986                then
14987                   Tag_Mismatch;
14988                end if;
14989
14990             --  The full declaration is either a tagged type (including
14991             --  a synchronized type that implements interfaces) or a
14992             --  type extension, otherwise this is an error.
14993
14994             elsif Nkind_In (N, N_Task_Type_Declaration,
14995                                N_Protected_Type_Declaration)
14996             then
14997                if No (Interface_List (N))
14998                  and then not Error_Posted (N)
14999                then
15000                   Tag_Mismatch;
15001                end if;
15002
15003             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
15004
15005                --  Indicate that the previous declaration (tagged incomplete
15006                --  or private declaration) requires the same on the full one.
15007
15008                if not Tagged_Present (Type_Definition (N)) then
15009                   Tag_Mismatch;
15010                   Set_Is_Tagged_Type (Id);
15011                end if;
15012
15013             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
15014                if No (Record_Extension_Part (Type_Definition (N))) then
15015                   Error_Msg_NE
15016                     ("full declaration of } must be a record extension",
15017                      Prev, Id);
15018
15019                   --  Set some attributes to produce a usable full view
15020
15021                   Set_Is_Tagged_Type (Id);
15022                end if;
15023
15024             else
15025                Tag_Mismatch;
15026             end if;
15027          end if;
15028
15029          return New_Id;
15030       end if;
15031    end Find_Type_Name;
15032
15033    -------------------------
15034    -- Find_Type_Of_Object --
15035    -------------------------
15036
15037    function Find_Type_Of_Object
15038      (Obj_Def     : Node_Id;
15039       Related_Nod : Node_Id) return Entity_Id
15040    is
15041       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
15042       P        : Node_Id := Parent (Obj_Def);
15043       T        : Entity_Id;
15044       Nam      : Name_Id;
15045
15046    begin
15047       --  If the parent is a component_definition node we climb to the
15048       --  component_declaration node
15049
15050       if Nkind (P) = N_Component_Definition then
15051          P := Parent (P);
15052       end if;
15053
15054       --  Case of an anonymous array subtype
15055
15056       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
15057                              N_Unconstrained_Array_Definition)
15058       then
15059          T := Empty;
15060          Array_Type_Declaration (T, Obj_Def);
15061
15062       --  Create an explicit subtype whenever possible
15063
15064       elsif Nkind (P) /= N_Component_Declaration
15065         and then Def_Kind = N_Subtype_Indication
15066       then
15067          --  Base name of subtype on object name, which will be unique in
15068          --  the current scope.
15069
15070          --  If this is a duplicate declaration, return base type, to avoid
15071          --  generating duplicate anonymous types.
15072
15073          if Error_Posted (P) then
15074             Analyze (Subtype_Mark (Obj_Def));
15075             return Entity (Subtype_Mark (Obj_Def));
15076          end if;
15077
15078          Nam :=
15079             New_External_Name
15080              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
15081
15082          T := Make_Defining_Identifier (Sloc (P), Nam);
15083
15084          Insert_Action (Obj_Def,
15085            Make_Subtype_Declaration (Sloc (P),
15086              Defining_Identifier => T,
15087              Subtype_Indication  => Relocate_Node (Obj_Def)));
15088
15089          --  This subtype may need freezing, and this will not be done
15090          --  automatically if the object declaration is not in declarative
15091          --  part. Since this is an object declaration, the type cannot always
15092          --  be frozen here. Deferred constants do not freeze their type
15093          --  (which often enough will be private).
15094
15095          if Nkind (P) = N_Object_Declaration
15096            and then Constant_Present (P)
15097            and then No (Expression (P))
15098          then
15099             null;
15100          else
15101             Insert_Actions (Obj_Def, Freeze_Entity (T, P));
15102          end if;
15103
15104       --  Ada 2005 AI-406: the object definition in an object declaration
15105       --  can be an access definition.
15106
15107       elsif Def_Kind = N_Access_Definition then
15108          T := Access_Definition (Related_Nod, Obj_Def);
15109          Set_Is_Local_Anonymous_Access (T);
15110
15111       --  Otherwise, the object definition is just a subtype_mark
15112
15113       else
15114          T := Process_Subtype (Obj_Def, Related_Nod);
15115
15116          --  If expansion is disabled an object definition that is an aggregate
15117          --  will not get expanded and may lead to scoping problems in the back
15118          --  end, if the object is referenced in an inner scope. In that case
15119          --  create an itype reference for the object definition now. This
15120          --  may be redundant in some cases, but harmless.
15121
15122          if Is_Itype (T)
15123            and then Nkind (Related_Nod) = N_Object_Declaration
15124            and then ASIS_Mode
15125          then
15126             Build_Itype_Reference (T, Related_Nod);
15127          end if;
15128       end if;
15129
15130       return T;
15131    end Find_Type_Of_Object;
15132
15133    --------------------------------
15134    -- Find_Type_Of_Subtype_Indic --
15135    --------------------------------
15136
15137    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
15138       Typ : Entity_Id;
15139
15140    begin
15141       --  Case of subtype mark with a constraint
15142
15143       if Nkind (S) = N_Subtype_Indication then
15144          Find_Type (Subtype_Mark (S));
15145          Typ := Entity (Subtype_Mark (S));
15146
15147          if not
15148            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
15149          then
15150             Error_Msg_N
15151               ("incorrect constraint for this kind of type", Constraint (S));
15152             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
15153          end if;
15154
15155       --  Otherwise we have a subtype mark without a constraint
15156
15157       elsif Error_Posted (S) then
15158          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
15159          return Any_Type;
15160
15161       else
15162          Find_Type (S);
15163          Typ := Entity (S);
15164       end if;
15165
15166       --  Check No_Wide_Characters restriction
15167
15168       Check_Wide_Character_Restriction (Typ, S);
15169
15170       return Typ;
15171    end Find_Type_Of_Subtype_Indic;
15172
15173    -------------------------------------
15174    -- Floating_Point_Type_Declaration --
15175    -------------------------------------
15176
15177    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
15178       Digs          : constant Node_Id := Digits_Expression (Def);
15179       Max_Digs_Val  : constant Uint := Digits_Value (Standard_Long_Long_Float);
15180       Digs_Val      : Uint;
15181       Base_Typ      : Entity_Id;
15182       Implicit_Base : Entity_Id;
15183       Bound         : Node_Id;
15184
15185       function Can_Derive_From (E : Entity_Id) return Boolean;
15186       --  Find if given digits value, and possibly a specified range, allows
15187       --  derivation from specified type
15188
15189       function Find_Base_Type return Entity_Id;
15190       --  Find a predefined base type that Def can derive from, or generate
15191       --  an error and substitute Long_Long_Float if none exists.
15192
15193       ---------------------
15194       -- Can_Derive_From --
15195       ---------------------
15196
15197       function Can_Derive_From (E : Entity_Id) return Boolean is
15198          Spec : constant Entity_Id := Real_Range_Specification (Def);
15199
15200       begin
15201          if Digs_Val > Digits_Value (E) then
15202             return False;
15203          end if;
15204
15205          if Present (Spec) then
15206             if Expr_Value_R (Type_Low_Bound (E)) >
15207                Expr_Value_R (Low_Bound (Spec))
15208             then
15209                return False;
15210             end if;
15211
15212             if Expr_Value_R (Type_High_Bound (E)) <
15213                Expr_Value_R (High_Bound (Spec))
15214             then
15215                return False;
15216             end if;
15217          end if;
15218
15219          return True;
15220       end Can_Derive_From;
15221
15222       --------------------
15223       -- Find_Base_Type --
15224       --------------------
15225
15226       function Find_Base_Type return Entity_Id is
15227          Choice : Elmt_Id := First_Elmt (Predefined_Float_Types);
15228
15229       begin
15230          --  Iterate over the predefined types in order, returning the first
15231          --  one that Def can derive from.
15232
15233          while Present (Choice) loop
15234             if Can_Derive_From (Node (Choice)) then
15235                return Node (Choice);
15236             end if;
15237
15238             Next_Elmt (Choice);
15239          end loop;
15240
15241          --  If we can't derive from any existing type, use Long_Long_Float
15242          --  and give appropriate message explaining the problem.
15243
15244          if Digs_Val > Max_Digs_Val then
15245             --  It might be the case that there is a type with the requested
15246             --  range, just not the combination of digits and range.
15247
15248             Error_Msg_N
15249               ("no predefined type has requested range and precision",
15250                Real_Range_Specification (Def));
15251
15252          else
15253             Error_Msg_N
15254               ("range too large for any predefined type",
15255                Real_Range_Specification (Def));
15256          end if;
15257
15258          return Standard_Long_Long_Float;
15259       end Find_Base_Type;
15260
15261    --  Start of processing for Floating_Point_Type_Declaration
15262
15263    begin
15264       Check_Restriction (No_Floating_Point, Def);
15265
15266       --  Create an implicit base type
15267
15268       Implicit_Base :=
15269         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
15270
15271       --  Analyze and verify digits value
15272
15273       Analyze_And_Resolve (Digs, Any_Integer);
15274       Check_Digits_Expression (Digs);
15275       Digs_Val := Expr_Value (Digs);
15276
15277       --  Process possible range spec and find correct type to derive from
15278
15279       Process_Real_Range_Specification (Def);
15280
15281       --  Check that requested number of digits is not too high.
15282
15283       if Digs_Val > Max_Digs_Val then
15284          --  The check for Max_Base_Digits may be somewhat expensive, as it
15285          --  requires reading System, so only do it when necessary.
15286
15287          declare
15288             Max_Base_Digits : constant Uint :=
15289                                 Expr_Value
15290                                   (Expression
15291                                      (Parent (RTE (RE_Max_Base_Digits))));
15292
15293          begin
15294             if Digs_Val > Max_Base_Digits then
15295                Error_Msg_Uint_1 := Max_Base_Digits;
15296                Error_Msg_N ("digits value out of range, maximum is ^", Digs);
15297
15298             elsif No (Real_Range_Specification (Def)) then
15299                Error_Msg_Uint_1 := Max_Digs_Val;
15300                Error_Msg_N ("types with more than ^ digits need range spec "
15301                  & "(RM 3.5.7(6))", Digs);
15302             end if;
15303          end;
15304       end if;
15305
15306       --  Find a suitable type to derive from or complain and use a substitute
15307
15308       Base_Typ := Find_Base_Type;
15309
15310       --  If there are bounds given in the declaration use them as the bounds
15311       --  of the type, otherwise use the bounds of the predefined base type
15312       --  that was chosen based on the Digits value.
15313
15314       if Present (Real_Range_Specification (Def)) then
15315          Set_Scalar_Range (T, Real_Range_Specification (Def));
15316          Set_Is_Constrained (T);
15317
15318          --  The bounds of this range must be converted to machine numbers
15319          --  in accordance with RM 4.9(38).
15320
15321          Bound := Type_Low_Bound (T);
15322
15323          if Nkind (Bound) = N_Real_Literal then
15324             Set_Realval
15325               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
15326             Set_Is_Machine_Number (Bound);
15327          end if;
15328
15329          Bound := Type_High_Bound (T);
15330
15331          if Nkind (Bound) = N_Real_Literal then
15332             Set_Realval
15333               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
15334             Set_Is_Machine_Number (Bound);
15335          end if;
15336
15337       else
15338          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
15339       end if;
15340
15341       --  Complete definition of implicit base and declared first subtype
15342
15343       Set_Etype          (Implicit_Base, Base_Typ);
15344
15345       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
15346       Set_Size_Info      (Implicit_Base,                (Base_Typ));
15347       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
15348       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
15349       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
15350       Set_Float_Rep      (Implicit_Base, Float_Rep      (Base_Typ));
15351
15352       Set_Ekind          (T, E_Floating_Point_Subtype);
15353       Set_Etype          (T, Implicit_Base);
15354
15355       Set_Size_Info      (T,                (Implicit_Base));
15356       Set_RM_Size        (T, RM_Size        (Implicit_Base));
15357       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
15358       Set_Digits_Value   (T, Digs_Val);
15359    end Floating_Point_Type_Declaration;
15360
15361    ----------------------------
15362    -- Get_Discriminant_Value --
15363    ----------------------------
15364
15365    --  This is the situation:
15366
15367    --  There is a non-derived type
15368
15369    --       type T0 (Dx, Dy, Dz...)
15370
15371    --  There are zero or more levels of derivation, with each derivation
15372    --  either purely inheriting the discriminants, or defining its own.
15373
15374    --       type Ti      is new Ti-1
15375    --  or
15376    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
15377    --  or
15378    --       subtype Ti is ...
15379
15380    --  The subtype issue is avoided by the use of Original_Record_Component,
15381    --  and the fact that derived subtypes also derive the constraints.
15382
15383    --  This chain leads back from
15384
15385    --       Typ_For_Constraint
15386
15387    --  Typ_For_Constraint has discriminants, and the value for each
15388    --  discriminant is given by its corresponding Elmt of Constraints.
15389
15390    --  Discriminant is some discriminant in this hierarchy
15391
15392    --  We need to return its value
15393
15394    --  We do this by recursively searching each level, and looking for
15395    --  Discriminant. Once we get to the bottom, we start backing up
15396    --  returning the value for it which may in turn be a discriminant
15397    --  further up, so on the backup we continue the substitution.
15398
15399    function Get_Discriminant_Value
15400      (Discriminant       : Entity_Id;
15401       Typ_For_Constraint : Entity_Id;
15402       Constraint         : Elist_Id) return Node_Id
15403    is
15404       function Search_Derivation_Levels
15405         (Ti                    : Entity_Id;
15406          Discrim_Values        : Elist_Id;
15407          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
15408       --  This is the routine that performs the recursive search of levels
15409       --  as described above.
15410
15411       ------------------------------
15412       -- Search_Derivation_Levels --
15413       ------------------------------
15414
15415       function Search_Derivation_Levels
15416         (Ti                    : Entity_Id;
15417          Discrim_Values        : Elist_Id;
15418          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
15419       is
15420          Assoc          : Elmt_Id;
15421          Disc           : Entity_Id;
15422          Result         : Node_Or_Entity_Id;
15423          Result_Entity  : Node_Id;
15424
15425       begin
15426          --  If inappropriate type, return Error, this happens only in
15427          --  cascaded error situations, and we want to avoid a blow up.
15428
15429          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
15430             return Error;
15431          end if;
15432
15433          --  Look deeper if possible. Use Stored_Constraints only for
15434          --  untagged types. For tagged types use the given constraint.
15435          --  This asymmetry needs explanation???
15436
15437          if not Stored_Discrim_Values
15438            and then Present (Stored_Constraint (Ti))
15439            and then not Is_Tagged_Type (Ti)
15440          then
15441             Result :=
15442               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
15443          else
15444             declare
15445                Td : constant Entity_Id := Etype (Ti);
15446
15447             begin
15448                if Td = Ti then
15449                   Result := Discriminant;
15450
15451                else
15452                   if Present (Stored_Constraint (Ti)) then
15453                      Result :=
15454                         Search_Derivation_Levels
15455                           (Td, Stored_Constraint (Ti), True);
15456                   else
15457                      Result :=
15458                         Search_Derivation_Levels
15459                           (Td, Discrim_Values, Stored_Discrim_Values);
15460                   end if;
15461                end if;
15462             end;
15463          end if;
15464
15465          --  Extra underlying places to search, if not found above. For
15466          --  concurrent types, the relevant discriminant appears in the
15467          --  corresponding record. For a type derived from a private type
15468          --  without discriminant, the full view inherits the discriminants
15469          --  of the full view of the parent.
15470
15471          if Result = Discriminant then
15472             if Is_Concurrent_Type (Ti)
15473               and then Present (Corresponding_Record_Type (Ti))
15474             then
15475                Result :=
15476                  Search_Derivation_Levels (
15477                    Corresponding_Record_Type (Ti),
15478                    Discrim_Values,
15479                    Stored_Discrim_Values);
15480
15481             elsif Is_Private_Type (Ti)
15482               and then not Has_Discriminants (Ti)
15483               and then Present (Full_View (Ti))
15484               and then Etype (Full_View (Ti)) /= Ti
15485             then
15486                Result :=
15487                  Search_Derivation_Levels (
15488                    Full_View (Ti),
15489                    Discrim_Values,
15490                    Stored_Discrim_Values);
15491             end if;
15492          end if;
15493
15494          --  If Result is not a (reference to a) discriminant, return it,
15495          --  otherwise set Result_Entity to the discriminant.
15496
15497          if Nkind (Result) = N_Defining_Identifier then
15498             pragma Assert (Result = Discriminant);
15499             Result_Entity := Result;
15500
15501          else
15502             if not Denotes_Discriminant (Result) then
15503                return Result;
15504             end if;
15505
15506             Result_Entity := Entity (Result);
15507          end if;
15508
15509          --  See if this level of derivation actually has discriminants
15510          --  because tagged derivations can add them, hence the lower
15511          --  levels need not have any.
15512
15513          if not Has_Discriminants (Ti) then
15514             return Result;
15515          end if;
15516
15517          --  Scan Ti's discriminants for Result_Entity,
15518          --  and return its corresponding value, if any.
15519
15520          Result_Entity := Original_Record_Component (Result_Entity);
15521
15522          Assoc := First_Elmt (Discrim_Values);
15523
15524          if Stored_Discrim_Values then
15525             Disc := First_Stored_Discriminant (Ti);
15526          else
15527             Disc := First_Discriminant (Ti);
15528          end if;
15529
15530          while Present (Disc) loop
15531             pragma Assert (Present (Assoc));
15532
15533             if Original_Record_Component (Disc) = Result_Entity then
15534                return Node (Assoc);
15535             end if;
15536
15537             Next_Elmt (Assoc);
15538
15539             if Stored_Discrim_Values then
15540                Next_Stored_Discriminant (Disc);
15541             else
15542                Next_Discriminant (Disc);
15543             end if;
15544          end loop;
15545
15546          --  Could not find it
15547          --
15548          return Result;
15549       end Search_Derivation_Levels;
15550
15551       --  Local Variables
15552
15553       Result : Node_Or_Entity_Id;
15554
15555    --  Start of processing for Get_Discriminant_Value
15556
15557    begin
15558       --  ??? This routine is a gigantic mess and will be deleted. For the
15559       --  time being just test for the trivial case before calling recurse.
15560
15561       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
15562          declare
15563             D : Entity_Id;
15564             E : Elmt_Id;
15565
15566          begin
15567             D := First_Discriminant (Typ_For_Constraint);
15568             E := First_Elmt (Constraint);
15569             while Present (D) loop
15570                if Chars (D) = Chars (Discriminant) then
15571                   return Node (E);
15572                end if;
15573
15574                Next_Discriminant (D);
15575                Next_Elmt (E);
15576             end loop;
15577          end;
15578       end if;
15579
15580       Result := Search_Derivation_Levels
15581         (Typ_For_Constraint, Constraint, False);
15582
15583       --  ??? hack to disappear when this routine is gone
15584
15585       if  Nkind (Result) = N_Defining_Identifier then
15586          declare
15587             D : Entity_Id;
15588             E : Elmt_Id;
15589
15590          begin
15591             D := First_Discriminant (Typ_For_Constraint);
15592             E := First_Elmt (Constraint);
15593             while Present (D) loop
15594                if Corresponding_Discriminant (D) = Discriminant then
15595                   return Node (E);
15596                end if;
15597
15598                Next_Discriminant (D);
15599                Next_Elmt (E);
15600             end loop;
15601          end;
15602       end if;
15603
15604       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
15605       return Result;
15606    end Get_Discriminant_Value;
15607
15608    --------------------------
15609    -- Has_Range_Constraint --
15610    --------------------------
15611
15612    function Has_Range_Constraint (N : Node_Id) return Boolean is
15613       C : constant Node_Id := Constraint (N);
15614
15615    begin
15616       if Nkind (C) = N_Range_Constraint then
15617          return True;
15618
15619       elsif Nkind (C) = N_Digits_Constraint then
15620          return
15621             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
15622               or else
15623             Present (Range_Constraint (C));
15624
15625       elsif Nkind (C) = N_Delta_Constraint then
15626          return Present (Range_Constraint (C));
15627
15628       else
15629          return False;
15630       end if;
15631    end Has_Range_Constraint;
15632
15633    ------------------------
15634    -- Inherit_Components --
15635    ------------------------
15636
15637    function Inherit_Components
15638      (N             : Node_Id;
15639       Parent_Base   : Entity_Id;
15640       Derived_Base  : Entity_Id;
15641       Is_Tagged     : Boolean;
15642       Inherit_Discr : Boolean;
15643       Discs         : Elist_Id) return Elist_Id
15644    is
15645       Assoc_List : constant Elist_Id := New_Elmt_List;
15646
15647       procedure Inherit_Component
15648         (Old_C          : Entity_Id;
15649          Plain_Discrim  : Boolean := False;
15650          Stored_Discrim : Boolean := False);
15651       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
15652       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
15653       --  True, Old_C is a stored discriminant. If they are both false then
15654       --  Old_C is a regular component.
15655
15656       -----------------------
15657       -- Inherit_Component --
15658       -----------------------
15659
15660       procedure Inherit_Component
15661         (Old_C          : Entity_Id;
15662          Plain_Discrim  : Boolean := False;
15663          Stored_Discrim : Boolean := False)
15664       is
15665          New_C : constant Entity_Id := New_Copy (Old_C);
15666
15667          Discrim      : Entity_Id;
15668          Corr_Discrim : Entity_Id;
15669
15670       begin
15671          pragma Assert (not Is_Tagged or else not Stored_Discrim);
15672
15673          Set_Parent (New_C, Parent (Old_C));
15674
15675          --  Regular discriminants and components must be inserted in the scope
15676          --  of the Derived_Base. Do it here.
15677
15678          if not Stored_Discrim then
15679             Enter_Name (New_C);
15680          end if;
15681
15682          --  For tagged types the Original_Record_Component must point to
15683          --  whatever this field was pointing to in the parent type. This has
15684          --  already been achieved by the call to New_Copy above.
15685
15686          if not Is_Tagged then
15687             Set_Original_Record_Component (New_C, New_C);
15688          end if;
15689
15690          --  If we have inherited a component then see if its Etype contains
15691          --  references to Parent_Base discriminants. In this case, replace
15692          --  these references with the constraints given in Discs. We do not
15693          --  do this for the partial view of private types because this is
15694          --  not needed (only the components of the full view will be used
15695          --  for code generation) and cause problem. We also avoid this
15696          --  transformation in some error situations.
15697
15698          if Ekind (New_C) = E_Component then
15699             if (Is_Private_Type (Derived_Base)
15700                  and then not Is_Generic_Type (Derived_Base))
15701               or else (Is_Empty_Elmt_List (Discs)
15702                         and then  not Expander_Active)
15703             then
15704                Set_Etype (New_C, Etype (Old_C));
15705
15706             else
15707                --  The current component introduces a circularity of the
15708                --  following kind:
15709
15710                --     limited with Pack_2;
15711                --     package Pack_1 is
15712                --        type T_1 is tagged record
15713                --           Comp : access Pack_2.T_2;
15714                --           ...
15715                --        end record;
15716                --     end Pack_1;
15717
15718                --     with Pack_1;
15719                --     package Pack_2 is
15720                --        type T_2 is new Pack_1.T_1 with ...;
15721                --     end Pack_2;
15722
15723                Set_Etype
15724                  (New_C,
15725                   Constrain_Component_Type
15726                   (Old_C, Derived_Base, N, Parent_Base, Discs));
15727             end if;
15728          end if;
15729
15730          --  In derived tagged types it is illegal to reference a non
15731          --  discriminant component in the parent type. To catch this, mark
15732          --  these components with an Ekind of E_Void. This will be reset in
15733          --  Record_Type_Definition after processing the record extension of
15734          --  the derived type.
15735
15736          --  If the declaration is a private extension, there is no further
15737          --  record extension to process, and the components retain their
15738          --  current kind, because they are visible at this point.
15739
15740          if Is_Tagged and then Ekind (New_C) = E_Component
15741            and then Nkind (N) /= N_Private_Extension_Declaration
15742          then
15743             Set_Ekind (New_C, E_Void);
15744          end if;
15745
15746          if Plain_Discrim then
15747             Set_Corresponding_Discriminant (New_C, Old_C);
15748             Build_Discriminal (New_C);
15749
15750          --  If we are explicitly inheriting a stored discriminant it will be
15751          --  completely hidden.
15752
15753          elsif Stored_Discrim then
15754             Set_Corresponding_Discriminant (New_C, Empty);
15755             Set_Discriminal (New_C, Empty);
15756             Set_Is_Completely_Hidden (New_C);
15757
15758             --  Set the Original_Record_Component of each discriminant in the
15759             --  derived base to point to the corresponding stored that we just
15760             --  created.
15761
15762             Discrim := First_Discriminant (Derived_Base);
15763             while Present (Discrim) loop
15764                Corr_Discrim := Corresponding_Discriminant (Discrim);
15765
15766                --  Corr_Discrim could be missing in an error situation
15767
15768                if Present (Corr_Discrim)
15769                  and then Original_Record_Component (Corr_Discrim) = Old_C
15770                then
15771                   Set_Original_Record_Component (Discrim, New_C);
15772                end if;
15773
15774                Next_Discriminant (Discrim);
15775             end loop;
15776
15777             Append_Entity (New_C, Derived_Base);
15778          end if;
15779
15780          if not Is_Tagged then
15781             Append_Elmt (Old_C, Assoc_List);
15782             Append_Elmt (New_C, Assoc_List);
15783          end if;
15784       end Inherit_Component;
15785
15786       --  Variables local to Inherit_Component
15787
15788       Loc : constant Source_Ptr := Sloc (N);
15789
15790       Parent_Discrim : Entity_Id;
15791       Stored_Discrim : Entity_Id;
15792       D              : Entity_Id;
15793       Component      : Entity_Id;
15794
15795    --  Start of processing for Inherit_Components
15796
15797    begin
15798       if not Is_Tagged then
15799          Append_Elmt (Parent_Base,  Assoc_List);
15800          Append_Elmt (Derived_Base, Assoc_List);
15801       end if;
15802
15803       --  Inherit parent discriminants if needed
15804
15805       if Inherit_Discr then
15806          Parent_Discrim := First_Discriminant (Parent_Base);
15807          while Present (Parent_Discrim) loop
15808             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
15809             Next_Discriminant (Parent_Discrim);
15810          end loop;
15811       end if;
15812
15813       --  Create explicit stored discrims for untagged types when necessary
15814
15815       if not Has_Unknown_Discriminants (Derived_Base)
15816         and then Has_Discriminants (Parent_Base)
15817         and then not Is_Tagged
15818         and then
15819           (not Inherit_Discr
15820              or else First_Discriminant (Parent_Base) /=
15821                      First_Stored_Discriminant (Parent_Base))
15822       then
15823          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
15824          while Present (Stored_Discrim) loop
15825             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
15826             Next_Stored_Discriminant (Stored_Discrim);
15827          end loop;
15828       end if;
15829
15830       --  See if we can apply the second transformation for derived types, as
15831       --  explained in point 6. in the comments above Build_Derived_Record_Type
15832       --  This is achieved by appending Derived_Base discriminants into Discs,
15833       --  which has the side effect of returning a non empty Discs list to the
15834       --  caller of Inherit_Components, which is what we want. This must be
15835       --  done for private derived types if there are explicit stored
15836       --  discriminants, to ensure that we can retrieve the values of the
15837       --  constraints provided in the ancestors.
15838
15839       if Inherit_Discr
15840         and then Is_Empty_Elmt_List (Discs)
15841         and then Present (First_Discriminant (Derived_Base))
15842         and then
15843           (not Is_Private_Type (Derived_Base)
15844              or else Is_Completely_Hidden
15845                (First_Stored_Discriminant (Derived_Base))
15846              or else Is_Generic_Type (Derived_Base))
15847       then
15848          D := First_Discriminant (Derived_Base);
15849          while Present (D) loop
15850             Append_Elmt (New_Reference_To (D, Loc), Discs);
15851             Next_Discriminant (D);
15852          end loop;
15853       end if;
15854
15855       --  Finally, inherit non-discriminant components unless they are not
15856       --  visible because defined or inherited from the full view of the
15857       --  parent. Don't inherit the _parent field of the parent type.
15858
15859       Component := First_Entity (Parent_Base);
15860       while Present (Component) loop
15861
15862          --  Ada 2005 (AI-251): Do not inherit components associated with
15863          --  secondary tags of the parent.
15864
15865          if Ekind (Component) = E_Component
15866            and then Present (Related_Type (Component))
15867          then
15868             null;
15869
15870          elsif Ekind (Component) /= E_Component
15871            or else Chars (Component) = Name_uParent
15872          then
15873             null;
15874
15875          --  If the derived type is within the parent type's declarative
15876          --  region, then the components can still be inherited even though
15877          --  they aren't visible at this point. This can occur for cases
15878          --  such as within public child units where the components must
15879          --  become visible upon entering the child unit's private part.
15880
15881          elsif not Is_Visible_Component (Component)
15882            and then not In_Open_Scopes (Scope (Parent_Base))
15883          then
15884             null;
15885
15886          elsif Ekind_In (Derived_Base, E_Private_Type,
15887                                        E_Limited_Private_Type)
15888          then
15889             null;
15890
15891          else
15892             Inherit_Component (Component);
15893          end if;
15894
15895          Next_Entity (Component);
15896       end loop;
15897
15898       --  For tagged derived types, inherited discriminants cannot be used in
15899       --  component declarations of the record extension part. To achieve this
15900       --  we mark the inherited discriminants as not visible.
15901
15902       if Is_Tagged and then Inherit_Discr then
15903          D := First_Discriminant (Derived_Base);
15904          while Present (D) loop
15905             Set_Is_Immediately_Visible (D, False);
15906             Next_Discriminant (D);
15907          end loop;
15908       end if;
15909
15910       return Assoc_List;
15911    end Inherit_Components;
15912
15913    -----------------------
15914    -- Is_Constant_Bound --
15915    -----------------------
15916
15917    function Is_Constant_Bound (Exp : Node_Id) return Boolean is
15918    begin
15919       if Compile_Time_Known_Value (Exp) then
15920          return True;
15921
15922       elsif Is_Entity_Name (Exp)
15923         and then Present (Entity (Exp))
15924       then
15925          return Is_Constant_Object (Entity (Exp))
15926            or else Ekind (Entity (Exp)) = E_Enumeration_Literal;
15927
15928       elsif Nkind (Exp) in N_Binary_Op then
15929          return Is_Constant_Bound (Left_Opnd (Exp))
15930            and then Is_Constant_Bound (Right_Opnd (Exp))
15931            and then Scope (Entity (Exp)) = Standard_Standard;
15932
15933       else
15934          return False;
15935       end if;
15936    end Is_Constant_Bound;
15937
15938    -----------------------
15939    -- Is_Null_Extension --
15940    -----------------------
15941
15942    function Is_Null_Extension (T : Entity_Id) return Boolean is
15943       Type_Decl : constant Node_Id := Parent (Base_Type (T));
15944       Comp_List : Node_Id;
15945       Comp      : Node_Id;
15946
15947    begin
15948       if Nkind (Type_Decl) /= N_Full_Type_Declaration
15949         or else not Is_Tagged_Type (T)
15950         or else Nkind (Type_Definition (Type_Decl)) /=
15951                                               N_Derived_Type_Definition
15952         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
15953       then
15954          return False;
15955       end if;
15956
15957       Comp_List :=
15958         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
15959
15960       if Present (Discriminant_Specifications (Type_Decl)) then
15961          return False;
15962
15963       elsif Present (Comp_List)
15964         and then Is_Non_Empty_List (Component_Items (Comp_List))
15965       then
15966          Comp := First (Component_Items (Comp_List));
15967
15968          --  Only user-defined components are relevant. The component list
15969          --  may also contain a parent component and internal components
15970          --  corresponding to secondary tags, but these do not determine
15971          --  whether this is a null extension.
15972
15973          while Present (Comp) loop
15974             if Comes_From_Source (Comp) then
15975                return False;
15976             end if;
15977
15978             Next (Comp);
15979          end loop;
15980
15981          return True;
15982       else
15983          return True;
15984       end if;
15985    end Is_Null_Extension;
15986
15987    ------------------------------
15988    -- Is_Valid_Constraint_Kind --
15989    ------------------------------
15990
15991    function Is_Valid_Constraint_Kind
15992      (T_Kind          : Type_Kind;
15993       Constraint_Kind : Node_Kind) return Boolean
15994    is
15995    begin
15996       case T_Kind is
15997          when Enumeration_Kind |
15998               Integer_Kind =>
15999             return Constraint_Kind = N_Range_Constraint;
16000
16001          when Decimal_Fixed_Point_Kind =>
16002             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
16003                                               N_Range_Constraint);
16004
16005          when Ordinary_Fixed_Point_Kind =>
16006             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
16007                                               N_Range_Constraint);
16008
16009          when Float_Kind =>
16010             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
16011                                               N_Range_Constraint);
16012
16013          when Access_Kind       |
16014               Array_Kind        |
16015               E_Record_Type     |
16016               E_Record_Subtype  |
16017               Class_Wide_Kind   |
16018               E_Incomplete_Type |
16019               Private_Kind      |
16020               Concurrent_Kind  =>
16021             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
16022
16023          when others =>
16024             return True; -- Error will be detected later
16025       end case;
16026    end Is_Valid_Constraint_Kind;
16027
16028    --------------------------
16029    -- Is_Visible_Component --
16030    --------------------------
16031
16032    function Is_Visible_Component (C : Entity_Id) return Boolean is
16033       Original_Comp  : Entity_Id := Empty;
16034       Original_Scope : Entity_Id;
16035       Type_Scope     : Entity_Id;
16036
16037       function Is_Local_Type (Typ : Entity_Id) return Boolean;
16038       --  Check whether parent type of inherited component is declared locally,
16039       --  possibly within a nested package or instance. The current scope is
16040       --  the derived record itself.
16041
16042       -------------------
16043       -- Is_Local_Type --
16044       -------------------
16045
16046       function Is_Local_Type (Typ : Entity_Id) return Boolean is
16047          Scop : Entity_Id;
16048
16049       begin
16050          Scop := Scope (Typ);
16051          while Present (Scop)
16052            and then Scop /= Standard_Standard
16053          loop
16054             if Scop = Scope (Current_Scope) then
16055                return True;
16056             end if;
16057
16058             Scop := Scope (Scop);
16059          end loop;
16060
16061          return False;
16062       end Is_Local_Type;
16063
16064    --  Start of processing for Is_Visible_Component
16065
16066    begin
16067       if Ekind_In (C, E_Component, E_Discriminant) then
16068          Original_Comp := Original_Record_Component (C);
16069       end if;
16070
16071       if No (Original_Comp) then
16072
16073          --  Premature usage, or previous error
16074
16075          return False;
16076
16077       else
16078          Original_Scope := Scope (Original_Comp);
16079          Type_Scope     := Scope (Base_Type (Scope (C)));
16080       end if;
16081
16082       --  This test only concerns tagged types
16083
16084       if not Is_Tagged_Type (Original_Scope) then
16085          return True;
16086
16087       --  If it is _Parent or _Tag, there is no visibility issue
16088
16089       elsif not Comes_From_Source (Original_Comp) then
16090          return True;
16091
16092       --  If we are in the body of an instantiation, the component is visible
16093       --  even when the parent type (possibly defined in an enclosing unit or
16094       --  in a parent unit) might not.
16095
16096       elsif In_Instance_Body then
16097          return True;
16098
16099       --  Discriminants are always visible
16100
16101       elsif Ekind (Original_Comp) = E_Discriminant
16102         and then not Has_Unknown_Discriminants (Original_Scope)
16103       then
16104          return True;
16105
16106       --  If the component has been declared in an ancestor which is currently
16107       --  a private type, then it is not visible. The same applies if the
16108       --  component's containing type is not in an open scope and the original
16109       --  component's enclosing type is a visible full view of a private type
16110       --  (which can occur in cases where an attempt is being made to reference
16111       --  a component in a sibling package that is inherited from a visible
16112       --  component of a type in an ancestor package; the component in the
16113       --  sibling package should not be visible even though the component it
16114       --  inherited from is visible). This does not apply however in the case
16115       --  where the scope of the type is a private child unit, or when the
16116       --  parent comes from a local package in which the ancestor is currently
16117       --  visible. The latter suppression of visibility is needed for cases
16118       --  that are tested in B730006.
16119
16120       elsif Is_Private_Type (Original_Scope)
16121         or else
16122           (not Is_Private_Descendant (Type_Scope)
16123             and then not In_Open_Scopes (Type_Scope)
16124             and then Has_Private_Declaration (Original_Scope))
16125       then
16126          --  If the type derives from an entity in a formal package, there
16127          --  are no additional visible components.
16128
16129          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
16130             N_Formal_Package_Declaration
16131          then
16132             return False;
16133
16134          --  if we are not in the private part of the current package, there
16135          --  are no additional visible components.
16136
16137          elsif Ekind (Scope (Current_Scope)) = E_Package
16138            and then not In_Private_Part (Scope (Current_Scope))
16139          then
16140             return False;
16141          else
16142             return
16143               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
16144                 and then In_Open_Scopes (Scope (Original_Scope))
16145                 and then Is_Local_Type (Type_Scope);
16146          end if;
16147
16148       --  There is another weird way in which a component may be invisible
16149       --  when the private and the full view are not derived from the same
16150       --  ancestor. Here is an example :
16151
16152       --       type A1 is tagged      record F1 : integer; end record;
16153       --       type A2 is new A1 with record F2 : integer; end record;
16154       --       type T is new A1 with private;
16155       --     private
16156       --       type T is new A2 with null record;
16157
16158       --  In this case, the full view of T inherits F1 and F2 but the private
16159       --  view inherits only F1
16160
16161       else
16162          declare
16163             Ancestor : Entity_Id := Scope (C);
16164
16165          begin
16166             loop
16167                if Ancestor = Original_Scope then
16168                   return True;
16169                elsif Ancestor = Etype (Ancestor) then
16170                   return False;
16171                end if;
16172
16173                Ancestor := Etype (Ancestor);
16174             end loop;
16175          end;
16176       end if;
16177    end Is_Visible_Component;
16178
16179    --------------------------
16180    -- Make_Class_Wide_Type --
16181    --------------------------
16182
16183    procedure Make_Class_Wide_Type (T : Entity_Id) is
16184       CW_Type : Entity_Id;
16185       CW_Name : Name_Id;
16186       Next_E  : Entity_Id;
16187
16188    begin
16189       if Present (Class_Wide_Type (T)) then
16190
16191          --  The class-wide type is a partially decorated entity created for a
16192          --  unanalyzed tagged type referenced through a limited with clause.
16193          --  When the tagged type is analyzed, its class-wide type needs to be
16194          --  redecorated. Note that we reuse the entity created by Decorate_
16195          --  Tagged_Type in order to preserve all links.
16196
16197          if Materialize_Entity (Class_Wide_Type (T)) then
16198             CW_Type := Class_Wide_Type (T);
16199             Set_Materialize_Entity (CW_Type, False);
16200
16201          --  The class wide type can have been defined by the partial view, in
16202          --  which case everything is already done.
16203
16204          else
16205             return;
16206          end if;
16207
16208       --  Default case, we need to create a new class-wide type
16209
16210       else
16211          CW_Type :=
16212            New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
16213       end if;
16214
16215       --  Inherit root type characteristics
16216
16217       CW_Name := Chars (CW_Type);
16218       Next_E  := Next_Entity (CW_Type);
16219       Copy_Node (T, CW_Type);
16220       Set_Comes_From_Source (CW_Type, False);
16221       Set_Chars (CW_Type, CW_Name);
16222       Set_Parent (CW_Type, Parent (T));
16223       Set_Next_Entity (CW_Type, Next_E);
16224
16225       --  Ensure we have a new freeze node for the class-wide type. The partial
16226       --  view may have freeze action of its own, requiring a proper freeze
16227       --  node, and the same freeze node cannot be shared between the two
16228       --  types.
16229
16230       Set_Has_Delayed_Freeze (CW_Type);
16231       Set_Freeze_Node (CW_Type, Empty);
16232
16233       --  Customize the class-wide type: It has no prim. op., it cannot be
16234       --  abstract and its Etype points back to the specific root type.
16235
16236       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
16237       Set_Is_Tagged_Type              (CW_Type, True);
16238       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
16239       Set_Is_Abstract_Type            (CW_Type, False);
16240       Set_Is_Constrained              (CW_Type, False);
16241       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
16242
16243       if Ekind (T) = E_Class_Wide_Subtype then
16244          Set_Etype             (CW_Type, Etype (Base_Type (T)));
16245       else
16246          Set_Etype             (CW_Type, T);
16247       end if;
16248
16249       --  If this is the class_wide type of a constrained subtype, it does
16250       --  not have discriminants.
16251
16252       Set_Has_Discriminants (CW_Type,
16253         Has_Discriminants (T) and then not Is_Constrained (T));
16254
16255       Set_Has_Unknown_Discriminants (CW_Type, True);
16256       Set_Class_Wide_Type (T, CW_Type);
16257       Set_Equivalent_Type (CW_Type, Empty);
16258
16259       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
16260
16261       Set_Class_Wide_Type (CW_Type, CW_Type);
16262    end Make_Class_Wide_Type;
16263
16264    ----------------
16265    -- Make_Index --
16266    ----------------
16267
16268    procedure Make_Index
16269      (I            : Node_Id;
16270       Related_Nod  : Node_Id;
16271       Related_Id   : Entity_Id := Empty;
16272       Suffix_Index : Nat := 1;
16273       In_Iter_Schm : Boolean := False)
16274    is
16275       R      : Node_Id;
16276       T      : Entity_Id;
16277       Def_Id : Entity_Id := Empty;
16278       Found  : Boolean := False;
16279
16280    begin
16281       --  For a discrete range used in a constrained array definition and
16282       --  defined by a range, an implicit conversion to the predefined type
16283       --  INTEGER is assumed if each bound is either a numeric literal, a named
16284       --  number, or an attribute, and the type of both bounds (prior to the
16285       --  implicit conversion) is the type universal_integer. Otherwise, both
16286       --  bounds must be of the same discrete type, other than universal
16287       --  integer; this type must be determinable independently of the
16288       --  context, but using the fact that the type must be discrete and that
16289       --  both bounds must have the same type.
16290
16291       --  Character literals also have a universal type in the absence of
16292       --  of additional context,  and are resolved to Standard_Character.
16293
16294       if Nkind (I) = N_Range then
16295
16296          --  The index is given by a range constraint. The bounds are known
16297          --  to be of a consistent type.
16298
16299          if not Is_Overloaded (I) then
16300             T := Etype (I);
16301
16302             --  For universal bounds, choose the specific predefined type
16303
16304             if T = Universal_Integer then
16305                T := Standard_Integer;
16306
16307             elsif T = Any_Character then
16308                Ambiguous_Character (Low_Bound (I));
16309
16310                T := Standard_Character;
16311             end if;
16312
16313          --  The node may be overloaded because some user-defined operators
16314          --  are available, but if a universal interpretation exists it is
16315          --  also the selected one.
16316
16317          elsif Universal_Interpretation (I) = Universal_Integer then
16318             T := Standard_Integer;
16319
16320          else
16321             T := Any_Type;
16322
16323             declare
16324                Ind : Interp_Index;
16325                It  : Interp;
16326
16327             begin
16328                Get_First_Interp (I, Ind, It);
16329                while Present (It.Typ) loop
16330                   if Is_Discrete_Type (It.Typ) then
16331
16332                      if Found
16333                        and then not Covers (It.Typ, T)
16334                        and then not Covers (T, It.Typ)
16335                      then
16336                         Error_Msg_N ("ambiguous bounds in discrete range", I);
16337                         exit;
16338                      else
16339                         T := It.Typ;
16340                         Found := True;
16341                      end if;
16342                   end if;
16343
16344                   Get_Next_Interp (Ind, It);
16345                end loop;
16346
16347                if T = Any_Type then
16348                   Error_Msg_N ("discrete type required for range", I);
16349                   Set_Etype (I, Any_Type);
16350                   return;
16351
16352                elsif T = Universal_Integer then
16353                   T := Standard_Integer;
16354                end if;
16355             end;
16356          end if;
16357
16358          if not Is_Discrete_Type (T) then
16359             Error_Msg_N ("discrete type required for range", I);
16360             Set_Etype (I, Any_Type);
16361             return;
16362          end if;
16363
16364          if Nkind (Low_Bound (I)) = N_Attribute_Reference
16365            and then Attribute_Name (Low_Bound (I)) = Name_First
16366            and then Is_Entity_Name (Prefix (Low_Bound (I)))
16367            and then Is_Type (Entity (Prefix (Low_Bound (I))))
16368            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
16369          then
16370             --  The type of the index will be the type of the prefix, as long
16371             --  as the upper bound is 'Last of the same type.
16372
16373             Def_Id := Entity (Prefix (Low_Bound (I)));
16374
16375             if Nkind (High_Bound (I)) /= N_Attribute_Reference
16376               or else Attribute_Name (High_Bound (I)) /= Name_Last
16377               or else not Is_Entity_Name (Prefix (High_Bound (I)))
16378               or else Entity (Prefix (High_Bound (I))) /= Def_Id
16379             then
16380                Def_Id := Empty;
16381             end if;
16382          end if;
16383
16384          R := I;
16385          Process_Range_Expr_In_Decl (R, T, In_Iter_Schm => In_Iter_Schm);
16386
16387       elsif Nkind (I) = N_Subtype_Indication then
16388
16389          --  The index is given by a subtype with a range constraint
16390
16391          T :=  Base_Type (Entity (Subtype_Mark (I)));
16392
16393          if not Is_Discrete_Type (T) then
16394             Error_Msg_N ("discrete type required for range", I);
16395             Set_Etype (I, Any_Type);
16396             return;
16397          end if;
16398
16399          R := Range_Expression (Constraint (I));
16400
16401          Resolve (R, T);
16402          Process_Range_Expr_In_Decl
16403            (R, Entity (Subtype_Mark (I)), In_Iter_Schm => In_Iter_Schm);
16404
16405       elsif Nkind (I) = N_Attribute_Reference then
16406
16407          --  The parser guarantees that the attribute is a RANGE attribute
16408
16409          --  If the node denotes the range of a type mark, that is also the
16410          --  resulting type, and we do no need to create an Itype for it.
16411
16412          if Is_Entity_Name (Prefix (I))
16413            and then Comes_From_Source (I)
16414            and then Is_Type (Entity (Prefix (I)))
16415            and then Is_Discrete_Type (Entity (Prefix (I)))
16416          then
16417             Def_Id := Entity (Prefix (I));
16418          end if;
16419
16420          Analyze_And_Resolve (I);
16421          T := Etype (I);
16422          R := I;
16423
16424       --  If none of the above, must be a subtype. We convert this to a
16425       --  range attribute reference because in the case of declared first
16426       --  named subtypes, the types in the range reference can be different
16427       --  from the type of the entity. A range attribute normalizes the
16428       --  reference and obtains the correct types for the bounds.
16429
16430       --  This transformation is in the nature of an expansion, is only
16431       --  done if expansion is active. In particular, it is not done on
16432       --  formal generic types,  because we need to retain the name of the
16433       --  original index for instantiation purposes.
16434
16435       else
16436          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
16437             Error_Msg_N ("invalid subtype mark in discrete range ", I);
16438             Set_Etype (I, Any_Integer);
16439             return;
16440
16441          else
16442             --  The type mark may be that of an incomplete type. It is only
16443             --  now that we can get the full view, previous analysis does
16444             --  not look specifically for a type mark.
16445
16446             Set_Entity (I, Get_Full_View (Entity (I)));
16447             Set_Etype  (I, Entity (I));
16448             Def_Id := Entity (I);
16449
16450             if not Is_Discrete_Type (Def_Id) then
16451                Error_Msg_N ("discrete type required for index", I);
16452                Set_Etype (I, Any_Type);
16453                return;
16454             end if;
16455          end if;
16456
16457          if Expander_Active then
16458             Rewrite (I,
16459               Make_Attribute_Reference (Sloc (I),
16460                 Attribute_Name => Name_Range,
16461                 Prefix         => Relocate_Node (I)));
16462
16463             --  The original was a subtype mark that does not freeze. This
16464             --  means that the rewritten version must not freeze either.
16465
16466             Set_Must_Not_Freeze (I);
16467             Set_Must_Not_Freeze (Prefix (I));
16468
16469             --  Is order critical??? if so, document why, if not
16470             --  use Analyze_And_Resolve
16471
16472             Analyze_And_Resolve (I);
16473             T := Etype (I);
16474             R := I;
16475
16476          --  If expander is inactive, type is legal, nothing else to construct
16477
16478          else
16479             return;
16480          end if;
16481       end if;
16482
16483       if not Is_Discrete_Type (T) then
16484          Error_Msg_N ("discrete type required for range", I);
16485          Set_Etype (I, Any_Type);
16486          return;
16487
16488       elsif T = Any_Type then
16489          Set_Etype (I, Any_Type);
16490          return;
16491       end if;
16492
16493       --  We will now create the appropriate Itype to describe the range, but
16494       --  first a check. If we originally had a subtype, then we just label
16495       --  the range with this subtype. Not only is there no need to construct
16496       --  a new subtype, but it is wrong to do so for two reasons:
16497
16498       --    1. A legality concern, if we have a subtype, it must not freeze,
16499       --       and the Itype would cause freezing incorrectly
16500
16501       --    2. An efficiency concern, if we created an Itype, it would not be
16502       --       recognized as the same type for the purposes of eliminating
16503       --       checks in some circumstances.
16504
16505       --  We signal this case by setting the subtype entity in Def_Id
16506
16507       if No (Def_Id) then
16508          Def_Id :=
16509            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
16510          Set_Etype (Def_Id, Base_Type (T));
16511
16512          if Is_Signed_Integer_Type (T) then
16513             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
16514
16515          elsif Is_Modular_Integer_Type (T) then
16516             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
16517
16518          else
16519             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
16520             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
16521             Set_First_Literal     (Def_Id, First_Literal (T));
16522          end if;
16523
16524          Set_Size_Info      (Def_Id,                  (T));
16525          Set_RM_Size        (Def_Id, RM_Size          (T));
16526          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
16527
16528          Set_Scalar_Range   (Def_Id, R);
16529          Conditional_Delay  (Def_Id, T);
16530
16531          --  In the subtype indication case, if the immediate parent of the
16532          --  new subtype is non-static, then the subtype we create is non-
16533          --  static, even if its bounds are static.
16534
16535          if Nkind (I) = N_Subtype_Indication
16536            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
16537          then
16538             Set_Is_Non_Static_Subtype (Def_Id);
16539          end if;
16540       end if;
16541
16542       --  Final step is to label the index with this constructed type
16543
16544       Set_Etype (I, Def_Id);
16545    end Make_Index;
16546
16547    ------------------------------
16548    -- Modular_Type_Declaration --
16549    ------------------------------
16550
16551    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
16552       Mod_Expr : constant Node_Id := Expression (Def);
16553       M_Val    : Uint;
16554
16555       procedure Set_Modular_Size (Bits : Int);
16556       --  Sets RM_Size to Bits, and Esize to normal word size above this
16557
16558       ----------------------
16559       -- Set_Modular_Size --
16560       ----------------------
16561
16562       procedure Set_Modular_Size (Bits : Int) is
16563       begin
16564          Set_RM_Size (T, UI_From_Int (Bits));
16565
16566          if Bits <= 8 then
16567             Init_Esize (T, 8);
16568
16569          elsif Bits <= 16 then
16570             Init_Esize (T, 16);
16571
16572          elsif Bits <= 32 then
16573             Init_Esize (T, 32);
16574
16575          else
16576             Init_Esize (T, System_Max_Binary_Modulus_Power);
16577          end if;
16578
16579          if not Non_Binary_Modulus (T)
16580            and then Esize (T) = RM_Size (T)
16581          then
16582             Set_Is_Known_Valid (T);
16583          end if;
16584       end Set_Modular_Size;
16585
16586    --  Start of processing for Modular_Type_Declaration
16587
16588    begin
16589       Analyze_And_Resolve (Mod_Expr, Any_Integer);
16590       Set_Etype (T, T);
16591       Set_Ekind (T, E_Modular_Integer_Type);
16592       Init_Alignment (T);
16593       Set_Is_Constrained (T);
16594
16595       if not Is_OK_Static_Expression (Mod_Expr) then
16596          Flag_Non_Static_Expr
16597            ("non-static expression used for modular type bound!", Mod_Expr);
16598          M_Val := 2 ** System_Max_Binary_Modulus_Power;
16599       else
16600          M_Val := Expr_Value (Mod_Expr);
16601       end if;
16602
16603       if M_Val < 1 then
16604          Error_Msg_N ("modulus value must be positive", Mod_Expr);
16605          M_Val := 2 ** System_Max_Binary_Modulus_Power;
16606       end if;
16607
16608       Set_Modulus (T, M_Val);
16609
16610       --   Create bounds for the modular type based on the modulus given in
16611       --   the type declaration and then analyze and resolve those bounds.
16612
16613       Set_Scalar_Range (T,
16614         Make_Range (Sloc (Mod_Expr),
16615           Low_Bound  => Make_Integer_Literal (Sloc (Mod_Expr), 0),
16616           High_Bound => Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
16617
16618       --  Properly analyze the literals for the range. We do this manually
16619       --  because we can't go calling Resolve, since we are resolving these
16620       --  bounds with the type, and this type is certainly not complete yet!
16621
16622       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
16623       Set_Etype (High_Bound (Scalar_Range (T)), T);
16624       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
16625       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
16626
16627       --  Loop through powers of two to find number of bits required
16628
16629       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
16630
16631          --  Binary case
16632
16633          if M_Val = 2 ** Bits then
16634             Set_Modular_Size (Bits);
16635             return;
16636
16637          --  Non-binary case
16638
16639          elsif M_Val < 2 ** Bits then
16640             Check_SPARK_Restriction ("modulus should be a power of 2", T);
16641             Set_Non_Binary_Modulus (T);
16642
16643             if Bits > System_Max_Nonbinary_Modulus_Power then
16644                Error_Msg_Uint_1 :=
16645                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
16646                Error_Msg_F
16647                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
16648                Set_Modular_Size (System_Max_Binary_Modulus_Power);
16649                return;
16650
16651             else
16652                --  In the non-binary case, set size as per RM 13.3(55)
16653
16654                Set_Modular_Size (Bits);
16655                return;
16656             end if;
16657          end if;
16658
16659       end loop;
16660
16661       --  If we fall through, then the size exceed System.Max_Binary_Modulus
16662       --  so we just signal an error and set the maximum size.
16663
16664       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
16665       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
16666
16667       Set_Modular_Size (System_Max_Binary_Modulus_Power);
16668       Init_Alignment (T);
16669
16670    end Modular_Type_Declaration;
16671
16672    --------------------------
16673    -- New_Concatenation_Op --
16674    --------------------------
16675
16676    procedure New_Concatenation_Op (Typ : Entity_Id) is
16677       Loc : constant Source_Ptr := Sloc (Typ);
16678       Op  : Entity_Id;
16679
16680       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
16681       --  Create abbreviated declaration for the formal of a predefined
16682       --  Operator 'Op' of type 'Typ'
16683
16684       --------------------
16685       -- Make_Op_Formal --
16686       --------------------
16687
16688       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
16689          Formal : Entity_Id;
16690       begin
16691          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
16692          Set_Etype (Formal, Typ);
16693          Set_Mechanism (Formal, Default_Mechanism);
16694          return Formal;
16695       end Make_Op_Formal;
16696
16697    --  Start of processing for New_Concatenation_Op
16698
16699    begin
16700       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
16701
16702       Set_Ekind                   (Op, E_Operator);
16703       Set_Scope                   (Op, Current_Scope);
16704       Set_Etype                   (Op, Typ);
16705       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
16706       Set_Is_Immediately_Visible  (Op);
16707       Set_Is_Intrinsic_Subprogram (Op);
16708       Set_Has_Completion          (Op);
16709       Append_Entity               (Op, Current_Scope);
16710
16711       Set_Name_Entity_Id (Name_Op_Concat, Op);
16712
16713       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16714       Append_Entity (Make_Op_Formal (Typ, Op), Op);
16715    end New_Concatenation_Op;
16716
16717    -------------------------
16718    -- OK_For_Limited_Init --
16719    -------------------------
16720
16721    --  ???Check all calls of this, and compare the conditions under which it's
16722    --  called.
16723
16724    function OK_For_Limited_Init
16725      (Typ : Entity_Id;
16726       Exp : Node_Id) return Boolean
16727    is
16728    begin
16729       return Is_CPP_Constructor_Call (Exp)
16730         or else (Ada_Version >= Ada_2005
16731                   and then not Debug_Flag_Dot_L
16732                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
16733    end OK_For_Limited_Init;
16734
16735    -------------------------------
16736    -- OK_For_Limited_Init_In_05 --
16737    -------------------------------
16738
16739    function OK_For_Limited_Init_In_05
16740      (Typ : Entity_Id;
16741       Exp : Node_Id) return Boolean
16742    is
16743    begin
16744       --  An object of a limited interface type can be initialized with any
16745       --  expression of a nonlimited descendant type.
16746
16747       if Is_Class_Wide_Type (Typ)
16748         and then Is_Limited_Interface (Typ)
16749         and then not Is_Limited_Type (Etype (Exp))
16750       then
16751          return True;
16752       end if;
16753
16754       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
16755       --  case of limited aggregates (including extension aggregates), and
16756       --  function calls. The function call may have been given in prefixed
16757       --  notation, in which case the original node is an indexed component.
16758       --  If the function is parameterless, the original node was an explicit
16759       --  dereference.
16760
16761       case Nkind (Original_Node (Exp)) is
16762          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
16763             return True;
16764
16765          when N_Qualified_Expression =>
16766             return
16767               OK_For_Limited_Init_In_05
16768                 (Typ, Expression (Original_Node (Exp)));
16769
16770          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
16771          --  with a function call, the expander has rewritten the call into an
16772          --  N_Type_Conversion node to force displacement of the pointer to
16773          --  reference the component containing the secondary dispatch table.
16774          --  Otherwise a type conversion is not a legal context.
16775          --  A return statement for a build-in-place function returning a
16776          --  synchronized type also introduces an unchecked conversion.
16777
16778          when N_Type_Conversion           |
16779               N_Unchecked_Type_Conversion =>
16780             return not Comes_From_Source (Exp)
16781               and then
16782                 OK_For_Limited_Init_In_05
16783                   (Typ, Expression (Original_Node (Exp)));
16784
16785          when N_Indexed_Component     |
16786               N_Selected_Component    |
16787               N_Explicit_Dereference  =>
16788             return Nkind (Exp) = N_Function_Call;
16789
16790          --  A use of 'Input is a function call, hence allowed. Normally the
16791          --  attribute will be changed to a call, but the attribute by itself
16792          --  can occur with -gnatc.
16793
16794          when N_Attribute_Reference =>
16795             return Attribute_Name (Original_Node (Exp)) = Name_Input;
16796
16797          when others =>
16798             return False;
16799       end case;
16800    end OK_For_Limited_Init_In_05;
16801
16802    -------------------------------------------
16803    -- Ordinary_Fixed_Point_Type_Declaration --
16804    -------------------------------------------
16805
16806    procedure Ordinary_Fixed_Point_Type_Declaration
16807      (T   : Entity_Id;
16808       Def : Node_Id)
16809    is
16810       Loc           : constant Source_Ptr := Sloc (Def);
16811       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
16812       RRS           : constant Node_Id    := Real_Range_Specification (Def);
16813       Implicit_Base : Entity_Id;
16814       Delta_Val     : Ureal;
16815       Small_Val     : Ureal;
16816       Low_Val       : Ureal;
16817       High_Val      : Ureal;
16818
16819    begin
16820       Check_Restriction (No_Fixed_Point, Def);
16821
16822       --  Create implicit base type
16823
16824       Implicit_Base :=
16825         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
16826       Set_Etype (Implicit_Base, Implicit_Base);
16827
16828       --  Analyze and process delta expression
16829
16830       Analyze_And_Resolve (Delta_Expr, Any_Real);
16831
16832       Check_Delta_Expression (Delta_Expr);
16833       Delta_Val := Expr_Value_R (Delta_Expr);
16834
16835       Set_Delta_Value (Implicit_Base, Delta_Val);
16836
16837       --  Compute default small from given delta, which is the largest power
16838       --  of two that does not exceed the given delta value.
16839
16840       declare
16841          Tmp   : Ureal;
16842          Scale : Int;
16843
16844       begin
16845          Tmp := Ureal_1;
16846          Scale := 0;
16847
16848          if Delta_Val < Ureal_1 then
16849             while Delta_Val < Tmp loop
16850                Tmp := Tmp / Ureal_2;
16851                Scale := Scale + 1;
16852             end loop;
16853
16854          else
16855             loop
16856                Tmp := Tmp * Ureal_2;
16857                exit when Tmp > Delta_Val;
16858                Scale := Scale - 1;
16859             end loop;
16860          end if;
16861
16862          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
16863       end;
16864
16865       Set_Small_Value (Implicit_Base, Small_Val);
16866
16867       --  If no range was given, set a dummy range
16868
16869       if RRS <= Empty_Or_Error then
16870          Low_Val  := -Small_Val;
16871          High_Val := Small_Val;
16872
16873       --  Otherwise analyze and process given range
16874
16875       else
16876          declare
16877             Low  : constant Node_Id := Low_Bound  (RRS);
16878             High : constant Node_Id := High_Bound (RRS);
16879
16880          begin
16881             Analyze_And_Resolve (Low, Any_Real);
16882             Analyze_And_Resolve (High, Any_Real);
16883             Check_Real_Bound (Low);
16884             Check_Real_Bound (High);
16885
16886             --  Obtain and set the range
16887
16888             Low_Val  := Expr_Value_R (Low);
16889             High_Val := Expr_Value_R (High);
16890
16891             if Low_Val > High_Val then
16892                Error_Msg_NE ("?fixed point type& has null range", Def, T);
16893             end if;
16894          end;
16895       end if;
16896
16897       --  The range for both the implicit base and the declared first subtype
16898       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
16899       --  set a temporary range in place. Note that the bounds of the base
16900       --  type will be widened to be symmetrical and to fill the available
16901       --  bits when the type is frozen.
16902
16903       --  We could do this with all discrete types, and probably should, but
16904       --  we absolutely have to do it for fixed-point, since the end-points
16905       --  of the range and the size are determined by the small value, which
16906       --  could be reset before the freeze point.
16907
16908       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
16909       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
16910
16911       --  Complete definition of first subtype
16912
16913       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
16914       Set_Etype          (T, Implicit_Base);
16915       Init_Size_Align    (T);
16916       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
16917       Set_Small_Value    (T, Small_Val);
16918       Set_Delta_Value    (T, Delta_Val);
16919       Set_Is_Constrained (T);
16920
16921    end Ordinary_Fixed_Point_Type_Declaration;
16922
16923    ----------------------------------------
16924    -- Prepare_Private_Subtype_Completion --
16925    ----------------------------------------
16926
16927    procedure Prepare_Private_Subtype_Completion
16928      (Id          : Entity_Id;
16929       Related_Nod : Node_Id)
16930    is
16931       Id_B   : constant Entity_Id := Base_Type (Id);
16932       Full_B : constant Entity_Id := Full_View (Id_B);
16933       Full   : Entity_Id;
16934
16935    begin
16936       if Present (Full_B) then
16937
16938          --  The Base_Type is already completed, we can complete the subtype
16939          --  now. We have to create a new entity with the same name, Thus we
16940          --  can't use Create_Itype.
16941
16942          --  This is messy, should be fixed ???
16943
16944          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
16945          Set_Is_Itype (Full);
16946          Set_Associated_Node_For_Itype (Full, Related_Nod);
16947          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
16948       end if;
16949
16950       --  The parent subtype may be private, but the base might not, in some
16951       --  nested instances. In that case, the subtype does not need to be
16952       --  exchanged. It would still be nice to make private subtypes and their
16953       --  bases consistent at all times ???
16954
16955       if Is_Private_Type (Id_B) then
16956          Append_Elmt (Id, Private_Dependents (Id_B));
16957       end if;
16958
16959    end Prepare_Private_Subtype_Completion;
16960
16961    ---------------------------
16962    -- Process_Discriminants --
16963    ---------------------------
16964
16965    procedure Process_Discriminants
16966      (N    : Node_Id;
16967       Prev : Entity_Id := Empty)
16968    is
16969       Elist               : constant Elist_Id := New_Elmt_List;
16970       Id                  : Node_Id;
16971       Discr               : Node_Id;
16972       Discr_Number        : Uint;
16973       Discr_Type          : Entity_Id;
16974       Default_Present     : Boolean := False;
16975       Default_Not_Present : Boolean := False;
16976
16977    begin
16978       --  A composite type other than an array type can have discriminants.
16979       --  On entry, the current scope is the composite type.
16980
16981       --  The discriminants are initially entered into the scope of the type
16982       --  via Enter_Name with the default Ekind of E_Void to prevent premature
16983       --  use, as explained at the end of this procedure.
16984
16985       Discr := First (Discriminant_Specifications (N));
16986       while Present (Discr) loop
16987          Enter_Name (Defining_Identifier (Discr));
16988
16989          --  For navigation purposes we add a reference to the discriminant
16990          --  in the entity for the type. If the current declaration is a
16991          --  completion, place references on the partial view. Otherwise the
16992          --  type is the current scope.
16993
16994          if Present (Prev) then
16995
16996             --  The references go on the partial view, if present. If the
16997             --  partial view has discriminants, the references have been
16998             --  generated already.
16999
17000             if not Has_Discriminants (Prev) then
17001                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
17002             end if;
17003          else
17004             Generate_Reference
17005               (Current_Scope, Defining_Identifier (Discr), 'd');
17006          end if;
17007
17008          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
17009             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
17010
17011             --  Ada 2005 (AI-254)
17012
17013             if Present (Access_To_Subprogram_Definition
17014                          (Discriminant_Type (Discr)))
17015               and then Protected_Present (Access_To_Subprogram_Definition
17016                                            (Discriminant_Type (Discr)))
17017             then
17018                Discr_Type :=
17019                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
17020             end if;
17021
17022          else
17023             Find_Type (Discriminant_Type (Discr));
17024             Discr_Type := Etype (Discriminant_Type (Discr));
17025
17026             if Error_Posted (Discriminant_Type (Discr)) then
17027                Discr_Type := Any_Type;
17028             end if;
17029          end if;
17030
17031          if Is_Access_Type (Discr_Type) then
17032
17033             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
17034             --  record types
17035
17036             if Ada_Version < Ada_2005 then
17037                Check_Access_Discriminant_Requires_Limited
17038                  (Discr, Discriminant_Type (Discr));
17039             end if;
17040
17041             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
17042                Error_Msg_N
17043                  ("(Ada 83) access discriminant not allowed", Discr);
17044             end if;
17045
17046          elsif not Is_Discrete_Type (Discr_Type) then
17047             Error_Msg_N ("discriminants must have a discrete or access type",
17048               Discriminant_Type (Discr));
17049          end if;
17050
17051          Set_Etype (Defining_Identifier (Discr), Discr_Type);
17052
17053          --  If a discriminant specification includes the assignment compound
17054          --  delimiter followed by an expression, the expression is the default
17055          --  expression of the discriminant; the default expression must be of
17056          --  the type of the discriminant. (RM 3.7.1) Since this expression is
17057          --  a default expression, we do the special preanalysis, since this
17058          --  expression does not freeze (see "Handling of Default and Per-
17059          --  Object Expressions" in spec of package Sem).
17060
17061          if Present (Expression (Discr)) then
17062             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
17063
17064             if Nkind (N) = N_Formal_Type_Declaration then
17065                Error_Msg_N
17066                  ("discriminant defaults not allowed for formal type",
17067                   Expression (Discr));
17068
17069             --  Flag an error for a tagged type with defaulted discriminants,
17070             --  excluding limited tagged types when compiling for Ada 2012
17071             --  (see AI05-0214).
17072
17073             elsif Is_Tagged_Type (Current_Scope)
17074               and then (not Is_Limited_Type (Current_Scope)
17075                          or else Ada_Version < Ada_2012)
17076               and then Comes_From_Source (N)
17077             then
17078                --  Note: see similar test in Check_Or_Process_Discriminants, to
17079                --  handle the (illegal) case of the completion of an untagged
17080                --  view with discriminants with defaults by a tagged full view.
17081                --  We skip the check if Discr does not come from source, to
17082                --  account for the case of an untagged derived type providing
17083                --  defaults for a renamed discriminant from a private untagged
17084                --  ancestor with a tagged full view (ACATS B460006).
17085
17086                if Ada_Version >= Ada_2012 then
17087                   Error_Msg_N
17088                     ("discriminants of nonlimited tagged type cannot have"
17089                        & " defaults",
17090                      Expression (Discr));
17091                else
17092                   Error_Msg_N
17093                     ("discriminants of tagged type cannot have defaults",
17094                      Expression (Discr));
17095                end if;
17096
17097             else
17098                Default_Present := True;
17099                Append_Elmt (Expression (Discr), Elist);
17100
17101                --  Tag the defining identifiers for the discriminants with
17102                --  their corresponding default expressions from the tree.
17103
17104                Set_Discriminant_Default_Value
17105                  (Defining_Identifier (Discr), Expression (Discr));
17106             end if;
17107
17108          else
17109             Default_Not_Present := True;
17110          end if;
17111
17112          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
17113          --  Discr_Type but with the null-exclusion attribute
17114
17115          if Ada_Version >= Ada_2005 then
17116
17117             --  Ada 2005 (AI-231): Static checks
17118
17119             if Can_Never_Be_Null (Discr_Type) then
17120                Null_Exclusion_Static_Checks (Discr);
17121
17122             elsif Is_Access_Type (Discr_Type)
17123               and then Null_Exclusion_Present (Discr)
17124
17125                --  No need to check itypes because in their case this check
17126                --  was done at their point of creation
17127
17128               and then not Is_Itype (Discr_Type)
17129             then
17130                if Can_Never_Be_Null (Discr_Type) then
17131                   Error_Msg_NE
17132                     ("`NOT NULL` not allowed (& already excludes null)",
17133                      Discr,
17134                      Discr_Type);
17135                end if;
17136
17137                Set_Etype (Defining_Identifier (Discr),
17138                  Create_Null_Excluding_Itype
17139                    (T           => Discr_Type,
17140                     Related_Nod => Discr));
17141
17142             --  Check for improper null exclusion if the type is otherwise
17143             --  legal for a discriminant.
17144
17145             elsif Null_Exclusion_Present (Discr)
17146               and then Is_Discrete_Type (Discr_Type)
17147             then
17148                Error_Msg_N
17149                  ("null exclusion can only apply to an access type", Discr);
17150             end if;
17151
17152             --  Ada 2005 (AI-402): access discriminants of nonlimited types
17153             --  can't have defaults. Synchronized types, or types that are
17154             --  explicitly limited are fine, but special tests apply to derived
17155             --  types in generics: in a generic body we have to assume the
17156             --  worst, and therefore defaults are not allowed if the parent is
17157             --  a generic formal private type (see ACATS B370001).
17158
17159             if Is_Access_Type (Discr_Type) then
17160                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
17161                  or else not Default_Present
17162                  or else Is_Limited_Record (Current_Scope)
17163                  or else Is_Concurrent_Type (Current_Scope)
17164                  or else Is_Concurrent_Record_Type (Current_Scope)
17165                  or else Ekind (Current_Scope) = E_Limited_Private_Type
17166                then
17167                   if not Is_Derived_Type (Current_Scope)
17168                     or else not Is_Generic_Type (Etype (Current_Scope))
17169                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
17170                     or else Limited_Present
17171                               (Type_Definition (Parent (Current_Scope)))
17172                   then
17173                      null;
17174
17175                   else
17176                      Error_Msg_N ("access discriminants of nonlimited types",
17177                          Expression (Discr));
17178                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
17179                   end if;
17180
17181                elsif Present (Expression (Discr)) then
17182                   Error_Msg_N
17183                     ("(Ada 2005) access discriminants of nonlimited types",
17184                      Expression (Discr));
17185                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
17186                end if;
17187             end if;
17188          end if;
17189
17190          Next (Discr);
17191       end loop;
17192
17193       --  An element list consisting of the default expressions of the
17194       --  discriminants is constructed in the above loop and used to set
17195       --  the Discriminant_Constraint attribute for the type. If an object
17196       --  is declared of this (record or task) type without any explicit
17197       --  discriminant constraint given, this element list will form the
17198       --  actual parameters for the corresponding initialization procedure
17199       --  for the type.
17200
17201       Set_Discriminant_Constraint (Current_Scope, Elist);
17202       Set_Stored_Constraint (Current_Scope, No_Elist);
17203
17204       --  Default expressions must be provided either for all or for none
17205       --  of the discriminants of a discriminant part. (RM 3.7.1)
17206
17207       if Default_Present and then Default_Not_Present then
17208          Error_Msg_N
17209            ("incomplete specification of defaults for discriminants", N);
17210       end if;
17211
17212       --  The use of the name of a discriminant is not allowed in default
17213       --  expressions of a discriminant part if the specification of the
17214       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
17215
17216       --  To detect this, the discriminant names are entered initially with an
17217       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
17218       --  attempt to use a void entity (for example in an expression that is
17219       --  type-checked) produces the error message: premature usage. Now after
17220       --  completing the semantic analysis of the discriminant part, we can set
17221       --  the Ekind of all the discriminants appropriately.
17222
17223       Discr := First (Discriminant_Specifications (N));
17224       Discr_Number := Uint_1;
17225       while Present (Discr) loop
17226          Id := Defining_Identifier (Discr);
17227          Set_Ekind (Id, E_Discriminant);
17228          Init_Component_Location (Id);
17229          Init_Esize (Id);
17230          Set_Discriminant_Number (Id, Discr_Number);
17231
17232          --  Make sure this is always set, even in illegal programs
17233
17234          Set_Corresponding_Discriminant (Id, Empty);
17235
17236          --  Initialize the Original_Record_Component to the entity itself.
17237          --  Inherit_Components will propagate the right value to
17238          --  discriminants in derived record types.
17239
17240          Set_Original_Record_Component (Id, Id);
17241
17242          --  Create the discriminal for the discriminant
17243
17244          Build_Discriminal (Id);
17245
17246          Next (Discr);
17247          Discr_Number := Discr_Number + 1;
17248       end loop;
17249
17250       Set_Has_Discriminants (Current_Scope);
17251    end Process_Discriminants;
17252
17253    -----------------------
17254    -- Process_Full_View --
17255    -----------------------
17256
17257    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
17258       Priv_Parent : Entity_Id;
17259       Full_Parent : Entity_Id;
17260       Full_Indic  : Node_Id;
17261
17262       procedure Collect_Implemented_Interfaces
17263         (Typ    : Entity_Id;
17264          Ifaces : Elist_Id);
17265       --  Ada 2005: Gather all the interfaces that Typ directly or
17266       --  inherently implements. Duplicate entries are not added to
17267       --  the list Ifaces.
17268
17269       ------------------------------------
17270       -- Collect_Implemented_Interfaces --
17271       ------------------------------------
17272
17273       procedure Collect_Implemented_Interfaces
17274         (Typ    : Entity_Id;
17275          Ifaces : Elist_Id)
17276       is
17277          Iface      : Entity_Id;
17278          Iface_Elmt : Elmt_Id;
17279
17280       begin
17281          --  Abstract interfaces are only associated with tagged record types
17282
17283          if not Is_Tagged_Type (Typ)
17284            or else not Is_Record_Type (Typ)
17285          then
17286             return;
17287          end if;
17288
17289          --  Recursively climb to the ancestors
17290
17291          if Etype (Typ) /= Typ
17292
17293             --  Protect the frontend against wrong cyclic declarations like:
17294
17295             --     type B is new A with private;
17296             --     type C is new A with private;
17297             --  private
17298             --     type B is new C with null record;
17299             --     type C is new B with null record;
17300
17301            and then Etype (Typ) /= Priv_T
17302            and then Etype (Typ) /= Full_T
17303          then
17304             --  Keep separate the management of private type declarations
17305
17306             if Ekind (Typ) = E_Record_Type_With_Private then
17307
17308                --  Handle the following erroneous case:
17309                --      type Private_Type is tagged private;
17310                --   private
17311                --      type Private_Type is new Type_Implementing_Iface;
17312
17313                if Present (Full_View (Typ))
17314                  and then Etype (Typ) /= Full_View (Typ)
17315                then
17316                   if Is_Interface (Etype (Typ)) then
17317                      Append_Unique_Elmt (Etype (Typ), Ifaces);
17318                   end if;
17319
17320                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
17321                end if;
17322
17323             --  Non-private types
17324
17325             else
17326                if Is_Interface (Etype (Typ)) then
17327                   Append_Unique_Elmt (Etype (Typ), Ifaces);
17328                end if;
17329
17330                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
17331             end if;
17332          end if;
17333
17334          --  Handle entities in the list of abstract interfaces
17335
17336          if Present (Interfaces (Typ)) then
17337             Iface_Elmt := First_Elmt (Interfaces (Typ));
17338             while Present (Iface_Elmt) loop
17339                Iface := Node (Iface_Elmt);
17340
17341                pragma Assert (Is_Interface (Iface));
17342
17343                if not Contain_Interface (Iface, Ifaces) then
17344                   Append_Elmt (Iface, Ifaces);
17345                   Collect_Implemented_Interfaces (Iface, Ifaces);
17346                end if;
17347
17348                Next_Elmt (Iface_Elmt);
17349             end loop;
17350          end if;
17351       end Collect_Implemented_Interfaces;
17352
17353    --  Start of processing for Process_Full_View
17354
17355    begin
17356       --  First some sanity checks that must be done after semantic
17357       --  decoration of the full view and thus cannot be placed with other
17358       --  similar checks in Find_Type_Name
17359
17360       if not Is_Limited_Type (Priv_T)
17361         and then (Is_Limited_Type (Full_T)
17362                    or else Is_Limited_Composite (Full_T))
17363       then
17364          Error_Msg_N
17365            ("completion of nonlimited type cannot be limited", Full_T);
17366          Explain_Limited_Type (Full_T, Full_T);
17367
17368       elsif Is_Abstract_Type (Full_T)
17369         and then not Is_Abstract_Type (Priv_T)
17370       then
17371          Error_Msg_N
17372            ("completion of nonabstract type cannot be abstract", Full_T);
17373
17374       elsif Is_Tagged_Type (Priv_T)
17375         and then Is_Limited_Type (Priv_T)
17376         and then not Is_Limited_Type (Full_T)
17377       then
17378          --  If pragma CPP_Class was applied to the private declaration
17379          --  propagate the limitedness to the full-view
17380
17381          if Is_CPP_Class (Priv_T) then
17382             Set_Is_Limited_Record (Full_T);
17383
17384          --  GNAT allow its own definition of Limited_Controlled to disobey
17385          --  this rule in order in ease the implementation. This test is safe
17386          --  because Root_Controlled is defined in a child of System that
17387          --  normal programs are not supposed to use.
17388
17389          elsif Is_RTE (Etype (Full_T), RE_Root_Controlled) then
17390             Set_Is_Limited_Composite (Full_T);
17391          else
17392             Error_Msg_N
17393               ("completion of limited tagged type must be limited", Full_T);
17394          end if;
17395
17396       elsif Is_Generic_Type (Priv_T) then
17397          Error_Msg_N ("generic type cannot have a completion", Full_T);
17398       end if;
17399
17400       --  Check that ancestor interfaces of private and full views are
17401       --  consistent. We omit this check for synchronized types because
17402       --  they are performed on the corresponding record type when frozen.
17403
17404       if Ada_Version >= Ada_2005
17405         and then Is_Tagged_Type (Priv_T)
17406         and then Is_Tagged_Type (Full_T)
17407         and then not Is_Concurrent_Type (Full_T)
17408       then
17409          declare
17410             Iface         : Entity_Id;
17411             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
17412             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
17413
17414          begin
17415             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
17416             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
17417
17418             --  Ada 2005 (AI-251): The partial view shall be a descendant of
17419             --  an interface type if and only if the full type is descendant
17420             --  of the interface type (AARM 7.3 (7.3/2).
17421
17422             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
17423
17424             if Present (Iface) then
17425                Error_Msg_NE
17426                  ("interface & not implemented by full type " &
17427                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
17428             end if;
17429
17430             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
17431
17432             if Present (Iface) then
17433                Error_Msg_NE
17434                  ("interface & not implemented by partial view " &
17435                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
17436             end if;
17437          end;
17438       end if;
17439
17440       if Is_Tagged_Type (Priv_T)
17441         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17442         and then Is_Derived_Type (Full_T)
17443       then
17444          Priv_Parent := Etype (Priv_T);
17445
17446          --  The full view of a private extension may have been transformed
17447          --  into an unconstrained derived type declaration and a subtype
17448          --  declaration (see build_derived_record_type for details).
17449
17450          if Nkind (N) = N_Subtype_Declaration then
17451             Full_Indic  := Subtype_Indication (N);
17452             Full_Parent := Etype (Base_Type (Full_T));
17453          else
17454             Full_Indic  := Subtype_Indication (Type_Definition (N));
17455             Full_Parent := Etype (Full_T);
17456          end if;
17457
17458          --  Check that the parent type of the full type is a descendant of
17459          --  the ancestor subtype given in the private extension. If either
17460          --  entity has an Etype equal to Any_Type then we had some previous
17461          --  error situation [7.3(8)].
17462
17463          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
17464             return;
17465
17466          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
17467          --  any order. Therefore we don't have to check that its parent must
17468          --  be a descendant of the parent of the private type declaration.
17469
17470          elsif Is_Interface (Priv_Parent)
17471            and then Is_Interface (Full_Parent)
17472          then
17473             null;
17474
17475          --  Ada 2005 (AI-251): If the parent of the private type declaration
17476          --  is an interface there is no need to check that it is an ancestor
17477          --  of the associated full type declaration. The required tests for
17478          --  this case are performed by Build_Derived_Record_Type.
17479
17480          elsif not Is_Interface (Base_Type (Priv_Parent))
17481            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
17482          then
17483             Error_Msg_N
17484               ("parent of full type must descend from parent"
17485                   & " of private extension", Full_Indic);
17486
17487          --  First check a formal restriction, and then proceed with checking
17488          --  Ada rules. Since the formal restriction is not a serious error, we
17489          --  don't prevent further error detection for this check, hence the
17490          --  ELSE.
17491
17492          else
17493
17494             --  In formal mode, when completing a private extension the type
17495             --  named in the private part must be exactly the same as that
17496             --  named in the visible part.
17497
17498             if Priv_Parent /= Full_Parent then
17499                Error_Msg_Name_1 := Chars (Priv_Parent);
17500                Check_SPARK_Restriction ("% expected", Full_Indic);
17501             end if;
17502
17503             --  Check the rules of 7.3(10): if the private extension inherits
17504             --  known discriminants, then the full type must also inherit those
17505             --  discriminants from the same (ancestor) type, and the parent
17506             --  subtype of the full type must be constrained if and only if
17507             --  the ancestor subtype of the private extension is constrained.
17508
17509             if No (Discriminant_Specifications (Parent (Priv_T)))
17510               and then not Has_Unknown_Discriminants (Priv_T)
17511               and then Has_Discriminants (Base_Type (Priv_Parent))
17512             then
17513                declare
17514                   Priv_Indic  : constant Node_Id :=
17515                                   Subtype_Indication (Parent (Priv_T));
17516
17517                   Priv_Constr : constant Boolean :=
17518                                   Is_Constrained (Priv_Parent)
17519                                     or else
17520                                       Nkind (Priv_Indic) = N_Subtype_Indication
17521                                     or else
17522                                       Is_Constrained (Entity (Priv_Indic));
17523
17524                   Full_Constr : constant Boolean :=
17525                                   Is_Constrained (Full_Parent)
17526                                     or else
17527                                       Nkind (Full_Indic) = N_Subtype_Indication
17528                                     or else
17529                                       Is_Constrained (Entity (Full_Indic));
17530
17531                   Priv_Discr : Entity_Id;
17532                   Full_Discr : Entity_Id;
17533
17534                begin
17535                   Priv_Discr := First_Discriminant (Priv_Parent);
17536                   Full_Discr := First_Discriminant (Full_Parent);
17537                   while Present (Priv_Discr) and then Present (Full_Discr) loop
17538                      if Original_Record_Component (Priv_Discr) =
17539                         Original_Record_Component (Full_Discr)
17540                        or else
17541                          Corresponding_Discriminant (Priv_Discr) =
17542                          Corresponding_Discriminant (Full_Discr)
17543                      then
17544                         null;
17545                      else
17546                         exit;
17547                      end if;
17548
17549                      Next_Discriminant (Priv_Discr);
17550                      Next_Discriminant (Full_Discr);
17551                   end loop;
17552
17553                   if Present (Priv_Discr) or else Present (Full_Discr) then
17554                      Error_Msg_N
17555                        ("full view must inherit discriminants of the parent"
17556                         & " type used in the private extension", Full_Indic);
17557
17558                   elsif Priv_Constr and then not Full_Constr then
17559                      Error_Msg_N
17560                        ("parent subtype of full type must be constrained",
17561                         Full_Indic);
17562
17563                   elsif Full_Constr and then not Priv_Constr then
17564                      Error_Msg_N
17565                        ("parent subtype of full type must be unconstrained",
17566                         Full_Indic);
17567                   end if;
17568                end;
17569
17570                --  Check the rules of 7.3(12): if a partial view has neither
17571                --  known or unknown discriminants, then the full type
17572                --  declaration shall define a definite subtype.
17573
17574             elsif      not Has_Unknown_Discriminants (Priv_T)
17575               and then not Has_Discriminants (Priv_T)
17576               and then not Is_Constrained (Full_T)
17577             then
17578                Error_Msg_N
17579                  ("full view must define a constrained type if partial view"
17580                   & " has no discriminants", Full_T);
17581             end if;
17582
17583             --  ??????? Do we implement the following properly ?????
17584             --  If the ancestor subtype of a private extension has constrained
17585             --  discriminants, then the parent subtype of the full view shall
17586             --  impose a statically matching constraint on those discriminants
17587             --  [7.3(13)].
17588          end if;
17589
17590       else
17591          --  For untagged types, verify that a type without discriminants
17592          --  is not completed with an unconstrained type.
17593
17594          if not Is_Indefinite_Subtype (Priv_T)
17595            and then Is_Indefinite_Subtype (Full_T)
17596          then
17597             Error_Msg_N ("full view of type must be definite subtype", Full_T);
17598          end if;
17599       end if;
17600
17601       --  AI-419: verify that the use of "limited" is consistent
17602
17603       declare
17604          Orig_Decl : constant Node_Id := Original_Node (N);
17605
17606       begin
17607          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17608            and then not Limited_Present (Parent (Priv_T))
17609            and then not Synchronized_Present (Parent (Priv_T))
17610            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
17611            and then Nkind
17612              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
17613            and then Limited_Present (Type_Definition (Orig_Decl))
17614          then
17615             Error_Msg_N
17616               ("full view of non-limited extension cannot be limited", N);
17617          end if;
17618       end;
17619
17620       --  Ada 2005 (AI-443): A synchronized private extension must be
17621       --  completed by a task or protected type.
17622
17623       if Ada_Version >= Ada_2005
17624         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
17625         and then Synchronized_Present (Parent (Priv_T))
17626         and then not Is_Concurrent_Type (Full_T)
17627       then
17628          Error_Msg_N ("full view of synchronized extension must " &
17629                       "be synchronized type", N);
17630       end if;
17631
17632       --  Ada 2005 AI-363: if the full view has discriminants with
17633       --  defaults, it is illegal to declare constrained access subtypes
17634       --  whose designated type is the current type. This allows objects
17635       --  of the type that are declared in the heap to be unconstrained.
17636
17637       if not Has_Unknown_Discriminants (Priv_T)
17638         and then not Has_Discriminants (Priv_T)
17639         and then Has_Discriminants (Full_T)
17640         and then
17641           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
17642       then
17643          Set_Has_Constrained_Partial_View (Full_T);
17644          Set_Has_Constrained_Partial_View (Priv_T);
17645       end if;
17646
17647       --  Create a full declaration for all its subtypes recorded in
17648       --  Private_Dependents and swap them similarly to the base type. These
17649       --  are subtypes that have been define before the full declaration of
17650       --  the private type. We also swap the entry in Private_Dependents list
17651       --  so we can properly restore the private view on exit from the scope.
17652
17653       declare
17654          Priv_Elmt : Elmt_Id;
17655          Priv      : Entity_Id;
17656          Full      : Entity_Id;
17657
17658       begin
17659          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
17660          while Present (Priv_Elmt) loop
17661             Priv := Node (Priv_Elmt);
17662
17663             if Ekind_In (Priv, E_Private_Subtype,
17664                                E_Limited_Private_Subtype,
17665                                E_Record_Subtype_With_Private)
17666             then
17667                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
17668                Set_Is_Itype (Full);
17669                Set_Parent (Full, Parent (Priv));
17670                Set_Associated_Node_For_Itype (Full, N);
17671
17672                --  Now we need to complete the private subtype, but since the
17673                --  base type has already been swapped, we must also swap the
17674                --  subtypes (and thus, reverse the arguments in the call to
17675                --  Complete_Private_Subtype).
17676
17677                Copy_And_Swap (Priv, Full);
17678                Complete_Private_Subtype (Full, Priv, Full_T, N);
17679                Replace_Elmt (Priv_Elmt, Full);
17680             end if;
17681
17682             Next_Elmt (Priv_Elmt);
17683          end loop;
17684       end;
17685
17686       --  If the private view was tagged, copy the new primitive operations
17687       --  from the private view to the full view.
17688
17689       if Is_Tagged_Type (Full_T) then
17690          declare
17691             Disp_Typ  : Entity_Id;
17692             Full_List : Elist_Id;
17693             Prim      : Entity_Id;
17694             Prim_Elmt : Elmt_Id;
17695             Priv_List : Elist_Id;
17696
17697             function Contains
17698               (E : Entity_Id;
17699                L : Elist_Id) return Boolean;
17700             --  Determine whether list L contains element E
17701
17702             --------------
17703             -- Contains --
17704             --------------
17705
17706             function Contains
17707               (E : Entity_Id;
17708                L : Elist_Id) return Boolean
17709             is
17710                List_Elmt : Elmt_Id;
17711
17712             begin
17713                List_Elmt := First_Elmt (L);
17714                while Present (List_Elmt) loop
17715                   if Node (List_Elmt) = E then
17716                      return True;
17717                   end if;
17718
17719                   Next_Elmt (List_Elmt);
17720                end loop;
17721
17722                return False;
17723             end Contains;
17724
17725          --  Start of processing
17726
17727          begin
17728             if Is_Tagged_Type (Priv_T) then
17729                Priv_List := Primitive_Operations (Priv_T);
17730                Prim_Elmt := First_Elmt (Priv_List);
17731
17732                --  In the case of a concurrent type completing a private tagged
17733                --  type, primitives may have been declared in between the two
17734                --  views. These subprograms need to be wrapped the same way
17735                --  entries and protected procedures are handled because they
17736                --  cannot be directly shared by the two views.
17737
17738                if Is_Concurrent_Type (Full_T) then
17739                   declare
17740                      Conc_Typ  : constant Entity_Id :=
17741                                    Corresponding_Record_Type (Full_T);
17742                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
17743                      Wrap_Spec : Node_Id;
17744
17745                   begin
17746                      while Present (Prim_Elmt) loop
17747                         Prim := Node (Prim_Elmt);
17748
17749                         if Comes_From_Source (Prim)
17750                           and then not Is_Abstract_Subprogram (Prim)
17751                         then
17752                            Wrap_Spec :=
17753                              Make_Subprogram_Declaration (Sloc (Prim),
17754                                Specification =>
17755                                  Build_Wrapper_Spec
17756                                    (Subp_Id => Prim,
17757                                     Obj_Typ => Conc_Typ,
17758                                     Formals =>
17759                                       Parameter_Specifications (
17760                                         Parent (Prim))));
17761
17762                            Insert_After (Curr_Nod, Wrap_Spec);
17763                            Curr_Nod := Wrap_Spec;
17764
17765                            Analyze (Wrap_Spec);
17766                         end if;
17767
17768                         Next_Elmt (Prim_Elmt);
17769                      end loop;
17770
17771                      return;
17772                   end;
17773
17774                --  For non-concurrent types, transfer explicit primitives, but
17775                --  omit those inherited from the parent of the private view
17776                --  since they will be re-inherited later on.
17777
17778                else
17779                   Full_List := Primitive_Operations (Full_T);
17780
17781                   while Present (Prim_Elmt) loop
17782                      Prim := Node (Prim_Elmt);
17783
17784                      if Comes_From_Source (Prim)
17785                        and then not Contains (Prim, Full_List)
17786                      then
17787                         Append_Elmt (Prim, Full_List);
17788                      end if;
17789
17790                      Next_Elmt (Prim_Elmt);
17791                   end loop;
17792                end if;
17793
17794             --  Untagged private view
17795
17796             else
17797                Full_List := Primitive_Operations (Full_T);
17798
17799                --  In this case the partial view is untagged, so here we locate
17800                --  all of the earlier primitives that need to be treated as
17801                --  dispatching (those that appear between the two views). Note
17802                --  that these additional operations must all be new operations
17803                --  (any earlier operations that override inherited operations
17804                --  of the full view will already have been inserted in the
17805                --  primitives list, marked by Check_Operation_From_Private_View
17806                --  as dispatching. Note that implicit "/=" operators are
17807                --  excluded from being added to the primitives list since they
17808                --  shouldn't be treated as dispatching (tagged "/=" is handled
17809                --  specially).
17810
17811                Prim := Next_Entity (Full_T);
17812                while Present (Prim) and then Prim /= Priv_T loop
17813                   if Ekind_In (Prim, E_Procedure, E_Function) then
17814                      Disp_Typ := Find_Dispatching_Type (Prim);
17815
17816                      if Disp_Typ = Full_T
17817                        and then (Chars (Prim) /= Name_Op_Ne
17818                                   or else Comes_From_Source (Prim))
17819                      then
17820                         Check_Controlling_Formals (Full_T, Prim);
17821
17822                         if not Is_Dispatching_Operation (Prim) then
17823                            Append_Elmt (Prim, Full_List);
17824                            Set_Is_Dispatching_Operation (Prim, True);
17825                            Set_DT_Position (Prim, No_Uint);
17826                         end if;
17827
17828                      elsif Is_Dispatching_Operation (Prim)
17829                        and then Disp_Typ  /= Full_T
17830                      then
17831
17832                         --  Verify that it is not otherwise controlled by a
17833                         --  formal or a return value of type T.
17834
17835                         Check_Controlling_Formals (Disp_Typ, Prim);
17836                      end if;
17837                   end if;
17838
17839                   Next_Entity (Prim);
17840                end loop;
17841             end if;
17842
17843             --  For the tagged case, the two views can share the same primitive
17844             --  operations list and the same class-wide type. Update attributes
17845             --  of the class-wide type which depend on the full declaration.
17846
17847             if Is_Tagged_Type (Priv_T) then
17848                Set_Direct_Primitive_Operations (Priv_T, Full_List);
17849                Set_Class_Wide_Type
17850                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
17851
17852                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
17853             end if;
17854          end;
17855       end if;
17856
17857       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
17858
17859       if Known_To_Have_Preelab_Init (Priv_T) then
17860
17861          --  Case where there is a pragma Preelaborable_Initialization. We
17862          --  always allow this in predefined units, which is a bit of a kludge,
17863          --  but it means we don't have to struggle to meet the requirements in
17864          --  the RM for having Preelaborable Initialization. Otherwise we
17865          --  require that the type meets the RM rules. But we can't check that
17866          --  yet, because of the rule about overriding Initialize, so we simply
17867          --  set a flag that will be checked at freeze time.
17868
17869          if not In_Predefined_Unit (Full_T) then
17870             Set_Must_Have_Preelab_Init (Full_T);
17871          end if;
17872       end if;
17873
17874       --  If pragma CPP_Class was applied to the private type declaration,
17875       --  propagate it now to the full type declaration.
17876
17877       if Is_CPP_Class (Priv_T) then
17878          Set_Is_CPP_Class (Full_T);
17879          Set_Convention   (Full_T, Convention_CPP);
17880       end if;
17881
17882       --  If the private view has user specified stream attributes, then so has
17883       --  the full view.
17884
17885       --  Why the test, how could these flags be already set in Full_T ???
17886
17887       if Has_Specified_Stream_Read (Priv_T) then
17888          Set_Has_Specified_Stream_Read (Full_T);
17889       end if;
17890
17891       if Has_Specified_Stream_Write (Priv_T) then
17892          Set_Has_Specified_Stream_Write (Full_T);
17893       end if;
17894
17895       if Has_Specified_Stream_Input (Priv_T) then
17896          Set_Has_Specified_Stream_Input (Full_T);
17897       end if;
17898
17899       if Has_Specified_Stream_Output (Priv_T) then
17900          Set_Has_Specified_Stream_Output (Full_T);
17901       end if;
17902
17903       --  Propagate invariants to full type
17904
17905       if Has_Invariants (Priv_T) then
17906          Set_Has_Invariants (Full_T);
17907          Set_Invariant_Procedure (Full_T, Invariant_Procedure (Priv_T));
17908       end if;
17909
17910       if Has_Inheritable_Invariants (Priv_T) then
17911          Set_Has_Inheritable_Invariants (Full_T);
17912       end if;
17913
17914       --  Propagate predicates to full type
17915
17916       if Has_Predicates (Priv_T) then
17917          Set_Predicate_Function (Priv_T, Predicate_Function (Full_T));
17918          Set_Has_Predicates (Priv_T);
17919       end if;
17920    end Process_Full_View;
17921
17922    -----------------------------------
17923    -- Process_Incomplete_Dependents --
17924    -----------------------------------
17925
17926    procedure Process_Incomplete_Dependents
17927      (N      : Node_Id;
17928       Full_T : Entity_Id;
17929       Inc_T  : Entity_Id)
17930    is
17931       Inc_Elmt : Elmt_Id;
17932       Priv_Dep : Entity_Id;
17933       New_Subt : Entity_Id;
17934
17935       Disc_Constraint : Elist_Id;
17936
17937    begin
17938       if No (Private_Dependents (Inc_T)) then
17939          return;
17940       end if;
17941
17942       --  Itypes that may be generated by the completion of an incomplete
17943       --  subtype are not used by the back-end and not attached to the tree.
17944       --  They are created only for constraint-checking purposes.
17945
17946       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
17947       while Present (Inc_Elmt) loop
17948          Priv_Dep := Node (Inc_Elmt);
17949
17950          if Ekind (Priv_Dep) = E_Subprogram_Type then
17951
17952             --  An Access_To_Subprogram type may have a return type or a
17953             --  parameter type that is incomplete. Replace with the full view.
17954
17955             if Etype (Priv_Dep) = Inc_T then
17956                Set_Etype (Priv_Dep, Full_T);
17957             end if;
17958
17959             declare
17960                Formal : Entity_Id;
17961
17962             begin
17963                Formal := First_Formal (Priv_Dep);
17964                while Present (Formal) loop
17965                   if Etype (Formal) = Inc_T then
17966                      Set_Etype (Formal, Full_T);
17967                   end if;
17968
17969                   Next_Formal (Formal);
17970                end loop;
17971             end;
17972
17973          elsif Is_Overloadable (Priv_Dep) then
17974
17975             --  If a subprogram in the incomplete dependents list is primitive
17976             --  for a tagged full type then mark it as a dispatching operation,
17977             --  check whether it overrides an inherited subprogram, and check
17978             --  restrictions on its controlling formals. Note that a protected
17979             --  operation is never dispatching: only its wrapper operation
17980             --  (which has convention Ada) is.
17981
17982             if Is_Tagged_Type (Full_T)
17983               and then Is_Primitive (Priv_Dep)
17984               and then Convention (Priv_Dep) /= Convention_Protected
17985             then
17986                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
17987                Set_Is_Dispatching_Operation (Priv_Dep);
17988                Check_Controlling_Formals (Full_T, Priv_Dep);
17989             end if;
17990
17991          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
17992
17993             --  Can happen during processing of a body before the completion
17994             --  of a TA type. Ignore, because spec is also on dependent list.
17995
17996             return;
17997
17998          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
17999          --  corresponding subtype of the full view.
18000
18001          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
18002             Set_Subtype_Indication
18003               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
18004             Set_Etype (Priv_Dep, Full_T);
18005             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
18006             Set_Analyzed (Parent (Priv_Dep), False);
18007
18008             --  Reanalyze the declaration, suppressing the call to
18009             --  Enter_Name to avoid duplicate names.
18010
18011             Analyze_Subtype_Declaration
18012               (N    => Parent (Priv_Dep),
18013                Skip => True);
18014
18015          --  Dependent is a subtype
18016
18017          else
18018             --  We build a new subtype indication using the full view of the
18019             --  incomplete parent. The discriminant constraints have been
18020             --  elaborated already at the point of the subtype declaration.
18021
18022             New_Subt := Create_Itype (E_Void, N);
18023
18024             if Has_Discriminants (Full_T) then
18025                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
18026             else
18027                Disc_Constraint := No_Elist;
18028             end if;
18029
18030             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
18031             Set_Full_View (Priv_Dep, New_Subt);
18032          end if;
18033
18034          Next_Elmt (Inc_Elmt);
18035       end loop;
18036    end Process_Incomplete_Dependents;
18037
18038    --------------------------------
18039    -- Process_Range_Expr_In_Decl --
18040    --------------------------------
18041
18042    procedure Process_Range_Expr_In_Decl
18043      (R            : Node_Id;
18044       T            : Entity_Id;
18045       Check_List   : List_Id := Empty_List;
18046       R_Check_Off  : Boolean := False;
18047       In_Iter_Schm : Boolean := False)
18048    is
18049       Lo, Hi      : Node_Id;
18050       R_Checks    : Check_Result;
18051       Insert_Node : Node_Id;
18052       Def_Id      : Entity_Id;
18053
18054    begin
18055       Analyze_And_Resolve (R, Base_Type (T));
18056
18057       if Nkind (R) = N_Range then
18058
18059          --  In SPARK, all ranges should be static, with the exception of the
18060          --  discrete type definition of a loop parameter specification.
18061
18062          if not In_Iter_Schm
18063            and then not Is_Static_Range (R)
18064          then
18065             Check_SPARK_Restriction ("range should be static", R);
18066          end if;
18067
18068          Lo := Low_Bound (R);
18069          Hi := High_Bound (R);
18070
18071          --  We need to ensure validity of the bounds here, because if we
18072          --  go ahead and do the expansion, then the expanded code will get
18073          --  analyzed with range checks suppressed and we miss the check.
18074
18075          Validity_Check_Range (R);
18076
18077          --  If there were errors in the declaration, try and patch up some
18078          --  common mistakes in the bounds. The cases handled are literals
18079          --  which are Integer where the expected type is Real and vice versa.
18080          --  These corrections allow the compilation process to proceed further
18081          --  along since some basic assumptions of the format of the bounds
18082          --  are guaranteed.
18083
18084          if Etype (R) = Any_Type then
18085
18086             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
18087                Rewrite (Lo,
18088                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
18089
18090             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
18091                Rewrite (Hi,
18092                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
18093
18094             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
18095                Rewrite (Lo,
18096                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
18097
18098             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
18099                Rewrite (Hi,
18100                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
18101             end if;
18102
18103             Set_Etype (Lo, T);
18104             Set_Etype (Hi, T);
18105          end if;
18106
18107          --  If the bounds of the range have been mistakenly given as string
18108          --  literals (perhaps in place of character literals), then an error
18109          --  has already been reported, but we rewrite the string literal as a
18110          --  bound of the range's type to avoid blowups in later processing
18111          --  that looks at static values.
18112
18113          if Nkind (Lo) = N_String_Literal then
18114             Rewrite (Lo,
18115               Make_Attribute_Reference (Sloc (Lo),
18116                 Attribute_Name => Name_First,
18117                 Prefix => New_Reference_To (T, Sloc (Lo))));
18118             Analyze_And_Resolve (Lo);
18119          end if;
18120
18121          if Nkind (Hi) = N_String_Literal then
18122             Rewrite (Hi,
18123               Make_Attribute_Reference (Sloc (Hi),
18124                 Attribute_Name => Name_First,
18125                 Prefix => New_Reference_To (T, Sloc (Hi))));
18126             Analyze_And_Resolve (Hi);
18127          end if;
18128
18129          --  If bounds aren't scalar at this point then exit, avoiding
18130          --  problems with further processing of the range in this procedure.
18131
18132          if not Is_Scalar_Type (Etype (Lo)) then
18133             return;
18134          end if;
18135
18136          --  Resolve (actually Sem_Eval) has checked that the bounds are in
18137          --  then range of the base type. Here we check whether the bounds
18138          --  are in the range of the subtype itself. Note that if the bounds
18139          --  represent the null range the Constraint_Error exception should
18140          --  not be raised.
18141
18142          --  ??? The following code should be cleaned up as follows
18143
18144          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
18145          --     is done in the call to Range_Check (R, T); below
18146
18147          --  2. The use of R_Check_Off should be investigated and possibly
18148          --     removed, this would clean up things a bit.
18149
18150          if Is_Null_Range (Lo, Hi) then
18151             null;
18152
18153          else
18154             --  Capture values of bounds and generate temporaries for them
18155             --  if needed, before applying checks, since checks may cause
18156             --  duplication of the expression without forcing evaluation.
18157
18158             if Expander_Active then
18159                Force_Evaluation (Lo);
18160                Force_Evaluation (Hi);
18161             end if;
18162
18163             --  We use a flag here instead of suppressing checks on the
18164             --  type because the type we check against isn't necessarily
18165             --  the place where we put the check.
18166
18167             if not R_Check_Off then
18168                R_Checks := Get_Range_Checks (R, T);
18169
18170                --  Look up tree to find an appropriate insertion point. We
18171                --  can't just use insert_actions because later processing
18172                --  depends on the insertion node. Prior to Ada2012 the
18173                --  insertion point could only be a declaration or a loop, but
18174                --  quantified expressions can appear within any context in an
18175                --  expression, and the insertion point can be any statement,
18176                --  pragma, or declaration.
18177
18178                Insert_Node := Parent (R);
18179                while Present (Insert_Node) loop
18180                   exit when
18181                     Nkind (Insert_Node) in N_Declaration
18182                     and then
18183                       not Nkind_In
18184                         (Insert_Node, N_Component_Declaration,
18185                                       N_Loop_Parameter_Specification,
18186                                       N_Function_Specification,
18187                                       N_Procedure_Specification);
18188
18189                   exit when Nkind (Insert_Node) in N_Later_Decl_Item
18190                     or else Nkind (Insert_Node) in
18191                               N_Statement_Other_Than_Procedure_Call
18192                     or else Nkind_In (Insert_Node, N_Procedure_Call_Statement,
18193                                                    N_Pragma);
18194
18195                   Insert_Node := Parent (Insert_Node);
18196                end loop;
18197
18198                --  Why would Type_Decl not be present???  Without this test,
18199                --  short regression tests fail.
18200
18201                if Present (Insert_Node) then
18202
18203                   --  Case of loop statement. Verify that the range is part
18204                   --  of the subtype indication of the iteration scheme.
18205
18206                   if Nkind (Insert_Node) = N_Loop_Statement then
18207                      declare
18208                         Indic : Node_Id;
18209
18210                      begin
18211                         Indic := Parent (R);
18212                         while Present (Indic)
18213                           and then Nkind (Indic) /= N_Subtype_Indication
18214                         loop
18215                            Indic := Parent (Indic);
18216                         end loop;
18217
18218                         if Present (Indic) then
18219                            Def_Id := Etype (Subtype_Mark (Indic));
18220
18221                            Insert_Range_Checks
18222                              (R_Checks,
18223                               Insert_Node,
18224                               Def_Id,
18225                               Sloc (Insert_Node),
18226                               R,
18227                               Do_Before => True);
18228                         end if;
18229                      end;
18230
18231                   --  Insertion before a declaration. If the declaration
18232                   --  includes discriminants, the list of applicable checks
18233                   --  is given by the caller.
18234
18235                   elsif Nkind (Insert_Node) in N_Declaration then
18236                      Def_Id := Defining_Identifier (Insert_Node);
18237
18238                      if (Ekind (Def_Id) = E_Record_Type
18239                           and then Depends_On_Discriminant (R))
18240                        or else
18241                         (Ekind (Def_Id) = E_Protected_Type
18242                           and then Has_Discriminants (Def_Id))
18243                      then
18244                         Append_Range_Checks
18245                           (R_Checks,
18246                             Check_List, Def_Id, Sloc (Insert_Node), R);
18247
18248                      else
18249                         Insert_Range_Checks
18250                           (R_Checks,
18251                             Insert_Node, Def_Id, Sloc (Insert_Node), R);
18252
18253                      end if;
18254
18255                   --  Insertion before a statement. Range appears in the
18256                   --  context of a quantified expression. Insertion will
18257                   --  take place when expression is expanded.
18258
18259                   else
18260                      null;
18261                   end if;
18262                end if;
18263             end if;
18264          end if;
18265
18266       --  Case of other than an explicit N_Range node
18267
18268       elsif Expander_Active then
18269          Get_Index_Bounds (R, Lo, Hi);
18270          Force_Evaluation (Lo);
18271          Force_Evaluation (Hi);
18272       end if;
18273    end Process_Range_Expr_In_Decl;
18274
18275    --------------------------------------
18276    -- Process_Real_Range_Specification --
18277    --------------------------------------
18278
18279    procedure Process_Real_Range_Specification (Def : Node_Id) is
18280       Spec : constant Node_Id := Real_Range_Specification (Def);
18281       Lo   : Node_Id;
18282       Hi   : Node_Id;
18283       Err  : Boolean := False;
18284
18285       procedure Analyze_Bound (N : Node_Id);
18286       --  Analyze and check one bound
18287
18288       -------------------
18289       -- Analyze_Bound --
18290       -------------------
18291
18292       procedure Analyze_Bound (N : Node_Id) is
18293       begin
18294          Analyze_And_Resolve (N, Any_Real);
18295
18296          if not Is_OK_Static_Expression (N) then
18297             Flag_Non_Static_Expr
18298               ("bound in real type definition is not static!", N);
18299             Err := True;
18300          end if;
18301       end Analyze_Bound;
18302
18303    --  Start of processing for Process_Real_Range_Specification
18304
18305    begin
18306       if Present (Spec) then
18307          Lo := Low_Bound (Spec);
18308          Hi := High_Bound (Spec);
18309          Analyze_Bound (Lo);
18310          Analyze_Bound (Hi);
18311
18312          --  If error, clear away junk range specification
18313
18314          if Err then
18315             Set_Real_Range_Specification (Def, Empty);
18316          end if;
18317       end if;
18318    end Process_Real_Range_Specification;
18319
18320    ---------------------
18321    -- Process_Subtype --
18322    ---------------------
18323
18324    function Process_Subtype
18325      (S           : Node_Id;
18326       Related_Nod : Node_Id;
18327       Related_Id  : Entity_Id := Empty;
18328       Suffix      : Character := ' ') return Entity_Id
18329    is
18330       P               : Node_Id;
18331       Def_Id          : Entity_Id;
18332       Error_Node      : Node_Id;
18333       Full_View_Id    : Entity_Id;
18334       Subtype_Mark_Id : Entity_Id;
18335
18336       May_Have_Null_Exclusion : Boolean;
18337
18338       procedure Check_Incomplete (T : Entity_Id);
18339       --  Called to verify that an incomplete type is not used prematurely
18340
18341       ----------------------
18342       -- Check_Incomplete --
18343       ----------------------
18344
18345       procedure Check_Incomplete (T : Entity_Id) is
18346       begin
18347          --  Ada 2005 (AI-412): Incomplete subtypes are legal
18348
18349          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
18350            and then
18351              not (Ada_Version >= Ada_2005
18352                     and then
18353                        (Nkind (Parent (T)) = N_Subtype_Declaration
18354                           or else
18355                             (Nkind (Parent (T)) = N_Subtype_Indication
18356                                and then Nkind (Parent (Parent (T))) =
18357                                           N_Subtype_Declaration)))
18358          then
18359             Error_Msg_N ("invalid use of type before its full declaration", T);
18360          end if;
18361       end Check_Incomplete;
18362
18363    --  Start of processing for Process_Subtype
18364
18365    begin
18366       --  Case of no constraints present
18367
18368       if Nkind (S) /= N_Subtype_Indication then
18369          Find_Type (S);
18370          Check_Incomplete (S);
18371          P := Parent (S);
18372
18373          --  Ada 2005 (AI-231): Static check
18374
18375          if Ada_Version >= Ada_2005
18376            and then Present (P)
18377            and then Null_Exclusion_Present (P)
18378            and then Nkind (P) /= N_Access_To_Object_Definition
18379            and then not Is_Access_Type (Entity (S))
18380          then
18381             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
18382          end if;
18383
18384          --  The following is ugly, can't we have a range or even a flag???
18385
18386          May_Have_Null_Exclusion :=
18387            Nkind_In (P, N_Access_Definition,
18388                         N_Access_Function_Definition,
18389                         N_Access_Procedure_Definition,
18390                         N_Access_To_Object_Definition,
18391                         N_Allocator,
18392                         N_Component_Definition)
18393              or else
18394            Nkind_In (P, N_Derived_Type_Definition,
18395                         N_Discriminant_Specification,
18396                         N_Formal_Object_Declaration,
18397                         N_Object_Declaration,
18398                         N_Object_Renaming_Declaration,
18399                         N_Parameter_Specification,
18400                         N_Subtype_Declaration);
18401
18402          --  Create an Itype that is a duplicate of Entity (S) but with the
18403          --  null-exclusion attribute.
18404
18405          if May_Have_Null_Exclusion
18406            and then Is_Access_Type (Entity (S))
18407            and then Null_Exclusion_Present (P)
18408
18409             --  No need to check the case of an access to object definition.
18410             --  It is correct to define double not-null pointers.
18411
18412             --  Example:
18413             --     type Not_Null_Int_Ptr is not null access Integer;
18414             --     type Acc is not null access Not_Null_Int_Ptr;
18415
18416            and then Nkind (P) /= N_Access_To_Object_Definition
18417          then
18418             if Can_Never_Be_Null (Entity (S)) then
18419                case Nkind (Related_Nod) is
18420                   when N_Full_Type_Declaration =>
18421                      if Nkind (Type_Definition (Related_Nod))
18422                        in N_Array_Type_Definition
18423                      then
18424                         Error_Node :=
18425                           Subtype_Indication
18426                             (Component_Definition
18427                              (Type_Definition (Related_Nod)));
18428                      else
18429                         Error_Node :=
18430                           Subtype_Indication (Type_Definition (Related_Nod));
18431                      end if;
18432
18433                   when N_Subtype_Declaration =>
18434                      Error_Node := Subtype_Indication (Related_Nod);
18435
18436                   when N_Object_Declaration =>
18437                      Error_Node := Object_Definition (Related_Nod);
18438
18439                   when N_Component_Declaration =>
18440                      Error_Node :=
18441                        Subtype_Indication (Component_Definition (Related_Nod));
18442
18443                   when N_Allocator =>
18444                      Error_Node := Expression (Related_Nod);
18445
18446                   when others =>
18447                      pragma Assert (False);
18448                      Error_Node := Related_Nod;
18449                end case;
18450
18451                Error_Msg_NE
18452                  ("`NOT NULL` not allowed (& already excludes null)",
18453                   Error_Node,
18454                   Entity (S));
18455             end if;
18456
18457             Set_Etype  (S,
18458               Create_Null_Excluding_Itype
18459                 (T           => Entity (S),
18460                  Related_Nod => P));
18461             Set_Entity (S, Etype (S));
18462          end if;
18463
18464          return Entity (S);
18465
18466       --  Case of constraint present, so that we have an N_Subtype_Indication
18467       --  node (this node is created only if constraints are present).
18468
18469       else
18470          Find_Type (Subtype_Mark (S));
18471
18472          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
18473            and then not
18474             (Nkind (Parent (S)) = N_Subtype_Declaration
18475               and then Is_Itype (Defining_Identifier (Parent (S))))
18476          then
18477             Check_Incomplete (Subtype_Mark (S));
18478          end if;
18479
18480          P := Parent (S);
18481          Subtype_Mark_Id := Entity (Subtype_Mark (S));
18482
18483          --  Explicit subtype declaration case
18484
18485          if Nkind (P) = N_Subtype_Declaration then
18486             Def_Id := Defining_Identifier (P);
18487
18488          --  Explicit derived type definition case
18489
18490          elsif Nkind (P) = N_Derived_Type_Definition then
18491             Def_Id := Defining_Identifier (Parent (P));
18492
18493          --  Implicit case, the Def_Id must be created as an implicit type.
18494          --  The one exception arises in the case of concurrent types, array
18495          --  and access types, where other subsidiary implicit types may be
18496          --  created and must appear before the main implicit type. In these
18497          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
18498          --  has not yet been called to create Def_Id.
18499
18500          else
18501             if Is_Array_Type (Subtype_Mark_Id)
18502               or else Is_Concurrent_Type (Subtype_Mark_Id)
18503               or else Is_Access_Type (Subtype_Mark_Id)
18504             then
18505                Def_Id := Empty;
18506
18507             --  For the other cases, we create a new unattached Itype,
18508             --  and set the indication to ensure it gets attached later.
18509
18510             else
18511                Def_Id :=
18512                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
18513             end if;
18514          end if;
18515
18516          --  If the kind of constraint is invalid for this kind of type,
18517          --  then give an error, and then pretend no constraint was given.
18518
18519          if not Is_Valid_Constraint_Kind
18520                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
18521          then
18522             Error_Msg_N
18523               ("incorrect constraint for this kind of type", Constraint (S));
18524
18525             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
18526
18527             --  Set Ekind of orphan itype, to prevent cascaded errors
18528
18529             if Present (Def_Id) then
18530                Set_Ekind (Def_Id, Ekind (Any_Type));
18531             end if;
18532
18533             --  Make recursive call, having got rid of the bogus constraint
18534
18535             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
18536          end if;
18537
18538          --  Remaining processing depends on type
18539
18540          case Ekind (Subtype_Mark_Id) is
18541             when Access_Kind =>
18542                Constrain_Access (Def_Id, S, Related_Nod);
18543
18544                if Expander_Active
18545                  and then  Is_Itype (Designated_Type (Def_Id))
18546                  and then Nkind (Related_Nod) = N_Subtype_Declaration
18547                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
18548                then
18549                   Build_Itype_Reference
18550                     (Designated_Type (Def_Id), Related_Nod);
18551                end if;
18552
18553             when Array_Kind =>
18554                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
18555
18556             when Decimal_Fixed_Point_Kind =>
18557                Constrain_Decimal (Def_Id, S);
18558
18559             when Enumeration_Kind =>
18560                Constrain_Enumeration (Def_Id, S);
18561
18562             when Ordinary_Fixed_Point_Kind =>
18563                Constrain_Ordinary_Fixed (Def_Id, S);
18564
18565             when Float_Kind =>
18566                Constrain_Float (Def_Id, S);
18567
18568             when Integer_Kind =>
18569                Constrain_Integer (Def_Id, S);
18570
18571             when E_Record_Type     |
18572                  E_Record_Subtype  |
18573                  Class_Wide_Kind   |
18574                  E_Incomplete_Type =>
18575                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
18576
18577                if Ekind (Def_Id) = E_Incomplete_Type then
18578                   Set_Private_Dependents (Def_Id, New_Elmt_List);
18579                end if;
18580
18581             when Private_Kind =>
18582                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
18583                Set_Private_Dependents (Def_Id, New_Elmt_List);
18584
18585                --  In case of an invalid constraint prevent further processing
18586                --  since the type constructed is missing expected fields.
18587
18588                if Etype (Def_Id) = Any_Type then
18589                   return Def_Id;
18590                end if;
18591
18592                --  If the full view is that of a task with discriminants,
18593                --  we must constrain both the concurrent type and its
18594                --  corresponding record type. Otherwise we will just propagate
18595                --  the constraint to the full view, if available.
18596
18597                if Present (Full_View (Subtype_Mark_Id))
18598                  and then Has_Discriminants (Subtype_Mark_Id)
18599                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
18600                then
18601                   Full_View_Id :=
18602                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
18603
18604                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
18605                   Constrain_Concurrent (Full_View_Id, S,
18606                     Related_Nod, Related_Id, Suffix);
18607                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
18608                   Set_Full_View (Def_Id, Full_View_Id);
18609
18610                   --  Introduce an explicit reference to the private subtype,
18611                   --  to prevent scope anomalies in gigi if first use appears
18612                   --  in a nested context, e.g. a later function body.
18613                   --  Should this be generated in other contexts than a full
18614                   --  type declaration?
18615
18616                   if Is_Itype (Def_Id)
18617                     and then
18618                       Nkind (Parent (P)) = N_Full_Type_Declaration
18619                   then
18620                      Build_Itype_Reference (Def_Id, Parent (P));
18621                   end if;
18622
18623                else
18624                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
18625                end if;
18626
18627             when Concurrent_Kind  =>
18628                Constrain_Concurrent (Def_Id, S,
18629                  Related_Nod, Related_Id, Suffix);
18630
18631             when others =>
18632                Error_Msg_N ("invalid subtype mark in subtype indication", S);
18633          end case;
18634
18635          --  Size and Convention are always inherited from the base type
18636
18637          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
18638          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
18639
18640          return Def_Id;
18641       end if;
18642    end Process_Subtype;
18643
18644    ---------------------------------------
18645    -- Check_Anonymous_Access_Components --
18646    ---------------------------------------
18647
18648    procedure Check_Anonymous_Access_Components
18649       (Typ_Decl  : Node_Id;
18650        Typ       : Entity_Id;
18651        Prev      : Entity_Id;
18652        Comp_List : Node_Id)
18653    is
18654       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
18655       Anon_Access : Entity_Id;
18656       Acc_Def     : Node_Id;
18657       Comp        : Node_Id;
18658       Comp_Def    : Node_Id;
18659       Decl        : Node_Id;
18660       Type_Def    : Node_Id;
18661
18662       procedure Build_Incomplete_Type_Declaration;
18663       --  If the record type contains components that include an access to the
18664       --  current record, then create an incomplete type declaration for the
18665       --  record, to be used as the designated type of the anonymous access.
18666       --  This is done only once, and only if there is no previous partial
18667       --  view of the type.
18668
18669       function Designates_T (Subt : Node_Id) return Boolean;
18670       --  Check whether a node designates the enclosing record type, or 'Class
18671       --  of that type
18672
18673       function Mentions_T (Acc_Def : Node_Id) return Boolean;
18674       --  Check whether an access definition includes a reference to
18675       --  the enclosing record type. The reference can be a subtype mark
18676       --  in the access definition itself, a 'Class attribute reference, or
18677       --  recursively a reference appearing in a parameter specification
18678       --  or result definition of an access_to_subprogram definition.
18679
18680       --------------------------------------
18681       -- Build_Incomplete_Type_Declaration --
18682       --------------------------------------
18683
18684       procedure Build_Incomplete_Type_Declaration is
18685          Decl  : Node_Id;
18686          Inc_T : Entity_Id;
18687          H     : Entity_Id;
18688
18689          --  Is_Tagged indicates whether the type is tagged. It is tagged if
18690          --  it's "is new ... with record" or else "is tagged record ...".
18691
18692          Is_Tagged : constant Boolean :=
18693              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
18694                  and then
18695                    Present
18696                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
18697            or else
18698              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
18699                  and then Tagged_Present (Type_Definition (Typ_Decl)));
18700
18701       begin
18702          --  If there is a previous partial view, no need to create a new one
18703          --  If the partial view, given by Prev, is incomplete,  If Prev is
18704          --  a private declaration, full declaration is flagged accordingly.
18705
18706          if Prev /= Typ then
18707             if Is_Tagged then
18708                Make_Class_Wide_Type (Prev);
18709                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
18710                Set_Etype (Class_Wide_Type (Typ), Typ);
18711             end if;
18712
18713             return;
18714
18715          elsif Has_Private_Declaration (Typ) then
18716
18717             --  If we refer to T'Class inside T, and T is the completion of a
18718             --  private type, then we need to make sure the class-wide type
18719             --  exists.
18720
18721             if Is_Tagged then
18722                Make_Class_Wide_Type (Typ);
18723             end if;
18724
18725             return;
18726
18727          --  If there was a previous anonymous access type, the incomplete
18728          --  type declaration will have been created already.
18729
18730          elsif Present (Current_Entity (Typ))
18731            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
18732            and then Full_View (Current_Entity (Typ)) = Typ
18733          then
18734             if Is_Tagged
18735               and then Comes_From_Source (Current_Entity (Typ))
18736               and then not Is_Tagged_Type (Current_Entity (Typ))
18737             then
18738                Make_Class_Wide_Type (Typ);
18739                Error_Msg_N
18740                  ("incomplete view of tagged type should be declared tagged?",
18741                   Parent (Current_Entity (Typ)));
18742             end if;
18743             return;
18744
18745          else
18746             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
18747             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
18748
18749             --  Type has already been inserted into the current scope. Remove
18750             --  it, and add incomplete declaration for type, so that subsequent
18751             --  anonymous access types can use it. The entity is unchained from
18752             --  the homonym list and from immediate visibility. After analysis,
18753             --  the entity in the incomplete declaration becomes immediately
18754             --  visible in the record declaration that follows.
18755
18756             H := Current_Entity (Typ);
18757
18758             if H = Typ then
18759                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
18760             else
18761                while Present (H)
18762                  and then Homonym (H) /= Typ
18763                loop
18764                   H := Homonym (Typ);
18765                end loop;
18766
18767                Set_Homonym (H, Homonym (Typ));
18768             end if;
18769
18770             Insert_Before (Typ_Decl, Decl);
18771             Analyze (Decl);
18772             Set_Full_View (Inc_T, Typ);
18773
18774             if Is_Tagged then
18775
18776                --  Create a common class-wide type for both views, and set the
18777                --  Etype of the class-wide type to the full view.
18778
18779                Make_Class_Wide_Type (Inc_T);
18780                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
18781                Set_Etype (Class_Wide_Type (Typ), Typ);
18782             end if;
18783          end if;
18784       end Build_Incomplete_Type_Declaration;
18785
18786       ------------------
18787       -- Designates_T --
18788       ------------------
18789
18790       function Designates_T (Subt : Node_Id) return Boolean is
18791          Type_Id : constant Name_Id := Chars (Typ);
18792
18793          function Names_T (Nam : Node_Id) return Boolean;
18794          --  The record type has not been introduced in the current scope
18795          --  yet, so we must examine the name of the type itself, either
18796          --  an identifier T, or an expanded name of the form P.T, where
18797          --  P denotes the current scope.
18798
18799          -------------
18800          -- Names_T --
18801          -------------
18802
18803          function Names_T (Nam : Node_Id) return Boolean is
18804          begin
18805             if Nkind (Nam) = N_Identifier then
18806                return Chars (Nam) = Type_Id;
18807
18808             elsif Nkind (Nam) = N_Selected_Component then
18809                if Chars (Selector_Name (Nam)) = Type_Id then
18810                   if Nkind (Prefix (Nam)) = N_Identifier then
18811                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
18812
18813                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
18814                      return Chars (Selector_Name (Prefix (Nam))) =
18815                             Chars (Current_Scope);
18816                   else
18817                      return False;
18818                   end if;
18819
18820                else
18821                   return False;
18822                end if;
18823
18824             else
18825                return False;
18826             end if;
18827          end Names_T;
18828
18829       --  Start of processing for Designates_T
18830
18831       begin
18832          if Nkind (Subt) = N_Identifier then
18833             return Chars (Subt) = Type_Id;
18834
18835             --  Reference can be through an expanded name which has not been
18836             --  analyzed yet, and which designates enclosing scopes.
18837
18838          elsif Nkind (Subt) = N_Selected_Component then
18839             if Names_T (Subt) then
18840                return True;
18841
18842             --  Otherwise it must denote an entity that is already visible.
18843             --  The access definition may name a subtype of the enclosing
18844             --  type, if there is a previous incomplete declaration for it.
18845
18846             else
18847                Find_Selected_Component (Subt);
18848                return
18849                  Is_Entity_Name (Subt)
18850                    and then Scope (Entity (Subt)) = Current_Scope
18851                    and then
18852                      (Chars (Base_Type (Entity (Subt))) = Type_Id
18853                        or else
18854                          (Is_Class_Wide_Type (Entity (Subt))
18855                            and then
18856                            Chars (Etype (Base_Type (Entity (Subt)))) =
18857                                                                   Type_Id));
18858             end if;
18859
18860          --  A reference to the current type may appear as the prefix of
18861          --  a 'Class attribute.
18862
18863          elsif Nkind (Subt) = N_Attribute_Reference
18864            and then Attribute_Name (Subt) = Name_Class
18865          then
18866             return Names_T (Prefix (Subt));
18867
18868          else
18869             return False;
18870          end if;
18871       end Designates_T;
18872
18873       ----------------
18874       -- Mentions_T --
18875       ----------------
18876
18877       function Mentions_T (Acc_Def : Node_Id) return Boolean is
18878          Param_Spec : Node_Id;
18879
18880          Acc_Subprg : constant Node_Id :=
18881                         Access_To_Subprogram_Definition (Acc_Def);
18882
18883       begin
18884          if No (Acc_Subprg) then
18885             return Designates_T (Subtype_Mark (Acc_Def));
18886          end if;
18887
18888          --  Component is an access_to_subprogram: examine its formals,
18889          --  and result definition in the case of an access_to_function.
18890
18891          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
18892          while Present (Param_Spec) loop
18893             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
18894               and then Mentions_T (Parameter_Type (Param_Spec))
18895             then
18896                return True;
18897
18898             elsif Designates_T (Parameter_Type (Param_Spec)) then
18899                return True;
18900             end if;
18901
18902             Next (Param_Spec);
18903          end loop;
18904
18905          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
18906             if Nkind (Result_Definition (Acc_Subprg)) =
18907                  N_Access_Definition
18908             then
18909                return Mentions_T (Result_Definition (Acc_Subprg));
18910             else
18911                return Designates_T (Result_Definition (Acc_Subprg));
18912             end if;
18913          end if;
18914
18915          return False;
18916       end Mentions_T;
18917
18918    --  Start of processing for Check_Anonymous_Access_Components
18919
18920    begin
18921       if No (Comp_List) then
18922          return;
18923       end if;
18924
18925       Comp := First (Component_Items (Comp_List));
18926       while Present (Comp) loop
18927          if Nkind (Comp) = N_Component_Declaration
18928            and then Present
18929              (Access_Definition (Component_Definition (Comp)))
18930            and then
18931              Mentions_T (Access_Definition (Component_Definition (Comp)))
18932          then
18933             Comp_Def := Component_Definition (Comp);
18934             Acc_Def :=
18935               Access_To_Subprogram_Definition
18936                 (Access_Definition (Comp_Def));
18937
18938             Build_Incomplete_Type_Declaration;
18939             Anon_Access := Make_Temporary (Loc, 'S');
18940
18941             --  Create a declaration for the anonymous access type: either
18942             --  an access_to_object or an access_to_subprogram.
18943
18944             if Present (Acc_Def) then
18945                if Nkind (Acc_Def) = N_Access_Function_Definition then
18946                   Type_Def :=
18947                     Make_Access_Function_Definition (Loc,
18948                       Parameter_Specifications =>
18949                         Parameter_Specifications (Acc_Def),
18950                       Result_Definition => Result_Definition (Acc_Def));
18951                else
18952                   Type_Def :=
18953                     Make_Access_Procedure_Definition (Loc,
18954                       Parameter_Specifications =>
18955                         Parameter_Specifications (Acc_Def));
18956                end if;
18957
18958             else
18959                Type_Def :=
18960                  Make_Access_To_Object_Definition (Loc,
18961                    Subtype_Indication =>
18962                       Relocate_Node
18963                         (Subtype_Mark
18964                           (Access_Definition (Comp_Def))));
18965
18966                Set_Constant_Present
18967                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
18968                Set_All_Present
18969                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
18970             end if;
18971
18972             Set_Null_Exclusion_Present
18973               (Type_Def,
18974                Null_Exclusion_Present (Access_Definition (Comp_Def)));
18975
18976             Decl :=
18977               Make_Full_Type_Declaration (Loc,
18978                 Defining_Identifier => Anon_Access,
18979                 Type_Definition     => Type_Def);
18980
18981             Insert_Before (Typ_Decl, Decl);
18982             Analyze (Decl);
18983
18984             --  If an access to subprogram, create the extra formals
18985
18986             if Present (Acc_Def) then
18987                Create_Extra_Formals (Designated_Type (Anon_Access));
18988
18989             --  If an access to object, preserve entity of designated type,
18990             --  for ASIS use, before rewriting the component definition.
18991
18992             else
18993                declare
18994                   Desig : Entity_Id;
18995
18996                begin
18997                   Desig := Entity (Subtype_Indication (Type_Def));
18998
18999                   --  If the access definition is to the current  record,
19000                   --  the visible entity at this point is an  incomplete
19001                   --  type. Retrieve the full view to simplify  ASIS queries
19002
19003                   if Ekind (Desig) = E_Incomplete_Type then
19004                      Desig := Full_View (Desig);
19005                   end if;
19006
19007                   Set_Entity
19008                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
19009                end;
19010             end if;
19011
19012             Rewrite (Comp_Def,
19013               Make_Component_Definition (Loc,
19014                 Subtype_Indication =>
19015                New_Occurrence_Of (Anon_Access, Loc)));
19016
19017             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
19018                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
19019             else
19020                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
19021             end if;
19022
19023             Set_Is_Local_Anonymous_Access (Anon_Access);
19024          end if;
19025
19026          Next (Comp);
19027       end loop;
19028
19029       if Present (Variant_Part (Comp_List)) then
19030          declare
19031             V : Node_Id;
19032          begin
19033             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
19034             while Present (V) loop
19035                Check_Anonymous_Access_Components
19036                  (Typ_Decl, Typ, Prev, Component_List (V));
19037                Next_Non_Pragma (V);
19038             end loop;
19039          end;
19040       end if;
19041    end Check_Anonymous_Access_Components;
19042
19043    --------------------------------
19044    -- Preanalyze_Spec_Expression --
19045    --------------------------------
19046
19047    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
19048       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
19049    begin
19050       In_Spec_Expression := True;
19051       Preanalyze_And_Resolve (N, T);
19052       In_Spec_Expression := Save_In_Spec_Expression;
19053    end Preanalyze_Spec_Expression;
19054
19055    -----------------------------
19056    -- Record_Type_Declaration --
19057    -----------------------------
19058
19059    procedure Record_Type_Declaration
19060      (T    : Entity_Id;
19061       N    : Node_Id;
19062       Prev : Entity_Id)
19063    is
19064       Def       : constant Node_Id := Type_Definition (N);
19065       Is_Tagged : Boolean;
19066       Tag_Comp  : Entity_Id;
19067
19068    begin
19069       --  These flags must be initialized before calling Process_Discriminants
19070       --  because this routine makes use of them.
19071
19072       Set_Ekind             (T, E_Record_Type);
19073       Set_Etype             (T, T);
19074       Init_Size_Align       (T);
19075       Set_Interfaces        (T, No_Elist);
19076       Set_Stored_Constraint (T, No_Elist);
19077
19078       --  Normal case
19079
19080       if Ada_Version < Ada_2005
19081         or else not Interface_Present (Def)
19082       then
19083          if Limited_Present (Def) then
19084             Check_SPARK_Restriction ("limited is not allowed", N);
19085          end if;
19086
19087          if Abstract_Present (Def) then
19088             Check_SPARK_Restriction ("abstract is not allowed", N);
19089          end if;
19090
19091          --  The flag Is_Tagged_Type might have already been set by
19092          --  Find_Type_Name if it detected an error for declaration T. This
19093          --  arises in the case of private tagged types where the full view
19094          --  omits the word tagged.
19095
19096          Is_Tagged :=
19097            Tagged_Present (Def)
19098              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
19099
19100          Set_Is_Tagged_Type      (T, Is_Tagged);
19101          Set_Is_Limited_Record   (T, Limited_Present (Def));
19102
19103          --  Type is abstract if full declaration carries keyword, or if
19104          --  previous partial view did.
19105
19106          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
19107                                       or else Abstract_Present (Def));
19108
19109       else
19110          Check_SPARK_Restriction ("interface is not allowed", N);
19111
19112          Is_Tagged := True;
19113          Analyze_Interface_Declaration (T, Def);
19114
19115          if Present (Discriminant_Specifications (N)) then
19116             Error_Msg_N
19117               ("interface types cannot have discriminants",
19118                 Defining_Identifier
19119                   (First (Discriminant_Specifications (N))));
19120          end if;
19121       end if;
19122
19123       --  First pass: if there are self-referential access components,
19124       --  create the required anonymous access type declarations, and if
19125       --  need be an incomplete type declaration for T itself.
19126
19127       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
19128
19129       if Ada_Version >= Ada_2005
19130         and then Present (Interface_List (Def))
19131       then
19132          Check_Interfaces (N, Def);
19133
19134          declare
19135             Ifaces_List : Elist_Id;
19136
19137          begin
19138             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
19139             --  already in the parents.
19140
19141             Collect_Interfaces
19142               (T               => T,
19143                Ifaces_List     => Ifaces_List,
19144                Exclude_Parents => True);
19145
19146             Set_Interfaces (T, Ifaces_List);
19147          end;
19148       end if;
19149
19150       --  Records constitute a scope for the component declarations within.
19151       --  The scope is created prior to the processing of these declarations.
19152       --  Discriminants are processed first, so that they are visible when
19153       --  processing the other components. The Ekind of the record type itself
19154       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
19155
19156       --  Enter record scope
19157
19158       Push_Scope (T);
19159
19160       --  If an incomplete or private type declaration was already given for
19161       --  the type, then this scope already exists, and the discriminants have
19162       --  been declared within. We must verify that the full declaration
19163       --  matches the incomplete one.
19164
19165       Check_Or_Process_Discriminants (N, T, Prev);
19166
19167       Set_Is_Constrained     (T, not Has_Discriminants (T));
19168       Set_Has_Delayed_Freeze (T, True);
19169
19170       --  For tagged types add a manually analyzed component corresponding
19171       --  to the component _tag, the corresponding piece of tree will be
19172       --  expanded as part of the freezing actions if it is not a CPP_Class.
19173
19174       if Is_Tagged then
19175
19176          --  Do not add the tag unless we are in expansion mode
19177
19178          if Expander_Active then
19179             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
19180             Enter_Name (Tag_Comp);
19181
19182             Set_Ekind                     (Tag_Comp, E_Component);
19183             Set_Is_Tag                    (Tag_Comp);
19184             Set_Is_Aliased                (Tag_Comp);
19185             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
19186             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
19187             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
19188             Init_Component_Location       (Tag_Comp);
19189
19190             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
19191             --  implemented interfaces.
19192
19193             if Has_Interfaces (T) then
19194                Add_Interface_Tag_Components (N, T);
19195             end if;
19196          end if;
19197
19198          Make_Class_Wide_Type (T);
19199          Set_Direct_Primitive_Operations (T, New_Elmt_List);
19200       end if;
19201
19202       --  We must suppress range checks when processing record components in
19203       --  the presence of discriminants, since we don't want spurious checks to
19204       --  be generated during their analysis, but Suppress_Range_Checks flags
19205       --  must be reset the after processing the record definition.
19206
19207       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
19208       --  couldn't we just use the normal range check suppression method here.
19209       --  That would seem cleaner ???
19210
19211       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
19212          Set_Kill_Range_Checks (T, True);
19213          Record_Type_Definition (Def, Prev);
19214          Set_Kill_Range_Checks (T, False);
19215       else
19216          Record_Type_Definition (Def, Prev);
19217       end if;
19218
19219       --  Exit from record scope
19220
19221       End_Scope;
19222
19223       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
19224       --  the implemented interfaces and associate them an aliased entity.
19225
19226       if Is_Tagged
19227         and then not Is_Empty_List (Interface_List (Def))
19228       then
19229          Derive_Progenitor_Subprograms (T, T);
19230       end if;
19231    end Record_Type_Declaration;
19232
19233    ----------------------------
19234    -- Record_Type_Definition --
19235    ----------------------------
19236
19237    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
19238       Component          : Entity_Id;
19239       Ctrl_Components    : Boolean := False;
19240       Final_Storage_Only : Boolean;
19241       T                  : Entity_Id;
19242
19243    begin
19244       if Ekind (Prev_T) = E_Incomplete_Type then
19245          T := Full_View (Prev_T);
19246       else
19247          T := Prev_T;
19248       end if;
19249
19250       --  In SPARK, tagged types and type extensions may only be declared in
19251       --  the specification of library unit packages.
19252
19253       if Present (Def) and then Is_Tagged_Type (T) then
19254          declare
19255             Typ  : Node_Id;
19256             Ctxt : Node_Id;
19257
19258          begin
19259             if Nkind (Parent (Def)) = N_Full_Type_Declaration then
19260                Typ := Parent (Def);
19261             else
19262                pragma Assert
19263                  (Nkind (Parent (Def)) = N_Derived_Type_Definition);
19264                Typ := Parent (Parent (Def));
19265             end if;
19266
19267             Ctxt := Parent (Typ);
19268
19269             if Nkind (Ctxt) = N_Package_Body
19270               and then Nkind (Parent (Ctxt)) = N_Compilation_Unit
19271             then
19272                Check_SPARK_Restriction
19273                  ("type should be defined in package specification", Typ);
19274
19275             elsif Nkind (Ctxt) /= N_Package_Specification
19276               or else Nkind (Parent (Parent (Ctxt))) /= N_Compilation_Unit
19277             then
19278                Check_SPARK_Restriction
19279                  ("type should be defined in library unit package", Typ);
19280             end if;
19281          end;
19282       end if;
19283
19284       Final_Storage_Only := not Is_Controlled (T);
19285
19286       --  Ada 2005: check whether an explicit Limited is present in a derived
19287       --  type declaration.
19288
19289       if Nkind (Parent (Def)) = N_Derived_Type_Definition
19290         and then Limited_Present (Parent (Def))
19291       then
19292          Set_Is_Limited_Record (T);
19293       end if;
19294
19295       --  If the component list of a record type is defined by the reserved
19296       --  word null and there is no discriminant part, then the record type has
19297       --  no components and all records of the type are null records (RM 3.7)
19298       --  This procedure is also called to process the extension part of a
19299       --  record extension, in which case the current scope may have inherited
19300       --  components.
19301
19302       if No (Def)
19303         or else No (Component_List (Def))
19304         or else Null_Present (Component_List (Def))
19305       then
19306          if not Is_Tagged_Type (T) then
19307             Check_SPARK_Restriction ("non-tagged record cannot be null", Def);
19308          end if;
19309
19310       else
19311          Analyze_Declarations (Component_Items (Component_List (Def)));
19312
19313          if Present (Variant_Part (Component_List (Def))) then
19314             Check_SPARK_Restriction ("variant part is not allowed", Def);
19315             Analyze (Variant_Part (Component_List (Def)));
19316          end if;
19317       end if;
19318
19319       --  After completing the semantic analysis of the record definition,
19320       --  record components, both new and inherited, are accessible. Set their
19321       --  kind accordingly. Exclude malformed itypes from illegal declarations,
19322       --  whose Ekind may be void.
19323
19324       Component := First_Entity (Current_Scope);
19325       while Present (Component) loop
19326          if Ekind (Component) = E_Void
19327            and then not Is_Itype (Component)
19328          then
19329             Set_Ekind (Component, E_Component);
19330             Init_Component_Location (Component);
19331          end if;
19332
19333          if Has_Task (Etype (Component)) then
19334             Set_Has_Task (T);
19335          end if;
19336
19337          if Ekind (Component) /= E_Component then
19338             null;
19339
19340          --  Do not set Has_Controlled_Component on a class-wide equivalent
19341          --  type. See Make_CW_Equivalent_Type.
19342
19343          elsif not Is_Class_Wide_Equivalent_Type (T)
19344            and then (Has_Controlled_Component (Etype (Component))
19345                       or else (Chars (Component) /= Name_uParent
19346                                 and then Is_Controlled (Etype (Component))))
19347          then
19348             Set_Has_Controlled_Component (T, True);
19349             Final_Storage_Only :=
19350               Final_Storage_Only
19351                 and then Finalize_Storage_Only (Etype (Component));
19352             Ctrl_Components := True;
19353          end if;
19354
19355          Next_Entity (Component);
19356       end loop;
19357
19358       --  A Type is Finalize_Storage_Only only if all its controlled components
19359       --  are also.
19360
19361       if Ctrl_Components then
19362          Set_Finalize_Storage_Only (T, Final_Storage_Only);
19363       end if;
19364
19365       --  Place reference to end record on the proper entity, which may
19366       --  be a partial view.
19367
19368       if Present (Def) then
19369          Process_End_Label (Def, 'e', Prev_T);
19370       end if;
19371    end Record_Type_Definition;
19372
19373    ------------------------
19374    -- Replace_Components --
19375    ------------------------
19376
19377    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
19378       function Process (N : Node_Id) return Traverse_Result;
19379
19380       -------------
19381       -- Process --
19382       -------------
19383
19384       function Process (N : Node_Id) return Traverse_Result is
19385          Comp : Entity_Id;
19386
19387       begin
19388          if Nkind (N) = N_Discriminant_Specification then
19389             Comp := First_Discriminant (Typ);
19390             while Present (Comp) loop
19391                if Chars (Comp) = Chars (Defining_Identifier (N)) then
19392                   Set_Defining_Identifier (N, Comp);
19393                   exit;
19394                end if;
19395
19396                Next_Discriminant (Comp);
19397             end loop;
19398
19399          elsif Nkind (N) = N_Component_Declaration then
19400             Comp := First_Component (Typ);
19401             while Present (Comp) loop
19402                if Chars (Comp) = Chars (Defining_Identifier (N)) then
19403                   Set_Defining_Identifier (N, Comp);
19404                   exit;
19405                end if;
19406
19407                Next_Component (Comp);
19408             end loop;
19409          end if;
19410
19411          return OK;
19412       end Process;
19413
19414       procedure Replace is new Traverse_Proc (Process);
19415
19416    --  Start of processing for Replace_Components
19417
19418    begin
19419       Replace (Decl);
19420    end Replace_Components;
19421
19422    -------------------------------
19423    -- Set_Completion_Referenced --
19424    -------------------------------
19425
19426    procedure Set_Completion_Referenced (E : Entity_Id) is
19427    begin
19428       --  If in main unit, mark entity that is a completion as referenced,
19429       --  warnings go on the partial view when needed.
19430
19431       if In_Extended_Main_Source_Unit (E) then
19432          Set_Referenced (E);
19433       end if;
19434    end Set_Completion_Referenced;
19435
19436    ---------------------
19437    -- Set_Fixed_Range --
19438    ---------------------
19439
19440    --  The range for fixed-point types is complicated by the fact that we
19441    --  do not know the exact end points at the time of the declaration. This
19442    --  is true for three reasons:
19443
19444    --     A size clause may affect the fudging of the end-points
19445    --     A small clause may affect the values of the end-points
19446    --     We try to include the end-points if it does not affect the size
19447
19448    --  This means that the actual end-points must be established at the point
19449    --  when the type is frozen. Meanwhile, we first narrow the range as
19450    --  permitted (so that it will fit if necessary in a small specified size),
19451    --  and then build a range subtree with these narrowed bounds.
19452
19453    --  Set_Fixed_Range constructs the range from real literal values, and sets
19454    --  the range as the Scalar_Range of the given fixed-point type entity.
19455
19456    --  The parent of this range is set to point to the entity so that it is
19457    --  properly hooked into the tree (unlike normal Scalar_Range entries for
19458    --  other scalar types, which are just pointers to the range in the
19459    --  original tree, this would otherwise be an orphan).
19460
19461    --  The tree is left unanalyzed. When the type is frozen, the processing
19462    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
19463    --  analyzed, and uses this as an indication that it should complete
19464    --  work on the range (it will know the final small and size values).
19465
19466    procedure Set_Fixed_Range
19467      (E   : Entity_Id;
19468       Loc : Source_Ptr;
19469       Lo  : Ureal;
19470       Hi  : Ureal)
19471    is
19472       S : constant Node_Id :=
19473             Make_Range (Loc,
19474               Low_Bound  => Make_Real_Literal (Loc, Lo),
19475               High_Bound => Make_Real_Literal (Loc, Hi));
19476    begin
19477       Set_Scalar_Range (E, S);
19478       Set_Parent (S, E);
19479    end Set_Fixed_Range;
19480
19481    ----------------------------------
19482    -- Set_Scalar_Range_For_Subtype --
19483    ----------------------------------
19484
19485    procedure Set_Scalar_Range_For_Subtype
19486      (Def_Id : Entity_Id;
19487       R      : Node_Id;
19488       Subt   : Entity_Id)
19489    is
19490       Kind : constant Entity_Kind :=  Ekind (Def_Id);
19491
19492    begin
19493       --  Defend against previous error
19494
19495       if Nkind (R) = N_Error then
19496          return;
19497       end if;
19498
19499       Set_Scalar_Range (Def_Id, R);
19500
19501       --  We need to link the range into the tree before resolving it so
19502       --  that types that are referenced, including importantly the subtype
19503       --  itself, are properly frozen (Freeze_Expression requires that the
19504       --  expression be properly linked into the tree). Of course if it is
19505       --  already linked in, then we do not disturb the current link.
19506
19507       if No (Parent (R)) then
19508          Set_Parent (R, Def_Id);
19509       end if;
19510
19511       --  Reset the kind of the subtype during analysis of the range, to
19512       --  catch possible premature use in the bounds themselves.
19513
19514       Set_Ekind (Def_Id, E_Void);
19515       Process_Range_Expr_In_Decl (R, Subt);
19516       Set_Ekind (Def_Id, Kind);
19517    end Set_Scalar_Range_For_Subtype;
19518
19519    --------------------------------------------------------
19520    -- Set_Stored_Constraint_From_Discriminant_Constraint --
19521    --------------------------------------------------------
19522
19523    procedure Set_Stored_Constraint_From_Discriminant_Constraint
19524      (E : Entity_Id)
19525    is
19526    begin
19527       --  Make sure set if encountered during Expand_To_Stored_Constraint
19528
19529       Set_Stored_Constraint (E, No_Elist);
19530
19531       --  Give it the right value
19532
19533       if Is_Constrained (E) and then Has_Discriminants (E) then
19534          Set_Stored_Constraint (E,
19535            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
19536       end if;
19537    end Set_Stored_Constraint_From_Discriminant_Constraint;
19538
19539    -------------------------------------
19540    -- Signed_Integer_Type_Declaration --
19541    -------------------------------------
19542
19543    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
19544       Implicit_Base : Entity_Id;
19545       Base_Typ      : Entity_Id;
19546       Lo_Val        : Uint;
19547       Hi_Val        : Uint;
19548       Errs          : Boolean := False;
19549       Lo            : Node_Id;
19550       Hi            : Node_Id;
19551
19552       function Can_Derive_From (E : Entity_Id) return Boolean;
19553       --  Determine whether given bounds allow derivation from specified type
19554
19555       procedure Check_Bound (Expr : Node_Id);
19556       --  Check bound to make sure it is integral and static. If not, post
19557       --  appropriate error message and set Errs flag
19558
19559       ---------------------
19560       -- Can_Derive_From --
19561       ---------------------
19562
19563       --  Note we check both bounds against both end values, to deal with
19564       --  strange types like ones with a range of 0 .. -12341234.
19565
19566       function Can_Derive_From (E : Entity_Id) return Boolean is
19567          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
19568          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
19569       begin
19570          return Lo <= Lo_Val and then Lo_Val <= Hi
19571                   and then
19572                 Lo <= Hi_Val and then Hi_Val <= Hi;
19573       end Can_Derive_From;
19574
19575       -----------------
19576       -- Check_Bound --
19577       -----------------
19578
19579       procedure Check_Bound (Expr : Node_Id) is
19580       begin
19581          --  If a range constraint is used as an integer type definition, each
19582          --  bound of the range must be defined by a static expression of some
19583          --  integer type, but the two bounds need not have the same integer
19584          --  type (Negative bounds are allowed.) (RM 3.5.4)
19585
19586          if not Is_Integer_Type (Etype (Expr)) then
19587             Error_Msg_N
19588               ("integer type definition bounds must be of integer type", Expr);
19589             Errs := True;
19590
19591          elsif not Is_OK_Static_Expression (Expr) then
19592             Flag_Non_Static_Expr
19593               ("non-static expression used for integer type bound!", Expr);
19594             Errs := True;
19595
19596          --  The bounds are folded into literals, and we set their type to be
19597          --  universal, to avoid typing difficulties: we cannot set the type
19598          --  of the literal to the new type, because this would be a forward
19599          --  reference for the back end,  and if the original type is user-
19600          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
19601
19602          else
19603             if Is_Entity_Name (Expr) then
19604                Fold_Uint (Expr, Expr_Value (Expr), True);
19605             end if;
19606
19607             Set_Etype (Expr, Universal_Integer);
19608          end if;
19609       end Check_Bound;
19610
19611    --  Start of processing for Signed_Integer_Type_Declaration
19612
19613    begin
19614       --  Create an anonymous base type
19615
19616       Implicit_Base :=
19617         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
19618
19619       --  Analyze and check the bounds, they can be of any integer type
19620
19621       Lo := Low_Bound (Def);
19622       Hi := High_Bound (Def);
19623
19624       --  Arbitrarily use Integer as the type if either bound had an error
19625
19626       if Hi = Error or else Lo = Error then
19627          Base_Typ := Any_Integer;
19628          Set_Error_Posted (T, True);
19629
19630       --  Here both bounds are OK expressions
19631
19632       else
19633          Analyze_And_Resolve (Lo, Any_Integer);
19634          Analyze_And_Resolve (Hi, Any_Integer);
19635
19636          Check_Bound (Lo);
19637          Check_Bound (Hi);
19638
19639          if Errs then
19640             Hi := Type_High_Bound (Standard_Long_Long_Integer);
19641             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
19642          end if;
19643
19644          --  Find type to derive from
19645
19646          Lo_Val := Expr_Value (Lo);
19647          Hi_Val := Expr_Value (Hi);
19648
19649          if Can_Derive_From (Standard_Short_Short_Integer) then
19650             Base_Typ := Base_Type (Standard_Short_Short_Integer);
19651
19652          elsif Can_Derive_From (Standard_Short_Integer) then
19653             Base_Typ := Base_Type (Standard_Short_Integer);
19654
19655          elsif Can_Derive_From (Standard_Integer) then
19656             Base_Typ := Base_Type (Standard_Integer);
19657
19658          elsif Can_Derive_From (Standard_Long_Integer) then
19659             Base_Typ := Base_Type (Standard_Long_Integer);
19660
19661          elsif Can_Derive_From (Standard_Long_Long_Integer) then
19662             Base_Typ := Base_Type (Standard_Long_Long_Integer);
19663
19664          else
19665             Base_Typ := Base_Type (Standard_Long_Long_Integer);
19666             Error_Msg_N ("integer type definition bounds out of range", Def);
19667             Hi := Type_High_Bound (Standard_Long_Long_Integer);
19668             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
19669          end if;
19670       end if;
19671
19672       --  Complete both implicit base and declared first subtype entities
19673
19674       Set_Etype          (Implicit_Base, Base_Typ);
19675       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
19676       Set_Size_Info      (Implicit_Base,                (Base_Typ));
19677       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
19678       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
19679
19680       Set_Ekind          (T, E_Signed_Integer_Subtype);
19681       Set_Etype          (T, Implicit_Base);
19682
19683       --  In formal verification mode, override partially the decisions above
19684       --  to restrict base type's range to the minimum allowed by RM 3.5.4,
19685       --  namely the smallest symmetric range around zero with a possible extra
19686       --  negative value that contains the subtype range. Keep Size, RM_Size
19687       --  and First_Rep_Item info, which should not be relied upon in formal
19688       --  verification.
19689
19690       if ALFA_Mode then
19691
19692          --  If the range of the type is already symmetric with a possible
19693          --  extra negative value, just make the type its own base type.
19694
19695          if UI_Le (Lo_Val, Hi_Val)
19696            and then (UI_Eq (Lo_Val, UI_Negate (Hi_Val))
19697                       or else
19698                         UI_Eq (Lo_Val, UI_Sub (UI_Negate (Hi_Val), Uint_1)))
19699          then
19700             Set_Etype (T, T);
19701
19702          else
19703             declare
19704                Sym_Hi_Val : Uint;
19705                Sym_Lo_Val : Uint;
19706                Decl       : Node_Id;
19707                Dloc       : constant Source_Ptr := Sloc (Def);
19708                Lbound     : Node_Id;
19709                Ubound     : Node_Id;
19710
19711             begin
19712                --  If the subtype range is empty, the smallest base type range
19713                --  is the symmetric range around zero containing Lo_Val and
19714                --  Hi_Val.
19715
19716                if UI_Gt (Lo_Val, Hi_Val) then
19717                   Sym_Hi_Val := UI_Max (UI_Abs (Lo_Val), UI_Abs (Hi_Val));
19718                   Sym_Lo_Val := UI_Negate (Sym_Hi_Val);
19719
19720                --  Otherwise, if the subtype range is not empty and Hi_Val has
19721                --  the largest absolute value, Hi_Val is non negative and the
19722                --  smallest base type range is the symmetric range around zero
19723                --  containing Hi_Val.
19724
19725                elsif UI_Le (UI_Abs (Lo_Val), UI_Abs (Hi_Val)) then
19726                   Sym_Hi_Val := Hi_Val;
19727                   Sym_Lo_Val := UI_Negate (Hi_Val);
19728
19729                --  Otherwise, the subtype range is not empty, Lo_Val has the
19730                --  strictly largest absolute value, Lo_Val is negative and the
19731                --  smallest base type range is the symmetric range around zero
19732                --  with an extra negative value Lo_Val.
19733
19734                else
19735                   Sym_Lo_Val := Lo_Val;
19736                   Sym_Hi_Val := UI_Sub (UI_Negate (Lo_Val), Uint_1);
19737                end if;
19738
19739                Lbound := Make_Integer_Literal (Dloc, Sym_Lo_Val);
19740                Ubound := Make_Integer_Literal (Dloc, Sym_Hi_Val);
19741                Set_Is_Static_Expression (Lbound);
19742                Set_Is_Static_Expression (Ubound);
19743
19744                Decl := Make_Full_Type_Declaration (Dloc,
19745                  Defining_Identifier => Implicit_Base,
19746                  Type_Definition     =>
19747                    Make_Signed_Integer_Type_Definition (Dloc,
19748                      Low_Bound  => Lbound,
19749                      High_Bound => Ubound));
19750
19751                Analyze (Decl);
19752                Set_Etype (Implicit_Base, Implicit_Base);
19753                Insert_Before (Parent (Def), Decl);
19754             end;
19755          end if;
19756       end if;
19757
19758       Set_Size_Info      (T,                (Implicit_Base));
19759       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
19760       Set_Scalar_Range   (T, Def);
19761       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
19762       Set_Is_Constrained (T);
19763    end Signed_Integer_Type_Declaration;
19764
19765 end Sem_Ch3;