OSDN Git Service

gcc/:
[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-2010, 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_Res;  use Sem_Res;
65 with Sem_Smem; use Sem_Smem;
66 with Sem_Type; use Sem_Type;
67 with Sem_Util; use Sem_Util;
68 with Sem_Warn; use Sem_Warn;
69 with Stand;    use Stand;
70 with Sinfo;    use Sinfo;
71 with Sinput;   use Sinput;
72 with Snames;   use Snames;
73 with Targparm; use Targparm;
74 with Tbuild;   use Tbuild;
75 with Ttypes;   use Ttypes;
76 with Uintp;    use Uintp;
77 with Urealp;   use Urealp;
78
79 package body Sem_Ch3 is
80
81    -----------------------
82    -- Local Subprograms --
83    -----------------------
84
85    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
86    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
87    --  abstract interface types implemented by a record type or a derived
88    --  record type.
89
90    procedure Build_Derived_Type
91      (N             : Node_Id;
92       Parent_Type   : Entity_Id;
93       Derived_Type  : Entity_Id;
94       Is_Completion : Boolean;
95       Derive_Subps  : Boolean := True);
96    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
97    --  the N_Full_Type_Declaration node containing the derived type definition.
98    --  Parent_Type is the entity for the parent type in the derived type
99    --  definition and Derived_Type the actual derived type. Is_Completion must
100    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
101    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
102    --  completion of a private type declaration. If Is_Completion is set to
103    --  True, N is the completion of a private type declaration and Derived_Type
104    --  is different from the defining identifier inside N (i.e. Derived_Type /=
105    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
106    --  subprograms should be derived. The only case where this parameter is
107    --  False is when Build_Derived_Type is recursively called to process an
108    --  implicit derived full type for a type derived from a private type (in
109    --  that case the subprograms must only be derived for the private view of
110    --  the type).
111    --
112    --  ??? These flags need a bit of re-examination and re-documentation:
113    --  ???  are they both necessary (both seem related to the recursion)?
114
115    procedure Build_Derived_Access_Type
116      (N            : Node_Id;
117       Parent_Type  : Entity_Id;
118       Derived_Type : Entity_Id);
119    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
120    --  create an implicit base if the parent type is constrained or if the
121    --  subtype indication has a constraint.
122
123    procedure Build_Derived_Array_Type
124      (N            : Node_Id;
125       Parent_Type  : Entity_Id;
126       Derived_Type : Entity_Id);
127    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
128    --  create an implicit base if the parent type is constrained or if the
129    --  subtype indication has a constraint.
130
131    procedure Build_Derived_Concurrent_Type
132      (N            : Node_Id;
133       Parent_Type  : Entity_Id;
134       Derived_Type : Entity_Id);
135    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
136    --  protected type, inherit entries and protected subprograms, check
137    --  legality of discriminant constraints if any.
138
139    procedure Build_Derived_Enumeration_Type
140      (N            : Node_Id;
141       Parent_Type  : Entity_Id;
142       Derived_Type : Entity_Id);
143    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
144    --  type, we must create a new list of literals. Types derived from
145    --  Character and [Wide_]Wide_Character are special-cased.
146
147    procedure Build_Derived_Numeric_Type
148      (N            : Node_Id;
149       Parent_Type  : Entity_Id;
150       Derived_Type : Entity_Id);
151    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
152    --  an anonymous base type, and propagate constraint to subtype if needed.
153
154    procedure Build_Derived_Private_Type
155      (N             : Node_Id;
156       Parent_Type   : Entity_Id;
157       Derived_Type  : Entity_Id;
158       Is_Completion : Boolean;
159       Derive_Subps  : Boolean := True);
160    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
161    --  because the parent may or may not have a completion, and the derivation
162    --  may itself be a completion.
163
164    procedure Build_Derived_Record_Type
165      (N            : Node_Id;
166       Parent_Type  : Entity_Id;
167       Derived_Type : Entity_Id;
168       Derive_Subps : Boolean := True);
169    --  Subsidiary procedure for Build_Derived_Type and
170    --  Analyze_Private_Extension_Declaration used for tagged and untagged
171    --  record types. All parameters are as in Build_Derived_Type except that
172    --  N, in addition to being an N_Full_Type_Declaration node, can also be an
173    --  N_Private_Extension_Declaration node. See the definition of this routine
174    --  for much more info. Derive_Subps indicates whether subprograms should
175    --  be derived from the parent type. The only case where Derive_Subps is
176    --  False is for an implicit derived full type for a type derived from a
177    --  private type (see Build_Derived_Type).
178
179    procedure Build_Discriminal (Discrim : Entity_Id);
180    --  Create the discriminal corresponding to discriminant Discrim, that is
181    --  the parameter corresponding to Discrim to be used in initialization
182    --  procedures for the type where Discrim is a discriminant. Discriminals
183    --  are not used during semantic analysis, and are not fully defined
184    --  entities until expansion. Thus they are not given a scope until
185    --  initialization procedures are built.
186
187    function Build_Discriminant_Constraints
188      (T           : Entity_Id;
189       Def         : Node_Id;
190       Derived_Def : Boolean := False) return Elist_Id;
191    --  Validate discriminant constraints and return the list of the constraints
192    --  in order of discriminant declarations, where T is the discriminated
193    --  unconstrained type. Def is the N_Subtype_Indication node where the
194    --  discriminants constraints for T are specified. Derived_Def is True
195    --  when building the discriminant constraints in a derived type definition
196    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
197    --  type and Def is the constraint "(xxx)" on T and this routine sets the
198    --  Corresponding_Discriminant field of the discriminants in the derived
199    --  type D to point to the corresponding discriminants in the parent type T.
200
201    procedure Build_Discriminated_Subtype
202      (T           : Entity_Id;
203       Def_Id      : Entity_Id;
204       Elist       : Elist_Id;
205       Related_Nod : Node_Id;
206       For_Access  : Boolean := False);
207    --  Subsidiary procedure to Constrain_Discriminated_Type and to
208    --  Process_Incomplete_Dependents. Given
209    --
210    --     T (a possibly discriminated base type)
211    --     Def_Id (a very partially built subtype for T),
212    --
213    --  the call completes Def_Id to be the appropriate E_*_Subtype.
214    --
215    --  The Elist is the list of discriminant constraints if any (it is set
216    --  to No_Elist if T is not a discriminated type, and to an empty list if
217    --  T has discriminants but there are no discriminant constraints). The
218    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
219    --  The For_Access says whether or not this subtype is really constraining
220    --  an access type. That is its sole purpose is the designated type of an
221    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
222    --  is built to avoid freezing T when the access subtype is frozen.
223
224    function Build_Scalar_Bound
225      (Bound : Node_Id;
226       Par_T : Entity_Id;
227       Der_T : Entity_Id) return Node_Id;
228    --  The bounds of a derived scalar type are conversions of the bounds of
229    --  the parent type. Optimize the representation if the bounds are literals.
230    --  Needs a more complete spec--what are the parameters exactly, and what
231    --  exactly is the returned value, and how is Bound affected???
232
233    procedure Build_Underlying_Full_View
234      (N   : Node_Id;
235       Typ : Entity_Id;
236       Par : Entity_Id);
237    --  If the completion of a private type is itself derived from a private
238    --  type, or if the full view of a private subtype is itself private, the
239    --  back-end has no way to compute the actual size of this type. We build
240    --  an internal subtype declaration of the proper parent type to convey
241    --  this information. This extra mechanism is needed because a full
242    --  view cannot itself have a full view (it would get clobbered during
243    --  view exchanges).
244
245    procedure Check_Access_Discriminant_Requires_Limited
246      (D   : Node_Id;
247       Loc : Node_Id);
248    --  Check the restriction that the type to which an access discriminant
249    --  belongs must be a concurrent type or a descendant of a type with
250    --  the reserved word 'limited' in its declaration.
251
252    procedure Check_Anonymous_Access_Components
253       (Typ_Decl  : Node_Id;
254        Typ       : Entity_Id;
255        Prev      : Entity_Id;
256        Comp_List : Node_Id);
257    --  Ada 2005 AI-382: an access component in a record definition can refer to
258    --  the enclosing record, in which case it denotes the type itself, and not
259    --  the current instance of the type. We create an anonymous access type for
260    --  the component, and flag it as an access to a component, so accessibility
261    --  checks are properly performed on it. The declaration of the access type
262    --  is placed ahead of that of the record to prevent order-of-elaboration
263    --  circularity issues in Gigi. We create an incomplete type for the record
264    --  declaration, which is the designated type of the anonymous access.
265
266    procedure Check_Delta_Expression (E : Node_Id);
267    --  Check that the expression represented by E is suitable for use as a
268    --  delta expression, i.e. it is of real type and is static.
269
270    procedure Check_Digits_Expression (E : Node_Id);
271    --  Check that the expression represented by E is suitable for use as a
272    --  digits expression, i.e. it is of integer type, positive and static.
273
274    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
275    --  Validate the initialization of an object declaration. T is the required
276    --  type, and Exp is the initialization expression.
277
278    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
279    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
280
281    procedure Check_Or_Process_Discriminants
282      (N    : Node_Id;
283       T    : Entity_Id;
284       Prev : Entity_Id := Empty);
285    --  If T is the full declaration of an incomplete or private type, check the
286    --  conformance of the discriminants, otherwise process them. Prev is the
287    --  entity of the partial declaration, if any.
288
289    procedure Check_Real_Bound (Bound : Node_Id);
290    --  Check given bound for being of real type and static. If not, post an
291    --  appropriate message, and rewrite the bound with the real literal zero.
292
293    procedure Constant_Redeclaration
294      (Id : Entity_Id;
295       N  : Node_Id;
296       T  : out Entity_Id);
297    --  Various checks on legality of full declaration of deferred constant.
298    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
299    --  node. The caller has not yet set any attributes of this entity.
300
301    function Contain_Interface
302      (Iface  : Entity_Id;
303       Ifaces : Elist_Id) return Boolean;
304    --  Ada 2005: Determine whether Iface is present in the list Ifaces
305
306    procedure Convert_Scalar_Bounds
307      (N            : Node_Id;
308       Parent_Type  : Entity_Id;
309       Derived_Type : Entity_Id;
310       Loc          : Source_Ptr);
311    --  For derived scalar types, convert the bounds in the type definition to
312    --  the derived type, and complete their analysis. Given a constraint of the
313    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
314    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
315    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
316    --  subtype are conversions of those bounds to the derived_type, so that
317    --  their typing is consistent.
318
319    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
320    --  Copies attributes from array base type T2 to array base type T1. Copies
321    --  only attributes that apply to base types, but not subtypes.
322
323    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
324    --  Copies attributes from array subtype T2 to array subtype T1. Copies
325    --  attributes that apply to both subtypes and base types.
326
327    procedure Create_Constrained_Components
328      (Subt        : Entity_Id;
329       Decl_Node   : Node_Id;
330       Typ         : Entity_Id;
331       Constraints : Elist_Id);
332    --  Build the list of entities for a constrained discriminated record
333    --  subtype. If a component depends on a discriminant, replace its subtype
334    --  using the discriminant values in the discriminant constraint. Subt
335    --  is the defining identifier for the subtype whose list of constrained
336    --  entities we will create. Decl_Node is the type declaration node where
337    --  we will attach all the itypes created. Typ is the base discriminated
338    --  type for the subtype Subt. Constraints is the list of discriminant
339    --  constraints for Typ.
340
341    function Constrain_Component_Type
342      (Comp            : Entity_Id;
343       Constrained_Typ : Entity_Id;
344       Related_Node    : Node_Id;
345       Typ             : Entity_Id;
346       Constraints     : Elist_Id) return Entity_Id;
347    --  Given a discriminated base type Typ, a list of discriminant constraint
348    --  Constraints for Typ and a component of Typ, with type Compon_Type,
349    --  create and return the type corresponding to Compon_type where all
350    --  discriminant references are replaced with the corresponding constraint.
351    --  If no discriminant references occur in Compon_Typ then return it as is.
352    --  Constrained_Typ is the final constrained subtype to which the
353    --  constrained Compon_Type belongs. Related_Node is the node where we will
354    --  attach all the itypes created.
355    --
356    --  Above description is confused, what is Compon_Type???
357
358    procedure Constrain_Access
359      (Def_Id      : in out Entity_Id;
360       S           : Node_Id;
361       Related_Nod : Node_Id);
362    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
363    --  an anonymous type created for a subtype indication. In that case it is
364    --  created in the procedure and attached to Related_Nod.
365
366    procedure Constrain_Array
367      (Def_Id      : in out Entity_Id;
368       SI          : Node_Id;
369       Related_Nod : Node_Id;
370       Related_Id  : Entity_Id;
371       Suffix      : Character);
372    --  Apply a list of index constraints to an unconstrained array type. The
373    --  first parameter is the entity for the resulting subtype. A value of
374    --  Empty for Def_Id indicates that an implicit type must be created, but
375    --  creation is delayed (and must be done by this procedure) because other
376    --  subsidiary implicit types must be created first (which is why Def_Id
377    --  is an in/out parameter). The second parameter is a subtype indication
378    --  node for the constrained array to be created (e.g. something of the
379    --  form string (1 .. 10)). Related_Nod gives the place where this type
380    --  has to be inserted in the tree. The Related_Id and Suffix parameters
381    --  are used to build the associated Implicit type name.
382
383    procedure Constrain_Concurrent
384      (Def_Id      : in out Entity_Id;
385       SI          : Node_Id;
386       Related_Nod : Node_Id;
387       Related_Id  : Entity_Id;
388       Suffix      : Character);
389    --  Apply list of discriminant constraints to an unconstrained concurrent
390    --  type.
391    --
392    --    SI is the N_Subtype_Indication node containing the constraint and
393    --    the unconstrained type to constrain.
394    --
395    --    Def_Id is the entity for the resulting constrained subtype. A value
396    --    of Empty for Def_Id indicates that an implicit type must be created,
397    --    but creation is delayed (and must be done by this procedure) because
398    --    other subsidiary implicit types must be created first (which is why
399    --    Def_Id is an in/out parameter).
400    --
401    --    Related_Nod gives the place where this type has to be inserted
402    --    in the tree
403    --
404    --  The last two arguments are used to create its external name if needed.
405
406    function Constrain_Corresponding_Record
407      (Prot_Subt   : Entity_Id;
408       Corr_Rec    : Entity_Id;
409       Related_Nod : Node_Id;
410       Related_Id  : Entity_Id) return Entity_Id;
411    --  When constraining a protected type or task type with discriminants,
412    --  constrain the corresponding record with the same discriminant values.
413
414    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
415    --  Constrain a decimal fixed point type with a digits constraint and/or a
416    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
417
418    procedure Constrain_Discriminated_Type
419      (Def_Id      : Entity_Id;
420       S           : Node_Id;
421       Related_Nod : Node_Id;
422       For_Access  : Boolean := False);
423    --  Process discriminant constraints of composite type. Verify that values
424    --  have been provided for all discriminants, that the original type is
425    --  unconstrained, and that the types of the supplied expressions match
426    --  the discriminant types. The first three parameters are like in routine
427    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
428    --  of For_Access.
429
430    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
431    --  Constrain an enumeration type with a range constraint. This is identical
432    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
433
434    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
435    --  Constrain a floating point type with either a digits constraint
436    --  and/or a range constraint, building a E_Floating_Point_Subtype.
437
438    procedure Constrain_Index
439      (Index        : Node_Id;
440       S            : Node_Id;
441       Related_Nod  : Node_Id;
442       Related_Id   : Entity_Id;
443       Suffix       : Character;
444       Suffix_Index : Nat);
445    --  Process an index constraint in a constrained array declaration. The
446    --  constraint can be a subtype name, or a range with or without an explicit
447    --  subtype mark. The index is the corresponding index of the unconstrained
448    --  array. The Related_Id and Suffix parameters are used to build the
449    --  associated Implicit type name.
450
451    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
452    --  Build subtype of a signed or modular integer type
453
454    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
455    --  Constrain an ordinary fixed point type with a range constraint, and
456    --  build an E_Ordinary_Fixed_Point_Subtype entity.
457
458    procedure Copy_And_Swap (Priv, Full : Entity_Id);
459    --  Copy the Priv entity into the entity of its full declaration then swap
460    --  the two entities in such a manner that the former private type is now
461    --  seen as a full type.
462
463    procedure Decimal_Fixed_Point_Type_Declaration
464      (T   : Entity_Id;
465       Def : Node_Id);
466    --  Create a new decimal fixed point type, and apply the constraint to
467    --  obtain a subtype of this new type.
468
469    procedure Complete_Private_Subtype
470      (Priv        : Entity_Id;
471       Full        : Entity_Id;
472       Full_Base   : Entity_Id;
473       Related_Nod : Node_Id);
474    --  Complete the implicit full view of a private subtype by setting the
475    --  appropriate semantic fields. If the full view of the parent is a record
476    --  type, build constrained components of subtype.
477
478    procedure Derive_Progenitor_Subprograms
479      (Parent_Type : Entity_Id;
480       Tagged_Type : Entity_Id);
481    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
482    --  operations of progenitors of Tagged_Type, and replace the subsidiary
483    --  subtypes with Tagged_Type, to build the specs of the inherited interface
484    --  primitives. The derived primitives are aliased to those of the
485    --  interface. This routine takes care also of transferring to the full-view
486    --  subprograms associated with the partial-view of Tagged_Type that cover
487    --  interface primitives.
488
489    procedure Derived_Standard_Character
490      (N             : Node_Id;
491       Parent_Type   : Entity_Id;
492       Derived_Type  : Entity_Id);
493    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
494    --  derivations from types Standard.Character and Standard.Wide_Character.
495
496    procedure Derived_Type_Declaration
497      (T             : Entity_Id;
498       N             : Node_Id;
499       Is_Completion : Boolean);
500    --  Process a derived type declaration. Build_Derived_Type is invoked
501    --  to process the actual derived type definition. Parameters N and
502    --  Is_Completion have the same meaning as in Build_Derived_Type.
503    --  T is the N_Defining_Identifier for the entity defined in the
504    --  N_Full_Type_Declaration node N, that is T is the derived type.
505
506    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
507    --  Insert each literal in symbol table, as an overloadable identifier. Each
508    --  enumeration type is mapped into a sequence of integers, and each literal
509    --  is defined as a constant with integer value. If any of the literals are
510    --  character literals, the type is a character type, which means that
511    --  strings are legal aggregates for arrays of components of the type.
512
513    function Expand_To_Stored_Constraint
514      (Typ        : Entity_Id;
515       Constraint : Elist_Id) return Elist_Id;
516    --  Given a constraint (i.e. a list of expressions) on the discriminants of
517    --  Typ, expand it into a constraint on the stored discriminants and return
518    --  the new list of expressions constraining the stored discriminants.
519
520    function Find_Type_Of_Object
521      (Obj_Def     : Node_Id;
522       Related_Nod : Node_Id) return Entity_Id;
523    --  Get type entity for object referenced by Obj_Def, attaching the
524    --  implicit types generated to Related_Nod
525
526    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
527    --  Create a new float and apply the constraint to obtain subtype of it
528
529    function Has_Range_Constraint (N : Node_Id) return Boolean;
530    --  Given an N_Subtype_Indication node N, return True if a range constraint
531    --  is present, either directly, or as part of a digits or delta constraint.
532    --  In addition, a digits constraint in the decimal case returns True, since
533    --  it establishes a default range if no explicit range is present.
534
535    function Inherit_Components
536      (N             : Node_Id;
537       Parent_Base   : Entity_Id;
538       Derived_Base  : Entity_Id;
539       Is_Tagged     : Boolean;
540       Inherit_Discr : Boolean;
541       Discs         : Elist_Id) return Elist_Id;
542    --  Called from Build_Derived_Record_Type to inherit the components of
543    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
544    --  For more information on derived types and component inheritance please
545    --  consult the comment above the body of Build_Derived_Record_Type.
546    --
547    --    N is the original derived type declaration
548    --
549    --    Is_Tagged is set if we are dealing with tagged types
550    --
551    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
552    --    Parent_Base, otherwise no discriminants are inherited.
553    --
554    --    Discs gives the list of constraints that apply to Parent_Base in the
555    --    derived type declaration. If Discs is set to No_Elist, then we have
556    --    the following situation:
557    --
558    --      type Parent (D1..Dn : ..) is [tagged] record ...;
559    --      type Derived is new Parent [with ...];
560    --
561    --    which gets treated as
562    --
563    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
564    --
565    --  For untagged types the returned value is an association list. The list
566    --  starts from the association (Parent_Base => Derived_Base), and then it
567    --  contains a sequence of the associations of the form
568    --
569    --    (Old_Component => New_Component),
570    --
571    --  where Old_Component is the Entity_Id of a component in Parent_Base and
572    --  New_Component is the Entity_Id of the corresponding component in
573    --  Derived_Base. For untagged records, this association list is needed when
574    --  copying the record declaration for the derived base. In the tagged case
575    --  the value returned is irrelevant.
576
577    function Is_Valid_Constraint_Kind
578      (T_Kind          : Type_Kind;
579       Constraint_Kind : Node_Kind) return Boolean;
580    --  Returns True if it is legal to apply the given kind of constraint to the
581    --  given kind of type (index constraint to an array type, for example).
582
583    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
584    --  Create new modular type. Verify that modulus is in bounds and is
585    --  a power of two (implementation restriction).
586
587    procedure New_Concatenation_Op (Typ : Entity_Id);
588    --  Create an abbreviated declaration for an operator in order to
589    --  materialize concatenation on array types.
590
591    procedure Ordinary_Fixed_Point_Type_Declaration
592      (T   : Entity_Id;
593       Def : Node_Id);
594    --  Create a new ordinary fixed point type, and apply the constraint to
595    --  obtain subtype of it.
596
597    procedure Prepare_Private_Subtype_Completion
598      (Id          : Entity_Id;
599       Related_Nod : Node_Id);
600    --  Id is a subtype of some private type. Creates the full declaration
601    --  associated with Id whenever possible, i.e. when the full declaration
602    --  of the base type is already known. Records each subtype into
603    --  Private_Dependents of the base type.
604
605    procedure Process_Incomplete_Dependents
606      (N      : Node_Id;
607       Full_T : Entity_Id;
608       Inc_T  : Entity_Id);
609    --  Process all entities that depend on an incomplete type. There include
610    --  subtypes, subprogram types that mention the incomplete type in their
611    --  profiles, and subprogram with access parameters that designate the
612    --  incomplete type.
613
614    --  Inc_T is the defining identifier of an incomplete type declaration, its
615    --  Ekind is E_Incomplete_Type.
616    --
617    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
618    --
619    --    Full_T is N's defining identifier.
620    --
621    --  Subtypes of incomplete types with discriminants are completed when the
622    --  parent type is. This is simpler than private subtypes, because they can
623    --  only appear in the same scope, and there is no need to exchange views.
624    --  Similarly, access_to_subprogram types may have a parameter or a return
625    --  type that is an incomplete type, and that must be replaced with the
626    --  full type.
627    --
628    --  If the full type is tagged, subprogram with access parameters that
629    --  designated the incomplete may be primitive operations of the full type,
630    --  and have to be processed accordingly.
631
632    procedure Process_Real_Range_Specification (Def : Node_Id);
633    --  Given the type definition for a real type, this procedure processes and
634    --  checks the real range specification of this type definition if one is
635    --  present. If errors are found, error messages are posted, and the
636    --  Real_Range_Specification of Def is reset to Empty.
637
638    procedure Record_Type_Declaration
639      (T    : Entity_Id;
640       N    : Node_Id;
641       Prev : Entity_Id);
642    --  Process a record type declaration (for both untagged and tagged
643    --  records). Parameters T and N are exactly like in procedure
644    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
645    --  for this routine. If this is the completion of an incomplete type
646    --  declaration, Prev is the entity of the incomplete declaration, used for
647    --  cross-referencing. Otherwise Prev = T.
648
649    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
650    --  This routine is used to process the actual record type definition (both
651    --  for untagged and tagged records). Def is a record type definition node.
652    --  This procedure analyzes the components in this record type definition.
653    --  Prev_T is the entity for the enclosing record type. It is provided so
654    --  that its Has_Task flag can be set if any of the component have Has_Task
655    --  set. If the declaration is the completion of an incomplete type
656    --  declaration, Prev_T is the original incomplete type, whose full view is
657    --  the record type.
658
659    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
660    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
661    --  build a copy of the declaration tree of the parent, and we create
662    --  independently the list of components for the derived type. Semantic
663    --  information uses the component entities, but record representation
664    --  clauses are validated on the declaration tree. This procedure replaces
665    --  discriminants and components in the declaration with those that have
666    --  been created by Inherit_Components.
667
668    procedure Set_Fixed_Range
669      (E   : Entity_Id;
670       Loc : Source_Ptr;
671       Lo  : Ureal;
672       Hi  : Ureal);
673    --  Build a range node with the given bounds and set it as the Scalar_Range
674    --  of the given fixed-point type entity. Loc is the source location used
675    --  for the constructed range. See body for further details.
676
677    procedure Set_Scalar_Range_For_Subtype
678      (Def_Id : Entity_Id;
679       R      : Node_Id;
680       Subt   : Entity_Id);
681    --  This routine is used to set the scalar range field for a subtype given
682    --  Def_Id, the entity for the subtype, and R, the range expression for the
683    --  scalar range. Subt provides the parent subtype to be used to analyze,
684    --  resolve, and check the given range.
685
686    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
687    --  Create a new signed integer entity, and apply the constraint to obtain
688    --  the required first named subtype of this type.
689
690    procedure Set_Stored_Constraint_From_Discriminant_Constraint
691      (E : Entity_Id);
692    --  E is some record type. This routine computes E's Stored_Constraint
693    --  from its Discriminant_Constraint.
694
695    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
696    --  Check that an entity in a list of progenitors is an interface,
697    --  emit error otherwise.
698
699    -----------------------
700    -- Access_Definition --
701    -----------------------
702
703    function Access_Definition
704      (Related_Nod : Node_Id;
705       N           : Node_Id) return Entity_Id
706    is
707       Loc                 : constant Source_Ptr := Sloc (Related_Nod);
708       Anon_Type           : Entity_Id;
709       Anon_Scope          : Entity_Id;
710       Desig_Type          : Entity_Id;
711       Decl                : Entity_Id;
712       Enclosing_Prot_Type : Entity_Id := Empty;
713
714    begin
715       if Is_Entry (Current_Scope)
716         and then Is_Task_Type (Etype (Scope (Current_Scope)))
717       then
718          Error_Msg_N ("task entries cannot have access parameters", N);
719          return Empty;
720       end if;
721
722       --  Ada 2005: for an object declaration the corresponding anonymous
723       --  type is declared in the current scope.
724
725       --  If the access definition is the return type of another access to
726       --  function, scope is the current one, because it is the one of the
727       --  current type declaration.
728
729       if Nkind_In (Related_Nod, N_Object_Declaration,
730                                 N_Access_Function_Definition)
731       then
732          Anon_Scope := Current_Scope;
733
734       --  For the anonymous function result case, retrieve the scope of the
735       --  function specification's associated entity rather than using the
736       --  current scope. The current scope will be the function itself if the
737       --  formal part is currently being analyzed, but will be the parent scope
738       --  in the case of a parameterless function, and we always want to use
739       --  the function's parent scope. Finally, if the function is a child
740       --  unit, we must traverse the tree to retrieve the proper entity.
741
742       elsif Nkind (Related_Nod) = N_Function_Specification
743         and then Nkind (Parent (N)) /= N_Parameter_Specification
744       then
745          --  If the current scope is a protected type, the anonymous access
746          --  is associated with one of the protected operations, and must
747          --  be available in the scope that encloses the protected declaration.
748          --  Otherwise the type is in the scope enclosing the subprogram.
749
750          --  If the function has formals, The return type of a subprogram
751          --  declaration is analyzed in the scope of the subprogram (see
752          --  Process_Formals) and thus the protected type, if present, is
753          --  the scope of the current function scope.
754
755          if Ekind (Current_Scope) = E_Protected_Type then
756             Enclosing_Prot_Type := Current_Scope;
757
758          elsif Ekind (Current_Scope) = E_Function
759            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
760          then
761             Enclosing_Prot_Type := Scope (Current_Scope);
762          end if;
763
764          if Present (Enclosing_Prot_Type) then
765             Anon_Scope := Scope (Enclosing_Prot_Type);
766
767          else
768             Anon_Scope := Scope (Defining_Entity (Related_Nod));
769          end if;
770
771       else
772          --  For access formals, access components, and access discriminants,
773          --  the scope is that of the enclosing declaration,
774
775          Anon_Scope := Scope (Current_Scope);
776       end if;
777
778       Anon_Type :=
779         Create_Itype
780          (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
781
782       if All_Present (N)
783         and then Ada_Version >= Ada_05
784       then
785          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
786       end if;
787
788       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
789       --  the corresponding semantic routine
790
791       if Present (Access_To_Subprogram_Definition (N)) then
792          Access_Subprogram_Declaration
793            (T_Name => Anon_Type,
794             T_Def  => Access_To_Subprogram_Definition (N));
795
796          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
797             Set_Ekind
798               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
799          else
800             Set_Ekind
801               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
802          end if;
803
804          Set_Can_Use_Internal_Rep
805            (Anon_Type, not Always_Compatible_Rep_On_Target);
806
807          --  If the anonymous access is associated with a protected operation
808          --  create a reference to it after the enclosing protected definition
809          --  because the itype will be used in the subsequent bodies.
810
811          if Ekind (Current_Scope) = E_Protected_Type then
812             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
813          end if;
814
815          return Anon_Type;
816       end if;
817
818       Find_Type (Subtype_Mark (N));
819       Desig_Type := Entity (Subtype_Mark (N));
820
821       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
822       Set_Etype (Anon_Type, Anon_Type);
823
824       --  Make sure the anonymous access type has size and alignment fields
825       --  set, as required by gigi. This is necessary in the case of the
826       --  Task_Body_Procedure.
827
828       if not Has_Private_Component (Desig_Type) then
829          Layout_Type (Anon_Type);
830       end if;
831
832       --  ???The following makes no sense, because Anon_Type is an access type
833       --  and therefore cannot have components, private or otherwise. Hence
834       --  the assertion. Not sure what was meant, here.
835       Set_Depends_On_Private (Anon_Type, Has_Private_Component (Anon_Type));
836       pragma Assert (not Depends_On_Private (Anon_Type));
837
838       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
839       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
840       --  the null value is allowed. In Ada 95 the null value is never allowed.
841
842       if Ada_Version >= Ada_05 then
843          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
844       else
845          Set_Can_Never_Be_Null (Anon_Type, True);
846       end if;
847
848       --  The anonymous access type is as public as the discriminated type or
849       --  subprogram that defines it. It is imported (for back-end purposes)
850       --  if the designated type is.
851
852       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
853
854       --  Ada 2005 (AI-231): Propagate the access-constant attribute
855
856       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
857
858       --  The context is either a subprogram declaration, object declaration,
859       --  or an access discriminant, in a private or a full type declaration.
860       --  In the case of a subprogram, if the designated type is incomplete,
861       --  the operation will be a primitive operation of the full type, to be
862       --  updated subsequently. If the type is imported through a limited_with
863       --  clause, the subprogram is not a primitive operation of the type
864       --  (which is declared elsewhere in some other scope).
865
866       if Ekind (Desig_Type) = E_Incomplete_Type
867         and then not From_With_Type (Desig_Type)
868         and then Is_Overloadable (Current_Scope)
869       then
870          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
871          Set_Has_Delayed_Freeze (Current_Scope);
872       end if;
873
874       --  Ada 2005: if the designated type is an interface that may contain
875       --  tasks, create a Master entity for the declaration. This must be done
876       --  before expansion of the full declaration, because the declaration may
877       --  include an expression that is an allocator, whose expansion needs the
878       --  proper Master for the created tasks.
879
880       if Nkind (Related_Nod) = N_Object_Declaration
881          and then Expander_Active
882       then
883          if Is_Interface (Desig_Type)
884            and then Is_Limited_Record (Desig_Type)
885          then
886             Build_Class_Wide_Master (Anon_Type);
887
888          --  Similarly, if the type is an anonymous access that designates
889          --  tasks, create a master entity for it in the current context.
890
891          elsif Has_Task (Desig_Type)
892            and then Comes_From_Source (Related_Nod)
893          then
894             if not Has_Master_Entity (Current_Scope) then
895                Decl :=
896                  Make_Object_Declaration (Loc,
897                    Defining_Identifier =>
898                      Make_Defining_Identifier (Loc, Name_uMaster),
899                    Constant_Present => True,
900                    Object_Definition =>
901                      New_Reference_To (RTE (RE_Master_Id), Loc),
902                    Expression =>
903                      Make_Explicit_Dereference (Loc,
904                        New_Reference_To (RTE (RE_Current_Master), Loc)));
905
906                Insert_Before (Related_Nod, Decl);
907                Analyze (Decl);
908
909                Set_Master_Id (Anon_Type, Defining_Identifier (Decl));
910                Set_Has_Master_Entity (Current_Scope);
911             else
912                Build_Master_Renaming (Related_Nod, Anon_Type);
913             end if;
914          end if;
915       end if;
916
917       --  For a private component of a protected type, it is imperative that
918       --  the back-end elaborate the type immediately after the protected
919       --  declaration, because this type will be used in the declarations
920       --  created for the component within each protected body, so we must
921       --  create an itype reference for it now.
922
923       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
924          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
925
926       --  Similarly, if the access definition is the return result of a
927       --  function, create an itype reference for it because it will be used
928       --  within the function body. For a regular function that is not a
929       --  compilation unit, insert reference after the declaration. For a
930       --  protected operation, insert it after the enclosing protected type
931       --  declaration. In either case, do not create a reference for a type
932       --  obtained through a limited_with clause, because this would introduce
933       --  semantic dependencies.
934
935       --  Similarly, do not create a reference if the designated type is a
936       --  generic formal, because no use of it will reach the backend.
937
938       elsif Nkind (Related_Nod) = N_Function_Specification
939         and then not From_With_Type (Desig_Type)
940         and then not Is_Generic_Type (Desig_Type)
941       then
942          if Present (Enclosing_Prot_Type) then
943             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
944
945          elsif Is_List_Member (Parent (Related_Nod))
946            and then Nkind (Parent (N)) /= N_Parameter_Specification
947          then
948             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
949          end if;
950
951       --  Finally, create an itype reference for an object declaration of an
952       --  anonymous access type. This is strictly necessary only for deferred
953       --  constants, but in any case will avoid out-of-scope problems in the
954       --  back-end.
955
956       elsif Nkind (Related_Nod) = N_Object_Declaration then
957          Build_Itype_Reference (Anon_Type, Related_Nod);
958       end if;
959
960       return Anon_Type;
961    end Access_Definition;
962
963    -----------------------------------
964    -- Access_Subprogram_Declaration --
965    -----------------------------------
966
967    procedure Access_Subprogram_Declaration
968      (T_Name : Entity_Id;
969       T_Def  : Node_Id)
970    is
971
972       procedure Check_For_Premature_Usage (Def : Node_Id);
973       --  Check that type T_Name is not used, directly or recursively, as a
974       --  parameter or a return type in Def. Def is either a subtype, an
975       --  access_definition, or an access_to_subprogram_definition.
976
977       -------------------------------
978       -- Check_For_Premature_Usage --
979       -------------------------------
980
981       procedure Check_For_Premature_Usage (Def : Node_Id) is
982          Param : Node_Id;
983
984       begin
985          --  Check for a subtype mark
986
987          if Nkind (Def) in N_Has_Etype then
988             if Etype (Def) = T_Name then
989                Error_Msg_N
990                  ("type& cannot be used before end of its declaration", Def);
991             end if;
992
993          --  If this is not a subtype, then this is an access_definition
994
995          elsif Nkind (Def) = N_Access_Definition then
996             if Present (Access_To_Subprogram_Definition (Def)) then
997                Check_For_Premature_Usage
998                  (Access_To_Subprogram_Definition (Def));
999             else
1000                Check_For_Premature_Usage (Subtype_Mark (Def));
1001             end if;
1002
1003          --  The only cases left are N_Access_Function_Definition and
1004          --  N_Access_Procedure_Definition.
1005
1006          else
1007             if Present (Parameter_Specifications (Def)) then
1008                Param := First (Parameter_Specifications (Def));
1009                while Present (Param) loop
1010                   Check_For_Premature_Usage (Parameter_Type (Param));
1011                   Param := Next (Param);
1012                end loop;
1013             end if;
1014
1015             if Nkind (Def) = N_Access_Function_Definition then
1016                Check_For_Premature_Usage (Result_Definition (Def));
1017             end if;
1018          end if;
1019       end Check_For_Premature_Usage;
1020
1021       --  Local variables
1022
1023       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1024       Formal     : Entity_Id;
1025       D_Ityp     : Node_Id;
1026       Desig_Type : constant Entity_Id :=
1027                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1028
1029    --  Start of processing for Access_Subprogram_Declaration
1030
1031    begin
1032       --  Associate the Itype node with the inner full-type declaration or
1033       --  subprogram spec or entry body. This is required to handle nested
1034       --  anonymous declarations. For example:
1035
1036       --      procedure P
1037       --       (X : access procedure
1038       --                     (Y : access procedure
1039       --                                   (Z : access T)))
1040
1041       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1042       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1043                                    N_Private_Type_Declaration,
1044                                    N_Private_Extension_Declaration,
1045                                    N_Procedure_Specification,
1046                                    N_Function_Specification,
1047                                    N_Entry_Body)
1048
1049                    or else
1050                  Nkind_In (D_Ityp, N_Object_Declaration,
1051                                    N_Object_Renaming_Declaration,
1052                                    N_Formal_Object_Declaration,
1053                                    N_Formal_Type_Declaration,
1054                                    N_Task_Type_Declaration,
1055                                    N_Protected_Type_Declaration))
1056       loop
1057          D_Ityp := Parent (D_Ityp);
1058          pragma Assert (D_Ityp /= Empty);
1059       end loop;
1060
1061       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1062
1063       if Nkind_In (D_Ityp, N_Procedure_Specification,
1064                            N_Function_Specification)
1065       then
1066          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1067
1068       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1069                               N_Object_Declaration,
1070                               N_Object_Renaming_Declaration,
1071                               N_Formal_Type_Declaration)
1072       then
1073          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1074       end if;
1075
1076       if Nkind (T_Def) = N_Access_Function_Definition then
1077          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1078             declare
1079                Acc : constant Node_Id := Result_Definition (T_Def);
1080
1081             begin
1082                if Present (Access_To_Subprogram_Definition (Acc))
1083                  and then
1084                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1085                then
1086                   Set_Etype
1087                     (Desig_Type,
1088                        Replace_Anonymous_Access_To_Protected_Subprogram
1089                          (T_Def));
1090
1091                else
1092                   Set_Etype
1093                     (Desig_Type,
1094                        Access_Definition (T_Def, Result_Definition (T_Def)));
1095                end if;
1096             end;
1097
1098          else
1099             Analyze (Result_Definition (T_Def));
1100
1101             declare
1102                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1103
1104             begin
1105                --  If a null exclusion is imposed on the result type, then
1106                --  create a null-excluding itype (an access subtype) and use
1107                --  it as the function's Etype.
1108
1109                if Is_Access_Type (Typ)
1110                  and then Null_Exclusion_In_Return_Present (T_Def)
1111                then
1112                   Set_Etype  (Desig_Type,
1113                     Create_Null_Excluding_Itype
1114                       (T           => Typ,
1115                        Related_Nod => T_Def,
1116                        Scope_Id    => Current_Scope));
1117
1118                else
1119                   if From_With_Type (Typ) then
1120                      Error_Msg_NE
1121                       ("illegal use of incomplete type&",
1122                          Result_Definition (T_Def), Typ);
1123
1124                   elsif Ekind (Current_Scope) = E_Package
1125                     and then In_Private_Part (Current_Scope)
1126                   then
1127                      if Ekind (Typ) = E_Incomplete_Type then
1128                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1129
1130                      elsif Is_Class_Wide_Type (Typ)
1131                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1132                      then
1133                         Append_Elmt
1134                           (Desig_Type, Private_Dependents (Etype (Typ)));
1135                      end if;
1136                   end if;
1137
1138                   Set_Etype (Desig_Type, Typ);
1139                end if;
1140             end;
1141          end if;
1142
1143          if not (Is_Type (Etype (Desig_Type))) then
1144             Error_Msg_N
1145               ("expect type in function specification",
1146                Result_Definition (T_Def));
1147          end if;
1148
1149       else
1150          Set_Etype (Desig_Type, Standard_Void_Type);
1151       end if;
1152
1153       if Present (Formals) then
1154          Push_Scope (Desig_Type);
1155
1156          --  A bit of a kludge here. These kludges will be removed when Itypes
1157          --  have proper parent pointers to their declarations???
1158
1159          --  Kludge 1) Link defining_identifier of formals. Required by
1160          --  First_Formal to provide its functionality.
1161
1162          declare
1163             F : Node_Id;
1164
1165          begin
1166             F := First (Formals);
1167             while Present (F) loop
1168                if No (Parent (Defining_Identifier (F))) then
1169                   Set_Parent (Defining_Identifier (F), F);
1170                end if;
1171
1172                Next (F);
1173             end loop;
1174          end;
1175
1176          Process_Formals (Formals, Parent (T_Def));
1177
1178          --  Kludge 2) End_Scope requires that the parent pointer be set to
1179          --  something reasonable, but Itypes don't have parent pointers. So
1180          --  we set it and then unset it ???
1181
1182          Set_Parent (Desig_Type, T_Name);
1183          End_Scope;
1184          Set_Parent (Desig_Type, Empty);
1185       end if;
1186
1187       --  Check for premature usage of the type being defined
1188
1189       Check_For_Premature_Usage (T_Def);
1190
1191       --  The return type and/or any parameter type may be incomplete. Mark
1192       --  the subprogram_type as depending on the incomplete type, so that
1193       --  it can be updated when the full type declaration is seen. This
1194       --  only applies to incomplete types declared in some enclosing scope,
1195       --  not to limited views from other packages.
1196
1197       if Present (Formals) then
1198          Formal := First_Formal (Desig_Type);
1199          while Present (Formal) loop
1200             if Ekind (Formal) /= E_In_Parameter
1201               and then Nkind (T_Def) = N_Access_Function_Definition
1202             then
1203                Error_Msg_N ("functions can only have IN parameters", Formal);
1204             end if;
1205
1206             if Ekind (Etype (Formal)) = E_Incomplete_Type
1207               and then In_Open_Scopes (Scope (Etype (Formal)))
1208             then
1209                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1210                Set_Has_Delayed_Freeze (Desig_Type);
1211             end if;
1212
1213             Next_Formal (Formal);
1214          end loop;
1215       end if;
1216
1217       --  If the return type is incomplete, this is legal as long as the
1218       --  type is declared in the current scope and will be completed in
1219       --  it (rather than being part of limited view).
1220
1221       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1222         and then not Has_Delayed_Freeze (Desig_Type)
1223         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1224       then
1225          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1226          Set_Has_Delayed_Freeze (Desig_Type);
1227       end if;
1228
1229       Check_Delayed_Subprogram (Desig_Type);
1230
1231       if Protected_Present (T_Def) then
1232          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1233          Set_Convention (Desig_Type, Convention_Protected);
1234       else
1235          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1236       end if;
1237
1238       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1239
1240       Set_Etype                    (T_Name, T_Name);
1241       Init_Size_Align              (T_Name);
1242       Set_Directly_Designated_Type (T_Name, Desig_Type);
1243
1244       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1245
1246       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1247
1248       Check_Restriction (No_Access_Subprograms, T_Def);
1249    end Access_Subprogram_Declaration;
1250
1251    ----------------------------
1252    -- Access_Type_Declaration --
1253    ----------------------------
1254
1255    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1256       S : constant Node_Id := Subtype_Indication (Def);
1257       P : constant Node_Id := Parent (Def);
1258    begin
1259       --  Check for permissible use of incomplete type
1260
1261       if Nkind (S) /= N_Subtype_Indication then
1262          Analyze (S);
1263
1264          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1265             Set_Directly_Designated_Type (T, Entity (S));
1266          else
1267             Set_Directly_Designated_Type (T,
1268               Process_Subtype (S, P, T, 'P'));
1269          end if;
1270
1271       else
1272          Set_Directly_Designated_Type (T,
1273            Process_Subtype (S, P, T, 'P'));
1274       end if;
1275
1276       if All_Present (Def) or Constant_Present (Def) then
1277          Set_Ekind (T, E_General_Access_Type);
1278       else
1279          Set_Ekind (T, E_Access_Type);
1280       end if;
1281
1282       if Base_Type (Designated_Type (T)) = T then
1283          Error_Msg_N ("access type cannot designate itself", S);
1284
1285       --  In Ada 2005, the type may have a limited view through some unit
1286       --  in its own context, allowing the following circularity that cannot
1287       --  be detected earlier
1288
1289       elsif Is_Class_Wide_Type (Designated_Type (T))
1290         and then Etype (Designated_Type (T)) = T
1291       then
1292          Error_Msg_N
1293            ("access type cannot designate its own classwide type", S);
1294
1295          --  Clean up indication of tagged status to prevent cascaded errors
1296
1297          Set_Is_Tagged_Type (T, False);
1298       end if;
1299
1300       Set_Etype (T, T);
1301
1302       --  If the type has appeared already in a with_type clause, it is
1303       --  frozen and the pointer size is already set. Else, initialize.
1304
1305       if not From_With_Type (T) then
1306          Init_Size_Align (T);
1307       end if;
1308
1309       --  Note that Has_Task is always false, since the access type itself
1310       --  is not a task type. See Einfo for more description on this point.
1311       --  Exactly the same consideration applies to Has_Controlled_Component.
1312
1313       Set_Has_Task (T, False);
1314       Set_Has_Controlled_Component (T, False);
1315
1316       --  Initialize Associated_Final_Chain explicitly to Empty, to avoid
1317       --  problems where an incomplete view of this entity has been previously
1318       --  established by a limited with and an overlaid version of this field
1319       --  (Stored_Constraint) was initialized for the incomplete view.
1320
1321       Set_Associated_Final_Chain (T, Empty);
1322
1323       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1324       --  attributes
1325
1326       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1327       Set_Is_Access_Constant (T, Constant_Present (Def));
1328    end Access_Type_Declaration;
1329
1330    ----------------------------------
1331    -- Add_Interface_Tag_Components --
1332    ----------------------------------
1333
1334    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1335       Loc      : constant Source_Ptr := Sloc (N);
1336       L        : List_Id;
1337       Last_Tag : Node_Id;
1338
1339       procedure Add_Tag (Iface : Entity_Id);
1340       --  Add tag for one of the progenitor interfaces
1341
1342       -------------
1343       -- Add_Tag --
1344       -------------
1345
1346       procedure Add_Tag (Iface : Entity_Id) is
1347          Decl   : Node_Id;
1348          Def    : Node_Id;
1349          Tag    : Entity_Id;
1350          Offset : Entity_Id;
1351
1352       begin
1353          pragma Assert (Is_Tagged_Type (Iface)
1354            and then Is_Interface (Iface));
1355
1356          Def :=
1357            Make_Component_Definition (Loc,
1358              Aliased_Present    => True,
1359              Subtype_Indication =>
1360                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1361
1362          Tag := Make_Temporary (Loc, 'V');
1363
1364          Decl :=
1365            Make_Component_Declaration (Loc,
1366              Defining_Identifier  => Tag,
1367              Component_Definition => Def);
1368
1369          Analyze_Component_Declaration (Decl);
1370
1371          Set_Analyzed (Decl);
1372          Set_Ekind               (Tag, E_Component);
1373          Set_Is_Tag              (Tag);
1374          Set_Is_Aliased          (Tag);
1375          Set_Related_Type        (Tag, Iface);
1376          Init_Component_Location (Tag);
1377
1378          pragma Assert (Is_Frozen (Iface));
1379
1380          Set_DT_Entry_Count    (Tag,
1381            DT_Entry_Count (First_Entity (Iface)));
1382
1383          if No (Last_Tag) then
1384             Prepend (Decl, L);
1385          else
1386             Insert_After (Last_Tag, Decl);
1387          end if;
1388
1389          Last_Tag := Decl;
1390
1391          --  If the ancestor has discriminants we need to give special support
1392          --  to store the offset_to_top value of the secondary dispatch tables.
1393          --  For this purpose we add a supplementary component just after the
1394          --  field that contains the tag associated with each secondary DT.
1395
1396          if Typ /= Etype (Typ)
1397            and then Has_Discriminants (Etype (Typ))
1398          then
1399             Def :=
1400               Make_Component_Definition (Loc,
1401                 Subtype_Indication =>
1402                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1403
1404             Offset := Make_Temporary (Loc, 'V');
1405
1406             Decl :=
1407               Make_Component_Declaration (Loc,
1408                 Defining_Identifier  => Offset,
1409                 Component_Definition => Def);
1410
1411             Analyze_Component_Declaration (Decl);
1412
1413             Set_Analyzed (Decl);
1414             Set_Ekind               (Offset, E_Component);
1415             Set_Is_Aliased          (Offset);
1416             Set_Related_Type        (Offset, Iface);
1417             Init_Component_Location (Offset);
1418             Insert_After (Last_Tag, Decl);
1419             Last_Tag := Decl;
1420          end if;
1421       end Add_Tag;
1422
1423       --  Local variables
1424
1425       Elmt : Elmt_Id;
1426       Ext  : Node_Id;
1427       Comp : Node_Id;
1428
1429    --  Start of processing for Add_Interface_Tag_Components
1430
1431    begin
1432       if not RTE_Available (RE_Interface_Tag) then
1433          Error_Msg
1434            ("(Ada 2005) interface types not supported by this run-time!",
1435             Sloc (N));
1436          return;
1437       end if;
1438
1439       if Ekind (Typ) /= E_Record_Type
1440         or else (Is_Concurrent_Record_Type (Typ)
1441                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1442         or else (not Is_Concurrent_Record_Type (Typ)
1443                   and then No (Interfaces (Typ))
1444                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1445       then
1446          return;
1447       end if;
1448
1449       --  Find the current last tag
1450
1451       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1452          Ext := Record_Extension_Part (Type_Definition (N));
1453       else
1454          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1455          Ext := Type_Definition (N);
1456       end if;
1457
1458       Last_Tag := Empty;
1459
1460       if not (Present (Component_List (Ext))) then
1461          Set_Null_Present (Ext, False);
1462          L := New_List;
1463          Set_Component_List (Ext,
1464            Make_Component_List (Loc,
1465              Component_Items => L,
1466              Null_Present => False));
1467       else
1468          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1469             L := Component_Items
1470                    (Component_List
1471                      (Record_Extension_Part
1472                        (Type_Definition (N))));
1473          else
1474             L := Component_Items
1475                    (Component_List
1476                      (Type_Definition (N)));
1477          end if;
1478
1479          --  Find the last tag component
1480
1481          Comp := First (L);
1482          while Present (Comp) loop
1483             if Nkind (Comp) = N_Component_Declaration
1484               and then Is_Tag (Defining_Identifier (Comp))
1485             then
1486                Last_Tag := Comp;
1487             end if;
1488
1489             Next (Comp);
1490          end loop;
1491       end if;
1492
1493       --  At this point L references the list of components and Last_Tag
1494       --  references the current last tag (if any). Now we add the tag
1495       --  corresponding with all the interfaces that are not implemented
1496       --  by the parent.
1497
1498       if Present (Interfaces (Typ)) then
1499          Elmt := First_Elmt (Interfaces (Typ));
1500          while Present (Elmt) loop
1501             Add_Tag (Node (Elmt));
1502             Next_Elmt (Elmt);
1503          end loop;
1504       end if;
1505    end Add_Interface_Tag_Components;
1506
1507    -------------------------------------
1508    -- Add_Internal_Interface_Entities --
1509    -------------------------------------
1510
1511    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1512       Elmt          : Elmt_Id;
1513       Iface         : Entity_Id;
1514       Iface_Elmt    : Elmt_Id;
1515       Iface_Prim    : Entity_Id;
1516       Ifaces_List   : Elist_Id;
1517       New_Subp      : Entity_Id := Empty;
1518       Prim          : Entity_Id;
1519       Restore_Scope : Boolean := False;
1520
1521    begin
1522       pragma Assert (Ada_Version >= Ada_05
1523         and then Is_Record_Type (Tagged_Type)
1524         and then Is_Tagged_Type (Tagged_Type)
1525         and then Has_Interfaces (Tagged_Type)
1526         and then not Is_Interface (Tagged_Type));
1527
1528       --  Ensure that the internal entities are added to the scope of the type
1529
1530       if Scope (Tagged_Type) /= Current_Scope then
1531          Push_Scope (Scope (Tagged_Type));
1532          Restore_Scope := True;
1533       end if;
1534
1535       Collect_Interfaces (Tagged_Type, Ifaces_List);
1536
1537       Iface_Elmt := First_Elmt (Ifaces_List);
1538       while Present (Iface_Elmt) loop
1539          Iface := Node (Iface_Elmt);
1540
1541          --  Originally we excluded here from this processing interfaces that
1542          --  are parents of Tagged_Type because their primitives are located
1543          --  in the primary dispatch table (and hence no auxiliary internal
1544          --  entities are required to handle secondary dispatch tables in such
1545          --  case). However, these auxiliary entities are also required to
1546          --  handle derivations of interfaces in formals of generics (see
1547          --  Derive_Subprograms).
1548
1549          Elmt := First_Elmt (Primitive_Operations (Iface));
1550          while Present (Elmt) loop
1551             Iface_Prim := Node (Elmt);
1552
1553             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1554                Prim :=
1555                  Find_Primitive_Covering_Interface
1556                    (Tagged_Type => Tagged_Type,
1557                     Iface_Prim  => Iface_Prim);
1558
1559                --  Handle cases where the type has no primitive covering this
1560                --  interface primitive.
1561
1562                if No (Prim) then
1563
1564                   --  Skip non-overridden null interface primitives because
1565                   --  their wrappers will be generated later.
1566
1567                   if Is_Null_Interface_Primitive (Iface_Prim) then
1568                      goto Continue;
1569
1570                   --  if the tagged type is defined at library level then we
1571                   --  invoke Check_Abstract_Overriding to report the error
1572                   --  and thus avoid generating the dispatch tables.
1573
1574                   elsif Is_Library_Level_Tagged_Type (Tagged_Type) then
1575                      Check_Abstract_Overriding (Tagged_Type);
1576                      pragma Assert (Serious_Errors_Detected > 0);
1577                      return;
1578
1579                   --  For tagged types defined in nested scopes it is still
1580                   --  possible to cover this interface primitive by means of
1581                   --  late overriding (see Override_Dispatching_Operation).
1582
1583                   --  Search in the list of primitives of the type for the
1584                   --  entity that will be overridden in such case to reference
1585                   --  it in the internal entity that we build here. If the
1586                   --  primitive is not overridden then the error will be
1587                   --  reported later as part of the analysis of entities
1588                   --  defined in the enclosing scope.
1589
1590                   else
1591                      declare
1592                         El : Elmt_Id;
1593
1594                      begin
1595                         El := First_Elmt (Primitive_Operations (Tagged_Type));
1596                         while Present (El)
1597                           and then Alias (Node (El)) /= Iface_Prim
1598                         loop
1599                            Next_Elmt (El);
1600                         end loop;
1601
1602                         pragma Assert (Present (El));
1603                         Prim := Node (El);
1604                      end;
1605                   end if;
1606                end if;
1607
1608                Derive_Subprogram
1609                  (New_Subp     => New_Subp,
1610                   Parent_Subp  => Iface_Prim,
1611                   Derived_Type => Tagged_Type,
1612                   Parent_Type  => Iface);
1613
1614                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1615                --  associated with interface types. These entities are
1616                --  only registered in the list of primitives of its
1617                --  corresponding tagged type because they are only used
1618                --  to fill the contents of the secondary dispatch tables.
1619                --  Therefore they are removed from the homonym chains.
1620
1621                Set_Is_Hidden (New_Subp);
1622                Set_Is_Internal (New_Subp);
1623                Set_Alias (New_Subp, Prim);
1624                Set_Is_Abstract_Subprogram
1625                  (New_Subp, Is_Abstract_Subprogram (Prim));
1626                Set_Interface_Alias (New_Subp, Iface_Prim);
1627
1628                --  Internal entities associated with interface types are
1629                --  only registered in the list of primitives of the tagged
1630                --  type. They are only used to fill the contents of the
1631                --  secondary dispatch tables. Therefore they are not needed
1632                --  in the homonym chains.
1633
1634                Remove_Homonym (New_Subp);
1635
1636                --  Hidden entities associated with interfaces must have set
1637                --  the Has_Delay_Freeze attribute to ensure that, in case of
1638                --  locally defined tagged types (or compiling with static
1639                --  dispatch tables generation disabled) the corresponding
1640                --  entry of the secondary dispatch table is filled when
1641                --  such an entity is frozen.
1642
1643                Set_Has_Delayed_Freeze (New_Subp);
1644             end if;
1645
1646             <<Continue>>
1647             Next_Elmt (Elmt);
1648          end loop;
1649
1650          Next_Elmt (Iface_Elmt);
1651       end loop;
1652
1653       if Restore_Scope then
1654          Pop_Scope;
1655       end if;
1656    end Add_Internal_Interface_Entities;
1657
1658    -----------------------------------
1659    -- Analyze_Component_Declaration --
1660    -----------------------------------
1661
1662    procedure Analyze_Component_Declaration (N : Node_Id) is
1663       Id : constant Entity_Id := Defining_Identifier (N);
1664       E  : constant Node_Id   := Expression (N);
1665       T  : Entity_Id;
1666       P  : Entity_Id;
1667
1668       function Contains_POC (Constr : Node_Id) return Boolean;
1669       --  Determines whether a constraint uses the discriminant of a record
1670       --  type thus becoming a per-object constraint (POC).
1671
1672       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1673       --  Typ is the type of the current component, check whether this type is
1674       --  a limited type. Used to validate declaration against that of
1675       --  enclosing record.
1676
1677       ------------------
1678       -- Contains_POC --
1679       ------------------
1680
1681       function Contains_POC (Constr : Node_Id) return Boolean is
1682       begin
1683          --  Prevent cascaded errors
1684
1685          if Error_Posted (Constr) then
1686             return False;
1687          end if;
1688
1689          case Nkind (Constr) is
1690             when N_Attribute_Reference =>
1691                return
1692                  Attribute_Name (Constr) = Name_Access
1693                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1694
1695             when N_Discriminant_Association =>
1696                return Denotes_Discriminant (Expression (Constr));
1697
1698             when N_Identifier =>
1699                return Denotes_Discriminant (Constr);
1700
1701             when N_Index_Or_Discriminant_Constraint =>
1702                declare
1703                   IDC : Node_Id;
1704
1705                begin
1706                   IDC := First (Constraints (Constr));
1707                   while Present (IDC) loop
1708
1709                      --  One per-object constraint is sufficient
1710
1711                      if Contains_POC (IDC) then
1712                         return True;
1713                      end if;
1714
1715                      Next (IDC);
1716                   end loop;
1717
1718                   return False;
1719                end;
1720
1721             when N_Range =>
1722                return Denotes_Discriminant (Low_Bound (Constr))
1723                         or else
1724                       Denotes_Discriminant (High_Bound (Constr));
1725
1726             when N_Range_Constraint =>
1727                return Denotes_Discriminant (Range_Expression (Constr));
1728
1729             when others =>
1730                return False;
1731
1732          end case;
1733       end Contains_POC;
1734
1735       ----------------------
1736       -- Is_Known_Limited --
1737       ----------------------
1738
1739       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1740          P : constant Entity_Id := Etype (Typ);
1741          R : constant Entity_Id := Root_Type (Typ);
1742
1743       begin
1744          if Is_Limited_Record (Typ) then
1745             return True;
1746
1747          --  If the root type is limited (and not a limited interface)
1748          --  so is the current type
1749
1750          elsif Is_Limited_Record (R)
1751            and then
1752              (not Is_Interface (R)
1753                or else not Is_Limited_Interface (R))
1754          then
1755             return True;
1756
1757          --  Else the type may have a limited interface progenitor, but a
1758          --  limited record parent.
1759
1760          elsif R /= P
1761            and then Is_Limited_Record (P)
1762          then
1763             return True;
1764
1765          else
1766             return False;
1767          end if;
1768       end Is_Known_Limited;
1769
1770    --  Start of processing for Analyze_Component_Declaration
1771
1772    begin
1773       Generate_Definition (Id);
1774       Enter_Name (Id);
1775
1776       if Present (Subtype_Indication (Component_Definition (N))) then
1777          T := Find_Type_Of_Object
1778                 (Subtype_Indication (Component_Definition (N)), N);
1779
1780       --  Ada 2005 (AI-230): Access Definition case
1781
1782       else
1783          pragma Assert (Present
1784                           (Access_Definition (Component_Definition (N))));
1785
1786          T := Access_Definition
1787                 (Related_Nod => N,
1788                  N => Access_Definition (Component_Definition (N)));
1789          Set_Is_Local_Anonymous_Access (T);
1790
1791          --  Ada 2005 (AI-254)
1792
1793          if Present (Access_To_Subprogram_Definition
1794                       (Access_Definition (Component_Definition (N))))
1795            and then Protected_Present (Access_To_Subprogram_Definition
1796                                         (Access_Definition
1797                                           (Component_Definition (N))))
1798          then
1799             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1800          end if;
1801       end if;
1802
1803       --  If the subtype is a constrained subtype of the enclosing record,
1804       --  (which must have a partial view) the back-end does not properly
1805       --  handle the recursion. Rewrite the component declaration with an
1806       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1807       --  the tree directly because side effects have already been removed from
1808       --  discriminant constraints.
1809
1810       if Ekind (T) = E_Access_Subtype
1811         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1812         and then Comes_From_Source (T)
1813         and then Nkind (Parent (T)) = N_Subtype_Declaration
1814         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1815       then
1816          Rewrite
1817            (Subtype_Indication (Component_Definition (N)),
1818              New_Copy_Tree (Subtype_Indication (Parent (T))));
1819          T := Find_Type_Of_Object
1820                  (Subtype_Indication (Component_Definition (N)), N);
1821       end if;
1822
1823       --  If the component declaration includes a default expression, then we
1824       --  check that the component is not of a limited type (RM 3.7(5)),
1825       --  and do the special preanalysis of the expression (see section on
1826       --  "Handling of Default and Per-Object Expressions" in the spec of
1827       --  package Sem).
1828
1829       if Present (E) then
1830          Preanalyze_Spec_Expression (E, T);
1831          Check_Initialization (T, E);
1832
1833          if Ada_Version >= Ada_05
1834            and then Ekind (T) = E_Anonymous_Access_Type
1835            and then Etype (E) /= Any_Type
1836          then
1837             --  Check RM 3.9.2(9): "if the expected type for an expression is
1838             --  an anonymous access-to-specific tagged type, then the object
1839             --  designated by the expression shall not be dynamically tagged
1840             --  unless it is a controlling operand in a call on a dispatching
1841             --  operation"
1842
1843             if Is_Tagged_Type (Directly_Designated_Type (T))
1844               and then
1845                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1846               and then
1847                 Ekind (Directly_Designated_Type (Etype (E))) =
1848                   E_Class_Wide_Type
1849             then
1850                Error_Msg_N
1851                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1852             end if;
1853
1854             --  (Ada 2005: AI-230): Accessibility check for anonymous
1855             --  components
1856
1857             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1858                Error_Msg_N
1859                  ("expression has deeper access level than component " &
1860                   "(RM 3.10.2 (12.2))", E);
1861             end if;
1862
1863             --  The initialization expression is a reference to an access
1864             --  discriminant. The type of the discriminant is always deeper
1865             --  than any access type.
1866
1867             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1868               and then Is_Entity_Name (E)
1869               and then Ekind (Entity (E)) = E_In_Parameter
1870               and then Present (Discriminal_Link (Entity (E)))
1871             then
1872                Error_Msg_N
1873                  ("discriminant has deeper accessibility level than target",
1874                   E);
1875             end if;
1876          end if;
1877       end if;
1878
1879       --  The parent type may be a private view with unknown discriminants,
1880       --  and thus unconstrained. Regular components must be constrained.
1881
1882       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1883          if Is_Class_Wide_Type (T) then
1884             Error_Msg_N
1885                ("class-wide subtype with unknown discriminants" &
1886                  " in component declaration",
1887                  Subtype_Indication (Component_Definition (N)));
1888          else
1889             Error_Msg_N
1890               ("unconstrained subtype in component declaration",
1891                Subtype_Indication (Component_Definition (N)));
1892          end if;
1893
1894       --  Components cannot be abstract, except for the special case of
1895       --  the _Parent field (case of extending an abstract tagged type)
1896
1897       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1898          Error_Msg_N ("type of a component cannot be abstract", N);
1899       end if;
1900
1901       Set_Etype (Id, T);
1902       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1903
1904       --  The component declaration may have a per-object constraint, set
1905       --  the appropriate flag in the defining identifier of the subtype.
1906
1907       if Present (Subtype_Indication (Component_Definition (N))) then
1908          declare
1909             Sindic : constant Node_Id :=
1910                        Subtype_Indication (Component_Definition (N));
1911          begin
1912             if Nkind (Sindic) = N_Subtype_Indication
1913               and then Present (Constraint (Sindic))
1914               and then Contains_POC (Constraint (Sindic))
1915             then
1916                Set_Has_Per_Object_Constraint (Id);
1917             end if;
1918          end;
1919       end if;
1920
1921       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1922       --  out some static checks.
1923
1924       if Ada_Version >= Ada_05
1925         and then Can_Never_Be_Null (T)
1926       then
1927          Null_Exclusion_Static_Checks (N);
1928       end if;
1929
1930       --  If this component is private (or depends on a private type), flag the
1931       --  record type to indicate that some operations are not available.
1932
1933       P := Private_Component (T);
1934
1935       if Present (P) then
1936
1937          --  Check for circular definitions
1938
1939          if P = Any_Type then
1940             Set_Etype (Id, Any_Type);
1941
1942          --  There is a gap in the visibility of operations only if the
1943          --  component type is not defined in the scope of the record type.
1944
1945          elsif Scope (P) = Scope (Current_Scope) then
1946             null;
1947
1948          elsif Is_Limited_Type (P) then
1949             Set_Is_Limited_Composite (Current_Scope);
1950
1951          else
1952             Set_Is_Private_Composite (Current_Scope);
1953          end if;
1954       end if;
1955
1956       if P /= Any_Type
1957         and then Is_Limited_Type (T)
1958         and then Chars (Id) /= Name_uParent
1959         and then Is_Tagged_Type (Current_Scope)
1960       then
1961          if Is_Derived_Type (Current_Scope)
1962            and then not Is_Known_Limited (Current_Scope)
1963          then
1964             Error_Msg_N
1965               ("extension of nonlimited type cannot have limited components",
1966                N);
1967
1968             if Is_Interface (Root_Type (Current_Scope)) then
1969                Error_Msg_N
1970                  ("\limitedness is not inherited from limited interface", N);
1971                Error_Msg_N ("\add LIMITED to type indication", N);
1972             end if;
1973
1974             Explain_Limited_Type (T, N);
1975             Set_Etype (Id, Any_Type);
1976             Set_Is_Limited_Composite (Current_Scope, False);
1977
1978          elsif not Is_Derived_Type (Current_Scope)
1979            and then not Is_Limited_Record (Current_Scope)
1980            and then not Is_Concurrent_Type (Current_Scope)
1981          then
1982             Error_Msg_N
1983               ("nonlimited tagged type cannot have limited components", N);
1984             Explain_Limited_Type (T, N);
1985             Set_Etype (Id, Any_Type);
1986             Set_Is_Limited_Composite (Current_Scope, False);
1987          end if;
1988       end if;
1989
1990       Set_Original_Record_Component (Id, Id);
1991    end Analyze_Component_Declaration;
1992
1993    --------------------------
1994    -- Analyze_Declarations --
1995    --------------------------
1996
1997    procedure Analyze_Declarations (L : List_Id) is
1998       D           : Node_Id;
1999       Freeze_From : Entity_Id := Empty;
2000       Next_Node   : Node_Id;
2001
2002       procedure Adjust_D;
2003       --  Adjust D not to include implicit label declarations, since these
2004       --  have strange Sloc values that result in elaboration check problems.
2005       --  (They have the sloc of the label as found in the source, and that
2006       --  is ahead of the current declarative part).
2007
2008       --------------
2009       -- Adjust_D --
2010       --------------
2011
2012       procedure Adjust_D is
2013       begin
2014          while Present (Prev (D))
2015            and then Nkind (D) = N_Implicit_Label_Declaration
2016          loop
2017             Prev (D);
2018          end loop;
2019       end Adjust_D;
2020
2021    --  Start of processing for Analyze_Declarations
2022
2023    begin
2024       D := First (L);
2025       while Present (D) loop
2026
2027          --  Complete analysis of declaration
2028
2029          Analyze (D);
2030          Next_Node := Next (D);
2031
2032          if No (Freeze_From) then
2033             Freeze_From := First_Entity (Current_Scope);
2034          end if;
2035
2036          --  At the end of a declarative part, freeze remaining entities
2037          --  declared in it. The end of the visible declarations of package
2038          --  specification is not the end of a declarative part if private
2039          --  declarations are present. The end of a package declaration is a
2040          --  freezing point only if it a library package. A task definition or
2041          --  protected type definition is not a freeze point either. Finally,
2042          --  we do not freeze entities in generic scopes, because there is no
2043          --  code generated for them and freeze nodes will be generated for
2044          --  the instance.
2045
2046          --  The end of a package instantiation is not a freeze point, but
2047          --  for now we make it one, because the generic body is inserted
2048          --  (currently) immediately after. Generic instantiations will not
2049          --  be a freeze point once delayed freezing of bodies is implemented.
2050          --  (This is needed in any case for early instantiations ???).
2051
2052          if No (Next_Node) then
2053             if Nkind_In (Parent (L), N_Component_List,
2054                                      N_Task_Definition,
2055                                      N_Protected_Definition)
2056             then
2057                null;
2058
2059             elsif Nkind (Parent (L)) /= N_Package_Specification then
2060                if Nkind (Parent (L)) = N_Package_Body then
2061                   Freeze_From := First_Entity (Current_Scope);
2062                end if;
2063
2064                Adjust_D;
2065                Freeze_All (Freeze_From, D);
2066                Freeze_From := Last_Entity (Current_Scope);
2067
2068             elsif Scope (Current_Scope) /= Standard_Standard
2069               and then not Is_Child_Unit (Current_Scope)
2070               and then No (Generic_Parent (Parent (L)))
2071             then
2072                null;
2073
2074             elsif L /= Visible_Declarations (Parent (L))
2075                or else No (Private_Declarations (Parent (L)))
2076                or else Is_Empty_List (Private_Declarations (Parent (L)))
2077             then
2078                Adjust_D;
2079                Freeze_All (Freeze_From, D);
2080                Freeze_From := Last_Entity (Current_Scope);
2081             end if;
2082
2083          --  If next node is a body then freeze all types before the body.
2084          --  An exception occurs for some expander-generated bodies. If these
2085          --  are generated at places where in general language rules would not
2086          --  allow a freeze point, then we assume that the expander has
2087          --  explicitly checked that all required types are properly frozen,
2088          --  and we do not cause general freezing here. This special circuit
2089          --  is used when the encountered body is marked as having already
2090          --  been analyzed.
2091
2092          --  In all other cases (bodies that come from source, and expander
2093          --  generated bodies that have not been analyzed yet), freeze all
2094          --  types now. Note that in the latter case, the expander must take
2095          --  care to attach the bodies at a proper place in the tree so as to
2096          --  not cause unwanted freezing at that point.
2097
2098          elsif not Analyzed (Next_Node)
2099            and then (Nkind_In (Next_Node, N_Subprogram_Body,
2100                                           N_Entry_Body,
2101                                           N_Package_Body,
2102                                           N_Protected_Body,
2103                                           N_Task_Body)
2104                        or else
2105                      Nkind (Next_Node) in N_Body_Stub)
2106          then
2107             Adjust_D;
2108             Freeze_All (Freeze_From, D);
2109             Freeze_From := Last_Entity (Current_Scope);
2110          end if;
2111
2112          D := Next_Node;
2113       end loop;
2114    end Analyze_Declarations;
2115
2116    ----------------------------------
2117    -- Analyze_Incomplete_Type_Decl --
2118    ----------------------------------
2119
2120    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2121       F : constant Boolean := Is_Pure (Current_Scope);
2122       T : Entity_Id;
2123
2124    begin
2125       Generate_Definition (Defining_Identifier (N));
2126
2127       --  Process an incomplete declaration. The identifier must not have been
2128       --  declared already in the scope. However, an incomplete declaration may
2129       --  appear in the private part of a package, for a private type that has
2130       --  already been declared.
2131
2132       --  In this case, the discriminants (if any) must match
2133
2134       T := Find_Type_Name (N);
2135
2136       Set_Ekind (T, E_Incomplete_Type);
2137       Init_Size_Align (T);
2138       Set_Is_First_Subtype (T, True);
2139       Set_Etype (T, T);
2140
2141       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2142       --  incomplete types.
2143
2144       if Tagged_Present (N) then
2145          Set_Is_Tagged_Type (T);
2146          Make_Class_Wide_Type (T);
2147          Set_Primitive_Operations (T, New_Elmt_List);
2148       end if;
2149
2150       Push_Scope (T);
2151
2152       Set_Stored_Constraint (T, No_Elist);
2153
2154       if Present (Discriminant_Specifications (N)) then
2155          Process_Discriminants (N);
2156       end if;
2157
2158       End_Scope;
2159
2160       --  If the type has discriminants, non-trivial subtypes may be
2161       --  declared before the full view of the type. The full views of those
2162       --  subtypes will be built after the full view of the type.
2163
2164       Set_Private_Dependents (T, New_Elmt_List);
2165       Set_Is_Pure (T, F);
2166    end Analyze_Incomplete_Type_Decl;
2167
2168    -----------------------------------
2169    -- Analyze_Interface_Declaration --
2170    -----------------------------------
2171
2172    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2173       CW : constant Entity_Id := Class_Wide_Type (T);
2174
2175    begin
2176       Set_Is_Tagged_Type (T);
2177
2178       Set_Is_Limited_Record (T, Limited_Present (Def)
2179                                   or else Task_Present (Def)
2180                                   or else Protected_Present (Def)
2181                                   or else Synchronized_Present (Def));
2182
2183       --  Type is abstract if full declaration carries keyword, or if previous
2184       --  partial view did.
2185
2186       Set_Is_Abstract_Type (T);
2187       Set_Is_Interface (T);
2188
2189       --  Type is a limited interface if it includes the keyword limited, task,
2190       --  protected, or synchronized.
2191
2192       Set_Is_Limited_Interface
2193         (T, Limited_Present (Def)
2194               or else Protected_Present (Def)
2195               or else Synchronized_Present (Def)
2196               or else Task_Present (Def));
2197
2198       Set_Interfaces (T, New_Elmt_List);
2199       Set_Primitive_Operations (T, New_Elmt_List);
2200
2201       --  Complete the decoration of the class-wide entity if it was already
2202       --  built (i.e. during the creation of the limited view)
2203
2204       if Present (CW) then
2205          Set_Is_Interface (CW);
2206          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2207       end if;
2208
2209       --  Check runtime support for synchronized interfaces
2210
2211       if VM_Target = No_VM
2212         and then (Is_Task_Interface (T)
2213                     or else Is_Protected_Interface (T)
2214                     or else Is_Synchronized_Interface (T))
2215         and then not RTE_Available (RE_Select_Specific_Data)
2216       then
2217          Error_Msg_CRT ("synchronized interfaces", T);
2218       end if;
2219    end Analyze_Interface_Declaration;
2220
2221    -----------------------------
2222    -- Analyze_Itype_Reference --
2223    -----------------------------
2224
2225    --  Nothing to do. This node is placed in the tree only for the benefit of
2226    --  back end processing, and has no effect on the semantic processing.
2227
2228    procedure Analyze_Itype_Reference (N : Node_Id) is
2229    begin
2230       pragma Assert (Is_Itype (Itype (N)));
2231       null;
2232    end Analyze_Itype_Reference;
2233
2234    --------------------------------
2235    -- Analyze_Number_Declaration --
2236    --------------------------------
2237
2238    procedure Analyze_Number_Declaration (N : Node_Id) is
2239       Id    : constant Entity_Id := Defining_Identifier (N);
2240       E     : constant Node_Id   := Expression (N);
2241       T     : Entity_Id;
2242       Index : Interp_Index;
2243       It    : Interp;
2244
2245    begin
2246       Generate_Definition (Id);
2247       Enter_Name (Id);
2248
2249       --  This is an optimization of a common case of an integer literal
2250
2251       if Nkind (E) = N_Integer_Literal then
2252          Set_Is_Static_Expression (E, True);
2253          Set_Etype                (E, Universal_Integer);
2254
2255          Set_Etype     (Id, Universal_Integer);
2256          Set_Ekind     (Id, E_Named_Integer);
2257          Set_Is_Frozen (Id, True);
2258          return;
2259       end if;
2260
2261       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2262
2263       --  Process expression, replacing error by integer zero, to avoid
2264       --  cascaded errors or aborts further along in the processing
2265
2266       --  Replace Error by integer zero, which seems least likely to
2267       --  cause cascaded errors.
2268
2269       if E = Error then
2270          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2271          Set_Error_Posted (E);
2272       end if;
2273
2274       Analyze (E);
2275
2276       --  Verify that the expression is static and numeric. If
2277       --  the expression is overloaded, we apply the preference
2278       --  rule that favors root numeric types.
2279
2280       if not Is_Overloaded (E) then
2281          T := Etype (E);
2282
2283       else
2284          T := Any_Type;
2285
2286          Get_First_Interp (E, Index, It);
2287          while Present (It.Typ) loop
2288             if (Is_Integer_Type (It.Typ)
2289                  or else Is_Real_Type (It.Typ))
2290               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2291             then
2292                if T = Any_Type then
2293                   T := It.Typ;
2294
2295                elsif It.Typ = Universal_Real
2296                  or else It.Typ = Universal_Integer
2297                then
2298                   --  Choose universal interpretation over any other
2299
2300                   T := It.Typ;
2301                   exit;
2302                end if;
2303             end if;
2304
2305             Get_Next_Interp (Index, It);
2306          end loop;
2307       end if;
2308
2309       if Is_Integer_Type (T)  then
2310          Resolve (E, T);
2311          Set_Etype (Id, Universal_Integer);
2312          Set_Ekind (Id, E_Named_Integer);
2313
2314       elsif Is_Real_Type (T) then
2315
2316          --  Because the real value is converted to universal_real, this is a
2317          --  legal context for a universal fixed expression.
2318
2319          if T = Universal_Fixed then
2320             declare
2321                Loc  : constant Source_Ptr := Sloc (N);
2322                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2323                         Subtype_Mark =>
2324                           New_Occurrence_Of (Universal_Real, Loc),
2325                         Expression => Relocate_Node (E));
2326
2327             begin
2328                Rewrite (E, Conv);
2329                Analyze (E);
2330             end;
2331
2332          elsif T = Any_Fixed then
2333             Error_Msg_N ("illegal context for mixed mode operation", E);
2334
2335             --  Expression is of the form : universal_fixed * integer. Try to
2336             --  resolve as universal_real.
2337
2338             T := Universal_Real;
2339             Set_Etype (E, T);
2340          end if;
2341
2342          Resolve (E, T);
2343          Set_Etype (Id, Universal_Real);
2344          Set_Ekind (Id, E_Named_Real);
2345
2346       else
2347          Wrong_Type (E, Any_Numeric);
2348          Resolve (E, T);
2349
2350          Set_Etype               (Id, T);
2351          Set_Ekind               (Id, E_Constant);
2352          Set_Never_Set_In_Source (Id, True);
2353          Set_Is_True_Constant    (Id, True);
2354          return;
2355       end if;
2356
2357       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2358          Set_Etype (E, Etype (Id));
2359       end if;
2360
2361       if not Is_OK_Static_Expression (E) then
2362          Flag_Non_Static_Expr
2363            ("non-static expression used in number declaration!", E);
2364          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2365          Set_Etype (E, Any_Type);
2366       end if;
2367    end Analyze_Number_Declaration;
2368
2369    --------------------------------
2370    -- Analyze_Object_Declaration --
2371    --------------------------------
2372
2373    procedure Analyze_Object_Declaration (N : Node_Id) is
2374       Loc   : constant Source_Ptr := Sloc (N);
2375       Id    : constant Entity_Id  := Defining_Identifier (N);
2376       T     : Entity_Id;
2377       Act_T : Entity_Id;
2378
2379       E : Node_Id := Expression (N);
2380       --  E is set to Expression (N) throughout this routine. When
2381       --  Expression (N) is modified, E is changed accordingly.
2382
2383       Prev_Entity : Entity_Id := Empty;
2384
2385       function Count_Tasks (T : Entity_Id) return Uint;
2386       --  This function is called when a non-generic library level object of a
2387       --  task type is declared. Its function is to count the static number of
2388       --  tasks declared within the type (it is only called if Has_Tasks is set
2389       --  for T). As a side effect, if an array of tasks with non-static bounds
2390       --  or a variant record type is encountered, Check_Restrictions is called
2391       --  indicating the count is unknown.
2392
2393       -----------------
2394       -- Count_Tasks --
2395       -----------------
2396
2397       function Count_Tasks (T : Entity_Id) return Uint is
2398          C : Entity_Id;
2399          X : Node_Id;
2400          V : Uint;
2401
2402       begin
2403          if Is_Task_Type (T) then
2404             return Uint_1;
2405
2406          elsif Is_Record_Type (T) then
2407             if Has_Discriminants (T) then
2408                Check_Restriction (Max_Tasks, N);
2409                return Uint_0;
2410
2411             else
2412                V := Uint_0;
2413                C := First_Component (T);
2414                while Present (C) loop
2415                   V := V + Count_Tasks (Etype (C));
2416                   Next_Component (C);
2417                end loop;
2418
2419                return V;
2420             end if;
2421
2422          elsif Is_Array_Type (T) then
2423             X := First_Index (T);
2424             V := Count_Tasks (Component_Type (T));
2425             while Present (X) loop
2426                C := Etype (X);
2427
2428                if not Is_Static_Subtype (C) then
2429                   Check_Restriction (Max_Tasks, N);
2430                   return Uint_0;
2431                else
2432                   V := V * (UI_Max (Uint_0,
2433                                     Expr_Value (Type_High_Bound (C)) -
2434                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2435                end if;
2436
2437                Next_Index (X);
2438             end loop;
2439
2440             return V;
2441
2442          else
2443             return Uint_0;
2444          end if;
2445       end Count_Tasks;
2446
2447    --  Start of processing for Analyze_Object_Declaration
2448
2449    begin
2450       --  There are three kinds of implicit types generated by an
2451       --  object declaration:
2452
2453       --   1. Those for generated by the original Object Definition
2454
2455       --   2. Those generated by the Expression
2456
2457       --   3. Those used to constrained the Object Definition with the
2458       --       expression constraints when it is unconstrained
2459
2460       --  They must be generated in this order to avoid order of elaboration
2461       --  issues. Thus the first step (after entering the name) is to analyze
2462       --  the object definition.
2463
2464       if Constant_Present (N) then
2465          Prev_Entity := Current_Entity_In_Scope (Id);
2466
2467          if Present (Prev_Entity)
2468            and then
2469              --  If the homograph is an implicit subprogram, it is overridden
2470              --  by the current declaration.
2471
2472              ((Is_Overloadable (Prev_Entity)
2473                 and then Is_Inherited_Operation (Prev_Entity))
2474
2475                --  The current object is a discriminal generated for an entry
2476                --  family index. Even though the index is a constant, in this
2477                --  particular context there is no true constant redeclaration.
2478                --  Enter_Name will handle the visibility.
2479
2480                or else
2481                 (Is_Discriminal (Id)
2482                    and then Ekind (Discriminal_Link (Id)) =
2483                               E_Entry_Index_Parameter)
2484
2485                --  The current object is the renaming for a generic declared
2486                --  within the instance.
2487
2488                or else
2489                 (Ekind (Prev_Entity) = E_Package
2490                   and then Nkind (Parent (Prev_Entity)) =
2491                                          N_Package_Renaming_Declaration
2492                   and then not Comes_From_Source (Prev_Entity)
2493                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
2494          then
2495             Prev_Entity := Empty;
2496          end if;
2497       end if;
2498
2499       if Present (Prev_Entity) then
2500          Constant_Redeclaration (Id, N, T);
2501
2502          Generate_Reference (Prev_Entity, Id, 'c');
2503          Set_Completion_Referenced (Id);
2504
2505          if Error_Posted (N) then
2506
2507             --  Type mismatch or illegal redeclaration, Do not analyze
2508             --  expression to avoid cascaded errors.
2509
2510             T := Find_Type_Of_Object (Object_Definition (N), N);
2511             Set_Etype (Id, T);
2512             Set_Ekind (Id, E_Variable);
2513             return;
2514          end if;
2515
2516       --  In the normal case, enter identifier at the start to catch premature
2517       --  usage in the initialization expression.
2518
2519       else
2520          Generate_Definition (Id);
2521          Enter_Name (Id);
2522
2523          Mark_Coextensions (N, Object_Definition (N));
2524
2525          T := Find_Type_Of_Object (Object_Definition (N), N);
2526
2527          if Nkind (Object_Definition (N)) = N_Access_Definition
2528            and then Present
2529              (Access_To_Subprogram_Definition (Object_Definition (N)))
2530            and then Protected_Present
2531              (Access_To_Subprogram_Definition (Object_Definition (N)))
2532          then
2533             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2534          end if;
2535
2536          if Error_Posted (Id) then
2537             Set_Etype (Id, T);
2538             Set_Ekind (Id, E_Variable);
2539             return;
2540          end if;
2541       end if;
2542
2543       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2544       --  out some static checks
2545
2546       if Ada_Version >= Ada_05
2547         and then Can_Never_Be_Null (T)
2548       then
2549          --  In case of aggregates we must also take care of the correct
2550          --  initialization of nested aggregates bug this is done at the
2551          --  point of the analysis of the aggregate (see sem_aggr.adb)
2552
2553          if Present (Expression (N))
2554            and then Nkind (Expression (N)) = N_Aggregate
2555          then
2556             null;
2557
2558          else
2559             declare
2560                Save_Typ : constant Entity_Id := Etype (Id);
2561             begin
2562                Set_Etype (Id, T); --  Temp. decoration for static checks
2563                Null_Exclusion_Static_Checks (N);
2564                Set_Etype (Id, Save_Typ);
2565             end;
2566          end if;
2567       end if;
2568
2569       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2570
2571       --  If deferred constant, make sure context is appropriate. We detect
2572       --  a deferred constant as a constant declaration with no expression.
2573       --  A deferred constant can appear in a package body if its completion
2574       --  is by means of an interface pragma.
2575
2576       if Constant_Present (N)
2577         and then No (E)
2578       then
2579          --  A deferred constant may appear in the declarative part of the
2580          --  following constructs:
2581
2582          --     blocks
2583          --     entry bodies
2584          --     extended return statements
2585          --     package specs
2586          --     package bodies
2587          --     subprogram bodies
2588          --     task bodies
2589
2590          --  When declared inside a package spec, a deferred constant must be
2591          --  completed by a full constant declaration or pragma Import. In all
2592          --  other cases, the only proper completion is pragma Import. Extended
2593          --  return statements are flagged as invalid contexts because they do
2594          --  not have a declarative part and so cannot accommodate the pragma.
2595
2596          if Ekind (Current_Scope) = E_Return_Statement then
2597             Error_Msg_N
2598               ("invalid context for deferred constant declaration (RM 7.4)",
2599                N);
2600             Error_Msg_N
2601               ("\declaration requires an initialization expression",
2602                 N);
2603             Set_Constant_Present (N, False);
2604
2605          --  In Ada 83, deferred constant must be of private type
2606
2607          elsif not Is_Private_Type (T) then
2608             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
2609                Error_Msg_N
2610                  ("(Ada 83) deferred constant must be private type", N);
2611             end if;
2612          end if;
2613
2614       --  If not a deferred constant, then object declaration freezes its type
2615
2616       else
2617          Check_Fully_Declared (T, N);
2618          Freeze_Before (N, T);
2619       end if;
2620
2621       --  If the object was created by a constrained array definition, then
2622       --  set the link in both the anonymous base type and anonymous subtype
2623       --  that are built to represent the array type to point to the object.
2624
2625       if Nkind (Object_Definition (Declaration_Node (Id))) =
2626                         N_Constrained_Array_Definition
2627       then
2628          Set_Related_Array_Object (T, Id);
2629          Set_Related_Array_Object (Base_Type (T), Id);
2630       end if;
2631
2632       --  Special checks for protected objects not at library level
2633
2634       if Is_Protected_Type (T)
2635         and then not Is_Library_Level_Entity (Id)
2636       then
2637          Check_Restriction (No_Local_Protected_Objects, Id);
2638
2639          --  Protected objects with interrupt handlers must be at library level
2640
2641          --  Ada 2005: this test is not needed (and the corresponding clause
2642          --  in the RM is removed) because accessibility checks are sufficient
2643          --  to make handlers not at the library level illegal.
2644
2645          if Has_Interrupt_Handler (T)
2646            and then Ada_Version < Ada_05
2647          then
2648             Error_Msg_N
2649               ("interrupt object can only be declared at library level", Id);
2650          end if;
2651       end if;
2652
2653       --  The actual subtype of the object is the nominal subtype, unless
2654       --  the nominal one is unconstrained and obtained from the expression.
2655
2656       Act_T := T;
2657
2658       --  Process initialization expression if present and not in error
2659
2660       if Present (E) and then E /= Error then
2661
2662          --  Generate an error in case of CPP class-wide object initialization.
2663          --  Required because otherwise the expansion of the class-wide
2664          --  assignment would try to use 'size to initialize the object
2665          --  (primitive that is not available in CPP tagged types).
2666
2667          if Is_Class_Wide_Type (Act_T)
2668            and then
2669              (Is_CPP_Class (Root_Type (Etype (Act_T)))
2670                or else
2671                  (Present (Full_View (Root_Type (Etype (Act_T))))
2672                     and then
2673                       Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
2674          then
2675             Error_Msg_N
2676               ("predefined assignment not available for 'C'P'P tagged types",
2677                E);
2678          end if;
2679
2680          Mark_Coextensions (N, E);
2681          Analyze (E);
2682
2683          --  In case of errors detected in the analysis of the expression,
2684          --  decorate it with the expected type to avoid cascaded errors
2685
2686          if No (Etype (E)) then
2687             Set_Etype (E, T);
2688          end if;
2689
2690          --  If an initialization expression is present, then we set the
2691          --  Is_True_Constant flag. It will be reset if this is a variable
2692          --  and it is indeed modified.
2693
2694          Set_Is_True_Constant (Id, True);
2695
2696          --  If we are analyzing a constant declaration, set its completion
2697          --  flag after analyzing and resolving the expression.
2698
2699          if Constant_Present (N) then
2700             Set_Has_Completion (Id);
2701          end if;
2702
2703          --  Set type and resolve (type may be overridden later on)
2704
2705          Set_Etype (Id, T);
2706          Resolve (E, T);
2707
2708          --  If E is null and has been replaced by an N_Raise_Constraint_Error
2709          --  node (which was marked already-analyzed), we need to set the type
2710          --  to something other than Any_Access in order to keep gigi happy.
2711
2712          if Etype (E) = Any_Access then
2713             Set_Etype (E, T);
2714          end if;
2715
2716          --  If the object is an access to variable, the initialization
2717          --  expression cannot be an access to constant.
2718
2719          if Is_Access_Type (T)
2720            and then not Is_Access_Constant (T)
2721            and then Is_Access_Type (Etype (E))
2722            and then Is_Access_Constant (Etype (E))
2723          then
2724             Error_Msg_N
2725               ("access to variable cannot be initialized "
2726                & "with an access-to-constant expression", E);
2727          end if;
2728
2729          if not Assignment_OK (N) then
2730             Check_Initialization (T, E);
2731          end if;
2732
2733          Check_Unset_Reference (E);
2734
2735          --  If this is a variable, then set current value. If this is a
2736          --  declared constant of a scalar type with a static expression,
2737          --  indicate that it is always valid.
2738
2739          if not Constant_Present (N) then
2740             if Compile_Time_Known_Value (E) then
2741                Set_Current_Value (Id, E);
2742             end if;
2743
2744          elsif Is_Scalar_Type (T)
2745            and then Is_OK_Static_Expression (E)
2746          then
2747             Set_Is_Known_Valid (Id);
2748          end if;
2749
2750          --  Deal with setting of null flags
2751
2752          if Is_Access_Type (T) then
2753             if Known_Non_Null (E) then
2754                Set_Is_Known_Non_Null (Id, True);
2755             elsif Known_Null (E)
2756               and then not Can_Never_Be_Null (Id)
2757             then
2758                Set_Is_Known_Null (Id, True);
2759             end if;
2760          end if;
2761
2762          --  Check incorrect use of dynamically tagged expressions.
2763
2764          if Is_Tagged_Type (T) then
2765             Check_Dynamically_Tagged_Expression
2766               (Expr        => E,
2767                Typ         => T,
2768                Related_Nod => N);
2769          end if;
2770
2771          Apply_Scalar_Range_Check (E, T);
2772          Apply_Static_Length_Check (E, T);
2773       end if;
2774
2775       --  If the No_Streams restriction is set, check that the type of the
2776       --  object is not, and does not contain, any subtype derived from
2777       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
2778       --  Has_Stream just for efficiency reasons. There is no point in
2779       --  spending time on a Has_Stream check if the restriction is not set.
2780
2781       if Restriction_Check_Required (No_Streams) then
2782          if Has_Stream (T) then
2783             Check_Restriction (No_Streams, N);
2784          end if;
2785       end if;
2786
2787       --  Case of unconstrained type
2788
2789       if Is_Indefinite_Subtype (T) then
2790
2791          --  Nothing to do in deferred constant case
2792
2793          if Constant_Present (N) and then No (E) then
2794             null;
2795
2796          --  Case of no initialization present
2797
2798          elsif No (E) then
2799             if No_Initialization (N) then
2800                null;
2801
2802             elsif Is_Class_Wide_Type (T) then
2803                Error_Msg_N
2804                  ("initialization required in class-wide declaration ", N);
2805
2806             else
2807                Error_Msg_N
2808                  ("unconstrained subtype not allowed (need initialization)",
2809                   Object_Definition (N));
2810
2811                if Is_Record_Type (T) and then Has_Discriminants (T) then
2812                   Error_Msg_N
2813                     ("\provide initial value or explicit discriminant values",
2814                      Object_Definition (N));
2815
2816                   Error_Msg_NE
2817                     ("\or give default discriminant values for type&",
2818                      Object_Definition (N), T);
2819
2820                elsif Is_Array_Type (T) then
2821                   Error_Msg_N
2822                     ("\provide initial value or explicit array bounds",
2823                      Object_Definition (N));
2824                end if;
2825             end if;
2826
2827          --  Case of initialization present but in error. Set initial
2828          --  expression as absent (but do not make above complaints)
2829
2830          elsif E = Error then
2831             Set_Expression (N, Empty);
2832             E := Empty;
2833
2834          --  Case of initialization present
2835
2836          else
2837             --  Not allowed in Ada 83
2838
2839             if not Constant_Present (N) then
2840                if Ada_Version = Ada_83
2841                  and then Comes_From_Source (Object_Definition (N))
2842                then
2843                   Error_Msg_N
2844                     ("(Ada 83) unconstrained variable not allowed",
2845                      Object_Definition (N));
2846                end if;
2847             end if;
2848
2849             --  Now we constrain the variable from the initializing expression
2850
2851             --  If the expression is an aggregate, it has been expanded into
2852             --  individual assignments. Retrieve the actual type from the
2853             --  expanded construct.
2854
2855             if Is_Array_Type (T)
2856               and then No_Initialization (N)
2857               and then Nkind (Original_Node (E)) = N_Aggregate
2858             then
2859                Act_T := Etype (E);
2860
2861             --  In case of class-wide interface object declarations we delay
2862             --  the generation of the equivalent record type declarations until
2863             --  its expansion because there are cases in they are not required.
2864
2865             elsif Is_Interface (T) then
2866                null;
2867
2868             else
2869                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
2870                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
2871             end if;
2872
2873             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
2874
2875             if Aliased_Present (N) then
2876                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
2877             end if;
2878
2879             Freeze_Before (N, Act_T);
2880             Freeze_Before (N, T);
2881          end if;
2882
2883       elsif Is_Array_Type (T)
2884         and then No_Initialization (N)
2885         and then Nkind (Original_Node (E)) = N_Aggregate
2886       then
2887          if not Is_Entity_Name (Object_Definition (N)) then
2888             Act_T := Etype (E);
2889             Check_Compile_Time_Size (Act_T);
2890
2891             if Aliased_Present (N) then
2892                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
2893             end if;
2894          end if;
2895
2896          --  When the given object definition and the aggregate are specified
2897          --  independently, and their lengths might differ do a length check.
2898          --  This cannot happen if the aggregate is of the form (others =>...)
2899
2900          if not Is_Constrained (T) then
2901             null;
2902
2903          elsif Nkind (E) = N_Raise_Constraint_Error then
2904
2905             --  Aggregate is statically illegal. Place back in declaration
2906
2907             Set_Expression (N, E);
2908             Set_No_Initialization (N, False);
2909
2910          elsif T = Etype (E) then
2911             null;
2912
2913          elsif Nkind (E) = N_Aggregate
2914            and then Present (Component_Associations (E))
2915            and then Present (Choices (First (Component_Associations (E))))
2916            and then Nkind (First
2917             (Choices (First (Component_Associations (E))))) = N_Others_Choice
2918          then
2919             null;
2920
2921          else
2922             Apply_Length_Check (E, T);
2923          end if;
2924
2925       --  If the type is limited unconstrained with defaulted discriminants and
2926       --  there is no expression, then the object is constrained by the
2927       --  defaults, so it is worthwhile building the corresponding subtype.
2928
2929       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
2930         and then not Is_Constrained (T)
2931         and then Has_Discriminants (T)
2932       then
2933          if No (E) then
2934             Act_T := Build_Default_Subtype (T, N);
2935          else
2936             --  Ada 2005:  a limited object may be initialized by means of an
2937             --  aggregate. If the type has default discriminants it has an
2938             --  unconstrained nominal type, Its actual subtype will be obtained
2939             --  from the aggregate, and not from the default discriminants.
2940
2941             Act_T := Etype (E);
2942          end if;
2943
2944          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
2945
2946       elsif Present (Underlying_Type (T))
2947         and then not Is_Constrained (Underlying_Type (T))
2948         and then Has_Discriminants (Underlying_Type (T))
2949         and then Nkind (E) = N_Function_Call
2950         and then Constant_Present (N)
2951       then
2952          --  The back-end has problems with constants of a discriminated type
2953          --  with defaults, if the initial value is a function call. We
2954          --  generate an intermediate temporary for the result of the call.
2955          --  It is unclear why this should make it acceptable to gcc. ???
2956
2957          Remove_Side_Effects (E);
2958       end if;
2959
2960       --  Check No_Wide_Characters restriction
2961
2962       Check_Wide_Character_Restriction (T, Object_Definition (N));
2963
2964       --  Indicate this is not set in source. Certainly true for constants,
2965       --  and true for variables so far (will be reset for a variable if and
2966       --  when we encounter a modification in the source).
2967
2968       Set_Never_Set_In_Source (Id, True);
2969
2970       --  Now establish the proper kind and type of the object
2971
2972       if Constant_Present (N) then
2973          Set_Ekind            (Id, E_Constant);
2974          Set_Is_True_Constant (Id, True);
2975
2976       else
2977          Set_Ekind (Id, E_Variable);
2978
2979          --  A variable is set as shared passive if it appears in a shared
2980          --  passive package, and is at the outer level. This is not done
2981          --  for entities generated during expansion, because those are
2982          --  always manipulated locally.
2983
2984          if Is_Shared_Passive (Current_Scope)
2985            and then Is_Library_Level_Entity (Id)
2986            and then Comes_From_Source (Id)
2987          then
2988             Set_Is_Shared_Passive (Id);
2989             Check_Shared_Var (Id, T, N);
2990          end if;
2991
2992          --  Set Has_Initial_Value if initializing expression present. Note
2993          --  that if there is no initializing expression, we leave the state
2994          --  of this flag unchanged (usually it will be False, but notably in
2995          --  the case of exception choice variables, it will already be true).
2996
2997          if Present (E) then
2998             Set_Has_Initial_Value (Id, True);
2999          end if;
3000       end if;
3001
3002       --  Initialize alignment and size and capture alignment setting
3003
3004       Init_Alignment               (Id);
3005       Init_Esize                   (Id);
3006       Set_Optimize_Alignment_Flags (Id);
3007
3008       --  Deal with aliased case
3009
3010       if Aliased_Present (N) then
3011          Set_Is_Aliased (Id);
3012
3013          --  If the object is aliased and the type is unconstrained with
3014          --  defaulted discriminants and there is no expression, then the
3015          --  object is constrained by the defaults, so it is worthwhile
3016          --  building the corresponding subtype.
3017
3018          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3019          --  unconstrained, then only establish an actual subtype if the
3020          --  nominal subtype is indefinite. In definite cases the object is
3021          --  unconstrained in Ada 2005.
3022
3023          if No (E)
3024            and then Is_Record_Type (T)
3025            and then not Is_Constrained (T)
3026            and then Has_Discriminants (T)
3027            and then (Ada_Version < Ada_05 or else Is_Indefinite_Subtype (T))
3028          then
3029             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3030          end if;
3031       end if;
3032
3033       --  Now we can set the type of the object
3034
3035       Set_Etype (Id, Act_T);
3036
3037       --  Deal with controlled types
3038
3039       if Has_Controlled_Component (Etype (Id))
3040         or else Is_Controlled (Etype (Id))
3041       then
3042          if not Is_Library_Level_Entity (Id) then
3043             Check_Restriction (No_Nested_Finalization, N);
3044          else
3045             Validate_Controlled_Object (Id);
3046          end if;
3047
3048          --  Generate a warning when an initialization causes an obvious ABE
3049          --  violation. If the init expression is a simple aggregate there
3050          --  shouldn't be any initialize/adjust call generated. This will be
3051          --  true as soon as aggregates are built in place when possible.
3052
3053          --  ??? at the moment we do not generate warnings for temporaries
3054          --  created for those aggregates although Program_Error might be
3055          --  generated if compiled with -gnato.
3056
3057          if Is_Controlled (Etype (Id))
3058             and then Comes_From_Source (Id)
3059          then
3060             declare
3061                BT : constant Entity_Id := Base_Type (Etype (Id));
3062
3063                Implicit_Call : Entity_Id;
3064                pragma Warnings (Off, Implicit_Call);
3065                --  ??? what is this for (never referenced!)
3066
3067                function Is_Aggr (N : Node_Id) return Boolean;
3068                --  Check that N is an aggregate
3069
3070                -------------
3071                -- Is_Aggr --
3072                -------------
3073
3074                function Is_Aggr (N : Node_Id) return Boolean is
3075                begin
3076                   case Nkind (Original_Node (N)) is
3077                      when N_Aggregate | N_Extension_Aggregate =>
3078                         return True;
3079
3080                      when N_Qualified_Expression |
3081                           N_Type_Conversion      |
3082                           N_Unchecked_Type_Conversion =>
3083                         return Is_Aggr (Expression (Original_Node (N)));
3084
3085                      when others =>
3086                         return False;
3087                   end case;
3088                end Is_Aggr;
3089
3090             begin
3091                --  If no underlying type, we already are in an error situation.
3092                --  Do not try to add a warning since we do not have access to
3093                --  prim-op list.
3094
3095                if No (Underlying_Type (BT)) then
3096                   Implicit_Call := Empty;
3097
3098                --  A generic type does not have usable primitive operators.
3099                --  Initialization calls are built for instances.
3100
3101                elsif Is_Generic_Type (BT) then
3102                   Implicit_Call := Empty;
3103
3104                --  If the init expression is not an aggregate, an adjust call
3105                --  will be generated
3106
3107                elsif Present (E) and then not Is_Aggr (E) then
3108                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
3109
3110                --  If no init expression and we are not in the deferred
3111                --  constant case, an Initialize call will be generated
3112
3113                elsif No (E) and then not Constant_Present (N) then
3114                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
3115
3116                else
3117                   Implicit_Call := Empty;
3118                end if;
3119             end;
3120          end if;
3121       end if;
3122
3123       if Has_Task (Etype (Id)) then
3124          Check_Restriction (No_Tasking, N);
3125
3126          --  Deal with counting max tasks
3127
3128          --  Nothing to do if inside a generic
3129
3130          if Inside_A_Generic then
3131             null;
3132
3133          --  If library level entity, then count tasks
3134
3135          elsif Is_Library_Level_Entity (Id) then
3136             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3137
3138          --  If not library level entity, then indicate we don't know max
3139          --  tasks and also check task hierarchy restriction and blocking
3140          --  operation (since starting a task is definitely blocking!)
3141
3142          else
3143             Check_Restriction (Max_Tasks, N);
3144             Check_Restriction (No_Task_Hierarchy, N);
3145             Check_Potentially_Blocking_Operation (N);
3146          end if;
3147
3148          --  A rather specialized test. If we see two tasks being declared
3149          --  of the same type in the same object declaration, and the task
3150          --  has an entry with an address clause, we know that program error
3151          --  will be raised at run time since we can't have two tasks with
3152          --  entries at the same address.
3153
3154          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3155             declare
3156                E : Entity_Id;
3157
3158             begin
3159                E := First_Entity (Etype (Id));
3160                while Present (E) loop
3161                   if Ekind (E) = E_Entry
3162                     and then Present (Get_Attribute_Definition_Clause
3163                                         (E, Attribute_Address))
3164                   then
3165                      Error_Msg_N
3166                        ("?more than one task with same entry address", N);
3167                      Error_Msg_N
3168                        ("\?Program_Error will be raised at run time", N);
3169                      Insert_Action (N,
3170                        Make_Raise_Program_Error (Loc,
3171                          Reason => PE_Duplicated_Entry_Address));
3172                      exit;
3173                   end if;
3174
3175                   Next_Entity (E);
3176                end loop;
3177             end;
3178          end if;
3179       end if;
3180
3181       --  Some simple constant-propagation: if the expression is a constant
3182       --  string initialized with a literal, share the literal. This avoids
3183       --  a run-time copy.
3184
3185       if Present (E)
3186         and then Is_Entity_Name (E)
3187         and then Ekind (Entity (E)) = E_Constant
3188         and then Base_Type (Etype (E)) = Standard_String
3189       then
3190          declare
3191             Val : constant Node_Id := Constant_Value (Entity (E));
3192          begin
3193             if Present (Val)
3194               and then Nkind (Val) = N_String_Literal
3195             then
3196                Rewrite (E, New_Copy (Val));
3197             end if;
3198          end;
3199       end if;
3200
3201       --  Another optimization: if the nominal subtype is unconstrained and
3202       --  the expression is a function call that returns an unconstrained
3203       --  type, rewrite the declaration as a renaming of the result of the
3204       --  call. The exceptions below are cases where the copy is expected,
3205       --  either by the back end (Aliased case) or by the semantics, as for
3206       --  initializing controlled types or copying tags for classwide types.
3207
3208       if Present (E)
3209         and then Nkind (E) = N_Explicit_Dereference
3210         and then Nkind (Original_Node (E)) = N_Function_Call
3211         and then not Is_Library_Level_Entity (Id)
3212         and then not Is_Constrained (Underlying_Type (T))
3213         and then not Is_Aliased (Id)
3214         and then not Is_Class_Wide_Type (T)
3215         and then not Is_Controlled (T)
3216         and then not Has_Controlled_Component (Base_Type (T))
3217         and then Expander_Active
3218       then
3219          Rewrite (N,
3220            Make_Object_Renaming_Declaration (Loc,
3221              Defining_Identifier => Id,
3222              Access_Definition   => Empty,
3223              Subtype_Mark        => New_Occurrence_Of
3224                                       (Base_Type (Etype (Id)), Loc),
3225              Name                => E));
3226
3227          Set_Renamed_Object (Id, E);
3228
3229          --  Force generation of debugging information for the constant and for
3230          --  the renamed function call.
3231
3232          Set_Debug_Info_Needed (Id);
3233          Set_Debug_Info_Needed (Entity (Prefix (E)));
3234       end if;
3235
3236       if Present (Prev_Entity)
3237         and then Is_Frozen (Prev_Entity)
3238         and then not Error_Posted (Id)
3239       then
3240          Error_Msg_N ("full constant declaration appears too late", N);
3241       end if;
3242
3243       Check_Eliminated (Id);
3244
3245       --  Deal with setting In_Private_Part flag if in private part
3246
3247       if Ekind (Scope (Id)) = E_Package
3248         and then In_Private_Part (Scope (Id))
3249       then
3250          Set_In_Private_Part (Id);
3251       end if;
3252
3253       --  Check for violation of No_Local_Timing_Events
3254
3255       if Is_RTE (Etype (Id), RE_Timing_Event)
3256         and then not Is_Library_Level_Entity (Id)
3257       then
3258          Check_Restriction (No_Local_Timing_Events, N);
3259       end if;
3260    end Analyze_Object_Declaration;
3261
3262    ---------------------------
3263    -- Analyze_Others_Choice --
3264    ---------------------------
3265
3266    --  Nothing to do for the others choice node itself, the semantic analysis
3267    --  of the others choice will occur as part of the processing of the parent
3268
3269    procedure Analyze_Others_Choice (N : Node_Id) is
3270       pragma Warnings (Off, N);
3271    begin
3272       null;
3273    end Analyze_Others_Choice;
3274
3275    -------------------------------------------
3276    -- Analyze_Private_Extension_Declaration --
3277    -------------------------------------------
3278
3279    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3280       T           : constant Entity_Id := Defining_Identifier (N);
3281       Indic       : constant Node_Id   := Subtype_Indication (N);
3282       Parent_Type : Entity_Id;
3283       Parent_Base : Entity_Id;
3284
3285    begin
3286       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3287
3288       if Is_Non_Empty_List (Interface_List (N)) then
3289          declare
3290             Intf : Node_Id;
3291             T    : Entity_Id;
3292
3293          begin
3294             Intf := First (Interface_List (N));
3295             while Present (Intf) loop
3296                T := Find_Type_Of_Subtype_Indic (Intf);
3297
3298                Diagnose_Interface (Intf, T);
3299                Next (Intf);
3300             end loop;
3301          end;
3302       end if;
3303
3304       Generate_Definition (T);
3305       Enter_Name (T);
3306
3307       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3308       Parent_Base := Base_Type (Parent_Type);
3309
3310       if Parent_Type = Any_Type
3311         or else Etype (Parent_Type) = Any_Type
3312       then
3313          Set_Ekind (T, Ekind (Parent_Type));
3314          Set_Etype (T, Any_Type);
3315          return;
3316
3317       elsif not Is_Tagged_Type (Parent_Type) then
3318          Error_Msg_N
3319            ("parent of type extension must be a tagged type ", Indic);
3320          return;
3321
3322       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3323          Error_Msg_N ("premature derivation of incomplete type", Indic);
3324          return;
3325
3326       elsif Is_Concurrent_Type (Parent_Type) then
3327          Error_Msg_N
3328            ("parent type of a private extension cannot be "
3329             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3330
3331          Set_Etype              (T, Any_Type);
3332          Set_Ekind              (T, E_Limited_Private_Type);
3333          Set_Private_Dependents (T, New_Elmt_List);
3334          Set_Error_Posted       (T);
3335          return;
3336       end if;
3337
3338       --  Perhaps the parent type should be changed to the class-wide type's
3339       --  specific type in this case to prevent cascading errors ???
3340
3341       if Is_Class_Wide_Type (Parent_Type) then
3342          Error_Msg_N
3343            ("parent of type extension must not be a class-wide type", Indic);
3344          return;
3345       end if;
3346
3347       if (not Is_Package_Or_Generic_Package (Current_Scope)
3348            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3349         or else In_Private_Part (Current_Scope)
3350
3351       then
3352          Error_Msg_N ("invalid context for private extension", N);
3353       end if;
3354
3355       --  Set common attributes
3356
3357       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3358       Set_Scope            (T, Current_Scope);
3359       Set_Ekind            (T, E_Record_Type_With_Private);
3360       Init_Size_Align      (T);
3361
3362       Set_Etype            (T,            Parent_Base);
3363       Set_Has_Task         (T, Has_Task  (Parent_Base));
3364
3365       Set_Convention       (T, Convention     (Parent_Type));
3366       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3367       Set_Is_First_Subtype (T);
3368       Make_Class_Wide_Type (T);
3369
3370       if Unknown_Discriminants_Present (N) then
3371          Set_Discriminant_Constraint (T, No_Elist);
3372       end if;
3373
3374       Build_Derived_Record_Type (N, Parent_Type, T);
3375
3376       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3377       --  synchronized formal derived type.
3378
3379       if Ada_Version >= Ada_05
3380         and then Synchronized_Present (N)
3381       then
3382          Set_Is_Limited_Record (T);
3383
3384          --  Formal derived type case
3385
3386          if Is_Generic_Type (T) then
3387
3388             --  The parent must be a tagged limited type or a synchronized
3389             --  interface.
3390
3391             if (not Is_Tagged_Type (Parent_Type)
3392                   or else not Is_Limited_Type (Parent_Type))
3393               and then
3394                (not Is_Interface (Parent_Type)
3395                   or else not Is_Synchronized_Interface (Parent_Type))
3396             then
3397                Error_Msg_NE ("parent type of & must be tagged limited " &
3398                              "or synchronized", N, T);
3399             end if;
3400
3401             --  The progenitors (if any) must be limited or synchronized
3402             --  interfaces.
3403
3404             if Present (Interfaces (T)) then
3405                declare
3406                   Iface      : Entity_Id;
3407                   Iface_Elmt : Elmt_Id;
3408
3409                begin
3410                   Iface_Elmt := First_Elmt (Interfaces (T));
3411                   while Present (Iface_Elmt) loop
3412                      Iface := Node (Iface_Elmt);
3413
3414                      if not Is_Limited_Interface (Iface)
3415                        and then not Is_Synchronized_Interface (Iface)
3416                      then
3417                         Error_Msg_NE ("progenitor & must be limited " &
3418                                       "or synchronized", N, Iface);
3419                      end if;
3420
3421                      Next_Elmt (Iface_Elmt);
3422                   end loop;
3423                end;
3424             end if;
3425
3426          --  Regular derived extension, the parent must be a limited or
3427          --  synchronized interface.
3428
3429          else
3430             if not Is_Interface (Parent_Type)
3431               or else (not Is_Limited_Interface (Parent_Type)
3432                          and then
3433                        not Is_Synchronized_Interface (Parent_Type))
3434             then
3435                Error_Msg_NE
3436                  ("parent type of & must be limited interface", N, T);
3437             end if;
3438          end if;
3439
3440       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
3441       --  extension with a synchronized parent must be explicitly declared
3442       --  synchronized, because the full view will be a synchronized type.
3443       --  This must be checked before the check for limited types below,
3444       --  to ensure that types declared limited are not allowed to extend
3445       --  synchronized interfaces.
3446
3447       elsif Is_Interface (Parent_Type)
3448         and then Is_Synchronized_Interface (Parent_Type)
3449         and then not Synchronized_Present (N)
3450       then
3451          Error_Msg_NE
3452            ("private extension of& must be explicitly synchronized",
3453              N, Parent_Type);
3454
3455       elsif Limited_Present (N) then
3456          Set_Is_Limited_Record (T);
3457
3458          if not Is_Limited_Type (Parent_Type)
3459            and then
3460              (not Is_Interface (Parent_Type)
3461                or else not Is_Limited_Interface (Parent_Type))
3462          then
3463             Error_Msg_NE ("parent type& of limited extension must be limited",
3464               N, Parent_Type);
3465          end if;
3466       end if;
3467    end Analyze_Private_Extension_Declaration;
3468
3469    ---------------------------------
3470    -- Analyze_Subtype_Declaration --
3471    ---------------------------------
3472
3473    procedure Analyze_Subtype_Declaration
3474      (N    : Node_Id;
3475       Skip : Boolean := False)
3476    is
3477       Id       : constant Entity_Id := Defining_Identifier (N);
3478       T        : Entity_Id;
3479       R_Checks : Check_Result;
3480
3481    begin
3482       Generate_Definition (Id);
3483       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3484       Init_Size_Align (Id);
3485
3486       --  The following guard condition on Enter_Name is to handle cases where
3487       --  the defining identifier has already been entered into the scope but
3488       --  the declaration as a whole needs to be analyzed.
3489
3490       --  This case in particular happens for derived enumeration types. The
3491       --  derived enumeration type is processed as an inserted enumeration type
3492       --  declaration followed by a rewritten subtype declaration. The defining
3493       --  identifier, however, is entered into the name scope very early in the
3494       --  processing of the original type declaration and therefore needs to be
3495       --  avoided here, when the created subtype declaration is analyzed. (See
3496       --  Build_Derived_Types)
3497
3498       --  This also happens when the full view of a private type is derived
3499       --  type with constraints. In this case the entity has been introduced
3500       --  in the private declaration.
3501
3502       if Skip
3503         or else (Present (Etype (Id))
3504                    and then (Is_Private_Type (Etype (Id))
3505                                or else Is_Task_Type (Etype (Id))
3506                                or else Is_Rewrite_Substitution (N)))
3507       then
3508          null;
3509
3510       else
3511          Enter_Name (Id);
3512       end if;
3513
3514       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
3515
3516       --  Inherit common attributes
3517
3518       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
3519       Set_Is_Volatile       (Id, Is_Volatile       (T));
3520       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
3521       Set_Is_Atomic         (Id, Is_Atomic         (T));
3522       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
3523       Set_Convention        (Id, Convention        (T));
3524
3525       --  In the case where there is no constraint given in the subtype
3526       --  indication, Process_Subtype just returns the Subtype_Mark, so its
3527       --  semantic attributes must be established here.
3528
3529       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
3530          Set_Etype (Id, Base_Type (T));
3531
3532          case Ekind (T) is
3533             when Array_Kind =>
3534                Set_Ekind                       (Id, E_Array_Subtype);
3535                Copy_Array_Subtype_Attributes   (Id, T);
3536
3537             when Decimal_Fixed_Point_Kind =>
3538                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
3539                Set_Digits_Value         (Id, Digits_Value       (T));
3540                Set_Delta_Value          (Id, Delta_Value        (T));
3541                Set_Scale_Value          (Id, Scale_Value        (T));
3542                Set_Small_Value          (Id, Small_Value        (T));
3543                Set_Scalar_Range         (Id, Scalar_Range       (T));
3544                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
3545                Set_Is_Constrained       (Id, Is_Constrained     (T));
3546                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3547                Set_RM_Size              (Id, RM_Size            (T));
3548
3549             when Enumeration_Kind =>
3550                Set_Ekind                (Id, E_Enumeration_Subtype);
3551                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
3552                Set_Scalar_Range         (Id, Scalar_Range       (T));
3553                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
3554                Set_Is_Constrained       (Id, Is_Constrained     (T));
3555                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3556                Set_RM_Size              (Id, RM_Size            (T));
3557
3558             when Ordinary_Fixed_Point_Kind =>
3559                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
3560                Set_Scalar_Range         (Id, Scalar_Range       (T));
3561                Set_Small_Value          (Id, Small_Value        (T));
3562                Set_Delta_Value          (Id, Delta_Value        (T));
3563                Set_Is_Constrained       (Id, Is_Constrained     (T));
3564                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3565                Set_RM_Size              (Id, RM_Size            (T));
3566
3567             when Float_Kind =>
3568                Set_Ekind                (Id, E_Floating_Point_Subtype);
3569                Set_Scalar_Range         (Id, Scalar_Range       (T));
3570                Set_Digits_Value         (Id, Digits_Value       (T));
3571                Set_Is_Constrained       (Id, Is_Constrained     (T));
3572
3573             when Signed_Integer_Kind =>
3574                Set_Ekind                (Id, E_Signed_Integer_Subtype);
3575                Set_Scalar_Range         (Id, Scalar_Range       (T));
3576                Set_Is_Constrained       (Id, Is_Constrained     (T));
3577                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3578                Set_RM_Size              (Id, RM_Size            (T));
3579
3580             when Modular_Integer_Kind =>
3581                Set_Ekind                (Id, E_Modular_Integer_Subtype);
3582                Set_Scalar_Range         (Id, Scalar_Range       (T));
3583                Set_Is_Constrained       (Id, Is_Constrained     (T));
3584                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3585                Set_RM_Size              (Id, RM_Size            (T));
3586
3587             when Class_Wide_Kind =>
3588                Set_Ekind                (Id, E_Class_Wide_Subtype);
3589                Set_First_Entity         (Id, First_Entity       (T));
3590                Set_Last_Entity          (Id, Last_Entity        (T));
3591                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
3592                Set_Cloned_Subtype       (Id, T);
3593                Set_Is_Tagged_Type       (Id, True);
3594                Set_Has_Unknown_Discriminants
3595                                         (Id, True);
3596
3597                if Ekind (T) = E_Class_Wide_Subtype then
3598                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
3599                end if;
3600
3601             when E_Record_Type | E_Record_Subtype =>
3602                Set_Ekind                (Id, E_Record_Subtype);
3603
3604                if Ekind (T) = E_Record_Subtype
3605                  and then Present (Cloned_Subtype (T))
3606                then
3607                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
3608                else
3609                   Set_Cloned_Subtype    (Id, T);
3610                end if;
3611
3612                Set_First_Entity         (Id, First_Entity       (T));
3613                Set_Last_Entity          (Id, Last_Entity        (T));
3614                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
3615                Set_Is_Constrained       (Id, Is_Constrained     (T));
3616                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
3617                Set_Has_Unknown_Discriminants
3618                                         (Id, Has_Unknown_Discriminants (T));
3619
3620                if Has_Discriminants (T) then
3621                   Set_Discriminant_Constraint
3622                                         (Id, Discriminant_Constraint (T));
3623                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3624
3625                elsif Has_Unknown_Discriminants (Id) then
3626                   Set_Discriminant_Constraint (Id, No_Elist);
3627                end if;
3628
3629                if Is_Tagged_Type (T) then
3630                   Set_Is_Tagged_Type    (Id);
3631                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
3632                   Set_Primitive_Operations
3633                                         (Id, Primitive_Operations (T));
3634                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
3635
3636                   if Is_Interface (T) then
3637                      Set_Is_Interface (Id);
3638                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
3639                   end if;
3640                end if;
3641
3642             when Private_Kind =>
3643                Set_Ekind              (Id, Subtype_Kind (Ekind   (T)));
3644                Set_Has_Discriminants  (Id, Has_Discriminants     (T));
3645                Set_Is_Constrained     (Id, Is_Constrained        (T));
3646                Set_First_Entity       (Id, First_Entity          (T));
3647                Set_Last_Entity        (Id, Last_Entity           (T));
3648                Set_Private_Dependents (Id, New_Elmt_List);
3649                Set_Is_Limited_Record  (Id, Is_Limited_Record     (T));
3650                Set_Has_Unknown_Discriminants
3651                                       (Id, Has_Unknown_Discriminants (T));
3652                Set_Known_To_Have_Preelab_Init
3653                                       (Id, Known_To_Have_Preelab_Init (T));
3654
3655                if Is_Tagged_Type (T) then
3656                   Set_Is_Tagged_Type       (Id);
3657                   Set_Is_Abstract_Type     (Id, Is_Abstract_Type (T));
3658                   Set_Primitive_Operations (Id, Primitive_Operations (T));
3659                   Set_Class_Wide_Type      (Id, Class_Wide_Type (T));
3660                end if;
3661
3662                --  In general the attributes of the subtype of a private type
3663                --  are the attributes of the partial view of parent. However,
3664                --  the full view may be a discriminated type, and the subtype
3665                --  must share the discriminant constraint to generate correct
3666                --  calls to initialization procedures.
3667
3668                if Has_Discriminants (T) then
3669                   Set_Discriminant_Constraint
3670                                      (Id, Discriminant_Constraint (T));
3671                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3672
3673                elsif Present (Full_View (T))
3674                  and then Has_Discriminants (Full_View (T))
3675                then
3676                   Set_Discriminant_Constraint
3677                                (Id, Discriminant_Constraint (Full_View (T)));
3678                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3679
3680                   --  This would seem semantically correct, but apparently
3681                   --  confuses the back-end. To be explained and checked with
3682                   --  current version ???
3683
3684                   --  Set_Has_Discriminants (Id);
3685                end if;
3686
3687                Prepare_Private_Subtype_Completion (Id, N);
3688
3689             when Access_Kind =>
3690                Set_Ekind             (Id, E_Access_Subtype);
3691                Set_Is_Constrained    (Id, Is_Constrained        (T));
3692                Set_Is_Access_Constant
3693                                      (Id, Is_Access_Constant    (T));
3694                Set_Directly_Designated_Type
3695                                      (Id, Designated_Type       (T));
3696                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
3697
3698                --  A Pure library_item must not contain the declaration of a
3699                --  named access type, except within a subprogram, generic
3700                --  subprogram, task unit, or protected unit, or if it has
3701                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
3702
3703                if Comes_From_Source (Id)
3704                  and then In_Pure_Unit
3705                  and then not In_Subprogram_Task_Protected_Unit
3706                  and then not No_Pool_Assigned (Id)
3707                then
3708                   Error_Msg_N
3709                     ("named access types not allowed in pure unit", N);
3710                end if;
3711
3712             when Concurrent_Kind =>
3713                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
3714                Set_Corresponding_Record_Type (Id,
3715                                          Corresponding_Record_Type (T));
3716                Set_First_Entity         (Id, First_Entity          (T));
3717                Set_First_Private_Entity (Id, First_Private_Entity  (T));
3718                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
3719                Set_Is_Constrained       (Id, Is_Constrained        (T));
3720                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
3721                Set_Last_Entity          (Id, Last_Entity           (T));
3722
3723                if Has_Discriminants (T) then
3724                   Set_Discriminant_Constraint (Id,
3725                                            Discriminant_Constraint (T));
3726                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3727                end if;
3728
3729             when E_Incomplete_Type =>
3730                if Ada_Version >= Ada_05 then
3731                   Set_Ekind (Id, E_Incomplete_Subtype);
3732
3733                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
3734                   --  of an incomplete type visible through a limited
3735                   --  with clause.
3736
3737                   if From_With_Type (T)
3738                     and then Present (Non_Limited_View (T))
3739                   then
3740                      Set_From_With_Type   (Id);
3741                      Set_Non_Limited_View (Id, Non_Limited_View (T));
3742
3743                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
3744                   --  to the private dependents of the original incomplete
3745                   --  type for future transformation.
3746
3747                   else
3748                      Append_Elmt (Id, Private_Dependents (T));
3749                   end if;
3750
3751                --  If the subtype name denotes an incomplete type an error
3752                --  was already reported by Process_Subtype.
3753
3754                else
3755                   Set_Etype (Id, Any_Type);
3756                end if;
3757
3758             when others =>
3759                raise Program_Error;
3760          end case;
3761       end if;
3762
3763       if Etype (Id) = Any_Type then
3764          return;
3765       end if;
3766
3767       --  Some common processing on all types
3768
3769       Set_Size_Info      (Id,                 T);
3770       Set_First_Rep_Item (Id, First_Rep_Item (T));
3771
3772       T := Etype (Id);
3773
3774       Set_Is_Immediately_Visible   (Id, True);
3775       Set_Depends_On_Private       (Id, Has_Private_Component (T));
3776       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
3777
3778       if Is_Interface (T) then
3779          Set_Is_Interface (Id);
3780       end if;
3781
3782       if Present (Generic_Parent_Type (N))
3783         and then
3784           (Nkind
3785             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
3786             or else Nkind
3787               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
3788                 /= N_Formal_Private_Type_Definition)
3789       then
3790          if Is_Tagged_Type (Id) then
3791
3792             --  If this is a generic actual subtype for a synchronized type,
3793             --  the primitive operations are those of the corresponding record
3794             --  for which there is a separate subtype declaration.
3795
3796             if Is_Concurrent_Type (Id) then
3797                null;
3798             elsif Is_Class_Wide_Type (Id) then
3799                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
3800             else
3801                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
3802             end if;
3803
3804          elsif Scope (Etype (Id)) /= Standard_Standard then
3805             Derive_Subprograms (Generic_Parent_Type (N), Id);
3806          end if;
3807       end if;
3808
3809       if Is_Private_Type (T)
3810         and then Present (Full_View (T))
3811       then
3812          Conditional_Delay (Id, Full_View (T));
3813
3814       --  The subtypes of components or subcomponents of protected types
3815       --  do not need freeze nodes, which would otherwise appear in the
3816       --  wrong scope (before the freeze node for the protected type). The
3817       --  proper subtypes are those of the subcomponents of the corresponding
3818       --  record.
3819
3820       elsif Ekind (Scope (Id)) /= E_Protected_Type
3821         and then Present (Scope (Scope (Id))) -- error defense!
3822         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
3823       then
3824          Conditional_Delay (Id, T);
3825       end if;
3826
3827       --  Check that constraint_error is raised for a scalar subtype
3828       --  indication when the lower or upper bound of a non-null range
3829       --  lies outside the range of the type mark.
3830
3831       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
3832          if Is_Scalar_Type (Etype (Id))
3833             and then Scalar_Range (Id) /=
3834                      Scalar_Range (Etype (Subtype_Mark
3835                                            (Subtype_Indication (N))))
3836          then
3837             Apply_Range_Check
3838               (Scalar_Range (Id),
3839                Etype (Subtype_Mark (Subtype_Indication (N))));
3840
3841          elsif Is_Array_Type (Etype (Id))
3842            and then Present (First_Index (Id))
3843          then
3844             --  This really should be a subprogram that finds the indications
3845             --  to check???
3846
3847             if ((Nkind (First_Index (Id)) = N_Identifier
3848                    and then Ekind (Entity (First_Index (Id))) in Scalar_Kind)
3849                  or else Nkind (First_Index (Id)) = N_Subtype_Indication)
3850               and then
3851                 Nkind (Scalar_Range (Etype (First_Index (Id)))) = N_Range
3852             then
3853                declare
3854                   Target_Typ : constant Entity_Id :=
3855                                  Etype
3856                                    (First_Index (Etype
3857                                      (Subtype_Mark (Subtype_Indication (N)))));
3858                begin
3859                   R_Checks :=
3860                     Get_Range_Checks
3861                       (Scalar_Range (Etype (First_Index (Id))),
3862                        Target_Typ,
3863                        Etype (First_Index (Id)),
3864                        Defining_Identifier (N));
3865
3866                   Insert_Range_Checks
3867                     (R_Checks,
3868                      N,
3869                      Target_Typ,
3870                      Sloc (Defining_Identifier (N)));
3871                end;
3872             end if;
3873          end if;
3874       end if;
3875
3876       Set_Optimize_Alignment_Flags (Id);
3877       Check_Eliminated (Id);
3878    end Analyze_Subtype_Declaration;
3879
3880    --------------------------------
3881    -- Analyze_Subtype_Indication --
3882    --------------------------------
3883
3884    procedure Analyze_Subtype_Indication (N : Node_Id) is
3885       T : constant Entity_Id := Subtype_Mark (N);
3886       R : constant Node_Id   := Range_Expression (Constraint (N));
3887
3888    begin
3889       Analyze (T);
3890
3891       if R /= Error then
3892          Analyze (R);
3893          Set_Etype (N, Etype (R));
3894          Resolve (R, Entity (T));
3895       else
3896          Set_Error_Posted (R);
3897          Set_Error_Posted (T);
3898       end if;
3899    end Analyze_Subtype_Indication;
3900
3901    ------------------------------
3902    -- Analyze_Type_Declaration --
3903    ------------------------------
3904
3905    procedure Analyze_Type_Declaration (N : Node_Id) is
3906       Def    : constant Node_Id   := Type_Definition (N);
3907       Def_Id : constant Entity_Id := Defining_Identifier (N);
3908       T      : Entity_Id;
3909       Prev   : Entity_Id;
3910
3911       Is_Remote : constant Boolean :=
3912                     (Is_Remote_Types (Current_Scope)
3913                        or else Is_Remote_Call_Interface (Current_Scope))
3914                     and then not (In_Private_Part (Current_Scope)
3915                                     or else In_Package_Body (Current_Scope));
3916
3917       procedure Check_Ops_From_Incomplete_Type;
3918       --  If there is a tagged incomplete partial view of the type, transfer
3919       --  its operations to the full view, and indicate that the type of the
3920       --  controlling parameter (s) is this full view.
3921
3922       ------------------------------------
3923       -- Check_Ops_From_Incomplete_Type --
3924       ------------------------------------
3925
3926       procedure Check_Ops_From_Incomplete_Type is
3927          Elmt   : Elmt_Id;
3928          Formal : Entity_Id;
3929          Op     : Entity_Id;
3930
3931       begin
3932          if Prev /= T
3933            and then Ekind (Prev) = E_Incomplete_Type
3934            and then Is_Tagged_Type (Prev)
3935            and then Is_Tagged_Type (T)
3936          then
3937             Elmt := First_Elmt (Primitive_Operations (Prev));
3938             while Present (Elmt) loop
3939                Op := Node (Elmt);
3940                Prepend_Elmt (Op, Primitive_Operations (T));
3941
3942                Formal := First_Formal (Op);
3943                while Present (Formal) loop
3944                   if Etype (Formal) = Prev then
3945                      Set_Etype (Formal, T);
3946                   end if;
3947
3948                   Next_Formal (Formal);
3949                end loop;
3950
3951                if Etype (Op) = Prev then
3952                   Set_Etype (Op, T);
3953                end if;
3954
3955                Next_Elmt (Elmt);
3956             end loop;
3957          end if;
3958       end Check_Ops_From_Incomplete_Type;
3959
3960    --  Start of processing for Analyze_Type_Declaration
3961
3962    begin
3963       Prev := Find_Type_Name (N);
3964
3965       --  The full view, if present, now points to the current type
3966
3967       --  Ada 2005 (AI-50217): If the type was previously decorated when
3968       --  imported through a LIMITED WITH clause, it appears as incomplete
3969       --  but has no full view.
3970       --  If the incomplete view is tagged, a class_wide type has been
3971       --  created already. Use it for the full view as well, to prevent
3972       --  multiple incompatible class-wide types that may be  created for
3973       --  self-referential anonymous access components.
3974
3975       if Ekind (Prev) = E_Incomplete_Type
3976         and then Present (Full_View (Prev))
3977       then
3978          T := Full_View (Prev);
3979
3980          if Is_Tagged_Type (Prev)
3981            and then Present (Class_Wide_Type (Prev))
3982          then
3983             Set_Ekind (T, Ekind (Prev));         --  will be reset later
3984             Set_Class_Wide_Type (T, Class_Wide_Type (Prev));
3985             Set_Etype (Class_Wide_Type (T), T);
3986          end if;
3987
3988       else
3989          T := Prev;
3990       end if;
3991
3992       Set_Is_Pure (T, Is_Pure (Current_Scope));
3993
3994       --  We set the flag Is_First_Subtype here. It is needed to set the
3995       --  corresponding flag for the Implicit class-wide-type created
3996       --  during tagged types processing.
3997
3998       Set_Is_First_Subtype (T, True);
3999
4000       --  Only composite types other than array types are allowed to have
4001       --  discriminants.
4002
4003       case Nkind (Def) is
4004
4005          --  For derived types, the rule will be checked once we've figured
4006          --  out the parent type.
4007
4008          when N_Derived_Type_Definition =>
4009             null;
4010
4011          --  For record types, discriminants are allowed
4012
4013          when N_Record_Definition =>
4014             null;
4015
4016          when others =>
4017             if Present (Discriminant_Specifications (N)) then
4018                Error_Msg_N
4019                  ("elementary or array type cannot have discriminants",
4020                   Defining_Identifier
4021                   (First (Discriminant_Specifications (N))));
4022             end if;
4023       end case;
4024
4025       --  Elaborate the type definition according to kind, and generate
4026       --  subsidiary (implicit) subtypes where needed. We skip this if it was
4027       --  already done (this happens during the reanalysis that follows a call
4028       --  to the high level optimizer).
4029
4030       if not Analyzed (T) then
4031          Set_Analyzed (T);
4032
4033          case Nkind (Def) is
4034
4035             when N_Access_To_Subprogram_Definition =>
4036                Access_Subprogram_Declaration (T, Def);
4037
4038                --  If this is a remote access to subprogram, we must create the
4039                --  equivalent fat pointer type, and related subprograms.
4040
4041                if Is_Remote then
4042                   Process_Remote_AST_Declaration (N);
4043                end if;
4044
4045                --  Validate categorization rule against access type declaration
4046                --  usually a violation in Pure unit, Shared_Passive unit.
4047
4048                Validate_Access_Type_Declaration (T, N);
4049
4050             when N_Access_To_Object_Definition =>
4051                Access_Type_Declaration (T, Def);
4052
4053                --  Validate categorization rule against access type declaration
4054                --  usually a violation in Pure unit, Shared_Passive unit.
4055
4056                Validate_Access_Type_Declaration (T, N);
4057
4058                --  If we are in a Remote_Call_Interface package and define a
4059                --  RACW, then calling stubs and specific stream attributes
4060                --  must be added.
4061
4062                if Is_Remote
4063                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
4064                then
4065                   Add_RACW_Features (Def_Id);
4066                end if;
4067
4068                --  Set no strict aliasing flag if config pragma seen
4069
4070                if Opt.No_Strict_Aliasing then
4071                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
4072                end if;
4073
4074             when N_Array_Type_Definition =>
4075                Array_Type_Declaration (T, Def);
4076
4077             when N_Derived_Type_Definition =>
4078                Derived_Type_Declaration (T, N, T /= Def_Id);
4079
4080             when N_Enumeration_Type_Definition =>
4081                Enumeration_Type_Declaration (T, Def);
4082
4083             when N_Floating_Point_Definition =>
4084                Floating_Point_Type_Declaration (T, Def);
4085
4086             when N_Decimal_Fixed_Point_Definition =>
4087                Decimal_Fixed_Point_Type_Declaration (T, Def);
4088
4089             when N_Ordinary_Fixed_Point_Definition =>
4090                Ordinary_Fixed_Point_Type_Declaration (T, Def);
4091
4092             when N_Signed_Integer_Type_Definition =>
4093                Signed_Integer_Type_Declaration (T, Def);
4094
4095             when N_Modular_Type_Definition =>
4096                Modular_Type_Declaration (T, Def);
4097
4098             when N_Record_Definition =>
4099                Record_Type_Declaration (T, N, Prev);
4100
4101             when others =>
4102                raise Program_Error;
4103
4104          end case;
4105       end if;
4106
4107       if Etype (T) = Any_Type then
4108          return;
4109       end if;
4110
4111       --  Some common processing for all types
4112
4113       Set_Depends_On_Private (T, Has_Private_Component (T));
4114       Check_Ops_From_Incomplete_Type;
4115
4116       --  Both the declared entity, and its anonymous base type if one
4117       --  was created, need freeze nodes allocated.
4118
4119       declare
4120          B : constant Entity_Id := Base_Type (T);
4121
4122       begin
4123          --  In the case where the base type differs from the first subtype, we
4124          --  pre-allocate a freeze node, and set the proper link to the first
4125          --  subtype. Freeze_Entity will use this preallocated freeze node when
4126          --  it freezes the entity.
4127
4128          --  This does not apply if the base type is a generic type, whose
4129          --  declaration is independent of the current derived definition.
4130
4131          if B /= T and then not Is_Generic_Type (B) then
4132             Ensure_Freeze_Node (B);
4133             Set_First_Subtype_Link (Freeze_Node (B), T);
4134          end if;
4135
4136          --  A type that is imported through a limited_with clause cannot
4137          --  generate any code, and thus need not be frozen. However, an access
4138          --  type with an imported designated type needs a finalization list,
4139          --  which may be referenced in some other package that has non-limited
4140          --  visibility on the designated type. Thus we must create the
4141          --  finalization list at the point the access type is frozen, to
4142          --  prevent unsatisfied references at link time.
4143
4144          if not From_With_Type (T) or else Is_Access_Type (T) then
4145             Set_Has_Delayed_Freeze (T);
4146          end if;
4147       end;
4148
4149       --  Case where T is the full declaration of some private type which has
4150       --  been swapped in Defining_Identifier (N).
4151
4152       if T /= Def_Id and then Is_Private_Type (Def_Id) then
4153          Process_Full_View (N, T, Def_Id);
4154
4155          --  Record the reference. The form of this is a little strange, since
4156          --  the full declaration has been swapped in. So the first parameter
4157          --  here represents the entity to which a reference is made which is
4158          --  the "real" entity, i.e. the one swapped in, and the second
4159          --  parameter provides the reference location.
4160
4161          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
4162          --  since we don't want a complaint about the full type being an
4163          --  unwanted reference to the private type
4164
4165          declare
4166             B : constant Boolean := Has_Pragma_Unreferenced (T);
4167          begin
4168             Set_Has_Pragma_Unreferenced (T, False);
4169             Generate_Reference (T, T, 'c');
4170             Set_Has_Pragma_Unreferenced (T, B);
4171          end;
4172
4173          Set_Completion_Referenced (Def_Id);
4174
4175       --  For completion of incomplete type, process incomplete dependents
4176       --  and always mark the full type as referenced (it is the incomplete
4177       --  type that we get for any real reference).
4178
4179       elsif Ekind (Prev) = E_Incomplete_Type then
4180          Process_Incomplete_Dependents (N, T, Prev);
4181          Generate_Reference (Prev, Def_Id, 'c');
4182          Set_Completion_Referenced (Def_Id);
4183
4184       --  If not private type or incomplete type completion, this is a real
4185       --  definition of a new entity, so record it.
4186
4187       else
4188          Generate_Definition (Def_Id);
4189       end if;
4190
4191       if Chars (Scope (Def_Id)) = Name_System
4192         and then Chars (Def_Id) = Name_Address
4193         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
4194       then
4195          Set_Is_Descendent_Of_Address (Def_Id);
4196          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
4197          Set_Is_Descendent_Of_Address (Prev);
4198       end if;
4199
4200       Set_Optimize_Alignment_Flags (Def_Id);
4201       Check_Eliminated (Def_Id);
4202    end Analyze_Type_Declaration;
4203
4204    --------------------------
4205    -- Analyze_Variant_Part --
4206    --------------------------
4207
4208    procedure Analyze_Variant_Part (N : Node_Id) is
4209
4210       procedure Non_Static_Choice_Error (Choice : Node_Id);
4211       --  Error routine invoked by the generic instantiation below when the
4212       --  variant part has a non static choice.
4213
4214       procedure Process_Declarations (Variant : Node_Id);
4215       --  Analyzes all the declarations associated with a Variant. Needed by
4216       --  the generic instantiation below.
4217
4218       package Variant_Choices_Processing is new
4219         Generic_Choices_Processing
4220           (Get_Alternatives          => Variants,
4221            Get_Choices               => Discrete_Choices,
4222            Process_Empty_Choice      => No_OP,
4223            Process_Non_Static_Choice => Non_Static_Choice_Error,
4224            Process_Associated_Node   => Process_Declarations);
4225       use Variant_Choices_Processing;
4226       --  Instantiation of the generic choice processing package
4227
4228       -----------------------------
4229       -- Non_Static_Choice_Error --
4230       -----------------------------
4231
4232       procedure Non_Static_Choice_Error (Choice : Node_Id) is
4233       begin
4234          Flag_Non_Static_Expr
4235            ("choice given in variant part is not static!", Choice);
4236       end Non_Static_Choice_Error;
4237
4238       --------------------------
4239       -- Process_Declarations --
4240       --------------------------
4241
4242       procedure Process_Declarations (Variant : Node_Id) is
4243       begin
4244          if not Null_Present (Component_List (Variant)) then
4245             Analyze_Declarations (Component_Items (Component_List (Variant)));
4246
4247             if Present (Variant_Part (Component_List (Variant))) then
4248                Analyze (Variant_Part (Component_List (Variant)));
4249             end if;
4250          end if;
4251       end Process_Declarations;
4252
4253       --  Local Variables
4254
4255       Discr_Name : Node_Id;
4256       Discr_Type : Entity_Id;
4257
4258       Case_Table     : Choice_Table_Type (1 .. Number_Of_Choices (N));
4259       Last_Choice    : Nat;
4260       Dont_Care      : Boolean;
4261       Others_Present : Boolean := False;
4262
4263       pragma Warnings (Off, Case_Table);
4264       pragma Warnings (Off, Last_Choice);
4265       pragma Warnings (Off, Dont_Care);
4266       pragma Warnings (Off, Others_Present);
4267       --  We don't care about the assigned values of any of these
4268
4269    --  Start of processing for Analyze_Variant_Part
4270
4271    begin
4272       Discr_Name := Name (N);
4273       Analyze (Discr_Name);
4274
4275       --  If Discr_Name bad, get out (prevent cascaded errors)
4276
4277       if Etype (Discr_Name) = Any_Type then
4278          return;
4279       end if;
4280
4281       --  Check invalid discriminant in variant part
4282
4283       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4284          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4285       end if;
4286
4287       Discr_Type := Etype (Entity (Discr_Name));
4288
4289       if not Is_Discrete_Type (Discr_Type) then
4290          Error_Msg_N
4291            ("discriminant in a variant part must be of a discrete type",
4292              Name (N));
4293          return;
4294       end if;
4295
4296       --  Call the instantiated Analyze_Choices which does the rest of the work
4297
4298       Analyze_Choices
4299         (N, Discr_Type, Case_Table, Last_Choice, Dont_Care, Others_Present);
4300    end Analyze_Variant_Part;
4301
4302    ----------------------------
4303    -- Array_Type_Declaration --
4304    ----------------------------
4305
4306    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4307       Component_Def : constant Node_Id := Component_Definition (Def);
4308       Element_Type  : Entity_Id;
4309       Implicit_Base : Entity_Id;
4310       Index         : Node_Id;
4311       Related_Id    : Entity_Id := Empty;
4312       Nb_Index      : Nat;
4313       P             : constant Node_Id := Parent (Def);
4314       Priv          : Entity_Id;
4315
4316    begin
4317       if Nkind (Def) = N_Constrained_Array_Definition then
4318          Index := First (Discrete_Subtype_Definitions (Def));
4319       else
4320          Index := First (Subtype_Marks (Def));
4321       end if;
4322
4323       --  Find proper names for the implicit types which may be public. In case
4324       --  of anonymous arrays we use the name of the first object of that type
4325       --  as prefix.
4326
4327       if No (T) then
4328          Related_Id :=  Defining_Identifier (P);
4329       else
4330          Related_Id := T;
4331       end if;
4332
4333       Nb_Index := 1;
4334       while Present (Index) loop
4335          Analyze (Index);
4336
4337          --  Add a subtype declaration for each index of private array type
4338          --  declaration whose etype is also private. For example:
4339
4340          --     package Pkg is
4341          --        type Index is private;
4342          --     private
4343          --        type Table is array (Index) of ...
4344          --     end;
4345
4346          --  This is currently required by the expander for the internally
4347          --  generated equality subprogram of records with variant parts in
4348          --  which the etype of some component is such private type.
4349
4350          if Ekind (Current_Scope) = E_Package
4351            and then In_Private_Part (Current_Scope)
4352            and then Has_Private_Declaration (Etype (Index))
4353          then
4354             declare
4355                Loc   : constant Source_Ptr := Sloc (Def);
4356                New_E : Entity_Id;
4357                Decl  : Entity_Id;
4358
4359             begin
4360                New_E := Make_Temporary (Loc, 'T');
4361                Set_Is_Internal (New_E);
4362
4363                Decl :=
4364                  Make_Subtype_Declaration (Loc,
4365                    Defining_Identifier => New_E,
4366                    Subtype_Indication  =>
4367                      New_Occurrence_Of (Etype (Index), Loc));
4368
4369                Insert_Before (Parent (Def), Decl);
4370                Analyze (Decl);
4371                Set_Etype (Index, New_E);
4372
4373                --  If the index is a range the Entity attribute is not
4374                --  available. Example:
4375
4376                --     package Pkg is
4377                --        type T is private;
4378                --     private
4379                --        type T is new Natural;
4380                --        Table : array (T(1) .. T(10)) of Boolean;
4381                --     end Pkg;
4382
4383                if Nkind (Index) /= N_Range then
4384                   Set_Entity (Index, New_E);
4385                end if;
4386             end;
4387          end if;
4388
4389          Make_Index (Index, P, Related_Id, Nb_Index);
4390          Next_Index (Index);
4391          Nb_Index := Nb_Index + 1;
4392       end loop;
4393
4394       --  Process subtype indication if one is present
4395
4396       if Present (Subtype_Indication (Component_Def)) then
4397          Element_Type :=
4398            Process_Subtype
4399              (Subtype_Indication (Component_Def), P, Related_Id, 'C');
4400
4401       --  Ada 2005 (AI-230): Access Definition case
4402
4403       else pragma Assert (Present (Access_Definition (Component_Def)));
4404
4405          --  Indicate that the anonymous access type is created by the
4406          --  array type declaration.
4407
4408          Element_Type := Access_Definition
4409                            (Related_Nod => P,
4410                             N           => Access_Definition (Component_Def));
4411          Set_Is_Local_Anonymous_Access (Element_Type);
4412
4413          --  Propagate the parent. This field is needed if we have to generate
4414          --  the master_id associated with an anonymous access to task type
4415          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4416
4417          Set_Parent (Element_Type, Parent (T));
4418
4419          --  Ada 2005 (AI-230): In case of components that are anonymous access
4420          --  types the level of accessibility depends on the enclosing type
4421          --  declaration
4422
4423          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4424
4425          --  Ada 2005 (AI-254)
4426
4427          declare
4428             CD : constant Node_Id :=
4429                    Access_To_Subprogram_Definition
4430                      (Access_Definition (Component_Def));
4431          begin
4432             if Present (CD) and then Protected_Present (CD) then
4433                Element_Type :=
4434                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4435             end if;
4436          end;
4437       end if;
4438
4439       --  Constrained array case
4440
4441       if No (T) then
4442          T := Create_Itype (E_Void, P, Related_Id, 'T');
4443       end if;
4444
4445       if Nkind (Def) = N_Constrained_Array_Definition then
4446
4447          --  Establish Implicit_Base as unconstrained base type
4448
4449          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4450
4451          Set_Etype              (Implicit_Base, Implicit_Base);
4452          Set_Scope              (Implicit_Base, Current_Scope);
4453          Set_Has_Delayed_Freeze (Implicit_Base);
4454
4455          --  The constrained array type is a subtype of the unconstrained one
4456
4457          Set_Ekind          (T, E_Array_Subtype);
4458          Init_Size_Align    (T);
4459          Set_Etype          (T, Implicit_Base);
4460          Set_Scope          (T, Current_Scope);
4461          Set_Is_Constrained (T, True);
4462          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4463          Set_Has_Delayed_Freeze (T);
4464
4465          --  Complete setup of implicit base type
4466
4467          Set_First_Index       (Implicit_Base, First_Index (T));
4468          Set_Component_Type    (Implicit_Base, Element_Type);
4469          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4470          Set_Component_Size    (Implicit_Base, Uint_0);
4471          Set_Packed_Array_Type (Implicit_Base, Empty);
4472          Set_Has_Controlled_Component
4473                                (Implicit_Base, Has_Controlled_Component
4474                                                         (Element_Type)
4475                                                  or else Is_Controlled
4476                                                         (Element_Type));
4477          Set_Finalize_Storage_Only
4478                                (Implicit_Base, Finalize_Storage_Only
4479                                                         (Element_Type));
4480
4481       --  Unconstrained array case
4482
4483       else
4484          Set_Ekind                    (T, E_Array_Type);
4485          Init_Size_Align              (T);
4486          Set_Etype                    (T, T);
4487          Set_Scope                    (T, Current_Scope);
4488          Set_Component_Size           (T, Uint_0);
4489          Set_Is_Constrained           (T, False);
4490          Set_First_Index              (T, First (Subtype_Marks (Def)));
4491          Set_Has_Delayed_Freeze       (T, True);
4492          Set_Has_Task                 (T, Has_Task      (Element_Type));
4493          Set_Has_Controlled_Component (T, Has_Controlled_Component
4494                                                         (Element_Type)
4495                                             or else
4496                                           Is_Controlled (Element_Type));
4497          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4498                                                         (Element_Type));
4499       end if;
4500
4501       --  Common attributes for both cases
4502
4503       Set_Component_Type (Base_Type (T), Element_Type);
4504       Set_Packed_Array_Type (T, Empty);
4505
4506       if Aliased_Present (Component_Definition (Def)) then
4507          Set_Has_Aliased_Components (Etype (T));
4508       end if;
4509
4510       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4511       --  array type to ensure that objects of this type are initialized.
4512
4513       if Ada_Version >= Ada_05
4514         and then Can_Never_Be_Null (Element_Type)
4515       then
4516          Set_Can_Never_Be_Null (T);
4517
4518          if Null_Exclusion_Present (Component_Definition (Def))
4519
4520             --  No need to check itypes because in their case this check was
4521             --  done at their point of creation
4522
4523            and then not Is_Itype (Element_Type)
4524          then
4525             Error_Msg_N
4526               ("`NOT NULL` not allowed (null already excluded)",
4527                Subtype_Indication (Component_Definition (Def)));
4528          end if;
4529       end if;
4530
4531       Priv := Private_Component (Element_Type);
4532
4533       if Present (Priv) then
4534
4535          --  Check for circular definitions
4536
4537          if Priv = Any_Type then
4538             Set_Component_Type (Etype (T), Any_Type);
4539
4540          --  There is a gap in the visibility of operations on the composite
4541          --  type only if the component type is defined in a different scope.
4542
4543          elsif Scope (Priv) = Current_Scope then
4544             null;
4545
4546          elsif Is_Limited_Type (Priv) then
4547             Set_Is_Limited_Composite (Etype (T));
4548             Set_Is_Limited_Composite (T);
4549          else
4550             Set_Is_Private_Composite (Etype (T));
4551             Set_Is_Private_Composite (T);
4552          end if;
4553       end if;
4554
4555       --  A syntax error in the declaration itself may lead to an empty index
4556       --  list, in which case do a minimal patch.
4557
4558       if No (First_Index (T)) then
4559          Error_Msg_N ("missing index definition in array type declaration", T);
4560
4561          declare
4562             Indices : constant List_Id :=
4563                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4564          begin
4565             Set_Discrete_Subtype_Definitions (Def, Indices);
4566             Set_First_Index (T, First (Indices));
4567             return;
4568          end;
4569       end if;
4570
4571       --  Create a concatenation operator for the new type. Internal array
4572       --  types created for packed entities do not need such, they are
4573       --  compatible with the user-defined type.
4574
4575       if Number_Dimensions (T) = 1
4576          and then not Is_Packed_Array_Type (T)
4577       then
4578          New_Concatenation_Op (T);
4579       end if;
4580
4581       --  In the case of an unconstrained array the parser has already verified
4582       --  that all the indices are unconstrained but we still need to make sure
4583       --  that the element type is constrained.
4584
4585       if Is_Indefinite_Subtype (Element_Type) then
4586          Error_Msg_N
4587            ("unconstrained element type in array declaration",
4588             Subtype_Indication (Component_Def));
4589
4590       elsif Is_Abstract_Type (Element_Type) then
4591          Error_Msg_N
4592            ("the type of a component cannot be abstract",
4593             Subtype_Indication (Component_Def));
4594       end if;
4595    end Array_Type_Declaration;
4596
4597    ------------------------------------------------------
4598    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4599    ------------------------------------------------------
4600
4601    function Replace_Anonymous_Access_To_Protected_Subprogram
4602      (N : Node_Id) return Entity_Id
4603    is
4604       Loc : constant Source_Ptr := Sloc (N);
4605
4606       Curr_Scope : constant Scope_Stack_Entry :=
4607                      Scope_Stack.Table (Scope_Stack.Last);
4608
4609       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
4610       Acc  : Node_Id;
4611       Comp : Node_Id;
4612       Decl : Node_Id;
4613       P    : Node_Id;
4614
4615    begin
4616       Set_Is_Internal (Anon);
4617
4618       case Nkind (N) is
4619          when N_Component_Declaration       |
4620            N_Unconstrained_Array_Definition |
4621            N_Constrained_Array_Definition   =>
4622             Comp := Component_Definition (N);
4623             Acc  := Access_Definition (Comp);
4624
4625          when N_Discriminant_Specification =>
4626             Comp := Discriminant_Type (N);
4627             Acc  := Comp;
4628
4629          when N_Parameter_Specification =>
4630             Comp := Parameter_Type (N);
4631             Acc  := Comp;
4632
4633          when N_Access_Function_Definition  =>
4634             Comp := Result_Definition (N);
4635             Acc  := Comp;
4636
4637          when N_Object_Declaration  =>
4638             Comp := Object_Definition (N);
4639             Acc  := Comp;
4640
4641          when N_Function_Specification =>
4642             Comp := Result_Definition (N);
4643             Acc  := Comp;
4644
4645          when others =>
4646             raise Program_Error;
4647       end case;
4648
4649       Decl := Make_Full_Type_Declaration (Loc,
4650                 Defining_Identifier => Anon,
4651                 Type_Definition   =>
4652                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
4653
4654       Mark_Rewrite_Insertion (Decl);
4655
4656       --  Insert the new declaration in the nearest enclosing scope. If the
4657       --  node is a body and N is its return type, the declaration belongs in
4658       --  the enclosing scope.
4659
4660       P := Parent (N);
4661
4662       if Nkind (P) = N_Subprogram_Body
4663         and then Nkind (N) = N_Function_Specification
4664       then
4665          P := Parent (P);
4666       end if;
4667
4668       while Present (P) and then not Has_Declarations (P) loop
4669          P := Parent (P);
4670       end loop;
4671
4672       pragma Assert (Present (P));
4673
4674       if Nkind (P) = N_Package_Specification then
4675          Prepend (Decl, Visible_Declarations (P));
4676       else
4677          Prepend (Decl, Declarations (P));
4678       end if;
4679
4680       --  Replace the anonymous type with an occurrence of the new declaration.
4681       --  In all cases the rewritten node does not have the null-exclusion
4682       --  attribute because (if present) it was already inherited by the
4683       --  anonymous entity (Anon). Thus, in case of components we do not
4684       --  inherit this attribute.
4685
4686       if Nkind (N) = N_Parameter_Specification then
4687          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4688          Set_Etype (Defining_Identifier (N), Anon);
4689          Set_Null_Exclusion_Present (N, False);
4690
4691       elsif Nkind (N) = N_Object_Declaration then
4692          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4693          Set_Etype (Defining_Identifier (N), Anon);
4694
4695       elsif Nkind (N) = N_Access_Function_Definition then
4696          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4697
4698       elsif Nkind (N) = N_Function_Specification then
4699          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4700          Set_Etype (Defining_Unit_Name (N), Anon);
4701
4702       else
4703          Rewrite (Comp,
4704            Make_Component_Definition (Loc,
4705              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
4706       end if;
4707
4708       Mark_Rewrite_Insertion (Comp);
4709
4710       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
4711          Analyze (Decl);
4712
4713       else
4714          --  Temporarily remove the current scope (record or subprogram) from
4715          --  the stack to add the new declarations to the enclosing scope.
4716
4717          Scope_Stack.Decrement_Last;
4718          Analyze (Decl);
4719          Set_Is_Itype (Anon);
4720          Scope_Stack.Append (Curr_Scope);
4721       end if;
4722
4723       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
4724       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
4725       return Anon;
4726    end Replace_Anonymous_Access_To_Protected_Subprogram;
4727
4728    -------------------------------
4729    -- Build_Derived_Access_Type --
4730    -------------------------------
4731
4732    procedure Build_Derived_Access_Type
4733      (N            : Node_Id;
4734       Parent_Type  : Entity_Id;
4735       Derived_Type : Entity_Id)
4736    is
4737       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
4738
4739       Desig_Type      : Entity_Id;
4740       Discr           : Entity_Id;
4741       Discr_Con_Elist : Elist_Id;
4742       Discr_Con_El    : Elmt_Id;
4743       Subt            : Entity_Id;
4744
4745    begin
4746       --  Set the designated type so it is available in case this is an access
4747       --  to a self-referential type, e.g. a standard list type with a next
4748       --  pointer. Will be reset after subtype is built.
4749
4750       Set_Directly_Designated_Type
4751         (Derived_Type, Designated_Type (Parent_Type));
4752
4753       Subt := Process_Subtype (S, N);
4754
4755       if Nkind (S) /= N_Subtype_Indication
4756         and then Subt /= Base_Type (Subt)
4757       then
4758          Set_Ekind (Derived_Type, E_Access_Subtype);
4759       end if;
4760
4761       if Ekind (Derived_Type) = E_Access_Subtype then
4762          declare
4763             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
4764             Ibase      : constant Entity_Id :=
4765                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
4766             Svg_Chars  : constant Name_Id   := Chars (Ibase);
4767             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
4768
4769          begin
4770             Copy_Node (Pbase, Ibase);
4771
4772             Set_Chars             (Ibase, Svg_Chars);
4773             Set_Next_Entity       (Ibase, Svg_Next_E);
4774             Set_Sloc              (Ibase, Sloc (Derived_Type));
4775             Set_Scope             (Ibase, Scope (Derived_Type));
4776             Set_Freeze_Node       (Ibase, Empty);
4777             Set_Is_Frozen         (Ibase, False);
4778             Set_Comes_From_Source (Ibase, False);
4779             Set_Is_First_Subtype  (Ibase, False);
4780
4781             Set_Etype (Ibase, Pbase);
4782             Set_Etype (Derived_Type, Ibase);
4783          end;
4784       end if;
4785
4786       Set_Directly_Designated_Type
4787         (Derived_Type, Designated_Type (Subt));
4788
4789       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
4790       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
4791       Set_Size_Info          (Derived_Type,                     Parent_Type);
4792       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
4793       Set_Depends_On_Private (Derived_Type,
4794                               Has_Private_Component (Derived_Type));
4795       Conditional_Delay      (Derived_Type, Subt);
4796
4797       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
4798       --  that it is not redundant.
4799
4800       if Null_Exclusion_Present (Type_Definition (N)) then
4801          Set_Can_Never_Be_Null (Derived_Type);
4802
4803          if Can_Never_Be_Null (Parent_Type)
4804            and then False
4805          then
4806             Error_Msg_NE
4807               ("`NOT NULL` not allowed (& already excludes null)",
4808                 N, Parent_Type);
4809          end if;
4810
4811       elsif Can_Never_Be_Null (Parent_Type) then
4812          Set_Can_Never_Be_Null (Derived_Type);
4813       end if;
4814
4815       --  Note: we do not copy the Storage_Size_Variable, since we always go to
4816       --  the root type for this information.
4817
4818       --  Apply range checks to discriminants for derived record case
4819       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
4820
4821       Desig_Type := Designated_Type (Derived_Type);
4822       if Is_Composite_Type (Desig_Type)
4823         and then (not Is_Array_Type (Desig_Type))
4824         and then Has_Discriminants (Desig_Type)
4825         and then Base_Type (Desig_Type) /= Desig_Type
4826       then
4827          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
4828          Discr_Con_El := First_Elmt (Discr_Con_Elist);
4829
4830          Discr := First_Discriminant (Base_Type (Desig_Type));
4831          while Present (Discr_Con_El) loop
4832             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
4833             Next_Elmt (Discr_Con_El);
4834             Next_Discriminant (Discr);
4835          end loop;
4836       end if;
4837    end Build_Derived_Access_Type;
4838
4839    ------------------------------
4840    -- Build_Derived_Array_Type --
4841    ------------------------------
4842
4843    procedure Build_Derived_Array_Type
4844      (N            : Node_Id;
4845       Parent_Type  : Entity_Id;
4846       Derived_Type : Entity_Id)
4847    is
4848       Loc           : constant Source_Ptr := Sloc (N);
4849       Tdef          : constant Node_Id    := Type_Definition (N);
4850       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
4851       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
4852       Implicit_Base : Entity_Id;
4853       New_Indic     : Node_Id;
4854
4855       procedure Make_Implicit_Base;
4856       --  If the parent subtype is constrained, the derived type is a subtype
4857       --  of an implicit base type derived from the parent base.
4858
4859       ------------------------
4860       -- Make_Implicit_Base --
4861       ------------------------
4862
4863       procedure Make_Implicit_Base is
4864       begin
4865          Implicit_Base :=
4866            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
4867
4868          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
4869          Set_Etype (Implicit_Base, Parent_Base);
4870
4871          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
4872          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
4873
4874          Set_Has_Delayed_Freeze (Implicit_Base, True);
4875       end Make_Implicit_Base;
4876
4877    --  Start of processing for Build_Derived_Array_Type
4878
4879    begin
4880       if not Is_Constrained (Parent_Type) then
4881          if Nkind (Indic) /= N_Subtype_Indication then
4882             Set_Ekind (Derived_Type, E_Array_Type);
4883
4884             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
4885             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
4886
4887             Set_Has_Delayed_Freeze (Derived_Type, True);
4888
4889          else
4890             Make_Implicit_Base;
4891             Set_Etype (Derived_Type, Implicit_Base);
4892
4893             New_Indic :=
4894               Make_Subtype_Declaration (Loc,
4895                 Defining_Identifier => Derived_Type,
4896                 Subtype_Indication  =>
4897                   Make_Subtype_Indication (Loc,
4898                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
4899                     Constraint => Constraint (Indic)));
4900
4901             Rewrite (N, New_Indic);
4902             Analyze (N);
4903          end if;
4904
4905       else
4906          if Nkind (Indic) /= N_Subtype_Indication then
4907             Make_Implicit_Base;
4908
4909             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
4910             Set_Etype             (Derived_Type, Implicit_Base);
4911             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
4912
4913          else
4914             Error_Msg_N ("illegal constraint on constrained type", Indic);
4915          end if;
4916       end if;
4917
4918       --  If parent type is not a derived type itself, and is declared in
4919       --  closed scope (e.g. a subprogram), then we must explicitly introduce
4920       --  the new type's concatenation operator since Derive_Subprograms
4921       --  will not inherit the parent's operator. If the parent type is
4922       --  unconstrained, the operator is of the unconstrained base type.
4923
4924       if Number_Dimensions (Parent_Type) = 1
4925         and then not Is_Limited_Type (Parent_Type)
4926         and then not Is_Derived_Type (Parent_Type)
4927         and then not Is_Package_Or_Generic_Package
4928                        (Scope (Base_Type (Parent_Type)))
4929       then
4930          if not Is_Constrained (Parent_Type)
4931            and then Is_Constrained (Derived_Type)
4932          then
4933             New_Concatenation_Op (Implicit_Base);
4934          else
4935             New_Concatenation_Op (Derived_Type);
4936          end if;
4937       end if;
4938    end Build_Derived_Array_Type;
4939
4940    -----------------------------------
4941    -- Build_Derived_Concurrent_Type --
4942    -----------------------------------
4943
4944    procedure Build_Derived_Concurrent_Type
4945      (N            : Node_Id;
4946       Parent_Type  : Entity_Id;
4947       Derived_Type : Entity_Id)
4948    is
4949       Loc : constant Source_Ptr := Sloc (N);
4950
4951       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
4952       Corr_Decl        : Node_Id;
4953       Corr_Decl_Needed : Boolean;
4954       --  If the derived type has fewer discriminants than its parent, the
4955       --  corresponding record is also a derived type, in order to account for
4956       --  the bound discriminants. We create a full type declaration for it in
4957       --  this case.
4958
4959       Constraint_Present : constant Boolean :=
4960                              Nkind (Subtype_Indication (Type_Definition (N))) =
4961                                                           N_Subtype_Indication;
4962
4963       D_Constraint   : Node_Id;
4964       New_Constraint : Elist_Id;
4965       Old_Disc       : Entity_Id;
4966       New_Disc       : Entity_Id;
4967       New_N          : Node_Id;
4968
4969    begin
4970       Set_Stored_Constraint (Derived_Type, No_Elist);
4971       Corr_Decl_Needed := False;
4972       Old_Disc := Empty;
4973
4974       if Present (Discriminant_Specifications (N))
4975         and then Constraint_Present
4976       then
4977          Old_Disc := First_Discriminant (Parent_Type);
4978          New_Disc := First (Discriminant_Specifications (N));
4979          while Present (New_Disc) and then Present (Old_Disc) loop
4980             Next_Discriminant (Old_Disc);
4981             Next (New_Disc);
4982          end loop;
4983       end if;
4984
4985       if Present (Old_Disc) then
4986
4987          --  The new type has fewer discriminants, so we need to create a new
4988          --  corresponding record, which is derived from the corresponding
4989          --  record of the parent, and has a stored constraint that captures
4990          --  the values of the discriminant constraints.
4991
4992          --  The type declaration for the derived corresponding record has
4993          --  the same discriminant part and constraints as the current
4994          --  declaration. Copy the unanalyzed tree to build declaration.
4995
4996          Corr_Decl_Needed := True;
4997          New_N := Copy_Separate_Tree (N);
4998
4999          Corr_Decl :=
5000            Make_Full_Type_Declaration (Loc,
5001              Defining_Identifier => Corr_Record,
5002              Discriminant_Specifications =>
5003                 Discriminant_Specifications (New_N),
5004              Type_Definition =>
5005                Make_Derived_Type_Definition (Loc,
5006                  Subtype_Indication =>
5007                    Make_Subtype_Indication (Loc,
5008                      Subtype_Mark =>
5009                         New_Occurrence_Of
5010                           (Corresponding_Record_Type (Parent_Type), Loc),
5011                      Constraint =>
5012                        Constraint
5013                          (Subtype_Indication (Type_Definition (New_N))))));
5014       end if;
5015
5016       --  Copy Storage_Size and Relative_Deadline variables if task case
5017
5018       if Is_Task_Type (Parent_Type) then
5019          Set_Storage_Size_Variable (Derived_Type,
5020            Storage_Size_Variable (Parent_Type));
5021          Set_Relative_Deadline_Variable (Derived_Type,
5022            Relative_Deadline_Variable (Parent_Type));
5023       end if;
5024
5025       if Present (Discriminant_Specifications (N)) then
5026          Push_Scope (Derived_Type);
5027          Check_Or_Process_Discriminants (N, Derived_Type);
5028
5029          if Constraint_Present then
5030             New_Constraint :=
5031               Expand_To_Stored_Constraint
5032                 (Parent_Type,
5033                  Build_Discriminant_Constraints
5034                    (Parent_Type,
5035                     Subtype_Indication (Type_Definition (N)), True));
5036          end if;
5037
5038          End_Scope;
5039
5040       elsif Constraint_Present then
5041
5042          --  Build constrained subtype and derive from it
5043
5044          declare
5045             Loc  : constant Source_Ptr := Sloc (N);
5046             Anon : constant Entity_Id :=
5047                      Make_Defining_Identifier (Loc,
5048                        New_External_Name (Chars (Derived_Type), 'T'));
5049             Decl : Node_Id;
5050
5051          begin
5052             Decl :=
5053               Make_Subtype_Declaration (Loc,
5054                 Defining_Identifier => Anon,
5055                 Subtype_Indication =>
5056                   Subtype_Indication (Type_Definition (N)));
5057             Insert_Before (N, Decl);
5058             Analyze (Decl);
5059
5060             Rewrite (Subtype_Indication (Type_Definition (N)),
5061               New_Occurrence_Of (Anon, Loc));
5062             Set_Analyzed (Derived_Type, False);
5063             Analyze (N);
5064             return;
5065          end;
5066       end if;
5067
5068       --  By default, operations and private data are inherited from parent.
5069       --  However, in the presence of bound discriminants, a new corresponding
5070       --  record will be created, see below.
5071
5072       Set_Has_Discriminants
5073         (Derived_Type, Has_Discriminants         (Parent_Type));
5074       Set_Corresponding_Record_Type
5075         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5076
5077       --  Is_Constrained is set according the parent subtype, but is set to
5078       --  False if the derived type is declared with new discriminants.
5079
5080       Set_Is_Constrained
5081         (Derived_Type,
5082          (Is_Constrained (Parent_Type) or else Constraint_Present)
5083            and then not Present (Discriminant_Specifications (N)));
5084
5085       if Constraint_Present then
5086          if not Has_Discriminants (Parent_Type) then
5087             Error_Msg_N ("untagged parent must have discriminants", N);
5088
5089          elsif Present (Discriminant_Specifications (N)) then
5090
5091             --  Verify that new discriminants are used to constrain old ones
5092
5093             D_Constraint :=
5094               First
5095                 (Constraints
5096                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5097
5098             Old_Disc := First_Discriminant (Parent_Type);
5099
5100             while Present (D_Constraint) loop
5101                if Nkind (D_Constraint) /= N_Discriminant_Association then
5102
5103                   --  Positional constraint. If it is a reference to a new
5104                   --  discriminant, it constrains the corresponding old one.
5105
5106                   if Nkind (D_Constraint) = N_Identifier then
5107                      New_Disc := First_Discriminant (Derived_Type);
5108                      while Present (New_Disc) loop
5109                         exit when Chars (New_Disc) = Chars (D_Constraint);
5110                         Next_Discriminant (New_Disc);
5111                      end loop;
5112
5113                      if Present (New_Disc) then
5114                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5115                      end if;
5116                   end if;
5117
5118                   Next_Discriminant (Old_Disc);
5119
5120                   --  if this is a named constraint, search by name for the old
5121                   --  discriminants constrained by the new one.
5122
5123                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5124
5125                   --  Find new discriminant with that name
5126
5127                   New_Disc := First_Discriminant (Derived_Type);
5128                   while Present (New_Disc) loop
5129                      exit when
5130                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5131                      Next_Discriminant (New_Disc);
5132                   end loop;
5133
5134                   if Present (New_Disc) then
5135
5136                      --  Verify that new discriminant renames some discriminant
5137                      --  of the parent type, and associate the new discriminant
5138                      --  with one or more old ones that it renames.
5139
5140                      declare
5141                         Selector : Node_Id;
5142
5143                      begin
5144                         Selector := First (Selector_Names (D_Constraint));
5145                         while Present (Selector) loop
5146                            Old_Disc := First_Discriminant (Parent_Type);
5147                            while Present (Old_Disc) loop
5148                               exit when Chars (Old_Disc) = Chars (Selector);
5149                               Next_Discriminant (Old_Disc);
5150                            end loop;
5151
5152                            if Present (Old_Disc) then
5153                               Set_Corresponding_Discriminant
5154                                 (New_Disc, Old_Disc);
5155                            end if;
5156
5157                            Next (Selector);
5158                         end loop;
5159                      end;
5160                   end if;
5161                end if;
5162
5163                Next (D_Constraint);
5164             end loop;
5165
5166             New_Disc := First_Discriminant (Derived_Type);
5167             while Present (New_Disc) loop
5168                if No (Corresponding_Discriminant (New_Disc)) then
5169                   Error_Msg_NE
5170                     ("new discriminant& must constrain old one", N, New_Disc);
5171
5172                elsif not
5173                  Subtypes_Statically_Compatible
5174                    (Etype (New_Disc),
5175                     Etype (Corresponding_Discriminant (New_Disc)))
5176                then
5177                   Error_Msg_NE
5178                     ("& not statically compatible with parent discriminant",
5179                       N, New_Disc);
5180                end if;
5181
5182                Next_Discriminant (New_Disc);
5183             end loop;
5184          end if;
5185
5186       elsif Present (Discriminant_Specifications (N)) then
5187          Error_Msg_N
5188            ("missing discriminant constraint in untagged derivation", N);
5189       end if;
5190
5191       --  The entity chain of the derived type includes the new discriminants
5192       --  but shares operations with the parent.
5193
5194       if Present (Discriminant_Specifications (N)) then
5195          Old_Disc := First_Discriminant (Parent_Type);
5196          while Present (Old_Disc) loop
5197             if No (Next_Entity (Old_Disc))
5198               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5199             then
5200                Set_Next_Entity
5201                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5202                exit;
5203             end if;
5204
5205             Next_Discriminant (Old_Disc);
5206          end loop;
5207
5208       else
5209          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5210          if Has_Discriminants (Parent_Type) then
5211             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5212             Set_Discriminant_Constraint (
5213               Derived_Type, Discriminant_Constraint (Parent_Type));
5214          end if;
5215       end if;
5216
5217       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5218
5219       Set_Has_Completion (Derived_Type);
5220
5221       if Corr_Decl_Needed then
5222          Set_Stored_Constraint (Derived_Type, New_Constraint);
5223          Insert_After (N, Corr_Decl);
5224          Analyze (Corr_Decl);
5225          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5226       end if;
5227    end Build_Derived_Concurrent_Type;
5228
5229    ------------------------------------
5230    -- Build_Derived_Enumeration_Type --
5231    ------------------------------------
5232
5233    procedure Build_Derived_Enumeration_Type
5234      (N            : Node_Id;
5235       Parent_Type  : Entity_Id;
5236       Derived_Type : Entity_Id)
5237    is
5238       Loc           : constant Source_Ptr := Sloc (N);
5239       Def           : constant Node_Id    := Type_Definition (N);
5240       Indic         : constant Node_Id    := Subtype_Indication (Def);
5241       Implicit_Base : Entity_Id;
5242       Literal       : Entity_Id;
5243       New_Lit       : Entity_Id;
5244       Literals_List : List_Id;
5245       Type_Decl     : Node_Id;
5246       Hi, Lo        : Node_Id;
5247       Rang_Expr     : Node_Id;
5248
5249    begin
5250       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5251       --  not have explicit literals lists we need to process types derived
5252       --  from them specially. This is handled by Derived_Standard_Character.
5253       --  If the parent type is a generic type, there are no literals either,
5254       --  and we construct the same skeletal representation as for the generic
5255       --  parent type.
5256
5257       if Is_Standard_Character_Type (Parent_Type) then
5258          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5259
5260       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5261          declare
5262             Lo : Node_Id;
5263             Hi : Node_Id;
5264
5265          begin
5266             if Nkind (Indic) /= N_Subtype_Indication then
5267                Lo :=
5268                   Make_Attribute_Reference (Loc,
5269                     Attribute_Name => Name_First,
5270                     Prefix         => New_Reference_To (Derived_Type, Loc));
5271                Set_Etype (Lo, Derived_Type);
5272
5273                Hi :=
5274                   Make_Attribute_Reference (Loc,
5275                     Attribute_Name => Name_Last,
5276                     Prefix         => New_Reference_To (Derived_Type, Loc));
5277                Set_Etype (Hi, Derived_Type);
5278
5279                Set_Scalar_Range (Derived_Type,
5280                   Make_Range (Loc,
5281                     Low_Bound  => Lo,
5282                     High_Bound => Hi));
5283             else
5284
5285                --   Analyze subtype indication and verify compatibility
5286                --   with parent type.
5287
5288                if Base_Type (Process_Subtype (Indic, N)) /=
5289                   Base_Type (Parent_Type)
5290                then
5291                   Error_Msg_N
5292                     ("illegal constraint for formal discrete type", N);
5293                end if;
5294             end if;
5295          end;
5296
5297       else
5298          --  If a constraint is present, analyze the bounds to catch
5299          --  premature usage of the derived literals.
5300
5301          if Nkind (Indic) = N_Subtype_Indication
5302            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5303          then
5304             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5305             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5306          end if;
5307
5308          --  Introduce an implicit base type for the derived type even if there
5309          --  is no constraint attached to it, since this seems closer to the
5310          --  Ada semantics. Build a full type declaration tree for the derived
5311          --  type using the implicit base type as the defining identifier. The
5312          --  build a subtype declaration tree which applies the constraint (if
5313          --  any) have it replace the derived type declaration.
5314
5315          Literal := First_Literal (Parent_Type);
5316          Literals_List := New_List;
5317          while Present (Literal)
5318            and then Ekind (Literal) = E_Enumeration_Literal
5319          loop
5320             --  Literals of the derived type have the same representation as
5321             --  those of the parent type, but this representation can be
5322             --  overridden by an explicit representation clause. Indicate
5323             --  that there is no explicit representation given yet. These
5324             --  derived literals are implicit operations of the new type,
5325             --  and can be overridden by explicit ones.
5326
5327             if Nkind (Literal) = N_Defining_Character_Literal then
5328                New_Lit :=
5329                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5330             else
5331                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5332             end if;
5333
5334             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5335             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5336             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5337             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5338             Set_Alias                (New_Lit, Literal);
5339             Set_Is_Known_Valid       (New_Lit, True);
5340
5341             Append (New_Lit, Literals_List);
5342             Next_Literal (Literal);
5343          end loop;
5344
5345          Implicit_Base :=
5346            Make_Defining_Identifier (Sloc (Derived_Type),
5347              New_External_Name (Chars (Derived_Type), 'B'));
5348
5349          --  Indicate the proper nature of the derived type. This must be done
5350          --  before analysis of the literals, to recognize cases when a literal
5351          --  may be hidden by a previous explicit function definition (cf.
5352          --  c83031a).
5353
5354          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5355          Set_Etype (Derived_Type, Implicit_Base);
5356
5357          Type_Decl :=
5358            Make_Full_Type_Declaration (Loc,
5359              Defining_Identifier => Implicit_Base,
5360              Discriminant_Specifications => No_List,
5361              Type_Definition =>
5362                Make_Enumeration_Type_Definition (Loc, Literals_List));
5363
5364          Mark_Rewrite_Insertion (Type_Decl);
5365          Insert_Before (N, Type_Decl);
5366          Analyze (Type_Decl);
5367
5368          --  After the implicit base is analyzed its Etype needs to be changed
5369          --  to reflect the fact that it is derived from the parent type which
5370          --  was ignored during analysis. We also set the size at this point.
5371
5372          Set_Etype (Implicit_Base, Parent_Type);
5373
5374          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5375          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5376          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5377
5378          --  Copy other flags from parent type
5379
5380          Set_Has_Non_Standard_Rep
5381                             (Implicit_Base, Has_Non_Standard_Rep
5382                                                            (Parent_Type));
5383          Set_Has_Pragma_Ordered
5384                             (Implicit_Base, Has_Pragma_Ordered
5385                                                            (Parent_Type));
5386          Set_Has_Delayed_Freeze (Implicit_Base);
5387
5388          --  Process the subtype indication including a validation check on the
5389          --  constraint, if any. If a constraint is given, its bounds must be
5390          --  implicitly converted to the new type.
5391
5392          if Nkind (Indic) = N_Subtype_Indication then
5393             declare
5394                R : constant Node_Id :=
5395                      Range_Expression (Constraint (Indic));
5396
5397             begin
5398                if Nkind (R) = N_Range then
5399                   Hi := Build_Scalar_Bound
5400                           (High_Bound (R), Parent_Type, Implicit_Base);
5401                   Lo := Build_Scalar_Bound
5402                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5403
5404                else
5405                   --  Constraint is a Range attribute. Replace with explicit
5406                   --  mention of the bounds of the prefix, which must be a
5407                   --  subtype.
5408
5409                   Analyze (Prefix (R));
5410                   Hi :=
5411                     Convert_To (Implicit_Base,
5412                       Make_Attribute_Reference (Loc,
5413                         Attribute_Name => Name_Last,
5414                         Prefix =>
5415                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5416
5417                   Lo :=
5418                     Convert_To (Implicit_Base,
5419                       Make_Attribute_Reference (Loc,
5420                         Attribute_Name => Name_First,
5421                         Prefix =>
5422                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5423                end if;
5424             end;
5425
5426          else
5427             Hi :=
5428               Build_Scalar_Bound
5429                 (Type_High_Bound (Parent_Type),
5430                  Parent_Type, Implicit_Base);
5431             Lo :=
5432                Build_Scalar_Bound
5433                  (Type_Low_Bound (Parent_Type),
5434                   Parent_Type, Implicit_Base);
5435          end if;
5436
5437          Rang_Expr :=
5438            Make_Range (Loc,
5439              Low_Bound  => Lo,
5440              High_Bound => Hi);
5441
5442          --  If we constructed a default range for the case where no range
5443          --  was given, then the expressions in the range must not freeze
5444          --  since they do not correspond to expressions in the source.
5445
5446          if Nkind (Indic) /= N_Subtype_Indication then
5447             Set_Must_Not_Freeze (Lo);
5448             Set_Must_Not_Freeze (Hi);
5449             Set_Must_Not_Freeze (Rang_Expr);
5450          end if;
5451
5452          Rewrite (N,
5453            Make_Subtype_Declaration (Loc,
5454              Defining_Identifier => Derived_Type,
5455              Subtype_Indication =>
5456                Make_Subtype_Indication (Loc,
5457                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
5458                  Constraint =>
5459                    Make_Range_Constraint (Loc,
5460                      Range_Expression => Rang_Expr))));
5461
5462          Analyze (N);
5463
5464          --  If pragma Discard_Names applies on the first subtype of the parent
5465          --  type, then it must be applied on this subtype as well.
5466
5467          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
5468             Set_Discard_Names (Derived_Type);
5469          end if;
5470
5471          --  Apply a range check. Since this range expression doesn't have an
5472          --  Etype, we have to specifically pass the Source_Typ parameter. Is
5473          --  this right???
5474
5475          if Nkind (Indic) = N_Subtype_Indication then
5476             Apply_Range_Check (Range_Expression (Constraint (Indic)),
5477                                Parent_Type,
5478                                Source_Typ => Entity (Subtype_Mark (Indic)));
5479          end if;
5480       end if;
5481    end Build_Derived_Enumeration_Type;
5482
5483    --------------------------------
5484    -- Build_Derived_Numeric_Type --
5485    --------------------------------
5486
5487    procedure Build_Derived_Numeric_Type
5488      (N            : Node_Id;
5489       Parent_Type  : Entity_Id;
5490       Derived_Type : Entity_Id)
5491    is
5492       Loc           : constant Source_Ptr := Sloc (N);
5493       Tdef          : constant Node_Id    := Type_Definition (N);
5494       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5495       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5496       No_Constraint : constant Boolean    := Nkind (Indic) /=
5497                                                   N_Subtype_Indication;
5498       Implicit_Base : Entity_Id;
5499
5500       Lo : Node_Id;
5501       Hi : Node_Id;
5502
5503    begin
5504       --  Process the subtype indication including a validation check on
5505       --  the constraint if any.
5506
5507       Discard_Node (Process_Subtype (Indic, N));
5508
5509       --  Introduce an implicit base type for the derived type even if there
5510       --  is no constraint attached to it, since this seems closer to the Ada
5511       --  semantics.
5512
5513       Implicit_Base :=
5514         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5515
5516       Set_Etype          (Implicit_Base, Parent_Base);
5517       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
5518       Set_Size_Info      (Implicit_Base,                 Parent_Base);
5519       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
5520       Set_Parent         (Implicit_Base, Parent (Derived_Type));
5521       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
5522
5523       --  Set RM Size for discrete type or decimal fixed-point type
5524       --  Ordinary fixed-point is excluded, why???
5525
5526       if Is_Discrete_Type (Parent_Base)
5527         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
5528       then
5529          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
5530       end if;
5531
5532       Set_Has_Delayed_Freeze (Implicit_Base);
5533
5534       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
5535       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
5536
5537       Set_Scalar_Range (Implicit_Base,
5538         Make_Range (Loc,
5539           Low_Bound  => Lo,
5540           High_Bound => Hi));
5541
5542       if Has_Infinities (Parent_Base) then
5543          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
5544       end if;
5545
5546       --  The Derived_Type, which is the entity of the declaration, is a
5547       --  subtype of the implicit base. Its Ekind is a subtype, even in the
5548       --  absence of an explicit constraint.
5549
5550       Set_Etype (Derived_Type, Implicit_Base);
5551
5552       --  If we did not have a constraint, then the Ekind is set from the
5553       --  parent type (otherwise Process_Subtype has set the bounds)
5554
5555       if No_Constraint then
5556          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
5557       end if;
5558
5559       --  If we did not have a range constraint, then set the range from the
5560       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
5561
5562       if No_Constraint
5563         or else not Has_Range_Constraint (Indic)
5564       then
5565          Set_Scalar_Range (Derived_Type,
5566            Make_Range (Loc,
5567              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
5568              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
5569          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5570
5571          if Has_Infinities (Parent_Type) then
5572             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5573          end if;
5574
5575          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
5576       end if;
5577
5578       Set_Is_Descendent_Of_Address (Derived_Type,
5579         Is_Descendent_Of_Address (Parent_Type));
5580       Set_Is_Descendent_Of_Address (Implicit_Base,
5581         Is_Descendent_Of_Address (Parent_Type));
5582
5583       --  Set remaining type-specific fields, depending on numeric type
5584
5585       if Is_Modular_Integer_Type (Parent_Type) then
5586          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5587
5588          Set_Non_Binary_Modulus
5589            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5590
5591          Set_Is_Known_Valid
5592            (Implicit_Base, Is_Known_Valid (Parent_Base));
5593
5594       elsif Is_Floating_Point_Type (Parent_Type) then
5595
5596          --  Digits of base type is always copied from the digits value of
5597          --  the parent base type, but the digits of the derived type will
5598          --  already have been set if there was a constraint present.
5599
5600          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5601          Set_Vax_Float    (Implicit_Base, Vax_Float    (Parent_Base));
5602
5603          if No_Constraint then
5604             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5605          end if;
5606
5607       elsif Is_Fixed_Point_Type (Parent_Type) then
5608
5609          --  Small of base type and derived type are always copied from the
5610          --  parent base type, since smalls never change. The delta of the
5611          --  base type is also copied from the parent base type. However the
5612          --  delta of the derived type will have been set already if a
5613          --  constraint was present.
5614
5615          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5616          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5617          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5618
5619          if No_Constraint then
5620             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5621          end if;
5622
5623          --  The scale and machine radix in the decimal case are always
5624          --  copied from the parent base type.
5625
5626          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
5627             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
5628             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
5629
5630             Set_Machine_Radix_10
5631               (Derived_Type,  Machine_Radix_10 (Parent_Base));
5632             Set_Machine_Radix_10
5633               (Implicit_Base, Machine_Radix_10 (Parent_Base));
5634
5635             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5636
5637             if No_Constraint then
5638                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
5639
5640             else
5641                --  the analysis of the subtype_indication sets the
5642                --  digits value of the derived type.
5643
5644                null;
5645             end if;
5646          end if;
5647       end if;
5648
5649       --  The type of the bounds is that of the parent type, and they
5650       --  must be converted to the derived type.
5651
5652       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
5653
5654       --  The implicit_base should be frozen when the derived type is frozen,
5655       --  but note that it is used in the conversions of the bounds. For fixed
5656       --  types we delay the determination of the bounds until the proper
5657       --  freezing point. For other numeric types this is rejected by GCC, for
5658       --  reasons that are currently unclear (???), so we choose to freeze the
5659       --  implicit base now. In the case of integers and floating point types
5660       --  this is harmless because subsequent representation clauses cannot
5661       --  affect anything, but it is still baffling that we cannot use the
5662       --  same mechanism for all derived numeric types.
5663
5664       --  There is a further complication: actually *some* representation
5665       --  clauses can affect the implicit base type. Namely, attribute
5666       --  definition clauses for stream-oriented attributes need to set the
5667       --  corresponding TSS entries on the base type, and this normally cannot
5668       --  be done after the base type is frozen, so the circuitry in
5669       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
5670       --  not use Set_TSS in this case.
5671
5672       if Is_Fixed_Point_Type (Parent_Type) then
5673          Conditional_Delay (Implicit_Base, Parent_Type);
5674       else
5675          Freeze_Before (N, Implicit_Base);
5676       end if;
5677    end Build_Derived_Numeric_Type;
5678
5679    --------------------------------
5680    -- Build_Derived_Private_Type --
5681    --------------------------------
5682
5683    procedure Build_Derived_Private_Type
5684      (N             : Node_Id;
5685       Parent_Type   : Entity_Id;
5686       Derived_Type  : Entity_Id;
5687       Is_Completion : Boolean;
5688       Derive_Subps  : Boolean := True)
5689    is
5690       Loc         : constant Source_Ptr := Sloc (N);
5691       Der_Base    : Entity_Id;
5692       Discr       : Entity_Id;
5693       Full_Decl   : Node_Id := Empty;
5694       Full_Der    : Entity_Id;
5695       Full_P      : Entity_Id;
5696       Last_Discr  : Entity_Id;
5697       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
5698       Swapped     : Boolean := False;
5699
5700       procedure Copy_And_Build;
5701       --  Copy derived type declaration, replace parent with its full view,
5702       --  and analyze new declaration.
5703
5704       --------------------
5705       -- Copy_And_Build --
5706       --------------------
5707
5708       procedure Copy_And_Build is
5709          Full_N : Node_Id;
5710
5711       begin
5712          if Ekind (Parent_Type) in Record_Kind
5713            or else
5714              (Ekind (Parent_Type) in Enumeration_Kind
5715                and then not Is_Standard_Character_Type (Parent_Type)
5716                and then not Is_Generic_Type (Root_Type (Parent_Type)))
5717          then
5718             Full_N := New_Copy_Tree (N);
5719             Insert_After (N, Full_N);
5720             Build_Derived_Type (
5721               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
5722
5723          else
5724             Build_Derived_Type (
5725               N, Parent_Type, Full_Der, True, Derive_Subps => False);
5726          end if;
5727       end Copy_And_Build;
5728
5729    --  Start of processing for Build_Derived_Private_Type
5730
5731    begin
5732       if Is_Tagged_Type (Parent_Type) then
5733          Full_P := Full_View (Parent_Type);
5734
5735          --  A type extension of a type with unknown discriminants is an
5736          --  indefinite type that the back-end cannot handle directly.
5737          --  We treat it as a private type, and build a completion that is
5738          --  derived from the full view of the parent, and hopefully has
5739          --  known discriminants.
5740
5741          --  If the full view of the parent type has an underlying record view,
5742          --  use it to generate the underlying record view of this derived type
5743          --  (required for chains of derivations with unknown discriminants).
5744
5745          --  Minor optimization: we avoid the generation of useless underlying
5746          --  record view entities if the private type declaration has unknown
5747          --  discriminants but its corresponding full view has no
5748          --  discriminants.
5749
5750          if Has_Unknown_Discriminants (Parent_Type)
5751            and then Present (Full_P)
5752            and then (Has_Discriminants (Full_P)
5753                       or else Present (Underlying_Record_View (Full_P)))
5754            and then not In_Open_Scopes (Par_Scope)
5755            and then Expander_Active
5756          then
5757             declare
5758                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
5759                New_Ext  : constant Node_Id :=
5760                             Copy_Separate_Tree
5761                               (Record_Extension_Part (Type_Definition (N)));
5762                Decl     : Node_Id;
5763
5764             begin
5765                Build_Derived_Record_Type
5766                  (N, Parent_Type, Derived_Type, Derive_Subps);
5767
5768                --  Build anonymous completion, as a derivation from the full
5769                --  view of the parent. This is not a completion in the usual
5770                --  sense, because the current type is not private.
5771
5772                Decl :=
5773                  Make_Full_Type_Declaration (Loc,
5774                    Defining_Identifier => Full_Der,
5775                    Type_Definition     =>
5776                      Make_Derived_Type_Definition (Loc,
5777                        Subtype_Indication =>
5778                          New_Copy_Tree
5779                            (Subtype_Indication (Type_Definition (N))),
5780                        Record_Extension_Part => New_Ext));
5781
5782                --  If the parent type has an underlying record view, use it
5783                --  here to build the new underlying record view.
5784
5785                if Present (Underlying_Record_View (Full_P)) then
5786                   pragma Assert
5787                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
5788                        = N_Identifier);
5789                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
5790                     Underlying_Record_View (Full_P));
5791                end if;
5792
5793                Install_Private_Declarations (Par_Scope);
5794                Install_Visible_Declarations (Par_Scope);
5795                Insert_Before (N, Decl);
5796
5797                --  Mark entity as an underlying record view before analysis,
5798                --  to avoid generating the list of its primitive operations
5799                --  (which is not really required for this entity) and thus
5800                --  prevent spurious errors associated with missing overriding
5801                --  of abstract primitives (overridden only for Derived_Type).
5802
5803                Set_Ekind (Full_Der, E_Record_Type);
5804                Set_Is_Underlying_Record_View (Full_Der);
5805
5806                Analyze (Decl);
5807
5808                pragma Assert (Has_Discriminants (Full_Der)
5809                  and then not Has_Unknown_Discriminants (Full_Der));
5810
5811                Uninstall_Declarations (Par_Scope);
5812
5813                --  Freeze the underlying record view, to prevent generation of
5814                --  useless dispatching information, which is simply shared with
5815                --  the real derived type.
5816
5817                Set_Is_Frozen (Full_Der);
5818
5819                --  Set up links between real entity and underlying record view
5820
5821                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
5822                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
5823             end;
5824
5825          --  If discriminants are known, build derived record
5826
5827          else
5828             Build_Derived_Record_Type
5829               (N, Parent_Type, Derived_Type, Derive_Subps);
5830          end if;
5831
5832          return;
5833
5834       elsif Has_Discriminants (Parent_Type) then
5835          if Present (Full_View (Parent_Type)) then
5836             if not Is_Completion then
5837
5838                --  Copy declaration for subsequent analysis, to provide a
5839                --  completion for what is a private declaration. Indicate that
5840                --  the full type is internally generated.
5841
5842                Full_Decl := New_Copy_Tree (N);
5843                Full_Der  := New_Copy (Derived_Type);
5844                Set_Comes_From_Source (Full_Decl, False);
5845                Set_Comes_From_Source (Full_Der, False);
5846                Set_Parent (Full_Der, Full_Decl);
5847
5848                Insert_After (N, Full_Decl);
5849
5850             else
5851                --  If this is a completion, the full view being built is itself
5852                --  private. We build a subtype of the parent with the same
5853                --  constraints as this full view, to convey to the back end the
5854                --  constrained components and the size of this subtype. If the
5855                --  parent is constrained, its full view can serve as the
5856                --  underlying full view of the derived type.
5857
5858                if No (Discriminant_Specifications (N)) then
5859                   if Nkind (Subtype_Indication (Type_Definition (N))) =
5860                                                         N_Subtype_Indication
5861                   then
5862                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
5863
5864                   elsif Is_Constrained (Full_View (Parent_Type)) then
5865                      Set_Underlying_Full_View
5866                        (Derived_Type, Full_View (Parent_Type));
5867                   end if;
5868
5869                else
5870                   --  If there are new discriminants, the parent subtype is
5871                   --  constrained by them, but it is not clear how to build
5872                   --  the Underlying_Full_View in this case???
5873
5874                   null;
5875                end if;
5876             end if;
5877          end if;
5878
5879          --  Build partial view of derived type from partial view of parent
5880
5881          Build_Derived_Record_Type
5882            (N, Parent_Type, Derived_Type, Derive_Subps);
5883
5884          if Present (Full_View (Parent_Type)) and then not Is_Completion then
5885             if not In_Open_Scopes (Par_Scope)
5886               or else not In_Same_Source_Unit (N, Parent_Type)
5887             then
5888                --  Swap partial and full views temporarily
5889
5890                Install_Private_Declarations (Par_Scope);
5891                Install_Visible_Declarations (Par_Scope);
5892                Swapped := True;
5893             end if;
5894
5895             --  Build full view of derived type from full view of parent which
5896             --  is now installed. Subprograms have been derived on the partial
5897             --  view, the completion does not derive them anew.
5898
5899             if not Is_Tagged_Type (Parent_Type) then
5900
5901                --  If the parent is itself derived from another private type,
5902                --  installing the private declarations has not affected its
5903                --  privacy status, so use its own full view explicitly.
5904
5905                if Is_Private_Type (Parent_Type) then
5906                   Build_Derived_Record_Type
5907                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
5908                else
5909                   Build_Derived_Record_Type
5910                     (Full_Decl, Parent_Type, Full_Der, False);
5911                end if;
5912
5913             else
5914                --  If full view of parent is tagged, the completion inherits
5915                --  the proper primitive operations.
5916
5917                Set_Defining_Identifier (Full_Decl, Full_Der);
5918                Build_Derived_Record_Type
5919                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
5920             end if;
5921
5922             --  The full declaration has been introduced into the tree and
5923             --  processed in the step above. It should not be analyzed again
5924             --  (when encountered later in the current list of declarations)
5925             --  to prevent spurious name conflicts. The full entity remains
5926             --  invisible.
5927
5928             Set_Analyzed (Full_Decl);
5929
5930             if Swapped then
5931                Uninstall_Declarations (Par_Scope);
5932
5933                if In_Open_Scopes (Par_Scope) then
5934                   Install_Visible_Declarations (Par_Scope);
5935                end if;
5936             end if;
5937
5938             Der_Base := Base_Type (Derived_Type);
5939             Set_Full_View (Derived_Type, Full_Der);
5940             Set_Full_View (Der_Base, Base_Type (Full_Der));
5941
5942             --  Copy the discriminant list from full view to the partial views
5943             --  (base type and its subtype). Gigi requires that the partial and
5944             --  full views have the same discriminants.
5945
5946             --  Note that since the partial view is pointing to discriminants
5947             --  in the full view, their scope will be that of the full view.
5948             --  This might cause some front end problems and need adjustment???
5949
5950             Discr := First_Discriminant (Base_Type (Full_Der));
5951             Set_First_Entity (Der_Base, Discr);
5952
5953             loop
5954                Last_Discr := Discr;
5955                Next_Discriminant (Discr);
5956                exit when No (Discr);
5957             end loop;
5958
5959             Set_Last_Entity (Der_Base, Last_Discr);
5960
5961             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
5962             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
5963             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
5964
5965          else
5966             --  If this is a completion, the derived type stays private and
5967             --  there is no need to create a further full view, except in the
5968             --  unusual case when the derivation is nested within a child unit,
5969             --  see below.
5970
5971             null;
5972          end if;
5973
5974       elsif Present (Full_View (Parent_Type))
5975         and then  Has_Discriminants (Full_View (Parent_Type))
5976       then
5977          if Has_Unknown_Discriminants (Parent_Type)
5978            and then Nkind (Subtype_Indication (Type_Definition (N))) =
5979                                                          N_Subtype_Indication
5980          then
5981             Error_Msg_N
5982               ("cannot constrain type with unknown discriminants",
5983                Subtype_Indication (Type_Definition (N)));
5984             return;
5985          end if;
5986
5987          --  If full view of parent is a record type, build full view as a
5988          --  derivation from the parent's full view. Partial view remains
5989          --  private. For code generation and linking, the full view must have
5990          --  the same public status as the partial one. This full view is only
5991          --  needed if the parent type is in an enclosing scope, so that the
5992          --  full view may actually become visible, e.g. in a child unit. This
5993          --  is both more efficient, and avoids order of freezing problems with
5994          --  the added entities.
5995
5996          if not Is_Private_Type (Full_View (Parent_Type))
5997            and then (In_Open_Scopes (Scope (Parent_Type)))
5998          then
5999             Full_Der := Make_Defining_Identifier (Sloc (Derived_Type),
6000                                               Chars (Derived_Type));
6001             Set_Is_Itype (Full_Der);
6002             Set_Has_Private_Declaration (Full_Der);
6003             Set_Has_Private_Declaration (Derived_Type);
6004             Set_Associated_Node_For_Itype (Full_Der, N);
6005             Set_Parent (Full_Der, Parent (Derived_Type));
6006             Set_Full_View (Derived_Type, Full_Der);
6007             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6008             Full_P := Full_View (Parent_Type);
6009             Exchange_Declarations (Parent_Type);
6010             Copy_And_Build;
6011             Exchange_Declarations (Full_P);
6012
6013          else
6014             Build_Derived_Record_Type
6015               (N, Full_View (Parent_Type), Derived_Type,
6016                 Derive_Subps => False);
6017          end if;
6018
6019          --  In any case, the primitive operations are inherited from the
6020          --  parent type, not from the internal full view.
6021
6022          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6023
6024          if Derive_Subps then
6025             Derive_Subprograms (Parent_Type, Derived_Type);
6026          end if;
6027
6028       else
6029          --  Untagged type, No discriminants on either view
6030
6031          if Nkind (Subtype_Indication (Type_Definition (N))) =
6032                                                    N_Subtype_Indication
6033          then
6034             Error_Msg_N
6035               ("illegal constraint on type without discriminants", N);
6036          end if;
6037
6038          if Present (Discriminant_Specifications (N))
6039            and then Present (Full_View (Parent_Type))
6040            and then not Is_Tagged_Type (Full_View (Parent_Type))
6041          then
6042             Error_Msg_N ("cannot add discriminants to untagged type", N);
6043          end if;
6044
6045          Set_Stored_Constraint (Derived_Type, No_Elist);
6046          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6047          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6048          Set_Has_Controlled_Component
6049                                (Derived_Type, Has_Controlled_Component
6050                                                              (Parent_Type));
6051
6052          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6053
6054          if not Is_Controlled  (Parent_Type) then
6055             Set_Finalize_Storage_Only
6056               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6057          end if;
6058
6059          --  Construct the implicit full view by deriving from full view of the
6060          --  parent type. In order to get proper visibility, we install the
6061          --  parent scope and its declarations.
6062
6063          --  ??? If the parent is untagged private and its completion is
6064          --  tagged, this mechanism will not work because we cannot derive from
6065          --  the tagged full view unless we have an extension.
6066
6067          if Present (Full_View (Parent_Type))
6068            and then not Is_Tagged_Type (Full_View (Parent_Type))
6069            and then not Is_Completion
6070          then
6071             Full_Der :=
6072               Make_Defining_Identifier (Sloc (Derived_Type),
6073                 Chars => Chars (Derived_Type));
6074             Set_Is_Itype (Full_Der);
6075             Set_Has_Private_Declaration (Full_Der);
6076             Set_Has_Private_Declaration (Derived_Type);
6077             Set_Associated_Node_For_Itype (Full_Der, N);
6078             Set_Parent (Full_Der, Parent (Derived_Type));
6079             Set_Full_View (Derived_Type, Full_Der);
6080
6081             if not In_Open_Scopes (Par_Scope) then
6082                Install_Private_Declarations (Par_Scope);
6083                Install_Visible_Declarations (Par_Scope);
6084                Copy_And_Build;
6085                Uninstall_Declarations (Par_Scope);
6086
6087             --  If parent scope is open and in another unit, and parent has a
6088             --  completion, then the derivation is taking place in the visible
6089             --  part of a child unit. In that case retrieve the full view of
6090             --  the parent momentarily.
6091
6092             elsif not In_Same_Source_Unit (N, Parent_Type) then
6093                Full_P := Full_View (Parent_Type);
6094                Exchange_Declarations (Parent_Type);
6095                Copy_And_Build;
6096                Exchange_Declarations (Full_P);
6097
6098             --  Otherwise it is a local derivation
6099
6100             else
6101                Copy_And_Build;
6102             end if;
6103
6104             Set_Scope                (Full_Der, Current_Scope);
6105             Set_Is_First_Subtype     (Full_Der,
6106                                        Is_First_Subtype (Derived_Type));
6107             Set_Has_Size_Clause      (Full_Der, False);
6108             Set_Has_Alignment_Clause (Full_Der, False);
6109             Set_Next_Entity          (Full_Der, Empty);
6110             Set_Has_Delayed_Freeze   (Full_Der);
6111             Set_Is_Frozen            (Full_Der, False);
6112             Set_Freeze_Node          (Full_Der, Empty);
6113             Set_Depends_On_Private   (Full_Der,
6114                                        Has_Private_Component (Full_Der));
6115             Set_Public_Status        (Full_Der);
6116          end if;
6117       end if;
6118
6119       Set_Has_Unknown_Discriminants (Derived_Type,
6120         Has_Unknown_Discriminants (Parent_Type));
6121
6122       if Is_Private_Type (Derived_Type) then
6123          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6124       end if;
6125
6126       if Is_Private_Type (Parent_Type)
6127         and then Base_Type (Parent_Type) = Parent_Type
6128         and then In_Open_Scopes (Scope (Parent_Type))
6129       then
6130          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6131
6132          if Is_Child_Unit (Scope (Current_Scope))
6133            and then Is_Completion
6134            and then In_Private_Part (Current_Scope)
6135            and then Scope (Parent_Type) /= Current_Scope
6136          then
6137             --  This is the unusual case where a type completed by a private
6138             --  derivation occurs within a package nested in a child unit, and
6139             --  the parent is declared in an ancestor. In this case, the full
6140             --  view of the parent type will become visible in the body of
6141             --  the enclosing child, and only then will the current type be
6142             --  possibly non-private. We build a underlying full view that
6143             --  will be installed when the enclosing child body is compiled.
6144
6145             Full_Der :=
6146               Make_Defining_Identifier (Sloc (Derived_Type),
6147                 Chars => Chars (Derived_Type));
6148             Set_Is_Itype (Full_Der);
6149             Build_Itype_Reference (Full_Der, N);
6150
6151             --  The full view will be used to swap entities on entry/exit to
6152             --  the body, and must appear in the entity list for the package.
6153
6154             Append_Entity (Full_Der, Scope (Derived_Type));
6155             Set_Has_Private_Declaration (Full_Der);
6156             Set_Has_Private_Declaration (Derived_Type);
6157             Set_Associated_Node_For_Itype (Full_Der, N);
6158             Set_Parent (Full_Der, Parent (Derived_Type));
6159             Full_P := Full_View (Parent_Type);
6160             Exchange_Declarations (Parent_Type);
6161             Copy_And_Build;
6162             Exchange_Declarations (Full_P);
6163             Set_Underlying_Full_View (Derived_Type, Full_Der);
6164          end if;
6165       end if;
6166    end Build_Derived_Private_Type;
6167
6168    -------------------------------
6169    -- Build_Derived_Record_Type --
6170    -------------------------------
6171
6172    --  1. INTRODUCTION
6173
6174    --  Ideally we would like to use the same model of type derivation for
6175    --  tagged and untagged record types. Unfortunately this is not quite
6176    --  possible because the semantics of representation clauses is different
6177    --  for tagged and untagged records under inheritance. Consider the
6178    --  following:
6179
6180    --     type R (...) is [tagged] record ... end record;
6181    --     type T (...) is new R (...) [with ...];
6182
6183    --  The representation clauses for T can specify a completely different
6184    --  record layout from R's. Hence the same component can be placed in two
6185    --  very different positions in objects of type T and R. If R and T are
6186    --  tagged types, representation clauses for T can only specify the layout
6187    --  of non inherited components, thus components that are common in R and T
6188    --  have the same position in objects of type R and T.
6189
6190    --  This has two implications. The first is that the entire tree for R's
6191    --  declaration needs to be copied for T in the untagged case, so that T
6192    --  can be viewed as a record type of its own with its own representation
6193    --  clauses. The second implication is the way we handle discriminants.
6194    --  Specifically, in the untagged case we need a way to communicate to Gigi
6195    --  what are the real discriminants in the record, while for the semantics
6196    --  we need to consider those introduced by the user to rename the
6197    --  discriminants in the parent type. This is handled by introducing the
6198    --  notion of stored discriminants. See below for more.
6199
6200    --  Fortunately the way regular components are inherited can be handled in
6201    --  the same way in tagged and untagged types.
6202
6203    --  To complicate things a bit more the private view of a private extension
6204    --  cannot be handled in the same way as the full view (for one thing the
6205    --  semantic rules are somewhat different). We will explain what differs
6206    --  below.
6207
6208    --  2. DISCRIMINANTS UNDER INHERITANCE
6209
6210    --  The semantic rules governing the discriminants of derived types are
6211    --  quite subtle.
6212
6213    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6214    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6215
6216    --  If parent type has discriminants, then the discriminants that are
6217    --  declared in the derived type are [3.4 (11)]:
6218
6219    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6220    --    there is one;
6221
6222    --  o Otherwise, each discriminant of the parent type (implicitly declared
6223    --    in the same order with the same specifications). In this case, the
6224    --    discriminants are said to be "inherited", or if unknown in the parent
6225    --    are also unknown in the derived type.
6226
6227    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6228
6229    --  o The parent subtype shall be constrained;
6230
6231    --  o If the parent type is not a tagged type, then each discriminant of
6232    --    the derived type shall be used in the constraint defining a parent
6233    --    subtype. [Implementation note: This ensures that the new discriminant
6234    --    can share storage with an existing discriminant.]
6235
6236    --  For the derived type each discriminant of the parent type is either
6237    --  inherited, constrained to equal some new discriminant of the derived
6238    --  type, or constrained to the value of an expression.
6239
6240    --  When inherited or constrained to equal some new discriminant, the
6241    --  parent discriminant and the discriminant of the derived type are said
6242    --  to "correspond".
6243
6244    --  If a discriminant of the parent type is constrained to a specific value
6245    --  in the derived type definition, then the discriminant is said to be
6246    --  "specified" by that derived type definition.
6247
6248    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6249
6250    --  We have spoken about stored discriminants in point 1 (introduction)
6251    --  above. There are two sort of stored discriminants: implicit and
6252    --  explicit. As long as the derived type inherits the same discriminants as
6253    --  the root record type, stored discriminants are the same as regular
6254    --  discriminants, and are said to be implicit. However, if any discriminant
6255    --  in the root type was renamed in the derived type, then the derived
6256    --  type will contain explicit stored discriminants. Explicit stored
6257    --  discriminants are discriminants in addition to the semantically visible
6258    --  discriminants defined for the derived type. Stored discriminants are
6259    --  used by Gigi to figure out what are the physical discriminants in
6260    --  objects of the derived type (see precise definition in einfo.ads).
6261    --  As an example, consider the following:
6262
6263    --           type R  (D1, D2, D3 : Int) is record ... end record;
6264    --           type T1 is new R;
6265    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6266    --           type T3 is new T2;
6267    --           type T4 (Y : Int) is new T3 (Y, 99);
6268
6269    --  The following table summarizes the discriminants and stored
6270    --  discriminants in R and T1 through T4.
6271
6272    --   Type      Discrim     Stored Discrim  Comment
6273    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6274    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6275    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6276    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6277    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6278
6279    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6280    --  find the corresponding discriminant in the parent type, while
6281    --  Original_Record_Component (abbreviated ORC below), the actual physical
6282    --  component that is renamed. Finally the field Is_Completely_Hidden
6283    --  (abbreviated ICH below) is set for all explicit stored discriminants
6284    --  (see einfo.ads for more info). For the above example this gives:
6285
6286    --                 Discrim     CD        ORC     ICH
6287    --                 ^^^^^^^     ^^        ^^^     ^^^
6288    --                 D1 in R    empty     itself    no
6289    --                 D2 in R    empty     itself    no
6290    --                 D3 in R    empty     itself    no
6291
6292    --                 D1 in T1  D1 in R    itself    no
6293    --                 D2 in T1  D2 in R    itself    no
6294    --                 D3 in T1  D3 in R    itself    no
6295
6296    --                 X1 in T2  D3 in T1  D3 in T2   no
6297    --                 X2 in T2  D1 in T1  D1 in T2   no
6298    --                 D1 in T2   empty    itself    yes
6299    --                 D2 in T2   empty    itself    yes
6300    --                 D3 in T2   empty    itself    yes
6301
6302    --                 X1 in T3  X1 in T2  D3 in T3   no
6303    --                 X2 in T3  X2 in T2  D1 in T3   no
6304    --                 D1 in T3   empty    itself    yes
6305    --                 D2 in T3   empty    itself    yes
6306    --                 D3 in T3   empty    itself    yes
6307
6308    --                 Y  in T4  X1 in T3  D3 in T3   no
6309    --                 D1 in T3   empty    itself    yes
6310    --                 D2 in T3   empty    itself    yes
6311    --                 D3 in T3   empty    itself    yes
6312
6313    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6314
6315    --  Type derivation for tagged types is fairly straightforward. If no
6316    --  discriminants are specified by the derived type, these are inherited
6317    --  from the parent. No explicit stored discriminants are ever necessary.
6318    --  The only manipulation that is done to the tree is that of adding a
6319    --  _parent field with parent type and constrained to the same constraint
6320    --  specified for the parent in the derived type definition. For instance:
6321
6322    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6323    --           type T1 is new R with null record;
6324    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6325
6326    --  are changed into:
6327
6328    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6329    --              _parent : R (D1, D2, D3);
6330    --           end record;
6331
6332    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6333    --              _parent : T1 (X2, 88, X1);
6334    --           end record;
6335
6336    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6337    --  ORC and ICH fields are:
6338
6339    --                 Discrim     CD        ORC     ICH
6340    --                 ^^^^^^^     ^^        ^^^     ^^^
6341    --                 D1 in R    empty     itself    no
6342    --                 D2 in R    empty     itself    no
6343    --                 D3 in R    empty     itself    no
6344
6345    --                 D1 in T1  D1 in R    D1 in R   no
6346    --                 D2 in T1  D2 in R    D2 in R   no
6347    --                 D3 in T1  D3 in R    D3 in R   no
6348
6349    --                 X1 in T2  D3 in T1   D3 in R   no
6350    --                 X2 in T2  D1 in T1   D1 in R   no
6351
6352    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6353    --
6354    --  Regardless of whether we dealing with a tagged or untagged type
6355    --  we will transform all derived type declarations of the form
6356    --
6357    --               type T is new R (...) [with ...];
6358    --  or
6359    --               subtype S is R (...);
6360    --               type T is new S [with ...];
6361    --  into
6362    --               type BT is new R [with ...];
6363    --               subtype T is BT (...);
6364    --
6365    --  That is, the base derived type is constrained only if it has no
6366    --  discriminants. The reason for doing this is that GNAT's semantic model
6367    --  assumes that a base type with discriminants is unconstrained.
6368    --
6369    --  Note that, strictly speaking, the above transformation is not always
6370    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6371    --
6372    --       procedure B34011A is
6373    --          type REC (D : integer := 0) is record
6374    --             I : Integer;
6375    --          end record;
6376
6377    --          package P is
6378    --             type T6 is new Rec;
6379    --             function F return T6;
6380    --          end P;
6381
6382    --          use P;
6383    --          package Q6 is
6384    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6385    --          end Q6;
6386    --
6387    --  The definition of Q6.U is illegal. However transforming Q6.U into
6388
6389    --             type BaseU is new T6;
6390    --             subtype U is BaseU (Q6.F.I)
6391
6392    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6393    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6394    --  the transformation described above.
6395
6396    --  There is another instance where the above transformation is incorrect.
6397    --  Consider:
6398
6399    --          package Pack is
6400    --             type Base (D : Integer) is tagged null record;
6401    --             procedure P (X : Base);
6402
6403    --             type Der is new Base (2) with null record;
6404    --             procedure P (X : Der);
6405    --          end Pack;
6406
6407    --  Then the above transformation turns this into
6408
6409    --             type Der_Base is new Base with null record;
6410    --             --  procedure P (X : Base) is implicitly inherited here
6411    --             --  as procedure P (X : Der_Base).
6412
6413    --             subtype Der is Der_Base (2);
6414    --             procedure P (X : Der);
6415    --             --  The overriding of P (X : Der_Base) is illegal since we
6416    --             --  have a parameter conformance problem.
6417
6418    --  To get around this problem, after having semantically processed Der_Base
6419    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6420    --  Discriminant_Constraint from Der so that when parameter conformance is
6421    --  checked when P is overridden, no semantic errors are flagged.
6422
6423    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6424
6425    --  Regardless of whether we are dealing with a tagged or untagged type
6426    --  we will transform all derived type declarations of the form
6427
6428    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6429    --               type T is new R [with ...];
6430    --  into
6431    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6432
6433    --  The reason for such transformation is that it allows us to implement a
6434    --  very clean form of component inheritance as explained below.
6435
6436    --  Note that this transformation is not achieved by direct tree rewriting
6437    --  and manipulation, but rather by redoing the semantic actions that the
6438    --  above transformation will entail. This is done directly in routine
6439    --  Inherit_Components.
6440
6441    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
6442
6443    --  In both tagged and untagged derived types, regular non discriminant
6444    --  components are inherited in the derived type from the parent type. In
6445    --  the absence of discriminants component, inheritance is straightforward
6446    --  as components can simply be copied from the parent.
6447
6448    --  If the parent has discriminants, inheriting components constrained with
6449    --  these discriminants requires caution. Consider the following example:
6450
6451    --      type R  (D1, D2 : Positive) is [tagged] record
6452    --         S : String (D1 .. D2);
6453    --      end record;
6454
6455    --      type T1                is new R        [with null record];
6456    --      type T2 (X : positive) is new R (1, X) [with null record];
6457
6458    --  As explained in 6. above, T1 is rewritten as
6459    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
6460    --  which makes the treatment for T1 and T2 identical.
6461
6462    --  What we want when inheriting S, is that references to D1 and D2 in R are
6463    --  replaced with references to their correct constraints, i.e. D1 and D2 in
6464    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
6465    --  with either discriminant references in the derived type or expressions.
6466    --  This replacement is achieved as follows: before inheriting R's
6467    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
6468    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
6469    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
6470    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
6471    --  by String (1 .. X).
6472
6473    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
6474
6475    --  We explain here the rules governing private type extensions relevant to
6476    --  type derivation. These rules are explained on the following example:
6477
6478    --      type D [(...)] is new A [(...)] with private;      <-- partial view
6479    --      type D [(...)] is new P [(...)] with null record;  <-- full view
6480
6481    --  Type A is called the ancestor subtype of the private extension.
6482    --  Type P is the parent type of the full view of the private extension. It
6483    --  must be A or a type derived from A.
6484
6485    --  The rules concerning the discriminants of private type extensions are
6486    --  [7.3(10-13)]:
6487
6488    --  o If a private extension inherits known discriminants from the ancestor
6489    --    subtype, then the full view shall also inherit its discriminants from
6490    --    the ancestor subtype and the parent subtype of the full view shall be
6491    --    constrained if and only if the ancestor subtype is constrained.
6492
6493    --  o If a partial view has unknown discriminants, then the full view may
6494    --    define a definite or an indefinite subtype, with or without
6495    --    discriminants.
6496
6497    --  o If a partial view has neither known nor unknown discriminants, then
6498    --    the full view shall define a definite subtype.
6499
6500    --  o If the ancestor subtype of a private extension has constrained
6501    --    discriminants, then the parent subtype of the full view shall impose a
6502    --    statically matching constraint on those discriminants.
6503
6504    --  This means that only the following forms of private extensions are
6505    --  allowed:
6506
6507    --      type D is new A with private;      <-- partial view
6508    --      type D is new P with null record;  <-- full view
6509
6510    --  If A has no discriminants than P has no discriminants, otherwise P must
6511    --  inherit A's discriminants.
6512
6513    --      type D is new A (...) with private;      <-- partial view
6514    --      type D is new P (:::) with null record;  <-- full view
6515
6516    --  P must inherit A's discriminants and (...) and (:::) must statically
6517    --  match.
6518
6519    --      subtype A is R (...);
6520    --      type D is new A with private;      <-- partial view
6521    --      type D is new P with null record;  <-- full view
6522
6523    --  P must have inherited R's discriminants and must be derived from A or
6524    --  any of its subtypes.
6525
6526    --      type D (..) is new A with private;              <-- partial view
6527    --      type D (..) is new P [(:::)] with null record;  <-- full view
6528
6529    --  No specific constraints on P's discriminants or constraint (:::).
6530    --  Note that A can be unconstrained, but the parent subtype P must either
6531    --  be constrained or (:::) must be present.
6532
6533    --      type D (..) is new A [(...)] with private;      <-- partial view
6534    --      type D (..) is new P [(:::)] with null record;  <-- full view
6535
6536    --  P's constraints on A's discriminants must statically match those
6537    --  imposed by (...).
6538
6539    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
6540
6541    --  The full view of a private extension is handled exactly as described
6542    --  above. The model chose for the private view of a private extension is
6543    --  the same for what concerns discriminants (i.e. they receive the same
6544    --  treatment as in the tagged case). However, the private view of the
6545    --  private extension always inherits the components of the parent base,
6546    --  without replacing any discriminant reference. Strictly speaking this is
6547    --  incorrect. However, Gigi never uses this view to generate code so this
6548    --  is a purely semantic issue. In theory, a set of transformations similar
6549    --  to those given in 5. and 6. above could be applied to private views of
6550    --  private extensions to have the same model of component inheritance as
6551    --  for non private extensions. However, this is not done because it would
6552    --  further complicate private type processing. Semantically speaking, this
6553    --  leaves us in an uncomfortable situation. As an example consider:
6554
6555    --          package Pack is
6556    --             type R (D : integer) is tagged record
6557    --                S : String (1 .. D);
6558    --             end record;
6559    --             procedure P (X : R);
6560    --             type T is new R (1) with private;
6561    --          private
6562    --             type T is new R (1) with null record;
6563    --          end;
6564
6565    --  This is transformed into:
6566
6567    --          package Pack is
6568    --             type R (D : integer) is tagged record
6569    --                S : String (1 .. D);
6570    --             end record;
6571    --             procedure P (X : R);
6572    --             type T is new R (1) with private;
6573    --          private
6574    --             type BaseT is new R with null record;
6575    --             subtype  T is BaseT (1);
6576    --          end;
6577
6578    --  (strictly speaking the above is incorrect Ada)
6579
6580    --  From the semantic standpoint the private view of private extension T
6581    --  should be flagged as constrained since one can clearly have
6582    --
6583    --             Obj : T;
6584    --
6585    --  in a unit withing Pack. However, when deriving subprograms for the
6586    --  private view of private extension T, T must be seen as unconstrained
6587    --  since T has discriminants (this is a constraint of the current
6588    --  subprogram derivation model). Thus, when processing the private view of
6589    --  a private extension such as T, we first mark T as unconstrained, we
6590    --  process it, we perform program derivation and just before returning from
6591    --  Build_Derived_Record_Type we mark T as constrained.
6592
6593    --  ??? Are there are other uncomfortable cases that we will have to
6594    --      deal with.
6595
6596    --  10. RECORD_TYPE_WITH_PRIVATE complications
6597
6598    --  Types that are derived from a visible record type and have a private
6599    --  extension present other peculiarities. They behave mostly like private
6600    --  types, but if they have primitive operations defined, these will not
6601    --  have the proper signatures for further inheritance, because other
6602    --  primitive operations will use the implicit base that we define for
6603    --  private derivations below. This affect subprogram inheritance (see
6604    --  Derive_Subprograms for details). We also derive the implicit base from
6605    --  the base type of the full view, so that the implicit base is a record
6606    --  type and not another private type, This avoids infinite loops.
6607
6608    procedure Build_Derived_Record_Type
6609      (N            : Node_Id;
6610       Parent_Type  : Entity_Id;
6611       Derived_Type : Entity_Id;
6612       Derive_Subps : Boolean := True)
6613    is
6614       Loc          : constant Source_Ptr := Sloc (N);
6615       Parent_Base  : Entity_Id;
6616       Type_Def     : Node_Id;
6617       Indic        : Node_Id;
6618       Discrim      : Entity_Id;
6619       Last_Discrim : Entity_Id;
6620       Constrs      : Elist_Id;
6621
6622       Discs : Elist_Id := New_Elmt_List;
6623       --  An empty Discs list means that there were no constraints in the
6624       --  subtype indication or that there was an error processing it.
6625
6626       Assoc_List : Elist_Id;
6627       New_Discrs : Elist_Id;
6628       New_Base   : Entity_Id;
6629       New_Decl   : Node_Id;
6630       New_Indic  : Node_Id;
6631
6632       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
6633       Discriminant_Specs : constant Boolean :=
6634                              Present (Discriminant_Specifications (N));
6635       Private_Extension  : constant Boolean :=
6636                              Nkind (N) = N_Private_Extension_Declaration;
6637
6638       Constraint_Present : Boolean;
6639       Inherit_Discrims   : Boolean := False;
6640       Save_Etype         : Entity_Id;
6641       Save_Discr_Constr  : Elist_Id;
6642       Save_Next_Entity   : Entity_Id;
6643
6644    begin
6645       if Ekind (Parent_Type) = E_Record_Type_With_Private
6646         and then Present (Full_View (Parent_Type))
6647         and then Has_Discriminants (Parent_Type)
6648       then
6649          Parent_Base := Base_Type (Full_View (Parent_Type));
6650       else
6651          Parent_Base := Base_Type (Parent_Type);
6652       end if;
6653
6654       --  Before we start the previously documented transformations, here is
6655       --  little fix for size and alignment of tagged types. Normally when we
6656       --  derive type D from type P, we copy the size and alignment of P as the
6657       --  default for D, and in the absence of explicit representation clauses
6658       --  for D, the size and alignment are indeed the same as the parent.
6659
6660       --  But this is wrong for tagged types, since fields may be added, and
6661       --  the default size may need to be larger, and the default alignment may
6662       --  need to be larger.
6663
6664       --  We therefore reset the size and alignment fields in the tagged case.
6665       --  Note that the size and alignment will in any case be at least as
6666       --  large as the parent type (since the derived type has a copy of the
6667       --  parent type in the _parent field)
6668
6669       --  The type is also marked as being tagged here, which is needed when
6670       --  processing components with a self-referential anonymous access type
6671       --  in the call to Check_Anonymous_Access_Components below. Note that
6672       --  this flag is also set later on for completeness.
6673
6674       if Is_Tagged then
6675          Set_Is_Tagged_Type (Derived_Type);
6676          Init_Size_Align    (Derived_Type);
6677       end if;
6678
6679       --  STEP 0a: figure out what kind of derived type declaration we have
6680
6681       if Private_Extension then
6682          Type_Def := N;
6683          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
6684
6685       else
6686          Type_Def := Type_Definition (N);
6687
6688          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
6689          --  Parent_Base can be a private type or private extension. However,
6690          --  for tagged types with an extension the newly added fields are
6691          --  visible and hence the Derived_Type is always an E_Record_Type.
6692          --  (except that the parent may have its own private fields).
6693          --  For untagged types we preserve the Ekind of the Parent_Base.
6694
6695          if Present (Record_Extension_Part (Type_Def)) then
6696             Set_Ekind (Derived_Type, E_Record_Type);
6697
6698             --  Create internal access types for components with anonymous
6699             --  access types.
6700
6701             if Ada_Version >= Ada_05 then
6702                Check_Anonymous_Access_Components
6703                  (N, Derived_Type, Derived_Type,
6704                    Component_List (Record_Extension_Part (Type_Def)));
6705             end if;
6706
6707          else
6708             Set_Ekind (Derived_Type, Ekind (Parent_Base));
6709          end if;
6710       end if;
6711
6712       --  Indic can either be an N_Identifier if the subtype indication
6713       --  contains no constraint or an N_Subtype_Indication if the subtype
6714       --  indication has a constraint.
6715
6716       Indic := Subtype_Indication (Type_Def);
6717       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
6718
6719       --  Check that the type has visible discriminants. The type may be
6720       --  a private type with unknown discriminants whose full view has
6721       --  discriminants which are invisible.
6722
6723       if Constraint_Present then
6724          if not Has_Discriminants (Parent_Base)
6725            or else
6726              (Has_Unknown_Discriminants (Parent_Base)
6727                 and then Is_Private_Type (Parent_Base))
6728          then
6729             Error_Msg_N
6730               ("invalid constraint: type has no discriminant",
6731                  Constraint (Indic));
6732
6733             Constraint_Present := False;
6734             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6735
6736          elsif Is_Constrained (Parent_Type) then
6737             Error_Msg_N
6738                ("invalid constraint: parent type is already constrained",
6739                   Constraint (Indic));
6740
6741             Constraint_Present := False;
6742             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6743          end if;
6744       end if;
6745
6746       --  STEP 0b: If needed, apply transformation given in point 5. above
6747
6748       if not Private_Extension
6749         and then Has_Discriminants (Parent_Type)
6750         and then not Discriminant_Specs
6751         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
6752       then
6753          --  First, we must analyze the constraint (see comment in point 5.)
6754
6755          if Constraint_Present then
6756             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
6757
6758             if Has_Discriminants (Derived_Type)
6759               and then Has_Private_Declaration (Derived_Type)
6760               and then Present (Discriminant_Constraint (Derived_Type))
6761             then
6762                --  Verify that constraints of the full view statically match
6763                --  those given in the partial view.
6764
6765                declare
6766                   C1, C2 : Elmt_Id;
6767
6768                begin
6769                   C1 := First_Elmt (New_Discrs);
6770                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
6771                   while Present (C1) and then Present (C2) loop
6772                      if Fully_Conformant_Expressions (Node (C1), Node (C2))
6773                        or else
6774                          (Is_OK_Static_Expression (Node (C1))
6775                             and then
6776                           Is_OK_Static_Expression (Node (C2))
6777                             and then
6778                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
6779                      then
6780                         null;
6781
6782                      else
6783                         Error_Msg_N (
6784                           "constraint not conformant to previous declaration",
6785                              Node (C1));
6786                      end if;
6787
6788                      Next_Elmt (C1);
6789                      Next_Elmt (C2);
6790                   end loop;
6791                end;
6792             end if;
6793          end if;
6794
6795          --  Insert and analyze the declaration for the unconstrained base type
6796
6797          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
6798
6799          New_Decl :=
6800            Make_Full_Type_Declaration (Loc,
6801               Defining_Identifier => New_Base,
6802               Type_Definition     =>
6803                 Make_Derived_Type_Definition (Loc,
6804                   Abstract_Present      => Abstract_Present (Type_Def),
6805                   Limited_Present       => Limited_Present (Type_Def),
6806                   Subtype_Indication    =>
6807                     New_Occurrence_Of (Parent_Base, Loc),
6808                   Record_Extension_Part =>
6809                     Relocate_Node (Record_Extension_Part (Type_Def)),
6810                   Interface_List        => Interface_List (Type_Def)));
6811
6812          Set_Parent (New_Decl, Parent (N));
6813          Mark_Rewrite_Insertion (New_Decl);
6814          Insert_Before (N, New_Decl);
6815
6816          --  In the extension case, make sure ancestor is frozen appropriately
6817          --  (see also non-discriminated case below).
6818
6819          if Present (Record_Extension_Part (Type_Def))
6820            or else Is_Interface (Parent_Base)
6821          then
6822             Freeze_Before (New_Decl, Parent_Type);
6823          end if;
6824
6825          --  Note that this call passes False for the Derive_Subps parameter
6826          --  because subprogram derivation is deferred until after creating
6827          --  the subtype (see below).
6828
6829          Build_Derived_Type
6830            (New_Decl, Parent_Base, New_Base,
6831             Is_Completion => True, Derive_Subps => False);
6832
6833          --  ??? This needs re-examination to determine whether the
6834          --  above call can simply be replaced by a call to Analyze.
6835
6836          Set_Analyzed (New_Decl);
6837
6838          --  Insert and analyze the declaration for the constrained subtype
6839
6840          if Constraint_Present then
6841             New_Indic :=
6842               Make_Subtype_Indication (Loc,
6843                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6844                 Constraint   => Relocate_Node (Constraint (Indic)));
6845
6846          else
6847             declare
6848                Constr_List : constant List_Id := New_List;
6849                C           : Elmt_Id;
6850                Expr        : Node_Id;
6851
6852             begin
6853                C := First_Elmt (Discriminant_Constraint (Parent_Type));
6854                while Present (C) loop
6855                   Expr := Node (C);
6856
6857                   --  It is safe here to call New_Copy_Tree since
6858                   --  Force_Evaluation was called on each constraint in
6859                   --  Build_Discriminant_Constraints.
6860
6861                   Append (New_Copy_Tree (Expr), To => Constr_List);
6862
6863                   Next_Elmt (C);
6864                end loop;
6865
6866                New_Indic :=
6867                  Make_Subtype_Indication (Loc,
6868                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6869                    Constraint   =>
6870                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
6871             end;
6872          end if;
6873
6874          Rewrite (N,
6875            Make_Subtype_Declaration (Loc,
6876              Defining_Identifier => Derived_Type,
6877              Subtype_Indication  => New_Indic));
6878
6879          Analyze (N);
6880
6881          --  Derivation of subprograms must be delayed until the full subtype
6882          --  has been established to ensure proper overriding of subprograms
6883          --  inherited by full types. If the derivations occurred as part of
6884          --  the call to Build_Derived_Type above, then the check for type
6885          --  conformance would fail because earlier primitive subprograms
6886          --  could still refer to the full type prior the change to the new
6887          --  subtype and hence would not match the new base type created here.
6888
6889          Derive_Subprograms (Parent_Type, Derived_Type);
6890
6891          --  For tagged types the Discriminant_Constraint of the new base itype
6892          --  is inherited from the first subtype so that no subtype conformance
6893          --  problem arise when the first subtype overrides primitive
6894          --  operations inherited by the implicit base type.
6895
6896          if Is_Tagged then
6897             Set_Discriminant_Constraint
6898               (New_Base, Discriminant_Constraint (Derived_Type));
6899          end if;
6900
6901          return;
6902       end if;
6903
6904       --  If we get here Derived_Type will have no discriminants or it will be
6905       --  a discriminated unconstrained base type.
6906
6907       --  STEP 1a: perform preliminary actions/checks for derived tagged types
6908
6909       if Is_Tagged then
6910
6911          --  The parent type is frozen for non-private extensions (RM 13.14(7))
6912          --  The declaration of a specific descendant of an interface type
6913          --  freezes the interface type (RM 13.14).
6914
6915          if not Private_Extension or else Is_Interface (Parent_Base) then
6916             Freeze_Before (N, Parent_Type);
6917          end if;
6918
6919          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
6920          --  cannot be declared at a deeper level than its parent type is
6921          --  removed. The check on derivation within a generic body is also
6922          --  relaxed, but there's a restriction that a derived tagged type
6923          --  cannot be declared in a generic body if it's derived directly
6924          --  or indirectly from a formal type of that generic.
6925
6926          if Ada_Version >= Ada_05 then
6927             if Present (Enclosing_Generic_Body (Derived_Type)) then
6928                declare
6929                   Ancestor_Type : Entity_Id;
6930
6931                begin
6932                   --  Check to see if any ancestor of the derived type is a
6933                   --  formal type.
6934
6935                   Ancestor_Type := Parent_Type;
6936                   while not Is_Generic_Type (Ancestor_Type)
6937                     and then Etype (Ancestor_Type) /= Ancestor_Type
6938                   loop
6939                      Ancestor_Type := Etype (Ancestor_Type);
6940                   end loop;
6941
6942                   --  If the derived type does have a formal type as an
6943                   --  ancestor, then it's an error if the derived type is
6944                   --  declared within the body of the generic unit that
6945                   --  declares the formal type in its generic formal part. It's
6946                   --  sufficient to check whether the ancestor type is declared
6947                   --  inside the same generic body as the derived type (such as
6948                   --  within a nested generic spec), in which case the
6949                   --  derivation is legal. If the formal type is declared
6950                   --  outside of that generic body, then it's guaranteed that
6951                   --  the derived type is declared within the generic body of
6952                   --  the generic unit declaring the formal type.
6953
6954                   if Is_Generic_Type (Ancestor_Type)
6955                     and then Enclosing_Generic_Body (Ancestor_Type) /=
6956                                Enclosing_Generic_Body (Derived_Type)
6957                   then
6958                      Error_Msg_NE
6959                        ("parent type of& must not be descendant of formal type"
6960                           & " of an enclosing generic body",
6961                             Indic, Derived_Type);
6962                   end if;
6963                end;
6964             end if;
6965
6966          elsif Type_Access_Level (Derived_Type) /=
6967                  Type_Access_Level (Parent_Type)
6968            and then not Is_Generic_Type (Derived_Type)
6969          then
6970             if Is_Controlled (Parent_Type) then
6971                Error_Msg_N
6972                  ("controlled type must be declared at the library level",
6973                   Indic);
6974             else
6975                Error_Msg_N
6976                  ("type extension at deeper accessibility level than parent",
6977                   Indic);
6978             end if;
6979
6980          else
6981             declare
6982                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
6983
6984             begin
6985                if Present (GB)
6986                  and then GB /= Enclosing_Generic_Body (Parent_Base)
6987                then
6988                   Error_Msg_NE
6989                     ("parent type of& must not be outside generic body"
6990                        & " (RM 3.9.1(4))",
6991                          Indic, Derived_Type);
6992                end if;
6993             end;
6994          end if;
6995       end if;
6996
6997       --  Ada 2005 (AI-251)
6998
6999       if Ada_Version >= Ada_05 and then Is_Tagged then
7000
7001          --  "The declaration of a specific descendant of an interface type
7002          --  freezes the interface type" (RM 13.14).
7003
7004          declare
7005             Iface : Node_Id;
7006          begin
7007             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7008                Iface := First (Interface_List (Type_Def));
7009                while Present (Iface) loop
7010                   Freeze_Before (N, Etype (Iface));
7011                   Next (Iface);
7012                end loop;
7013             end if;
7014          end;
7015       end if;
7016
7017       --  STEP 1b : preliminary cleanup of the full view of private types
7018
7019       --  If the type is already marked as having discriminants, then it's the
7020       --  completion of a private type or private extension and we need to
7021       --  retain the discriminants from the partial view if the current
7022       --  declaration has Discriminant_Specifications so that we can verify
7023       --  conformance. However, we must remove any existing components that
7024       --  were inherited from the parent (and attached in Copy_And_Swap)
7025       --  because the full type inherits all appropriate components anyway, and
7026       --  we do not want the partial view's components interfering.
7027
7028       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7029          Discrim := First_Discriminant (Derived_Type);
7030          loop
7031             Last_Discrim := Discrim;
7032             Next_Discriminant (Discrim);
7033             exit when No (Discrim);
7034          end loop;
7035
7036          Set_Last_Entity (Derived_Type, Last_Discrim);
7037
7038       --  In all other cases wipe out the list of inherited components (even
7039       --  inherited discriminants), it will be properly rebuilt here.
7040
7041       else
7042          Set_First_Entity (Derived_Type, Empty);
7043          Set_Last_Entity  (Derived_Type, Empty);
7044       end if;
7045
7046       --  STEP 1c: Initialize some flags for the Derived_Type
7047
7048       --  The following flags must be initialized here so that
7049       --  Process_Discriminants can check that discriminants of tagged types do
7050       --  not have a default initial value and that access discriminants are
7051       --  only specified for limited records. For completeness, these flags are
7052       --  also initialized along with all the other flags below.
7053
7054       --  AI-419: Limitedness is not inherited from an interface parent, so to
7055       --  be limited in that case the type must be explicitly declared as
7056       --  limited. However, task and protected interfaces are always limited.
7057
7058       if Limited_Present (Type_Def) then
7059          Set_Is_Limited_Record (Derived_Type);
7060
7061       elsif Is_Limited_Record (Parent_Type)
7062         or else (Present (Full_View (Parent_Type))
7063                    and then Is_Limited_Record (Full_View (Parent_Type)))
7064       then
7065          if not Is_Interface (Parent_Type)
7066            or else Is_Synchronized_Interface (Parent_Type)
7067            or else Is_Protected_Interface (Parent_Type)
7068            or else Is_Task_Interface (Parent_Type)
7069          then
7070             Set_Is_Limited_Record (Derived_Type);
7071          end if;
7072       end if;
7073
7074       --  STEP 2a: process discriminants of derived type if any
7075
7076       Push_Scope (Derived_Type);
7077
7078       if Discriminant_Specs then
7079          Set_Has_Unknown_Discriminants (Derived_Type, False);
7080
7081          --  The following call initializes fields Has_Discriminants and
7082          --  Discriminant_Constraint, unless we are processing the completion
7083          --  of a private type declaration.
7084
7085          Check_Or_Process_Discriminants (N, Derived_Type);
7086
7087          --  For non-tagged types the constraint on the Parent_Type must be
7088          --  present and is used to rename the discriminants.
7089
7090          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7091             Error_Msg_N ("untagged parent must have discriminants", Indic);
7092
7093          elsif not Is_Tagged and then not Constraint_Present then
7094             Error_Msg_N
7095               ("discriminant constraint needed for derived untagged records",
7096                Indic);
7097
7098          --  Otherwise the parent subtype must be constrained unless we have a
7099          --  private extension.
7100
7101          elsif not Constraint_Present
7102            and then not Private_Extension
7103            and then not Is_Constrained (Parent_Type)
7104          then
7105             Error_Msg_N
7106               ("unconstrained type not allowed in this context", Indic);
7107
7108          elsif Constraint_Present then
7109             --  The following call sets the field Corresponding_Discriminant
7110             --  for the discriminants in the Derived_Type.
7111
7112             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7113
7114             --  For untagged types all new discriminants must rename
7115             --  discriminants in the parent. For private extensions new
7116             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7117
7118             Discrim := First_Discriminant (Derived_Type);
7119             while Present (Discrim) loop
7120                if not Is_Tagged
7121                  and then No (Corresponding_Discriminant (Discrim))
7122                then
7123                   Error_Msg_N
7124                     ("new discriminants must constrain old ones", Discrim);
7125
7126                elsif Private_Extension
7127                  and then Present (Corresponding_Discriminant (Discrim))
7128                then
7129                   Error_Msg_N
7130                     ("only static constraints allowed for parent"
7131                      & " discriminants in the partial view", Indic);
7132                   exit;
7133                end if;
7134
7135                --  If a new discriminant is used in the constraint, then its
7136                --  subtype must be statically compatible with the parent
7137                --  discriminant's subtype (3.7(15)).
7138
7139                if Present (Corresponding_Discriminant (Discrim))
7140                  and then
7141                    not Subtypes_Statically_Compatible
7142                          (Etype (Discrim),
7143                           Etype (Corresponding_Discriminant (Discrim)))
7144                then
7145                   Error_Msg_N
7146                     ("subtype must be compatible with parent discriminant",
7147                      Discrim);
7148                end if;
7149
7150                Next_Discriminant (Discrim);
7151             end loop;
7152
7153             --  Check whether the constraints of the full view statically
7154             --  match those imposed by the parent subtype [7.3(13)].
7155
7156             if Present (Stored_Constraint (Derived_Type)) then
7157                declare
7158                   C1, C2 : Elmt_Id;
7159
7160                begin
7161                   C1 := First_Elmt (Discs);
7162                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7163                   while Present (C1) and then Present (C2) loop
7164                      if not
7165                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7166                      then
7167                         Error_Msg_N
7168                           ("not conformant with 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       --  STEP 2b: No new discriminants, inherit discriminants if any
7180
7181       else
7182          if Private_Extension then
7183             Set_Has_Unknown_Discriminants
7184               (Derived_Type,
7185                Has_Unknown_Discriminants (Parent_Type)
7186                  or else Unknown_Discriminants_Present (N));
7187
7188          --  The partial view of the parent may have unknown discriminants,
7189          --  but if the full view has discriminants and the parent type is
7190          --  in scope they must be inherited.
7191
7192          elsif Has_Unknown_Discriminants (Parent_Type)
7193            and then
7194             (not Has_Discriminants (Parent_Type)
7195               or else not In_Open_Scopes (Scope (Parent_Type)))
7196          then
7197             Set_Has_Unknown_Discriminants (Derived_Type);
7198          end if;
7199
7200          if not Has_Unknown_Discriminants (Derived_Type)
7201            and then not Has_Unknown_Discriminants (Parent_Base)
7202            and then Has_Discriminants (Parent_Type)
7203          then
7204             Inherit_Discrims := True;
7205             Set_Has_Discriminants
7206               (Derived_Type, True);
7207             Set_Discriminant_Constraint
7208               (Derived_Type, Discriminant_Constraint (Parent_Base));
7209          end if;
7210
7211          --  The following test is true for private types (remember
7212          --  transformation 5. is not applied to those) and in an error
7213          --  situation.
7214
7215          if Constraint_Present then
7216             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7217          end if;
7218
7219          --  For now mark a new derived type as constrained only if it has no
7220          --  discriminants. At the end of Build_Derived_Record_Type we properly
7221          --  set this flag in the case of private extensions. See comments in
7222          --  point 9. just before body of Build_Derived_Record_Type.
7223
7224          Set_Is_Constrained
7225            (Derived_Type,
7226             not (Inherit_Discrims
7227                    or else Has_Unknown_Discriminants (Derived_Type)));
7228       end if;
7229
7230       --  STEP 3: initialize fields of derived type
7231
7232       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7233       Set_Stored_Constraint (Derived_Type, No_Elist);
7234
7235       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7236       --  but cannot be interfaces
7237
7238       if not Private_Extension
7239          and then Ekind (Derived_Type) /= E_Private_Type
7240          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7241       then
7242          if Interface_Present (Type_Def) then
7243             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7244          end if;
7245
7246          Set_Interfaces (Derived_Type, No_Elist);
7247       end if;
7248
7249       --  Fields inherited from the Parent_Type
7250
7251       Set_Discard_Names
7252         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
7253       Set_Has_Specified_Layout
7254         (Derived_Type, Has_Specified_Layout (Parent_Type));
7255       Set_Is_Limited_Composite
7256         (Derived_Type, Is_Limited_Composite (Parent_Type));
7257       Set_Is_Private_Composite
7258         (Derived_Type, Is_Private_Composite (Parent_Type));
7259
7260       --  Fields inherited from the Parent_Base
7261
7262       Set_Has_Controlled_Component
7263         (Derived_Type, Has_Controlled_Component (Parent_Base));
7264       Set_Has_Non_Standard_Rep
7265         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7266       Set_Has_Primitive_Operations
7267         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7268
7269       --  Fields inherited from the Parent_Base in the non-private case
7270
7271       if Ekind (Derived_Type) = E_Record_Type then
7272          Set_Has_Complex_Representation
7273            (Derived_Type, Has_Complex_Representation (Parent_Base));
7274       end if;
7275
7276       --  Fields inherited from the Parent_Base for record types
7277
7278       if Is_Record_Type (Derived_Type) then
7279
7280          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7281          --  Parent_Base can be a private type or private extension.
7282
7283          if Present (Full_View (Parent_Base)) then
7284             Set_OK_To_Reorder_Components
7285               (Derived_Type,
7286                OK_To_Reorder_Components (Full_View (Parent_Base)));
7287             Set_Reverse_Bit_Order
7288               (Derived_Type, Reverse_Bit_Order (Full_View (Parent_Base)));
7289          else
7290             Set_OK_To_Reorder_Components
7291               (Derived_Type, OK_To_Reorder_Components (Parent_Base));
7292             Set_Reverse_Bit_Order
7293               (Derived_Type, Reverse_Bit_Order (Parent_Base));
7294          end if;
7295       end if;
7296
7297       --  Direct controlled types do not inherit Finalize_Storage_Only flag
7298
7299       if not Is_Controlled (Parent_Type) then
7300          Set_Finalize_Storage_Only
7301            (Derived_Type, Finalize_Storage_Only (Parent_Type));
7302       end if;
7303
7304       --  Set fields for private derived types
7305
7306       if Is_Private_Type (Derived_Type) then
7307          Set_Depends_On_Private (Derived_Type, True);
7308          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7309
7310       --  Inherit fields from non private record types. If this is the
7311       --  completion of a derivation from a private type, the parent itself
7312       --  is private, and the attributes come from its full view, which must
7313       --  be present.
7314
7315       else
7316          if Is_Private_Type (Parent_Base)
7317            and then not Is_Record_Type (Parent_Base)
7318          then
7319             Set_Component_Alignment
7320               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7321             Set_C_Pass_By_Copy
7322               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7323          else
7324             Set_Component_Alignment
7325               (Derived_Type, Component_Alignment (Parent_Base));
7326             Set_C_Pass_By_Copy
7327               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7328          end if;
7329       end if;
7330
7331       --  Set fields for tagged types
7332
7333       if Is_Tagged then
7334          Set_Primitive_Operations (Derived_Type, New_Elmt_List);
7335
7336          --  All tagged types defined in Ada.Finalization are controlled
7337
7338          if Chars (Scope (Derived_Type)) = Name_Finalization
7339            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7340            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7341          then
7342             Set_Is_Controlled (Derived_Type);
7343          else
7344             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7345          end if;
7346
7347          --  Minor optimization: there is no need to generate the class-wide
7348          --  entity associated with an underlying record view.
7349
7350          if not Is_Underlying_Record_View (Derived_Type) then
7351             Make_Class_Wide_Type (Derived_Type);
7352          end if;
7353
7354          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7355
7356          if Has_Discriminants (Derived_Type)
7357            and then Constraint_Present
7358          then
7359             Set_Stored_Constraint
7360               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7361          end if;
7362
7363          if Ada_Version >= Ada_05 then
7364             declare
7365                Ifaces_List : Elist_Id;
7366
7367             begin
7368                --  Checks rules 3.9.4 (13/2 and 14/2)
7369
7370                if Comes_From_Source (Derived_Type)
7371                  and then not Is_Private_Type (Derived_Type)
7372                  and then Is_Interface (Parent_Type)
7373                  and then not Is_Interface (Derived_Type)
7374                then
7375                   if Is_Task_Interface (Parent_Type) then
7376                      Error_Msg_N
7377                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
7378                         Derived_Type);
7379
7380                   elsif Is_Protected_Interface (Parent_Type) then
7381                      Error_Msg_N
7382                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
7383                         Derived_Type);
7384                   end if;
7385                end if;
7386
7387                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
7388
7389                Check_Interfaces (N, Type_Def);
7390
7391                --  Ada 2005 (AI-251): Collect the list of progenitors that are
7392                --  not already in the parents.
7393
7394                Collect_Interfaces
7395                  (T               => Derived_Type,
7396                   Ifaces_List     => Ifaces_List,
7397                   Exclude_Parents => True);
7398
7399                Set_Interfaces (Derived_Type, Ifaces_List);
7400
7401                --  If the derived type is the anonymous type created for
7402                --  a declaration whose parent has a constraint, propagate
7403                --  the interface list to the source type. This must be done
7404                --  prior to the completion of the analysis of the source type
7405                --  because the components in the extension may contain current
7406                --  instances whose legality depends on some ancestor.
7407
7408                if Is_Itype (Derived_Type) then
7409                   declare
7410                      Def : constant Node_Id :=
7411                        Associated_Node_For_Itype (Derived_Type);
7412                   begin
7413                      if Present (Def)
7414                        and then Nkind (Def) = N_Full_Type_Declaration
7415                      then
7416                         Set_Interfaces
7417                           (Defining_Identifier (Def), Ifaces_List);
7418                      end if;
7419                   end;
7420                end if;
7421             end;
7422          end if;
7423
7424       else
7425          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
7426          Set_Has_Non_Standard_Rep
7427                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
7428       end if;
7429
7430       --  STEP 4: Inherit components from the parent base and constrain them.
7431       --          Apply the second transformation described in point 6. above.
7432
7433       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
7434         or else not Has_Discriminants (Parent_Type)
7435         or else not Is_Constrained (Parent_Type)
7436       then
7437          Constrs := Discs;
7438       else
7439          Constrs := Discriminant_Constraint (Parent_Type);
7440       end if;
7441
7442       Assoc_List :=
7443         Inherit_Components
7444           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
7445
7446       --  STEP 5a: Copy the parent record declaration for untagged types
7447
7448       if not Is_Tagged then
7449
7450          --  Discriminant_Constraint (Derived_Type) has been properly
7451          --  constructed. Save it and temporarily set it to Empty because we
7452          --  do not want the call to New_Copy_Tree below to mess this list.
7453
7454          if Has_Discriminants (Derived_Type) then
7455             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
7456             Set_Discriminant_Constraint (Derived_Type, No_Elist);
7457          else
7458             Save_Discr_Constr := No_Elist;
7459          end if;
7460
7461          --  Save the Etype field of Derived_Type. It is correctly set now,
7462          --  but the call to New_Copy tree may remap it to point to itself,
7463          --  which is not what we want. Ditto for the Next_Entity field.
7464
7465          Save_Etype       := Etype (Derived_Type);
7466          Save_Next_Entity := Next_Entity (Derived_Type);
7467
7468          --  Assoc_List maps all stored discriminants in the Parent_Base to
7469          --  stored discriminants in the Derived_Type. It is fundamental that
7470          --  no types or itypes with discriminants other than the stored
7471          --  discriminants appear in the entities declared inside
7472          --  Derived_Type, since the back end cannot deal with it.
7473
7474          New_Decl :=
7475            New_Copy_Tree
7476              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
7477
7478          --  Restore the fields saved prior to the New_Copy_Tree call
7479          --  and compute the stored constraint.
7480
7481          Set_Etype       (Derived_Type, Save_Etype);
7482          Set_Next_Entity (Derived_Type, Save_Next_Entity);
7483
7484          if Has_Discriminants (Derived_Type) then
7485             Set_Discriminant_Constraint
7486               (Derived_Type, Save_Discr_Constr);
7487             Set_Stored_Constraint
7488               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
7489             Replace_Components (Derived_Type, New_Decl);
7490          end if;
7491
7492          --  Insert the new derived type declaration
7493
7494          Rewrite (N, New_Decl);
7495
7496       --  STEP 5b: Complete the processing for record extensions in generics
7497
7498       --  There is no completion for record extensions declared in the
7499       --  parameter part of a generic, so we need to complete processing for
7500       --  these generic record extensions here. The Record_Type_Definition call
7501       --  will change the Ekind of the components from E_Void to E_Component.
7502
7503       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
7504          Record_Type_Definition (Empty, Derived_Type);
7505
7506       --  STEP 5c: Process the record extension for non private tagged types
7507
7508       elsif not Private_Extension then
7509
7510          --  Add the _parent field in the derived type
7511
7512          Expand_Record_Extension (Derived_Type, Type_Def);
7513
7514          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
7515          --  implemented interfaces if we are in expansion mode
7516
7517          if Expander_Active
7518            and then Has_Interfaces (Derived_Type)
7519          then
7520             Add_Interface_Tag_Components (N, Derived_Type);
7521          end if;
7522
7523          --  Analyze the record extension
7524
7525          Record_Type_Definition
7526            (Record_Extension_Part (Type_Def), Derived_Type);
7527       end if;
7528
7529       End_Scope;
7530
7531       --  Nothing else to do if there is an error in the derivation.
7532       --  An unusual case: the full view may be derived from a type in an
7533       --  instance, when the partial view was used illegally as an actual
7534       --  in that instance, leading to a circular definition.
7535
7536       if Etype (Derived_Type) = Any_Type
7537         or else Etype (Parent_Type) = Derived_Type
7538       then
7539          return;
7540       end if;
7541
7542       --  Set delayed freeze and then derive subprograms, we need to do
7543       --  this in this order so that derived subprograms inherit the
7544       --  derived freeze if necessary.
7545
7546       Set_Has_Delayed_Freeze (Derived_Type);
7547
7548       if Derive_Subps then
7549          Derive_Subprograms (Parent_Type, Derived_Type);
7550       end if;
7551
7552       --  If we have a private extension which defines a constrained derived
7553       --  type mark as constrained here after we have derived subprograms. See
7554       --  comment on point 9. just above the body of Build_Derived_Record_Type.
7555
7556       if Private_Extension and then Inherit_Discrims then
7557          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
7558             Set_Is_Constrained          (Derived_Type, True);
7559             Set_Discriminant_Constraint (Derived_Type, Discs);
7560
7561          elsif Is_Constrained (Parent_Type) then
7562             Set_Is_Constrained
7563               (Derived_Type, True);
7564             Set_Discriminant_Constraint
7565               (Derived_Type, Discriminant_Constraint (Parent_Type));
7566          end if;
7567       end if;
7568
7569       --  Update the class-wide type, which shares the now-completed entity
7570       --  list with its specific type. In case of underlying record views,
7571       --  we do not generate the corresponding class wide entity.
7572
7573       if Is_Tagged
7574         and then not Is_Underlying_Record_View (Derived_Type)
7575       then
7576          Set_First_Entity
7577            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
7578          Set_Last_Entity
7579            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
7580       end if;
7581
7582       --  Update the scope of anonymous access types of discriminants and other
7583       --  components, to prevent scope anomalies in gigi, when the derivation
7584       --  appears in a scope nested within that of the parent.
7585
7586       declare
7587          D : Entity_Id;
7588
7589       begin
7590          D := First_Entity (Derived_Type);
7591          while Present (D) loop
7592             if Ekind_In (D, E_Discriminant, E_Component) then
7593                if Is_Itype (Etype (D))
7594                   and then Ekind (Etype (D)) = E_Anonymous_Access_Type
7595                then
7596                   Set_Scope (Etype (D), Current_Scope);
7597                end if;
7598             end if;
7599
7600             Next_Entity (D);
7601          end loop;
7602       end;
7603    end Build_Derived_Record_Type;
7604
7605    ------------------------
7606    -- Build_Derived_Type --
7607    ------------------------
7608
7609    procedure Build_Derived_Type
7610      (N             : Node_Id;
7611       Parent_Type   : Entity_Id;
7612       Derived_Type  : Entity_Id;
7613       Is_Completion : Boolean;
7614       Derive_Subps  : Boolean := True)
7615    is
7616       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
7617
7618    begin
7619       --  Set common attributes
7620
7621       Set_Scope         (Derived_Type, Current_Scope);
7622
7623       Set_Ekind         (Derived_Type, Ekind    (Parent_Base));
7624       Set_Etype         (Derived_Type,           Parent_Base);
7625       Set_Has_Task      (Derived_Type, Has_Task (Parent_Base));
7626
7627       Set_Size_Info      (Derived_Type,                 Parent_Type);
7628       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
7629       Set_Convention     (Derived_Type, Convention     (Parent_Type));
7630       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
7631       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
7632
7633       --  The derived type inherits the representation clauses of the parent.
7634       --  However, for a private type that is completed by a derivation, there
7635       --  may be operation attributes that have been specified already (stream
7636       --  attributes and External_Tag) and those must be provided. Finally,
7637       --  if the partial view is a private extension, the representation items
7638       --  of the parent have been inherited already, and should not be chained
7639       --  twice to the derived type.
7640
7641       if Is_Tagged_Type (Parent_Type)
7642         and then Present (First_Rep_Item (Derived_Type))
7643       then
7644          --  The existing items are either operational items or items inherited
7645          --  from a private extension declaration.
7646
7647          declare
7648             Rep : Node_Id;
7649             --  Used to iterate over representation items of the derived type
7650
7651             Last_Rep : Node_Id;
7652             --  Last representation item of the (non-empty) representation
7653             --  item list of the derived type.
7654
7655             Found : Boolean := False;
7656
7657          begin
7658             Rep      := First_Rep_Item (Derived_Type);
7659             Last_Rep := Rep;
7660             while Present (Rep) loop
7661                if Rep = First_Rep_Item (Parent_Type) then
7662                   Found := True;
7663                   exit;
7664
7665                else
7666                   Rep := Next_Rep_Item (Rep);
7667
7668                   if Present (Rep) then
7669                      Last_Rep := Rep;
7670                   end if;
7671                end if;
7672             end loop;
7673
7674             --  Here if we either encountered the parent type's first rep
7675             --  item on the derived type's rep item list (in which case
7676             --  Found is True, and we have nothing else to do), or if we
7677             --  reached the last rep item of the derived type, which is
7678             --  Last_Rep, in which case we further chain the parent type's
7679             --  rep items to those of the derived type.
7680
7681             if not Found then
7682                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
7683             end if;
7684          end;
7685
7686       else
7687          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
7688       end if;
7689
7690       case Ekind (Parent_Type) is
7691          when Numeric_Kind =>
7692             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
7693
7694          when Array_Kind =>
7695             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
7696
7697          when E_Record_Type
7698             | E_Record_Subtype
7699             | Class_Wide_Kind  =>
7700             Build_Derived_Record_Type
7701               (N, Parent_Type, Derived_Type, Derive_Subps);
7702             return;
7703
7704          when Enumeration_Kind =>
7705             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
7706
7707          when Access_Kind =>
7708             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
7709
7710          when Incomplete_Or_Private_Kind =>
7711             Build_Derived_Private_Type
7712               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
7713
7714             --  For discriminated types, the derivation includes deriving
7715             --  primitive operations. For others it is done below.
7716
7717             if Is_Tagged_Type (Parent_Type)
7718               or else Has_Discriminants (Parent_Type)
7719               or else (Present (Full_View (Parent_Type))
7720                         and then Has_Discriminants (Full_View (Parent_Type)))
7721             then
7722                return;
7723             end if;
7724
7725          when Concurrent_Kind =>
7726             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
7727
7728          when others =>
7729             raise Program_Error;
7730       end case;
7731
7732       if Etype (Derived_Type) = Any_Type then
7733          return;
7734       end if;
7735
7736       --  Set delayed freeze and then derive subprograms, we need to do this
7737       --  in this order so that derived subprograms inherit the derived freeze
7738       --  if necessary.
7739
7740       Set_Has_Delayed_Freeze (Derived_Type);
7741       if Derive_Subps then
7742          Derive_Subprograms (Parent_Type, Derived_Type);
7743       end if;
7744
7745       Set_Has_Primitive_Operations
7746         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
7747    end Build_Derived_Type;
7748
7749    -----------------------
7750    -- Build_Discriminal --
7751    -----------------------
7752
7753    procedure Build_Discriminal (Discrim : Entity_Id) is
7754       D_Minal : Entity_Id;
7755       CR_Disc : Entity_Id;
7756
7757    begin
7758       --  A discriminal has the same name as the discriminant
7759
7760       D_Minal :=
7761         Make_Defining_Identifier (Sloc (Discrim),
7762           Chars => Chars (Discrim));
7763
7764       Set_Ekind     (D_Minal, E_In_Parameter);
7765       Set_Mechanism (D_Minal, Default_Mechanism);
7766       Set_Etype     (D_Minal, Etype (Discrim));
7767       Set_Scope     (D_Minal, Current_Scope);
7768
7769       Set_Discriminal (Discrim, D_Minal);
7770       Set_Discriminal_Link (D_Minal, Discrim);
7771
7772       --  For task types, build at once the discriminants of the corresponding
7773       --  record, which are needed if discriminants are used in entry defaults
7774       --  and in family bounds.
7775
7776       if Is_Concurrent_Type (Current_Scope)
7777         or else Is_Limited_Type (Current_Scope)
7778       then
7779          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
7780
7781          Set_Ekind            (CR_Disc, E_In_Parameter);
7782          Set_Mechanism        (CR_Disc, Default_Mechanism);
7783          Set_Etype            (CR_Disc, Etype (Discrim));
7784          Set_Scope            (CR_Disc, Current_Scope);
7785          Set_Discriminal_Link (CR_Disc, Discrim);
7786          Set_CR_Discriminant  (Discrim, CR_Disc);
7787       end if;
7788    end Build_Discriminal;
7789
7790    ------------------------------------
7791    -- Build_Discriminant_Constraints --
7792    ------------------------------------
7793
7794    function Build_Discriminant_Constraints
7795      (T           : Entity_Id;
7796       Def         : Node_Id;
7797       Derived_Def : Boolean := False) return Elist_Id
7798    is
7799       C        : constant Node_Id := Constraint (Def);
7800       Nb_Discr : constant Nat     := Number_Discriminants (T);
7801
7802       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
7803       --  Saves the expression corresponding to a given discriminant in T
7804
7805       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
7806       --  Return the Position number within array Discr_Expr of a discriminant
7807       --  D within the discriminant list of the discriminated type T.
7808
7809       ------------------
7810       -- Pos_Of_Discr --
7811       ------------------
7812
7813       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
7814          Disc : Entity_Id;
7815
7816       begin
7817          Disc := First_Discriminant (T);
7818          for J in Discr_Expr'Range loop
7819             if Disc = D then
7820                return J;
7821             end if;
7822
7823             Next_Discriminant (Disc);
7824          end loop;
7825
7826          --  Note: Since this function is called on discriminants that are
7827          --  known to belong to the discriminated type, falling through the
7828          --  loop with no match signals an internal compiler error.
7829
7830          raise Program_Error;
7831       end Pos_Of_Discr;
7832
7833       --  Declarations local to Build_Discriminant_Constraints
7834
7835       Discr : Entity_Id;
7836       E     : Entity_Id;
7837       Elist : constant Elist_Id := New_Elmt_List;
7838
7839       Constr   : Node_Id;
7840       Expr     : Node_Id;
7841       Id       : Node_Id;
7842       Position : Nat;
7843       Found    : Boolean;
7844
7845       Discrim_Present : Boolean := False;
7846
7847    --  Start of processing for Build_Discriminant_Constraints
7848
7849    begin
7850       --  The following loop will process positional associations only.
7851       --  For a positional association, the (single) discriminant is
7852       --  implicitly specified by position, in textual order (RM 3.7.2).
7853
7854       Discr  := First_Discriminant (T);
7855       Constr := First (Constraints (C));
7856       for D in Discr_Expr'Range loop
7857          exit when Nkind (Constr) = N_Discriminant_Association;
7858
7859          if No (Constr) then
7860             Error_Msg_N ("too few discriminants given in constraint", C);
7861             return New_Elmt_List;
7862
7863          elsif Nkind (Constr) = N_Range
7864            or else (Nkind (Constr) = N_Attribute_Reference
7865                      and then
7866                     Attribute_Name (Constr) = Name_Range)
7867          then
7868             Error_Msg_N
7869               ("a range is not a valid discriminant constraint", Constr);
7870             Discr_Expr (D) := Error;
7871
7872          else
7873             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
7874             Discr_Expr (D) := Constr;
7875          end if;
7876
7877          Next_Discriminant (Discr);
7878          Next (Constr);
7879       end loop;
7880
7881       if No (Discr) and then Present (Constr) then
7882          Error_Msg_N ("too many discriminants given in constraint", Constr);
7883          return New_Elmt_List;
7884       end if;
7885
7886       --  Named associations can be given in any order, but if both positional
7887       --  and named associations are used in the same discriminant constraint,
7888       --  then positional associations must occur first, at their normal
7889       --  position. Hence once a named association is used, the rest of the
7890       --  discriminant constraint must use only named associations.
7891
7892       while Present (Constr) loop
7893
7894          --  Positional association forbidden after a named association
7895
7896          if Nkind (Constr) /= N_Discriminant_Association then
7897             Error_Msg_N ("positional association follows named one", Constr);
7898             return New_Elmt_List;
7899
7900          --  Otherwise it is a named association
7901
7902          else
7903             --  E records the type of the discriminants in the named
7904             --  association. All the discriminants specified in the same name
7905             --  association must have the same type.
7906
7907             E := Empty;
7908
7909             --  Search the list of discriminants in T to see if the simple name
7910             --  given in the constraint matches any of them.
7911
7912             Id := First (Selector_Names (Constr));
7913             while Present (Id) loop
7914                Found := False;
7915
7916                --  If Original_Discriminant is present, we are processing a
7917                --  generic instantiation and this is an instance node. We need
7918                --  to find the name of the corresponding discriminant in the
7919                --  actual record type T and not the name of the discriminant in
7920                --  the generic formal. Example:
7921
7922                --    generic
7923                --       type G (D : int) is private;
7924                --    package P is
7925                --       subtype W is G (D => 1);
7926                --    end package;
7927                --    type Rec (X : int) is record ... end record;
7928                --    package Q is new P (G => Rec);
7929
7930                --  At the point of the instantiation, formal type G is Rec
7931                --  and therefore when reanalyzing "subtype W is G (D => 1);"
7932                --  which really looks like "subtype W is Rec (D => 1);" at
7933                --  the point of instantiation, we want to find the discriminant
7934                --  that corresponds to D in Rec, i.e. X.
7935
7936                if Present (Original_Discriminant (Id)) then
7937                   Discr := Find_Corresponding_Discriminant (Id, T);
7938                   Found := True;
7939
7940                else
7941                   Discr := First_Discriminant (T);
7942                   while Present (Discr) loop
7943                      if Chars (Discr) = Chars (Id) then
7944                         Found := True;
7945                         exit;
7946                      end if;
7947
7948                      Next_Discriminant (Discr);
7949                   end loop;
7950
7951                   if not Found then
7952                      Error_Msg_N ("& does not match any discriminant", Id);
7953                      return New_Elmt_List;
7954
7955                   --  The following is only useful for the benefit of generic
7956                   --  instances but it does not interfere with other
7957                   --  processing for the non-generic case so we do it in all
7958                   --  cases (for generics this statement is executed when
7959                   --  processing the generic definition, see comment at the
7960                   --  beginning of this if statement).
7961
7962                   else
7963                      Set_Original_Discriminant (Id, Discr);
7964                   end if;
7965                end if;
7966
7967                Position := Pos_Of_Discr (T, Discr);
7968
7969                if Present (Discr_Expr (Position)) then
7970                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
7971
7972                else
7973                   --  Each discriminant specified in the same named association
7974                   --  must be associated with a separate copy of the
7975                   --  corresponding expression.
7976
7977                   if Present (Next (Id)) then
7978                      Expr := New_Copy_Tree (Expression (Constr));
7979                      Set_Parent (Expr, Parent (Expression (Constr)));
7980                   else
7981                      Expr := Expression (Constr);
7982                   end if;
7983
7984                   Discr_Expr (Position) := Expr;
7985                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
7986                end if;
7987
7988                --  A discriminant association with more than one discriminant
7989                --  name is only allowed if the named discriminants are all of
7990                --  the same type (RM 3.7.1(8)).
7991
7992                if E = Empty then
7993                   E := Base_Type (Etype (Discr));
7994
7995                elsif Base_Type (Etype (Discr)) /= E then
7996                   Error_Msg_N
7997                     ("all discriminants in an association " &
7998                      "must have the same type", Id);
7999                end if;
8000
8001                Next (Id);
8002             end loop;
8003          end if;
8004
8005          Next (Constr);
8006       end loop;
8007
8008       --  A discriminant constraint must provide exactly one value for each
8009       --  discriminant of the type (RM 3.7.1(8)).
8010
8011       for J in Discr_Expr'Range loop
8012          if No (Discr_Expr (J)) then
8013             Error_Msg_N ("too few discriminants given in constraint", C);
8014             return New_Elmt_List;
8015          end if;
8016       end loop;
8017
8018       --  Determine if there are discriminant expressions in the constraint
8019
8020       for J in Discr_Expr'Range loop
8021          if Denotes_Discriminant
8022               (Discr_Expr (J), Check_Concurrent => True)
8023          then
8024             Discrim_Present := True;
8025          end if;
8026       end loop;
8027
8028       --  Build an element list consisting of the expressions given in the
8029       --  discriminant constraint and apply the appropriate checks. The list
8030       --  is constructed after resolving any named discriminant associations
8031       --  and therefore the expressions appear in the textual order of the
8032       --  discriminants.
8033
8034       Discr := First_Discriminant (T);
8035       for J in Discr_Expr'Range loop
8036          if Discr_Expr (J) /= Error then
8037             Append_Elmt (Discr_Expr (J), Elist);
8038
8039             --  If any of the discriminant constraints is given by a
8040             --  discriminant and we are in a derived type declaration we
8041             --  have a discriminant renaming. Establish link between new
8042             --  and old discriminant.
8043
8044             if Denotes_Discriminant (Discr_Expr (J)) then
8045                if Derived_Def then
8046                   Set_Corresponding_Discriminant
8047                     (Entity (Discr_Expr (J)), Discr);
8048                end if;
8049
8050             --  Force the evaluation of non-discriminant expressions.
8051             --  If we have found a discriminant in the constraint 3.4(26)
8052             --  and 3.8(18) demand that no range checks are performed are
8053             --  after evaluation. If the constraint is for a component
8054             --  definition that has a per-object constraint, expressions are
8055             --  evaluated but not checked either. In all other cases perform
8056             --  a range check.
8057
8058             else
8059                if Discrim_Present then
8060                   null;
8061
8062                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8063                  and then
8064                    Has_Per_Object_Constraint
8065                      (Defining_Identifier (Parent (Parent (Def))))
8066                then
8067                   null;
8068
8069                elsif Is_Access_Type (Etype (Discr)) then
8070                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8071
8072                else
8073                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8074                end if;
8075
8076                Force_Evaluation (Discr_Expr (J));
8077             end if;
8078
8079             --  Check that the designated type of an access discriminant's
8080             --  expression is not a class-wide type unless the discriminant's
8081             --  designated type is also class-wide.
8082
8083             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8084               and then not Is_Class_Wide_Type
8085                          (Designated_Type (Etype (Discr)))
8086               and then Etype (Discr_Expr (J)) /= Any_Type
8087               and then Is_Class_Wide_Type
8088                          (Designated_Type (Etype (Discr_Expr (J))))
8089             then
8090                Wrong_Type (Discr_Expr (J), Etype (Discr));
8091
8092             elsif Is_Access_Type (Etype (Discr))
8093               and then not Is_Access_Constant (Etype (Discr))
8094               and then Is_Access_Type (Etype (Discr_Expr (J)))
8095               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8096             then
8097                Error_Msg_NE
8098                  ("constraint for discriminant& must be access to variable",
8099                     Def, Discr);
8100             end if;
8101          end if;
8102
8103          Next_Discriminant (Discr);
8104       end loop;
8105
8106       return Elist;
8107    end Build_Discriminant_Constraints;
8108
8109    ---------------------------------
8110    -- Build_Discriminated_Subtype --
8111    ---------------------------------
8112
8113    procedure Build_Discriminated_Subtype
8114      (T           : Entity_Id;
8115       Def_Id      : Entity_Id;
8116       Elist       : Elist_Id;
8117       Related_Nod : Node_Id;
8118       For_Access  : Boolean := False)
8119    is
8120       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8121       Constrained : constant Boolean :=
8122                       (Has_Discrs
8123                          and then not Is_Empty_Elmt_List (Elist)
8124                          and then not Is_Class_Wide_Type (T))
8125                         or else Is_Constrained (T);
8126
8127    begin
8128       if Ekind (T) = E_Record_Type then
8129          if For_Access then
8130             Set_Ekind (Def_Id, E_Private_Subtype);
8131             Set_Is_For_Access_Subtype (Def_Id, True);
8132          else
8133             Set_Ekind (Def_Id, E_Record_Subtype);
8134          end if;
8135
8136          --  Inherit preelaboration flag from base, for types for which it
8137          --  may have been set: records, private types, protected types.
8138
8139          Set_Known_To_Have_Preelab_Init
8140            (Def_Id, Known_To_Have_Preelab_Init (T));
8141
8142       elsif Ekind (T) = E_Task_Type then
8143          Set_Ekind (Def_Id, E_Task_Subtype);
8144
8145       elsif Ekind (T) = E_Protected_Type then
8146          Set_Ekind (Def_Id, E_Protected_Subtype);
8147          Set_Known_To_Have_Preelab_Init
8148            (Def_Id, Known_To_Have_Preelab_Init (T));
8149
8150       elsif Is_Private_Type (T) then
8151          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8152          Set_Known_To_Have_Preelab_Init
8153            (Def_Id, Known_To_Have_Preelab_Init (T));
8154
8155       elsif Is_Class_Wide_Type (T) then
8156          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8157
8158       else
8159          --  Incomplete type. Attach subtype to list of dependents, to be
8160          --  completed with full view of parent type,  unless is it the
8161          --  designated subtype of a record component within an init_proc.
8162          --  This last case arises for a component of an access type whose
8163          --  designated type is incomplete (e.g. a Taft Amendment type).
8164          --  The designated subtype is within an inner scope, and needs no
8165          --  elaboration, because only the access type is needed in the
8166          --  initialization procedure.
8167
8168          Set_Ekind (Def_Id, Ekind (T));
8169
8170          if For_Access and then Within_Init_Proc then
8171             null;
8172          else
8173             Append_Elmt (Def_Id, Private_Dependents (T));
8174          end if;
8175       end if;
8176
8177       Set_Etype             (Def_Id, T);
8178       Init_Size_Align       (Def_Id);
8179       Set_Has_Discriminants (Def_Id, Has_Discrs);
8180       Set_Is_Constrained    (Def_Id, Constrained);
8181
8182       Set_First_Entity      (Def_Id, First_Entity   (T));
8183       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8184
8185       --  If the subtype is the completion of a private declaration, there may
8186       --  have been representation clauses for the partial view, and they must
8187       --  be preserved. Build_Derived_Type chains the inherited clauses with
8188       --  the ones appearing on the extension. If this comes from a subtype
8189       --  declaration, all clauses are inherited.
8190
8191       if No (First_Rep_Item (Def_Id)) then
8192          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8193       end if;
8194
8195       if Is_Tagged_Type (T) then
8196          Set_Is_Tagged_Type  (Def_Id);
8197          Make_Class_Wide_Type (Def_Id);
8198       end if;
8199
8200       Set_Stored_Constraint (Def_Id, No_Elist);
8201
8202       if Has_Discrs then
8203          Set_Discriminant_Constraint (Def_Id, Elist);
8204          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8205       end if;
8206
8207       if Is_Tagged_Type (T) then
8208
8209          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8210          --  concurrent record type (which has the list of primitive
8211          --  operations).
8212
8213          if Ada_Version >= Ada_05
8214            and then Is_Concurrent_Type (T)
8215          then
8216             Set_Corresponding_Record_Type (Def_Id,
8217                Corresponding_Record_Type (T));
8218          else
8219             Set_Primitive_Operations (Def_Id, Primitive_Operations (T));
8220          end if;
8221
8222          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8223       end if;
8224
8225       --  Subtypes introduced by component declarations do not need to be
8226       --  marked as delayed, and do not get freeze nodes, because the semantics
8227       --  verifies that the parents of the subtypes are frozen before the
8228       --  enclosing record is frozen.
8229
8230       if not Is_Type (Scope (Def_Id)) then
8231          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8232
8233          if Is_Private_Type (T)
8234            and then Present (Full_View (T))
8235          then
8236             Conditional_Delay (Def_Id, Full_View (T));
8237          else
8238             Conditional_Delay (Def_Id, T);
8239          end if;
8240       end if;
8241
8242       if Is_Record_Type (T) then
8243          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8244
8245          if Has_Discrs
8246             and then not Is_Empty_Elmt_List (Elist)
8247             and then not For_Access
8248          then
8249             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8250          elsif not For_Access then
8251             Set_Cloned_Subtype (Def_Id, T);
8252          end if;
8253       end if;
8254    end Build_Discriminated_Subtype;
8255
8256    ---------------------------
8257    -- Build_Itype_Reference --
8258    ---------------------------
8259
8260    procedure Build_Itype_Reference
8261      (Ityp : Entity_Id;
8262       Nod  : Node_Id)
8263    is
8264       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8265    begin
8266       Set_Itype (IR, Ityp);
8267       Insert_After (Nod, IR);
8268    end Build_Itype_Reference;
8269
8270    ------------------------
8271    -- Build_Scalar_Bound --
8272    ------------------------
8273
8274    function Build_Scalar_Bound
8275      (Bound : Node_Id;
8276       Par_T : Entity_Id;
8277       Der_T : Entity_Id) return Node_Id
8278    is
8279       New_Bound : Entity_Id;
8280
8281    begin
8282       --  Note: not clear why this is needed, how can the original bound
8283       --  be unanalyzed at this point? and if it is, what business do we
8284       --  have messing around with it? and why is the base type of the
8285       --  parent type the right type for the resolution. It probably is
8286       --  not! It is OK for the new bound we are creating, but not for
8287       --  the old one??? Still if it never happens, no problem!
8288
8289       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8290
8291       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8292          New_Bound := New_Copy (Bound);
8293          Set_Etype (New_Bound, Der_T);
8294          Set_Analyzed (New_Bound);
8295
8296       elsif Is_Entity_Name (Bound) then
8297          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8298
8299       --  The following is almost certainly wrong. What business do we have
8300       --  relocating a node (Bound) that is presumably still attached to
8301       --  the tree elsewhere???
8302
8303       else
8304          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8305       end if;
8306
8307       Set_Etype (New_Bound, Der_T);
8308       return New_Bound;
8309    end Build_Scalar_Bound;
8310
8311    --------------------------------
8312    -- Build_Underlying_Full_View --
8313    --------------------------------
8314
8315    procedure Build_Underlying_Full_View
8316      (N   : Node_Id;
8317       Typ : Entity_Id;
8318       Par : Entity_Id)
8319    is
8320       Loc  : constant Source_Ptr := Sloc (N);
8321       Subt : constant Entity_Id :=
8322                Make_Defining_Identifier
8323                  (Loc, New_External_Name (Chars (Typ), 'S'));
8324
8325       Constr : Node_Id;
8326       Indic  : Node_Id;
8327       C      : Node_Id;
8328       Id     : Node_Id;
8329
8330       procedure Set_Discriminant_Name (Id : Node_Id);
8331       --  If the derived type has discriminants, they may rename discriminants
8332       --  of the parent. When building the full view of the parent, we need to
8333       --  recover the names of the original discriminants if the constraint is
8334       --  given by named associations.
8335
8336       ---------------------------
8337       -- Set_Discriminant_Name --
8338       ---------------------------
8339
8340       procedure Set_Discriminant_Name (Id : Node_Id) is
8341          Disc : Entity_Id;
8342
8343       begin
8344          Set_Original_Discriminant (Id, Empty);
8345
8346          if Has_Discriminants (Typ) then
8347             Disc := First_Discriminant (Typ);
8348             while Present (Disc) loop
8349                if Chars (Disc) = Chars (Id)
8350                  and then Present (Corresponding_Discriminant (Disc))
8351                then
8352                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
8353                end if;
8354                Next_Discriminant (Disc);
8355             end loop;
8356          end if;
8357       end Set_Discriminant_Name;
8358
8359    --  Start of processing for Build_Underlying_Full_View
8360
8361    begin
8362       if Nkind (N) = N_Full_Type_Declaration then
8363          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
8364
8365       elsif Nkind (N) = N_Subtype_Declaration then
8366          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
8367
8368       elsif Nkind (N) = N_Component_Declaration then
8369          Constr :=
8370            New_Copy_Tree
8371              (Constraint (Subtype_Indication (Component_Definition (N))));
8372
8373       else
8374          raise Program_Error;
8375       end if;
8376
8377       C := First (Constraints (Constr));
8378       while Present (C) loop
8379          if Nkind (C) = N_Discriminant_Association then
8380             Id := First (Selector_Names (C));
8381             while Present (Id) loop
8382                Set_Discriminant_Name (Id);
8383                Next (Id);
8384             end loop;
8385          end if;
8386
8387          Next (C);
8388       end loop;
8389
8390       Indic :=
8391         Make_Subtype_Declaration (Loc,
8392           Defining_Identifier => Subt,
8393           Subtype_Indication  =>
8394             Make_Subtype_Indication (Loc,
8395               Subtype_Mark => New_Reference_To (Par, Loc),
8396               Constraint   => New_Copy_Tree (Constr)));
8397
8398       --  If this is a component subtype for an outer itype, it is not
8399       --  a list member, so simply set the parent link for analysis: if
8400       --  the enclosing type does not need to be in a declarative list,
8401       --  neither do the components.
8402
8403       if Is_List_Member (N)
8404         and then Nkind (N) /= N_Component_Declaration
8405       then
8406          Insert_Before (N, Indic);
8407       else
8408          Set_Parent (Indic, Parent (N));
8409       end if;
8410
8411       Analyze (Indic);
8412       Set_Underlying_Full_View (Typ, Full_View (Subt));
8413    end Build_Underlying_Full_View;
8414
8415    -------------------------------
8416    -- Check_Abstract_Overriding --
8417    -------------------------------
8418
8419    procedure Check_Abstract_Overriding (T : Entity_Id) is
8420       Alias_Subp : Entity_Id;
8421       Elmt       : Elmt_Id;
8422       Op_List    : Elist_Id;
8423       Subp       : Entity_Id;
8424       Type_Def   : Node_Id;
8425
8426    begin
8427       Op_List := Primitive_Operations (T);
8428
8429       --  Loop to check primitive operations
8430
8431       Elmt := First_Elmt (Op_List);
8432       while Present (Elmt) loop
8433          Subp := Node (Elmt);
8434          Alias_Subp := Alias (Subp);
8435
8436          --  Inherited subprograms are identified by the fact that they do not
8437          --  come from source, and the associated source location is the
8438          --  location of the first subtype of the derived type.
8439
8440          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
8441          --  subprograms that "require overriding".
8442
8443          --  Special exception, do not complain about failure to override the
8444          --  stream routines _Input and _Output, as well as the primitive
8445          --  operations used in dispatching selects since we always provide
8446          --  automatic overridings for these subprograms.
8447
8448          --  Also ignore this rule for convention CIL since .NET libraries
8449          --  do bizarre things with interfaces???
8450
8451          --  The partial view of T may have been a private extension, for
8452          --  which inherited functions dispatching on result are abstract.
8453          --  If the full view is a null extension, there is no need for
8454          --  overriding in Ada2005, but wrappers need to be built for them
8455          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
8456
8457          if Is_Null_Extension (T)
8458            and then Has_Controlling_Result (Subp)
8459            and then Ada_Version >= Ada_05
8460            and then Present (Alias_Subp)
8461            and then not Comes_From_Source (Subp)
8462            and then not Is_Abstract_Subprogram (Alias_Subp)
8463            and then not Is_Access_Type (Etype (Subp))
8464          then
8465             null;
8466
8467          --  Ada 2005 (AI-251): Internal entities of interfaces need no
8468          --  processing because this check is done with the aliased
8469          --  entity
8470
8471          elsif Present (Interface_Alias (Subp)) then
8472             null;
8473
8474          elsif (Is_Abstract_Subprogram (Subp)
8475                  or else Requires_Overriding (Subp)
8476                  or else
8477                    (Has_Controlling_Result (Subp)
8478                      and then Present (Alias_Subp)
8479                      and then not Comes_From_Source (Subp)
8480                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
8481            and then not Is_TSS (Subp, TSS_Stream_Input)
8482            and then not Is_TSS (Subp, TSS_Stream_Output)
8483            and then not Is_Abstract_Type (T)
8484            and then Convention (T) /= Convention_CIL
8485            and then not Is_Predefined_Interface_Primitive (Subp)
8486
8487             --  Ada 2005 (AI-251): Do not consider hidden entities associated
8488             --  with abstract interface types because the check will be done
8489             --  with the aliased entity (otherwise we generate a duplicated
8490             --  error message).
8491
8492            and then not Present (Interface_Alias (Subp))
8493          then
8494             if Present (Alias_Subp) then
8495
8496                --  Only perform the check for a derived subprogram when the
8497                --  type has an explicit record extension. This avoids incorrect
8498                --  flagging of abstract subprograms for the case of a type
8499                --  without an extension that is derived from a formal type
8500                --  with a tagged actual (can occur within a private part).
8501
8502                --  Ada 2005 (AI-391): In the case of an inherited function with
8503                --  a controlling result of the type, the rule does not apply if
8504                --  the type is a null extension (unless the parent function
8505                --  itself is abstract, in which case the function must still be
8506                --  be overridden). The expander will generate an overriding
8507                --  wrapper function calling the parent subprogram (see
8508                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
8509
8510                Type_Def := Type_Definition (Parent (T));
8511
8512                if Nkind (Type_Def) = N_Derived_Type_Definition
8513                  and then Present (Record_Extension_Part (Type_Def))
8514                  and then
8515                    (Ada_Version < Ada_05
8516                       or else not Is_Null_Extension (T)
8517                       or else Ekind (Subp) = E_Procedure
8518                       or else not Has_Controlling_Result (Subp)
8519                       or else Is_Abstract_Subprogram (Alias_Subp)
8520                       or else Requires_Overriding (Subp)
8521                       or else Is_Access_Type (Etype (Subp)))
8522                then
8523                   --  Avoid reporting error in case of abstract predefined
8524                   --  primitive inherited from interface type because the
8525                   --  body of internally generated predefined primitives
8526                   --  of tagged types are generated later by Freeze_Type
8527
8528                   if Is_Interface (Root_Type (T))
8529                     and then Is_Abstract_Subprogram (Subp)
8530                     and then Is_Predefined_Dispatching_Operation (Subp)
8531                     and then not Comes_From_Source (Ultimate_Alias (Subp))
8532                   then
8533                      null;
8534
8535                   else
8536                      Error_Msg_NE
8537                        ("type must be declared abstract or & overridden",
8538                         T, Subp);
8539
8540                      --  Traverse the whole chain of aliased subprograms to
8541                      --  complete the error notification. This is especially
8542                      --  useful for traceability of the chain of entities when
8543                      --  the subprogram corresponds with an interface
8544                      --  subprogram (which may be defined in another package).
8545
8546                      if Present (Alias_Subp) then
8547                         declare
8548                            E : Entity_Id;
8549
8550                         begin
8551                            E := Subp;
8552                            while Present (Alias (E)) loop
8553                               Error_Msg_Sloc := Sloc (E);
8554                               Error_Msg_NE
8555                                 ("\& has been inherited #", T, Subp);
8556                               E := Alias (E);
8557                            end loop;
8558
8559                            Error_Msg_Sloc := Sloc (E);
8560                            Error_Msg_NE
8561                              ("\& has been inherited from subprogram #",
8562                               T, Subp);
8563                         end;
8564                      end if;
8565                   end if;
8566
8567                --  Ada 2005 (AI-345): Protected or task type implementing
8568                --  abstract interfaces.
8569
8570                elsif Is_Concurrent_Record_Type (T)
8571                  and then Present (Interfaces (T))
8572                then
8573                   --  The controlling formal of Subp must be of mode "out",
8574                   --  "in out" or an access-to-variable to be overridden.
8575
8576                   --  Error message below needs rewording (remember comma
8577                   --  in -gnatj mode) ???
8578
8579                   if Ekind (First_Formal (Subp)) = E_In_Parameter
8580                     and then Ekind (Subp) /= E_Function
8581                   then
8582                      if not Is_Predefined_Dispatching_Operation (Subp) then
8583                         Error_Msg_NE
8584                           ("first formal of & must be of mode `OUT`, " &
8585                            "`IN OUT` or access-to-variable", T, Subp);
8586                         Error_Msg_N
8587                           ("\to be overridden by protected procedure or " &
8588                            "entry (RM 9.4(11.9/2))", T);
8589                      end if;
8590
8591                   --  Some other kind of overriding failure
8592
8593                   else
8594                      Error_Msg_NE
8595                        ("interface subprogram & must be overridden",
8596                         T, Subp);
8597
8598                      --  Examine primitive operations of synchronized type,
8599                      --  to find homonyms that have the wrong profile.
8600
8601                      declare
8602                         Prim : Entity_Id;
8603
8604                      begin
8605                         Prim :=
8606                           First_Entity (Corresponding_Concurrent_Type (T));
8607                         while Present (Prim) loop
8608                            if Chars (Prim) = Chars (Subp) then
8609                               Error_Msg_NE
8610                                 ("profile is not type conformant with "
8611                                    & "prefixed view profile of "
8612                                    & "inherited operation&", Prim, Subp);
8613                            end if;
8614
8615                            Next_Entity (Prim);
8616                         end loop;
8617                      end;
8618                   end if;
8619                end if;
8620
8621             else
8622                Error_Msg_Node_2 := T;
8623                Error_Msg_N
8624                  ("abstract subprogram& not allowed for type&", Subp);
8625
8626                --  Also post unconditional warning on the type (unconditional
8627                --  so that if there are more than one of these cases, we get
8628                --  them all, and not just the first one).
8629
8630                Error_Msg_Node_2 := Subp;
8631                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
8632             end if;
8633          end if;
8634
8635          --  Ada 2005 (AI05-0030): Inspect hidden subprograms which provide
8636          --  the mapping between interface and implementing type primitives.
8637          --  If the interface alias is marked as Implemented_By_Entry, the
8638          --  alias must be an entry wrapper.
8639
8640          if Ada_Version >= Ada_05
8641            and then Is_Hidden (Subp)
8642            and then Present (Interface_Alias (Subp))
8643            and then Implemented_By_Entry (Interface_Alias (Subp))
8644            and then Present (Alias_Subp)
8645            and then
8646              (not Is_Primitive_Wrapper (Alias_Subp)
8647                 or else Ekind (Wrapped_Entity (Alias_Subp)) /= E_Entry)
8648          then
8649             declare
8650                Error_Ent : Entity_Id := T;
8651
8652             begin
8653                if Is_Concurrent_Record_Type (Error_Ent) then
8654                   Error_Ent := Corresponding_Concurrent_Type (Error_Ent);
8655                end if;
8656
8657                Error_Msg_Node_2 := Interface_Alias (Subp);
8658                Error_Msg_NE
8659                  ("type & must implement abstract subprogram & with an entry",
8660                   Error_Ent, Error_Ent);
8661             end;
8662          end if;
8663
8664          Next_Elmt (Elmt);
8665       end loop;
8666    end Check_Abstract_Overriding;
8667
8668    ------------------------------------------------
8669    -- Check_Access_Discriminant_Requires_Limited --
8670    ------------------------------------------------
8671
8672    procedure Check_Access_Discriminant_Requires_Limited
8673      (D   : Node_Id;
8674       Loc : Node_Id)
8675    is
8676    begin
8677       --  A discriminant_specification for an access discriminant shall appear
8678       --  only in the declaration for a task or protected type, or for a type
8679       --  with the reserved word 'limited' in its definition or in one of its
8680       --  ancestors. (RM 3.7(10))
8681
8682       if Nkind (Discriminant_Type (D)) = N_Access_Definition
8683         and then not Is_Concurrent_Type (Current_Scope)
8684         and then not Is_Concurrent_Record_Type (Current_Scope)
8685         and then not Is_Limited_Record (Current_Scope)
8686         and then Ekind (Current_Scope) /= E_Limited_Private_Type
8687       then
8688          Error_Msg_N
8689            ("access discriminants allowed only for limited types", Loc);
8690       end if;
8691    end Check_Access_Discriminant_Requires_Limited;
8692
8693    -----------------------------------
8694    -- Check_Aliased_Component_Types --
8695    -----------------------------------
8696
8697    procedure Check_Aliased_Component_Types (T : Entity_Id) is
8698       C : Entity_Id;
8699
8700    begin
8701       --  ??? Also need to check components of record extensions, but not
8702       --  components of protected types (which are always limited).
8703
8704       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
8705       --  types to be unconstrained. This is safe because it is illegal to
8706       --  create access subtypes to such types with explicit discriminant
8707       --  constraints.
8708
8709       if not Is_Limited_Type (T) then
8710          if Ekind (T) = E_Record_Type then
8711             C := First_Component (T);
8712             while Present (C) loop
8713                if Is_Aliased (C)
8714                  and then Has_Discriminants (Etype (C))
8715                  and then not Is_Constrained (Etype (C))
8716                  and then not In_Instance_Body
8717                  and then Ada_Version < Ada_05
8718                then
8719                   Error_Msg_N
8720                     ("aliased component must be constrained (RM 3.6(11))",
8721                       C);
8722                end if;
8723
8724                Next_Component (C);
8725             end loop;
8726
8727          elsif Ekind (T) = E_Array_Type then
8728             if Has_Aliased_Components (T)
8729               and then Has_Discriminants (Component_Type (T))
8730               and then not Is_Constrained (Component_Type (T))
8731               and then not In_Instance_Body
8732               and then Ada_Version < Ada_05
8733             then
8734                Error_Msg_N
8735                  ("aliased component type must be constrained (RM 3.6(11))",
8736                     T);
8737             end if;
8738          end if;
8739       end if;
8740    end Check_Aliased_Component_Types;
8741
8742    ----------------------
8743    -- Check_Completion --
8744    ----------------------
8745
8746    procedure Check_Completion (Body_Id : Node_Id := Empty) is
8747       E : Entity_Id;
8748
8749       procedure Post_Error;
8750       --  Post error message for lack of completion for entity E
8751
8752       ----------------
8753       -- Post_Error --
8754       ----------------
8755
8756       procedure Post_Error is
8757
8758          procedure Missing_Body;
8759          --  Output missing body message
8760
8761          ------------------
8762          -- Missing_Body --
8763          ------------------
8764
8765          procedure Missing_Body is
8766          begin
8767             --  Spec is in same unit, so we can post on spec
8768
8769             if In_Same_Source_Unit (Body_Id, E) then
8770                Error_Msg_N ("missing body for &", E);
8771
8772             --  Spec is in a separate unit, so we have to post on the body
8773
8774             else
8775                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
8776             end if;
8777          end Missing_Body;
8778
8779       --  Start of processing for Post_Error
8780
8781       begin
8782          if not Comes_From_Source (E) then
8783
8784             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
8785                --  It may be an anonymous protected type created for a
8786                --  single variable. Post error on variable, if present.
8787
8788                declare
8789                   Var : Entity_Id;
8790
8791                begin
8792                   Var := First_Entity (Current_Scope);
8793                   while Present (Var) loop
8794                      exit when Etype (Var) = E
8795                        and then Comes_From_Source (Var);
8796
8797                      Next_Entity (Var);
8798                   end loop;
8799
8800                   if Present (Var) then
8801                      E := Var;
8802                   end if;
8803                end;
8804             end if;
8805          end if;
8806
8807          --  If a generated entity has no completion, then either previous
8808          --  semantic errors have disabled the expansion phase, or else we had
8809          --  missing subunits, or else we are compiling without expansion,
8810          --  or else something is very wrong.
8811
8812          if not Comes_From_Source (E) then
8813             pragma Assert
8814               (Serious_Errors_Detected > 0
8815                 or else Configurable_Run_Time_Violations > 0
8816                 or else Subunits_Missing
8817                 or else not Expander_Active);
8818             return;
8819
8820          --  Here for source entity
8821
8822          else
8823             --  Here if no body to post the error message, so we post the error
8824             --  on the declaration that has no completion. This is not really
8825             --  the right place to post it, think about this later ???
8826
8827             if No (Body_Id) then
8828                if Is_Type (E) then
8829                   Error_Msg_NE
8830                     ("missing full declaration for }", Parent (E), E);
8831                else
8832                   Error_Msg_NE ("missing body for &", Parent (E), E);
8833                end if;
8834
8835             --  Package body has no completion for a declaration that appears
8836             --  in the corresponding spec. Post error on the body, with a
8837             --  reference to the non-completed declaration.
8838
8839             else
8840                Error_Msg_Sloc := Sloc (E);
8841
8842                if Is_Type (E) then
8843                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
8844
8845                elsif Is_Overloadable (E)
8846                  and then Current_Entity_In_Scope (E) /= E
8847                then
8848                   --  It may be that the completion is mistyped and appears as
8849                   --  a distinct overloading of the entity.
8850
8851                   declare
8852                      Candidate : constant Entity_Id :=
8853                                    Current_Entity_In_Scope (E);
8854                      Decl      : constant Node_Id :=
8855                                    Unit_Declaration_Node (Candidate);
8856
8857                   begin
8858                      if Is_Overloadable (Candidate)
8859                        and then Ekind (Candidate) = Ekind (E)
8860                        and then Nkind (Decl) = N_Subprogram_Body
8861                        and then Acts_As_Spec (Decl)
8862                      then
8863                         Check_Type_Conformant (Candidate, E);
8864
8865                      else
8866                         Missing_Body;
8867                      end if;
8868                   end;
8869
8870                else
8871                   Missing_Body;
8872                end if;
8873             end if;
8874          end if;
8875       end Post_Error;
8876
8877    --  Start of processing for Check_Completion
8878
8879    begin
8880       E := First_Entity (Current_Scope);
8881       while Present (E) loop
8882          if Is_Intrinsic_Subprogram (E) then
8883             null;
8884
8885          --  The following situation requires special handling: a child unit
8886          --  that appears in the context clause of the body of its parent:
8887
8888          --    procedure Parent.Child (...);
8889
8890          --    with Parent.Child;
8891          --    package body Parent is
8892
8893          --  Here Parent.Child appears as a local entity, but should not be
8894          --  flagged as requiring completion, because it is a compilation
8895          --  unit.
8896
8897          --  Ignore missing completion for a subprogram that does not come from
8898          --  source (including the _Call primitive operation of RAS types,
8899          --  which has to have the flag Comes_From_Source for other purposes):
8900          --  we assume that the expander will provide the missing completion.
8901          --  In case of previous errors, other expansion actions that provide
8902          --  bodies for null procedures with not be invoked, so inhibit message
8903          --  in those cases.
8904          --  Note that E_Operator is not in the list that follows, because
8905          --  this kind is reserved for predefined operators, that are
8906          --  intrinsic and do not need completion.
8907
8908          elsif     Ekind (E) = E_Function
8909            or else Ekind (E) = E_Procedure
8910            or else Ekind (E) = E_Generic_Function
8911            or else Ekind (E) = E_Generic_Procedure
8912          then
8913             if Has_Completion (E) then
8914                null;
8915
8916             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
8917                null;
8918
8919             elsif Is_Subprogram (E)
8920               and then (not Comes_From_Source (E)
8921                           or else Chars (E) = Name_uCall)
8922             then
8923                null;
8924
8925             elsif
8926                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
8927             then
8928                null;
8929
8930             elsif Nkind (Parent (E)) = N_Procedure_Specification
8931               and then Null_Present (Parent (E))
8932               and then Serious_Errors_Detected > 0
8933             then
8934                null;
8935
8936             else
8937                Post_Error;
8938             end if;
8939
8940          elsif Is_Entry (E) then
8941             if not Has_Completion (E) and then
8942               (Ekind (Scope (E)) = E_Protected_Object
8943                 or else Ekind (Scope (E)) = E_Protected_Type)
8944             then
8945                Post_Error;
8946             end if;
8947
8948          elsif Is_Package_Or_Generic_Package (E) then
8949             if Unit_Requires_Body (E) then
8950                if not Has_Completion (E)
8951                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
8952                                                        N_Compilation_Unit
8953                then
8954                   Post_Error;
8955                end if;
8956
8957             elsif not Is_Child_Unit (E) then
8958                May_Need_Implicit_Body (E);
8959             end if;
8960
8961          elsif Ekind (E) = E_Incomplete_Type
8962            and then No (Underlying_Type (E))
8963          then
8964             Post_Error;
8965
8966          elsif (Ekind (E) = E_Task_Type or else
8967                 Ekind (E) = E_Protected_Type)
8968            and then not Has_Completion (E)
8969          then
8970             Post_Error;
8971
8972          --  A single task declared in the current scope is a constant, verify
8973          --  that the body of its anonymous type is in the same scope. If the
8974          --  task is defined elsewhere, this may be a renaming declaration for
8975          --  which no completion is needed.
8976
8977          elsif Ekind (E) = E_Constant
8978            and then Ekind (Etype (E)) = E_Task_Type
8979            and then not Has_Completion (Etype (E))
8980            and then Scope (Etype (E)) = Current_Scope
8981          then
8982             Post_Error;
8983
8984          elsif Ekind (E) = E_Protected_Object
8985            and then not Has_Completion (Etype (E))
8986          then
8987             Post_Error;
8988
8989          elsif Ekind (E) = E_Record_Type then
8990             if Is_Tagged_Type (E) then
8991                Check_Abstract_Overriding (E);
8992                Check_Conventions (E);
8993             end if;
8994
8995             Check_Aliased_Component_Types (E);
8996
8997          elsif Ekind (E) = E_Array_Type then
8998             Check_Aliased_Component_Types (E);
8999
9000          end if;
9001
9002          Next_Entity (E);
9003       end loop;
9004    end Check_Completion;
9005
9006    ----------------------------
9007    -- Check_Delta_Expression --
9008    ----------------------------
9009
9010    procedure Check_Delta_Expression (E : Node_Id) is
9011    begin
9012       if not (Is_Real_Type (Etype (E))) then
9013          Wrong_Type (E, Any_Real);
9014
9015       elsif not Is_OK_Static_Expression (E) then
9016          Flag_Non_Static_Expr
9017            ("non-static expression used for delta value!", E);
9018
9019       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9020          Error_Msg_N ("delta expression must be positive", E);
9021
9022       else
9023          return;
9024       end if;
9025
9026       --  If any of above errors occurred, then replace the incorrect
9027       --  expression by the real 0.1, which should prevent further errors.
9028
9029       Rewrite (E,
9030         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9031       Analyze_And_Resolve (E, Standard_Float);
9032    end Check_Delta_Expression;
9033
9034    -----------------------------
9035    -- Check_Digits_Expression --
9036    -----------------------------
9037
9038    procedure Check_Digits_Expression (E : Node_Id) is
9039    begin
9040       if not (Is_Integer_Type (Etype (E))) then
9041          Wrong_Type (E, Any_Integer);
9042
9043       elsif not Is_OK_Static_Expression (E) then
9044          Flag_Non_Static_Expr
9045            ("non-static expression used for digits value!", E);
9046
9047       elsif Expr_Value (E) <= 0 then
9048          Error_Msg_N ("digits value must be greater than zero", E);
9049
9050       else
9051          return;
9052       end if;
9053
9054       --  If any of above errors occurred, then replace the incorrect
9055       --  expression by the integer 1, which should prevent further errors.
9056
9057       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9058       Analyze_And_Resolve (E, Standard_Integer);
9059
9060    end Check_Digits_Expression;
9061
9062    --------------------------
9063    -- Check_Initialization --
9064    --------------------------
9065
9066    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9067    begin
9068       if Is_Limited_Type (T)
9069         and then not In_Instance
9070         and then not In_Inlined_Body
9071       then
9072          if not OK_For_Limited_Init (T, Exp) then
9073
9074             --  In GNAT mode, this is just a warning, to allow it to be evilly
9075             --  turned off. Otherwise it is a real error.
9076
9077             if GNAT_Mode then
9078                Error_Msg_N
9079                  ("?cannot initialize entities of limited type!", Exp);
9080
9081             elsif Ada_Version < Ada_05 then
9082                Error_Msg_N
9083                  ("cannot initialize entities of limited type", Exp);
9084                Explain_Limited_Type (T, Exp);
9085
9086             else
9087                --  Specialize error message according to kind of illegal
9088                --  initial expression.
9089
9090                if Nkind (Exp) = N_Type_Conversion
9091                  and then Nkind (Expression (Exp)) = N_Function_Call
9092                then
9093                   Error_Msg_N
9094                     ("illegal context for call"
9095                       & " to function with limited result", Exp);
9096
9097                else
9098                   Error_Msg_N
9099                     ("initialization of limited object requires aggregate "
9100                       & "or function call",  Exp);
9101                end if;
9102             end if;
9103          end if;
9104       end if;
9105    end Check_Initialization;
9106
9107    ----------------------
9108    -- Check_Interfaces --
9109    ----------------------
9110
9111    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
9112       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
9113
9114       Iface       : Node_Id;
9115       Iface_Def   : Node_Id;
9116       Iface_Typ   : Entity_Id;
9117       Parent_Node : Node_Id;
9118
9119       Is_Task : Boolean := False;
9120       --  Set True if parent type or any progenitor is a task interface
9121
9122       Is_Protected : Boolean := False;
9123       --  Set True if parent type or any progenitor is a protected interface
9124
9125       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
9126       --  Check that a progenitor is compatible with declaration.
9127       --  Error is posted on Error_Node.
9128
9129       ------------------
9130       -- Check_Ifaces --
9131       ------------------
9132
9133       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
9134          Iface_Id : constant Entity_Id :=
9135                       Defining_Identifier (Parent (Iface_Def));
9136          Type_Def : Node_Id;
9137
9138       begin
9139          if Nkind (N) = N_Private_Extension_Declaration then
9140             Type_Def := N;
9141          else
9142             Type_Def := Type_Definition (N);
9143          end if;
9144
9145          if Is_Task_Interface (Iface_Id) then
9146             Is_Task := True;
9147
9148          elsif Is_Protected_Interface (Iface_Id) then
9149             Is_Protected := True;
9150          end if;
9151
9152          if Is_Synchronized_Interface (Iface_Id) then
9153
9154             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
9155             --  extension derived from a synchronized interface must explicitly
9156             --  be declared synchronized, because the full view will be a
9157             --  synchronized type.
9158
9159             if Nkind (N) = N_Private_Extension_Declaration then
9160                if not Synchronized_Present (N) then
9161                   Error_Msg_NE
9162                     ("private extension of& must be explicitly synchronized",
9163                       N, Iface_Id);
9164                end if;
9165
9166             --  However, by 3.9.4(16/2), a full type that is a record extension
9167             --  is never allowed to derive from a synchronized interface (note
9168             --  that interfaces must be excluded from this check, because those
9169             --  are represented by derived type definitions in some cases).
9170
9171             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9172               and then not Interface_Present (Type_Definition (N))
9173             then
9174                Error_Msg_N ("record extension cannot derive from synchronized"
9175                              & " interface", Error_Node);
9176             end if;
9177          end if;
9178
9179          --  Check that the characteristics of the progenitor are compatible
9180          --  with the explicit qualifier in the declaration.
9181          --  The check only applies to qualifiers that come from source.
9182          --  Limited_Present also appears in the declaration of corresponding
9183          --  records, and the check does not apply to them.
9184
9185          if Limited_Present (Type_Def)
9186            and then not
9187              Is_Concurrent_Record_Type (Defining_Identifier (N))
9188          then
9189             if Is_Limited_Interface (Parent_Type)
9190               and then not Is_Limited_Interface (Iface_Id)
9191             then
9192                Error_Msg_NE
9193                  ("progenitor& must be limited interface",
9194                    Error_Node, Iface_Id);
9195
9196             elsif
9197               (Task_Present (Iface_Def)
9198                 or else Protected_Present (Iface_Def)
9199                 or else Synchronized_Present (Iface_Def))
9200               and then Nkind (N) /= N_Private_Extension_Declaration
9201               and then not Error_Posted (N)
9202             then
9203                Error_Msg_NE
9204                  ("progenitor& must be limited interface",
9205                    Error_Node, Iface_Id);
9206             end if;
9207
9208          --  Protected interfaces can only inherit from limited, synchronized
9209          --  or protected interfaces.
9210
9211          elsif Nkind (N) = N_Full_Type_Declaration
9212            and then  Protected_Present (Type_Def)
9213          then
9214             if Limited_Present (Iface_Def)
9215               or else Synchronized_Present (Iface_Def)
9216               or else Protected_Present (Iface_Def)
9217             then
9218                null;
9219
9220             elsif Task_Present (Iface_Def) then
9221                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9222                             & " from task interface", Error_Node);
9223
9224             else
9225                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9226                             & " from non-limited interface", Error_Node);
9227             end if;
9228
9229          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
9230          --  limited and synchronized.
9231
9232          elsif Synchronized_Present (Type_Def) then
9233             if Limited_Present (Iface_Def)
9234               or else Synchronized_Present (Iface_Def)
9235             then
9236                null;
9237
9238             elsif Protected_Present (Iface_Def)
9239               and then Nkind (N) /= N_Private_Extension_Declaration
9240             then
9241                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9242                             & " from protected interface", Error_Node);
9243
9244             elsif Task_Present (Iface_Def)
9245               and then Nkind (N) /= N_Private_Extension_Declaration
9246             then
9247                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9248                             & " from task interface", Error_Node);
9249
9250             elsif not Is_Limited_Interface (Iface_Id) then
9251                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9252                             & " from non-limited interface", Error_Node);
9253             end if;
9254
9255          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
9256          --  synchronized or task interfaces.
9257
9258          elsif Nkind (N) = N_Full_Type_Declaration
9259            and then Task_Present (Type_Def)
9260          then
9261             if Limited_Present (Iface_Def)
9262               or else Synchronized_Present (Iface_Def)
9263               or else Task_Present (Iface_Def)
9264             then
9265                null;
9266
9267             elsif Protected_Present (Iface_Def) then
9268                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9269                             & " protected interface", Error_Node);
9270
9271             else
9272                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9273                             & " non-limited interface", Error_Node);
9274             end if;
9275          end if;
9276       end Check_Ifaces;
9277
9278    --  Start of processing for Check_Interfaces
9279
9280    begin
9281       if Is_Interface (Parent_Type) then
9282          if Is_Task_Interface (Parent_Type) then
9283             Is_Task := True;
9284
9285          elsif Is_Protected_Interface (Parent_Type) then
9286             Is_Protected := True;
9287          end if;
9288       end if;
9289
9290       if Nkind (N) = N_Private_Extension_Declaration then
9291
9292          --  Check that progenitors are compatible with declaration
9293
9294          Iface := First (Interface_List (Def));
9295          while Present (Iface) loop
9296             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9297
9298             Parent_Node := Parent (Base_Type (Iface_Typ));
9299             Iface_Def   := Type_Definition (Parent_Node);
9300
9301             if not Is_Interface (Iface_Typ) then
9302                Diagnose_Interface (Iface, Iface_Typ);
9303
9304             else
9305                Check_Ifaces (Iface_Def, Iface);
9306             end if;
9307
9308             Next (Iface);
9309          end loop;
9310
9311          if Is_Task and Is_Protected then
9312             Error_Msg_N
9313               ("type cannot derive from task and protected interface", N);
9314          end if;
9315
9316          return;
9317       end if;
9318
9319       --  Full type declaration of derived type.
9320       --  Check compatibility with parent if it is interface type
9321
9322       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9323         and then Is_Interface (Parent_Type)
9324       then
9325          Parent_Node := Parent (Parent_Type);
9326
9327          --  More detailed checks for interface varieties
9328
9329          Check_Ifaces
9330            (Iface_Def  => Type_Definition (Parent_Node),
9331             Error_Node => Subtype_Indication (Type_Definition (N)));
9332       end if;
9333
9334       Iface := First (Interface_List (Def));
9335       while Present (Iface) loop
9336          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9337
9338          Parent_Node := Parent (Base_Type (Iface_Typ));
9339          Iface_Def   := Type_Definition (Parent_Node);
9340
9341          if not Is_Interface (Iface_Typ) then
9342             Diagnose_Interface (Iface, Iface_Typ);
9343
9344          else
9345             --  "The declaration of a specific descendant of an interface
9346             --   type freezes the interface type" RM 13.14
9347
9348             Freeze_Before (N, Iface_Typ);
9349             Check_Ifaces (Iface_Def, Error_Node => Iface);
9350          end if;
9351
9352          Next (Iface);
9353       end loop;
9354
9355       if Is_Task and Is_Protected then
9356          Error_Msg_N
9357            ("type cannot derive from task and protected interface", N);
9358       end if;
9359    end Check_Interfaces;
9360
9361    ------------------------------------
9362    -- Check_Or_Process_Discriminants --
9363    ------------------------------------
9364
9365    --  If an incomplete or private type declaration was already given for the
9366    --  type, the discriminants may have already been processed if they were
9367    --  present on the incomplete declaration. In this case a full conformance
9368    --  check is performed otherwise just process them.
9369
9370    procedure Check_Or_Process_Discriminants
9371      (N    : Node_Id;
9372       T    : Entity_Id;
9373       Prev : Entity_Id := Empty)
9374    is
9375    begin
9376       if Has_Discriminants (T) then
9377
9378          --  Make the discriminants visible to component declarations
9379
9380          declare
9381             D    : Entity_Id;
9382             Prev : Entity_Id;
9383
9384          begin
9385             D := First_Discriminant (T);
9386             while Present (D) loop
9387                Prev := Current_Entity (D);
9388                Set_Current_Entity (D);
9389                Set_Is_Immediately_Visible (D);
9390                Set_Homonym (D, Prev);
9391
9392                --  Ada 2005 (AI-230): Access discriminant allowed in
9393                --  non-limited record types.
9394
9395                if Ada_Version < Ada_05 then
9396
9397                   --  This restriction gets applied to the full type here. It
9398                   --  has already been applied earlier to the partial view.
9399
9400                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
9401                end if;
9402
9403                Next_Discriminant (D);
9404             end loop;
9405          end;
9406
9407       elsif Present (Discriminant_Specifications (N)) then
9408          Process_Discriminants (N, Prev);
9409       end if;
9410    end Check_Or_Process_Discriminants;
9411
9412    ----------------------
9413    -- Check_Real_Bound --
9414    ----------------------
9415
9416    procedure Check_Real_Bound (Bound : Node_Id) is
9417    begin
9418       if not Is_Real_Type (Etype (Bound)) then
9419          Error_Msg_N
9420            ("bound in real type definition must be of real type", Bound);
9421
9422       elsif not Is_OK_Static_Expression (Bound) then
9423          Flag_Non_Static_Expr
9424            ("non-static expression used for real type bound!", Bound);
9425
9426       else
9427          return;
9428       end if;
9429
9430       Rewrite
9431         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
9432       Analyze (Bound);
9433       Resolve (Bound, Standard_Float);
9434    end Check_Real_Bound;
9435
9436    ------------------------------
9437    -- Complete_Private_Subtype --
9438    ------------------------------
9439
9440    procedure Complete_Private_Subtype
9441      (Priv        : Entity_Id;
9442       Full        : Entity_Id;
9443       Full_Base   : Entity_Id;
9444       Related_Nod : Node_Id)
9445    is
9446       Save_Next_Entity : Entity_Id;
9447       Save_Homonym     : Entity_Id;
9448
9449    begin
9450       --  Set semantic attributes for (implicit) private subtype completion.
9451       --  If the full type has no discriminants, then it is a copy of the full
9452       --  view of the base. Otherwise, it is a subtype of the base with a
9453       --  possible discriminant constraint. Save and restore the original
9454       --  Next_Entity field of full to ensure that the calls to Copy_Node
9455       --  do not corrupt the entity chain.
9456
9457       --  Note that the type of the full view is the same entity as the type of
9458       --  the partial view. In this fashion, the subtype has access to the
9459       --  correct view of the parent.
9460
9461       Save_Next_Entity := Next_Entity (Full);
9462       Save_Homonym     := Homonym (Priv);
9463
9464       case Ekind (Full_Base) is
9465          when E_Record_Type    |
9466               E_Record_Subtype |
9467               Class_Wide_Kind  |
9468               Private_Kind     |
9469               Task_Kind        |
9470               Protected_Kind   =>
9471             Copy_Node (Priv, Full);
9472
9473             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
9474             Set_First_Entity       (Full, First_Entity (Full_Base));
9475             Set_Last_Entity        (Full, Last_Entity (Full_Base));
9476
9477          when others =>
9478             Copy_Node (Full_Base, Full);
9479             Set_Chars          (Full, Chars (Priv));
9480             Conditional_Delay  (Full, Priv);
9481             Set_Sloc           (Full, Sloc (Priv));
9482       end case;
9483
9484       Set_Next_Entity (Full, Save_Next_Entity);
9485       Set_Homonym     (Full, Save_Homonym);
9486       Set_Associated_Node_For_Itype (Full, Related_Nod);
9487
9488       --  Set common attributes for all subtypes
9489
9490       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
9491
9492       --  The Etype of the full view is inconsistent. Gigi needs to see the
9493       --  structural full view,  which is what the current scheme gives:
9494       --  the Etype of the full view is the etype of the full base. However,
9495       --  if the full base is a derived type, the full view then looks like
9496       --  a subtype of the parent, not a subtype of the full base. If instead
9497       --  we write:
9498
9499       --       Set_Etype (Full, Full_Base);
9500
9501       --  then we get inconsistencies in the front-end (confusion between
9502       --  views). Several outstanding bugs are related to this ???
9503
9504       Set_Is_First_Subtype (Full, False);
9505       Set_Scope            (Full, Scope (Priv));
9506       Set_Size_Info        (Full, Full_Base);
9507       Set_RM_Size          (Full, RM_Size (Full_Base));
9508       Set_Is_Itype         (Full);
9509
9510       --  A subtype of a private-type-without-discriminants, whose full-view
9511       --  has discriminants with default expressions, is not constrained!
9512
9513       if not Has_Discriminants (Priv) then
9514          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
9515
9516          if Has_Discriminants (Full_Base) then
9517             Set_Discriminant_Constraint
9518               (Full, Discriminant_Constraint (Full_Base));
9519
9520             --  The partial view may have been indefinite, the full view
9521             --  might not be.
9522
9523             Set_Has_Unknown_Discriminants
9524               (Full, Has_Unknown_Discriminants (Full_Base));
9525          end if;
9526       end if;
9527
9528       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
9529       Set_Depends_On_Private (Full, Has_Private_Component (Full));
9530
9531       --  Freeze the private subtype entity if its parent is delayed, and not
9532       --  already frozen. We skip this processing if the type is an anonymous
9533       --  subtype of a record component, or is the corresponding record of a
9534       --  protected type, since ???
9535
9536       if not Is_Type (Scope (Full)) then
9537          Set_Has_Delayed_Freeze (Full,
9538            Has_Delayed_Freeze (Full_Base)
9539              and then (not Is_Frozen (Full_Base)));
9540       end if;
9541
9542       Set_Freeze_Node (Full, Empty);
9543       Set_Is_Frozen (Full, False);
9544       Set_Full_View (Priv, Full);
9545
9546       if Has_Discriminants (Full) then
9547          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
9548          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
9549
9550          if Has_Unknown_Discriminants (Full) then
9551             Set_Discriminant_Constraint (Full, No_Elist);
9552          end if;
9553       end if;
9554
9555       if Ekind (Full_Base) = E_Record_Type
9556         and then Has_Discriminants (Full_Base)
9557         and then Has_Discriminants (Priv) -- might not, if errors
9558         and then not Has_Unknown_Discriminants (Priv)
9559         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
9560       then
9561          Create_Constrained_Components
9562            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
9563
9564       --  If the full base is itself derived from private, build a congruent
9565       --  subtype of its underlying type, for use by the back end. For a
9566       --  constrained record component, the declaration cannot be placed on
9567       --  the component list, but it must nevertheless be built an analyzed, to
9568       --  supply enough information for Gigi to compute the size of component.
9569
9570       elsif Ekind (Full_Base) in Private_Kind
9571         and then Is_Derived_Type (Full_Base)
9572         and then Has_Discriminants (Full_Base)
9573         and then (Ekind (Current_Scope) /= E_Record_Subtype)
9574       then
9575          if not Is_Itype (Priv)
9576            and then
9577              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
9578          then
9579             Build_Underlying_Full_View
9580               (Parent (Priv), Full, Etype (Full_Base));
9581
9582          elsif Nkind (Related_Nod) = N_Component_Declaration then
9583             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
9584          end if;
9585
9586       elsif Is_Record_Type (Full_Base) then
9587
9588          --  Show Full is simply a renaming of Full_Base
9589
9590          Set_Cloned_Subtype (Full, Full_Base);
9591       end if;
9592
9593       --  It is unsafe to share to bounds of a scalar type, because the Itype
9594       --  is elaborated on demand, and if a bound is non-static then different
9595       --  orders of elaboration in different units will lead to different
9596       --  external symbols.
9597
9598       if Is_Scalar_Type (Full_Base) then
9599          Set_Scalar_Range (Full,
9600            Make_Range (Sloc (Related_Nod),
9601              Low_Bound  =>
9602                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
9603              High_Bound =>
9604                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
9605
9606          --  This completion inherits the bounds of the full parent, but if
9607          --  the parent is an unconstrained floating point type, so is the
9608          --  completion.
9609
9610          if Is_Floating_Point_Type (Full_Base) then
9611             Set_Includes_Infinities
9612              (Scalar_Range (Full), Has_Infinities (Full_Base));
9613          end if;
9614       end if;
9615
9616       --  ??? It seems that a lot of fields are missing that should be copied
9617       --  from Full_Base to Full. Here are some that are introduced in a
9618       --  non-disruptive way but a cleanup is necessary.
9619
9620       if Is_Tagged_Type (Full_Base) then
9621          Set_Is_Tagged_Type (Full);
9622          Set_Primitive_Operations (Full, Primitive_Operations (Full_Base));
9623
9624          --  Inherit class_wide type of full_base in case the partial view was
9625          --  not tagged. Otherwise it has already been created when the private
9626          --  subtype was analyzed.
9627
9628          if No (Class_Wide_Type (Full)) then
9629             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
9630          end if;
9631
9632       --  If this is a subtype of a protected or task type, constrain its
9633       --  corresponding record, unless this is a subtype without constraints,
9634       --  i.e. a simple renaming as with an actual subtype in an instance.
9635
9636       elsif Is_Concurrent_Type (Full_Base) then
9637          if Has_Discriminants (Full)
9638            and then Present (Corresponding_Record_Type (Full_Base))
9639            and then
9640              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
9641          then
9642             Set_Corresponding_Record_Type (Full,
9643               Constrain_Corresponding_Record
9644                 (Full, Corresponding_Record_Type (Full_Base),
9645                   Related_Nod, Full_Base));
9646
9647          else
9648             Set_Corresponding_Record_Type (Full,
9649               Corresponding_Record_Type (Full_Base));
9650          end if;
9651       end if;
9652    end Complete_Private_Subtype;
9653
9654    ----------------------------
9655    -- Constant_Redeclaration --
9656    ----------------------------
9657
9658    procedure Constant_Redeclaration
9659      (Id : Entity_Id;
9660       N  : Node_Id;
9661       T  : out Entity_Id)
9662    is
9663       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
9664       Obj_Def : constant Node_Id := Object_Definition (N);
9665       New_T   : Entity_Id;
9666
9667       procedure Check_Possible_Deferred_Completion
9668         (Prev_Id      : Entity_Id;
9669          Prev_Obj_Def : Node_Id;
9670          Curr_Obj_Def : Node_Id);
9671       --  Determine whether the two object definitions describe the partial
9672       --  and the full view of a constrained deferred constant. Generate
9673       --  a subtype for the full view and verify that it statically matches
9674       --  the subtype of the partial view.
9675
9676       procedure Check_Recursive_Declaration (Typ : Entity_Id);
9677       --  If deferred constant is an access type initialized with an allocator,
9678       --  check whether there is an illegal recursion in the definition,
9679       --  through a default value of some record subcomponent. This is normally
9680       --  detected when generating init procs, but requires this additional
9681       --  mechanism when expansion is disabled.
9682
9683       ----------------------------------------
9684       -- Check_Possible_Deferred_Completion --
9685       ----------------------------------------
9686
9687       procedure Check_Possible_Deferred_Completion
9688         (Prev_Id      : Entity_Id;
9689          Prev_Obj_Def : Node_Id;
9690          Curr_Obj_Def : Node_Id)
9691       is
9692       begin
9693          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
9694            and then Present (Constraint (Prev_Obj_Def))
9695            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
9696            and then Present (Constraint (Curr_Obj_Def))
9697          then
9698             declare
9699                Loc    : constant Source_Ptr := Sloc (N);
9700                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
9701                Decl   : constant Node_Id    :=
9702                           Make_Subtype_Declaration (Loc,
9703                             Defining_Identifier => Def_Id,
9704                             Subtype_Indication  =>
9705                               Relocate_Node (Curr_Obj_Def));
9706
9707             begin
9708                Insert_Before_And_Analyze (N, Decl);
9709                Set_Etype (Id, Def_Id);
9710
9711                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
9712                   Error_Msg_Sloc := Sloc (Prev_Id);
9713                   Error_Msg_N ("subtype does not statically match deferred " &
9714                                "declaration#", N);
9715                end if;
9716             end;
9717          end if;
9718       end Check_Possible_Deferred_Completion;
9719
9720       ---------------------------------
9721       -- Check_Recursive_Declaration --
9722       ---------------------------------
9723
9724       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
9725          Comp : Entity_Id;
9726
9727       begin
9728          if Is_Record_Type (Typ) then
9729             Comp := First_Component (Typ);
9730             while Present (Comp) loop
9731                if Comes_From_Source (Comp) then
9732                   if Present (Expression (Parent (Comp)))
9733                     and then Is_Entity_Name (Expression (Parent (Comp)))
9734                     and then Entity (Expression (Parent (Comp))) = Prev
9735                   then
9736                      Error_Msg_Sloc := Sloc (Parent (Comp));
9737                      Error_Msg_NE
9738                        ("illegal circularity with declaration for&#",
9739                          N, Comp);
9740                      return;
9741
9742                   elsif Is_Record_Type (Etype (Comp)) then
9743                      Check_Recursive_Declaration (Etype (Comp));
9744                   end if;
9745                end if;
9746
9747                Next_Component (Comp);
9748             end loop;
9749          end if;
9750       end Check_Recursive_Declaration;
9751
9752    --  Start of processing for Constant_Redeclaration
9753
9754    begin
9755       if Nkind (Parent (Prev)) = N_Object_Declaration then
9756          if Nkind (Object_Definition
9757                      (Parent (Prev))) = N_Subtype_Indication
9758          then
9759             --  Find type of new declaration. The constraints of the two
9760             --  views must match statically, but there is no point in
9761             --  creating an itype for the full view.
9762
9763             if Nkind (Obj_Def) = N_Subtype_Indication then
9764                Find_Type (Subtype_Mark (Obj_Def));
9765                New_T := Entity (Subtype_Mark (Obj_Def));
9766
9767             else
9768                Find_Type (Obj_Def);
9769                New_T := Entity (Obj_Def);
9770             end if;
9771
9772             T := Etype (Prev);
9773
9774          else
9775             --  The full view may impose a constraint, even if the partial
9776             --  view does not, so construct the subtype.
9777
9778             New_T := Find_Type_Of_Object (Obj_Def, N);
9779             T     := New_T;
9780          end if;
9781
9782       else
9783          --  Current declaration is illegal, diagnosed below in Enter_Name
9784
9785          T := Empty;
9786          New_T := Any_Type;
9787       end if;
9788
9789       --  If previous full declaration or a renaming declaration exists, or if
9790       --  a homograph is present, let Enter_Name handle it, either with an
9791       --  error or with the removal of an overridden implicit subprogram.
9792
9793       if Ekind (Prev) /= E_Constant
9794         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
9795         or else Present (Expression (Parent (Prev)))
9796         or else Present (Full_View (Prev))
9797       then
9798          Enter_Name (Id);
9799
9800       --  Verify that types of both declarations match, or else that both types
9801       --  are anonymous access types whose designated subtypes statically match
9802       --  (as allowed in Ada 2005 by AI-385).
9803
9804       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
9805         and then
9806           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
9807              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
9808              or else Is_Access_Constant (Etype (New_T)) /=
9809                      Is_Access_Constant (Etype (Prev))
9810              or else Can_Never_Be_Null (Etype (New_T)) /=
9811                      Can_Never_Be_Null (Etype (Prev))
9812              or else Null_Exclusion_Present (Parent (Prev)) /=
9813                      Null_Exclusion_Present (Parent (Id))
9814              or else not Subtypes_Statically_Match
9815                            (Designated_Type (Etype (Prev)),
9816                             Designated_Type (Etype (New_T))))
9817       then
9818          Error_Msg_Sloc := Sloc (Prev);
9819          Error_Msg_N ("type does not match declaration#", N);
9820          Set_Full_View (Prev, Id);
9821          Set_Etype (Id, Any_Type);
9822
9823       elsif
9824         Null_Exclusion_Present (Parent (Prev))
9825           and then not Null_Exclusion_Present (N)
9826       then
9827          Error_Msg_Sloc := Sloc (Prev);
9828          Error_Msg_N ("null-exclusion does not match declaration#", N);
9829          Set_Full_View (Prev, Id);
9830          Set_Etype (Id, Any_Type);
9831
9832       --  If so, process the full constant declaration
9833
9834       else
9835          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
9836          --  the deferred declaration is constrained, then the subtype defined
9837          --  by the subtype_indication in the full declaration shall match it
9838          --  statically.
9839
9840          Check_Possible_Deferred_Completion
9841            (Prev_Id      => Prev,
9842             Prev_Obj_Def => Object_Definition (Parent (Prev)),
9843             Curr_Obj_Def => Obj_Def);
9844
9845          Set_Full_View (Prev, Id);
9846          Set_Is_Public (Id, Is_Public (Prev));
9847          Set_Is_Internal (Id);
9848          Append_Entity (Id, Current_Scope);
9849
9850          --  Check ALIASED present if present before (RM 7.4(7))
9851
9852          if Is_Aliased (Prev)
9853            and then not Aliased_Present (N)
9854          then
9855             Error_Msg_Sloc := Sloc (Prev);
9856             Error_Msg_N ("ALIASED required (see declaration#)", N);
9857          end if;
9858
9859          --  Check that placement is in private part and that the incomplete
9860          --  declaration appeared in the visible part.
9861
9862          if Ekind (Current_Scope) = E_Package
9863            and then not In_Private_Part (Current_Scope)
9864          then
9865             Error_Msg_Sloc := Sloc (Prev);
9866             Error_Msg_N
9867               ("full constant for declaration#"
9868                & " must be in private part", N);
9869
9870          elsif Ekind (Current_Scope) = E_Package
9871            and then
9872              List_Containing (Parent (Prev)) /=
9873                Visible_Declarations
9874                  (Specification (Unit_Declaration_Node (Current_Scope)))
9875          then
9876             Error_Msg_N
9877               ("deferred constant must be declared in visible part",
9878                  Parent (Prev));
9879          end if;
9880
9881          if Is_Access_Type (T)
9882            and then Nkind (Expression (N)) = N_Allocator
9883          then
9884             Check_Recursive_Declaration (Designated_Type (T));
9885          end if;
9886       end if;
9887    end Constant_Redeclaration;
9888
9889    ----------------------
9890    -- Constrain_Access --
9891    ----------------------
9892
9893    procedure Constrain_Access
9894      (Def_Id      : in out Entity_Id;
9895       S           : Node_Id;
9896       Related_Nod : Node_Id)
9897    is
9898       T             : constant Entity_Id := Entity (Subtype_Mark (S));
9899       Desig_Type    : constant Entity_Id := Designated_Type (T);
9900       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
9901       Constraint_OK : Boolean := True;
9902
9903       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
9904       --  Simple predicate to test for defaulted discriminants
9905       --  Shouldn't this be in sem_util???
9906
9907       ---------------------------------
9908       -- Has_Defaulted_Discriminants --
9909       ---------------------------------
9910
9911       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
9912       begin
9913          return Has_Discriminants (Typ)
9914           and then Present (First_Discriminant (Typ))
9915           and then Present
9916             (Discriminant_Default_Value (First_Discriminant (Typ)));
9917       end Has_Defaulted_Discriminants;
9918
9919    --  Start of processing for Constrain_Access
9920
9921    begin
9922       if Is_Array_Type (Desig_Type) then
9923          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
9924
9925       elsif (Is_Record_Type (Desig_Type)
9926               or else Is_Incomplete_Or_Private_Type (Desig_Type))
9927         and then not Is_Constrained (Desig_Type)
9928       then
9929          --  ??? The following code is a temporary kludge to ignore a
9930          --  discriminant constraint on access type if it is constraining
9931          --  the current record. Avoid creating the implicit subtype of the
9932          --  record we are currently compiling since right now, we cannot
9933          --  handle these. For now, just return the access type itself.
9934
9935          if Desig_Type = Current_Scope
9936            and then No (Def_Id)
9937          then
9938             Set_Ekind (Desig_Subtype, E_Record_Subtype);
9939             Def_Id := Entity (Subtype_Mark (S));
9940
9941             --  This call added to ensure that the constraint is analyzed
9942             --  (needed for a B test). Note that we still return early from
9943             --  this procedure to avoid recursive processing. ???
9944
9945             Constrain_Discriminated_Type
9946               (Desig_Subtype, S, Related_Nod, For_Access => True);
9947             return;
9948          end if;
9949
9950          if (Ekind (T) = E_General_Access_Type
9951               or else Ada_Version >= Ada_05)
9952            and then Has_Private_Declaration (Desig_Type)
9953            and then In_Open_Scopes (Scope (Desig_Type))
9954            and then Has_Discriminants (Desig_Type)
9955          then
9956             --  Enforce rule that the constraint is illegal if there is
9957             --  an unconstrained view of the designated type. This means
9958             --  that the partial view (either a private type declaration or
9959             --  a derivation from a private type) has no discriminants.
9960             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
9961             --  by ACATS B371001).
9962
9963             --  Rule updated for Ada 2005: the private type is said to have
9964             --  a constrained partial view, given that objects of the type
9965             --  can be declared. Furthermore, the rule applies to all access
9966             --  types, unlike the rule concerning default discriminants.
9967
9968             declare
9969                Pack  : constant Node_Id :=
9970                          Unit_Declaration_Node (Scope (Desig_Type));
9971                Decls : List_Id;
9972                Decl  : Node_Id;
9973
9974             begin
9975                if Nkind (Pack) = N_Package_Declaration then
9976                   Decls := Visible_Declarations (Specification (Pack));
9977                   Decl := First (Decls);
9978                   while Present (Decl) loop
9979                      if (Nkind (Decl) = N_Private_Type_Declaration
9980                           and then
9981                             Chars (Defining_Identifier (Decl)) =
9982                                                      Chars (Desig_Type))
9983
9984                        or else
9985                         (Nkind (Decl) = N_Full_Type_Declaration
9986                           and then
9987                             Chars (Defining_Identifier (Decl)) =
9988                                                      Chars (Desig_Type)
9989                           and then Is_Derived_Type (Desig_Type)
9990                           and then
9991                             Has_Private_Declaration (Etype (Desig_Type)))
9992                      then
9993                         if No (Discriminant_Specifications (Decl)) then
9994                            Error_Msg_N
9995                             ("cannot constrain general access type if " &
9996                                "designated type has constrained partial view",
9997                                 S);
9998                         end if;
9999
10000                         exit;
10001                      end if;
10002
10003                      Next (Decl);
10004                   end loop;
10005                end if;
10006             end;
10007          end if;
10008
10009          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
10010            For_Access => True);
10011
10012       elsif (Is_Task_Type (Desig_Type)
10013               or else Is_Protected_Type (Desig_Type))
10014         and then not Is_Constrained (Desig_Type)
10015       then
10016          Constrain_Concurrent
10017            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
10018
10019       else
10020          Error_Msg_N ("invalid constraint on access type", S);
10021          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
10022          Constraint_OK := False;
10023       end if;
10024
10025       if No (Def_Id) then
10026          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
10027       else
10028          Set_Ekind (Def_Id, E_Access_Subtype);
10029       end if;
10030
10031       if Constraint_OK then
10032          Set_Etype (Def_Id, Base_Type (T));
10033
10034          if Is_Private_Type (Desig_Type) then
10035             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
10036          end if;
10037       else
10038          Set_Etype (Def_Id, Any_Type);
10039       end if;
10040
10041       Set_Size_Info                (Def_Id, T);
10042       Set_Is_Constrained           (Def_Id, Constraint_OK);
10043       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
10044       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
10045       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
10046
10047       Conditional_Delay (Def_Id, T);
10048
10049       --  AI-363 : Subtypes of general access types whose designated types have
10050       --  default discriminants are disallowed. In instances, the rule has to
10051       --  be checked against the actual, of which T is the subtype. In a
10052       --  generic body, the rule is checked assuming that the actual type has
10053       --  defaulted discriminants.
10054
10055       if Ada_Version >= Ada_05 or else Warn_On_Ada_2005_Compatibility then
10056          if Ekind (Base_Type (T)) = E_General_Access_Type
10057            and then Has_Defaulted_Discriminants (Desig_Type)
10058          then
10059             if Ada_Version < Ada_05 then
10060                Error_Msg_N
10061                  ("access subtype of general access type would not " &
10062                   "be allowed in Ada 2005?", S);
10063             else
10064                Error_Msg_N
10065                  ("access subype of general access type not allowed", S);
10066             end if;
10067
10068             Error_Msg_N ("\discriminants have defaults", S);
10069
10070          elsif Is_Access_Type (T)
10071            and then Is_Generic_Type (Desig_Type)
10072            and then Has_Discriminants (Desig_Type)
10073            and then In_Package_Body (Current_Scope)
10074          then
10075             if Ada_Version < Ada_05 then
10076                Error_Msg_N
10077                  ("access subtype would not be allowed in generic body " &
10078                   "in Ada 2005?", S);
10079             else
10080                Error_Msg_N
10081                  ("access subtype not allowed in generic body", S);
10082             end if;
10083
10084             Error_Msg_N
10085               ("\designated type is a discriminated formal", S);
10086          end if;
10087       end if;
10088    end Constrain_Access;
10089
10090    ---------------------
10091    -- Constrain_Array --
10092    ---------------------
10093
10094    procedure Constrain_Array
10095      (Def_Id      : in out Entity_Id;
10096       SI          : Node_Id;
10097       Related_Nod : Node_Id;
10098       Related_Id  : Entity_Id;
10099       Suffix      : Character)
10100    is
10101       C                     : constant Node_Id := Constraint (SI);
10102       Number_Of_Constraints : Nat := 0;
10103       Index                 : Node_Id;
10104       S, T                  : Entity_Id;
10105       Constraint_OK         : Boolean := True;
10106
10107    begin
10108       T := Entity (Subtype_Mark (SI));
10109
10110       if Ekind (T) in Access_Kind then
10111          T := Designated_Type (T);
10112       end if;
10113
10114       --  If an index constraint follows a subtype mark in a subtype indication
10115       --  then the type or subtype denoted by the subtype mark must not already
10116       --  impose an index constraint. The subtype mark must denote either an
10117       --  unconstrained array type or an access type whose designated type
10118       --  is such an array type... (RM 3.6.1)
10119
10120       if Is_Constrained (T) then
10121          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
10122          Constraint_OK := False;
10123
10124       else
10125          S := First (Constraints (C));
10126          while Present (S) loop
10127             Number_Of_Constraints := Number_Of_Constraints + 1;
10128             Next (S);
10129          end loop;
10130
10131          --  In either case, the index constraint must provide a discrete
10132          --  range for each index of the array type and the type of each
10133          --  discrete range must be the same as that of the corresponding
10134          --  index. (RM 3.6.1)
10135
10136          if Number_Of_Constraints /= Number_Dimensions (T) then
10137             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
10138             Constraint_OK := False;
10139
10140          else
10141             S := First (Constraints (C));
10142             Index := First_Index (T);
10143             Analyze (Index);
10144
10145             --  Apply constraints to each index type
10146
10147             for J in 1 .. Number_Of_Constraints loop
10148                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
10149                Next (Index);
10150                Next (S);
10151             end loop;
10152
10153          end if;
10154       end if;
10155
10156       if No (Def_Id) then
10157          Def_Id :=
10158            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
10159          Set_Parent (Def_Id, Related_Nod);
10160
10161       else
10162          Set_Ekind (Def_Id, E_Array_Subtype);
10163       end if;
10164
10165       Set_Size_Info      (Def_Id,                (T));
10166       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10167       Set_Etype          (Def_Id, Base_Type      (T));
10168
10169       if Constraint_OK then
10170          Set_First_Index (Def_Id, First (Constraints (C)));
10171       else
10172          Set_First_Index (Def_Id, First_Index (T));
10173       end if;
10174
10175       Set_Is_Constrained     (Def_Id, True);
10176       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
10177       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10178
10179       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
10180       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
10181
10182       --  A subtype does not inherit the packed_array_type of is parent. We
10183       --  need to initialize the attribute because if Def_Id is previously
10184       --  analyzed through a limited_with clause, it will have the attributes
10185       --  of an incomplete type, one of which is an Elist that overlaps the
10186       --  Packed_Array_Type field.
10187
10188       Set_Packed_Array_Type (Def_Id, Empty);
10189
10190       --  Build a freeze node if parent still needs one. Also make sure that
10191       --  the Depends_On_Private status is set because the subtype will need
10192       --  reprocessing at the time the base type does, and also we must set a
10193       --  conditional delay.
10194
10195       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
10196       Conditional_Delay (Def_Id, T);
10197    end Constrain_Array;
10198
10199    ------------------------------
10200    -- Constrain_Component_Type --
10201    ------------------------------
10202
10203    function Constrain_Component_Type
10204      (Comp            : Entity_Id;
10205       Constrained_Typ : Entity_Id;
10206       Related_Node    : Node_Id;
10207       Typ             : Entity_Id;
10208       Constraints     : Elist_Id) return Entity_Id
10209    is
10210       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
10211       Compon_Type : constant Entity_Id := Etype (Comp);
10212
10213       function Build_Constrained_Array_Type
10214         (Old_Type : Entity_Id) return Entity_Id;
10215       --  If Old_Type is an array type, one of whose indices is constrained
10216       --  by a discriminant, build an Itype whose constraint replaces the
10217       --  discriminant with its value in the constraint.
10218
10219       function Build_Constrained_Discriminated_Type
10220         (Old_Type : Entity_Id) return Entity_Id;
10221       --  Ditto for record components
10222
10223       function Build_Constrained_Access_Type
10224         (Old_Type : Entity_Id) return Entity_Id;
10225       --  Ditto for access types. Makes use of previous two functions, to
10226       --  constrain designated type.
10227
10228       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
10229       --  T is an array or discriminated type, C is a list of constraints
10230       --  that apply to T. This routine builds the constrained subtype.
10231
10232       function Is_Discriminant (Expr : Node_Id) return Boolean;
10233       --  Returns True if Expr is a discriminant
10234
10235       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
10236       --  Find the value of discriminant Discrim in Constraint
10237
10238       -----------------------------------
10239       -- Build_Constrained_Access_Type --
10240       -----------------------------------
10241
10242       function Build_Constrained_Access_Type
10243         (Old_Type : Entity_Id) return Entity_Id
10244       is
10245          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
10246          Itype         : Entity_Id;
10247          Desig_Subtype : Entity_Id;
10248          Scop          : Entity_Id;
10249
10250       begin
10251          --  if the original access type was not embedded in the enclosing
10252          --  type definition, there is no need to produce a new access
10253          --  subtype. In fact every access type with an explicit constraint
10254          --  generates an itype whose scope is the enclosing record.
10255
10256          if not Is_Type (Scope (Old_Type)) then
10257             return Old_Type;
10258
10259          elsif Is_Array_Type (Desig_Type) then
10260             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
10261
10262          elsif Has_Discriminants (Desig_Type) then
10263
10264             --  This may be an access type to an enclosing record type for
10265             --  which we are constructing the constrained components. Return
10266             --  the enclosing record subtype. This is not always correct,
10267             --  but avoids infinite recursion. ???
10268
10269             Desig_Subtype := Any_Type;
10270
10271             for J in reverse 0 .. Scope_Stack.Last loop
10272                Scop := Scope_Stack.Table (J).Entity;
10273
10274                if Is_Type (Scop)
10275                  and then Base_Type (Scop) = Base_Type (Desig_Type)
10276                then
10277                   Desig_Subtype := Scop;
10278                end if;
10279
10280                exit when not Is_Type (Scop);
10281             end loop;
10282
10283             if Desig_Subtype = Any_Type then
10284                Desig_Subtype :=
10285                  Build_Constrained_Discriminated_Type (Desig_Type);
10286             end if;
10287
10288          else
10289             return Old_Type;
10290          end if;
10291
10292          if Desig_Subtype /= Desig_Type then
10293
10294             --  The Related_Node better be here or else we won't be able
10295             --  to attach new itypes to a node in the tree.
10296
10297             pragma Assert (Present (Related_Node));
10298
10299             Itype := Create_Itype (E_Access_Subtype, Related_Node);
10300
10301             Set_Etype                    (Itype, Base_Type      (Old_Type));
10302             Set_Size_Info                (Itype,                (Old_Type));
10303             Set_Directly_Designated_Type (Itype, Desig_Subtype);
10304             Set_Depends_On_Private       (Itype, Has_Private_Component
10305                                                                 (Old_Type));
10306             Set_Is_Access_Constant       (Itype, Is_Access_Constant
10307                                                                 (Old_Type));
10308
10309             --  The new itype needs freezing when it depends on a not frozen
10310             --  type and the enclosing subtype needs freezing.
10311
10312             if Has_Delayed_Freeze (Constrained_Typ)
10313               and then not Is_Frozen (Constrained_Typ)
10314             then
10315                Conditional_Delay (Itype, Base_Type (Old_Type));
10316             end if;
10317
10318             return Itype;
10319
10320          else
10321             return Old_Type;
10322          end if;
10323       end Build_Constrained_Access_Type;
10324
10325       ----------------------------------
10326       -- Build_Constrained_Array_Type --
10327       ----------------------------------
10328
10329       function Build_Constrained_Array_Type
10330         (Old_Type : Entity_Id) return Entity_Id
10331       is
10332          Lo_Expr     : Node_Id;
10333          Hi_Expr     : Node_Id;
10334          Old_Index   : Node_Id;
10335          Range_Node  : Node_Id;
10336          Constr_List : List_Id;
10337
10338          Need_To_Create_Itype : Boolean := False;
10339
10340       begin
10341          Old_Index := First_Index (Old_Type);
10342          while Present (Old_Index) loop
10343             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10344
10345             if Is_Discriminant (Lo_Expr)
10346               or else Is_Discriminant (Hi_Expr)
10347             then
10348                Need_To_Create_Itype := True;
10349             end if;
10350
10351             Next_Index (Old_Index);
10352          end loop;
10353
10354          if Need_To_Create_Itype then
10355             Constr_List := New_List;
10356
10357             Old_Index := First_Index (Old_Type);
10358             while Present (Old_Index) loop
10359                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10360
10361                if Is_Discriminant (Lo_Expr) then
10362                   Lo_Expr := Get_Discr_Value (Lo_Expr);
10363                end if;
10364
10365                if Is_Discriminant (Hi_Expr) then
10366                   Hi_Expr := Get_Discr_Value (Hi_Expr);
10367                end if;
10368
10369                Range_Node :=
10370                  Make_Range
10371                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
10372
10373                Append (Range_Node, To => Constr_List);
10374
10375                Next_Index (Old_Index);
10376             end loop;
10377
10378             return Build_Subtype (Old_Type, Constr_List);
10379
10380          else
10381             return Old_Type;
10382          end if;
10383       end Build_Constrained_Array_Type;
10384
10385       ------------------------------------------
10386       -- Build_Constrained_Discriminated_Type --
10387       ------------------------------------------
10388
10389       function Build_Constrained_Discriminated_Type
10390         (Old_Type : Entity_Id) return Entity_Id
10391       is
10392          Expr           : Node_Id;
10393          Constr_List    : List_Id;
10394          Old_Constraint : Elmt_Id;
10395
10396          Need_To_Create_Itype : Boolean := False;
10397
10398       begin
10399          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10400          while Present (Old_Constraint) loop
10401             Expr := Node (Old_Constraint);
10402
10403             if Is_Discriminant (Expr) then
10404                Need_To_Create_Itype := True;
10405             end if;
10406
10407             Next_Elmt (Old_Constraint);
10408          end loop;
10409
10410          if Need_To_Create_Itype then
10411             Constr_List := New_List;
10412
10413             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10414             while Present (Old_Constraint) loop
10415                Expr := Node (Old_Constraint);
10416
10417                if Is_Discriminant (Expr) then
10418                   Expr := Get_Discr_Value (Expr);
10419                end if;
10420
10421                Append (New_Copy_Tree (Expr), To => Constr_List);
10422
10423                Next_Elmt (Old_Constraint);
10424             end loop;
10425
10426             return Build_Subtype (Old_Type, Constr_List);
10427
10428          else
10429             return Old_Type;
10430          end if;
10431       end Build_Constrained_Discriminated_Type;
10432
10433       -------------------
10434       -- Build_Subtype --
10435       -------------------
10436
10437       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
10438          Indic       : Node_Id;
10439          Subtyp_Decl : Node_Id;
10440          Def_Id      : Entity_Id;
10441          Btyp        : Entity_Id := Base_Type (T);
10442
10443       begin
10444          --  The Related_Node better be here or else we won't be able to
10445          --  attach new itypes to a node in the tree.
10446
10447          pragma Assert (Present (Related_Node));
10448
10449          --  If the view of the component's type is incomplete or private
10450          --  with unknown discriminants, then the constraint must be applied
10451          --  to the full type.
10452
10453          if Has_Unknown_Discriminants (Btyp)
10454            and then Present (Underlying_Type (Btyp))
10455          then
10456             Btyp := Underlying_Type (Btyp);
10457          end if;
10458
10459          Indic :=
10460            Make_Subtype_Indication (Loc,
10461              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
10462              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
10463
10464          Def_Id := Create_Itype (Ekind (T), Related_Node);
10465
10466          Subtyp_Decl :=
10467            Make_Subtype_Declaration (Loc,
10468              Defining_Identifier => Def_Id,
10469              Subtype_Indication  => Indic);
10470
10471          Set_Parent (Subtyp_Decl, Parent (Related_Node));
10472
10473          --  Itypes must be analyzed with checks off (see package Itypes)
10474
10475          Analyze (Subtyp_Decl, Suppress => All_Checks);
10476
10477          return Def_Id;
10478       end Build_Subtype;
10479
10480       ---------------------
10481       -- Get_Discr_Value --
10482       ---------------------
10483
10484       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
10485          D : Entity_Id;
10486          E : Elmt_Id;
10487
10488       begin
10489          --  The discriminant may be declared for the type, in which case we
10490          --  find it by iterating over the list of discriminants. If the
10491          --  discriminant is inherited from a parent type, it appears as the
10492          --  corresponding discriminant of the current type. This will be the
10493          --  case when constraining an inherited component whose constraint is
10494          --  given by a discriminant of the parent.
10495
10496          D := First_Discriminant (Typ);
10497          E := First_Elmt (Constraints);
10498
10499          while Present (D) loop
10500             if D = Entity (Discrim)
10501               or else D = CR_Discriminant (Entity (Discrim))
10502               or else Corresponding_Discriminant (D) = Entity (Discrim)
10503             then
10504                return Node (E);
10505             end if;
10506
10507             Next_Discriminant (D);
10508             Next_Elmt (E);
10509          end loop;
10510
10511          --  The corresponding_Discriminant mechanism is incomplete, because
10512          --  the correspondence between new and old discriminants is not one
10513          --  to one: one new discriminant can constrain several old ones. In
10514          --  that case, scan sequentially the stored_constraint, the list of
10515          --  discriminants of the parents, and the constraints.
10516          --  Previous code checked for the present of the Stored_Constraint
10517          --  list for the derived type, but did not use it at all. Should it
10518          --  be present when the component is a discriminated task type?
10519
10520          if Is_Derived_Type (Typ)
10521            and then Scope (Entity (Discrim)) = Etype (Typ)
10522          then
10523             D := First_Discriminant (Etype (Typ));
10524             E := First_Elmt (Constraints);
10525             while Present (D) loop
10526                if D = Entity (Discrim) then
10527                   return Node (E);
10528                end if;
10529
10530                Next_Discriminant (D);
10531                Next_Elmt (E);
10532             end loop;
10533          end if;
10534
10535          --  Something is wrong if we did not find the value
10536
10537          raise Program_Error;
10538       end Get_Discr_Value;
10539
10540       ---------------------
10541       -- Is_Discriminant --
10542       ---------------------
10543
10544       function Is_Discriminant (Expr : Node_Id) return Boolean is
10545          Discrim_Scope : Entity_Id;
10546
10547       begin
10548          if Denotes_Discriminant (Expr) then
10549             Discrim_Scope := Scope (Entity (Expr));
10550
10551             --  Either we have a reference to one of Typ's discriminants,
10552
10553             pragma Assert (Discrim_Scope = Typ
10554
10555                --  or to the discriminants of the parent type, in the case
10556                --  of a derivation of a tagged type with variants.
10557
10558                or else Discrim_Scope = Etype (Typ)
10559                or else Full_View (Discrim_Scope) = Etype (Typ)
10560
10561                --  or same as above for the case where the discriminants
10562                --  were declared in Typ's private view.
10563
10564                or else (Is_Private_Type (Discrim_Scope)
10565                         and then Chars (Discrim_Scope) = Chars (Typ))
10566
10567                --  or else we are deriving from the full view and the
10568                --  discriminant is declared in the private entity.
10569
10570                or else (Is_Private_Type (Typ)
10571                          and then Chars (Discrim_Scope) = Chars (Typ))
10572
10573                --  Or we are constrained the corresponding record of a
10574                --  synchronized type that completes a private declaration.
10575
10576                or else (Is_Concurrent_Record_Type (Typ)
10577                          and then
10578                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
10579
10580                --  or we have a class-wide type, in which case make sure the
10581                --  discriminant found belongs to the root type.
10582
10583                or else (Is_Class_Wide_Type (Typ)
10584                          and then Etype (Typ) = Discrim_Scope));
10585
10586             return True;
10587          end if;
10588
10589          --  In all other cases we have something wrong
10590
10591          return False;
10592       end Is_Discriminant;
10593
10594    --  Start of processing for Constrain_Component_Type
10595
10596    begin
10597       if Nkind (Parent (Comp)) = N_Component_Declaration
10598         and then Comes_From_Source (Parent (Comp))
10599         and then Comes_From_Source
10600           (Subtype_Indication (Component_Definition (Parent (Comp))))
10601         and then
10602           Is_Entity_Name
10603             (Subtype_Indication (Component_Definition (Parent (Comp))))
10604       then
10605          return Compon_Type;
10606
10607       elsif Is_Array_Type (Compon_Type) then
10608          return Build_Constrained_Array_Type (Compon_Type);
10609
10610       elsif Has_Discriminants (Compon_Type) then
10611          return Build_Constrained_Discriminated_Type (Compon_Type);
10612
10613       elsif Is_Access_Type (Compon_Type) then
10614          return Build_Constrained_Access_Type (Compon_Type);
10615
10616       else
10617          return Compon_Type;
10618       end if;
10619    end Constrain_Component_Type;
10620
10621    --------------------------
10622    -- Constrain_Concurrent --
10623    --------------------------
10624
10625    --  For concurrent types, the associated record value type carries the same
10626    --  discriminants, so when we constrain a concurrent type, we must constrain
10627    --  the corresponding record type as well.
10628
10629    procedure Constrain_Concurrent
10630      (Def_Id      : in out Entity_Id;
10631       SI          : Node_Id;
10632       Related_Nod : Node_Id;
10633       Related_Id  : Entity_Id;
10634       Suffix      : Character)
10635    is
10636       T_Ent : Entity_Id := Entity (Subtype_Mark (SI));
10637       T_Val : Entity_Id;
10638
10639    begin
10640       if Ekind (T_Ent) in Access_Kind then
10641          T_Ent := Designated_Type (T_Ent);
10642       end if;
10643
10644       T_Val := Corresponding_Record_Type (T_Ent);
10645
10646       if Present (T_Val) then
10647
10648          if No (Def_Id) then
10649             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
10650          end if;
10651
10652          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
10653
10654          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10655          Set_Corresponding_Record_Type (Def_Id,
10656            Constrain_Corresponding_Record
10657              (Def_Id, T_Val, Related_Nod, Related_Id));
10658
10659       else
10660          --  If there is no associated record, expansion is disabled and this
10661          --  is a generic context. Create a subtype in any case, so that
10662          --  semantic analysis can proceed.
10663
10664          if No (Def_Id) then
10665             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
10666          end if;
10667
10668          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
10669       end if;
10670    end Constrain_Concurrent;
10671
10672    ------------------------------------
10673    -- Constrain_Corresponding_Record --
10674    ------------------------------------
10675
10676    function Constrain_Corresponding_Record
10677      (Prot_Subt   : Entity_Id;
10678       Corr_Rec    : Entity_Id;
10679       Related_Nod : Node_Id;
10680       Related_Id  : Entity_Id) return Entity_Id
10681    is
10682       T_Sub : constant Entity_Id :=
10683                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
10684
10685    begin
10686       Set_Etype             (T_Sub, Corr_Rec);
10687       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
10688       Set_Is_Constrained    (T_Sub, True);
10689       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
10690       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
10691
10692       --  As elsewhere, we do not want to create a freeze node for this itype
10693       --  if it is created for a constrained component of an enclosing record
10694       --  because references to outer discriminants will appear out of scope.
10695
10696       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
10697          Conditional_Delay (T_Sub, Corr_Rec);
10698       else
10699          Set_Is_Frozen (T_Sub);
10700       end if;
10701
10702       if Has_Discriminants (Prot_Subt) then -- False only if errors.
10703          Set_Discriminant_Constraint
10704            (T_Sub, Discriminant_Constraint (Prot_Subt));
10705          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
10706          Create_Constrained_Components
10707            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
10708       end if;
10709
10710       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
10711
10712       return T_Sub;
10713    end Constrain_Corresponding_Record;
10714
10715    -----------------------
10716    -- Constrain_Decimal --
10717    -----------------------
10718
10719    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
10720       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
10721       C           : constant Node_Id    := Constraint (S);
10722       Loc         : constant Source_Ptr := Sloc (C);
10723       Range_Expr  : Node_Id;
10724       Digits_Expr : Node_Id;
10725       Digits_Val  : Uint;
10726       Bound_Val   : Ureal;
10727
10728    begin
10729       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
10730
10731       if Nkind (C) = N_Range_Constraint then
10732          Range_Expr := Range_Expression (C);
10733          Digits_Val := Digits_Value (T);
10734
10735       else
10736          pragma Assert (Nkind (C) = N_Digits_Constraint);
10737          Digits_Expr := Digits_Expression (C);
10738          Analyze_And_Resolve (Digits_Expr, Any_Integer);
10739
10740          Check_Digits_Expression (Digits_Expr);
10741          Digits_Val := Expr_Value (Digits_Expr);
10742
10743          if Digits_Val > Digits_Value (T) then
10744             Error_Msg_N
10745                ("digits expression is incompatible with subtype", C);
10746             Digits_Val := Digits_Value (T);
10747          end if;
10748
10749          if Present (Range_Constraint (C)) then
10750             Range_Expr := Range_Expression (Range_Constraint (C));
10751          else
10752             Range_Expr := Empty;
10753          end if;
10754       end if;
10755
10756       Set_Etype            (Def_Id, Base_Type        (T));
10757       Set_Size_Info        (Def_Id,                  (T));
10758       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
10759       Set_Delta_Value      (Def_Id, Delta_Value      (T));
10760       Set_Scale_Value      (Def_Id, Scale_Value      (T));
10761       Set_Small_Value      (Def_Id, Small_Value      (T));
10762       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
10763       Set_Digits_Value     (Def_Id, Digits_Val);
10764
10765       --  Manufacture range from given digits value if no range present
10766
10767       if No (Range_Expr) then
10768          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
10769          Range_Expr :=
10770            Make_Range (Loc,
10771              Low_Bound =>
10772                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
10773              High_Bound =>
10774                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
10775       end if;
10776
10777       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
10778       Set_Discrete_RM_Size (Def_Id);
10779
10780       --  Unconditionally delay the freeze, since we cannot set size
10781       --  information in all cases correctly until the freeze point.
10782
10783       Set_Has_Delayed_Freeze (Def_Id);
10784    end Constrain_Decimal;
10785
10786    ----------------------------------
10787    -- Constrain_Discriminated_Type --
10788    ----------------------------------
10789
10790    procedure Constrain_Discriminated_Type
10791      (Def_Id      : Entity_Id;
10792       S           : Node_Id;
10793       Related_Nod : Node_Id;
10794       For_Access  : Boolean := False)
10795    is
10796       E     : constant Entity_Id := Entity (Subtype_Mark (S));
10797       T     : Entity_Id;
10798       C     : Node_Id;
10799       Elist : Elist_Id := New_Elmt_List;
10800
10801       procedure Fixup_Bad_Constraint;
10802       --  This is called after finding a bad constraint, and after having
10803       --  posted an appropriate error message. The mission is to leave the
10804       --  entity T in as reasonable state as possible!
10805
10806       --------------------------
10807       -- Fixup_Bad_Constraint --
10808       --------------------------
10809
10810       procedure Fixup_Bad_Constraint is
10811       begin
10812          --  Set a reasonable Ekind for the entity. For an incomplete type,
10813          --  we can't do much, but for other types, we can set the proper
10814          --  corresponding subtype kind.
10815
10816          if Ekind (T) = E_Incomplete_Type then
10817             Set_Ekind (Def_Id, Ekind (T));
10818          else
10819             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
10820          end if;
10821
10822          --  Set Etype to the known type, to reduce chances of cascaded errors
10823
10824          Set_Etype (Def_Id, E);
10825          Set_Error_Posted (Def_Id);
10826       end Fixup_Bad_Constraint;
10827
10828    --  Start of processing for Constrain_Discriminated_Type
10829
10830    begin
10831       C := Constraint (S);
10832
10833       --  A discriminant constraint is only allowed in a subtype indication,
10834       --  after a subtype mark. This subtype mark must denote either a type
10835       --  with discriminants, or an access type whose designated type is a
10836       --  type with discriminants. A discriminant constraint specifies the
10837       --  values of these discriminants (RM 3.7.2(5)).
10838
10839       T := Base_Type (Entity (Subtype_Mark (S)));
10840
10841       if Ekind (T) in Access_Kind then
10842          T := Designated_Type (T);
10843       end if;
10844
10845       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
10846       --  Avoid generating an error for access-to-incomplete subtypes.
10847
10848       if Ada_Version >= Ada_05
10849         and then Ekind (T) = E_Incomplete_Type
10850         and then Nkind (Parent (S)) = N_Subtype_Declaration
10851         and then not Is_Itype (Def_Id)
10852       then
10853          --  A little sanity check, emit an error message if the type
10854          --  has discriminants to begin with. Type T may be a regular
10855          --  incomplete type or imported via a limited with clause.
10856
10857          if Has_Discriminants (T)
10858            or else
10859              (From_With_Type (T)
10860                 and then Present (Non_Limited_View (T))
10861                 and then Nkind (Parent (Non_Limited_View (T))) =
10862                            N_Full_Type_Declaration
10863                 and then Present (Discriminant_Specifications
10864                           (Parent (Non_Limited_View (T)))))
10865          then
10866             Error_Msg_N
10867               ("(Ada 2005) incomplete subtype may not be constrained", C);
10868          else
10869             Error_Msg_N ("invalid constraint: type has no discriminant", C);
10870          end if;
10871
10872          Fixup_Bad_Constraint;
10873          return;
10874
10875       --  Check that the type has visible discriminants. The type may be
10876       --  a private type with unknown discriminants whose full view has
10877       --  discriminants which are invisible.
10878
10879       elsif not Has_Discriminants (T)
10880         or else
10881           (Has_Unknown_Discriminants (T)
10882              and then Is_Private_Type (T))
10883       then
10884          Error_Msg_N ("invalid constraint: type has no discriminant", C);
10885          Fixup_Bad_Constraint;
10886          return;
10887
10888       elsif Is_Constrained (E)
10889         or else (Ekind (E) = E_Class_Wide_Subtype
10890                   and then Present (Discriminant_Constraint (E)))
10891       then
10892          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
10893          Fixup_Bad_Constraint;
10894          return;
10895       end if;
10896
10897       --  T may be an unconstrained subtype (e.g. a generic actual).
10898       --  Constraint applies to the base type.
10899
10900       T := Base_Type (T);
10901
10902       Elist := Build_Discriminant_Constraints (T, S);
10903
10904       --  If the list returned was empty we had an error in building the
10905       --  discriminant constraint. We have also already signalled an error
10906       --  in the incomplete type case
10907
10908       if Is_Empty_Elmt_List (Elist) then
10909          Fixup_Bad_Constraint;
10910          return;
10911       end if;
10912
10913       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
10914    end Constrain_Discriminated_Type;
10915
10916    ---------------------------
10917    -- Constrain_Enumeration --
10918    ---------------------------
10919
10920    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
10921       T : constant Entity_Id := Entity (Subtype_Mark (S));
10922       C : constant Node_Id   := Constraint (S);
10923
10924    begin
10925       Set_Ekind (Def_Id, E_Enumeration_Subtype);
10926
10927       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
10928
10929       Set_Etype             (Def_Id, Base_Type         (T));
10930       Set_Size_Info         (Def_Id,                   (T));
10931       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
10932       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
10933
10934       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
10935
10936       Set_Discrete_RM_Size (Def_Id);
10937    end Constrain_Enumeration;
10938
10939    ----------------------
10940    -- Constrain_Float --
10941    ----------------------
10942
10943    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
10944       T    : constant Entity_Id := Entity (Subtype_Mark (S));
10945       C    : Node_Id;
10946       D    : Node_Id;
10947       Rais : Node_Id;
10948
10949    begin
10950       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
10951
10952       Set_Etype          (Def_Id, Base_Type      (T));
10953       Set_Size_Info      (Def_Id,                (T));
10954       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10955
10956       --  Process the constraint
10957
10958       C := Constraint (S);
10959
10960       --  Digits constraint present
10961
10962       if Nkind (C) = N_Digits_Constraint then
10963          Check_Restriction (No_Obsolescent_Features, C);
10964
10965          if Warn_On_Obsolescent_Feature then
10966             Error_Msg_N
10967               ("subtype digits constraint is an " &
10968                "obsolescent feature (RM J.3(8))?", C);
10969          end if;
10970
10971          D := Digits_Expression (C);
10972          Analyze_And_Resolve (D, Any_Integer);
10973          Check_Digits_Expression (D);
10974          Set_Digits_Value (Def_Id, Expr_Value (D));
10975
10976          --  Check that digits value is in range. Obviously we can do this
10977          --  at compile time, but it is strictly a runtime check, and of
10978          --  course there is an ACVC test that checks this!
10979
10980          if Digits_Value (Def_Id) > Digits_Value (T) then
10981             Error_Msg_Uint_1 := Digits_Value (T);
10982             Error_Msg_N ("?digits value is too large, maximum is ^", D);
10983             Rais :=
10984               Make_Raise_Constraint_Error (Sloc (D),
10985                 Reason => CE_Range_Check_Failed);
10986             Insert_Action (Declaration_Node (Def_Id), Rais);
10987          end if;
10988
10989          C := Range_Constraint (C);
10990
10991       --  No digits constraint present
10992
10993       else
10994          Set_Digits_Value (Def_Id, Digits_Value (T));
10995       end if;
10996
10997       --  Range constraint present
10998
10999       if Nkind (C) = N_Range_Constraint then
11000          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11001
11002       --  No range constraint present
11003
11004       else
11005          pragma Assert (No (C));
11006          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11007       end if;
11008
11009       Set_Is_Constrained (Def_Id);
11010    end Constrain_Float;
11011
11012    ---------------------
11013    -- Constrain_Index --
11014    ---------------------
11015
11016    procedure Constrain_Index
11017      (Index        : Node_Id;
11018       S            : Node_Id;
11019       Related_Nod  : Node_Id;
11020       Related_Id   : Entity_Id;
11021       Suffix       : Character;
11022       Suffix_Index : Nat)
11023    is
11024       Def_Id : Entity_Id;
11025       R      : Node_Id := Empty;
11026       T      : constant Entity_Id := Etype (Index);
11027
11028    begin
11029       if Nkind (S) = N_Range
11030         or else
11031           (Nkind (S) = N_Attribute_Reference
11032             and then Attribute_Name (S) = Name_Range)
11033       then
11034          --  A Range attribute will transformed into N_Range by Resolve
11035
11036          Analyze (S);
11037          Set_Etype (S, T);
11038          R := S;
11039
11040          Process_Range_Expr_In_Decl (R, T, Empty_List);
11041
11042          if not Error_Posted (S)
11043            and then
11044              (Nkind (S) /= N_Range
11045                or else not Covers (T, (Etype (Low_Bound (S))))
11046                or else not Covers (T, (Etype (High_Bound (S)))))
11047          then
11048             if Base_Type (T) /= Any_Type
11049               and then Etype (Low_Bound (S)) /= Any_Type
11050               and then Etype (High_Bound (S)) /= Any_Type
11051             then
11052                Error_Msg_N ("range expected", S);
11053             end if;
11054          end if;
11055
11056       elsif Nkind (S) = N_Subtype_Indication then
11057
11058          --  The parser has verified that this is a discrete indication
11059
11060          Resolve_Discrete_Subtype_Indication (S, T);
11061          R := Range_Expression (Constraint (S));
11062
11063       elsif Nkind (S) = N_Discriminant_Association then
11064
11065          --  Syntactically valid in subtype indication
11066
11067          Error_Msg_N ("invalid index constraint", S);
11068          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11069          return;
11070
11071       --  Subtype_Mark case, no anonymous subtypes to construct
11072
11073       else
11074          Analyze (S);
11075
11076          if Is_Entity_Name (S) then
11077             if not Is_Type (Entity (S)) then
11078                Error_Msg_N ("expect subtype mark for index constraint", S);
11079
11080             elsif Base_Type (Entity (S)) /= Base_Type (T) then
11081                Wrong_Type (S, Base_Type (T));
11082             end if;
11083
11084             return;
11085
11086          else
11087             Error_Msg_N ("invalid index constraint", S);
11088             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11089             return;
11090          end if;
11091       end if;
11092
11093       Def_Id :=
11094         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
11095
11096       Set_Etype (Def_Id, Base_Type (T));
11097
11098       if Is_Modular_Integer_Type (T) then
11099          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11100
11101       elsif Is_Integer_Type (T) then
11102          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11103
11104       else
11105          Set_Ekind (Def_Id, E_Enumeration_Subtype);
11106          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11107          Set_First_Literal     (Def_Id, First_Literal (T));
11108       end if;
11109
11110       Set_Size_Info      (Def_Id,                (T));
11111       Set_RM_Size        (Def_Id, RM_Size        (T));
11112       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11113
11114       Set_Scalar_Range   (Def_Id, R);
11115
11116       Set_Etype (S, Def_Id);
11117       Set_Discrete_RM_Size (Def_Id);
11118    end Constrain_Index;
11119
11120    -----------------------
11121    -- Constrain_Integer --
11122    -----------------------
11123
11124    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
11125       T : constant Entity_Id := Entity (Subtype_Mark (S));
11126       C : constant Node_Id   := Constraint (S);
11127
11128    begin
11129       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11130
11131       if Is_Modular_Integer_Type (T) then
11132          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11133       else
11134          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11135       end if;
11136
11137       Set_Etype            (Def_Id, Base_Type        (T));
11138       Set_Size_Info        (Def_Id,                  (T));
11139       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11140       Set_Discrete_RM_Size (Def_Id);
11141    end Constrain_Integer;
11142
11143    ------------------------------
11144    -- Constrain_Ordinary_Fixed --
11145    ------------------------------
11146
11147    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
11148       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11149       C    : Node_Id;
11150       D    : Node_Id;
11151       Rais : Node_Id;
11152
11153    begin
11154       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
11155       Set_Etype          (Def_Id, Base_Type        (T));
11156       Set_Size_Info      (Def_Id,                  (T));
11157       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
11158       Set_Small_Value    (Def_Id, Small_Value      (T));
11159
11160       --  Process the constraint
11161
11162       C := Constraint (S);
11163
11164       --  Delta constraint present
11165
11166       if Nkind (C) = N_Delta_Constraint then
11167          Check_Restriction (No_Obsolescent_Features, C);
11168
11169          if Warn_On_Obsolescent_Feature then
11170             Error_Msg_S
11171               ("subtype delta constraint is an " &
11172                "obsolescent feature (RM J.3(7))?");
11173          end if;
11174
11175          D := Delta_Expression (C);
11176          Analyze_And_Resolve (D, Any_Real);
11177          Check_Delta_Expression (D);
11178          Set_Delta_Value (Def_Id, Expr_Value_R (D));
11179
11180          --  Check that delta value is in range. Obviously we can do this
11181          --  at compile time, but it is strictly a runtime check, and of
11182          --  course there is an ACVC test that checks this!
11183
11184          if Delta_Value (Def_Id) < Delta_Value (T) then
11185             Error_Msg_N ("?delta value is too small", D);
11186             Rais :=
11187               Make_Raise_Constraint_Error (Sloc (D),
11188                 Reason => CE_Range_Check_Failed);
11189             Insert_Action (Declaration_Node (Def_Id), Rais);
11190          end if;
11191
11192          C := Range_Constraint (C);
11193
11194       --  No delta constraint present
11195
11196       else
11197          Set_Delta_Value (Def_Id, Delta_Value (T));
11198       end if;
11199
11200       --  Range constraint present
11201
11202       if Nkind (C) = N_Range_Constraint then
11203          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11204
11205       --  No range constraint present
11206
11207       else
11208          pragma Assert (No (C));
11209          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11210
11211       end if;
11212
11213       Set_Discrete_RM_Size (Def_Id);
11214
11215       --  Unconditionally delay the freeze, since we cannot set size
11216       --  information in all cases correctly until the freeze point.
11217
11218       Set_Has_Delayed_Freeze (Def_Id);
11219    end Constrain_Ordinary_Fixed;
11220
11221    -----------------------
11222    -- Contain_Interface --
11223    -----------------------
11224
11225    function Contain_Interface
11226      (Iface  : Entity_Id;
11227       Ifaces : Elist_Id) return Boolean
11228    is
11229       Iface_Elmt : Elmt_Id;
11230
11231    begin
11232       if Present (Ifaces) then
11233          Iface_Elmt := First_Elmt (Ifaces);
11234          while Present (Iface_Elmt) loop
11235             if Node (Iface_Elmt) = Iface then
11236                return True;
11237             end if;
11238
11239             Next_Elmt (Iface_Elmt);
11240          end loop;
11241       end if;
11242
11243       return False;
11244    end Contain_Interface;
11245
11246    ---------------------------
11247    -- Convert_Scalar_Bounds --
11248    ---------------------------
11249
11250    procedure Convert_Scalar_Bounds
11251      (N            : Node_Id;
11252       Parent_Type  : Entity_Id;
11253       Derived_Type : Entity_Id;
11254       Loc          : Source_Ptr)
11255    is
11256       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
11257
11258       Lo  : Node_Id;
11259       Hi  : Node_Id;
11260       Rng : Node_Id;
11261
11262    begin
11263       --  Defend against previous errors
11264
11265       if No (Scalar_Range (Derived_Type)) then
11266          return;
11267       end if;
11268
11269       Lo := Build_Scalar_Bound
11270               (Type_Low_Bound (Derived_Type),
11271                Parent_Type, Implicit_Base);
11272
11273       Hi := Build_Scalar_Bound
11274               (Type_High_Bound (Derived_Type),
11275                Parent_Type, Implicit_Base);
11276
11277       Rng :=
11278         Make_Range (Loc,
11279           Low_Bound  => Lo,
11280           High_Bound => Hi);
11281
11282       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
11283
11284       Set_Parent (Rng, N);
11285       Set_Scalar_Range (Derived_Type, Rng);
11286
11287       --  Analyze the bounds
11288
11289       Analyze_And_Resolve (Lo, Implicit_Base);
11290       Analyze_And_Resolve (Hi, Implicit_Base);
11291
11292       --  Analyze the range itself, except that we do not analyze it if
11293       --  the bounds are real literals, and we have a fixed-point type.
11294       --  The reason for this is that we delay setting the bounds in this
11295       --  case till we know the final Small and Size values (see circuit
11296       --  in Freeze.Freeze_Fixed_Point_Type for further details).
11297
11298       if Is_Fixed_Point_Type (Parent_Type)
11299         and then Nkind (Lo) = N_Real_Literal
11300         and then Nkind (Hi) = N_Real_Literal
11301       then
11302          return;
11303
11304       --  Here we do the analysis of the range
11305
11306       --  Note: we do this manually, since if we do a normal Analyze and
11307       --  Resolve call, there are problems with the conversions used for
11308       --  the derived type range.
11309
11310       else
11311          Set_Etype    (Rng, Implicit_Base);
11312          Set_Analyzed (Rng, True);
11313       end if;
11314    end Convert_Scalar_Bounds;
11315
11316    -------------------
11317    -- Copy_And_Swap --
11318    -------------------
11319
11320    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
11321    begin
11322       --  Initialize new full declaration entity by copying the pertinent
11323       --  fields of the corresponding private declaration entity.
11324
11325       --  We temporarily set Ekind to a value appropriate for a type to
11326       --  avoid assert failures in Einfo from checking for setting type
11327       --  attributes on something that is not a type. Ekind (Priv) is an
11328       --  appropriate choice, since it allowed the attributes to be set
11329       --  in the first place. This Ekind value will be modified later.
11330
11331       Set_Ekind (Full, Ekind (Priv));
11332
11333       --  Also set Etype temporarily to Any_Type, again, in the absence
11334       --  of errors, it will be properly reset, and if there are errors,
11335       --  then we want a value of Any_Type to remain.
11336
11337       Set_Etype (Full, Any_Type);
11338
11339       --  Now start copying attributes
11340
11341       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
11342
11343       if Has_Discriminants (Full) then
11344          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
11345          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
11346       end if;
11347
11348       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
11349       Set_Homonym                    (Full, Homonym                 (Priv));
11350       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
11351       Set_Is_Public                  (Full, Is_Public               (Priv));
11352       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
11353       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
11354       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
11355       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
11356       Set_Has_Pragma_Unreferenced_Objects
11357                                      (Full, Has_Pragma_Unreferenced_Objects
11358                                                                     (Priv));
11359
11360       Conditional_Delay              (Full,                          Priv);
11361
11362       if Is_Tagged_Type (Full) then
11363          Set_Primitive_Operations    (Full, Primitive_Operations    (Priv));
11364
11365          if Priv = Base_Type (Priv) then
11366             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
11367          end if;
11368       end if;
11369
11370       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
11371       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
11372       Set_Scope                      (Full, Scope                   (Priv));
11373       Set_Next_Entity                (Full, Next_Entity             (Priv));
11374       Set_First_Entity               (Full, First_Entity            (Priv));
11375       Set_Last_Entity                (Full, Last_Entity             (Priv));
11376
11377       --  If access types have been recorded for later handling, keep them in
11378       --  the full view so that they get handled when the full view freeze
11379       --  node is expanded.
11380
11381       if Present (Freeze_Node (Priv))
11382         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
11383       then
11384          Ensure_Freeze_Node (Full);
11385          Set_Access_Types_To_Process
11386            (Freeze_Node (Full),
11387             Access_Types_To_Process (Freeze_Node (Priv)));
11388       end if;
11389
11390       --  Swap the two entities. Now Privat is the full type entity and Full is
11391       --  the private one. They will be swapped back at the end of the private
11392       --  part. This swapping ensures that the entity that is visible in the
11393       --  private part is the full declaration.
11394
11395       Exchange_Entities (Priv, Full);
11396       Append_Entity (Full, Scope (Full));
11397    end Copy_And_Swap;
11398
11399    -------------------------------------
11400    -- Copy_Array_Base_Type_Attributes --
11401    -------------------------------------
11402
11403    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
11404    begin
11405       Set_Component_Alignment      (T1, Component_Alignment      (T2));
11406       Set_Component_Type           (T1, Component_Type           (T2));
11407       Set_Component_Size           (T1, Component_Size           (T2));
11408       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
11409       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
11410       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
11411       Set_Has_Task                 (T1, Has_Task                 (T2));
11412       Set_Is_Packed                (T1, Is_Packed                (T2));
11413       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
11414       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
11415       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
11416    end Copy_Array_Base_Type_Attributes;
11417
11418    -----------------------------------
11419    -- Copy_Array_Subtype_Attributes --
11420    -----------------------------------
11421
11422    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
11423    begin
11424       Set_Size_Info (T1, T2);
11425
11426       Set_First_Index          (T1, First_Index           (T2));
11427       Set_Is_Aliased           (T1, Is_Aliased            (T2));
11428       Set_Is_Atomic            (T1, Is_Atomic             (T2));
11429       Set_Is_Volatile          (T1, Is_Volatile           (T2));
11430       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
11431       Set_Is_Constrained       (T1, Is_Constrained        (T2));
11432       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
11433       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
11434       Set_Convention           (T1, Convention            (T2));
11435       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
11436       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
11437       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
11438    end Copy_Array_Subtype_Attributes;
11439
11440    -----------------------------------
11441    -- Create_Constrained_Components --
11442    -----------------------------------
11443
11444    procedure Create_Constrained_Components
11445      (Subt        : Entity_Id;
11446       Decl_Node   : Node_Id;
11447       Typ         : Entity_Id;
11448       Constraints : Elist_Id)
11449    is
11450       Loc         : constant Source_Ptr := Sloc (Subt);
11451       Comp_List   : constant Elist_Id   := New_Elmt_List;
11452       Parent_Type : constant Entity_Id  := Etype (Typ);
11453       Assoc_List  : constant List_Id    := New_List;
11454       Discr_Val   : Elmt_Id;
11455       Errors      : Boolean;
11456       New_C       : Entity_Id;
11457       Old_C       : Entity_Id;
11458       Is_Static   : Boolean := True;
11459
11460       procedure Collect_Fixed_Components (Typ : Entity_Id);
11461       --  Collect parent type components that do not appear in a variant part
11462
11463       procedure Create_All_Components;
11464       --  Iterate over Comp_List to create the components of the subtype
11465
11466       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
11467       --  Creates a new component from Old_Compon, copying all the fields from
11468       --  it, including its Etype, inserts the new component in the Subt entity
11469       --  chain and returns the new component.
11470
11471       function Is_Variant_Record (T : Entity_Id) return Boolean;
11472       --  If true, and discriminants are static, collect only components from
11473       --  variants selected by discriminant values.
11474
11475       ------------------------------
11476       -- Collect_Fixed_Components --
11477       ------------------------------
11478
11479       procedure Collect_Fixed_Components (Typ : Entity_Id) is
11480       begin
11481       --  Build association list for discriminants, and find components of the
11482       --  variant part selected by the values of the discriminants.
11483
11484          Old_C := First_Discriminant (Typ);
11485          Discr_Val := First_Elmt (Constraints);
11486          while Present (Old_C) loop
11487             Append_To (Assoc_List,
11488               Make_Component_Association (Loc,
11489                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
11490                  Expression => New_Copy (Node (Discr_Val))));
11491
11492             Next_Elmt (Discr_Val);
11493             Next_Discriminant (Old_C);
11494          end loop;
11495
11496          --  The tag, and the possible parent and controller components
11497          --  are unconditionally in the subtype.
11498
11499          if Is_Tagged_Type (Typ)
11500            or else Has_Controlled_Component (Typ)
11501          then
11502             Old_C := First_Component (Typ);
11503             while Present (Old_C) loop
11504                if Chars ((Old_C)) = Name_uTag
11505                  or else Chars ((Old_C)) = Name_uParent
11506                  or else Chars ((Old_C)) = Name_uController
11507                then
11508                   Append_Elmt (Old_C, Comp_List);
11509                end if;
11510
11511                Next_Component (Old_C);
11512             end loop;
11513          end if;
11514       end Collect_Fixed_Components;
11515
11516       ---------------------------
11517       -- Create_All_Components --
11518       ---------------------------
11519
11520       procedure Create_All_Components is
11521          Comp : Elmt_Id;
11522
11523       begin
11524          Comp := First_Elmt (Comp_List);
11525          while Present (Comp) loop
11526             Old_C := Node (Comp);
11527             New_C := Create_Component (Old_C);
11528
11529             Set_Etype
11530               (New_C,
11531                Constrain_Component_Type
11532                  (Old_C, Subt, Decl_Node, Typ, Constraints));
11533             Set_Is_Public (New_C, Is_Public (Subt));
11534
11535             Next_Elmt (Comp);
11536          end loop;
11537       end Create_All_Components;
11538
11539       ----------------------
11540       -- Create_Component --
11541       ----------------------
11542
11543       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
11544          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
11545
11546       begin
11547          if Ekind (Old_Compon) = E_Discriminant
11548            and then Is_Completely_Hidden (Old_Compon)
11549          then
11550             --  This is a shadow discriminant created for a discriminant of
11551             --  the parent type, which needs to be present in the subtype.
11552             --  Give the shadow discriminant an internal name that cannot
11553             --  conflict with that of visible components.
11554
11555             Set_Chars (New_Compon, New_Internal_Name ('C'));
11556          end if;
11557
11558          --  Set the parent so we have a proper link for freezing etc. This is
11559          --  not a real parent pointer, since of course our parent does not own
11560          --  up to us and reference us, we are an illegitimate child of the
11561          --  original parent!
11562
11563          Set_Parent (New_Compon, Parent (Old_Compon));
11564
11565          --  If the old component's Esize was already determined and is a
11566          --  static value, then the new component simply inherits it. Otherwise
11567          --  the old component's size may require run-time determination, but
11568          --  the new component's size still might be statically determinable
11569          --  (if, for example it has a static constraint). In that case we want
11570          --  Layout_Type to recompute the component's size, so we reset its
11571          --  size and positional fields.
11572
11573          if Frontend_Layout_On_Target
11574            and then not Known_Static_Esize (Old_Compon)
11575          then
11576             Set_Esize (New_Compon, Uint_0);
11577             Init_Normalized_First_Bit    (New_Compon);
11578             Init_Normalized_Position     (New_Compon);
11579             Init_Normalized_Position_Max (New_Compon);
11580          end if;
11581
11582          --  We do not want this node marked as Comes_From_Source, since
11583          --  otherwise it would get first class status and a separate cross-
11584          --  reference line would be generated. Illegitimate children do not
11585          --  rate such recognition.
11586
11587          Set_Comes_From_Source (New_Compon, False);
11588
11589          --  But it is a real entity, and a birth certificate must be properly
11590          --  registered by entering it into the entity list.
11591
11592          Enter_Name (New_Compon);
11593
11594          return New_Compon;
11595       end Create_Component;
11596
11597       -----------------------
11598       -- Is_Variant_Record --
11599       -----------------------
11600
11601       function Is_Variant_Record (T : Entity_Id) return Boolean is
11602       begin
11603          return Nkind (Parent (T)) = N_Full_Type_Declaration
11604            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
11605            and then Present (Component_List (Type_Definition (Parent (T))))
11606            and then
11607              Present
11608                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
11609       end Is_Variant_Record;
11610
11611    --  Start of processing for Create_Constrained_Components
11612
11613    begin
11614       pragma Assert (Subt /= Base_Type (Subt));
11615       pragma Assert (Typ = Base_Type (Typ));
11616
11617       Set_First_Entity (Subt, Empty);
11618       Set_Last_Entity  (Subt, Empty);
11619
11620       --  Check whether constraint is fully static, in which case we can
11621       --  optimize the list of components.
11622
11623       Discr_Val := First_Elmt (Constraints);
11624       while Present (Discr_Val) loop
11625          if not Is_OK_Static_Expression (Node (Discr_Val)) then
11626             Is_Static := False;
11627             exit;
11628          end if;
11629
11630          Next_Elmt (Discr_Val);
11631       end loop;
11632
11633       Set_Has_Static_Discriminants (Subt, Is_Static);
11634
11635       Push_Scope (Subt);
11636
11637       --  Inherit the discriminants of the parent type
11638
11639       Add_Discriminants : declare
11640          Num_Disc : Int;
11641          Num_Gird : Int;
11642
11643       begin
11644          Num_Disc := 0;
11645          Old_C := First_Discriminant (Typ);
11646
11647          while Present (Old_C) loop
11648             Num_Disc := Num_Disc + 1;
11649             New_C := Create_Component (Old_C);
11650             Set_Is_Public (New_C, Is_Public (Subt));
11651             Next_Discriminant (Old_C);
11652          end loop;
11653
11654          --  For an untagged derived subtype, the number of discriminants may
11655          --  be smaller than the number of inherited discriminants, because
11656          --  several of them may be renamed by a single new discriminant or
11657          --  constrained. In this case, add the hidden discriminants back into
11658          --  the subtype, because they need to be present if the optimizer of
11659          --  the GCC 4.x back-end decides to break apart assignments between
11660          --  objects using the parent view into member-wise assignments.
11661
11662          Num_Gird := 0;
11663
11664          if Is_Derived_Type (Typ)
11665            and then not Is_Tagged_Type (Typ)
11666          then
11667             Old_C := First_Stored_Discriminant (Typ);
11668
11669             while Present (Old_C) loop
11670                Num_Gird := Num_Gird + 1;
11671                Next_Stored_Discriminant (Old_C);
11672             end loop;
11673          end if;
11674
11675          if Num_Gird > Num_Disc then
11676
11677             --  Find out multiple uses of new discriminants, and add hidden
11678             --  components for the extra renamed discriminants. We recognize
11679             --  multiple uses through the Corresponding_Discriminant of a
11680             --  new discriminant: if it constrains several old discriminants,
11681             --  this field points to the last one in the parent type. The
11682             --  stored discriminants of the derived type have the same name
11683             --  as those of the parent.
11684
11685             declare
11686                Constr    : Elmt_Id;
11687                New_Discr : Entity_Id;
11688                Old_Discr : Entity_Id;
11689
11690             begin
11691                Constr    := First_Elmt (Stored_Constraint (Typ));
11692                Old_Discr := First_Stored_Discriminant (Typ);
11693                while Present (Constr) loop
11694                   if Is_Entity_Name (Node (Constr))
11695                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
11696                   then
11697                      New_Discr := Entity (Node (Constr));
11698
11699                      if Chars (Corresponding_Discriminant (New_Discr)) /=
11700                         Chars (Old_Discr)
11701                      then
11702                         --  The new discriminant has been used to rename a
11703                         --  subsequent old discriminant. Introduce a shadow
11704                         --  component for the current old discriminant.
11705
11706                         New_C := Create_Component (Old_Discr);
11707                         Set_Original_Record_Component (New_C, Old_Discr);
11708                      end if;
11709
11710                   else
11711                      --  The constraint has eliminated the old discriminant.
11712                      --  Introduce a shadow component.
11713
11714                      New_C := Create_Component (Old_Discr);
11715                      Set_Original_Record_Component (New_C, Old_Discr);
11716                   end if;
11717
11718                   Next_Elmt (Constr);
11719                   Next_Stored_Discriminant (Old_Discr);
11720                end loop;
11721             end;
11722          end if;
11723       end Add_Discriminants;
11724
11725       if Is_Static
11726         and then Is_Variant_Record (Typ)
11727       then
11728          Collect_Fixed_Components (Typ);
11729
11730          Gather_Components (
11731            Typ,
11732            Component_List (Type_Definition (Parent (Typ))),
11733            Governed_By   => Assoc_List,
11734            Into          => Comp_List,
11735            Report_Errors => Errors);
11736          pragma Assert (not Errors);
11737
11738          Create_All_Components;
11739
11740       --  If the subtype declaration is created for a tagged type derivation
11741       --  with constraints, we retrieve the record definition of the parent
11742       --  type to select the components of the proper variant.
11743
11744       elsif Is_Static
11745         and then Is_Tagged_Type (Typ)
11746         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
11747         and then
11748           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
11749         and then Is_Variant_Record (Parent_Type)
11750       then
11751          Collect_Fixed_Components (Typ);
11752
11753          Gather_Components (
11754            Typ,
11755            Component_List (Type_Definition (Parent (Parent_Type))),
11756            Governed_By   => Assoc_List,
11757            Into          => Comp_List,
11758            Report_Errors => Errors);
11759          pragma Assert (not Errors);
11760
11761          --  If the tagged derivation has a type extension, collect all the
11762          --  new components therein.
11763
11764          if Present
11765               (Record_Extension_Part (Type_Definition (Parent (Typ))))
11766          then
11767             Old_C := First_Component (Typ);
11768             while Present (Old_C) loop
11769                if Original_Record_Component (Old_C) = Old_C
11770                 and then Chars (Old_C) /= Name_uTag
11771                 and then Chars (Old_C) /= Name_uParent
11772                 and then Chars (Old_C) /= Name_uController
11773                then
11774                   Append_Elmt (Old_C, Comp_List);
11775                end if;
11776
11777                Next_Component (Old_C);
11778             end loop;
11779          end if;
11780
11781          Create_All_Components;
11782
11783       else
11784          --  If discriminants are not static, or if this is a multi-level type
11785          --  extension, we have to include all components of the parent type.
11786
11787          Old_C := First_Component (Typ);
11788          while Present (Old_C) loop
11789             New_C := Create_Component (Old_C);
11790
11791             Set_Etype
11792               (New_C,
11793                Constrain_Component_Type
11794                  (Old_C, Subt, Decl_Node, Typ, Constraints));
11795             Set_Is_Public (New_C, Is_Public (Subt));
11796
11797             Next_Component (Old_C);
11798          end loop;
11799       end if;
11800
11801       End_Scope;
11802    end Create_Constrained_Components;
11803
11804    ------------------------------------------
11805    -- Decimal_Fixed_Point_Type_Declaration --
11806    ------------------------------------------
11807
11808    procedure Decimal_Fixed_Point_Type_Declaration
11809      (T   : Entity_Id;
11810       Def : Node_Id)
11811    is
11812       Loc           : constant Source_Ptr := Sloc (Def);
11813       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
11814       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
11815       Implicit_Base : Entity_Id;
11816       Digs_Val      : Uint;
11817       Delta_Val     : Ureal;
11818       Scale_Val     : Uint;
11819       Bound_Val     : Ureal;
11820
11821    begin
11822       Check_Restriction (No_Fixed_Point, Def);
11823
11824       --  Create implicit base type
11825
11826       Implicit_Base :=
11827         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
11828       Set_Etype (Implicit_Base, Implicit_Base);
11829
11830       --  Analyze and process delta expression
11831
11832       Analyze_And_Resolve (Delta_Expr, Universal_Real);
11833
11834       Check_Delta_Expression (Delta_Expr);
11835       Delta_Val := Expr_Value_R (Delta_Expr);
11836
11837       --  Check delta is power of 10, and determine scale value from it
11838
11839       declare
11840          Val : Ureal;
11841
11842       begin
11843          Scale_Val := Uint_0;
11844          Val := Delta_Val;
11845
11846          if Val < Ureal_1 then
11847             while Val < Ureal_1 loop
11848                Val := Val * Ureal_10;
11849                Scale_Val := Scale_Val + 1;
11850             end loop;
11851
11852             if Scale_Val > 18 then
11853                Error_Msg_N ("scale exceeds maximum value of 18", Def);
11854                Scale_Val := UI_From_Int (+18);
11855             end if;
11856
11857          else
11858             while Val > Ureal_1 loop
11859                Val := Val / Ureal_10;
11860                Scale_Val := Scale_Val - 1;
11861             end loop;
11862
11863             if Scale_Val < -18 then
11864                Error_Msg_N ("scale is less than minimum value of -18", Def);
11865                Scale_Val := UI_From_Int (-18);
11866             end if;
11867          end if;
11868
11869          if Val /= Ureal_1 then
11870             Error_Msg_N ("delta expression must be a power of 10", Def);
11871             Delta_Val := Ureal_10 ** (-Scale_Val);
11872          end if;
11873       end;
11874
11875       --  Set delta, scale and small (small = delta for decimal type)
11876
11877       Set_Delta_Value (Implicit_Base, Delta_Val);
11878       Set_Scale_Value (Implicit_Base, Scale_Val);
11879       Set_Small_Value (Implicit_Base, Delta_Val);
11880
11881       --  Analyze and process digits expression
11882
11883       Analyze_And_Resolve (Digs_Expr, Any_Integer);
11884       Check_Digits_Expression (Digs_Expr);
11885       Digs_Val := Expr_Value (Digs_Expr);
11886
11887       if Digs_Val > 18 then
11888          Digs_Val := UI_From_Int (+18);
11889          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
11890       end if;
11891
11892       Set_Digits_Value (Implicit_Base, Digs_Val);
11893       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
11894
11895       --  Set range of base type from digits value for now. This will be
11896       --  expanded to represent the true underlying base range by Freeze.
11897
11898       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
11899
11900       --  Note: We leave size as zero for now, size will be set at freeze
11901       --  time. We have to do this for ordinary fixed-point, because the size
11902       --  depends on the specified small, and we might as well do the same for
11903       --  decimal fixed-point.
11904
11905       pragma Assert (Esize (Implicit_Base) = Uint_0);
11906
11907       --  If there are bounds given in the declaration use them as the
11908       --  bounds of the first named subtype.
11909
11910       if Present (Real_Range_Specification (Def)) then
11911          declare
11912             RRS      : constant Node_Id := Real_Range_Specification (Def);
11913             Low      : constant Node_Id := Low_Bound (RRS);
11914             High     : constant Node_Id := High_Bound (RRS);
11915             Low_Val  : Ureal;
11916             High_Val : Ureal;
11917
11918          begin
11919             Analyze_And_Resolve (Low, Any_Real);
11920             Analyze_And_Resolve (High, Any_Real);
11921             Check_Real_Bound (Low);
11922             Check_Real_Bound (High);
11923             Low_Val := Expr_Value_R (Low);
11924             High_Val := Expr_Value_R (High);
11925
11926             if Low_Val < (-Bound_Val) then
11927                Error_Msg_N
11928                  ("range low bound too small for digits value", Low);
11929                Low_Val := -Bound_Val;
11930             end if;
11931
11932             if High_Val > Bound_Val then
11933                Error_Msg_N
11934                  ("range high bound too large for digits value", High);
11935                High_Val := Bound_Val;
11936             end if;
11937
11938             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
11939          end;
11940
11941       --  If no explicit range, use range that corresponds to given
11942       --  digits value. This will end up as the final range for the
11943       --  first subtype.
11944
11945       else
11946          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
11947       end if;
11948
11949       --  Complete entity for first subtype
11950
11951       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
11952       Set_Etype          (T, Implicit_Base);
11953       Set_Size_Info      (T, Implicit_Base);
11954       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
11955       Set_Digits_Value   (T, Digs_Val);
11956       Set_Delta_Value    (T, Delta_Val);
11957       Set_Small_Value    (T, Delta_Val);
11958       Set_Scale_Value    (T, Scale_Val);
11959       Set_Is_Constrained (T);
11960    end Decimal_Fixed_Point_Type_Declaration;
11961
11962    -----------------------------------
11963    -- Derive_Progenitor_Subprograms --
11964    -----------------------------------
11965
11966    procedure Derive_Progenitor_Subprograms
11967      (Parent_Type : Entity_Id;
11968       Tagged_Type : Entity_Id)
11969    is
11970       E          : Entity_Id;
11971       Elmt       : Elmt_Id;
11972       Iface      : Entity_Id;
11973       Iface_Elmt : Elmt_Id;
11974       Iface_Subp : Entity_Id;
11975       New_Subp   : Entity_Id := Empty;
11976       Prim_Elmt  : Elmt_Id;
11977       Subp       : Entity_Id;
11978       Typ        : Entity_Id;
11979
11980    begin
11981       pragma Assert (Ada_Version >= Ada_05
11982         and then Is_Record_Type (Tagged_Type)
11983         and then Is_Tagged_Type (Tagged_Type)
11984         and then Has_Interfaces (Tagged_Type));
11985
11986       --  Step 1: Transfer to the full-view primitives associated with the
11987       --  partial-view that cover interface primitives. Conceptually this
11988       --  work should be done later by Process_Full_View; done here to
11989       --  simplify its implementation at later stages. It can be safely
11990       --  done here because interfaces must be visible in the partial and
11991       --  private view (RM 7.3(7.3/2)).
11992
11993       --  Small optimization: This work is only required if the parent is
11994       --  abstract. If the tagged type is not abstract, it cannot have
11995       --  abstract primitives (the only entities in the list of primitives of
11996       --  non-abstract tagged types that can reference abstract primitives
11997       --  through its Alias attribute are the internal entities that have
11998       --  attribute Interface_Alias, and these entities are generated later
11999       --  by Add_Internal_Interface_Entities).
12000
12001       if In_Private_Part (Current_Scope)
12002         and then Is_Abstract_Type (Parent_Type)
12003       then
12004          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
12005          while Present (Elmt) loop
12006             Subp := Node (Elmt);
12007
12008             --  At this stage it is not possible to have entities in the list
12009             --  of primitives that have attribute Interface_Alias
12010
12011             pragma Assert (No (Interface_Alias (Subp)));
12012
12013             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
12014
12015             if Is_Interface (Typ) then
12016                E := Find_Primitive_Covering_Interface
12017                       (Tagged_Type => Tagged_Type,
12018                        Iface_Prim  => Subp);
12019
12020                if Present (E)
12021                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
12022                then
12023                   Replace_Elmt (Elmt, E);
12024                   Remove_Homonym (Subp);
12025                end if;
12026             end if;
12027
12028             Next_Elmt (Elmt);
12029          end loop;
12030       end if;
12031
12032       --  Step 2: Add primitives of progenitors that are not implemented by
12033       --  parents of Tagged_Type
12034
12035       if Present (Interfaces (Base_Type (Tagged_Type))) then
12036          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
12037          while Present (Iface_Elmt) loop
12038             Iface := Node (Iface_Elmt);
12039
12040             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
12041             while Present (Prim_Elmt) loop
12042                Iface_Subp := Node (Prim_Elmt);
12043
12044                --  Exclude derivation of predefined primitives except those
12045                --  that come from source. Required to catch declarations of
12046                --  equality operators of interfaces. For example:
12047
12048                --     type Iface is interface;
12049                --     function "=" (Left, Right : Iface) return Boolean;
12050
12051                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
12052                  or else Comes_From_Source (Iface_Subp)
12053                then
12054                   E := Find_Primitive_Covering_Interface
12055                          (Tagged_Type => Tagged_Type,
12056                           Iface_Prim  => Iface_Subp);
12057
12058                   --  If not found we derive a new primitive leaving its alias
12059                   --  attribute referencing the interface primitive
12060
12061                   if No (E) then
12062                      Derive_Subprogram
12063                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12064
12065                   --  Propagate to the full view interface entities associated
12066                   --  with the partial view
12067
12068                   elsif In_Private_Part (Current_Scope)
12069                     and then Present (Alias (E))
12070                     and then Alias (E) = Iface_Subp
12071                     and then
12072                       List_Containing (Parent (E)) /=
12073                         Private_Declarations
12074                           (Specification
12075                             (Unit_Declaration_Node (Current_Scope)))
12076                   then
12077                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
12078                   end if;
12079                end if;
12080
12081                Next_Elmt (Prim_Elmt);
12082             end loop;
12083
12084             Next_Elmt (Iface_Elmt);
12085          end loop;
12086       end if;
12087    end Derive_Progenitor_Subprograms;
12088
12089    -----------------------
12090    -- Derive_Subprogram --
12091    -----------------------
12092
12093    procedure Derive_Subprogram
12094      (New_Subp     : in out Entity_Id;
12095       Parent_Subp  : Entity_Id;
12096       Derived_Type : Entity_Id;
12097       Parent_Type  : Entity_Id;
12098       Actual_Subp  : Entity_Id := Empty)
12099    is
12100       Formal : Entity_Id;
12101       --  Formal parameter of parent primitive operation
12102
12103       Formal_Of_Actual : Entity_Id;
12104       --  Formal parameter of actual operation, when the derivation is to
12105       --  create a renaming for a primitive operation of an actual in an
12106       --  instantiation.
12107
12108       New_Formal : Entity_Id;
12109       --  Formal of inherited operation
12110
12111       Visible_Subp : Entity_Id := Parent_Subp;
12112
12113       function Is_Private_Overriding return Boolean;
12114       --  If Subp is a private overriding of a visible operation, the inherited
12115       --  operation derives from the overridden op (even though its body is the
12116       --  overriding one) and the inherited operation is visible now. See
12117       --  sem_disp to see the full details of the handling of the overridden
12118       --  subprogram, which is removed from the list of primitive operations of
12119       --  the type. The overridden subprogram is saved locally in Visible_Subp,
12120       --  and used to diagnose abstract operations that need overriding in the
12121       --  derived type.
12122
12123       procedure Replace_Type (Id, New_Id : Entity_Id);
12124       --  When the type is an anonymous access type, create a new access type
12125       --  designating the derived type.
12126
12127       procedure Set_Derived_Name;
12128       --  This procedure sets the appropriate Chars name for New_Subp. This
12129       --  is normally just a copy of the parent name. An exception arises for
12130       --  type support subprograms, where the name is changed to reflect the
12131       --  name of the derived type, e.g. if type foo is derived from type bar,
12132       --  then a procedure barDA is derived with a name fooDA.
12133
12134       ---------------------------
12135       -- Is_Private_Overriding --
12136       ---------------------------
12137
12138       function Is_Private_Overriding return Boolean is
12139          Prev : Entity_Id;
12140
12141       begin
12142          --  If the parent is not a dispatching operation there is no
12143          --  need to investigate overridings
12144
12145          if not Is_Dispatching_Operation (Parent_Subp) then
12146             return False;
12147          end if;
12148
12149          --  The visible operation that is overridden is a homonym of the
12150          --  parent subprogram. We scan the homonym chain to find the one
12151          --  whose alias is the subprogram we are deriving.
12152
12153          Prev := Current_Entity (Parent_Subp);
12154          while Present (Prev) loop
12155             if Ekind (Prev) = Ekind (Parent_Subp)
12156               and then Alias (Prev) = Parent_Subp
12157               and then Scope (Parent_Subp) = Scope (Prev)
12158               and then not Is_Hidden (Prev)
12159             then
12160                Visible_Subp := Prev;
12161                return True;
12162             end if;
12163
12164             Prev := Homonym (Prev);
12165          end loop;
12166
12167          return False;
12168       end Is_Private_Overriding;
12169
12170       ------------------
12171       -- Replace_Type --
12172       ------------------
12173
12174       procedure Replace_Type (Id, New_Id : Entity_Id) is
12175          Acc_Type : Entity_Id;
12176          Par      : constant Node_Id := Parent (Derived_Type);
12177
12178       begin
12179          --  When the type is an anonymous access type, create a new access
12180          --  type designating the derived type. This itype must be elaborated
12181          --  at the point of the derivation, not on subsequent calls that may
12182          --  be out of the proper scope for Gigi, so we insert a reference to
12183          --  it after the derivation.
12184
12185          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
12186             declare
12187                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
12188
12189             begin
12190                if Ekind (Desig_Typ) = E_Record_Type_With_Private
12191                  and then Present (Full_View (Desig_Typ))
12192                  and then not Is_Private_Type (Parent_Type)
12193                then
12194                   Desig_Typ := Full_View (Desig_Typ);
12195                end if;
12196
12197                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
12198
12199                   --  Ada 2005 (AI-251): Handle also derivations of abstract
12200                   --  interface primitives.
12201
12202                  or else (Is_Interface (Desig_Typ)
12203                           and then not Is_Class_Wide_Type (Desig_Typ))
12204                then
12205                   Acc_Type := New_Copy (Etype (Id));
12206                   Set_Etype (Acc_Type, Acc_Type);
12207                   Set_Scope (Acc_Type, New_Subp);
12208
12209                   --  Compute size of anonymous access type
12210
12211                   if Is_Array_Type (Desig_Typ)
12212                     and then not Is_Constrained (Desig_Typ)
12213                   then
12214                      Init_Size (Acc_Type, 2 * System_Address_Size);
12215                   else
12216                      Init_Size (Acc_Type, System_Address_Size);
12217                   end if;
12218
12219                   Init_Alignment (Acc_Type);
12220                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
12221
12222                   Set_Etype (New_Id, Acc_Type);
12223                   Set_Scope (New_Id, New_Subp);
12224
12225                   --  Create a reference to it
12226                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
12227
12228                else
12229                   Set_Etype (New_Id, Etype (Id));
12230                end if;
12231             end;
12232
12233          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
12234            or else
12235              (Ekind (Etype (Id)) = E_Record_Type_With_Private
12236                and then Present (Full_View (Etype (Id)))
12237                and then
12238                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
12239          then
12240             --  Constraint checks on formals are generated during expansion,
12241             --  based on the signature of the original subprogram. The bounds
12242             --  of the derived type are not relevant, and thus we can use
12243             --  the base type for the formals. However, the return type may be
12244             --  used in a context that requires that the proper static bounds
12245             --  be used (a case statement, for example)  and for those cases
12246             --  we must use the derived type (first subtype), not its base.
12247
12248             --  If the derived_type_definition has no constraints, we know that
12249             --  the derived type has the same constraints as the first subtype
12250             --  of the parent, and we can also use it rather than its base,
12251             --  which can lead to more efficient code.
12252
12253             if Etype (Id) = Parent_Type then
12254                if Is_Scalar_Type (Parent_Type)
12255                  and then
12256                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
12257                then
12258                   Set_Etype (New_Id, Derived_Type);
12259
12260                elsif Nkind (Par) = N_Full_Type_Declaration
12261                  and then
12262                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
12263                  and then
12264                    Is_Entity_Name
12265                      (Subtype_Indication (Type_Definition (Par)))
12266                then
12267                   Set_Etype (New_Id, Derived_Type);
12268
12269                else
12270                   Set_Etype (New_Id, Base_Type (Derived_Type));
12271                end if;
12272
12273             else
12274                Set_Etype (New_Id, Base_Type (Derived_Type));
12275             end if;
12276
12277          else
12278             Set_Etype (New_Id, Etype (Id));
12279          end if;
12280       end Replace_Type;
12281
12282       ----------------------
12283       -- Set_Derived_Name --
12284       ----------------------
12285
12286       procedure Set_Derived_Name is
12287          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
12288       begin
12289          if Nm = TSS_Null then
12290             Set_Chars (New_Subp, Chars (Parent_Subp));
12291          else
12292             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
12293          end if;
12294       end Set_Derived_Name;
12295
12296    --  Start of processing for Derive_Subprogram
12297
12298    begin
12299       New_Subp :=
12300          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
12301       Set_Ekind (New_Subp, Ekind (Parent_Subp));
12302
12303       --  Check whether the inherited subprogram is a private operation that
12304       --  should be inherited but not yet made visible. Such subprograms can
12305       --  become visible at a later point (e.g., the private part of a public
12306       --  child unit) via Declare_Inherited_Private_Subprograms. If the
12307       --  following predicate is true, then this is not such a private
12308       --  operation and the subprogram simply inherits the name of the parent
12309       --  subprogram. Note the special check for the names of controlled
12310       --  operations, which are currently exempted from being inherited with
12311       --  a hidden name because they must be findable for generation of
12312       --  implicit run-time calls.
12313
12314       if not Is_Hidden (Parent_Subp)
12315         or else Is_Internal (Parent_Subp)
12316         or else Is_Private_Overriding
12317         or else Is_Internal_Name (Chars (Parent_Subp))
12318         or else Chars (Parent_Subp) = Name_Initialize
12319         or else Chars (Parent_Subp) = Name_Adjust
12320         or else Chars (Parent_Subp) = Name_Finalize
12321       then
12322          Set_Derived_Name;
12323
12324       --  An inherited dispatching equality will be overridden by an internally
12325       --  generated one, or by an explicit one, so preserve its name and thus
12326       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
12327       --  private operation it may become invisible if the full view has
12328       --  progenitors, and the dispatch table will be malformed.
12329       --  We check that the type is limited to handle the anomalous declaration
12330       --  of Limited_Controlled, which is derived from a non-limited type, and
12331       --  which is handled specially elsewhere as well.
12332
12333       elsif Chars (Parent_Subp) = Name_Op_Eq
12334         and then Is_Dispatching_Operation (Parent_Subp)
12335         and then Etype (Parent_Subp) = Standard_Boolean
12336         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
12337         and then
12338           Etype (First_Formal (Parent_Subp)) =
12339             Etype (Next_Formal (First_Formal (Parent_Subp)))
12340       then
12341          Set_Derived_Name;
12342
12343       --  If parent is hidden, this can be a regular derivation if the
12344       --  parent is immediately visible in a non-instantiating context,
12345       --  or if we are in the private part of an instance. This test
12346       --  should still be refined ???
12347
12348       --  The test for In_Instance_Not_Visible avoids inheriting the derived
12349       --  operation as a non-visible operation in cases where the parent
12350       --  subprogram might not be visible now, but was visible within the
12351       --  original generic, so it would be wrong to make the inherited
12352       --  subprogram non-visible now. (Not clear if this test is fully
12353       --  correct; are there any cases where we should declare the inherited
12354       --  operation as not visible to avoid it being overridden, e.g., when
12355       --  the parent type is a generic actual with private primitives ???)
12356
12357       --  (they should be treated the same as other private inherited
12358       --  subprograms, but it's not clear how to do this cleanly). ???
12359
12360       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
12361               and then Is_Immediately_Visible (Parent_Subp)
12362               and then not In_Instance)
12363         or else In_Instance_Not_Visible
12364       then
12365          Set_Derived_Name;
12366
12367       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
12368       --  overrides an interface primitive because interface primitives
12369       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
12370
12371       elsif Ada_Version >= Ada_05
12372          and then Is_Dispatching_Operation (Parent_Subp)
12373          and then Covers_Some_Interface (Parent_Subp)
12374       then
12375          Set_Derived_Name;
12376
12377       --  Otherwise, the type is inheriting a private operation, so enter
12378       --  it with a special name so it can't be overridden.
12379
12380       else
12381          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
12382       end if;
12383
12384       Set_Parent (New_Subp, Parent (Derived_Type));
12385
12386       if Present (Actual_Subp) then
12387          Replace_Type (Actual_Subp, New_Subp);
12388       else
12389          Replace_Type (Parent_Subp, New_Subp);
12390       end if;
12391
12392       Conditional_Delay (New_Subp, Parent_Subp);
12393
12394       --  If we are creating a renaming for a primitive operation of an
12395       --  actual of a generic derived type, we must examine the signature
12396       --  of the actual primitive, not that of the generic formal, which for
12397       --  example may be an interface. However the name and initial value
12398       --  of the inherited operation are those of the formal primitive.
12399
12400       Formal := First_Formal (Parent_Subp);
12401
12402       if Present (Actual_Subp) then
12403          Formal_Of_Actual := First_Formal (Actual_Subp);
12404       else
12405          Formal_Of_Actual := Empty;
12406       end if;
12407
12408       while Present (Formal) loop
12409          New_Formal := New_Copy (Formal);
12410
12411          --  Normally we do not go copying parents, but in the case of
12412          --  formals, we need to link up to the declaration (which is the
12413          --  parameter specification), and it is fine to link up to the
12414          --  original formal's parameter specification in this case.
12415
12416          Set_Parent (New_Formal, Parent (Formal));
12417          Append_Entity (New_Formal, New_Subp);
12418
12419          if Present (Formal_Of_Actual) then
12420             Replace_Type (Formal_Of_Actual, New_Formal);
12421             Next_Formal (Formal_Of_Actual);
12422          else
12423             Replace_Type (Formal, New_Formal);
12424          end if;
12425
12426          Next_Formal (Formal);
12427       end loop;
12428
12429       --  If this derivation corresponds to a tagged generic actual, then
12430       --  primitive operations rename those of the actual. Otherwise the
12431       --  primitive operations rename those of the parent type, If the parent
12432       --  renames an intrinsic operator, so does the new subprogram. We except
12433       --  concatenation, which is always properly typed, and does not get
12434       --  expanded as other intrinsic operations.
12435
12436       if No (Actual_Subp) then
12437          if Is_Intrinsic_Subprogram (Parent_Subp) then
12438             Set_Is_Intrinsic_Subprogram (New_Subp);
12439
12440             if Present (Alias (Parent_Subp))
12441               and then Chars (Parent_Subp) /= Name_Op_Concat
12442             then
12443                Set_Alias (New_Subp, Alias (Parent_Subp));
12444             else
12445                Set_Alias (New_Subp, Parent_Subp);
12446             end if;
12447
12448          else
12449             Set_Alias (New_Subp, Parent_Subp);
12450          end if;
12451
12452       else
12453          Set_Alias (New_Subp, Actual_Subp);
12454       end if;
12455
12456       --  Derived subprograms of a tagged type must inherit the convention
12457       --  of the parent subprogram (a requirement of AI-117). Derived
12458       --  subprograms of untagged types simply get convention Ada by default.
12459
12460       if Is_Tagged_Type (Derived_Type) then
12461          Set_Convention (New_Subp, Convention (Parent_Subp));
12462       end if;
12463
12464       --  Predefined controlled operations retain their name even if the parent
12465       --  is hidden (see above), but they are not primitive operations if the
12466       --  ancestor is not visible, for example if the parent is a private
12467       --  extension completed with a controlled extension. Note that a full
12468       --  type that is controlled can break privacy: the flag Is_Controlled is
12469       --  set on both views of the type.
12470
12471       if Is_Controlled (Parent_Type)
12472         and then
12473           (Chars (Parent_Subp) = Name_Initialize
12474             or else Chars (Parent_Subp) = Name_Adjust
12475             or else Chars (Parent_Subp) = Name_Finalize)
12476         and then Is_Hidden (Parent_Subp)
12477         and then not Is_Visibly_Controlled (Parent_Type)
12478       then
12479          Set_Is_Hidden (New_Subp);
12480       end if;
12481
12482       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
12483       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
12484
12485       if Ekind (Parent_Subp) = E_Procedure then
12486          Set_Is_Valued_Procedure
12487            (New_Subp, Is_Valued_Procedure (Parent_Subp));
12488       end if;
12489
12490       --  No_Return must be inherited properly. If this is overridden in the
12491       --  case of a dispatching operation, then a check is made in Sem_Disp
12492       --  that the overriding operation is also No_Return (no such check is
12493       --  required for the case of non-dispatching operation.
12494
12495       Set_No_Return (New_Subp, No_Return (Parent_Subp));
12496
12497       --  A derived function with a controlling result is abstract. If the
12498       --  Derived_Type is a nonabstract formal generic derived type, then
12499       --  inherited operations are not abstract: the required check is done at
12500       --  instantiation time. If the derivation is for a generic actual, the
12501       --  function is not abstract unless the actual is.
12502
12503       if Is_Generic_Type (Derived_Type)
12504         and then not Is_Abstract_Type (Derived_Type)
12505       then
12506          null;
12507
12508       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
12509       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
12510
12511       elsif Ada_Version >= Ada_05
12512         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12513                    or else (Is_Tagged_Type (Derived_Type)
12514                             and then Etype (New_Subp) = Derived_Type
12515                             and then not Is_Null_Extension (Derived_Type))
12516                    or else (Is_Tagged_Type (Derived_Type)
12517                             and then Ekind (Etype (New_Subp)) =
12518                                                        E_Anonymous_Access_Type
12519                             and then Designated_Type (Etype (New_Subp)) =
12520                                                        Derived_Type
12521                             and then not Is_Null_Extension (Derived_Type)))
12522         and then No (Actual_Subp)
12523       then
12524          if not Is_Tagged_Type (Derived_Type)
12525            or else Is_Abstract_Type (Derived_Type)
12526            or else Is_Abstract_Subprogram (Alias (New_Subp))
12527          then
12528             Set_Is_Abstract_Subprogram (New_Subp);
12529          else
12530             Set_Requires_Overriding (New_Subp);
12531          end if;
12532
12533       elsif Ada_Version < Ada_05
12534         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12535                    or else (Is_Tagged_Type (Derived_Type)
12536                              and then Etype (New_Subp) = Derived_Type
12537                              and then No (Actual_Subp)))
12538       then
12539          Set_Is_Abstract_Subprogram (New_Subp);
12540
12541       --  Finally, if the parent type is abstract we must verify that all
12542       --  inherited operations are either non-abstract or overridden, or that
12543       --  the derived type itself is abstract (this check is performed at the
12544       --  end of a package declaration, in Check_Abstract_Overriding). A
12545       --  private overriding in the parent type will not be visible in the
12546       --  derivation if we are not in an inner package or in a child unit of
12547       --  the parent type, in which case the abstractness of the inherited
12548       --  operation is carried to the new subprogram.
12549
12550       elsif Is_Abstract_Type (Parent_Type)
12551         and then not In_Open_Scopes (Scope (Parent_Type))
12552         and then Is_Private_Overriding
12553         and then Is_Abstract_Subprogram (Visible_Subp)
12554       then
12555          if No (Actual_Subp) then
12556             Set_Alias (New_Subp, Visible_Subp);
12557             Set_Is_Abstract_Subprogram (New_Subp, True);
12558
12559          else
12560             --  If this is a derivation for an instance of a formal derived
12561             --  type, abstractness comes from the primitive operation of the
12562             --  actual, not from the operation inherited from the ancestor.
12563
12564             Set_Is_Abstract_Subprogram
12565               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
12566          end if;
12567       end if;
12568
12569       New_Overloaded_Entity (New_Subp, Derived_Type);
12570
12571       --  Check for case of a derived subprogram for the instantiation of a
12572       --  formal derived tagged type, if so mark the subprogram as dispatching
12573       --  and inherit the dispatching attributes of the parent subprogram. The
12574       --  derived subprogram is effectively renaming of the actual subprogram,
12575       --  so it needs to have the same attributes as the actual.
12576
12577       if Present (Actual_Subp)
12578         and then Is_Dispatching_Operation (Parent_Subp)
12579       then
12580          Set_Is_Dispatching_Operation (New_Subp);
12581
12582          if Present (DTC_Entity (Parent_Subp)) then
12583             Set_DTC_Entity (New_Subp, DTC_Entity (Parent_Subp));
12584             Set_DT_Position (New_Subp, DT_Position (Parent_Subp));
12585          end if;
12586       end if;
12587
12588       --  Indicate that a derived subprogram does not require a body and that
12589       --  it does not require processing of default expressions.
12590
12591       Set_Has_Completion (New_Subp);
12592       Set_Default_Expressions_Processed (New_Subp);
12593
12594       if Ekind (New_Subp) = E_Function then
12595          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
12596       end if;
12597    end Derive_Subprogram;
12598
12599    ------------------------
12600    -- Derive_Subprograms --
12601    ------------------------
12602
12603    procedure Derive_Subprograms
12604      (Parent_Type    : Entity_Id;
12605       Derived_Type   : Entity_Id;
12606       Generic_Actual : Entity_Id := Empty)
12607    is
12608       Op_List : constant Elist_Id :=
12609                   Collect_Primitive_Operations (Parent_Type);
12610
12611       function Check_Derived_Type return Boolean;
12612       --  Check that all primitive inherited from Parent_Type are found in
12613       --  the list of primitives of Derived_Type exactly in the same order.
12614
12615       function Check_Derived_Type return Boolean is
12616          E        : Entity_Id;
12617          Elmt     : Elmt_Id;
12618          List     : Elist_Id;
12619          New_Subp : Entity_Id;
12620          Op_Elmt  : Elmt_Id;
12621          Subp     : Entity_Id;
12622
12623       begin
12624          --  Traverse list of entities in the current scope searching for
12625          --  an incomplete type whose full-view is derived type
12626
12627          E := First_Entity (Scope (Derived_Type));
12628          while Present (E)
12629            and then E /= Derived_Type
12630          loop
12631             if Ekind (E) = E_Incomplete_Type
12632               and then Present (Full_View (E))
12633               and then Full_View (E) = Derived_Type
12634             then
12635                --  Disable this test if Derived_Type completes an incomplete
12636                --  type because in such case more primitives can be added
12637                --  later to the list of primitives of Derived_Type by routine
12638                --  Process_Incomplete_Dependents
12639
12640                return True;
12641             end if;
12642
12643             E := Next_Entity (E);
12644          end loop;
12645
12646          List := Collect_Primitive_Operations (Derived_Type);
12647          Elmt := First_Elmt (List);
12648
12649          Op_Elmt := First_Elmt (Op_List);
12650          while Present (Op_Elmt) loop
12651             Subp     := Node (Op_Elmt);
12652             New_Subp := Node (Elmt);
12653
12654             --  At this early stage Derived_Type has no entities with attribute
12655             --  Interface_Alias. In addition, such primitives are always
12656             --  located at the end of the list of primitives of Parent_Type.
12657             --  Therefore, if found we can safely stop processing pending
12658             --  entities.
12659
12660             exit when Present (Interface_Alias (Subp));
12661
12662             --  Handle hidden entities
12663
12664             if not Is_Predefined_Dispatching_Operation (Subp)
12665               and then Is_Hidden (Subp)
12666             then
12667                if Present (New_Subp)
12668                  and then Primitive_Names_Match (Subp, New_Subp)
12669                then
12670                   Next_Elmt (Elmt);
12671                end if;
12672
12673             else
12674                if not Present (New_Subp)
12675                  or else Ekind (Subp) /= Ekind (New_Subp)
12676                  or else not Primitive_Names_Match (Subp, New_Subp)
12677                then
12678                   return False;
12679                end if;
12680
12681                Next_Elmt (Elmt);
12682             end if;
12683
12684             Next_Elmt (Op_Elmt);
12685          end loop;
12686
12687          return True;
12688       end Check_Derived_Type;
12689
12690       --  Local variables
12691
12692       Alias_Subp   : Entity_Id;
12693       Act_List     : Elist_Id;
12694       Act_Elmt     : Elmt_Id   := No_Elmt;
12695       Act_Subp     : Entity_Id := Empty;
12696       Elmt         : Elmt_Id;
12697       Need_Search  : Boolean   := False;
12698       New_Subp     : Entity_Id := Empty;
12699       Parent_Base  : Entity_Id;
12700       Subp         : Entity_Id;
12701
12702    --  Start of processing for Derive_Subprograms
12703
12704    begin
12705       if Ekind (Parent_Type) = E_Record_Type_With_Private
12706         and then Has_Discriminants (Parent_Type)
12707         and then Present (Full_View (Parent_Type))
12708       then
12709          Parent_Base := Full_View (Parent_Type);
12710       else
12711          Parent_Base := Parent_Type;
12712       end if;
12713
12714       if Present (Generic_Actual) then
12715          Act_List := Collect_Primitive_Operations (Generic_Actual);
12716          Act_Elmt := First_Elmt (Act_List);
12717       end if;
12718
12719       --  Derive primitives inherited from the parent. Note that if the generic
12720       --  actual is present, this is not really a type derivation, it is a
12721       --  completion within an instance.
12722
12723       --  Case 1: Derived_Type does not implement interfaces
12724
12725       if not Is_Tagged_Type (Derived_Type)
12726         or else (not Has_Interfaces (Derived_Type)
12727                   and then not (Present (Generic_Actual)
12728                                   and then
12729                                 Has_Interfaces (Generic_Actual)))
12730       then
12731          Elmt := First_Elmt (Op_List);
12732          while Present (Elmt) loop
12733             Subp := Node (Elmt);
12734
12735             --  Literals are derived earlier in the process of building the
12736             --  derived type, and are skipped here.
12737
12738             if Ekind (Subp) = E_Enumeration_Literal then
12739                null;
12740
12741             --  The actual is a direct descendant and the common primitive
12742             --  operations appear in the same order.
12743
12744             --  If the generic parent type is present, the derived type is an
12745             --  instance of a formal derived type, and within the instance its
12746             --  operations are those of the actual. We derive from the formal
12747             --  type but make the inherited operations aliases of the
12748             --  corresponding operations of the actual.
12749
12750             else
12751                pragma Assert (No (Node (Act_Elmt))
12752                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
12753                             and then
12754                           Type_Conformant (Subp, Node (Act_Elmt),
12755                                            Skip_Controlling_Formals => True)));
12756
12757                Derive_Subprogram
12758                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
12759
12760                if Present (Act_Elmt) then
12761                   Next_Elmt (Act_Elmt);
12762                end if;
12763             end if;
12764
12765             Next_Elmt (Elmt);
12766          end loop;
12767
12768       --  Case 2: Derived_Type implements interfaces
12769
12770       else
12771          --  If the parent type has no predefined primitives we remove
12772          --  predefined primitives from the list of primitives of generic
12773          --  actual to simplify the complexity of this algorithm.
12774
12775          if Present (Generic_Actual) then
12776             declare
12777                Has_Predefined_Primitives : Boolean := False;
12778
12779             begin
12780                --  Check if the parent type has predefined primitives
12781
12782                Elmt := First_Elmt (Op_List);
12783                while Present (Elmt) loop
12784                   Subp := Node (Elmt);
12785
12786                   if Is_Predefined_Dispatching_Operation (Subp)
12787                     and then not Comes_From_Source (Ultimate_Alias (Subp))
12788                   then
12789                      Has_Predefined_Primitives := True;
12790                      exit;
12791                   end if;
12792
12793                   Next_Elmt (Elmt);
12794                end loop;
12795
12796                --  Remove predefined primitives of Generic_Actual. We must use
12797                --  an auxiliary list because in case of tagged types the value
12798                --  returned by Collect_Primitive_Operations is the value stored
12799                --  in its Primitive_Operations attribute (and we don't want to
12800                --  modify its current contents).
12801
12802                if not Has_Predefined_Primitives then
12803                   declare
12804                      Aux_List : constant Elist_Id := New_Elmt_List;
12805
12806                   begin
12807                      Elmt := First_Elmt (Act_List);
12808                      while Present (Elmt) loop
12809                         Subp := Node (Elmt);
12810
12811                         if not Is_Predefined_Dispatching_Operation (Subp)
12812                           or else Comes_From_Source (Subp)
12813                         then
12814                            Append_Elmt (Subp, Aux_List);
12815                         end if;
12816
12817                         Next_Elmt (Elmt);
12818                      end loop;
12819
12820                      Act_List := Aux_List;
12821                   end;
12822                end if;
12823
12824                Act_Elmt := First_Elmt (Act_List);
12825                Act_Subp := Node (Act_Elmt);
12826             end;
12827          end if;
12828
12829          --  Stage 1: If the generic actual is not present we derive the
12830          --  primitives inherited from the parent type. If the generic parent
12831          --  type is present, the derived type is an instance of a formal
12832          --  derived type, and within the instance its operations are those of
12833          --  the actual. We derive from the formal type but make the inherited
12834          --  operations aliases of the corresponding operations of the actual.
12835
12836          Elmt := First_Elmt (Op_List);
12837          while Present (Elmt) loop
12838             Subp       := Node (Elmt);
12839             Alias_Subp := Ultimate_Alias (Subp);
12840
12841             --  Do not derive internal entities of the parent that link
12842             --  interface primitives and its covering primitive. These
12843             --  entities will be added to this type when frozen.
12844
12845             if Present (Interface_Alias (Subp)) then
12846                goto Continue;
12847             end if;
12848
12849             --  If the generic actual is present find the corresponding
12850             --  operation in the generic actual. If the parent type is a
12851             --  direct ancestor of the derived type then, even if it is an
12852             --  interface, the operations are inherited from the primary
12853             --  dispatch table and are in the proper order. If we detect here
12854             --  that primitives are not in the same order we traverse the list
12855             --  of primitive operations of the actual to find the one that
12856             --  implements the interface primitive.
12857
12858             if Need_Search
12859               or else
12860                 (Present (Generic_Actual)
12861                   and then Present (Act_Subp)
12862                   and then not
12863                     (Primitive_Names_Match (Subp, Act_Subp)
12864                        and then
12865                      Type_Conformant (Subp, Act_Subp,
12866                                       Skip_Controlling_Formals => True)))
12867             then
12868                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual));
12869
12870                --  Remember that we need searching for all pending primitives
12871
12872                Need_Search := True;
12873
12874                --  Handle entities associated with interface primitives
12875
12876                if Present (Alias_Subp)
12877                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
12878                  and then not Is_Predefined_Dispatching_Operation (Subp)
12879                then
12880                   --  Search for the primitive in the homonym chain
12881
12882                   Act_Subp :=
12883                     Find_Primitive_Covering_Interface
12884                       (Tagged_Type => Generic_Actual,
12885                        Iface_Prim  => Alias_Subp);
12886
12887                   --  Previous search may not locate primitives covering
12888                   --  interfaces defined in generics units or instantiations.
12889                   --  (it fails if the covering primitive has formals whose
12890                   --  type is also defined in generics or instantiations).
12891                   --  In such case we search in the list of primitives of the
12892                   --  generic actual for the internal entity that links the
12893                   --  interface primitive and the covering primitive.
12894
12895                   if No (Act_Subp)
12896                     and then Is_Generic_Type (Parent_Type)
12897                   then
12898                      --  This code has been designed to handle only generic
12899                      --  formals that implement interfaces that are defined
12900                      --  in a generic unit or instantiation. If this code is
12901                      --  needed for other cases we must review it because
12902                      --  (given that it relies on Original_Location to locate
12903                      --  the primitive of Generic_Actual that covers the
12904                      --  interface) it could leave linked through attribute
12905                      --  Alias entities of unrelated instantiations).
12906
12907                      pragma Assert
12908                        (Is_Generic_Unit
12909                           (Scope (Find_Dispatching_Type (Alias_Subp)))
12910                        or else
12911                         Instantiation_Depth
12912                           (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
12913
12914                      declare
12915                         Iface_Prim_Loc : constant Source_Ptr :=
12916                                          Original_Location (Sloc (Alias_Subp));
12917                         Elmt      : Elmt_Id;
12918                         Prim      : Entity_Id;
12919                      begin
12920                         Elmt :=
12921                           First_Elmt (Primitive_Operations (Generic_Actual));
12922
12923                         Search : while Present (Elmt) loop
12924                            Prim := Node (Elmt);
12925
12926                            if Present (Interface_Alias (Prim))
12927                              and then Original_Location
12928                                         (Sloc (Interface_Alias (Prim)))
12929                                        = Iface_Prim_Loc
12930                            then
12931                               Act_Subp := Alias (Prim);
12932                               exit Search;
12933                            end if;
12934
12935                            Next_Elmt (Elmt);
12936                         end loop Search;
12937                      end;
12938                   end if;
12939
12940                   pragma Assert (Present (Act_Subp)
12941                     or else Is_Abstract_Type (Generic_Actual)
12942                     or else Serious_Errors_Detected > 0);
12943
12944                --  Handle predefined primitives plus the rest of user-defined
12945                --  primitives
12946
12947                else
12948                   Act_Elmt := First_Elmt (Act_List);
12949                   while Present (Act_Elmt) loop
12950                      Act_Subp := Node (Act_Elmt);
12951
12952                      exit when Primitive_Names_Match (Subp, Act_Subp)
12953                        and then Type_Conformant
12954                                   (Subp, Act_Subp,
12955                                    Skip_Controlling_Formals => True)
12956                        and then No (Interface_Alias (Act_Subp));
12957
12958                      Next_Elmt (Act_Elmt);
12959                   end loop;
12960
12961                   if No (Act_Elmt) then
12962                      Act_Subp := Empty;
12963                   end if;
12964                end if;
12965             end if;
12966
12967             --   Case 1: If the parent is a limited interface then it has the
12968             --   predefined primitives of synchronized interfaces. However, the
12969             --   actual type may be a non-limited type and hence it does not
12970             --   have such primitives.
12971
12972             if Present (Generic_Actual)
12973               and then not Present (Act_Subp)
12974               and then Is_Limited_Interface (Parent_Base)
12975               and then Is_Predefined_Interface_Primitive (Subp)
12976             then
12977                null;
12978
12979             --  Case 2: Inherit entities associated with interfaces that were
12980             --  not covered by the parent type. We exclude here null interface
12981             --  primitives because they do not need special management.
12982
12983             --  We also exclude interface operations that are renamings. If the
12984             --  subprogram is an explicit renaming of an interface primitive,
12985             --  it is a regular primitive operation, and the presence of its
12986             --  alias is not relevant: it has to be derived like any other
12987             --  primitive.
12988
12989             elsif Present (Alias (Subp))
12990               and then Nkind (Unit_Declaration_Node (Subp)) /=
12991                                             N_Subprogram_Renaming_Declaration
12992               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
12993               and then not
12994                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
12995                   and then Null_Present (Parent (Alias_Subp)))
12996             then
12997                Derive_Subprogram
12998                  (New_Subp     => New_Subp,
12999                   Parent_Subp  => Alias_Subp,
13000                   Derived_Type => Derived_Type,
13001                   Parent_Type  => Find_Dispatching_Type (Alias_Subp),
13002                   Actual_Subp  => Act_Subp);
13003
13004                if No (Generic_Actual) then
13005                   Set_Alias (New_Subp, Subp);
13006                end if;
13007
13008             --  Case 3: Common derivation
13009
13010             else
13011                Derive_Subprogram
13012                  (New_Subp     => New_Subp,
13013                   Parent_Subp  => Subp,
13014                   Derived_Type => Derived_Type,
13015                   Parent_Type  => Parent_Base,
13016                   Actual_Subp  => Act_Subp);
13017             end if;
13018
13019             --  No need to update Act_Elm if we must search for the
13020             --  corresponding operation in the generic actual
13021
13022             if not Need_Search
13023               and then Present (Act_Elmt)
13024             then
13025                Next_Elmt (Act_Elmt);
13026                Act_Subp := Node (Act_Elmt);
13027             end if;
13028
13029             <<Continue>>
13030             Next_Elmt (Elmt);
13031          end loop;
13032
13033          --  Inherit additional operations from progenitors. If the derived
13034          --  type is a generic actual, there are not new primitive operations
13035          --  for the type because it has those of the actual, and therefore
13036          --  nothing needs to be done. The renamings generated above are not
13037          --  primitive operations, and their purpose is simply to make the
13038          --  proper operations visible within an instantiation.
13039
13040          if No (Generic_Actual) then
13041             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
13042          end if;
13043       end if;
13044
13045       --  Final check: Direct descendants must have their primitives in the
13046       --  same order. We exclude from this test non-tagged types and instances
13047       --  of formal derived types. We skip this test if we have already
13048       --  reported serious errors in the sources.
13049
13050       pragma Assert (not Is_Tagged_Type (Derived_Type)
13051         or else Present (Generic_Actual)
13052         or else Serious_Errors_Detected > 0
13053         or else Check_Derived_Type);
13054    end Derive_Subprograms;
13055
13056    --------------------------------
13057    -- Derived_Standard_Character --
13058    --------------------------------
13059
13060    procedure Derived_Standard_Character
13061      (N            : Node_Id;
13062       Parent_Type  : Entity_Id;
13063       Derived_Type : Entity_Id)
13064    is
13065       Loc           : constant Source_Ptr := Sloc (N);
13066       Def           : constant Node_Id    := Type_Definition (N);
13067       Indic         : constant Node_Id    := Subtype_Indication (Def);
13068       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
13069       Implicit_Base : constant Entity_Id  :=
13070                         Create_Itype
13071                           (E_Enumeration_Type, N, Derived_Type, 'B');
13072
13073       Lo : Node_Id;
13074       Hi : Node_Id;
13075
13076    begin
13077       Discard_Node (Process_Subtype (Indic, N));
13078
13079       Set_Etype     (Implicit_Base, Parent_Base);
13080       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
13081       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
13082
13083       Set_Is_Character_Type  (Implicit_Base, True);
13084       Set_Has_Delayed_Freeze (Implicit_Base);
13085
13086       --  The bounds of the implicit base are the bounds of the parent base.
13087       --  Note that their type is the parent base.
13088
13089       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
13090       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
13091
13092       Set_Scalar_Range (Implicit_Base,
13093         Make_Range (Loc,
13094           Low_Bound  => Lo,
13095           High_Bound => Hi));
13096
13097       Conditional_Delay (Derived_Type, Parent_Type);
13098
13099       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
13100       Set_Etype (Derived_Type, Implicit_Base);
13101       Set_Size_Info         (Derived_Type, Parent_Type);
13102
13103       if Unknown_RM_Size (Derived_Type) then
13104          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
13105       end if;
13106
13107       Set_Is_Character_Type (Derived_Type, True);
13108
13109       if Nkind (Indic) /= N_Subtype_Indication then
13110
13111          --  If no explicit constraint, the bounds are those
13112          --  of the parent type.
13113
13114          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
13115          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
13116          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
13117       end if;
13118
13119       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
13120
13121       --  Because the implicit base is used in the conversion of the bounds, we
13122       --  have to freeze it now. This is similar to what is done for numeric
13123       --  types, and it equally suspicious, but otherwise a non-static bound
13124       --  will have a reference to an unfrozen type, which is rejected by Gigi
13125       --  (???). This requires specific care for definition of stream
13126       --  attributes. For details, see comments at the end of
13127       --  Build_Derived_Numeric_Type.
13128
13129       Freeze_Before (N, Implicit_Base);
13130    end Derived_Standard_Character;
13131
13132    ------------------------------
13133    -- Derived_Type_Declaration --
13134    ------------------------------
13135
13136    procedure Derived_Type_Declaration
13137      (T             : Entity_Id;
13138       N             : Node_Id;
13139       Is_Completion : Boolean)
13140    is
13141       Parent_Type  : Entity_Id;
13142
13143       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
13144       --  Check whether the parent type is a generic formal, or derives
13145       --  directly or indirectly from one.
13146
13147       ------------------------
13148       -- Comes_From_Generic --
13149       ------------------------
13150
13151       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
13152       begin
13153          if Is_Generic_Type (Typ) then
13154             return True;
13155
13156          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
13157             return True;
13158
13159          elsif Is_Private_Type (Typ)
13160            and then Present (Full_View (Typ))
13161            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
13162          then
13163             return True;
13164
13165          elsif Is_Generic_Actual_Type (Typ) then
13166             return True;
13167
13168          else
13169             return False;
13170          end if;
13171       end Comes_From_Generic;
13172
13173       --  Local variables
13174
13175       Def          : constant Node_Id := Type_Definition (N);
13176       Iface_Def    : Node_Id;
13177       Indic        : constant Node_Id := Subtype_Indication (Def);
13178       Extension    : constant Node_Id := Record_Extension_Part (Def);
13179       Parent_Node  : Node_Id;
13180       Parent_Scope : Entity_Id;
13181       Taggd        : Boolean;
13182
13183    --  Start of processing for Derived_Type_Declaration
13184
13185    begin
13186       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
13187
13188       --  Ada 2005 (AI-251): In case of interface derivation check that the
13189       --  parent is also an interface.
13190
13191       if Interface_Present (Def) then
13192          if not Is_Interface (Parent_Type) then
13193             Diagnose_Interface (Indic, Parent_Type);
13194
13195          else
13196             Parent_Node := Parent (Base_Type (Parent_Type));
13197             Iface_Def   := Type_Definition (Parent_Node);
13198
13199             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
13200             --  other limited interfaces.
13201
13202             if Limited_Present (Def) then
13203                if Limited_Present (Iface_Def) then
13204                   null;
13205
13206                elsif Protected_Present (Iface_Def) then
13207                   Error_Msg_NE
13208                     ("descendant of& must be declared"
13209                        & " as a protected interface",
13210                          N, Parent_Type);
13211
13212                elsif Synchronized_Present (Iface_Def) then
13213                   Error_Msg_NE
13214                     ("descendant of& must be declared"
13215                        & " as a synchronized interface",
13216                          N, Parent_Type);
13217
13218                elsif Task_Present (Iface_Def) then
13219                   Error_Msg_NE
13220                     ("descendant of& must be declared as a task interface",
13221                        N, Parent_Type);
13222
13223                else
13224                   Error_Msg_N
13225                     ("(Ada 2005) limited interface cannot "
13226                      & "inherit from non-limited interface", Indic);
13227                end if;
13228
13229             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
13230             --  from non-limited or limited interfaces.
13231
13232             elsif not Protected_Present (Def)
13233               and then not Synchronized_Present (Def)
13234               and then not Task_Present (Def)
13235             then
13236                if Limited_Present (Iface_Def) then
13237                   null;
13238
13239                elsif Protected_Present (Iface_Def) then
13240                   Error_Msg_NE
13241                     ("descendant of& must be declared"
13242                        & " as a protected interface",
13243                          N, Parent_Type);
13244
13245                elsif Synchronized_Present (Iface_Def) then
13246                   Error_Msg_NE
13247                     ("descendant of& must be declared"
13248                        & " as a synchronized interface",
13249                          N, Parent_Type);
13250
13251                elsif Task_Present (Iface_Def) then
13252                   Error_Msg_NE
13253                     ("descendant of& must be declared as a task interface",
13254                        N, Parent_Type);
13255                else
13256                   null;
13257                end if;
13258             end if;
13259          end if;
13260       end if;
13261
13262       if Is_Tagged_Type (Parent_Type)
13263         and then Is_Concurrent_Type (Parent_Type)
13264         and then not Is_Interface (Parent_Type)
13265       then
13266          Error_Msg_N
13267            ("parent type of a record extension cannot be "
13268             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
13269          Set_Etype (T, Any_Type);
13270          return;
13271       end if;
13272
13273       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
13274       --  interfaces
13275
13276       if Is_Tagged_Type (Parent_Type)
13277         and then Is_Non_Empty_List (Interface_List (Def))
13278       then
13279          declare
13280             Intf : Node_Id;
13281             T    : Entity_Id;
13282
13283          begin
13284             Intf := First (Interface_List (Def));
13285             while Present (Intf) loop
13286                T := Find_Type_Of_Subtype_Indic (Intf);
13287
13288                if not Is_Interface (T) then
13289                   Diagnose_Interface (Intf, T);
13290
13291                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
13292                --  a limited type from having a nonlimited progenitor.
13293
13294                elsif (Limited_Present (Def)
13295                        or else (not Is_Interface (Parent_Type)
13296                                  and then Is_Limited_Type (Parent_Type)))
13297                  and then not Is_Limited_Interface (T)
13298                then
13299                   Error_Msg_NE
13300                    ("progenitor interface& of limited type must be limited",
13301                      N, T);
13302                end if;
13303
13304                Next (Intf);
13305             end loop;
13306          end;
13307       end if;
13308
13309       if Parent_Type = Any_Type
13310         or else Etype (Parent_Type) = Any_Type
13311         or else (Is_Class_Wide_Type (Parent_Type)
13312                    and then Etype (Parent_Type) = T)
13313       then
13314          --  If Parent_Type is undefined or illegal, make new type into a
13315          --  subtype of Any_Type, and set a few attributes to prevent cascaded
13316          --  errors. If this is a self-definition, emit error now.
13317
13318          if T = Parent_Type
13319            or else T = Etype (Parent_Type)
13320          then
13321             Error_Msg_N ("type cannot be used in its own definition", Indic);
13322          end if;
13323
13324          Set_Ekind        (T, Ekind (Parent_Type));
13325          Set_Etype        (T, Any_Type);
13326          Set_Scalar_Range (T, Scalar_Range (Any_Type));
13327
13328          if Is_Tagged_Type (T) then
13329             Set_Primitive_Operations (T, New_Elmt_List);
13330          end if;
13331
13332          return;
13333       end if;
13334
13335       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
13336       --  an interface is special because the list of interfaces in the full
13337       --  view can be given in any order. For example:
13338
13339       --     type A is interface;
13340       --     type B is interface and A;
13341       --     type D is new B with private;
13342       --   private
13343       --     type D is new A and B with null record; -- 1 --
13344
13345       --  In this case we perform the following transformation of -1-:
13346
13347       --     type D is new B and A with null record;
13348
13349       --  If the parent of the full-view covers the parent of the partial-view
13350       --  we have two possible cases:
13351
13352       --     1) They have the same parent
13353       --     2) The parent of the full-view implements some further interfaces
13354
13355       --  In both cases we do not need to perform the transformation. In the
13356       --  first case the source program is correct and the transformation is
13357       --  not needed; in the second case the source program does not fulfill
13358       --  the no-hidden interfaces rule (AI-396) and the error will be reported
13359       --  later.
13360
13361       --  This transformation not only simplifies the rest of the analysis of
13362       --  this type declaration but also simplifies the correct generation of
13363       --  the object layout to the expander.
13364
13365       if In_Private_Part (Current_Scope)
13366         and then Is_Interface (Parent_Type)
13367       then
13368          declare
13369             Iface               : Node_Id;
13370             Partial_View        : Entity_Id;
13371             Partial_View_Parent : Entity_Id;
13372             New_Iface           : Node_Id;
13373
13374          begin
13375             --  Look for the associated private type declaration
13376
13377             Partial_View := First_Entity (Current_Scope);
13378             loop
13379                exit when No (Partial_View)
13380                  or else (Has_Private_Declaration (Partial_View)
13381                            and then Full_View (Partial_View) = T);
13382
13383                Next_Entity (Partial_View);
13384             end loop;
13385
13386             --  If the partial view was not found then the source code has
13387             --  errors and the transformation is not needed.
13388
13389             if Present (Partial_View) then
13390                Partial_View_Parent := Etype (Partial_View);
13391
13392                --  If the parent of the full-view covers the parent of the
13393                --  partial-view we have nothing else to do.
13394
13395                if Interface_Present_In_Ancestor
13396                     (Parent_Type, Partial_View_Parent)
13397                then
13398                   null;
13399
13400                --  Traverse the list of interfaces of the full-view to look
13401                --  for the parent of the partial-view and perform the tree
13402                --  transformation.
13403
13404                else
13405                   Iface := First (Interface_List (Def));
13406                   while Present (Iface) loop
13407                      if Etype (Iface) = Etype (Partial_View) then
13408                         Rewrite (Subtype_Indication (Def),
13409                           New_Copy (Subtype_Indication
13410                                      (Parent (Partial_View))));
13411
13412                         New_Iface := Make_Identifier (Sloc (N),
13413                                        Chars (Parent_Type));
13414                         Append (New_Iface, Interface_List (Def));
13415
13416                         --  Analyze the transformed code
13417
13418                         Derived_Type_Declaration (T, N, Is_Completion);
13419                         return;
13420                      end if;
13421
13422                      Next (Iface);
13423                   end loop;
13424                end if;
13425             end if;
13426          end;
13427       end if;
13428
13429       --  Only composite types other than array types are allowed to have
13430       --  discriminants.
13431
13432       if Present (Discriminant_Specifications (N))
13433         and then (Is_Elementary_Type (Parent_Type)
13434                   or else Is_Array_Type (Parent_Type))
13435         and then not Error_Posted (N)
13436       then
13437          Error_Msg_N
13438            ("elementary or array type cannot have discriminants",
13439             Defining_Identifier (First (Discriminant_Specifications (N))));
13440          Set_Has_Discriminants (T, False);
13441       end if;
13442
13443       --  In Ada 83, a derived type defined in a package specification cannot
13444       --  be used for further derivation until the end of its visible part.
13445       --  Note that derivation in the private part of the package is allowed.
13446
13447       if Ada_Version = Ada_83
13448         and then Is_Derived_Type (Parent_Type)
13449         and then In_Visible_Part (Scope (Parent_Type))
13450       then
13451          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
13452             Error_Msg_N
13453               ("(Ada 83): premature use of type for derivation", Indic);
13454          end if;
13455       end if;
13456
13457       --  Check for early use of incomplete or private type
13458
13459       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
13460          Error_Msg_N ("premature derivation of incomplete type", Indic);
13461          return;
13462
13463       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
13464               and then not Comes_From_Generic (Parent_Type))
13465         or else Has_Private_Component (Parent_Type)
13466       then
13467          --  The ancestor type of a formal type can be incomplete, in which
13468          --  case only the operations of the partial view are available in
13469          --  the generic. Subsequent checks may be required when the full
13470          --  view is analyzed, to verify that derivation from a tagged type
13471          --  has an extension.
13472
13473          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
13474             null;
13475
13476          elsif No (Underlying_Type (Parent_Type))
13477            or else Has_Private_Component (Parent_Type)
13478          then
13479             Error_Msg_N
13480               ("premature derivation of derived or private type", Indic);
13481
13482             --  Flag the type itself as being in error, this prevents some
13483             --  nasty problems with subsequent uses of the malformed type.
13484
13485             Set_Error_Posted (T);
13486
13487          --  Check that within the immediate scope of an untagged partial
13488          --  view it's illegal to derive from the partial view if the
13489          --  full view is tagged. (7.3(7))
13490
13491          --  We verify that the Parent_Type is a partial view by checking
13492          --  that it is not a Full_Type_Declaration (i.e. a private type or
13493          --  private extension declaration), to distinguish a partial view
13494          --  from  a derivation from a private type which also appears as
13495          --  E_Private_Type.
13496
13497          elsif Present (Full_View (Parent_Type))
13498            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
13499            and then not Is_Tagged_Type (Parent_Type)
13500            and then Is_Tagged_Type (Full_View (Parent_Type))
13501          then
13502             Parent_Scope := Scope (T);
13503             while Present (Parent_Scope)
13504               and then Parent_Scope /= Standard_Standard
13505             loop
13506                if Parent_Scope = Scope (Parent_Type) then
13507                   Error_Msg_N
13508                     ("premature derivation from type with tagged full view",
13509                      Indic);
13510                end if;
13511
13512                Parent_Scope := Scope (Parent_Scope);
13513             end loop;
13514          end if;
13515       end if;
13516
13517       --  Check that form of derivation is appropriate
13518
13519       Taggd := Is_Tagged_Type (Parent_Type);
13520
13521       --  Perhaps the parent type should be changed to the class-wide type's
13522       --  specific type in this case to prevent cascading errors ???
13523
13524       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
13525          Error_Msg_N ("parent type must not be a class-wide type", Indic);
13526          return;
13527       end if;
13528
13529       if Present (Extension) and then not Taggd then
13530          Error_Msg_N
13531            ("type derived from untagged type cannot have extension", Indic);
13532
13533       elsif No (Extension) and then Taggd then
13534
13535          --  If this declaration is within a private part (or body) of a
13536          --  generic instantiation then the derivation is allowed (the parent
13537          --  type can only appear tagged in this case if it's a generic actual
13538          --  type, since it would otherwise have been rejected in the analysis
13539          --  of the generic template).
13540
13541          if not Is_Generic_Actual_Type (Parent_Type)
13542            or else In_Visible_Part (Scope (Parent_Type))
13543          then
13544             if Is_Class_Wide_Type (Parent_Type) then
13545                Error_Msg_N
13546                  ("parent type must not be a class-wide type", Indic);
13547
13548                --  Use specific type to prevent cascaded errors.
13549
13550                Parent_Type := Etype (Parent_Type);
13551
13552             else
13553                Error_Msg_N
13554                  ("type derived from tagged type must have extension", Indic);
13555             end if;
13556          end if;
13557       end if;
13558
13559       --  AI-443: Synchronized formal derived types require a private
13560       --  extension. There is no point in checking the ancestor type or
13561       --  the progenitors since the construct is wrong to begin with.
13562
13563       if Ada_Version >= Ada_05
13564         and then Is_Generic_Type (T)
13565         and then Present (Original_Node (N))
13566       then
13567          declare
13568             Decl : constant Node_Id := Original_Node (N);
13569
13570          begin
13571             if Nkind (Decl) = N_Formal_Type_Declaration
13572               and then Nkind (Formal_Type_Definition (Decl)) =
13573                          N_Formal_Derived_Type_Definition
13574               and then Synchronized_Present (Formal_Type_Definition (Decl))
13575               and then No (Extension)
13576
13577                --  Avoid emitting a duplicate error message
13578
13579               and then not Error_Posted (Indic)
13580             then
13581                Error_Msg_N
13582                  ("synchronized derived type must have extension", N);
13583             end if;
13584          end;
13585       end if;
13586
13587       if Null_Exclusion_Present (Def)
13588         and then not Is_Access_Type (Parent_Type)
13589       then
13590          Error_Msg_N ("null exclusion can only apply to an access type", N);
13591       end if;
13592
13593       --  Avoid deriving parent primitives of underlying record views
13594
13595       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
13596         Derive_Subps => not Is_Underlying_Record_View (T));
13597
13598       --  AI-419: The parent type of an explicitly limited derived type must
13599       --  be a limited type or a limited interface.
13600
13601       if Limited_Present (Def) then
13602          Set_Is_Limited_Record (T);
13603
13604          if Is_Interface (T) then
13605             Set_Is_Limited_Interface (T);
13606          end if;
13607
13608          if not Is_Limited_Type (Parent_Type)
13609            and then
13610              (not Is_Interface (Parent_Type)
13611                or else not Is_Limited_Interface (Parent_Type))
13612          then
13613             Error_Msg_NE
13614               ("parent type& of limited type must be limited",
13615                N, Parent_Type);
13616          end if;
13617       end if;
13618    end Derived_Type_Declaration;
13619
13620    ------------------------
13621    -- Diagnose_Interface --
13622    ------------------------
13623
13624    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
13625    begin
13626       if not Is_Interface (E)
13627         and then  E /= Any_Type
13628       then
13629          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
13630       end if;
13631    end Diagnose_Interface;
13632
13633    ----------------------------------
13634    -- Enumeration_Type_Declaration --
13635    ----------------------------------
13636
13637    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
13638       Ev     : Uint;
13639       L      : Node_Id;
13640       R_Node : Node_Id;
13641       B_Node : Node_Id;
13642
13643    begin
13644       --  Create identifier node representing lower bound
13645
13646       B_Node := New_Node (N_Identifier, Sloc (Def));
13647       L := First (Literals (Def));
13648       Set_Chars (B_Node, Chars (L));
13649       Set_Entity (B_Node,  L);
13650       Set_Etype (B_Node, T);
13651       Set_Is_Static_Expression (B_Node, True);
13652
13653       R_Node := New_Node (N_Range, Sloc (Def));
13654       Set_Low_Bound  (R_Node, B_Node);
13655
13656       Set_Ekind (T, E_Enumeration_Type);
13657       Set_First_Literal (T, L);
13658       Set_Etype (T, T);
13659       Set_Is_Constrained (T);
13660
13661       Ev := Uint_0;
13662
13663       --  Loop through literals of enumeration type setting pos and rep values
13664       --  except that if the Ekind is already set, then it means the literal
13665       --  was already constructed (case of a derived type declaration and we
13666       --  should not disturb the Pos and Rep values.
13667
13668       while Present (L) loop
13669          if Ekind (L) /= E_Enumeration_Literal then
13670             Set_Ekind (L, E_Enumeration_Literal);
13671             Set_Enumeration_Pos (L, Ev);
13672             Set_Enumeration_Rep (L, Ev);
13673             Set_Is_Known_Valid  (L, True);
13674          end if;
13675
13676          Set_Etype (L, T);
13677          New_Overloaded_Entity (L);
13678          Generate_Definition (L);
13679          Set_Convention (L, Convention_Intrinsic);
13680
13681          --  Case of character literal
13682
13683          if Nkind (L) = N_Defining_Character_Literal then
13684             Set_Is_Character_Type (T, True);
13685
13686             --  Check violation of No_Wide_Characters
13687
13688             if Restriction_Check_Required (No_Wide_Characters) then
13689                Get_Name_String (Chars (L));
13690
13691                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
13692                   Check_Restriction (No_Wide_Characters, L);
13693                end if;
13694             end if;
13695          end if;
13696
13697          Ev := Ev + 1;
13698          Next (L);
13699       end loop;
13700
13701       --  Now create a node representing upper bound
13702
13703       B_Node := New_Node (N_Identifier, Sloc (Def));
13704       Set_Chars (B_Node, Chars (Last (Literals (Def))));
13705       Set_Entity (B_Node,  Last (Literals (Def)));
13706       Set_Etype (B_Node, T);
13707       Set_Is_Static_Expression (B_Node, True);
13708
13709       Set_High_Bound (R_Node, B_Node);
13710
13711       --  Initialize various fields of the type. Some of this information
13712       --  may be overwritten later through rep.clauses.
13713
13714       Set_Scalar_Range    (T, R_Node);
13715       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
13716       Set_Enum_Esize      (T);
13717       Set_Enum_Pos_To_Rep (T, Empty);
13718
13719       --  Set Discard_Names if configuration pragma set, or if there is
13720       --  a parameterless pragma in the current declarative region
13721
13722       if Global_Discard_Names
13723         or else Discard_Names (Scope (T))
13724       then
13725          Set_Discard_Names (T);
13726       end if;
13727
13728       --  Process end label if there is one
13729
13730       if Present (Def) then
13731          Process_End_Label (Def, 'e', T);
13732       end if;
13733    end Enumeration_Type_Declaration;
13734
13735    ---------------------------------
13736    -- Expand_To_Stored_Constraint --
13737    ---------------------------------
13738
13739    function Expand_To_Stored_Constraint
13740      (Typ        : Entity_Id;
13741       Constraint : Elist_Id) return Elist_Id
13742    is
13743       Explicitly_Discriminated_Type : Entity_Id;
13744       Expansion    : Elist_Id;
13745       Discriminant : Entity_Id;
13746
13747       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
13748       --  Find the nearest type that actually specifies discriminants
13749
13750       ---------------------------------
13751       -- Type_With_Explicit_Discrims --
13752       ---------------------------------
13753
13754       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
13755          Typ : constant E := Base_Type (Id);
13756
13757       begin
13758          if Ekind (Typ) in Incomplete_Or_Private_Kind then
13759             if Present (Full_View (Typ)) then
13760                return Type_With_Explicit_Discrims (Full_View (Typ));
13761             end if;
13762
13763          else
13764             if Has_Discriminants (Typ) then
13765                return Typ;
13766             end if;
13767          end if;
13768
13769          if Etype (Typ) = Typ then
13770             return Empty;
13771          elsif Has_Discriminants (Typ) then
13772             return Typ;
13773          else
13774             return Type_With_Explicit_Discrims (Etype (Typ));
13775          end if;
13776
13777       end Type_With_Explicit_Discrims;
13778
13779    --  Start of processing for Expand_To_Stored_Constraint
13780
13781    begin
13782       if No (Constraint)
13783         or else Is_Empty_Elmt_List (Constraint)
13784       then
13785          return No_Elist;
13786       end if;
13787
13788       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
13789
13790       if No (Explicitly_Discriminated_Type) then
13791          return No_Elist;
13792       end if;
13793
13794       Expansion := New_Elmt_List;
13795
13796       Discriminant :=
13797          First_Stored_Discriminant (Explicitly_Discriminated_Type);
13798       while Present (Discriminant) loop
13799          Append_Elmt (
13800            Get_Discriminant_Value (
13801              Discriminant, Explicitly_Discriminated_Type, Constraint),
13802            Expansion);
13803          Next_Stored_Discriminant (Discriminant);
13804       end loop;
13805
13806       return Expansion;
13807    end Expand_To_Stored_Constraint;
13808
13809    ---------------------------
13810    -- Find_Hidden_Interface --
13811    ---------------------------
13812
13813    function Find_Hidden_Interface
13814      (Src  : Elist_Id;
13815       Dest : Elist_Id) return Entity_Id
13816    is
13817       Iface      : Entity_Id;
13818       Iface_Elmt : Elmt_Id;
13819
13820    begin
13821       if Present (Src) and then Present (Dest) then
13822          Iface_Elmt := First_Elmt (Src);
13823          while Present (Iface_Elmt) loop
13824             Iface := Node (Iface_Elmt);
13825
13826             if Is_Interface (Iface)
13827               and then not Contain_Interface (Iface, Dest)
13828             then
13829                return Iface;
13830             end if;
13831
13832             Next_Elmt (Iface_Elmt);
13833          end loop;
13834       end if;
13835
13836       return Empty;
13837    end Find_Hidden_Interface;
13838
13839    --------------------
13840    -- Find_Type_Name --
13841    --------------------
13842
13843    function Find_Type_Name (N : Node_Id) return Entity_Id is
13844       Id       : constant Entity_Id := Defining_Identifier (N);
13845       Prev     : Entity_Id;
13846       New_Id   : Entity_Id;
13847       Prev_Par : Node_Id;
13848
13849       procedure Tag_Mismatch;
13850       --  Diagnose a tagged partial view whose full view is untagged.
13851       --  We post the message on the full view, with a reference to
13852       --  the previous partial view. The partial view can be private
13853       --  or incomplete, and these are handled in a different manner,
13854       --  so we determine the position of the error message from the
13855       --  respective slocs of both.
13856
13857       ------------------
13858       -- Tag_Mismatch --
13859       ------------------
13860
13861       procedure Tag_Mismatch is
13862       begin
13863          if Sloc (Prev) < Sloc (Id) then
13864             Error_Msg_NE
13865               ("full declaration of } must be a tagged type ", Id, Prev);
13866          else
13867             Error_Msg_NE
13868               ("full declaration of } must be a tagged type ", Prev, Id);
13869          end if;
13870       end Tag_Mismatch;
13871
13872    --  Start of processing for Find_Type_Name
13873
13874    begin
13875       --  Find incomplete declaration, if one was given
13876
13877       Prev := Current_Entity_In_Scope (Id);
13878
13879       if Present (Prev) then
13880
13881          --  Previous declaration exists. Error if not incomplete/private case
13882          --  except if previous declaration is implicit, etc. Enter_Name will
13883          --  emit error if appropriate.
13884
13885          Prev_Par := Parent (Prev);
13886
13887          if not Is_Incomplete_Or_Private_Type (Prev) then
13888             Enter_Name (Id);
13889             New_Id := Id;
13890
13891          elsif not Nkind_In (N, N_Full_Type_Declaration,
13892                                 N_Task_Type_Declaration,
13893                                 N_Protected_Type_Declaration)
13894          then
13895             --  Completion must be a full type declarations (RM 7.3(4))
13896
13897             Error_Msg_Sloc := Sloc (Prev);
13898             Error_Msg_NE ("invalid completion of }", Id, Prev);
13899
13900             --  Set scope of Id to avoid cascaded errors. Entity is never
13901             --  examined again, except when saving globals in generics.
13902
13903             Set_Scope (Id, Current_Scope);
13904             New_Id := Id;
13905
13906             --  If this is a repeated incomplete declaration, no further
13907             --  checks are possible.
13908
13909             if Nkind (N) = N_Incomplete_Type_Declaration then
13910                return Prev;
13911             end if;
13912
13913          --  Case of full declaration of incomplete type
13914
13915          elsif Ekind (Prev) = E_Incomplete_Type then
13916
13917             --  Indicate that the incomplete declaration has a matching full
13918             --  declaration. The defining occurrence of the incomplete
13919             --  declaration remains the visible one, and the procedure
13920             --  Get_Full_View dereferences it whenever the type is used.
13921
13922             if Present (Full_View (Prev)) then
13923                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
13924             end if;
13925
13926             Set_Full_View (Prev,  Id);
13927             Append_Entity (Id, Current_Scope);
13928             Set_Is_Public (Id, Is_Public (Prev));
13929             Set_Is_Internal (Id);
13930             New_Id := Prev;
13931
13932          --  Case of full declaration of private type
13933
13934          else
13935             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
13936                if Etype (Prev) /= Prev then
13937
13938                   --  Prev is a private subtype or a derived type, and needs
13939                   --  no completion.
13940
13941                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
13942                   New_Id := Id;
13943
13944                elsif Ekind (Prev) = E_Private_Type
13945                  and then Nkind_In (N, N_Task_Type_Declaration,
13946                                        N_Protected_Type_Declaration)
13947                then
13948                   Error_Msg_N
13949                    ("completion of nonlimited type cannot be limited", N);
13950
13951                elsif Ekind (Prev) = E_Record_Type_With_Private
13952                  and then Nkind_In (N, N_Task_Type_Declaration,
13953                                        N_Protected_Type_Declaration)
13954                then
13955                   if not Is_Limited_Record (Prev) then
13956                      Error_Msg_N
13957                         ("completion of nonlimited type cannot be limited", N);
13958
13959                   elsif No (Interface_List (N)) then
13960                      Error_Msg_N
13961                         ("completion of tagged private type must be tagged",
13962                          N);
13963                   end if;
13964
13965                elsif Nkind (N) = N_Full_Type_Declaration
13966                  and then
13967                    Nkind (Type_Definition (N)) = N_Record_Definition
13968                  and then Interface_Present (Type_Definition (N))
13969                then
13970                   Error_Msg_N
13971                     ("completion of private type cannot be an interface", N);
13972                end if;
13973
13974             --  Ada 2005 (AI-251): Private extension declaration of a task
13975             --  type or a protected type. This case arises when covering
13976             --  interface types.
13977
13978             elsif Nkind_In (N, N_Task_Type_Declaration,
13979                                N_Protected_Type_Declaration)
13980             then
13981                null;
13982
13983             elsif Nkind (N) /= N_Full_Type_Declaration
13984               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
13985             then
13986                Error_Msg_N
13987                  ("full view of private extension must be an extension", N);
13988
13989             elsif not (Abstract_Present (Parent (Prev)))
13990               and then Abstract_Present (Type_Definition (N))
13991             then
13992                Error_Msg_N
13993                  ("full view of non-abstract extension cannot be abstract", N);
13994             end if;
13995
13996             if not In_Private_Part (Current_Scope) then
13997                Error_Msg_N
13998                  ("declaration of full view must appear in private part", N);
13999             end if;
14000
14001             Copy_And_Swap (Prev, Id);
14002             Set_Has_Private_Declaration (Prev);
14003             Set_Has_Private_Declaration (Id);
14004
14005             --  If no error, propagate freeze_node from private to full view.
14006             --  It may have been generated for an early operational item.
14007
14008             if Present (Freeze_Node (Id))
14009               and then Serious_Errors_Detected = 0
14010               and then No (Full_View (Id))
14011             then
14012                Set_Freeze_Node (Prev, Freeze_Node (Id));
14013                Set_Freeze_Node (Id, Empty);
14014                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
14015             end if;
14016
14017             Set_Full_View (Id, Prev);
14018             New_Id := Prev;
14019          end if;
14020
14021          --  Verify that full declaration conforms to partial one
14022
14023          if Is_Incomplete_Or_Private_Type (Prev)
14024            and then Present (Discriminant_Specifications (Prev_Par))
14025          then
14026             if Present (Discriminant_Specifications (N)) then
14027                if Ekind (Prev) = E_Incomplete_Type then
14028                   Check_Discriminant_Conformance (N, Prev, Prev);
14029                else
14030                   Check_Discriminant_Conformance (N, Prev, Id);
14031                end if;
14032
14033             else
14034                Error_Msg_N
14035                  ("missing discriminants in full type declaration", N);
14036
14037                --  To avoid cascaded errors on subsequent use, share the
14038                --  discriminants of the partial view.
14039
14040                Set_Discriminant_Specifications (N,
14041                  Discriminant_Specifications (Prev_Par));
14042             end if;
14043          end if;
14044
14045          --  A prior untagged partial view can have an associated class-wide
14046          --  type due to use of the class attribute, and in this case the full
14047          --  type must also be tagged. This Ada 95 usage is deprecated in favor
14048          --  of incomplete tagged declarations, but we check for it.
14049
14050          if Is_Type (Prev)
14051            and then (Is_Tagged_Type (Prev)
14052                       or else Present (Class_Wide_Type (Prev)))
14053          then
14054             --  The full declaration is either a tagged type (including
14055             --  a synchronized type that implements interfaces) or a
14056             --  type extension, otherwise this is an error.
14057
14058             if Nkind_In (N, N_Task_Type_Declaration,
14059                             N_Protected_Type_Declaration)
14060             then
14061                if No (Interface_List (N))
14062                  and then not Error_Posted (N)
14063                then
14064                   Tag_Mismatch;
14065                end if;
14066
14067             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
14068
14069                --  Indicate that the previous declaration (tagged incomplete
14070                --  or private declaration) requires the same on the full one.
14071
14072                if not Tagged_Present (Type_Definition (N)) then
14073                   Tag_Mismatch;
14074                   Set_Is_Tagged_Type (Id);
14075                   Set_Primitive_Operations (Id, New_Elmt_List);
14076                end if;
14077
14078             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
14079                if No (Record_Extension_Part (Type_Definition (N))) then
14080                   Error_Msg_NE
14081                     ("full declaration of } must be a record extension",
14082                      Prev, Id);
14083
14084                   --  Set some attributes to produce a usable full view
14085
14086                   Set_Is_Tagged_Type (Id);
14087                   Set_Primitive_Operations (Id, New_Elmt_List);
14088                end if;
14089
14090             else
14091                Tag_Mismatch;
14092             end if;
14093          end if;
14094
14095          return New_Id;
14096
14097       else
14098          --  New type declaration
14099
14100          Enter_Name (Id);
14101          return Id;
14102       end if;
14103    end Find_Type_Name;
14104
14105    -------------------------
14106    -- Find_Type_Of_Object --
14107    -------------------------
14108
14109    function Find_Type_Of_Object
14110      (Obj_Def     : Node_Id;
14111       Related_Nod : Node_Id) return Entity_Id
14112    is
14113       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
14114       P        : Node_Id := Parent (Obj_Def);
14115       T        : Entity_Id;
14116       Nam      : Name_Id;
14117
14118    begin
14119       --  If the parent is a component_definition node we climb to the
14120       --  component_declaration node
14121
14122       if Nkind (P) = N_Component_Definition then
14123          P := Parent (P);
14124       end if;
14125
14126       --  Case of an anonymous array subtype
14127
14128       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
14129                              N_Unconstrained_Array_Definition)
14130       then
14131          T := Empty;
14132          Array_Type_Declaration (T, Obj_Def);
14133
14134       --  Create an explicit subtype whenever possible
14135
14136       elsif Nkind (P) /= N_Component_Declaration
14137         and then Def_Kind = N_Subtype_Indication
14138       then
14139          --  Base name of subtype on object name, which will be unique in
14140          --  the current scope.
14141
14142          --  If this is a duplicate declaration, return base type, to avoid
14143          --  generating duplicate anonymous types.
14144
14145          if Error_Posted (P) then
14146             Analyze (Subtype_Mark (Obj_Def));
14147             return Entity (Subtype_Mark (Obj_Def));
14148          end if;
14149
14150          Nam :=
14151             New_External_Name
14152              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
14153
14154          T := Make_Defining_Identifier (Sloc (P), Nam);
14155
14156          Insert_Action (Obj_Def,
14157            Make_Subtype_Declaration (Sloc (P),
14158              Defining_Identifier => T,
14159              Subtype_Indication  => Relocate_Node (Obj_Def)));
14160
14161          --  This subtype may need freezing, and this will not be done
14162          --  automatically if the object declaration is not in declarative
14163          --  part. Since this is an object declaration, the type cannot always
14164          --  be frozen here. Deferred constants do not freeze their type
14165          --  (which often enough will be private).
14166
14167          if Nkind (P) = N_Object_Declaration
14168            and then Constant_Present (P)
14169            and then No (Expression (P))
14170          then
14171             null;
14172          else
14173             Insert_Actions (Obj_Def, Freeze_Entity (T, Sloc (P)));
14174          end if;
14175
14176       --  Ada 2005 AI-406: the object definition in an object declaration
14177       --  can be an access definition.
14178
14179       elsif Def_Kind = N_Access_Definition then
14180          T := Access_Definition (Related_Nod, Obj_Def);
14181          Set_Is_Local_Anonymous_Access (T);
14182
14183       --  Otherwise, the object definition is just a subtype_mark
14184
14185       else
14186          T := Process_Subtype (Obj_Def, Related_Nod);
14187       end if;
14188
14189       return T;
14190    end Find_Type_Of_Object;
14191
14192    --------------------------------
14193    -- Find_Type_Of_Subtype_Indic --
14194    --------------------------------
14195
14196    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
14197       Typ : Entity_Id;
14198
14199    begin
14200       --  Case of subtype mark with a constraint
14201
14202       if Nkind (S) = N_Subtype_Indication then
14203          Find_Type (Subtype_Mark (S));
14204          Typ := Entity (Subtype_Mark (S));
14205
14206          if not
14207            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
14208          then
14209             Error_Msg_N
14210               ("incorrect constraint for this kind of type", Constraint (S));
14211             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
14212          end if;
14213
14214       --  Otherwise we have a subtype mark without a constraint
14215
14216       elsif Error_Posted (S) then
14217          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
14218          return Any_Type;
14219
14220       else
14221          Find_Type (S);
14222          Typ := Entity (S);
14223       end if;
14224
14225       --  Check No_Wide_Characters restriction
14226
14227       Check_Wide_Character_Restriction (Typ, S);
14228
14229       return Typ;
14230    end Find_Type_Of_Subtype_Indic;
14231
14232    -------------------------------------
14233    -- Floating_Point_Type_Declaration --
14234    -------------------------------------
14235
14236    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14237       Digs          : constant Node_Id := Digits_Expression (Def);
14238       Digs_Val      : Uint;
14239       Base_Typ      : Entity_Id;
14240       Implicit_Base : Entity_Id;
14241       Bound         : Node_Id;
14242
14243       function Can_Derive_From (E : Entity_Id) return Boolean;
14244       --  Find if given digits value allows derivation from specified type
14245
14246       ---------------------
14247       -- Can_Derive_From --
14248       ---------------------
14249
14250       function Can_Derive_From (E : Entity_Id) return Boolean is
14251          Spec : constant Entity_Id := Real_Range_Specification (Def);
14252
14253       begin
14254          if Digs_Val > Digits_Value (E) then
14255             return False;
14256          end if;
14257
14258          if Present (Spec) then
14259             if Expr_Value_R (Type_Low_Bound (E)) >
14260                Expr_Value_R (Low_Bound (Spec))
14261             then
14262                return False;
14263             end if;
14264
14265             if Expr_Value_R (Type_High_Bound (E)) <
14266                Expr_Value_R (High_Bound (Spec))
14267             then
14268                return False;
14269             end if;
14270          end if;
14271
14272          return True;
14273       end Can_Derive_From;
14274
14275    --  Start of processing for Floating_Point_Type_Declaration
14276
14277    begin
14278       Check_Restriction (No_Floating_Point, Def);
14279
14280       --  Create an implicit base type
14281
14282       Implicit_Base :=
14283         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
14284
14285       --  Analyze and verify digits value
14286
14287       Analyze_And_Resolve (Digs, Any_Integer);
14288       Check_Digits_Expression (Digs);
14289       Digs_Val := Expr_Value (Digs);
14290
14291       --  Process possible range spec and find correct type to derive from
14292
14293       Process_Real_Range_Specification (Def);
14294
14295       if Can_Derive_From (Standard_Short_Float) then
14296          Base_Typ := Standard_Short_Float;
14297       elsif Can_Derive_From (Standard_Float) then
14298          Base_Typ := Standard_Float;
14299       elsif Can_Derive_From (Standard_Long_Float) then
14300          Base_Typ := Standard_Long_Float;
14301       elsif Can_Derive_From (Standard_Long_Long_Float) then
14302          Base_Typ := Standard_Long_Long_Float;
14303
14304       --  If we can't derive from any existing type, use long_long_float
14305       --  and give appropriate message explaining the problem.
14306
14307       else
14308          Base_Typ := Standard_Long_Long_Float;
14309
14310          if Digs_Val >= Digits_Value (Standard_Long_Long_Float) then
14311             Error_Msg_Uint_1 := Digits_Value (Standard_Long_Long_Float);
14312             Error_Msg_N ("digits value out of range, maximum is ^", Digs);
14313
14314          else
14315             Error_Msg_N
14316               ("range too large for any predefined type",
14317                Real_Range_Specification (Def));
14318          end if;
14319       end if;
14320
14321       --  If there are bounds given in the declaration use them as the bounds
14322       --  of the type, otherwise use the bounds of the predefined base type
14323       --  that was chosen based on the Digits value.
14324
14325       if Present (Real_Range_Specification (Def)) then
14326          Set_Scalar_Range (T, Real_Range_Specification (Def));
14327          Set_Is_Constrained (T);
14328
14329          --  The bounds of this range must be converted to machine numbers
14330          --  in accordance with RM 4.9(38).
14331
14332          Bound := Type_Low_Bound (T);
14333
14334          if Nkind (Bound) = N_Real_Literal then
14335             Set_Realval
14336               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14337             Set_Is_Machine_Number (Bound);
14338          end if;
14339
14340          Bound := Type_High_Bound (T);
14341
14342          if Nkind (Bound) = N_Real_Literal then
14343             Set_Realval
14344               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14345             Set_Is_Machine_Number (Bound);
14346          end if;
14347
14348       else
14349          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
14350       end if;
14351
14352       --  Complete definition of implicit base and declared first subtype
14353
14354       Set_Etype          (Implicit_Base, Base_Typ);
14355
14356       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
14357       Set_Size_Info      (Implicit_Base,                (Base_Typ));
14358       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
14359       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
14360       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
14361       Set_Vax_Float      (Implicit_Base, Vax_Float      (Base_Typ));
14362
14363       Set_Ekind          (T, E_Floating_Point_Subtype);
14364       Set_Etype          (T, Implicit_Base);
14365
14366       Set_Size_Info      (T,                (Implicit_Base));
14367       Set_RM_Size        (T, RM_Size        (Implicit_Base));
14368       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
14369       Set_Digits_Value   (T, Digs_Val);
14370    end Floating_Point_Type_Declaration;
14371
14372    ----------------------------
14373    -- Get_Discriminant_Value --
14374    ----------------------------
14375
14376    --  This is the situation:
14377
14378    --  There is a non-derived type
14379
14380    --       type T0 (Dx, Dy, Dz...)
14381
14382    --  There are zero or more levels of derivation, with each derivation
14383    --  either purely inheriting the discriminants, or defining its own.
14384
14385    --       type Ti      is new Ti-1
14386    --  or
14387    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
14388    --  or
14389    --       subtype Ti is ...
14390
14391    --  The subtype issue is avoided by the use of Original_Record_Component,
14392    --  and the fact that derived subtypes also derive the constraints.
14393
14394    --  This chain leads back from
14395
14396    --       Typ_For_Constraint
14397
14398    --  Typ_For_Constraint has discriminants, and the value for each
14399    --  discriminant is given by its corresponding Elmt of Constraints.
14400
14401    --  Discriminant is some discriminant in this hierarchy
14402
14403    --  We need to return its value
14404
14405    --  We do this by recursively searching each level, and looking for
14406    --  Discriminant. Once we get to the bottom, we start backing up
14407    --  returning the value for it which may in turn be a discriminant
14408    --  further up, so on the backup we continue the substitution.
14409
14410    function Get_Discriminant_Value
14411      (Discriminant       : Entity_Id;
14412       Typ_For_Constraint : Entity_Id;
14413       Constraint         : Elist_Id) return Node_Id
14414    is
14415       function Search_Derivation_Levels
14416         (Ti                    : Entity_Id;
14417          Discrim_Values        : Elist_Id;
14418          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
14419       --  This is the routine that performs the recursive search of levels
14420       --  as described above.
14421
14422       ------------------------------
14423       -- Search_Derivation_Levels --
14424       ------------------------------
14425
14426       function Search_Derivation_Levels
14427         (Ti                    : Entity_Id;
14428          Discrim_Values        : Elist_Id;
14429          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
14430       is
14431          Assoc          : Elmt_Id;
14432          Disc           : Entity_Id;
14433          Result         : Node_Or_Entity_Id;
14434          Result_Entity  : Node_Id;
14435
14436       begin
14437          --  If inappropriate type, return Error, this happens only in
14438          --  cascaded error situations, and we want to avoid a blow up.
14439
14440          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
14441             return Error;
14442          end if;
14443
14444          --  Look deeper if possible. Use Stored_Constraints only for
14445          --  untagged types. For tagged types use the given constraint.
14446          --  This asymmetry needs explanation???
14447
14448          if not Stored_Discrim_Values
14449            and then Present (Stored_Constraint (Ti))
14450            and then not Is_Tagged_Type (Ti)
14451          then
14452             Result :=
14453               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
14454          else
14455             declare
14456                Td : constant Entity_Id := Etype (Ti);
14457
14458             begin
14459                if Td = Ti then
14460                   Result := Discriminant;
14461
14462                else
14463                   if Present (Stored_Constraint (Ti)) then
14464                      Result :=
14465                         Search_Derivation_Levels
14466                           (Td, Stored_Constraint (Ti), True);
14467                   else
14468                      Result :=
14469                         Search_Derivation_Levels
14470                           (Td, Discrim_Values, Stored_Discrim_Values);
14471                   end if;
14472                end if;
14473             end;
14474          end if;
14475
14476          --  Extra underlying places to search, if not found above. For
14477          --  concurrent types, the relevant discriminant appears in the
14478          --  corresponding record. For a type derived from a private type
14479          --  without discriminant, the full view inherits the discriminants
14480          --  of the full view of the parent.
14481
14482          if Result = Discriminant then
14483             if Is_Concurrent_Type (Ti)
14484               and then Present (Corresponding_Record_Type (Ti))
14485             then
14486                Result :=
14487                  Search_Derivation_Levels (
14488                    Corresponding_Record_Type (Ti),
14489                    Discrim_Values,
14490                    Stored_Discrim_Values);
14491
14492             elsif Is_Private_Type (Ti)
14493               and then not Has_Discriminants (Ti)
14494               and then Present (Full_View (Ti))
14495               and then Etype (Full_View (Ti)) /= Ti
14496             then
14497                Result :=
14498                  Search_Derivation_Levels (
14499                    Full_View (Ti),
14500                    Discrim_Values,
14501                    Stored_Discrim_Values);
14502             end if;
14503          end if;
14504
14505          --  If Result is not a (reference to a) discriminant, return it,
14506          --  otherwise set Result_Entity to the discriminant.
14507
14508          if Nkind (Result) = N_Defining_Identifier then
14509             pragma Assert (Result = Discriminant);
14510             Result_Entity := Result;
14511
14512          else
14513             if not Denotes_Discriminant (Result) then
14514                return Result;
14515             end if;
14516
14517             Result_Entity := Entity (Result);
14518          end if;
14519
14520          --  See if this level of derivation actually has discriminants
14521          --  because tagged derivations can add them, hence the lower
14522          --  levels need not have any.
14523
14524          if not Has_Discriminants (Ti) then
14525             return Result;
14526          end if;
14527
14528          --  Scan Ti's discriminants for Result_Entity,
14529          --  and return its corresponding value, if any.
14530
14531          Result_Entity := Original_Record_Component (Result_Entity);
14532
14533          Assoc := First_Elmt (Discrim_Values);
14534
14535          if Stored_Discrim_Values then
14536             Disc := First_Stored_Discriminant (Ti);
14537          else
14538             Disc := First_Discriminant (Ti);
14539          end if;
14540
14541          while Present (Disc) loop
14542             pragma Assert (Present (Assoc));
14543
14544             if Original_Record_Component (Disc) = Result_Entity then
14545                return Node (Assoc);
14546             end if;
14547
14548             Next_Elmt (Assoc);
14549
14550             if Stored_Discrim_Values then
14551                Next_Stored_Discriminant (Disc);
14552             else
14553                Next_Discriminant (Disc);
14554             end if;
14555          end loop;
14556
14557          --  Could not find it
14558          --
14559          return Result;
14560       end Search_Derivation_Levels;
14561
14562       --  Local Variables
14563
14564       Result : Node_Or_Entity_Id;
14565
14566    --  Start of processing for Get_Discriminant_Value
14567
14568    begin
14569       --  ??? This routine is a gigantic mess and will be deleted. For the
14570       --  time being just test for the trivial case before calling recurse.
14571
14572       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
14573          declare
14574             D : Entity_Id;
14575             E : Elmt_Id;
14576
14577          begin
14578             D := First_Discriminant (Typ_For_Constraint);
14579             E := First_Elmt (Constraint);
14580             while Present (D) loop
14581                if Chars (D) = Chars (Discriminant) then
14582                   return Node (E);
14583                end if;
14584
14585                Next_Discriminant (D);
14586                Next_Elmt (E);
14587             end loop;
14588          end;
14589       end if;
14590
14591       Result := Search_Derivation_Levels
14592         (Typ_For_Constraint, Constraint, False);
14593
14594       --  ??? hack to disappear when this routine is gone
14595
14596       if  Nkind (Result) = N_Defining_Identifier then
14597          declare
14598             D : Entity_Id;
14599             E : Elmt_Id;
14600
14601          begin
14602             D := First_Discriminant (Typ_For_Constraint);
14603             E := First_Elmt (Constraint);
14604             while Present (D) loop
14605                if Corresponding_Discriminant (D) = Discriminant then
14606                   return Node (E);
14607                end if;
14608
14609                Next_Discriminant (D);
14610                Next_Elmt (E);
14611             end loop;
14612          end;
14613       end if;
14614
14615       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
14616       return Result;
14617    end Get_Discriminant_Value;
14618
14619    --------------------------
14620    -- Has_Range_Constraint --
14621    --------------------------
14622
14623    function Has_Range_Constraint (N : Node_Id) return Boolean is
14624       C : constant Node_Id := Constraint (N);
14625
14626    begin
14627       if Nkind (C) = N_Range_Constraint then
14628          return True;
14629
14630       elsif Nkind (C) = N_Digits_Constraint then
14631          return
14632             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
14633               or else
14634             Present (Range_Constraint (C));
14635
14636       elsif Nkind (C) = N_Delta_Constraint then
14637          return Present (Range_Constraint (C));
14638
14639       else
14640          return False;
14641       end if;
14642    end Has_Range_Constraint;
14643
14644    ------------------------
14645    -- Inherit_Components --
14646    ------------------------
14647
14648    function Inherit_Components
14649      (N             : Node_Id;
14650       Parent_Base   : Entity_Id;
14651       Derived_Base  : Entity_Id;
14652       Is_Tagged     : Boolean;
14653       Inherit_Discr : Boolean;
14654       Discs         : Elist_Id) return Elist_Id
14655    is
14656       Assoc_List : constant Elist_Id := New_Elmt_List;
14657
14658       procedure Inherit_Component
14659         (Old_C          : Entity_Id;
14660          Plain_Discrim  : Boolean := False;
14661          Stored_Discrim : Boolean := False);
14662       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
14663       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
14664       --  True, Old_C is a stored discriminant. If they are both false then
14665       --  Old_C is a regular component.
14666
14667       -----------------------
14668       -- Inherit_Component --
14669       -----------------------
14670
14671       procedure Inherit_Component
14672         (Old_C          : Entity_Id;
14673          Plain_Discrim  : Boolean := False;
14674          Stored_Discrim : Boolean := False)
14675       is
14676          New_C : constant Entity_Id := New_Copy (Old_C);
14677
14678          Discrim      : Entity_Id;
14679          Corr_Discrim : Entity_Id;
14680
14681       begin
14682          pragma Assert (not Is_Tagged or else not Stored_Discrim);
14683
14684          Set_Parent (New_C, Parent (Old_C));
14685
14686          --  Regular discriminants and components must be inserted in the scope
14687          --  of the Derived_Base. Do it here.
14688
14689          if not Stored_Discrim then
14690             Enter_Name (New_C);
14691          end if;
14692
14693          --  For tagged types the Original_Record_Component must point to
14694          --  whatever this field was pointing to in the parent type. This has
14695          --  already been achieved by the call to New_Copy above.
14696
14697          if not Is_Tagged then
14698             Set_Original_Record_Component (New_C, New_C);
14699          end if;
14700
14701          --  If we have inherited a component then see if its Etype contains
14702          --  references to Parent_Base discriminants. In this case, replace
14703          --  these references with the constraints given in Discs. We do not
14704          --  do this for the partial view of private types because this is
14705          --  not needed (only the components of the full view will be used
14706          --  for code generation) and cause problem. We also avoid this
14707          --  transformation in some error situations.
14708
14709          if Ekind (New_C) = E_Component then
14710             if (Is_Private_Type (Derived_Base)
14711                  and then not Is_Generic_Type (Derived_Base))
14712               or else (Is_Empty_Elmt_List (Discs)
14713                         and then  not Expander_Active)
14714             then
14715                Set_Etype (New_C, Etype (Old_C));
14716
14717             else
14718                --  The current component introduces a circularity of the
14719                --  following kind:
14720
14721                --     limited with Pack_2;
14722                --     package Pack_1 is
14723                --        type T_1 is tagged record
14724                --           Comp : access Pack_2.T_2;
14725                --           ...
14726                --        end record;
14727                --     end Pack_1;
14728
14729                --     with Pack_1;
14730                --     package Pack_2 is
14731                --        type T_2 is new Pack_1.T_1 with ...;
14732                --     end Pack_2;
14733
14734                Set_Etype
14735                  (New_C,
14736                   Constrain_Component_Type
14737                   (Old_C, Derived_Base, N, Parent_Base, Discs));
14738             end if;
14739          end if;
14740
14741          --  In derived tagged types it is illegal to reference a non
14742          --  discriminant component in the parent type. To catch this, mark
14743          --  these components with an Ekind of E_Void. This will be reset in
14744          --  Record_Type_Definition after processing the record extension of
14745          --  the derived type.
14746
14747          --  If the declaration is a private extension, there is no further
14748          --  record extension to process, and the components retain their
14749          --  current kind, because they are visible at this point.
14750
14751          if Is_Tagged and then Ekind (New_C) = E_Component
14752            and then Nkind (N) /= N_Private_Extension_Declaration
14753          then
14754             Set_Ekind (New_C, E_Void);
14755          end if;
14756
14757          if Plain_Discrim then
14758             Set_Corresponding_Discriminant (New_C, Old_C);
14759             Build_Discriminal (New_C);
14760
14761          --  If we are explicitly inheriting a stored discriminant it will be
14762          --  completely hidden.
14763
14764          elsif Stored_Discrim then
14765             Set_Corresponding_Discriminant (New_C, Empty);
14766             Set_Discriminal (New_C, Empty);
14767             Set_Is_Completely_Hidden (New_C);
14768
14769             --  Set the Original_Record_Component of each discriminant in the
14770             --  derived base to point to the corresponding stored that we just
14771             --  created.
14772
14773             Discrim := First_Discriminant (Derived_Base);
14774             while Present (Discrim) loop
14775                Corr_Discrim := Corresponding_Discriminant (Discrim);
14776
14777                --  Corr_Discrim could be missing in an error situation
14778
14779                if Present (Corr_Discrim)
14780                  and then Original_Record_Component (Corr_Discrim) = Old_C
14781                then
14782                   Set_Original_Record_Component (Discrim, New_C);
14783                end if;
14784
14785                Next_Discriminant (Discrim);
14786             end loop;
14787
14788             Append_Entity (New_C, Derived_Base);
14789          end if;
14790
14791          if not Is_Tagged then
14792             Append_Elmt (Old_C, Assoc_List);
14793             Append_Elmt (New_C, Assoc_List);
14794          end if;
14795       end Inherit_Component;
14796
14797       --  Variables local to Inherit_Component
14798
14799       Loc : constant Source_Ptr := Sloc (N);
14800
14801       Parent_Discrim : Entity_Id;
14802       Stored_Discrim : Entity_Id;
14803       D              : Entity_Id;
14804       Component      : Entity_Id;
14805
14806    --  Start of processing for Inherit_Components
14807
14808    begin
14809       if not Is_Tagged then
14810          Append_Elmt (Parent_Base,  Assoc_List);
14811          Append_Elmt (Derived_Base, Assoc_List);
14812       end if;
14813
14814       --  Inherit parent discriminants if needed
14815
14816       if Inherit_Discr then
14817          Parent_Discrim := First_Discriminant (Parent_Base);
14818          while Present (Parent_Discrim) loop
14819             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
14820             Next_Discriminant (Parent_Discrim);
14821          end loop;
14822       end if;
14823
14824       --  Create explicit stored discrims for untagged types when necessary
14825
14826       if not Has_Unknown_Discriminants (Derived_Base)
14827         and then Has_Discriminants (Parent_Base)
14828         and then not Is_Tagged
14829         and then
14830           (not Inherit_Discr
14831              or else First_Discriminant (Parent_Base) /=
14832                      First_Stored_Discriminant (Parent_Base))
14833       then
14834          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
14835          while Present (Stored_Discrim) loop
14836             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
14837             Next_Stored_Discriminant (Stored_Discrim);
14838          end loop;
14839       end if;
14840
14841       --  See if we can apply the second transformation for derived types, as
14842       --  explained in point 6. in the comments above Build_Derived_Record_Type
14843       --  This is achieved by appending Derived_Base discriminants into Discs,
14844       --  which has the side effect of returning a non empty Discs list to the
14845       --  caller of Inherit_Components, which is what we want. This must be
14846       --  done for private derived types if there are explicit stored
14847       --  discriminants, to ensure that we can retrieve the values of the
14848       --  constraints provided in the ancestors.
14849
14850       if Inherit_Discr
14851         and then Is_Empty_Elmt_List (Discs)
14852         and then Present (First_Discriminant (Derived_Base))
14853         and then
14854           (not Is_Private_Type (Derived_Base)
14855              or else Is_Completely_Hidden
14856                (First_Stored_Discriminant (Derived_Base))
14857              or else Is_Generic_Type (Derived_Base))
14858       then
14859          D := First_Discriminant (Derived_Base);
14860          while Present (D) loop
14861             Append_Elmt (New_Reference_To (D, Loc), Discs);
14862             Next_Discriminant (D);
14863          end loop;
14864       end if;
14865
14866       --  Finally, inherit non-discriminant components unless they are not
14867       --  visible because defined or inherited from the full view of the
14868       --  parent. Don't inherit the _parent field of the parent type.
14869
14870       Component := First_Entity (Parent_Base);
14871       while Present (Component) loop
14872
14873          --  Ada 2005 (AI-251): Do not inherit components associated with
14874          --  secondary tags of the parent.
14875
14876          if Ekind (Component) = E_Component
14877            and then Present (Related_Type (Component))
14878          then
14879             null;
14880
14881          elsif Ekind (Component) /= E_Component
14882            or else Chars (Component) = Name_uParent
14883          then
14884             null;
14885
14886          --  If the derived type is within the parent type's declarative
14887          --  region, then the components can still be inherited even though
14888          --  they aren't visible at this point. This can occur for cases
14889          --  such as within public child units where the components must
14890          --  become visible upon entering the child unit's private part.
14891
14892          elsif not Is_Visible_Component (Component)
14893            and then not In_Open_Scopes (Scope (Parent_Base))
14894          then
14895             null;
14896
14897          elsif Ekind_In (Derived_Base, E_Private_Type,
14898                                        E_Limited_Private_Type)
14899          then
14900             null;
14901
14902          else
14903             Inherit_Component (Component);
14904          end if;
14905
14906          Next_Entity (Component);
14907       end loop;
14908
14909       --  For tagged derived types, inherited discriminants cannot be used in
14910       --  component declarations of the record extension part. To achieve this
14911       --  we mark the inherited discriminants as not visible.
14912
14913       if Is_Tagged and then Inherit_Discr then
14914          D := First_Discriminant (Derived_Base);
14915          while Present (D) loop
14916             Set_Is_Immediately_Visible (D, False);
14917             Next_Discriminant (D);
14918          end loop;
14919       end if;
14920
14921       return Assoc_List;
14922    end Inherit_Components;
14923
14924    -----------------------
14925    -- Is_Null_Extension --
14926    -----------------------
14927
14928    function Is_Null_Extension (T : Entity_Id) return Boolean is
14929       Type_Decl : constant Node_Id := Parent (Base_Type (T));
14930       Comp_List : Node_Id;
14931       Comp      : Node_Id;
14932
14933    begin
14934       if Nkind (Type_Decl) /= N_Full_Type_Declaration
14935         or else not Is_Tagged_Type (T)
14936         or else Nkind (Type_Definition (Type_Decl)) /=
14937                                               N_Derived_Type_Definition
14938         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
14939       then
14940          return False;
14941       end if;
14942
14943       Comp_List :=
14944         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
14945
14946       if Present (Discriminant_Specifications (Type_Decl)) then
14947          return False;
14948
14949       elsif Present (Comp_List)
14950         and then Is_Non_Empty_List (Component_Items (Comp_List))
14951       then
14952          Comp := First (Component_Items (Comp_List));
14953
14954          --  Only user-defined components are relevant. The component list
14955          --  may also contain a parent component and internal components
14956          --  corresponding to secondary tags, but these do not determine
14957          --  whether this is a null extension.
14958
14959          while Present (Comp) loop
14960             if Comes_From_Source (Comp) then
14961                return False;
14962             end if;
14963
14964             Next (Comp);
14965          end loop;
14966
14967          return True;
14968       else
14969          return True;
14970       end if;
14971    end Is_Null_Extension;
14972
14973    ------------------------------
14974    -- Is_Valid_Constraint_Kind --
14975    ------------------------------
14976
14977    function Is_Valid_Constraint_Kind
14978      (T_Kind          : Type_Kind;
14979       Constraint_Kind : Node_Kind) return Boolean
14980    is
14981    begin
14982       case T_Kind is
14983          when Enumeration_Kind |
14984               Integer_Kind =>
14985             return Constraint_Kind = N_Range_Constraint;
14986
14987          when Decimal_Fixed_Point_Kind =>
14988             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
14989                                               N_Range_Constraint);
14990
14991          when Ordinary_Fixed_Point_Kind =>
14992             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
14993                                               N_Range_Constraint);
14994
14995          when Float_Kind =>
14996             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
14997                                               N_Range_Constraint);
14998
14999          when Access_Kind       |
15000               Array_Kind        |
15001               E_Record_Type     |
15002               E_Record_Subtype  |
15003               Class_Wide_Kind   |
15004               E_Incomplete_Type |
15005               Private_Kind      |
15006               Concurrent_Kind  =>
15007             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
15008
15009          when others =>
15010             return True; -- Error will be detected later
15011       end case;
15012    end Is_Valid_Constraint_Kind;
15013
15014    --------------------------
15015    -- Is_Visible_Component --
15016    --------------------------
15017
15018    function Is_Visible_Component (C : Entity_Id) return Boolean is
15019       Original_Comp  : Entity_Id := Empty;
15020       Original_Scope : Entity_Id;
15021       Type_Scope     : Entity_Id;
15022
15023       function Is_Local_Type (Typ : Entity_Id) return Boolean;
15024       --  Check whether parent type of inherited component is declared locally,
15025       --  possibly within a nested package or instance. The current scope is
15026       --  the derived record itself.
15027
15028       -------------------
15029       -- Is_Local_Type --
15030       -------------------
15031
15032       function Is_Local_Type (Typ : Entity_Id) return Boolean is
15033          Scop : Entity_Id;
15034
15035       begin
15036          Scop := Scope (Typ);
15037          while Present (Scop)
15038            and then Scop /= Standard_Standard
15039          loop
15040             if Scop = Scope (Current_Scope) then
15041                return True;
15042             end if;
15043
15044             Scop := Scope (Scop);
15045          end loop;
15046
15047          return False;
15048       end Is_Local_Type;
15049
15050    --  Start of processing for Is_Visible_Component
15051
15052    begin
15053       if Ekind_In (C, E_Component, E_Discriminant) then
15054          Original_Comp := Original_Record_Component (C);
15055       end if;
15056
15057       if No (Original_Comp) then
15058
15059          --  Premature usage, or previous error
15060
15061          return False;
15062
15063       else
15064          Original_Scope := Scope (Original_Comp);
15065          Type_Scope     := Scope (Base_Type (Scope (C)));
15066       end if;
15067
15068       --  This test only concerns tagged types
15069
15070       if not Is_Tagged_Type (Original_Scope) then
15071          return True;
15072
15073       --  If it is _Parent or _Tag, there is no visibility issue
15074
15075       elsif not Comes_From_Source (Original_Comp) then
15076          return True;
15077
15078       --  If we are in the body of an instantiation, the component is visible
15079       --  even when the parent type (possibly defined in an enclosing unit or
15080       --  in a parent unit) might not.
15081
15082       elsif In_Instance_Body then
15083          return True;
15084
15085       --  Discriminants are always visible
15086
15087       elsif Ekind (Original_Comp) = E_Discriminant
15088         and then not Has_Unknown_Discriminants (Original_Scope)
15089       then
15090          return True;
15091
15092       --  If the component has been declared in an ancestor which is currently
15093       --  a private type, then it is not visible. The same applies if the
15094       --  component's containing type is not in an open scope and the original
15095       --  component's enclosing type is a visible full view of a private type
15096       --  (which can occur in cases where an attempt is being made to reference
15097       --  a component in a sibling package that is inherited from a visible
15098       --  component of a type in an ancestor package; the component in the
15099       --  sibling package should not be visible even though the component it
15100       --  inherited from is visible). This does not apply however in the case
15101       --  where the scope of the type is a private child unit, or when the
15102       --  parent comes from a local package in which the ancestor is currently
15103       --  visible. The latter suppression of visibility is needed for cases
15104       --  that are tested in B730006.
15105
15106       elsif Is_Private_Type (Original_Scope)
15107         or else
15108           (not Is_Private_Descendant (Type_Scope)
15109             and then not In_Open_Scopes (Type_Scope)
15110             and then Has_Private_Declaration (Original_Scope))
15111       then
15112          --  If the type derives from an entity in a formal package, there
15113          --  are no additional visible components.
15114
15115          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
15116             N_Formal_Package_Declaration
15117          then
15118             return False;
15119
15120          --  if we are not in the private part of the current package, there
15121          --  are no additional visible components.
15122
15123          elsif Ekind (Scope (Current_Scope)) = E_Package
15124            and then not In_Private_Part (Scope (Current_Scope))
15125          then
15126             return False;
15127          else
15128             return
15129               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
15130                 and then In_Open_Scopes (Scope (Original_Scope))
15131                 and then Is_Local_Type (Type_Scope);
15132          end if;
15133
15134       --  There is another weird way in which a component may be invisible
15135       --  when the private and the full view are not derived from the same
15136       --  ancestor. Here is an example :
15137
15138       --       type A1 is tagged      record F1 : integer; end record;
15139       --       type A2 is new A1 with record F2 : integer; end record;
15140       --       type T is new A1 with private;
15141       --     private
15142       --       type T is new A2 with null record;
15143
15144       --  In this case, the full view of T inherits F1 and F2 but the private
15145       --  view inherits only F1
15146
15147       else
15148          declare
15149             Ancestor : Entity_Id := Scope (C);
15150
15151          begin
15152             loop
15153                if Ancestor = Original_Scope then
15154                   return True;
15155                elsif Ancestor = Etype (Ancestor) then
15156                   return False;
15157                end if;
15158
15159                Ancestor := Etype (Ancestor);
15160             end loop;
15161          end;
15162       end if;
15163    end Is_Visible_Component;
15164
15165    --------------------------
15166    -- Make_Class_Wide_Type --
15167    --------------------------
15168
15169    procedure Make_Class_Wide_Type (T : Entity_Id) is
15170       CW_Type : Entity_Id;
15171       CW_Name : Name_Id;
15172       Next_E  : Entity_Id;
15173
15174    begin
15175       --  The class wide type can have been defined by the partial view, in
15176       --  which case everything is already done.
15177
15178       if Present (Class_Wide_Type (T)) then
15179          return;
15180       end if;
15181
15182       CW_Type :=
15183         New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
15184
15185       --  Inherit root type characteristics
15186
15187       CW_Name := Chars (CW_Type);
15188       Next_E  := Next_Entity (CW_Type);
15189       Copy_Node (T, CW_Type);
15190       Set_Comes_From_Source (CW_Type, False);
15191       Set_Chars (CW_Type, CW_Name);
15192       Set_Parent (CW_Type, Parent (T));
15193       Set_Next_Entity (CW_Type, Next_E);
15194
15195       --  Ensure we have a new freeze node for the class-wide type. The partial
15196       --  view may have freeze action of its own, requiring a proper freeze
15197       --  node, and the same freeze node cannot be shared between the two
15198       --  types.
15199
15200       Set_Has_Delayed_Freeze (CW_Type);
15201       Set_Freeze_Node (CW_Type, Empty);
15202
15203       --  Customize the class-wide type: It has no prim. op., it cannot be
15204       --  abstract and its Etype points back to the specific root type.
15205
15206       Set_Ekind                (CW_Type, E_Class_Wide_Type);
15207       Set_Is_Tagged_Type       (CW_Type, True);
15208       Set_Primitive_Operations (CW_Type, New_Elmt_List);
15209       Set_Is_Abstract_Type     (CW_Type, False);
15210       Set_Is_Constrained       (CW_Type, False);
15211       Set_Is_First_Subtype     (CW_Type, Is_First_Subtype (T));
15212
15213       if Ekind (T) = E_Class_Wide_Subtype then
15214          Set_Etype             (CW_Type, Etype (Base_Type (T)));
15215       else
15216          Set_Etype             (CW_Type, T);
15217       end if;
15218
15219       --  If this is the class_wide type of a constrained subtype, it does
15220       --  not have discriminants.
15221
15222       Set_Has_Discriminants (CW_Type,
15223         Has_Discriminants (T) and then not Is_Constrained (T));
15224
15225       Set_Has_Unknown_Discriminants (CW_Type, True);
15226       Set_Class_Wide_Type (T, CW_Type);
15227       Set_Equivalent_Type (CW_Type, Empty);
15228
15229       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
15230
15231       Set_Class_Wide_Type (CW_Type, CW_Type);
15232    end Make_Class_Wide_Type;
15233
15234    ----------------
15235    -- Make_Index --
15236    ----------------
15237
15238    procedure Make_Index
15239      (I            : Node_Id;
15240       Related_Nod  : Node_Id;
15241       Related_Id   : Entity_Id := Empty;
15242       Suffix_Index : Nat := 1)
15243    is
15244       R      : Node_Id;
15245       T      : Entity_Id;
15246       Def_Id : Entity_Id := Empty;
15247       Found  : Boolean := False;
15248
15249    begin
15250       --  For a discrete range used in a constrained array definition and
15251       --  defined by a range, an implicit conversion to the predefined type
15252       --  INTEGER is assumed if each bound is either a numeric literal, a named
15253       --  number, or an attribute, and the type of both bounds (prior to the
15254       --  implicit conversion) is the type universal_integer. Otherwise, both
15255       --  bounds must be of the same discrete type, other than universal
15256       --  integer; this type must be determinable independently of the
15257       --  context, but using the fact that the type must be discrete and that
15258       --  both bounds must have the same type.
15259
15260       --  Character literals also have a universal type in the absence of
15261       --  of additional context,  and are resolved to Standard_Character.
15262
15263       if Nkind (I) = N_Range then
15264
15265          --  The index is given by a range constraint. The bounds are known
15266          --  to be of a consistent type.
15267
15268          if not Is_Overloaded (I) then
15269             T := Etype (I);
15270
15271             --  For universal bounds, choose the specific predefined type
15272
15273             if T = Universal_Integer then
15274                T := Standard_Integer;
15275
15276             elsif T = Any_Character then
15277                Ambiguous_Character (Low_Bound (I));
15278
15279                T := Standard_Character;
15280             end if;
15281
15282          --  The node may be overloaded because some user-defined operators
15283          --  are available, but if a universal interpretation exists it is
15284          --  also the selected one.
15285
15286          elsif Universal_Interpretation (I) = Universal_Integer then
15287             T := Standard_Integer;
15288
15289          else
15290             T := Any_Type;
15291
15292             declare
15293                Ind : Interp_Index;
15294                It  : Interp;
15295
15296             begin
15297                Get_First_Interp (I, Ind, It);
15298                while Present (It.Typ) loop
15299                   if Is_Discrete_Type (It.Typ) then
15300
15301                      if Found
15302                        and then not Covers (It.Typ, T)
15303                        and then not Covers (T, It.Typ)
15304                      then
15305                         Error_Msg_N ("ambiguous bounds in discrete range", I);
15306                         exit;
15307                      else
15308                         T := It.Typ;
15309                         Found := True;
15310                      end if;
15311                   end if;
15312
15313                   Get_Next_Interp (Ind, It);
15314                end loop;
15315
15316                if T = Any_Type then
15317                   Error_Msg_N ("discrete type required for range", I);
15318                   Set_Etype (I, Any_Type);
15319                   return;
15320
15321                elsif T = Universal_Integer then
15322                   T := Standard_Integer;
15323                end if;
15324             end;
15325          end if;
15326
15327          if not Is_Discrete_Type (T) then
15328             Error_Msg_N ("discrete type required for range", I);
15329             Set_Etype (I, Any_Type);
15330             return;
15331          end if;
15332
15333          if Nkind (Low_Bound (I)) = N_Attribute_Reference
15334            and then Attribute_Name (Low_Bound (I)) = Name_First
15335            and then Is_Entity_Name (Prefix (Low_Bound (I)))
15336            and then Is_Type (Entity (Prefix (Low_Bound (I))))
15337            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
15338          then
15339             --  The type of the index will be the type of the prefix, as long
15340             --  as the upper bound is 'Last of the same type.
15341
15342             Def_Id := Entity (Prefix (Low_Bound (I)));
15343
15344             if Nkind (High_Bound (I)) /= N_Attribute_Reference
15345               or else Attribute_Name (High_Bound (I)) /= Name_Last
15346               or else not Is_Entity_Name (Prefix (High_Bound (I)))
15347               or else Entity (Prefix (High_Bound (I))) /= Def_Id
15348             then
15349                Def_Id := Empty;
15350             end if;
15351          end if;
15352
15353          R := I;
15354          Process_Range_Expr_In_Decl (R, T);
15355
15356       elsif Nkind (I) = N_Subtype_Indication then
15357
15358          --  The index is given by a subtype with a range constraint
15359
15360          T :=  Base_Type (Entity (Subtype_Mark (I)));
15361
15362          if not Is_Discrete_Type (T) then
15363             Error_Msg_N ("discrete type required for range", I);
15364             Set_Etype (I, Any_Type);
15365             return;
15366          end if;
15367
15368          R := Range_Expression (Constraint (I));
15369
15370          Resolve (R, T);
15371          Process_Range_Expr_In_Decl (R, Entity (Subtype_Mark (I)));
15372
15373       elsif Nkind (I) = N_Attribute_Reference then
15374
15375          --  The parser guarantees that the attribute is a RANGE attribute
15376
15377          --  If the node denotes the range of a type mark, that is also the
15378          --  resulting type, and we do no need to create an Itype for it.
15379
15380          if Is_Entity_Name (Prefix (I))
15381            and then Comes_From_Source (I)
15382            and then Is_Type (Entity (Prefix (I)))
15383            and then Is_Discrete_Type (Entity (Prefix (I)))
15384          then
15385             Def_Id := Entity (Prefix (I));
15386          end if;
15387
15388          Analyze_And_Resolve (I);
15389          T := Etype (I);
15390          R := I;
15391
15392       --  If none of the above, must be a subtype. We convert this to a
15393       --  range attribute reference because in the case of declared first
15394       --  named subtypes, the types in the range reference can be different
15395       --  from the type of the entity. A range attribute normalizes the
15396       --  reference and obtains the correct types for the bounds.
15397
15398       --  This transformation is in the nature of an expansion, is only
15399       --  done if expansion is active. In particular, it is not done on
15400       --  formal generic types,  because we need to retain the name of the
15401       --  original index for instantiation purposes.
15402
15403       else
15404          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
15405             Error_Msg_N ("invalid subtype mark in discrete range ", I);
15406             Set_Etype (I, Any_Integer);
15407             return;
15408
15409          else
15410             --  The type mark may be that of an incomplete type. It is only
15411             --  now that we can get the full view, previous analysis does
15412             --  not look specifically for a type mark.
15413
15414             Set_Entity (I, Get_Full_View (Entity (I)));
15415             Set_Etype  (I, Entity (I));
15416             Def_Id := Entity (I);
15417
15418             if not Is_Discrete_Type (Def_Id) then
15419                Error_Msg_N ("discrete type required for index", I);
15420                Set_Etype (I, Any_Type);
15421                return;
15422             end if;
15423          end if;
15424
15425          if Expander_Active then
15426             Rewrite (I,
15427               Make_Attribute_Reference (Sloc (I),
15428                 Attribute_Name => Name_Range,
15429                 Prefix         => Relocate_Node (I)));
15430
15431             --  The original was a subtype mark that does not freeze. This
15432             --  means that the rewritten version must not freeze either.
15433
15434             Set_Must_Not_Freeze (I);
15435             Set_Must_Not_Freeze (Prefix (I));
15436
15437             --  Is order critical??? if so, document why, if not
15438             --  use Analyze_And_Resolve
15439
15440             Analyze_And_Resolve (I);
15441             T := Etype (I);
15442             R := I;
15443
15444          --  If expander is inactive, type is legal, nothing else to construct
15445
15446          else
15447             return;
15448          end if;
15449       end if;
15450
15451       if not Is_Discrete_Type (T) then
15452          Error_Msg_N ("discrete type required for range", I);
15453          Set_Etype (I, Any_Type);
15454          return;
15455
15456       elsif T = Any_Type then
15457          Set_Etype (I, Any_Type);
15458          return;
15459       end if;
15460
15461       --  We will now create the appropriate Itype to describe the range, but
15462       --  first a check. If we originally had a subtype, then we just label
15463       --  the range with this subtype. Not only is there no need to construct
15464       --  a new subtype, but it is wrong to do so for two reasons:
15465
15466       --    1. A legality concern, if we have a subtype, it must not freeze,
15467       --       and the Itype would cause freezing incorrectly
15468
15469       --    2. An efficiency concern, if we created an Itype, it would not be
15470       --       recognized as the same type for the purposes of eliminating
15471       --       checks in some circumstances.
15472
15473       --  We signal this case by setting the subtype entity in Def_Id
15474
15475       if No (Def_Id) then
15476          Def_Id :=
15477            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
15478          Set_Etype (Def_Id, Base_Type (T));
15479
15480          if Is_Signed_Integer_Type (T) then
15481             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
15482
15483          elsif Is_Modular_Integer_Type (T) then
15484             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
15485
15486          else
15487             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
15488             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
15489             Set_First_Literal     (Def_Id, First_Literal (T));
15490          end if;
15491
15492          Set_Size_Info      (Def_Id,                  (T));
15493          Set_RM_Size        (Def_Id, RM_Size          (T));
15494          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
15495
15496          Set_Scalar_Range   (Def_Id, R);
15497          Conditional_Delay  (Def_Id, T);
15498
15499          --  In the subtype indication case, if the immediate parent of the
15500          --  new subtype is non-static, then the subtype we create is non-
15501          --  static, even if its bounds are static.
15502
15503          if Nkind (I) = N_Subtype_Indication
15504            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
15505          then
15506             Set_Is_Non_Static_Subtype (Def_Id);
15507          end if;
15508       end if;
15509
15510       --  Final step is to label the index with this constructed type
15511
15512       Set_Etype (I, Def_Id);
15513    end Make_Index;
15514
15515    ------------------------------
15516    -- Modular_Type_Declaration --
15517    ------------------------------
15518
15519    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
15520       Mod_Expr : constant Node_Id := Expression (Def);
15521       M_Val    : Uint;
15522
15523       procedure Set_Modular_Size (Bits : Int);
15524       --  Sets RM_Size to Bits, and Esize to normal word size above this
15525
15526       ----------------------
15527       -- Set_Modular_Size --
15528       ----------------------
15529
15530       procedure Set_Modular_Size (Bits : Int) is
15531       begin
15532          Set_RM_Size (T, UI_From_Int (Bits));
15533
15534          if Bits <= 8 then
15535             Init_Esize (T, 8);
15536
15537          elsif Bits <= 16 then
15538             Init_Esize (T, 16);
15539
15540          elsif Bits <= 32 then
15541             Init_Esize (T, 32);
15542
15543          else
15544             Init_Esize (T, System_Max_Binary_Modulus_Power);
15545          end if;
15546
15547          if not Non_Binary_Modulus (T)
15548            and then Esize (T) = RM_Size (T)
15549          then
15550             Set_Is_Known_Valid (T);
15551          end if;
15552       end Set_Modular_Size;
15553
15554    --  Start of processing for Modular_Type_Declaration
15555
15556    begin
15557       Analyze_And_Resolve (Mod_Expr, Any_Integer);
15558       Set_Etype (T, T);
15559       Set_Ekind (T, E_Modular_Integer_Type);
15560       Init_Alignment (T);
15561       Set_Is_Constrained (T);
15562
15563       if not Is_OK_Static_Expression (Mod_Expr) then
15564          Flag_Non_Static_Expr
15565            ("non-static expression used for modular type bound!", Mod_Expr);
15566          M_Val := 2 ** System_Max_Binary_Modulus_Power;
15567       else
15568          M_Val := Expr_Value (Mod_Expr);
15569       end if;
15570
15571       if M_Val < 1 then
15572          Error_Msg_N ("modulus value must be positive", Mod_Expr);
15573          M_Val := 2 ** System_Max_Binary_Modulus_Power;
15574       end if;
15575
15576       Set_Modulus (T, M_Val);
15577
15578       --   Create bounds for the modular type based on the modulus given in
15579       --   the type declaration and then analyze and resolve those bounds.
15580
15581       Set_Scalar_Range (T,
15582         Make_Range (Sloc (Mod_Expr),
15583           Low_Bound  =>
15584             Make_Integer_Literal (Sloc (Mod_Expr), 0),
15585           High_Bound =>
15586             Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
15587
15588       --  Properly analyze the literals for the range. We do this manually
15589       --  because we can't go calling Resolve, since we are resolving these
15590       --  bounds with the type, and this type is certainly not complete yet!
15591
15592       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
15593       Set_Etype (High_Bound (Scalar_Range (T)), T);
15594       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
15595       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
15596
15597       --  Loop through powers of two to find number of bits required
15598
15599       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
15600
15601          --  Binary case
15602
15603          if M_Val = 2 ** Bits then
15604             Set_Modular_Size (Bits);
15605             return;
15606
15607          --  Non-binary case
15608
15609          elsif M_Val < 2 ** Bits then
15610             Set_Non_Binary_Modulus (T);
15611
15612             if Bits > System_Max_Nonbinary_Modulus_Power then
15613                Error_Msg_Uint_1 :=
15614                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
15615                Error_Msg_F
15616                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
15617                Set_Modular_Size (System_Max_Binary_Modulus_Power);
15618                return;
15619
15620             else
15621                --  In the non-binary case, set size as per RM 13.3(55)
15622
15623                Set_Modular_Size (Bits);
15624                return;
15625             end if;
15626          end if;
15627
15628       end loop;
15629
15630       --  If we fall through, then the size exceed System.Max_Binary_Modulus
15631       --  so we just signal an error and set the maximum size.
15632
15633       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
15634       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
15635
15636       Set_Modular_Size (System_Max_Binary_Modulus_Power);
15637       Init_Alignment (T);
15638
15639    end Modular_Type_Declaration;
15640
15641    --------------------------
15642    -- New_Concatenation_Op --
15643    --------------------------
15644
15645    procedure New_Concatenation_Op (Typ : Entity_Id) is
15646       Loc : constant Source_Ptr := Sloc (Typ);
15647       Op  : Entity_Id;
15648
15649       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
15650       --  Create abbreviated declaration for the formal of a predefined
15651       --  Operator 'Op' of type 'Typ'
15652
15653       --------------------
15654       -- Make_Op_Formal --
15655       --------------------
15656
15657       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
15658          Formal : Entity_Id;
15659       begin
15660          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
15661          Set_Etype (Formal, Typ);
15662          Set_Mechanism (Formal, Default_Mechanism);
15663          return Formal;
15664       end Make_Op_Formal;
15665
15666    --  Start of processing for New_Concatenation_Op
15667
15668    begin
15669       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
15670
15671       Set_Ekind                   (Op, E_Operator);
15672       Set_Scope                   (Op, Current_Scope);
15673       Set_Etype                   (Op, Typ);
15674       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
15675       Set_Is_Immediately_Visible  (Op);
15676       Set_Is_Intrinsic_Subprogram (Op);
15677       Set_Has_Completion          (Op);
15678       Append_Entity               (Op, Current_Scope);
15679
15680       Set_Name_Entity_Id (Name_Op_Concat, Op);
15681
15682       Append_Entity (Make_Op_Formal (Typ, Op), Op);
15683       Append_Entity (Make_Op_Formal (Typ, Op), Op);
15684    end New_Concatenation_Op;
15685
15686    -------------------------
15687    -- OK_For_Limited_Init --
15688    -------------------------
15689
15690    --  ???Check all calls of this, and compare the conditions under which it's
15691    --  called.
15692
15693    function OK_For_Limited_Init
15694      (Typ : Entity_Id;
15695       Exp : Node_Id) return Boolean
15696    is
15697    begin
15698       return Is_CPP_Constructor_Call (Exp)
15699         or else (Ada_Version >= Ada_05
15700                   and then not Debug_Flag_Dot_L
15701                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
15702    end OK_For_Limited_Init;
15703
15704    -------------------------------
15705    -- OK_For_Limited_Init_In_05 --
15706    -------------------------------
15707
15708    function OK_For_Limited_Init_In_05
15709      (Typ : Entity_Id;
15710       Exp : Node_Id) return Boolean
15711    is
15712    begin
15713       --  An object of a limited interface type can be initialized with any
15714       --  expression of a nonlimited descendant type.
15715
15716       if Is_Class_Wide_Type (Typ)
15717         and then Is_Limited_Interface (Typ)
15718         and then not Is_Limited_Type (Etype (Exp))
15719       then
15720          return True;
15721       end if;
15722
15723       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
15724       --  case of limited aggregates (including extension aggregates), and
15725       --  function calls. The function call may have been give in prefixed
15726       --  notation, in which case the original node is an indexed component.
15727
15728       case Nkind (Original_Node (Exp)) is
15729          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
15730             return True;
15731
15732          when N_Qualified_Expression =>
15733             return
15734               OK_For_Limited_Init_In_05
15735                 (Typ, Expression (Original_Node (Exp)));
15736
15737          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
15738          --  with a function call, the expander has rewritten the call into an
15739          --  N_Type_Conversion node to force displacement of the pointer to
15740          --  reference the component containing the secondary dispatch table.
15741          --  Otherwise a type conversion is not a legal context.
15742          --  A return statement for a build-in-place function returning a
15743          --  synchronized type also introduces an unchecked conversion.
15744
15745          when N_Type_Conversion | N_Unchecked_Type_Conversion =>
15746             return not Comes_From_Source (Exp)
15747               and then
15748                 OK_For_Limited_Init_In_05
15749                   (Typ, Expression (Original_Node (Exp)));
15750
15751          when N_Indexed_Component | N_Selected_Component  =>
15752             return Nkind (Exp) = N_Function_Call;
15753
15754          --  A use of 'Input is a function call, hence allowed. Normally the
15755          --  attribute will be changed to a call, but the attribute by itself
15756          --  can occur with -gnatc.
15757
15758          when N_Attribute_Reference =>
15759             return Attribute_Name (Original_Node (Exp)) = Name_Input;
15760
15761          when others =>
15762             return False;
15763       end case;
15764    end OK_For_Limited_Init_In_05;
15765
15766    -------------------------------------------
15767    -- Ordinary_Fixed_Point_Type_Declaration --
15768    -------------------------------------------
15769
15770    procedure Ordinary_Fixed_Point_Type_Declaration
15771      (T   : Entity_Id;
15772       Def : Node_Id)
15773    is
15774       Loc           : constant Source_Ptr := Sloc (Def);
15775       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
15776       RRS           : constant Node_Id    := Real_Range_Specification (Def);
15777       Implicit_Base : Entity_Id;
15778       Delta_Val     : Ureal;
15779       Small_Val     : Ureal;
15780       Low_Val       : Ureal;
15781       High_Val      : Ureal;
15782
15783    begin
15784       Check_Restriction (No_Fixed_Point, Def);
15785
15786       --  Create implicit base type
15787
15788       Implicit_Base :=
15789         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
15790       Set_Etype (Implicit_Base, Implicit_Base);
15791
15792       --  Analyze and process delta expression
15793
15794       Analyze_And_Resolve (Delta_Expr, Any_Real);
15795
15796       Check_Delta_Expression (Delta_Expr);
15797       Delta_Val := Expr_Value_R (Delta_Expr);
15798
15799       Set_Delta_Value (Implicit_Base, Delta_Val);
15800
15801       --  Compute default small from given delta, which is the largest power
15802       --  of two that does not exceed the given delta value.
15803
15804       declare
15805          Tmp   : Ureal;
15806          Scale : Int;
15807
15808       begin
15809          Tmp := Ureal_1;
15810          Scale := 0;
15811
15812          if Delta_Val < Ureal_1 then
15813             while Delta_Val < Tmp loop
15814                Tmp := Tmp / Ureal_2;
15815                Scale := Scale + 1;
15816             end loop;
15817
15818          else
15819             loop
15820                Tmp := Tmp * Ureal_2;
15821                exit when Tmp > Delta_Val;
15822                Scale := Scale - 1;
15823             end loop;
15824          end if;
15825
15826          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
15827       end;
15828
15829       Set_Small_Value (Implicit_Base, Small_Val);
15830
15831       --  If no range was given, set a dummy range
15832
15833       if RRS <= Empty_Or_Error then
15834          Low_Val  := -Small_Val;
15835          High_Val := Small_Val;
15836
15837       --  Otherwise analyze and process given range
15838
15839       else
15840          declare
15841             Low  : constant Node_Id := Low_Bound  (RRS);
15842             High : constant Node_Id := High_Bound (RRS);
15843
15844          begin
15845             Analyze_And_Resolve (Low, Any_Real);
15846             Analyze_And_Resolve (High, Any_Real);
15847             Check_Real_Bound (Low);
15848             Check_Real_Bound (High);
15849
15850             --  Obtain and set the range
15851
15852             Low_Val  := Expr_Value_R (Low);
15853             High_Val := Expr_Value_R (High);
15854
15855             if Low_Val > High_Val then
15856                Error_Msg_NE ("?fixed point type& has null range", Def, T);
15857             end if;
15858          end;
15859       end if;
15860
15861       --  The range for both the implicit base and the declared first subtype
15862       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
15863       --  set a temporary range in place. Note that the bounds of the base
15864       --  type will be widened to be symmetrical and to fill the available
15865       --  bits when the type is frozen.
15866
15867       --  We could do this with all discrete types, and probably should, but
15868       --  we absolutely have to do it for fixed-point, since the end-points
15869       --  of the range and the size are determined by the small value, which
15870       --  could be reset before the freeze point.
15871
15872       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
15873       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
15874
15875       --  Complete definition of first subtype
15876
15877       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
15878       Set_Etype          (T, Implicit_Base);
15879       Init_Size_Align    (T);
15880       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
15881       Set_Small_Value    (T, Small_Val);
15882       Set_Delta_Value    (T, Delta_Val);
15883       Set_Is_Constrained (T);
15884
15885    end Ordinary_Fixed_Point_Type_Declaration;
15886
15887    ----------------------------------------
15888    -- Prepare_Private_Subtype_Completion --
15889    ----------------------------------------
15890
15891    procedure Prepare_Private_Subtype_Completion
15892      (Id          : Entity_Id;
15893       Related_Nod : Node_Id)
15894    is
15895       Id_B   : constant Entity_Id := Base_Type (Id);
15896       Full_B : constant Entity_Id := Full_View (Id_B);
15897       Full   : Entity_Id;
15898
15899    begin
15900       if Present (Full_B) then
15901
15902          --  The Base_Type is already completed, we can complete the subtype
15903          --  now. We have to create a new entity with the same name, Thus we
15904          --  can't use Create_Itype.
15905
15906          --  This is messy, should be fixed ???
15907
15908          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
15909          Set_Is_Itype (Full);
15910          Set_Associated_Node_For_Itype (Full, Related_Nod);
15911          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
15912       end if;
15913
15914       --  The parent subtype may be private, but the base might not, in some
15915       --  nested instances. In that case, the subtype does not need to be
15916       --  exchanged. It would still be nice to make private subtypes and their
15917       --  bases consistent at all times ???
15918
15919       if Is_Private_Type (Id_B) then
15920          Append_Elmt (Id, Private_Dependents (Id_B));
15921       end if;
15922
15923    end Prepare_Private_Subtype_Completion;
15924
15925    ---------------------------
15926    -- Process_Discriminants --
15927    ---------------------------
15928
15929    procedure Process_Discriminants
15930      (N    : Node_Id;
15931       Prev : Entity_Id := Empty)
15932    is
15933       Elist               : constant Elist_Id := New_Elmt_List;
15934       Id                  : Node_Id;
15935       Discr               : Node_Id;
15936       Discr_Number        : Uint;
15937       Discr_Type          : Entity_Id;
15938       Default_Present     : Boolean := False;
15939       Default_Not_Present : Boolean := False;
15940
15941    begin
15942       --  A composite type other than an array type can have discriminants.
15943       --  On entry, the current scope is the composite type.
15944
15945       --  The discriminants are initially entered into the scope of the type
15946       --  via Enter_Name with the default Ekind of E_Void to prevent premature
15947       --  use, as explained at the end of this procedure.
15948
15949       Discr := First (Discriminant_Specifications (N));
15950       while Present (Discr) loop
15951          Enter_Name (Defining_Identifier (Discr));
15952
15953          --  For navigation purposes we add a reference to the discriminant
15954          --  in the entity for the type. If the current declaration is a
15955          --  completion, place references on the partial view. Otherwise the
15956          --  type is the current scope.
15957
15958          if Present (Prev) then
15959
15960             --  The references go on the partial view, if present. If the
15961             --  partial view has discriminants, the references have been
15962             --  generated already.
15963
15964             if not Has_Discriminants (Prev) then
15965                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
15966             end if;
15967          else
15968             Generate_Reference
15969               (Current_Scope, Defining_Identifier (Discr), 'd');
15970          end if;
15971
15972          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
15973             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
15974
15975             --  Ada 2005 (AI-254)
15976
15977             if Present (Access_To_Subprogram_Definition
15978                          (Discriminant_Type (Discr)))
15979               and then Protected_Present (Access_To_Subprogram_Definition
15980                                            (Discriminant_Type (Discr)))
15981             then
15982                Discr_Type :=
15983                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
15984             end if;
15985
15986          else
15987             Find_Type (Discriminant_Type (Discr));
15988             Discr_Type := Etype (Discriminant_Type (Discr));
15989
15990             if Error_Posted (Discriminant_Type (Discr)) then
15991                Discr_Type := Any_Type;
15992             end if;
15993          end if;
15994
15995          if Is_Access_Type (Discr_Type) then
15996
15997             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
15998             --  record types
15999
16000             if Ada_Version < Ada_05 then
16001                Check_Access_Discriminant_Requires_Limited
16002                  (Discr, Discriminant_Type (Discr));
16003             end if;
16004
16005             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
16006                Error_Msg_N
16007                  ("(Ada 83) access discriminant not allowed", Discr);
16008             end if;
16009
16010          elsif not Is_Discrete_Type (Discr_Type) then
16011             Error_Msg_N ("discriminants must have a discrete or access type",
16012               Discriminant_Type (Discr));
16013          end if;
16014
16015          Set_Etype (Defining_Identifier (Discr), Discr_Type);
16016
16017          --  If a discriminant specification includes the assignment compound
16018          --  delimiter followed by an expression, the expression is the default
16019          --  expression of the discriminant; the default expression must be of
16020          --  the type of the discriminant. (RM 3.7.1) Since this expression is
16021          --  a default expression, we do the special preanalysis, since this
16022          --  expression does not freeze (see "Handling of Default and Per-
16023          --  Object Expressions" in spec of package Sem).
16024
16025          if Present (Expression (Discr)) then
16026             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
16027
16028             if Nkind (N) = N_Formal_Type_Declaration then
16029                Error_Msg_N
16030                  ("discriminant defaults not allowed for formal type",
16031                   Expression (Discr));
16032
16033             --  Tagged types cannot have defaulted discriminants, but a
16034             --  non-tagged private type with defaulted discriminants
16035             --   can have a tagged completion.
16036
16037             elsif Is_Tagged_Type (Current_Scope)
16038               and then Comes_From_Source (N)
16039             then
16040                Error_Msg_N
16041                  ("discriminants of tagged type cannot have defaults",
16042                   Expression (Discr));
16043
16044             else
16045                Default_Present := True;
16046                Append_Elmt (Expression (Discr), Elist);
16047
16048                --  Tag the defining identifiers for the discriminants with
16049                --  their corresponding default expressions from the tree.
16050
16051                Set_Discriminant_Default_Value
16052                  (Defining_Identifier (Discr), Expression (Discr));
16053             end if;
16054
16055          else
16056             Default_Not_Present := True;
16057          end if;
16058
16059          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
16060          --  Discr_Type but with the null-exclusion attribute
16061
16062          if Ada_Version >= Ada_05 then
16063
16064             --  Ada 2005 (AI-231): Static checks
16065
16066             if Can_Never_Be_Null (Discr_Type) then
16067                Null_Exclusion_Static_Checks (Discr);
16068
16069             elsif Is_Access_Type (Discr_Type)
16070               and then Null_Exclusion_Present (Discr)
16071
16072                --  No need to check itypes because in their case this check
16073                --  was done at their point of creation
16074
16075               and then not Is_Itype (Discr_Type)
16076             then
16077                if Can_Never_Be_Null (Discr_Type) then
16078                   Error_Msg_NE
16079                     ("`NOT NULL` not allowed (& already excludes null)",
16080                      Discr,
16081                      Discr_Type);
16082                end if;
16083
16084                Set_Etype (Defining_Identifier (Discr),
16085                  Create_Null_Excluding_Itype
16086                    (T           => Discr_Type,
16087                     Related_Nod => Discr));
16088
16089             --  Check for improper null exclusion if the type is otherwise
16090             --  legal for a discriminant.
16091
16092             elsif Null_Exclusion_Present (Discr)
16093               and then Is_Discrete_Type (Discr_Type)
16094             then
16095                Error_Msg_N
16096                  ("null exclusion can only apply to an access type", Discr);
16097             end if;
16098
16099             --  Ada 2005 (AI-402): access discriminants of nonlimited types
16100             --  can't have defaults. Synchronized types, or types that are
16101             --  explicitly limited are fine, but special tests apply to derived
16102             --  types in generics: in a generic body we have to assume the
16103             --  worst, and therefore defaults are not allowed if the parent is
16104             --  a generic formal private type (see ACATS B370001).
16105
16106             if Is_Access_Type (Discr_Type) then
16107                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
16108                  or else not Default_Present
16109                  or else Is_Limited_Record (Current_Scope)
16110                  or else Is_Concurrent_Type (Current_Scope)
16111                  or else Is_Concurrent_Record_Type (Current_Scope)
16112                  or else Ekind (Current_Scope) = E_Limited_Private_Type
16113                then
16114                   if not Is_Derived_Type (Current_Scope)
16115                     or else not Is_Generic_Type (Etype (Current_Scope))
16116                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
16117                     or else Limited_Present
16118                               (Type_Definition (Parent (Current_Scope)))
16119                   then
16120                      null;
16121
16122                   else
16123                      Error_Msg_N ("access discriminants of nonlimited types",
16124                          Expression (Discr));
16125                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
16126                   end if;
16127
16128                elsif Present (Expression (Discr)) then
16129                   Error_Msg_N
16130                     ("(Ada 2005) access discriminants of nonlimited types",
16131                      Expression (Discr));
16132                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
16133                end if;
16134             end if;
16135          end if;
16136
16137          Next (Discr);
16138       end loop;
16139
16140       --  An element list consisting of the default expressions of the
16141       --  discriminants is constructed in the above loop and used to set
16142       --  the Discriminant_Constraint attribute for the type. If an object
16143       --  is declared of this (record or task) type without any explicit
16144       --  discriminant constraint given, this element list will form the
16145       --  actual parameters for the corresponding initialization procedure
16146       --  for the type.
16147
16148       Set_Discriminant_Constraint (Current_Scope, Elist);
16149       Set_Stored_Constraint (Current_Scope, No_Elist);
16150
16151       --  Default expressions must be provided either for all or for none
16152       --  of the discriminants of a discriminant part. (RM 3.7.1)
16153
16154       if Default_Present and then Default_Not_Present then
16155          Error_Msg_N
16156            ("incomplete specification of defaults for discriminants", N);
16157       end if;
16158
16159       --  The use of the name of a discriminant is not allowed in default
16160       --  expressions of a discriminant part if the specification of the
16161       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
16162
16163       --  To detect this, the discriminant names are entered initially with an
16164       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
16165       --  attempt to use a void entity (for example in an expression that is
16166       --  type-checked) produces the error message: premature usage. Now after
16167       --  completing the semantic analysis of the discriminant part, we can set
16168       --  the Ekind of all the discriminants appropriately.
16169
16170       Discr := First (Discriminant_Specifications (N));
16171       Discr_Number := Uint_1;
16172       while Present (Discr) loop
16173          Id := Defining_Identifier (Discr);
16174          Set_Ekind (Id, E_Discriminant);
16175          Init_Component_Location (Id);
16176          Init_Esize (Id);
16177          Set_Discriminant_Number (Id, Discr_Number);
16178
16179          --  Make sure this is always set, even in illegal programs
16180
16181          Set_Corresponding_Discriminant (Id, Empty);
16182
16183          --  Initialize the Original_Record_Component to the entity itself.
16184          --  Inherit_Components will propagate the right value to
16185          --  discriminants in derived record types.
16186
16187          Set_Original_Record_Component (Id, Id);
16188
16189          --  Create the discriminal for the discriminant
16190
16191          Build_Discriminal (Id);
16192
16193          Next (Discr);
16194          Discr_Number := Discr_Number + 1;
16195       end loop;
16196
16197       Set_Has_Discriminants (Current_Scope);
16198    end Process_Discriminants;
16199
16200    -----------------------
16201    -- Process_Full_View --
16202    -----------------------
16203
16204    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
16205       Priv_Parent : Entity_Id;
16206       Full_Parent : Entity_Id;
16207       Full_Indic  : Node_Id;
16208
16209       procedure Collect_Implemented_Interfaces
16210         (Typ    : Entity_Id;
16211          Ifaces : Elist_Id);
16212       --  Ada 2005: Gather all the interfaces that Typ directly or
16213       --  inherently implements. Duplicate entries are not added to
16214       --  the list Ifaces.
16215
16216       ------------------------------------
16217       -- Collect_Implemented_Interfaces --
16218       ------------------------------------
16219
16220       procedure Collect_Implemented_Interfaces
16221         (Typ    : Entity_Id;
16222          Ifaces : Elist_Id)
16223       is
16224          Iface      : Entity_Id;
16225          Iface_Elmt : Elmt_Id;
16226
16227       begin
16228          --  Abstract interfaces are only associated with tagged record types
16229
16230          if not Is_Tagged_Type (Typ)
16231            or else not Is_Record_Type (Typ)
16232          then
16233             return;
16234          end if;
16235
16236          --  Recursively climb to the ancestors
16237
16238          if Etype (Typ) /= Typ
16239
16240             --  Protect the frontend against wrong cyclic declarations like:
16241
16242             --     type B is new A with private;
16243             --     type C is new A with private;
16244             --  private
16245             --     type B is new C with null record;
16246             --     type C is new B with null record;
16247
16248            and then Etype (Typ) /= Priv_T
16249            and then Etype (Typ) /= Full_T
16250          then
16251             --  Keep separate the management of private type declarations
16252
16253             if Ekind (Typ) = E_Record_Type_With_Private then
16254
16255                --  Handle the following erronous case:
16256                --      type Private_Type is tagged private;
16257                --   private
16258                --      type Private_Type is new Type_Implementing_Iface;
16259
16260                if Present (Full_View (Typ))
16261                  and then Etype (Typ) /= Full_View (Typ)
16262                then
16263                   if Is_Interface (Etype (Typ)) then
16264                      Append_Unique_Elmt (Etype (Typ), Ifaces);
16265                   end if;
16266
16267                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16268                end if;
16269
16270             --  Non-private types
16271
16272             else
16273                if Is_Interface (Etype (Typ)) then
16274                   Append_Unique_Elmt (Etype (Typ), Ifaces);
16275                end if;
16276
16277                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16278             end if;
16279          end if;
16280
16281          --  Handle entities in the list of abstract interfaces
16282
16283          if Present (Interfaces (Typ)) then
16284             Iface_Elmt := First_Elmt (Interfaces (Typ));
16285             while Present (Iface_Elmt) loop
16286                Iface := Node (Iface_Elmt);
16287
16288                pragma Assert (Is_Interface (Iface));
16289
16290                if not Contain_Interface (Iface, Ifaces) then
16291                   Append_Elmt (Iface, Ifaces);
16292                   Collect_Implemented_Interfaces (Iface, Ifaces);
16293                end if;
16294
16295                Next_Elmt (Iface_Elmt);
16296             end loop;
16297          end if;
16298       end Collect_Implemented_Interfaces;
16299
16300    --  Start of processing for Process_Full_View
16301
16302    begin
16303       --  First some sanity checks that must be done after semantic
16304       --  decoration of the full view and thus cannot be placed with other
16305       --  similar checks in Find_Type_Name
16306
16307       if not Is_Limited_Type (Priv_T)
16308         and then (Is_Limited_Type (Full_T)
16309                    or else Is_Limited_Composite (Full_T))
16310       then
16311          Error_Msg_N
16312            ("completion of nonlimited type cannot be limited", Full_T);
16313          Explain_Limited_Type (Full_T, Full_T);
16314
16315       elsif Is_Abstract_Type (Full_T)
16316         and then not Is_Abstract_Type (Priv_T)
16317       then
16318          Error_Msg_N
16319            ("completion of nonabstract type cannot be abstract", Full_T);
16320
16321       elsif Is_Tagged_Type (Priv_T)
16322         and then Is_Limited_Type (Priv_T)
16323         and then not Is_Limited_Type (Full_T)
16324       then
16325          --  If pragma CPP_Class was applied to the private declaration
16326          --  propagate the limitedness to the full-view
16327
16328          if Is_CPP_Class (Priv_T) then
16329             Set_Is_Limited_Record (Full_T);
16330
16331          --  GNAT allow its own definition of Limited_Controlled to disobey
16332          --  this rule in order in ease the implementation. The next test is
16333          --  safe because Root_Controlled is defined in a private system child
16334
16335          elsif Etype (Full_T) = Full_View (RTE (RE_Root_Controlled)) then
16336             Set_Is_Limited_Composite (Full_T);
16337          else
16338             Error_Msg_N
16339               ("completion of limited tagged type must be limited", Full_T);
16340          end if;
16341
16342       elsif Is_Generic_Type (Priv_T) then
16343          Error_Msg_N ("generic type cannot have a completion", Full_T);
16344       end if;
16345
16346       --  Check that ancestor interfaces of private and full views are
16347       --  consistent. We omit this check for synchronized types because
16348       --  they are performed on the corresponding record type when frozen.
16349
16350       if Ada_Version >= Ada_05
16351         and then Is_Tagged_Type (Priv_T)
16352         and then Is_Tagged_Type (Full_T)
16353         and then not Is_Concurrent_Type (Full_T)
16354       then
16355          declare
16356             Iface         : Entity_Id;
16357             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
16358             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
16359
16360          begin
16361             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
16362             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
16363
16364             --  Ada 2005 (AI-251): The partial view shall be a descendant of
16365             --  an interface type if and only if the full type is descendant
16366             --  of the interface type (AARM 7.3 (7.3/2).
16367
16368             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
16369
16370             if Present (Iface) then
16371                Error_Msg_NE
16372                  ("interface & not implemented by full type " &
16373                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
16374             end if;
16375
16376             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
16377
16378             if Present (Iface) then
16379                Error_Msg_NE
16380                  ("interface & not implemented by partial view " &
16381                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
16382             end if;
16383          end;
16384       end if;
16385
16386       if Is_Tagged_Type (Priv_T)
16387         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16388         and then Is_Derived_Type (Full_T)
16389       then
16390          Priv_Parent := Etype (Priv_T);
16391
16392          --  The full view of a private extension may have been transformed
16393          --  into an unconstrained derived type declaration and a subtype
16394          --  declaration (see build_derived_record_type for details).
16395
16396          if Nkind (N) = N_Subtype_Declaration then
16397             Full_Indic  := Subtype_Indication (N);
16398             Full_Parent := Etype (Base_Type (Full_T));
16399          else
16400             Full_Indic  := Subtype_Indication (Type_Definition (N));
16401             Full_Parent := Etype (Full_T);
16402          end if;
16403
16404          --  Check that the parent type of the full type is a descendant of
16405          --  the ancestor subtype given in the private extension. If either
16406          --  entity has an Etype equal to Any_Type then we had some previous
16407          --  error situation [7.3(8)].
16408
16409          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
16410             return;
16411
16412          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
16413          --  any order. Therefore we don't have to check that its parent must
16414          --  be a descendant of the parent of the private type declaration.
16415
16416          elsif Is_Interface (Priv_Parent)
16417            and then Is_Interface (Full_Parent)
16418          then
16419             null;
16420
16421          --  Ada 2005 (AI-251): If the parent of the private type declaration
16422          --  is an interface there is no need to check that it is an ancestor
16423          --  of the associated full type declaration. The required tests for
16424          --  this case are performed by Build_Derived_Record_Type.
16425
16426          elsif not Is_Interface (Base_Type (Priv_Parent))
16427            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
16428          then
16429             Error_Msg_N
16430               ("parent of full type must descend from parent"
16431                   & " of private extension", Full_Indic);
16432
16433          --  Check the rules of 7.3(10): if the private extension inherits
16434          --  known discriminants, then the full type must also inherit those
16435          --  discriminants from the same (ancestor) type, and the parent
16436          --  subtype of the full type must be constrained if and only if
16437          --  the ancestor subtype of the private extension is constrained.
16438
16439          elsif No (Discriminant_Specifications (Parent (Priv_T)))
16440            and then not Has_Unknown_Discriminants (Priv_T)
16441            and then Has_Discriminants (Base_Type (Priv_Parent))
16442          then
16443             declare
16444                Priv_Indic  : constant Node_Id :=
16445                                Subtype_Indication (Parent (Priv_T));
16446
16447                Priv_Constr : constant Boolean :=
16448                                Is_Constrained (Priv_Parent)
16449                                  or else
16450                                    Nkind (Priv_Indic) = N_Subtype_Indication
16451                                  or else Is_Constrained (Entity (Priv_Indic));
16452
16453                Full_Constr : constant Boolean :=
16454                                Is_Constrained (Full_Parent)
16455                                  or else
16456                                    Nkind (Full_Indic) = N_Subtype_Indication
16457                                  or else Is_Constrained (Entity (Full_Indic));
16458
16459                Priv_Discr : Entity_Id;
16460                Full_Discr : Entity_Id;
16461
16462             begin
16463                Priv_Discr := First_Discriminant (Priv_Parent);
16464                Full_Discr := First_Discriminant (Full_Parent);
16465                while Present (Priv_Discr) and then Present (Full_Discr) loop
16466                   if Original_Record_Component (Priv_Discr) =
16467                      Original_Record_Component (Full_Discr)
16468                     or else
16469                      Corresponding_Discriminant (Priv_Discr) =
16470                      Corresponding_Discriminant (Full_Discr)
16471                   then
16472                      null;
16473                   else
16474                      exit;
16475                   end if;
16476
16477                   Next_Discriminant (Priv_Discr);
16478                   Next_Discriminant (Full_Discr);
16479                end loop;
16480
16481                if Present (Priv_Discr) or else Present (Full_Discr) then
16482                   Error_Msg_N
16483                     ("full view must inherit discriminants of the parent type"
16484                      & " used in the private extension", Full_Indic);
16485
16486                elsif Priv_Constr and then not Full_Constr then
16487                   Error_Msg_N
16488                     ("parent subtype of full type must be constrained",
16489                      Full_Indic);
16490
16491                elsif Full_Constr and then not Priv_Constr then
16492                   Error_Msg_N
16493                     ("parent subtype of full type must be unconstrained",
16494                      Full_Indic);
16495                end if;
16496             end;
16497
16498          --  Check the rules of 7.3(12): if a partial view has neither known
16499          --  or unknown discriminants, then the full type declaration shall
16500          --  define a definite subtype.
16501
16502          elsif      not Has_Unknown_Discriminants (Priv_T)
16503            and then not Has_Discriminants (Priv_T)
16504            and then not Is_Constrained (Full_T)
16505          then
16506             Error_Msg_N
16507               ("full view must define a constrained type if partial view"
16508                 & " has no discriminants", Full_T);
16509          end if;
16510
16511          --  ??????? Do we implement the following properly ?????
16512          --  If the ancestor subtype of a private extension has constrained
16513          --  discriminants, then the parent subtype of the full view shall
16514          --  impose a statically matching constraint on those discriminants
16515          --  [7.3(13)].
16516
16517       else
16518          --  For untagged types, verify that a type without discriminants
16519          --  is not completed with an unconstrained type.
16520
16521          if not Is_Indefinite_Subtype (Priv_T)
16522            and then Is_Indefinite_Subtype (Full_T)
16523          then
16524             Error_Msg_N ("full view of type must be definite subtype", Full_T);
16525          end if;
16526       end if;
16527
16528       --  AI-419: verify that the use of "limited" is consistent
16529
16530       declare
16531          Orig_Decl : constant Node_Id := Original_Node (N);
16532
16533       begin
16534          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16535            and then not Limited_Present (Parent (Priv_T))
16536            and then not Synchronized_Present (Parent (Priv_T))
16537            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
16538            and then Nkind
16539              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
16540            and then Limited_Present (Type_Definition (Orig_Decl))
16541          then
16542             Error_Msg_N
16543               ("full view of non-limited extension cannot be limited", N);
16544          end if;
16545       end;
16546
16547       --  Ada 2005 (AI-443): A synchronized private extension must be
16548       --  completed by a task or protected type.
16549
16550       if Ada_Version >= Ada_05
16551         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16552         and then Synchronized_Present (Parent (Priv_T))
16553         and then not Is_Concurrent_Type (Full_T)
16554       then
16555          Error_Msg_N ("full view of synchronized extension must " &
16556                       "be synchronized type", N);
16557       end if;
16558
16559       --  Ada 2005 AI-363: if the full view has discriminants with
16560       --  defaults, it is illegal to declare constrained access subtypes
16561       --  whose designated type is the current type. This allows objects
16562       --  of the type that are declared in the heap to be unconstrained.
16563
16564       if not Has_Unknown_Discriminants (Priv_T)
16565         and then not Has_Discriminants (Priv_T)
16566         and then Has_Discriminants (Full_T)
16567         and then
16568           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
16569       then
16570          Set_Has_Constrained_Partial_View (Full_T);
16571          Set_Has_Constrained_Partial_View (Priv_T);
16572       end if;
16573
16574       --  Create a full declaration for all its subtypes recorded in
16575       --  Private_Dependents and swap them similarly to the base type. These
16576       --  are subtypes that have been define before the full declaration of
16577       --  the private type. We also swap the entry in Private_Dependents list
16578       --  so we can properly restore the private view on exit from the scope.
16579
16580       declare
16581          Priv_Elmt : Elmt_Id;
16582          Priv      : Entity_Id;
16583          Full      : Entity_Id;
16584
16585       begin
16586          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
16587          while Present (Priv_Elmt) loop
16588             Priv := Node (Priv_Elmt);
16589
16590             if Ekind_In (Priv, E_Private_Subtype,
16591                                E_Limited_Private_Subtype,
16592                                E_Record_Subtype_With_Private)
16593             then
16594                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
16595                Set_Is_Itype (Full);
16596                Set_Parent (Full, Parent (Priv));
16597                Set_Associated_Node_For_Itype (Full, N);
16598
16599                --  Now we need to complete the private subtype, but since the
16600                --  base type has already been swapped, we must also swap the
16601                --  subtypes (and thus, reverse the arguments in the call to
16602                --  Complete_Private_Subtype).
16603
16604                Copy_And_Swap (Priv, Full);
16605                Complete_Private_Subtype (Full, Priv, Full_T, N);
16606                Replace_Elmt (Priv_Elmt, Full);
16607             end if;
16608
16609             Next_Elmt (Priv_Elmt);
16610          end loop;
16611       end;
16612
16613       --  If the private view was tagged, copy the new primitive operations
16614       --  from the private view to the full view.
16615
16616       if Is_Tagged_Type (Full_T) then
16617          declare
16618             Disp_Typ  : Entity_Id;
16619             Full_List : Elist_Id;
16620             Prim      : Entity_Id;
16621             Prim_Elmt : Elmt_Id;
16622             Priv_List : Elist_Id;
16623
16624             function Contains
16625               (E : Entity_Id;
16626                L : Elist_Id) return Boolean;
16627             --  Determine whether list L contains element E
16628
16629             --------------
16630             -- Contains --
16631             --------------
16632
16633             function Contains
16634               (E : Entity_Id;
16635                L : Elist_Id) return Boolean
16636             is
16637                List_Elmt : Elmt_Id;
16638
16639             begin
16640                List_Elmt := First_Elmt (L);
16641                while Present (List_Elmt) loop
16642                   if Node (List_Elmt) = E then
16643                      return True;
16644                   end if;
16645
16646                   Next_Elmt (List_Elmt);
16647                end loop;
16648
16649                return False;
16650             end Contains;
16651
16652          --  Start of processing
16653
16654          begin
16655             if Is_Tagged_Type (Priv_T) then
16656                Priv_List := Primitive_Operations (Priv_T);
16657                Prim_Elmt := First_Elmt (Priv_List);
16658
16659                --  In the case of a concurrent type completing a private tagged
16660                --  type, primitives may have been declared in between the two
16661                --  views. These subprograms need to be wrapped the same way
16662                --  entries and protected procedures are handled because they
16663                --  cannot be directly shared by the two views.
16664
16665                if Is_Concurrent_Type (Full_T) then
16666                   declare
16667                      Conc_Typ  : constant Entity_Id :=
16668                                    Corresponding_Record_Type (Full_T);
16669                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
16670                      Wrap_Spec : Node_Id;
16671
16672                   begin
16673                      while Present (Prim_Elmt) loop
16674                         Prim := Node (Prim_Elmt);
16675
16676                         if Comes_From_Source (Prim)
16677                           and then not Is_Abstract_Subprogram (Prim)
16678                         then
16679                            Wrap_Spec :=
16680                              Make_Subprogram_Declaration (Sloc (Prim),
16681                                Specification =>
16682                                  Build_Wrapper_Spec
16683                                    (Subp_Id => Prim,
16684                                     Obj_Typ => Conc_Typ,
16685                                     Formals =>
16686                                       Parameter_Specifications (
16687                                         Parent (Prim))));
16688
16689                            Insert_After (Curr_Nod, Wrap_Spec);
16690                            Curr_Nod := Wrap_Spec;
16691
16692                            Analyze (Wrap_Spec);
16693                         end if;
16694
16695                         Next_Elmt (Prim_Elmt);
16696                      end loop;
16697
16698                      return;
16699                   end;
16700
16701                --  For non-concurrent types, transfer explicit primitives, but
16702                --  omit those inherited from the parent of the private view
16703                --  since they will be re-inherited later on.
16704
16705                else
16706                   Full_List := Primitive_Operations (Full_T);
16707
16708                   while Present (Prim_Elmt) loop
16709                      Prim := Node (Prim_Elmt);
16710
16711                      if Comes_From_Source (Prim)
16712                        and then not Contains (Prim, Full_List)
16713                      then
16714                         Append_Elmt (Prim, Full_List);
16715                      end if;
16716
16717                      Next_Elmt (Prim_Elmt);
16718                   end loop;
16719                end if;
16720
16721             --  Untagged private view
16722
16723             else
16724                Full_List := Primitive_Operations (Full_T);
16725
16726                --  In this case the partial view is untagged, so here we locate
16727                --  all of the earlier primitives that need to be treated as
16728                --  dispatching (those that appear between the two views). Note
16729                --  that these additional operations must all be new operations
16730                --  (any earlier operations that override inherited operations
16731                --  of the full view will already have been inserted in the
16732                --  primitives list, marked by Check_Operation_From_Private_View
16733                --  as dispatching. Note that implicit "/=" operators are
16734                --  excluded from being added to the primitives list since they
16735                --  shouldn't be treated as dispatching (tagged "/=" is handled
16736                --  specially).
16737
16738                Prim := Next_Entity (Full_T);
16739                while Present (Prim) and then Prim /= Priv_T loop
16740                   if Ekind_In (Prim, E_Procedure, E_Function) then
16741                      Disp_Typ := Find_Dispatching_Type (Prim);
16742
16743                      if Disp_Typ = Full_T
16744                        and then (Chars (Prim) /= Name_Op_Ne
16745                                   or else Comes_From_Source (Prim))
16746                      then
16747                         Check_Controlling_Formals (Full_T, Prim);
16748
16749                         if not Is_Dispatching_Operation (Prim) then
16750                            Append_Elmt (Prim, Full_List);
16751                            Set_Is_Dispatching_Operation (Prim, True);
16752                            Set_DT_Position (Prim, No_Uint);
16753                         end if;
16754
16755                      elsif Is_Dispatching_Operation (Prim)
16756                        and then Disp_Typ  /= Full_T
16757                      then
16758
16759                         --  Verify that it is not otherwise controlled by a
16760                         --  formal or a return value of type T.
16761
16762                         Check_Controlling_Formals (Disp_Typ, Prim);
16763                      end if;
16764                   end if;
16765
16766                   Next_Entity (Prim);
16767                end loop;
16768             end if;
16769
16770             --  For the tagged case, the two views can share the same primitive
16771             --  operations list and the same class-wide type. Update attributes
16772             --  of the class-wide type which depend on the full declaration.
16773
16774             if Is_Tagged_Type (Priv_T) then
16775                Set_Primitive_Operations (Priv_T, Full_List);
16776                Set_Class_Wide_Type
16777                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
16778
16779                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
16780             end if;
16781          end;
16782       end if;
16783
16784       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
16785
16786       if Known_To_Have_Preelab_Init (Priv_T) then
16787
16788          --  Case where there is a pragma Preelaborable_Initialization. We
16789          --  always allow this in predefined units, which is a bit of a kludge,
16790          --  but it means we don't have to struggle to meet the requirements in
16791          --  the RM for having Preelaborable Initialization. Otherwise we
16792          --  require that the type meets the RM rules. But we can't check that
16793          --  yet, because of the rule about overriding Ininitialize, so we
16794          --  simply set a flag that will be checked at freeze time.
16795
16796          if not In_Predefined_Unit (Full_T) then
16797             Set_Must_Have_Preelab_Init (Full_T);
16798          end if;
16799       end if;
16800
16801       --  If pragma CPP_Class was applied to the private type declaration,
16802       --  propagate it now to the full type declaration.
16803
16804       if Is_CPP_Class (Priv_T) then
16805          Set_Is_CPP_Class (Full_T);
16806          Set_Convention   (Full_T, Convention_CPP);
16807       end if;
16808
16809       --  If the private view has user specified stream attributes, then so has
16810       --  the full view.
16811
16812       if Has_Specified_Stream_Read (Priv_T) then
16813          Set_Has_Specified_Stream_Read (Full_T);
16814       end if;
16815       if Has_Specified_Stream_Write (Priv_T) then
16816          Set_Has_Specified_Stream_Write (Full_T);
16817       end if;
16818       if Has_Specified_Stream_Input (Priv_T) then
16819          Set_Has_Specified_Stream_Input (Full_T);
16820       end if;
16821       if Has_Specified_Stream_Output (Priv_T) then
16822          Set_Has_Specified_Stream_Output (Full_T);
16823       end if;
16824    end Process_Full_View;
16825
16826    -----------------------------------
16827    -- Process_Incomplete_Dependents --
16828    -----------------------------------
16829
16830    procedure Process_Incomplete_Dependents
16831      (N      : Node_Id;
16832       Full_T : Entity_Id;
16833       Inc_T  : Entity_Id)
16834    is
16835       Inc_Elmt : Elmt_Id;
16836       Priv_Dep : Entity_Id;
16837       New_Subt : Entity_Id;
16838
16839       Disc_Constraint : Elist_Id;
16840
16841    begin
16842       if No (Private_Dependents (Inc_T)) then
16843          return;
16844       end if;
16845
16846       --  Itypes that may be generated by the completion of an incomplete
16847       --  subtype are not used by the back-end and not attached to the tree.
16848       --  They are created only for constraint-checking purposes.
16849
16850       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
16851       while Present (Inc_Elmt) loop
16852          Priv_Dep := Node (Inc_Elmt);
16853
16854          if Ekind (Priv_Dep) = E_Subprogram_Type then
16855
16856             --  An Access_To_Subprogram type may have a return type or a
16857             --  parameter type that is incomplete. Replace with the full view.
16858
16859             if Etype (Priv_Dep) = Inc_T then
16860                Set_Etype (Priv_Dep, Full_T);
16861             end if;
16862
16863             declare
16864                Formal : Entity_Id;
16865
16866             begin
16867                Formal := First_Formal (Priv_Dep);
16868                while Present (Formal) loop
16869                   if Etype (Formal) = Inc_T then
16870                      Set_Etype (Formal, Full_T);
16871                   end if;
16872
16873                   Next_Formal (Formal);
16874                end loop;
16875             end;
16876
16877          elsif Is_Overloadable (Priv_Dep) then
16878
16879             --  A protected operation is never dispatching: only its
16880             --  wrapper operation (which has convention Ada) is.
16881
16882             if Is_Tagged_Type (Full_T)
16883               and then Convention (Priv_Dep) /= Convention_Protected
16884             then
16885
16886                --  Subprogram has an access parameter whose designated type
16887                --  was incomplete. Reexamine declaration now, because it may
16888                --  be a primitive operation of the full type.
16889
16890                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
16891                Set_Is_Dispatching_Operation (Priv_Dep);
16892                Check_Controlling_Formals (Full_T, Priv_Dep);
16893             end if;
16894
16895          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
16896
16897             --  Can happen during processing of a body before the completion
16898             --  of a TA type. Ignore, because spec is also on dependent list.
16899
16900             return;
16901
16902          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
16903          --  corresponding subtype of the full view.
16904
16905          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
16906             Set_Subtype_Indication
16907               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
16908             Set_Etype (Priv_Dep, Full_T);
16909             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
16910             Set_Analyzed (Parent (Priv_Dep), False);
16911
16912             --  Reanalyze the declaration, suppressing the call to
16913             --  Enter_Name to avoid duplicate names.
16914
16915             Analyze_Subtype_Declaration
16916               (N    => Parent (Priv_Dep),
16917                Skip => True);
16918
16919          --  Dependent is a subtype
16920
16921          else
16922             --  We build a new subtype indication using the full view of the
16923             --  incomplete parent. The discriminant constraints have been
16924             --  elaborated already at the point of the subtype declaration.
16925
16926             New_Subt := Create_Itype (E_Void, N);
16927
16928             if Has_Discriminants (Full_T) then
16929                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
16930             else
16931                Disc_Constraint := No_Elist;
16932             end if;
16933
16934             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
16935             Set_Full_View (Priv_Dep, New_Subt);
16936          end if;
16937
16938          Next_Elmt (Inc_Elmt);
16939       end loop;
16940    end Process_Incomplete_Dependents;
16941
16942    --------------------------------
16943    -- Process_Range_Expr_In_Decl --
16944    --------------------------------
16945
16946    procedure Process_Range_Expr_In_Decl
16947      (R           : Node_Id;
16948       T           : Entity_Id;
16949       Check_List  : List_Id := Empty_List;
16950       R_Check_Off : Boolean := False)
16951    is
16952       Lo, Hi    : Node_Id;
16953       R_Checks  : Check_Result;
16954       Type_Decl : Node_Id;
16955       Def_Id    : Entity_Id;
16956
16957    begin
16958       Analyze_And_Resolve (R, Base_Type (T));
16959
16960       if Nkind (R) = N_Range then
16961          Lo := Low_Bound (R);
16962          Hi := High_Bound (R);
16963
16964          --  We need to ensure validity of the bounds here, because if we
16965          --  go ahead and do the expansion, then the expanded code will get
16966          --  analyzed with range checks suppressed and we miss the check.
16967
16968          Validity_Check_Range (R);
16969
16970          --  If there were errors in the declaration, try and patch up some
16971          --  common mistakes in the bounds. The cases handled are literals
16972          --  which are Integer where the expected type is Real and vice versa.
16973          --  These corrections allow the compilation process to proceed further
16974          --  along since some basic assumptions of the format of the bounds
16975          --  are guaranteed.
16976
16977          if Etype (R) = Any_Type then
16978
16979             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
16980                Rewrite (Lo,
16981                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
16982
16983             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
16984                Rewrite (Hi,
16985                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
16986
16987             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
16988                Rewrite (Lo,
16989                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
16990
16991             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
16992                Rewrite (Hi,
16993                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
16994             end if;
16995
16996             Set_Etype (Lo, T);
16997             Set_Etype (Hi, T);
16998          end if;
16999
17000          --  If the bounds of the range have been mistakenly given as string
17001          --  literals (perhaps in place of character literals), then an error
17002          --  has already been reported, but we rewrite the string literal as a
17003          --  bound of the range's type to avoid blowups in later processing
17004          --  that looks at static values.
17005
17006          if Nkind (Lo) = N_String_Literal then
17007             Rewrite (Lo,
17008               Make_Attribute_Reference (Sloc (Lo),
17009                 Attribute_Name => Name_First,
17010                 Prefix => New_Reference_To (T, Sloc (Lo))));
17011             Analyze_And_Resolve (Lo);
17012          end if;
17013
17014          if Nkind (Hi) = N_String_Literal then
17015             Rewrite (Hi,
17016               Make_Attribute_Reference (Sloc (Hi),
17017                 Attribute_Name => Name_First,
17018                 Prefix => New_Reference_To (T, Sloc (Hi))));
17019             Analyze_And_Resolve (Hi);
17020          end if;
17021
17022          --  If bounds aren't scalar at this point then exit, avoiding
17023          --  problems with further processing of the range in this procedure.
17024
17025          if not Is_Scalar_Type (Etype (Lo)) then
17026             return;
17027          end if;
17028
17029          --  Resolve (actually Sem_Eval) has checked that the bounds are in
17030          --  then range of the base type. Here we check whether the bounds
17031          --  are in the range of the subtype itself. Note that if the bounds
17032          --  represent the null range the Constraint_Error exception should
17033          --  not be raised.
17034
17035          --  ??? The following code should be cleaned up as follows
17036
17037          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
17038          --     is done in the call to Range_Check (R, T); below
17039
17040          --  2. The use of R_Check_Off should be investigated and possibly
17041          --     removed, this would clean up things a bit.
17042
17043          if Is_Null_Range (Lo, Hi) then
17044             null;
17045
17046          else
17047             --  Capture values of bounds and generate temporaries for them
17048             --  if needed, before applying checks, since checks may cause
17049             --  duplication of the expression without forcing evaluation.
17050
17051             if Expander_Active then
17052                Force_Evaluation (Lo);
17053                Force_Evaluation (Hi);
17054             end if;
17055
17056             --  We use a flag here instead of suppressing checks on the
17057             --  type because the type we check against isn't necessarily
17058             --  the place where we put the check.
17059
17060             if not R_Check_Off then
17061                R_Checks := Get_Range_Checks (R, T);
17062
17063                --  Look up tree to find an appropriate insertion point.
17064                --  This seems really junk code, and very brittle, couldn't
17065                --  we just use an insert actions call of some kind ???
17066
17067                Type_Decl := Parent (R);
17068                while Present (Type_Decl) and then not
17069                  (Nkind_In (Type_Decl, N_Full_Type_Declaration,
17070                                        N_Subtype_Declaration,
17071                                        N_Loop_Statement,
17072                                        N_Task_Type_Declaration)
17073                     or else
17074                   Nkind_In (Type_Decl, N_Single_Task_Declaration,
17075                                        N_Protected_Type_Declaration,
17076                                        N_Single_Protected_Declaration))
17077                loop
17078                   Type_Decl := Parent (Type_Decl);
17079                end loop;
17080
17081                --  Why would Type_Decl not be present???  Without this test,
17082                --  short regression tests fail.
17083
17084                if Present (Type_Decl) then
17085
17086                   --  Case of loop statement (more comments ???)
17087
17088                   if Nkind (Type_Decl) = N_Loop_Statement then
17089                      declare
17090                         Indic : Node_Id;
17091
17092                      begin
17093                         Indic := Parent (R);
17094                         while Present (Indic)
17095                           and then Nkind (Indic) /= N_Subtype_Indication
17096                         loop
17097                            Indic := Parent (Indic);
17098                         end loop;
17099
17100                         if Present (Indic) then
17101                            Def_Id := Etype (Subtype_Mark (Indic));
17102
17103                            Insert_Range_Checks
17104                              (R_Checks,
17105                               Type_Decl,
17106                               Def_Id,
17107                               Sloc (Type_Decl),
17108                               R,
17109                               Do_Before => True);
17110                         end if;
17111                      end;
17112
17113                   --  All other cases (more comments ???)
17114
17115                   else
17116                      Def_Id := Defining_Identifier (Type_Decl);
17117
17118                      if (Ekind (Def_Id) = E_Record_Type
17119                           and then Depends_On_Discriminant (R))
17120                        or else
17121                         (Ekind (Def_Id) = E_Protected_Type
17122                           and then Has_Discriminants (Def_Id))
17123                      then
17124                         Append_Range_Checks
17125                           (R_Checks, Check_List, Def_Id, Sloc (Type_Decl), R);
17126
17127                      else
17128                         Insert_Range_Checks
17129                           (R_Checks, Type_Decl, Def_Id, Sloc (Type_Decl), R);
17130
17131                      end if;
17132                   end if;
17133                end if;
17134             end if;
17135          end if;
17136
17137       elsif Expander_Active then
17138          Get_Index_Bounds (R, Lo, Hi);
17139          Force_Evaluation (Lo);
17140          Force_Evaluation (Hi);
17141       end if;
17142    end Process_Range_Expr_In_Decl;
17143
17144    --------------------------------------
17145    -- Process_Real_Range_Specification --
17146    --------------------------------------
17147
17148    procedure Process_Real_Range_Specification (Def : Node_Id) is
17149       Spec : constant Node_Id := Real_Range_Specification (Def);
17150       Lo   : Node_Id;
17151       Hi   : Node_Id;
17152       Err  : Boolean := False;
17153
17154       procedure Analyze_Bound (N : Node_Id);
17155       --  Analyze and check one bound
17156
17157       -------------------
17158       -- Analyze_Bound --
17159       -------------------
17160
17161       procedure Analyze_Bound (N : Node_Id) is
17162       begin
17163          Analyze_And_Resolve (N, Any_Real);
17164
17165          if not Is_OK_Static_Expression (N) then
17166             Flag_Non_Static_Expr
17167               ("bound in real type definition is not static!", N);
17168             Err := True;
17169          end if;
17170       end Analyze_Bound;
17171
17172    --  Start of processing for Process_Real_Range_Specification
17173
17174    begin
17175       if Present (Spec) then
17176          Lo := Low_Bound (Spec);
17177          Hi := High_Bound (Spec);
17178          Analyze_Bound (Lo);
17179          Analyze_Bound (Hi);
17180
17181          --  If error, clear away junk range specification
17182
17183          if Err then
17184             Set_Real_Range_Specification (Def, Empty);
17185          end if;
17186       end if;
17187    end Process_Real_Range_Specification;
17188
17189    ---------------------
17190    -- Process_Subtype --
17191    ---------------------
17192
17193    function Process_Subtype
17194      (S           : Node_Id;
17195       Related_Nod : Node_Id;
17196       Related_Id  : Entity_Id := Empty;
17197       Suffix      : Character := ' ') return Entity_Id
17198    is
17199       P               : Node_Id;
17200       Def_Id          : Entity_Id;
17201       Error_Node      : Node_Id;
17202       Full_View_Id    : Entity_Id;
17203       Subtype_Mark_Id : Entity_Id;
17204
17205       May_Have_Null_Exclusion : Boolean;
17206
17207       procedure Check_Incomplete (T : Entity_Id);
17208       --  Called to verify that an incomplete type is not used prematurely
17209
17210       ----------------------
17211       -- Check_Incomplete --
17212       ----------------------
17213
17214       procedure Check_Incomplete (T : Entity_Id) is
17215       begin
17216          --  Ada 2005 (AI-412): Incomplete subtypes are legal
17217
17218          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
17219            and then
17220              not (Ada_Version >= Ada_05
17221                     and then
17222                        (Nkind (Parent (T)) = N_Subtype_Declaration
17223                           or else
17224                             (Nkind (Parent (T)) = N_Subtype_Indication
17225                                and then Nkind (Parent (Parent (T))) =
17226                                           N_Subtype_Declaration)))
17227          then
17228             Error_Msg_N ("invalid use of type before its full declaration", T);
17229          end if;
17230       end Check_Incomplete;
17231
17232    --  Start of processing for Process_Subtype
17233
17234    begin
17235       --  Case of no constraints present
17236
17237       if Nkind (S) /= N_Subtype_Indication then
17238          Find_Type (S);
17239          Check_Incomplete (S);
17240          P := Parent (S);
17241
17242          --  Ada 2005 (AI-231): Static check
17243
17244          if Ada_Version >= Ada_05
17245            and then Present (P)
17246            and then Null_Exclusion_Present (P)
17247            and then Nkind (P) /= N_Access_To_Object_Definition
17248            and then not Is_Access_Type (Entity (S))
17249          then
17250             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
17251          end if;
17252
17253          --  The following is ugly, can't we have a range or even a flag???
17254
17255          May_Have_Null_Exclusion :=
17256            Nkind_In (P, N_Access_Definition,
17257                         N_Access_Function_Definition,
17258                         N_Access_Procedure_Definition,
17259                         N_Access_To_Object_Definition,
17260                         N_Allocator,
17261                         N_Component_Definition)
17262              or else
17263            Nkind_In (P, N_Derived_Type_Definition,
17264                         N_Discriminant_Specification,
17265                         N_Formal_Object_Declaration,
17266                         N_Object_Declaration,
17267                         N_Object_Renaming_Declaration,
17268                         N_Parameter_Specification,
17269                         N_Subtype_Declaration);
17270
17271          --  Create an Itype that is a duplicate of Entity (S) but with the
17272          --  null-exclusion attribute.
17273
17274          if May_Have_Null_Exclusion
17275            and then Is_Access_Type (Entity (S))
17276            and then Null_Exclusion_Present (P)
17277
17278             --  No need to check the case of an access to object definition.
17279             --  It is correct to define double not-null pointers.
17280
17281             --  Example:
17282             --     type Not_Null_Int_Ptr is not null access Integer;
17283             --     type Acc is not null access Not_Null_Int_Ptr;
17284
17285            and then Nkind (P) /= N_Access_To_Object_Definition
17286          then
17287             if Can_Never_Be_Null (Entity (S)) then
17288                case Nkind (Related_Nod) is
17289                   when N_Full_Type_Declaration =>
17290                      if Nkind (Type_Definition (Related_Nod))
17291                        in N_Array_Type_Definition
17292                      then
17293                         Error_Node :=
17294                           Subtype_Indication
17295                             (Component_Definition
17296                              (Type_Definition (Related_Nod)));
17297                      else
17298                         Error_Node :=
17299                           Subtype_Indication (Type_Definition (Related_Nod));
17300                      end if;
17301
17302                   when N_Subtype_Declaration =>
17303                      Error_Node := Subtype_Indication (Related_Nod);
17304
17305                   when N_Object_Declaration =>
17306                      Error_Node := Object_Definition (Related_Nod);
17307
17308                   when N_Component_Declaration =>
17309                      Error_Node :=
17310                        Subtype_Indication (Component_Definition (Related_Nod));
17311
17312                   when N_Allocator =>
17313                      Error_Node := Expression (Related_Nod);
17314
17315                   when others =>
17316                      pragma Assert (False);
17317                      Error_Node := Related_Nod;
17318                end case;
17319
17320                Error_Msg_NE
17321                  ("`NOT NULL` not allowed (& already excludes null)",
17322                   Error_Node,
17323                   Entity (S));
17324             end if;
17325
17326             Set_Etype  (S,
17327               Create_Null_Excluding_Itype
17328                 (T           => Entity (S),
17329                  Related_Nod => P));
17330             Set_Entity (S, Etype (S));
17331          end if;
17332
17333          return Entity (S);
17334
17335       --  Case of constraint present, so that we have an N_Subtype_Indication
17336       --  node (this node is created only if constraints are present).
17337
17338       else
17339          Find_Type (Subtype_Mark (S));
17340
17341          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
17342            and then not
17343             (Nkind (Parent (S)) = N_Subtype_Declaration
17344               and then Is_Itype (Defining_Identifier (Parent (S))))
17345          then
17346             Check_Incomplete (Subtype_Mark (S));
17347          end if;
17348
17349          P := Parent (S);
17350          Subtype_Mark_Id := Entity (Subtype_Mark (S));
17351
17352          --  Explicit subtype declaration case
17353
17354          if Nkind (P) = N_Subtype_Declaration then
17355             Def_Id := Defining_Identifier (P);
17356
17357          --  Explicit derived type definition case
17358
17359          elsif Nkind (P) = N_Derived_Type_Definition then
17360             Def_Id := Defining_Identifier (Parent (P));
17361
17362          --  Implicit case, the Def_Id must be created as an implicit type.
17363          --  The one exception arises in the case of concurrent types, array
17364          --  and access types, where other subsidiary implicit types may be
17365          --  created and must appear before the main implicit type. In these
17366          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
17367          --  has not yet been called to create Def_Id.
17368
17369          else
17370             if Is_Array_Type (Subtype_Mark_Id)
17371               or else Is_Concurrent_Type (Subtype_Mark_Id)
17372               or else Is_Access_Type (Subtype_Mark_Id)
17373             then
17374                Def_Id := Empty;
17375
17376             --  For the other cases, we create a new unattached Itype,
17377             --  and set the indication to ensure it gets attached later.
17378
17379             else
17380                Def_Id :=
17381                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
17382             end if;
17383          end if;
17384
17385          --  If the kind of constraint is invalid for this kind of type,
17386          --  then give an error, and then pretend no constraint was given.
17387
17388          if not Is_Valid_Constraint_Kind
17389                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
17390          then
17391             Error_Msg_N
17392               ("incorrect constraint for this kind of type", Constraint (S));
17393
17394             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
17395
17396             --  Set Ekind of orphan itype, to prevent cascaded errors
17397
17398             if Present (Def_Id) then
17399                Set_Ekind (Def_Id, Ekind (Any_Type));
17400             end if;
17401
17402             --  Make recursive call, having got rid of the bogus constraint
17403
17404             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
17405          end if;
17406
17407          --  Remaining processing depends on type
17408
17409          case Ekind (Subtype_Mark_Id) is
17410             when Access_Kind =>
17411                Constrain_Access (Def_Id, S, Related_Nod);
17412
17413                if Expander_Active
17414                  and then  Is_Itype (Designated_Type (Def_Id))
17415                  and then Nkind (Related_Nod) = N_Subtype_Declaration
17416                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
17417                then
17418                   Build_Itype_Reference
17419                     (Designated_Type (Def_Id), Related_Nod);
17420                end if;
17421
17422             when Array_Kind =>
17423                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
17424
17425             when Decimal_Fixed_Point_Kind =>
17426                Constrain_Decimal (Def_Id, S);
17427
17428             when Enumeration_Kind =>
17429                Constrain_Enumeration (Def_Id, S);
17430
17431             when Ordinary_Fixed_Point_Kind =>
17432                Constrain_Ordinary_Fixed (Def_Id, S);
17433
17434             when Float_Kind =>
17435                Constrain_Float (Def_Id, S);
17436
17437             when Integer_Kind =>
17438                Constrain_Integer (Def_Id, S);
17439
17440             when E_Record_Type     |
17441                  E_Record_Subtype  |
17442                  Class_Wide_Kind   |
17443                  E_Incomplete_Type =>
17444                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
17445
17446                if Ekind (Def_Id) = E_Incomplete_Type then
17447                   Set_Private_Dependents (Def_Id, New_Elmt_List);
17448                end if;
17449
17450             when Private_Kind =>
17451                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
17452                Set_Private_Dependents (Def_Id, New_Elmt_List);
17453
17454                --  In case of an invalid constraint prevent further processing
17455                --  since the type constructed is missing expected fields.
17456
17457                if Etype (Def_Id) = Any_Type then
17458                   return Def_Id;
17459                end if;
17460
17461                --  If the full view is that of a task with discriminants,
17462                --  we must constrain both the concurrent type and its
17463                --  corresponding record type. Otherwise we will just propagate
17464                --  the constraint to the full view, if available.
17465
17466                if Present (Full_View (Subtype_Mark_Id))
17467                  and then Has_Discriminants (Subtype_Mark_Id)
17468                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
17469                then
17470                   Full_View_Id :=
17471                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
17472
17473                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
17474                   Constrain_Concurrent (Full_View_Id, S,
17475                     Related_Nod, Related_Id, Suffix);
17476                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
17477                   Set_Full_View (Def_Id, Full_View_Id);
17478
17479                   --  Introduce an explicit reference to the private subtype,
17480                   --  to prevent scope anomalies in gigi if first use appears
17481                   --  in a nested context, e.g. a later function body.
17482                   --  Should this be generated in other contexts than a full
17483                   --  type declaration?
17484
17485                   if Is_Itype (Def_Id)
17486                     and then
17487                       Nkind (Parent (P)) = N_Full_Type_Declaration
17488                   then
17489                      Build_Itype_Reference (Def_Id, Parent (P));
17490                   end if;
17491
17492                else
17493                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
17494                end if;
17495
17496             when Concurrent_Kind  =>
17497                Constrain_Concurrent (Def_Id, S,
17498                  Related_Nod, Related_Id, Suffix);
17499
17500             when others =>
17501                Error_Msg_N ("invalid subtype mark in subtype indication", S);
17502          end case;
17503
17504          --  Size and Convention are always inherited from the base type
17505
17506          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
17507          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
17508
17509          return Def_Id;
17510       end if;
17511    end Process_Subtype;
17512
17513    ---------------------------------------
17514    -- Check_Anonymous_Access_Components --
17515    ---------------------------------------
17516
17517    procedure Check_Anonymous_Access_Components
17518       (Typ_Decl  : Node_Id;
17519        Typ       : Entity_Id;
17520        Prev      : Entity_Id;
17521        Comp_List : Node_Id)
17522    is
17523       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
17524       Anon_Access : Entity_Id;
17525       Acc_Def     : Node_Id;
17526       Comp        : Node_Id;
17527       Comp_Def    : Node_Id;
17528       Decl        : Node_Id;
17529       Type_Def    : Node_Id;
17530
17531       procedure Build_Incomplete_Type_Declaration;
17532       --  If the record type contains components that include an access to the
17533       --  current record, then create an incomplete type declaration for the
17534       --  record, to be used as the designated type of the anonymous access.
17535       --  This is done only once, and only if there is no previous partial
17536       --  view of the type.
17537
17538       function Designates_T (Subt : Node_Id) return Boolean;
17539       --  Check whether a node designates the enclosing record type, or 'Class
17540       --  of that type
17541
17542       function Mentions_T (Acc_Def : Node_Id) return Boolean;
17543       --  Check whether an access definition includes a reference to
17544       --  the enclosing record type. The reference can be a subtype mark
17545       --  in the access definition itself, a 'Class attribute reference, or
17546       --  recursively a reference appearing in a parameter specification
17547       --  or result definition of an access_to_subprogram definition.
17548
17549       --------------------------------------
17550       -- Build_Incomplete_Type_Declaration --
17551       --------------------------------------
17552
17553       procedure Build_Incomplete_Type_Declaration is
17554          Decl  : Node_Id;
17555          Inc_T : Entity_Id;
17556          H     : Entity_Id;
17557
17558          --  Is_Tagged indicates whether the type is tagged. It is tagged if
17559          --  it's "is new ... with record" or else "is tagged record ...".
17560
17561          Is_Tagged : constant Boolean :=
17562              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
17563                  and then
17564                    Present
17565                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
17566            or else
17567              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
17568                  and then Tagged_Present (Type_Definition (Typ_Decl)));
17569
17570       begin
17571          --  If there is a previous partial view, no need to create a new one
17572          --  If the partial view, given by Prev, is incomplete,  If Prev is
17573          --  a private declaration, full declaration is flagged accordingly.
17574
17575          if Prev /= Typ then
17576             if Is_Tagged then
17577                Make_Class_Wide_Type (Prev);
17578                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
17579                Set_Etype (Class_Wide_Type (Typ), Typ);
17580             end if;
17581
17582             return;
17583
17584          elsif Has_Private_Declaration (Typ) then
17585
17586             --  If we refer to T'Class inside T, and T is the completion of a
17587             --  private type, then we need to make sure the class-wide type
17588             --  exists.
17589
17590             if Is_Tagged then
17591                Make_Class_Wide_Type (Typ);
17592             end if;
17593
17594             return;
17595
17596          --  If there was a previous anonymous access type, the incomplete
17597          --  type declaration will have been created already.
17598
17599          elsif Present (Current_Entity (Typ))
17600            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
17601            and then Full_View (Current_Entity (Typ)) = Typ
17602          then
17603             if Is_Tagged
17604               and then Comes_From_Source (Current_Entity (Typ))
17605               and then not Is_Tagged_Type (Current_Entity (Typ))
17606             then
17607                Make_Class_Wide_Type (Typ);
17608                Error_Msg_N
17609                  ("incomplete view of tagged type should be declared tagged?",
17610                   Parent (Current_Entity (Typ)));
17611             end if;
17612             return;
17613
17614          else
17615             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
17616             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
17617
17618             --  Type has already been inserted into the current scope. Remove
17619             --  it, and add incomplete declaration for type, so that subsequent
17620             --  anonymous access types can use it. The entity is unchained from
17621             --  the homonym list and from immediate visibility. After analysis,
17622             --  the entity in the incomplete declaration becomes immediately
17623             --  visible in the record declaration that follows.
17624
17625             H := Current_Entity (Typ);
17626
17627             if H = Typ then
17628                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
17629             else
17630                while Present (H)
17631                  and then Homonym (H) /= Typ
17632                loop
17633                   H := Homonym (Typ);
17634                end loop;
17635
17636                Set_Homonym (H, Homonym (Typ));
17637             end if;
17638
17639             Insert_Before (Typ_Decl, Decl);
17640             Analyze (Decl);
17641             Set_Full_View (Inc_T, Typ);
17642
17643             if Is_Tagged then
17644
17645                --  Create a common class-wide type for both views, and set the
17646                --  Etype of the class-wide type to the full view.
17647
17648                Make_Class_Wide_Type (Inc_T);
17649                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
17650                Set_Etype (Class_Wide_Type (Typ), Typ);
17651             end if;
17652          end if;
17653       end Build_Incomplete_Type_Declaration;
17654
17655       ------------------
17656       -- Designates_T --
17657       ------------------
17658
17659       function Designates_T (Subt : Node_Id) return Boolean is
17660          Type_Id : constant Name_Id := Chars (Typ);
17661
17662          function Names_T (Nam : Node_Id) return Boolean;
17663          --  The record type has not been introduced in the current scope
17664          --  yet, so we must examine the name of the type itself, either
17665          --  an identifier T, or an expanded name of the form P.T, where
17666          --  P denotes the current scope.
17667
17668          -------------
17669          -- Names_T --
17670          -------------
17671
17672          function Names_T (Nam : Node_Id) return Boolean is
17673          begin
17674             if Nkind (Nam) = N_Identifier then
17675                return Chars (Nam) = Type_Id;
17676
17677             elsif Nkind (Nam) = N_Selected_Component then
17678                if Chars (Selector_Name (Nam)) = Type_Id then
17679                   if Nkind (Prefix (Nam)) = N_Identifier then
17680                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
17681
17682                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
17683                      return Chars (Selector_Name (Prefix (Nam))) =
17684                             Chars (Current_Scope);
17685                   else
17686                      return False;
17687                   end if;
17688
17689                else
17690                   return False;
17691                end if;
17692
17693             else
17694                return False;
17695             end if;
17696          end Names_T;
17697
17698       --  Start of processing for Designates_T
17699
17700       begin
17701          if Nkind (Subt) = N_Identifier then
17702             return Chars (Subt) = Type_Id;
17703
17704             --  Reference can be through an expanded name which has not been
17705             --  analyzed yet, and which designates enclosing scopes.
17706
17707          elsif Nkind (Subt) = N_Selected_Component then
17708             if Names_T (Subt) then
17709                return True;
17710
17711             --  Otherwise it must denote an entity that is already visible.
17712             --  The access definition may name a subtype of the enclosing
17713             --  type, if there is a previous incomplete declaration for it.
17714
17715             else
17716                Find_Selected_Component (Subt);
17717                return
17718                  Is_Entity_Name (Subt)
17719                    and then Scope (Entity (Subt)) = Current_Scope
17720                    and then
17721                      (Chars (Base_Type (Entity (Subt))) = Type_Id
17722                        or else
17723                          (Is_Class_Wide_Type (Entity (Subt))
17724                            and then
17725                            Chars (Etype (Base_Type (Entity (Subt)))) =
17726                                                                   Type_Id));
17727             end if;
17728
17729          --  A reference to the current type may appear as the prefix of
17730          --  a 'Class attribute.
17731
17732          elsif Nkind (Subt) = N_Attribute_Reference
17733            and then Attribute_Name (Subt) = Name_Class
17734          then
17735             return Names_T (Prefix (Subt));
17736
17737          else
17738             return False;
17739          end if;
17740       end Designates_T;
17741
17742       ----------------
17743       -- Mentions_T --
17744       ----------------
17745
17746       function Mentions_T (Acc_Def : Node_Id) return Boolean is
17747          Param_Spec : Node_Id;
17748
17749          Acc_Subprg : constant Node_Id :=
17750                         Access_To_Subprogram_Definition (Acc_Def);
17751
17752       begin
17753          if No (Acc_Subprg) then
17754             return Designates_T (Subtype_Mark (Acc_Def));
17755          end if;
17756
17757          --  Component is an access_to_subprogram: examine its formals,
17758          --  and result definition in the case of an access_to_function.
17759
17760          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
17761          while Present (Param_Spec) loop
17762             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
17763               and then Mentions_T (Parameter_Type (Param_Spec))
17764             then
17765                return True;
17766
17767             elsif Designates_T (Parameter_Type (Param_Spec)) then
17768                return True;
17769             end if;
17770
17771             Next (Param_Spec);
17772          end loop;
17773
17774          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
17775             if Nkind (Result_Definition (Acc_Subprg)) =
17776                  N_Access_Definition
17777             then
17778                return Mentions_T (Result_Definition (Acc_Subprg));
17779             else
17780                return Designates_T (Result_Definition (Acc_Subprg));
17781             end if;
17782          end if;
17783
17784          return False;
17785       end Mentions_T;
17786
17787    --  Start of processing for Check_Anonymous_Access_Components
17788
17789    begin
17790       if No (Comp_List) then
17791          return;
17792       end if;
17793
17794       Comp := First (Component_Items (Comp_List));
17795       while Present (Comp) loop
17796          if Nkind (Comp) = N_Component_Declaration
17797            and then Present
17798              (Access_Definition (Component_Definition (Comp)))
17799            and then
17800              Mentions_T (Access_Definition (Component_Definition (Comp)))
17801          then
17802             Comp_Def := Component_Definition (Comp);
17803             Acc_Def :=
17804               Access_To_Subprogram_Definition
17805                 (Access_Definition (Comp_Def));
17806
17807             Build_Incomplete_Type_Declaration;
17808             Anon_Access := Make_Temporary (Loc, 'S');
17809
17810             --  Create a declaration for the anonymous access type: either
17811             --  an access_to_object or an access_to_subprogram.
17812
17813             if Present (Acc_Def) then
17814                if Nkind  (Acc_Def) = N_Access_Function_Definition then
17815                   Type_Def :=
17816                     Make_Access_Function_Definition (Loc,
17817                       Parameter_Specifications =>
17818                         Parameter_Specifications (Acc_Def),
17819                       Result_Definition => Result_Definition (Acc_Def));
17820                else
17821                   Type_Def :=
17822                     Make_Access_Procedure_Definition (Loc,
17823                       Parameter_Specifications =>
17824                         Parameter_Specifications (Acc_Def));
17825                end if;
17826
17827             else
17828                Type_Def :=
17829                  Make_Access_To_Object_Definition (Loc,
17830                    Subtype_Indication =>
17831                       Relocate_Node
17832                         (Subtype_Mark
17833                           (Access_Definition (Comp_Def))));
17834
17835                Set_Constant_Present
17836                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
17837                Set_All_Present
17838                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
17839             end if;
17840
17841             Set_Null_Exclusion_Present
17842               (Type_Def,
17843                Null_Exclusion_Present (Access_Definition (Comp_Def)));
17844
17845             Decl :=
17846               Make_Full_Type_Declaration (Loc,
17847                 Defining_Identifier => Anon_Access,
17848                 Type_Definition     => Type_Def);
17849
17850             Insert_Before (Typ_Decl, Decl);
17851             Analyze (Decl);
17852
17853             --  If an access to object, Preserve entity of designated type,
17854             --  for ASIS use, before rewriting the component definition.
17855
17856             if No (Acc_Def) then
17857                declare
17858                   Desig : Entity_Id;
17859
17860                begin
17861                   Desig := Entity (Subtype_Indication (Type_Def));
17862
17863                   --  If the access definition is to the current  record,
17864                   --  the visible entity at this point is an  incomplete
17865                   --  type. Retrieve the full view to simplify  ASIS queries
17866
17867                   if Ekind (Desig) = E_Incomplete_Type then
17868                      Desig := Full_View (Desig);
17869                   end if;
17870
17871                   Set_Entity
17872                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
17873                end;
17874             end if;
17875
17876             Rewrite (Comp_Def,
17877               Make_Component_Definition (Loc,
17878                 Subtype_Indication =>
17879                New_Occurrence_Of (Anon_Access, Loc)));
17880
17881             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
17882                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
17883             else
17884                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
17885             end if;
17886
17887             Set_Is_Local_Anonymous_Access (Anon_Access);
17888          end if;
17889
17890          Next (Comp);
17891       end loop;
17892
17893       if Present (Variant_Part (Comp_List)) then
17894          declare
17895             V : Node_Id;
17896          begin
17897             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
17898             while Present (V) loop
17899                Check_Anonymous_Access_Components
17900                  (Typ_Decl, Typ, Prev, Component_List (V));
17901                Next_Non_Pragma (V);
17902             end loop;
17903          end;
17904       end if;
17905    end Check_Anonymous_Access_Components;
17906
17907    --------------------------------
17908    -- Preanalyze_Spec_Expression --
17909    --------------------------------
17910
17911    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
17912       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
17913    begin
17914       In_Spec_Expression := True;
17915       Preanalyze_And_Resolve (N, T);
17916       In_Spec_Expression := Save_In_Spec_Expression;
17917    end Preanalyze_Spec_Expression;
17918
17919    -----------------------------
17920    -- Record_Type_Declaration --
17921    -----------------------------
17922
17923    procedure Record_Type_Declaration
17924      (T    : Entity_Id;
17925       N    : Node_Id;
17926       Prev : Entity_Id)
17927    is
17928       Def       : constant Node_Id := Type_Definition (N);
17929       Is_Tagged : Boolean;
17930       Tag_Comp  : Entity_Id;
17931
17932    begin
17933       --  These flags must be initialized before calling Process_Discriminants
17934       --  because this routine makes use of them.
17935
17936       Set_Ekind             (T, E_Record_Type);
17937       Set_Etype             (T, T);
17938       Init_Size_Align       (T);
17939       Set_Interfaces        (T, No_Elist);
17940       Set_Stored_Constraint (T, No_Elist);
17941
17942       --  Normal case
17943
17944       if Ada_Version < Ada_05
17945         or else not Interface_Present (Def)
17946       then
17947          --  The flag Is_Tagged_Type might have already been set by
17948          --  Find_Type_Name if it detected an error for declaration T. This
17949          --  arises in the case of private tagged types where the full view
17950          --  omits the word tagged.
17951
17952          Is_Tagged :=
17953            Tagged_Present (Def)
17954              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
17955
17956          Set_Is_Tagged_Type      (T, Is_Tagged);
17957          Set_Is_Limited_Record   (T, Limited_Present (Def));
17958
17959          --  Type is abstract if full declaration carries keyword, or if
17960          --  previous partial view did.
17961
17962          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
17963                                       or else Abstract_Present (Def));
17964
17965       else
17966          Is_Tagged := True;
17967          Analyze_Interface_Declaration (T, Def);
17968
17969          if Present (Discriminant_Specifications (N)) then
17970             Error_Msg_N
17971               ("interface types cannot have discriminants",
17972                 Defining_Identifier
17973                   (First (Discriminant_Specifications (N))));
17974          end if;
17975       end if;
17976
17977       --  First pass: if there are self-referential access components,
17978       --  create the required anonymous access type declarations, and if
17979       --  need be an incomplete type declaration for T itself.
17980
17981       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
17982
17983       if Ada_Version >= Ada_05
17984         and then Present (Interface_List (Def))
17985       then
17986          Check_Interfaces (N, Def);
17987
17988          declare
17989             Ifaces_List : Elist_Id;
17990
17991          begin
17992             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
17993             --  already in the parents.
17994
17995             Collect_Interfaces
17996               (T               => T,
17997                Ifaces_List     => Ifaces_List,
17998                Exclude_Parents => True);
17999
18000             Set_Interfaces (T, Ifaces_List);
18001          end;
18002       end if;
18003
18004       --  Records constitute a scope for the component declarations within.
18005       --  The scope is created prior to the processing of these declarations.
18006       --  Discriminants are processed first, so that they are visible when
18007       --  processing the other components. The Ekind of the record type itself
18008       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
18009
18010       --  Enter record scope
18011
18012       Push_Scope (T);
18013
18014       --  If an incomplete or private type declaration was already given for
18015       --  the type, then this scope already exists, and the discriminants have
18016       --  been declared within. We must verify that the full declaration
18017       --  matches the incomplete one.
18018
18019       Check_Or_Process_Discriminants (N, T, Prev);
18020
18021       Set_Is_Constrained     (T, not Has_Discriminants (T));
18022       Set_Has_Delayed_Freeze (T, True);
18023
18024       --  For tagged types add a manually analyzed component corresponding
18025       --  to the component _tag, the corresponding piece of tree will be
18026       --  expanded as part of the freezing actions if it is not a CPP_Class.
18027
18028       if Is_Tagged then
18029
18030          --  Do not add the tag unless we are in expansion mode
18031
18032          if Expander_Active then
18033             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
18034             Enter_Name (Tag_Comp);
18035
18036             Set_Ekind                     (Tag_Comp, E_Component);
18037             Set_Is_Tag                    (Tag_Comp);
18038             Set_Is_Aliased                (Tag_Comp);
18039             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
18040             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
18041             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
18042             Init_Component_Location       (Tag_Comp);
18043
18044             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
18045             --  implemented interfaces.
18046
18047             if Has_Interfaces (T) then
18048                Add_Interface_Tag_Components (N, T);
18049             end if;
18050          end if;
18051
18052          Make_Class_Wide_Type (T);
18053          Set_Primitive_Operations (T, New_Elmt_List);
18054       end if;
18055
18056       --  We must suppress range checks when processing the components
18057       --  of a record in the presence of discriminants, since we don't
18058       --  want spurious checks to be generated during their analysis, but
18059       --  must reset the Suppress_Range_Checks flags after having processed
18060       --  the record definition.
18061
18062       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
18063       --  couldn't we just use the normal range check suppression method here.
18064       --  That would seem cleaner ???
18065
18066       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
18067          Set_Kill_Range_Checks (T, True);
18068          Record_Type_Definition (Def, Prev);
18069          Set_Kill_Range_Checks (T, False);
18070       else
18071          Record_Type_Definition (Def, Prev);
18072       end if;
18073
18074       --  Exit from record scope
18075
18076       End_Scope;
18077
18078       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
18079       --  the implemented interfaces and associate them an aliased entity.
18080
18081       if Is_Tagged
18082         and then not Is_Empty_List (Interface_List (Def))
18083       then
18084          Derive_Progenitor_Subprograms (T, T);
18085       end if;
18086    end Record_Type_Declaration;
18087
18088    ----------------------------
18089    -- Record_Type_Definition --
18090    ----------------------------
18091
18092    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
18093       Component          : Entity_Id;
18094       Ctrl_Components    : Boolean := False;
18095       Final_Storage_Only : Boolean;
18096       T                  : Entity_Id;
18097
18098    begin
18099       if Ekind (Prev_T) = E_Incomplete_Type then
18100          T := Full_View (Prev_T);
18101       else
18102          T := Prev_T;
18103       end if;
18104
18105       Final_Storage_Only := not Is_Controlled (T);
18106
18107       --  Ada 2005: check whether an explicit Limited is present in a derived
18108       --  type declaration.
18109
18110       if Nkind (Parent (Def)) = N_Derived_Type_Definition
18111         and then Limited_Present (Parent (Def))
18112       then
18113          Set_Is_Limited_Record (T);
18114       end if;
18115
18116       --  If the component list of a record type is defined by the reserved
18117       --  word null and there is no discriminant part, then the record type has
18118       --  no components and all records of the type are null records (RM 3.7)
18119       --  This procedure is also called to process the extension part of a
18120       --  record extension, in which case the current scope may have inherited
18121       --  components.
18122
18123       if No (Def)
18124         or else No (Component_List (Def))
18125         or else Null_Present (Component_List (Def))
18126       then
18127          null;
18128
18129       else
18130          Analyze_Declarations (Component_Items (Component_List (Def)));
18131
18132          if Present (Variant_Part (Component_List (Def))) then
18133             Analyze (Variant_Part (Component_List (Def)));
18134          end if;
18135       end if;
18136
18137       --  After completing the semantic analysis of the record definition,
18138       --  record components, both new and inherited, are accessible. Set their
18139       --  kind accordingly. Exclude malformed itypes from illegal declarations,
18140       --  whose Ekind may be void.
18141
18142       Component := First_Entity (Current_Scope);
18143       while Present (Component) loop
18144          if Ekind (Component) = E_Void
18145            and then not Is_Itype (Component)
18146          then
18147             Set_Ekind (Component, E_Component);
18148             Init_Component_Location (Component);
18149          end if;
18150
18151          if Has_Task (Etype (Component)) then
18152             Set_Has_Task (T);
18153          end if;
18154
18155          if Ekind (Component) /= E_Component then
18156             null;
18157
18158          --  Do not set Has_Controlled_Component on a class-wide equivalent
18159          --  type. See Make_CW_Equivalent_Type.
18160
18161          elsif not Is_Class_Wide_Equivalent_Type (T)
18162            and then (Has_Controlled_Component (Etype (Component))
18163                       or else (Chars (Component) /= Name_uParent
18164                                 and then Is_Controlled (Etype (Component))))
18165          then
18166             Set_Has_Controlled_Component (T, True);
18167             Final_Storage_Only :=
18168               Final_Storage_Only
18169                 and then Finalize_Storage_Only (Etype (Component));
18170             Ctrl_Components := True;
18171          end if;
18172
18173          Next_Entity (Component);
18174       end loop;
18175
18176       --  A Type is Finalize_Storage_Only only if all its controlled components
18177       --  are also.
18178
18179       if Ctrl_Components then
18180          Set_Finalize_Storage_Only (T, Final_Storage_Only);
18181       end if;
18182
18183       --  Place reference to end record on the proper entity, which may
18184       --  be a partial view.
18185
18186       if Present (Def) then
18187          Process_End_Label (Def, 'e', Prev_T);
18188       end if;
18189    end Record_Type_Definition;
18190
18191    ------------------------
18192    -- Replace_Components --
18193    ------------------------
18194
18195    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
18196       function Process (N : Node_Id) return Traverse_Result;
18197
18198       -------------
18199       -- Process --
18200       -------------
18201
18202       function Process (N : Node_Id) return Traverse_Result is
18203          Comp : Entity_Id;
18204
18205       begin
18206          if Nkind (N) = N_Discriminant_Specification then
18207             Comp := First_Discriminant (Typ);
18208             while Present (Comp) loop
18209                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18210                   Set_Defining_Identifier (N, Comp);
18211                   exit;
18212                end if;
18213
18214                Next_Discriminant (Comp);
18215             end loop;
18216
18217          elsif Nkind (N) = N_Component_Declaration then
18218             Comp := First_Component (Typ);
18219             while Present (Comp) loop
18220                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18221                   Set_Defining_Identifier (N, Comp);
18222                   exit;
18223                end if;
18224
18225                Next_Component (Comp);
18226             end loop;
18227          end if;
18228
18229          return OK;
18230       end Process;
18231
18232       procedure Replace is new Traverse_Proc (Process);
18233
18234    --  Start of processing for Replace_Components
18235
18236    begin
18237       Replace (Decl);
18238    end Replace_Components;
18239
18240    -------------------------------
18241    -- Set_Completion_Referenced --
18242    -------------------------------
18243
18244    procedure Set_Completion_Referenced (E : Entity_Id) is
18245    begin
18246       --  If in main unit, mark entity that is a completion as referenced,
18247       --  warnings go on the partial view when needed.
18248
18249       if In_Extended_Main_Source_Unit (E) then
18250          Set_Referenced (E);
18251       end if;
18252    end Set_Completion_Referenced;
18253
18254    ---------------------
18255    -- Set_Fixed_Range --
18256    ---------------------
18257
18258    --  The range for fixed-point types is complicated by the fact that we
18259    --  do not know the exact end points at the time of the declaration. This
18260    --  is true for three reasons:
18261
18262    --     A size clause may affect the fudging of the end-points
18263    --     A small clause may affect the values of the end-points
18264    --     We try to include the end-points if it does not affect the size
18265
18266    --  This means that the actual end-points must be established at the point
18267    --  when the type is frozen. Meanwhile, we first narrow the range as
18268    --  permitted (so that it will fit if necessary in a small specified size),
18269    --  and then build a range subtree with these narrowed bounds.
18270
18271    --  Set_Fixed_Range constructs the range from real literal values, and sets
18272    --  the range as the Scalar_Range of the given fixed-point type entity.
18273
18274    --  The parent of this range is set to point to the entity so that it is
18275    --  properly hooked into the tree (unlike normal Scalar_Range entries for
18276    --  other scalar types, which are just pointers to the range in the
18277    --  original tree, this would otherwise be an orphan).
18278
18279    --  The tree is left unanalyzed. When the type is frozen, the processing
18280    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
18281    --  analyzed, and uses this as an indication that it should complete
18282    --  work on the range (it will know the final small and size values).
18283
18284    procedure Set_Fixed_Range
18285      (E   : Entity_Id;
18286       Loc : Source_Ptr;
18287       Lo  : Ureal;
18288       Hi  : Ureal)
18289    is
18290       S : constant Node_Id :=
18291             Make_Range (Loc,
18292               Low_Bound  => Make_Real_Literal (Loc, Lo),
18293               High_Bound => Make_Real_Literal (Loc, Hi));
18294    begin
18295       Set_Scalar_Range (E, S);
18296       Set_Parent (S, E);
18297    end Set_Fixed_Range;
18298
18299    ----------------------------------
18300    -- Set_Scalar_Range_For_Subtype --
18301    ----------------------------------
18302
18303    procedure Set_Scalar_Range_For_Subtype
18304      (Def_Id : Entity_Id;
18305       R      : Node_Id;
18306       Subt   : Entity_Id)
18307    is
18308       Kind : constant Entity_Kind :=  Ekind (Def_Id);
18309
18310    begin
18311       --  Defend against previous error
18312
18313       if Nkind (R) = N_Error then
18314          return;
18315       end if;
18316
18317       Set_Scalar_Range (Def_Id, R);
18318
18319       --  We need to link the range into the tree before resolving it so
18320       --  that types that are referenced, including importantly the subtype
18321       --  itself, are properly frozen (Freeze_Expression requires that the
18322       --  expression be properly linked into the tree). Of course if it is
18323       --  already linked in, then we do not disturb the current link.
18324
18325       if No (Parent (R)) then
18326          Set_Parent (R, Def_Id);
18327       end if;
18328
18329       --  Reset the kind of the subtype during analysis of the range, to
18330       --  catch possible premature use in the bounds themselves.
18331
18332       Set_Ekind (Def_Id, E_Void);
18333       Process_Range_Expr_In_Decl (R, Subt);
18334       Set_Ekind (Def_Id, Kind);
18335    end Set_Scalar_Range_For_Subtype;
18336
18337    --------------------------------------------------------
18338    -- Set_Stored_Constraint_From_Discriminant_Constraint --
18339    --------------------------------------------------------
18340
18341    procedure Set_Stored_Constraint_From_Discriminant_Constraint
18342      (E : Entity_Id)
18343    is
18344    begin
18345       --  Make sure set if encountered during Expand_To_Stored_Constraint
18346
18347       Set_Stored_Constraint (E, No_Elist);
18348
18349       --  Give it the right value
18350
18351       if Is_Constrained (E) and then Has_Discriminants (E) then
18352          Set_Stored_Constraint (E,
18353            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
18354       end if;
18355    end Set_Stored_Constraint_From_Discriminant_Constraint;
18356
18357    -------------------------------------
18358    -- Signed_Integer_Type_Declaration --
18359    -------------------------------------
18360
18361    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
18362       Implicit_Base : Entity_Id;
18363       Base_Typ      : Entity_Id;
18364       Lo_Val        : Uint;
18365       Hi_Val        : Uint;
18366       Errs          : Boolean := False;
18367       Lo            : Node_Id;
18368       Hi            : Node_Id;
18369
18370       function Can_Derive_From (E : Entity_Id) return Boolean;
18371       --  Determine whether given bounds allow derivation from specified type
18372
18373       procedure Check_Bound (Expr : Node_Id);
18374       --  Check bound to make sure it is integral and static. If not, post
18375       --  appropriate error message and set Errs flag
18376
18377       ---------------------
18378       -- Can_Derive_From --
18379       ---------------------
18380
18381       --  Note we check both bounds against both end values, to deal with
18382       --  strange types like ones with a range of 0 .. -12341234.
18383
18384       function Can_Derive_From (E : Entity_Id) return Boolean is
18385          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
18386          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
18387       begin
18388          return Lo <= Lo_Val and then Lo_Val <= Hi
18389                   and then
18390                 Lo <= Hi_Val and then Hi_Val <= Hi;
18391       end Can_Derive_From;
18392
18393       -----------------
18394       -- Check_Bound --
18395       -----------------
18396
18397       procedure Check_Bound (Expr : Node_Id) is
18398       begin
18399          --  If a range constraint is used as an integer type definition, each
18400          --  bound of the range must be defined by a static expression of some
18401          --  integer type, but the two bounds need not have the same integer
18402          --  type (Negative bounds are allowed.) (RM 3.5.4)
18403
18404          if not Is_Integer_Type (Etype (Expr)) then
18405             Error_Msg_N
18406               ("integer type definition bounds must be of integer type", Expr);
18407             Errs := True;
18408
18409          elsif not Is_OK_Static_Expression (Expr) then
18410             Flag_Non_Static_Expr
18411               ("non-static expression used for integer type bound!", Expr);
18412             Errs := True;
18413
18414          --  The bounds are folded into literals, and we set their type to be
18415          --  universal, to avoid typing difficulties: we cannot set the type
18416          --  of the literal to the new type, because this would be a forward
18417          --  reference for the back end,  and if the original type is user-
18418          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
18419
18420          else
18421             if Is_Entity_Name (Expr) then
18422                Fold_Uint (Expr, Expr_Value (Expr), True);
18423             end if;
18424
18425             Set_Etype (Expr, Universal_Integer);
18426          end if;
18427       end Check_Bound;
18428
18429    --  Start of processing for Signed_Integer_Type_Declaration
18430
18431    begin
18432       --  Create an anonymous base type
18433
18434       Implicit_Base :=
18435         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
18436
18437       --  Analyze and check the bounds, they can be of any integer type
18438
18439       Lo := Low_Bound (Def);
18440       Hi := High_Bound (Def);
18441
18442       --  Arbitrarily use Integer as the type if either bound had an error
18443
18444       if Hi = Error or else Lo = Error then
18445          Base_Typ := Any_Integer;
18446          Set_Error_Posted (T, True);
18447
18448       --  Here both bounds are OK expressions
18449
18450       else
18451          Analyze_And_Resolve (Lo, Any_Integer);
18452          Analyze_And_Resolve (Hi, Any_Integer);
18453
18454          Check_Bound (Lo);
18455          Check_Bound (Hi);
18456
18457          if Errs then
18458             Hi := Type_High_Bound (Standard_Long_Long_Integer);
18459             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
18460          end if;
18461
18462          --  Find type to derive from
18463
18464          Lo_Val := Expr_Value (Lo);
18465          Hi_Val := Expr_Value (Hi);
18466
18467          if Can_Derive_From (Standard_Short_Short_Integer) then
18468             Base_Typ := Base_Type (Standard_Short_Short_Integer);
18469
18470          elsif Can_Derive_From (Standard_Short_Integer) then
18471             Base_Typ := Base_Type (Standard_Short_Integer);
18472
18473          elsif Can_Derive_From (Standard_Integer) then
18474             Base_Typ := Base_Type (Standard_Integer);
18475
18476          elsif Can_Derive_From (Standard_Long_Integer) then
18477             Base_Typ := Base_Type (Standard_Long_Integer);
18478
18479          elsif Can_Derive_From (Standard_Long_Long_Integer) then
18480             Base_Typ := Base_Type (Standard_Long_Long_Integer);
18481
18482          else
18483             Base_Typ := Base_Type (Standard_Long_Long_Integer);
18484             Error_Msg_N ("integer type definition bounds out of range", Def);
18485             Hi := Type_High_Bound (Standard_Long_Long_Integer);
18486             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
18487          end if;
18488       end if;
18489
18490       --  Complete both implicit base and declared first subtype entities
18491
18492       Set_Etype          (Implicit_Base, Base_Typ);
18493       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
18494       Set_Size_Info      (Implicit_Base,                (Base_Typ));
18495       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
18496       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
18497
18498       Set_Ekind          (T, E_Signed_Integer_Subtype);
18499       Set_Etype          (T, Implicit_Base);
18500
18501       Set_Size_Info      (T,                (Implicit_Base));
18502       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
18503       Set_Scalar_Range   (T, Def);
18504       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
18505       Set_Is_Constrained (T);
18506    end Signed_Integer_Type_Declaration;
18507
18508 end Sem_Ch3;