OSDN Git Service

2010-10-18 Javier Miranda <miranda@adacore.com>
[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 Aspects;  use Aspects;
27 with Atree;    use Atree;
28 with Checks;   use Checks;
29 with Debug;    use Debug;
30 with Elists;   use Elists;
31 with Einfo;    use Einfo;
32 with Errout;   use Errout;
33 with Eval_Fat; use Eval_Fat;
34 with Exp_Ch3;  use Exp_Ch3;
35 with Exp_Ch9;  use Exp_Ch9;
36 with Exp_Disp; use Exp_Disp;
37 with Exp_Dist; use Exp_Dist;
38 with Exp_Tss;  use Exp_Tss;
39 with Exp_Util; use Exp_Util;
40 with Fname;    use Fname;
41 with Freeze;   use Freeze;
42 with Itypes;   use Itypes;
43 with Layout;   use Layout;
44 with Lib;      use Lib;
45 with Lib.Xref; use Lib.Xref;
46 with Namet;    use Namet;
47 with Nmake;    use Nmake;
48 with Opt;      use Opt;
49 with Restrict; use Restrict;
50 with Rident;   use Rident;
51 with Rtsfind;  use Rtsfind;
52 with Sem;      use Sem;
53 with Sem_Aux;  use Sem_Aux;
54 with Sem_Case; use Sem_Case;
55 with Sem_Cat;  use Sem_Cat;
56 with Sem_Ch6;  use Sem_Ch6;
57 with Sem_Ch7;  use Sem_Ch7;
58 with Sem_Ch8;  use Sem_Ch8;
59 with Sem_Ch13; use Sem_Ch13;
60 with Sem_Disp; use Sem_Disp;
61 with Sem_Dist; use Sem_Dist;
62 with Sem_Elim; use Sem_Elim;
63 with Sem_Eval; use Sem_Eval;
64 with Sem_Mech; use Sem_Mech;
65 with Sem_Prag; use Sem_Prag;
66 with Sem_Res;  use Sem_Res;
67 with Sem_Smem; use Sem_Smem;
68 with Sem_Type; use Sem_Type;
69 with Sem_Util; use Sem_Util;
70 with Sem_Warn; use Sem_Warn;
71 with Stand;    use Stand;
72 with Sinfo;    use Sinfo;
73 with Sinput;   use Sinput;
74 with Snames;   use Snames;
75 with Targparm; use Targparm;
76 with Tbuild;   use Tbuild;
77 with Ttypes;   use Ttypes;
78 with Uintp;    use Uintp;
79 with Urealp;   use Urealp;
80
81 package body Sem_Ch3 is
82
83    -----------------------
84    -- Local Subprograms --
85    -----------------------
86
87    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id);
88    --  Ada 2005 (AI-251): Add the tag components corresponding to all the
89    --  abstract interface types implemented by a record type or a derived
90    --  record type.
91
92    procedure Build_Derived_Type
93      (N             : Node_Id;
94       Parent_Type   : Entity_Id;
95       Derived_Type  : Entity_Id;
96       Is_Completion : Boolean;
97       Derive_Subps  : Boolean := True);
98    --  Create and decorate a Derived_Type given the Parent_Type entity. N is
99    --  the N_Full_Type_Declaration node containing the derived type definition.
100    --  Parent_Type is the entity for the parent type in the derived type
101    --  definition and Derived_Type the actual derived type. Is_Completion must
102    --  be set to False if Derived_Type is the N_Defining_Identifier node in N
103    --  (i.e. Derived_Type = Defining_Identifier (N)). In this case N is not the
104    --  completion of a private type declaration. If Is_Completion is set to
105    --  True, N is the completion of a private type declaration and Derived_Type
106    --  is different from the defining identifier inside N (i.e. Derived_Type /=
107    --  Defining_Identifier (N)). Derive_Subps indicates whether the parent
108    --  subprograms should be derived. The only case where this parameter is
109    --  False is when Build_Derived_Type is recursively called to process an
110    --  implicit derived full type for a type derived from a private type (in
111    --  that case the subprograms must only be derived for the private view of
112    --  the type).
113    --
114    --  ??? These flags need a bit of re-examination and re-documentation:
115    --  ???  are they both necessary (both seem related to the recursion)?
116
117    procedure Build_Derived_Access_Type
118      (N            : Node_Id;
119       Parent_Type  : Entity_Id;
120       Derived_Type : Entity_Id);
121    --  Subsidiary procedure to Build_Derived_Type. For a derived access type,
122    --  create an implicit base if the parent type is constrained or if the
123    --  subtype indication has a constraint.
124
125    procedure Build_Derived_Array_Type
126      (N            : Node_Id;
127       Parent_Type  : Entity_Id;
128       Derived_Type : Entity_Id);
129    --  Subsidiary procedure to Build_Derived_Type. For a derived array type,
130    --  create an implicit base if the parent type is constrained or if the
131    --  subtype indication has a constraint.
132
133    procedure Build_Derived_Concurrent_Type
134      (N            : Node_Id;
135       Parent_Type  : Entity_Id;
136       Derived_Type : Entity_Id);
137    --  Subsidiary procedure to Build_Derived_Type. For a derived task or
138    --  protected type, inherit entries and protected subprograms, check
139    --  legality of discriminant constraints if any.
140
141    procedure Build_Derived_Enumeration_Type
142      (N            : Node_Id;
143       Parent_Type  : Entity_Id;
144       Derived_Type : Entity_Id);
145    --  Subsidiary procedure to Build_Derived_Type. For a derived enumeration
146    --  type, we must create a new list of literals. Types derived from
147    --  Character and [Wide_]Wide_Character are special-cased.
148
149    procedure Build_Derived_Numeric_Type
150      (N            : Node_Id;
151       Parent_Type  : Entity_Id;
152       Derived_Type : Entity_Id);
153    --  Subsidiary procedure to Build_Derived_Type. For numeric types, create
154    --  an anonymous base type, and propagate constraint to subtype if needed.
155
156    procedure Build_Derived_Private_Type
157      (N             : Node_Id;
158       Parent_Type   : Entity_Id;
159       Derived_Type  : Entity_Id;
160       Is_Completion : Boolean;
161       Derive_Subps  : Boolean := True);
162    --  Subsidiary procedure to Build_Derived_Type. This procedure is complex
163    --  because the parent may or may not have a completion, and the derivation
164    --  may itself be a completion.
165
166    procedure Build_Derived_Record_Type
167      (N            : Node_Id;
168       Parent_Type  : Entity_Id;
169       Derived_Type : Entity_Id;
170       Derive_Subps : Boolean := True);
171    --  Subsidiary procedure for Build_Derived_Type and
172    --  Analyze_Private_Extension_Declaration used for tagged and untagged
173    --  record types. All parameters are as in Build_Derived_Type except that
174    --  N, in addition to being an N_Full_Type_Declaration node, can also be an
175    --  N_Private_Extension_Declaration node. See the definition of this routine
176    --  for much more info. Derive_Subps indicates whether subprograms should
177    --  be derived from the parent type. The only case where Derive_Subps is
178    --  False is for an implicit derived full type for a type derived from a
179    --  private type (see Build_Derived_Type).
180
181    procedure Build_Discriminal (Discrim : Entity_Id);
182    --  Create the discriminal corresponding to discriminant Discrim, that is
183    --  the parameter corresponding to Discrim to be used in initialization
184    --  procedures for the type where Discrim is a discriminant. Discriminals
185    --  are not used during semantic analysis, and are not fully defined
186    --  entities until expansion. Thus they are not given a scope until
187    --  initialization procedures are built.
188
189    function Build_Discriminant_Constraints
190      (T           : Entity_Id;
191       Def         : Node_Id;
192       Derived_Def : Boolean := False) return Elist_Id;
193    --  Validate discriminant constraints and return the list of the constraints
194    --  in order of discriminant declarations, where T is the discriminated
195    --  unconstrained type. Def is the N_Subtype_Indication node where the
196    --  discriminants constraints for T are specified. Derived_Def is True
197    --  when building the discriminant constraints in a derived type definition
198    --  of the form "type D (...) is new T (xxx)". In this case T is the parent
199    --  type and Def is the constraint "(xxx)" on T and this routine sets the
200    --  Corresponding_Discriminant field of the discriminants in the derived
201    --  type D to point to the corresponding discriminants in the parent type T.
202
203    procedure Build_Discriminated_Subtype
204      (T           : Entity_Id;
205       Def_Id      : Entity_Id;
206       Elist       : Elist_Id;
207       Related_Nod : Node_Id;
208       For_Access  : Boolean := False);
209    --  Subsidiary procedure to Constrain_Discriminated_Type and to
210    --  Process_Incomplete_Dependents. Given
211    --
212    --     T (a possibly discriminated base type)
213    --     Def_Id (a very partially built subtype for T),
214    --
215    --  the call completes Def_Id to be the appropriate E_*_Subtype.
216    --
217    --  The Elist is the list of discriminant constraints if any (it is set
218    --  to No_Elist if T is not a discriminated type, and to an empty list if
219    --  T has discriminants but there are no discriminant constraints). The
220    --  Related_Nod is the same as Decl_Node in Create_Constrained_Components.
221    --  The For_Access says whether or not this subtype is really constraining
222    --  an access type. That is its sole purpose is the designated type of an
223    --  access type -- in which case a Private_Subtype Is_For_Access_Subtype
224    --  is built to avoid freezing T when the access subtype is frozen.
225
226    function Build_Scalar_Bound
227      (Bound : Node_Id;
228       Par_T : Entity_Id;
229       Der_T : Entity_Id) return Node_Id;
230    --  The bounds of a derived scalar type are conversions of the bounds of
231    --  the parent type. Optimize the representation if the bounds are literals.
232    --  Needs a more complete spec--what are the parameters exactly, and what
233    --  exactly is the returned value, and how is Bound affected???
234
235    procedure Build_Underlying_Full_View
236      (N   : Node_Id;
237       Typ : Entity_Id;
238       Par : Entity_Id);
239    --  If the completion of a private type is itself derived from a private
240    --  type, or if the full view of a private subtype is itself private, the
241    --  back-end has no way to compute the actual size of this type. We build
242    --  an internal subtype declaration of the proper parent type to convey
243    --  this information. This extra mechanism is needed because a full
244    --  view cannot itself have a full view (it would get clobbered during
245    --  view exchanges).
246
247    procedure Check_Access_Discriminant_Requires_Limited
248      (D   : Node_Id;
249       Loc : Node_Id);
250    --  Check the restriction that the type to which an access discriminant
251    --  belongs must be a concurrent type or a descendant of a type with
252    --  the reserved word 'limited' in its declaration.
253
254    procedure Check_Anonymous_Access_Components
255       (Typ_Decl  : Node_Id;
256        Typ       : Entity_Id;
257        Prev      : Entity_Id;
258        Comp_List : Node_Id);
259    --  Ada 2005 AI-382: an access component in a record definition can refer to
260    --  the enclosing record, in which case it denotes the type itself, and not
261    --  the current instance of the type. We create an anonymous access type for
262    --  the component, and flag it as an access to a component, so accessibility
263    --  checks are properly performed on it. The declaration of the access type
264    --  is placed ahead of that of the record to prevent order-of-elaboration
265    --  circularity issues in Gigi. We create an incomplete type for the record
266    --  declaration, which is the designated type of the anonymous access.
267
268    procedure Check_Delta_Expression (E : Node_Id);
269    --  Check that the expression represented by E is suitable for use as a
270    --  delta expression, i.e. it is of real type and is static.
271
272    procedure Check_Digits_Expression (E : Node_Id);
273    --  Check that the expression represented by E is suitable for use as a
274    --  digits expression, i.e. it is of integer type, positive and static.
275
276    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id);
277    --  Validate the initialization of an object declaration. T is the required
278    --  type, and Exp is the initialization expression.
279
280    procedure Check_Interfaces (N : Node_Id; Def : Node_Id);
281    --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
282
283    procedure Check_Or_Process_Discriminants
284      (N    : Node_Id;
285       T    : Entity_Id;
286       Prev : Entity_Id := Empty);
287    --  If T is the full declaration of an incomplete or private type, check the
288    --  conformance of the discriminants, otherwise process them. Prev is the
289    --  entity of the partial declaration, if any.
290
291    procedure Check_Real_Bound (Bound : Node_Id);
292    --  Check given bound for being of real type and static. If not, post an
293    --  appropriate message, and rewrite the bound with the real literal zero.
294
295    procedure Constant_Redeclaration
296      (Id : Entity_Id;
297       N  : Node_Id;
298       T  : out Entity_Id);
299    --  Various checks on legality of full declaration of deferred constant.
300    --  Id is the entity for the redeclaration, N is the N_Object_Declaration,
301    --  node. The caller has not yet set any attributes of this entity.
302
303    function Contain_Interface
304      (Iface  : Entity_Id;
305       Ifaces : Elist_Id) return Boolean;
306    --  Ada 2005: Determine whether Iface is present in the list Ifaces
307
308    procedure Convert_Scalar_Bounds
309      (N            : Node_Id;
310       Parent_Type  : Entity_Id;
311       Derived_Type : Entity_Id;
312       Loc          : Source_Ptr);
313    --  For derived scalar types, convert the bounds in the type definition to
314    --  the derived type, and complete their analysis. Given a constraint of the
315    --  form ".. new T range Lo .. Hi", Lo and Hi are analyzed and resolved with
316    --  T'Base, the parent_type. The bounds of the derived type (the anonymous
317    --  base) are copies of Lo and Hi. Finally, the bounds of the derived
318    --  subtype are conversions of those bounds to the derived_type, so that
319    --  their typing is consistent.
320
321    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id);
322    --  Copies attributes from array base type T2 to array base type T1. Copies
323    --  only attributes that apply to base types, but not subtypes.
324
325    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id);
326    --  Copies attributes from array subtype T2 to array subtype T1. Copies
327    --  attributes that apply to both subtypes and base types.
328
329    procedure Create_Constrained_Components
330      (Subt        : Entity_Id;
331       Decl_Node   : Node_Id;
332       Typ         : Entity_Id;
333       Constraints : Elist_Id);
334    --  Build the list of entities for a constrained discriminated record
335    --  subtype. If a component depends on a discriminant, replace its subtype
336    --  using the discriminant values in the discriminant constraint. Subt
337    --  is the defining identifier for the subtype whose list of constrained
338    --  entities we will create. Decl_Node is the type declaration node where
339    --  we will attach all the itypes created. Typ is the base discriminated
340    --  type for the subtype Subt. Constraints is the list of discriminant
341    --  constraints for Typ.
342
343    function Constrain_Component_Type
344      (Comp            : Entity_Id;
345       Constrained_Typ : Entity_Id;
346       Related_Node    : Node_Id;
347       Typ             : Entity_Id;
348       Constraints     : Elist_Id) return Entity_Id;
349    --  Given a discriminated base type Typ, a list of discriminant constraint
350    --  Constraints for Typ and a component of Typ, with type Compon_Type,
351    --  create and return the type corresponding to Compon_type where all
352    --  discriminant references are replaced with the corresponding constraint.
353    --  If no discriminant references occur in Compon_Typ then return it as is.
354    --  Constrained_Typ is the final constrained subtype to which the
355    --  constrained Compon_Type belongs. Related_Node is the node where we will
356    --  attach all the itypes created.
357    --
358    --  Above description is confused, what is Compon_Type???
359
360    procedure Constrain_Access
361      (Def_Id      : in out Entity_Id;
362       S           : Node_Id;
363       Related_Nod : Node_Id);
364    --  Apply a list of constraints to an access type. If Def_Id is empty, it is
365    --  an anonymous type created for a subtype indication. In that case it is
366    --  created in the procedure and attached to Related_Nod.
367
368    procedure Constrain_Array
369      (Def_Id      : in out Entity_Id;
370       SI          : Node_Id;
371       Related_Nod : Node_Id;
372       Related_Id  : Entity_Id;
373       Suffix      : Character);
374    --  Apply a list of index constraints to an unconstrained array type. The
375    --  first parameter is the entity for the resulting subtype. A value of
376    --  Empty for Def_Id indicates that an implicit type must be created, but
377    --  creation is delayed (and must be done by this procedure) because other
378    --  subsidiary implicit types must be created first (which is why Def_Id
379    --  is an in/out parameter). The second parameter is a subtype indication
380    --  node for the constrained array to be created (e.g. something of the
381    --  form string (1 .. 10)). Related_Nod gives the place where this type
382    --  has to be inserted in the tree. The Related_Id and Suffix parameters
383    --  are used to build the associated Implicit type name.
384
385    procedure Constrain_Concurrent
386      (Def_Id      : in out Entity_Id;
387       SI          : Node_Id;
388       Related_Nod : Node_Id;
389       Related_Id  : Entity_Id;
390       Suffix      : Character);
391    --  Apply list of discriminant constraints to an unconstrained concurrent
392    --  type.
393    --
394    --    SI is the N_Subtype_Indication node containing the constraint and
395    --    the unconstrained type to constrain.
396    --
397    --    Def_Id is the entity for the resulting constrained subtype. A value
398    --    of Empty for Def_Id indicates that an implicit type must be created,
399    --    but creation is delayed (and must be done by this procedure) because
400    --    other subsidiary implicit types must be created first (which is why
401    --    Def_Id is an in/out parameter).
402    --
403    --    Related_Nod gives the place where this type has to be inserted
404    --    in the tree
405    --
406    --  The last two arguments are used to create its external name if needed.
407
408    function Constrain_Corresponding_Record
409      (Prot_Subt   : Entity_Id;
410       Corr_Rec    : Entity_Id;
411       Related_Nod : Node_Id;
412       Related_Id  : Entity_Id) return Entity_Id;
413    --  When constraining a protected type or task type with discriminants,
414    --  constrain the corresponding record with the same discriminant values.
415
416    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id);
417    --  Constrain a decimal fixed point type with a digits constraint and/or a
418    --  range constraint, and build E_Decimal_Fixed_Point_Subtype entity.
419
420    procedure Constrain_Discriminated_Type
421      (Def_Id      : Entity_Id;
422       S           : Node_Id;
423       Related_Nod : Node_Id;
424       For_Access  : Boolean := False);
425    --  Process discriminant constraints of composite type. Verify that values
426    --  have been provided for all discriminants, that the original type is
427    --  unconstrained, and that the types of the supplied expressions match
428    --  the discriminant types. The first three parameters are like in routine
429    --  Constrain_Concurrent. See Build_Discriminated_Subtype for an explanation
430    --  of For_Access.
431
432    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id);
433    --  Constrain an enumeration type with a range constraint. This is identical
434    --  to Constrain_Integer, but for the Ekind of the resulting subtype.
435
436    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id);
437    --  Constrain a floating point type with either a digits constraint
438    --  and/or a range constraint, building a E_Floating_Point_Subtype.
439
440    procedure Constrain_Index
441      (Index        : Node_Id;
442       S            : Node_Id;
443       Related_Nod  : Node_Id;
444       Related_Id   : Entity_Id;
445       Suffix       : Character;
446       Suffix_Index : Nat);
447    --  Process an index constraint in a constrained array declaration. The
448    --  constraint can be a subtype name, or a range with or without an explicit
449    --  subtype mark. The index is the corresponding index of the unconstrained
450    --  array. The Related_Id and Suffix parameters are used to build the
451    --  associated Implicit type name.
452
453    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id);
454    --  Build subtype of a signed or modular integer type
455
456    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id);
457    --  Constrain an ordinary fixed point type with a range constraint, and
458    --  build an E_Ordinary_Fixed_Point_Subtype entity.
459
460    procedure Copy_And_Swap (Priv, Full : Entity_Id);
461    --  Copy the Priv entity into the entity of its full declaration then swap
462    --  the two entities in such a manner that the former private type is now
463    --  seen as a full type.
464
465    procedure Decimal_Fixed_Point_Type_Declaration
466      (T   : Entity_Id;
467       Def : Node_Id);
468    --  Create a new decimal fixed point type, and apply the constraint to
469    --  obtain a subtype of this new type.
470
471    procedure Complete_Private_Subtype
472      (Priv        : Entity_Id;
473       Full        : Entity_Id;
474       Full_Base   : Entity_Id;
475       Related_Nod : Node_Id);
476    --  Complete the implicit full view of a private subtype by setting the
477    --  appropriate semantic fields. If the full view of the parent is a record
478    --  type, build constrained components of subtype.
479
480    procedure Derive_Progenitor_Subprograms
481      (Parent_Type : Entity_Id;
482       Tagged_Type : Entity_Id);
483    --  Ada 2005 (AI-251): To complete type derivation, collect the primitive
484    --  operations of progenitors of Tagged_Type, and replace the subsidiary
485    --  subtypes with Tagged_Type, to build the specs of the inherited interface
486    --  primitives. The derived primitives are aliased to those of the
487    --  interface. This routine takes care also of transferring to the full-view
488    --  subprograms associated with the partial-view of Tagged_Type that cover
489    --  interface primitives.
490
491    procedure Derived_Standard_Character
492      (N             : Node_Id;
493       Parent_Type   : Entity_Id;
494       Derived_Type  : Entity_Id);
495    --  Subsidiary procedure to Build_Derived_Enumeration_Type which handles
496    --  derivations from types Standard.Character and Standard.Wide_Character.
497
498    procedure Derived_Type_Declaration
499      (T             : Entity_Id;
500       N             : Node_Id;
501       Is_Completion : Boolean);
502    --  Process a derived type declaration. Build_Derived_Type is invoked
503    --  to process the actual derived type definition. Parameters N and
504    --  Is_Completion have the same meaning as in Build_Derived_Type.
505    --  T is the N_Defining_Identifier for the entity defined in the
506    --  N_Full_Type_Declaration node N, that is T is the derived type.
507
508    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id);
509    --  Insert each literal in symbol table, as an overloadable identifier. Each
510    --  enumeration type is mapped into a sequence of integers, and each literal
511    --  is defined as a constant with integer value. If any of the literals are
512    --  character literals, the type is a character type, which means that
513    --  strings are legal aggregates for arrays of components of the type.
514
515    function Expand_To_Stored_Constraint
516      (Typ        : Entity_Id;
517       Constraint : Elist_Id) return Elist_Id;
518    --  Given a constraint (i.e. a list of expressions) on the discriminants of
519    --  Typ, expand it into a constraint on the stored discriminants and return
520    --  the new list of expressions constraining the stored discriminants.
521
522    function Find_Type_Of_Object
523      (Obj_Def     : Node_Id;
524       Related_Nod : Node_Id) return Entity_Id;
525    --  Get type entity for object referenced by Obj_Def, attaching the
526    --  implicit types generated to Related_Nod
527
528    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id);
529    --  Create a new float and apply the constraint to obtain subtype of it
530
531    function Has_Range_Constraint (N : Node_Id) return Boolean;
532    --  Given an N_Subtype_Indication node N, return True if a range constraint
533    --  is present, either directly, or as part of a digits or delta constraint.
534    --  In addition, a digits constraint in the decimal case returns True, since
535    --  it establishes a default range if no explicit range is present.
536
537    function Inherit_Components
538      (N             : Node_Id;
539       Parent_Base   : Entity_Id;
540       Derived_Base  : Entity_Id;
541       Is_Tagged     : Boolean;
542       Inherit_Discr : Boolean;
543       Discs         : Elist_Id) return Elist_Id;
544    --  Called from Build_Derived_Record_Type to inherit the components of
545    --  Parent_Base (a base type) into the Derived_Base (the derived base type).
546    --  For more information on derived types and component inheritance please
547    --  consult the comment above the body of Build_Derived_Record_Type.
548    --
549    --    N is the original derived type declaration
550    --
551    --    Is_Tagged is set if we are dealing with tagged types
552    --
553    --    If Inherit_Discr is set, Derived_Base inherits its discriminants from
554    --    Parent_Base, otherwise no discriminants are inherited.
555    --
556    --    Discs gives the list of constraints that apply to Parent_Base in the
557    --    derived type declaration. If Discs is set to No_Elist, then we have
558    --    the following situation:
559    --
560    --      type Parent (D1..Dn : ..) is [tagged] record ...;
561    --      type Derived is new Parent [with ...];
562    --
563    --    which gets treated as
564    --
565    --      type Derived (D1..Dn : ..) is new Parent (D1,..,Dn) [with ...];
566    --
567    --  For untagged types the returned value is an association list. The list
568    --  starts from the association (Parent_Base => Derived_Base), and then it
569    --  contains a sequence of the associations of the form
570    --
571    --    (Old_Component => New_Component),
572    --
573    --  where Old_Component is the Entity_Id of a component in Parent_Base and
574    --  New_Component is the Entity_Id of the corresponding component in
575    --  Derived_Base. For untagged records, this association list is needed when
576    --  copying the record declaration for the derived base. In the tagged case
577    --  the value returned is irrelevant.
578
579    function Is_Valid_Constraint_Kind
580      (T_Kind          : Type_Kind;
581       Constraint_Kind : Node_Kind) return Boolean;
582    --  Returns True if it is legal to apply the given kind of constraint to the
583    --  given kind of type (index constraint to an array type, for example).
584
585    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id);
586    --  Create new modular type. Verify that modulus is in bounds and is
587    --  a power of two (implementation restriction).
588
589    procedure New_Concatenation_Op (Typ : Entity_Id);
590    --  Create an abbreviated declaration for an operator in order to
591    --  materialize concatenation on array types.
592
593    procedure Ordinary_Fixed_Point_Type_Declaration
594      (T   : Entity_Id;
595       Def : Node_Id);
596    --  Create a new ordinary fixed point type, and apply the constraint to
597    --  obtain subtype of it.
598
599    procedure Prepare_Private_Subtype_Completion
600      (Id          : Entity_Id;
601       Related_Nod : Node_Id);
602    --  Id is a subtype of some private type. Creates the full declaration
603    --  associated with Id whenever possible, i.e. when the full declaration
604    --  of the base type is already known. Records each subtype into
605    --  Private_Dependents of the base type.
606
607    procedure Process_Incomplete_Dependents
608      (N      : Node_Id;
609       Full_T : Entity_Id;
610       Inc_T  : Entity_Id);
611    --  Process all entities that depend on an incomplete type. There include
612    --  subtypes, subprogram types that mention the incomplete type in their
613    --  profiles, and subprogram with access parameters that designate the
614    --  incomplete type.
615
616    --  Inc_T is the defining identifier of an incomplete type declaration, its
617    --  Ekind is E_Incomplete_Type.
618    --
619    --    N is the corresponding N_Full_Type_Declaration for Inc_T.
620    --
621    --    Full_T is N's defining identifier.
622    --
623    --  Subtypes of incomplete types with discriminants are completed when the
624    --  parent type is. This is simpler than private subtypes, because they can
625    --  only appear in the same scope, and there is no need to exchange views.
626    --  Similarly, access_to_subprogram types may have a parameter or a return
627    --  type that is an incomplete type, and that must be replaced with the
628    --  full type.
629    --
630    --  If the full type is tagged, subprogram with access parameters that
631    --  designated the incomplete may be primitive operations of the full type,
632    --  and have to be processed accordingly.
633
634    procedure Process_Real_Range_Specification (Def : Node_Id);
635    --  Given the type definition for a real type, this procedure processes and
636    --  checks the real range specification of this type definition if one is
637    --  present. If errors are found, error messages are posted, and the
638    --  Real_Range_Specification of Def is reset to Empty.
639
640    procedure Record_Type_Declaration
641      (T    : Entity_Id;
642       N    : Node_Id;
643       Prev : Entity_Id);
644    --  Process a record type declaration (for both untagged and tagged
645    --  records). Parameters T and N are exactly like in procedure
646    --  Derived_Type_Declaration, except that no flag Is_Completion is needed
647    --  for this routine. If this is the completion of an incomplete type
648    --  declaration, Prev is the entity of the incomplete declaration, used for
649    --  cross-referencing. Otherwise Prev = T.
650
651    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id);
652    --  This routine is used to process the actual record type definition (both
653    --  for untagged and tagged records). Def is a record type definition node.
654    --  This procedure analyzes the components in this record type definition.
655    --  Prev_T is the entity for the enclosing record type. It is provided so
656    --  that its Has_Task flag can be set if any of the component have Has_Task
657    --  set. If the declaration is the completion of an incomplete type
658    --  declaration, Prev_T is the original incomplete type, whose full view is
659    --  the record type.
660
661    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id);
662    --  Subsidiary to Build_Derived_Record_Type. For untagged records, we
663    --  build a copy of the declaration tree of the parent, and we create
664    --  independently the list of components for the derived type. Semantic
665    --  information uses the component entities, but record representation
666    --  clauses are validated on the declaration tree. This procedure replaces
667    --  discriminants and components in the declaration with those that have
668    --  been created by Inherit_Components.
669
670    procedure Set_Fixed_Range
671      (E   : Entity_Id;
672       Loc : Source_Ptr;
673       Lo  : Ureal;
674       Hi  : Ureal);
675    --  Build a range node with the given bounds and set it as the Scalar_Range
676    --  of the given fixed-point type entity. Loc is the source location used
677    --  for the constructed range. See body for further details.
678
679    procedure Set_Scalar_Range_For_Subtype
680      (Def_Id : Entity_Id;
681       R      : Node_Id;
682       Subt   : Entity_Id);
683    --  This routine is used to set the scalar range field for a subtype given
684    --  Def_Id, the entity for the subtype, and R, the range expression for the
685    --  scalar range. Subt provides the parent subtype to be used to analyze,
686    --  resolve, and check the given range.
687
688    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id);
689    --  Create a new signed integer entity, and apply the constraint to obtain
690    --  the required first named subtype of this type.
691
692    procedure Set_Stored_Constraint_From_Discriminant_Constraint
693      (E : Entity_Id);
694    --  E is some record type. This routine computes E's Stored_Constraint
695    --  from its Discriminant_Constraint.
696
697    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id);
698    --  Check that an entity in a list of progenitors is an interface,
699    --  emit error otherwise.
700
701    -----------------------
702    -- Access_Definition --
703    -----------------------
704
705    function Access_Definition
706      (Related_Nod : Node_Id;
707       N           : Node_Id) return Entity_Id
708    is
709       Loc                 : constant Source_Ptr := Sloc (Related_Nod);
710       Anon_Type           : Entity_Id;
711       Anon_Scope          : Entity_Id;
712       Desig_Type          : Entity_Id;
713       Decl                : Entity_Id;
714       Enclosing_Prot_Type : Entity_Id := Empty;
715
716    begin
717       if Is_Entry (Current_Scope)
718         and then Is_Task_Type (Etype (Scope (Current_Scope)))
719       then
720          Error_Msg_N ("task entries cannot have access parameters", N);
721          return Empty;
722       end if;
723
724       --  Ada 2005: for an object declaration the corresponding anonymous
725       --  type is declared in the current scope.
726
727       --  If the access definition is the return type of another access to
728       --  function, scope is the current one, because it is the one of the
729       --  current type declaration.
730
731       if Nkind_In (Related_Nod, N_Object_Declaration,
732                                 N_Access_Function_Definition)
733       then
734          Anon_Scope := Current_Scope;
735
736       --  For the anonymous function result case, retrieve the scope of the
737       --  function specification's associated entity rather than using the
738       --  current scope. The current scope will be the function itself if the
739       --  formal part is currently being analyzed, but will be the parent scope
740       --  in the case of a parameterless function, and we always want to use
741       --  the function's parent scope. Finally, if the function is a child
742       --  unit, we must traverse the tree to retrieve the proper entity.
743
744       elsif Nkind (Related_Nod) = N_Function_Specification
745         and then Nkind (Parent (N)) /= N_Parameter_Specification
746       then
747          --  If the current scope is a protected type, the anonymous access
748          --  is associated with one of the protected operations, and must
749          --  be available in the scope that encloses the protected declaration.
750          --  Otherwise the type is in the scope enclosing the subprogram.
751
752          --  If the function has formals, The return type of a subprogram
753          --  declaration is analyzed in the scope of the subprogram (see
754          --  Process_Formals) and thus the protected type, if present, is
755          --  the scope of the current function scope.
756
757          if Ekind (Current_Scope) = E_Protected_Type then
758             Enclosing_Prot_Type := Current_Scope;
759
760          elsif Ekind (Current_Scope) = E_Function
761            and then Ekind (Scope (Current_Scope)) = E_Protected_Type
762          then
763             Enclosing_Prot_Type := Scope (Current_Scope);
764          end if;
765
766          if Present (Enclosing_Prot_Type) then
767             Anon_Scope := Scope (Enclosing_Prot_Type);
768
769          else
770             Anon_Scope := Scope (Defining_Entity (Related_Nod));
771          end if;
772
773       else
774          --  For access formals, access components, and access discriminants,
775          --  the scope is that of the enclosing declaration,
776
777          Anon_Scope := Scope (Current_Scope);
778       end if;
779
780       Anon_Type :=
781         Create_Itype
782          (E_Anonymous_Access_Type, Related_Nod, Scope_Id => Anon_Scope);
783
784       if All_Present (N)
785         and then Ada_Version >= Ada_2005
786       then
787          Error_Msg_N ("ALL is not permitted for anonymous access types", N);
788       end if;
789
790       --  Ada 2005 (AI-254): In case of anonymous access to subprograms call
791       --  the corresponding semantic routine
792
793       if Present (Access_To_Subprogram_Definition (N)) then
794          Access_Subprogram_Declaration
795            (T_Name => Anon_Type,
796             T_Def  => Access_To_Subprogram_Definition (N));
797
798          if Ekind (Anon_Type) = E_Access_Protected_Subprogram_Type then
799             Set_Ekind
800               (Anon_Type, E_Anonymous_Access_Protected_Subprogram_Type);
801          else
802             Set_Ekind
803               (Anon_Type, E_Anonymous_Access_Subprogram_Type);
804          end if;
805
806          Set_Can_Use_Internal_Rep
807            (Anon_Type, not Always_Compatible_Rep_On_Target);
808
809          --  If the anonymous access is associated with a protected operation
810          --  create a reference to it after the enclosing protected definition
811          --  because the itype will be used in the subsequent bodies.
812
813          if Ekind (Current_Scope) = E_Protected_Type then
814             Build_Itype_Reference (Anon_Type, Parent (Current_Scope));
815          end if;
816
817          return Anon_Type;
818       end if;
819
820       Find_Type (Subtype_Mark (N));
821       Desig_Type := Entity (Subtype_Mark (N));
822
823       Set_Directly_Designated_Type (Anon_Type, Desig_Type);
824       Set_Etype (Anon_Type, Anon_Type);
825
826       --  Make sure the anonymous access type has size and alignment fields
827       --  set, as required by gigi. This is necessary in the case of the
828       --  Task_Body_Procedure.
829
830       if not Has_Private_Component (Desig_Type) then
831          Layout_Type (Anon_Type);
832       end if;
833
834       --  Ada 2005 (AI-231): Ada 2005 semantics for anonymous access differs
835       --  from Ada 95 semantics. In Ada 2005, anonymous access must specify if
836       --  the null value is allowed. In Ada 95 the null value is never allowed.
837
838       if Ada_Version >= Ada_2005 then
839          Set_Can_Never_Be_Null (Anon_Type, Null_Exclusion_Present (N));
840       else
841          Set_Can_Never_Be_Null (Anon_Type, True);
842       end if;
843
844       --  The anonymous access type is as public as the discriminated type or
845       --  subprogram that defines it. It is imported (for back-end purposes)
846       --  if the designated type is.
847
848       Set_Is_Public (Anon_Type, Is_Public (Scope (Anon_Type)));
849
850       --  Ada 2005 (AI-231): Propagate the access-constant attribute
851
852       Set_Is_Access_Constant (Anon_Type, Constant_Present (N));
853
854       --  The context is either a subprogram declaration, object declaration,
855       --  or an access discriminant, in a private or a full type declaration.
856       --  In the case of a subprogram, if the designated type is incomplete,
857       --  the operation will be a primitive operation of the full type, to be
858       --  updated subsequently. If the type is imported through a limited_with
859       --  clause, the subprogram is not a primitive operation of the type
860       --  (which is declared elsewhere in some other scope).
861
862       if Ekind (Desig_Type) = E_Incomplete_Type
863         and then not From_With_Type (Desig_Type)
864         and then Is_Overloadable (Current_Scope)
865       then
866          Append_Elmt (Current_Scope, Private_Dependents (Desig_Type));
867          Set_Has_Delayed_Freeze (Current_Scope);
868       end if;
869
870       --  Ada 2005: if the designated type is an interface that may contain
871       --  tasks, create a Master entity for the declaration. This must be done
872       --  before expansion of the full declaration, because the declaration may
873       --  include an expression that is an allocator, whose expansion needs the
874       --  proper Master for the created tasks.
875
876       if Nkind (Related_Nod) = N_Object_Declaration
877          and then Expander_Active
878       then
879          if Is_Interface (Desig_Type)
880            and then Is_Limited_Record (Desig_Type)
881          then
882             Build_Class_Wide_Master (Anon_Type);
883
884          --  Similarly, if the type is an anonymous access that designates
885          --  tasks, create a master entity for it in the current context.
886
887          elsif Has_Task (Desig_Type)
888            and then Comes_From_Source (Related_Nod)
889            and then not Restriction_Active (No_Task_Hierarchy)
890          then
891             if not Has_Master_Entity (Current_Scope) then
892                Decl :=
893                  Make_Object_Declaration (Loc,
894                    Defining_Identifier =>
895                      Make_Defining_Identifier (Loc, Name_uMaster),
896                    Constant_Present => True,
897                    Object_Definition =>
898                      New_Reference_To (RTE (RE_Master_Id), Loc),
899                    Expression =>
900                      Make_Explicit_Dereference (Loc,
901                        New_Reference_To (RTE (RE_Current_Master), Loc)));
902
903                Insert_Before (Related_Nod, Decl);
904                Analyze (Decl);
905
906                Set_Master_Id (Anon_Type, Defining_Identifier (Decl));
907                Set_Has_Master_Entity (Current_Scope);
908             else
909                Build_Master_Renaming (Related_Nod, Anon_Type);
910             end if;
911          end if;
912       end if;
913
914       --  For a private component of a protected type, it is imperative that
915       --  the back-end elaborate the type immediately after the protected
916       --  declaration, because this type will be used in the declarations
917       --  created for the component within each protected body, so we must
918       --  create an itype reference for it now.
919
920       if Nkind (Parent (Related_Nod)) = N_Protected_Definition then
921          Build_Itype_Reference (Anon_Type, Parent (Parent (Related_Nod)));
922
923       --  Similarly, if the access definition is the return result of a
924       --  function, create an itype reference for it because it will be used
925       --  within the function body. For a regular function that is not a
926       --  compilation unit, insert reference after the declaration. For a
927       --  protected operation, insert it after the enclosing protected type
928       --  declaration. In either case, do not create a reference for a type
929       --  obtained through a limited_with clause, because this would introduce
930       --  semantic dependencies.
931
932       --  Similarly, do not create a reference if the designated type is a
933       --  generic formal, because no use of it will reach the backend.
934
935       elsif Nkind (Related_Nod) = N_Function_Specification
936         and then not From_With_Type (Desig_Type)
937         and then not Is_Generic_Type (Desig_Type)
938       then
939          if Present (Enclosing_Prot_Type) then
940             Build_Itype_Reference (Anon_Type, Parent (Enclosing_Prot_Type));
941
942          elsif Is_List_Member (Parent (Related_Nod))
943            and then Nkind (Parent (N)) /= N_Parameter_Specification
944          then
945             Build_Itype_Reference (Anon_Type, Parent (Related_Nod));
946          end if;
947
948       --  Finally, create an itype reference for an object declaration of an
949       --  anonymous access type. This is strictly necessary only for deferred
950       --  constants, but in any case will avoid out-of-scope problems in the
951       --  back-end.
952
953       elsif Nkind (Related_Nod) = N_Object_Declaration then
954          Build_Itype_Reference (Anon_Type, Related_Nod);
955       end if;
956
957       return Anon_Type;
958    end Access_Definition;
959
960    -----------------------------------
961    -- Access_Subprogram_Declaration --
962    -----------------------------------
963
964    procedure Access_Subprogram_Declaration
965      (T_Name : Entity_Id;
966       T_Def  : Node_Id)
967    is
968
969       procedure Check_For_Premature_Usage (Def : Node_Id);
970       --  Check that type T_Name is not used, directly or recursively, as a
971       --  parameter or a return type in Def. Def is either a subtype, an
972       --  access_definition, or an access_to_subprogram_definition.
973
974       -------------------------------
975       -- Check_For_Premature_Usage --
976       -------------------------------
977
978       procedure Check_For_Premature_Usage (Def : Node_Id) is
979          Param : Node_Id;
980
981       begin
982          --  Check for a subtype mark
983
984          if Nkind (Def) in N_Has_Etype then
985             if Etype (Def) = T_Name then
986                Error_Msg_N
987                  ("type& cannot be used before end of its declaration", Def);
988             end if;
989
990          --  If this is not a subtype, then this is an access_definition
991
992          elsif Nkind (Def) = N_Access_Definition then
993             if Present (Access_To_Subprogram_Definition (Def)) then
994                Check_For_Premature_Usage
995                  (Access_To_Subprogram_Definition (Def));
996             else
997                Check_For_Premature_Usage (Subtype_Mark (Def));
998             end if;
999
1000          --  The only cases left are N_Access_Function_Definition and
1001          --  N_Access_Procedure_Definition.
1002
1003          else
1004             if Present (Parameter_Specifications (Def)) then
1005                Param := First (Parameter_Specifications (Def));
1006                while Present (Param) loop
1007                   Check_For_Premature_Usage (Parameter_Type (Param));
1008                   Param := Next (Param);
1009                end loop;
1010             end if;
1011
1012             if Nkind (Def) = N_Access_Function_Definition then
1013                Check_For_Premature_Usage (Result_Definition (Def));
1014             end if;
1015          end if;
1016       end Check_For_Premature_Usage;
1017
1018       --  Local variables
1019
1020       Formals    : constant List_Id := Parameter_Specifications (T_Def);
1021       Formal     : Entity_Id;
1022       D_Ityp     : Node_Id;
1023       Desig_Type : constant Entity_Id :=
1024                      Create_Itype (E_Subprogram_Type, Parent (T_Def));
1025
1026    --  Start of processing for Access_Subprogram_Declaration
1027
1028    begin
1029       --  Associate the Itype node with the inner full-type declaration or
1030       --  subprogram spec or entry body. This is required to handle nested
1031       --  anonymous declarations. For example:
1032
1033       --      procedure P
1034       --       (X : access procedure
1035       --                     (Y : access procedure
1036       --                                   (Z : access T)))
1037
1038       D_Ityp := Associated_Node_For_Itype (Desig_Type);
1039       while not (Nkind_In (D_Ityp, N_Full_Type_Declaration,
1040                                    N_Private_Type_Declaration,
1041                                    N_Private_Extension_Declaration,
1042                                    N_Procedure_Specification,
1043                                    N_Function_Specification,
1044                                    N_Entry_Body)
1045
1046                    or else
1047                  Nkind_In (D_Ityp, N_Object_Declaration,
1048                                    N_Object_Renaming_Declaration,
1049                                    N_Formal_Object_Declaration,
1050                                    N_Formal_Type_Declaration,
1051                                    N_Task_Type_Declaration,
1052                                    N_Protected_Type_Declaration))
1053       loop
1054          D_Ityp := Parent (D_Ityp);
1055          pragma Assert (D_Ityp /= Empty);
1056       end loop;
1057
1058       Set_Associated_Node_For_Itype (Desig_Type, D_Ityp);
1059
1060       if Nkind_In (D_Ityp, N_Procedure_Specification,
1061                            N_Function_Specification)
1062       then
1063          Set_Scope (Desig_Type, Scope (Defining_Entity (D_Ityp)));
1064
1065       elsif Nkind_In (D_Ityp, N_Full_Type_Declaration,
1066                               N_Object_Declaration,
1067                               N_Object_Renaming_Declaration,
1068                               N_Formal_Type_Declaration)
1069       then
1070          Set_Scope (Desig_Type, Scope (Defining_Identifier (D_Ityp)));
1071       end if;
1072
1073       if Nkind (T_Def) = N_Access_Function_Definition then
1074          if Nkind (Result_Definition (T_Def)) = N_Access_Definition then
1075             declare
1076                Acc : constant Node_Id := Result_Definition (T_Def);
1077
1078             begin
1079                if Present (Access_To_Subprogram_Definition (Acc))
1080                  and then
1081                    Protected_Present (Access_To_Subprogram_Definition (Acc))
1082                then
1083                   Set_Etype
1084                     (Desig_Type,
1085                        Replace_Anonymous_Access_To_Protected_Subprogram
1086                          (T_Def));
1087
1088                else
1089                   Set_Etype
1090                     (Desig_Type,
1091                        Access_Definition (T_Def, Result_Definition (T_Def)));
1092                end if;
1093             end;
1094
1095          else
1096             Analyze (Result_Definition (T_Def));
1097
1098             declare
1099                Typ : constant Entity_Id := Entity (Result_Definition (T_Def));
1100
1101             begin
1102                --  If a null exclusion is imposed on the result type, then
1103                --  create a null-excluding itype (an access subtype) and use
1104                --  it as the function's Etype.
1105
1106                if Is_Access_Type (Typ)
1107                  and then Null_Exclusion_In_Return_Present (T_Def)
1108                then
1109                   Set_Etype  (Desig_Type,
1110                     Create_Null_Excluding_Itype
1111                       (T           => Typ,
1112                        Related_Nod => T_Def,
1113                        Scope_Id    => Current_Scope));
1114
1115                else
1116                   if From_With_Type (Typ) then
1117
1118                      --  AI05-151: Incomplete types are allowed in all basic
1119                      --  declarations, including access to subprograms.
1120
1121                      if Ada_Version >= Ada_2012 then
1122                         null;
1123
1124                      else
1125                         Error_Msg_NE
1126                          ("illegal use of incomplete type&",
1127                             Result_Definition (T_Def), Typ);
1128                      end if;
1129
1130                   elsif Ekind (Current_Scope) = E_Package
1131                     and then In_Private_Part (Current_Scope)
1132                   then
1133                      if Ekind (Typ) = E_Incomplete_Type then
1134                         Append_Elmt (Desig_Type, Private_Dependents (Typ));
1135
1136                      elsif Is_Class_Wide_Type (Typ)
1137                        and then Ekind (Etype (Typ)) = E_Incomplete_Type
1138                      then
1139                         Append_Elmt
1140                           (Desig_Type, Private_Dependents (Etype (Typ)));
1141                      end if;
1142                   end if;
1143
1144                   Set_Etype (Desig_Type, Typ);
1145                end if;
1146             end;
1147          end if;
1148
1149          if not (Is_Type (Etype (Desig_Type))) then
1150             Error_Msg_N
1151               ("expect type in function specification",
1152                Result_Definition (T_Def));
1153          end if;
1154
1155       else
1156          Set_Etype (Desig_Type, Standard_Void_Type);
1157       end if;
1158
1159       if Present (Formals) then
1160          Push_Scope (Desig_Type);
1161
1162          --  A bit of a kludge here. These kludges will be removed when Itypes
1163          --  have proper parent pointers to their declarations???
1164
1165          --  Kludge 1) Link defining_identifier of formals. Required by
1166          --  First_Formal to provide its functionality.
1167
1168          declare
1169             F : Node_Id;
1170
1171          begin
1172             F := First (Formals);
1173             while Present (F) loop
1174                if No (Parent (Defining_Identifier (F))) then
1175                   Set_Parent (Defining_Identifier (F), F);
1176                end if;
1177
1178                Next (F);
1179             end loop;
1180          end;
1181
1182          Process_Formals (Formals, Parent (T_Def));
1183
1184          --  Kludge 2) End_Scope requires that the parent pointer be set to
1185          --  something reasonable, but Itypes don't have parent pointers. So
1186          --  we set it and then unset it ???
1187
1188          Set_Parent (Desig_Type, T_Name);
1189          End_Scope;
1190          Set_Parent (Desig_Type, Empty);
1191       end if;
1192
1193       --  Check for premature usage of the type being defined
1194
1195       Check_For_Premature_Usage (T_Def);
1196
1197       --  The return type and/or any parameter type may be incomplete. Mark
1198       --  the subprogram_type as depending on the incomplete type, so that
1199       --  it can be updated when the full type declaration is seen. This
1200       --  only applies to incomplete types declared in some enclosing scope,
1201       --  not to limited views from other packages.
1202
1203       if Present (Formals) then
1204          Formal := First_Formal (Desig_Type);
1205          while Present (Formal) loop
1206             if Ekind (Formal) /= E_In_Parameter
1207               and then Nkind (T_Def) = N_Access_Function_Definition
1208             then
1209                Error_Msg_N ("functions can only have IN parameters", Formal);
1210             end if;
1211
1212             if Ekind (Etype (Formal)) = E_Incomplete_Type
1213               and then In_Open_Scopes (Scope (Etype (Formal)))
1214             then
1215                Append_Elmt (Desig_Type, Private_Dependents (Etype (Formal)));
1216                Set_Has_Delayed_Freeze (Desig_Type);
1217             end if;
1218
1219             Next_Formal (Formal);
1220          end loop;
1221       end if;
1222
1223       --  If the return type is incomplete, this is legal as long as the
1224       --  type is declared in the current scope and will be completed in
1225       --  it (rather than being part of limited view).
1226
1227       if Ekind (Etype (Desig_Type)) = E_Incomplete_Type
1228         and then not Has_Delayed_Freeze (Desig_Type)
1229         and then In_Open_Scopes (Scope (Etype (Desig_Type)))
1230       then
1231          Append_Elmt (Desig_Type, Private_Dependents (Etype (Desig_Type)));
1232          Set_Has_Delayed_Freeze (Desig_Type);
1233       end if;
1234
1235       Check_Delayed_Subprogram (Desig_Type);
1236
1237       if Protected_Present (T_Def) then
1238          Set_Ekind (T_Name, E_Access_Protected_Subprogram_Type);
1239          Set_Convention (Desig_Type, Convention_Protected);
1240       else
1241          Set_Ekind (T_Name, E_Access_Subprogram_Type);
1242       end if;
1243
1244       Set_Can_Use_Internal_Rep (T_Name, not Always_Compatible_Rep_On_Target);
1245
1246       Set_Etype                    (T_Name, T_Name);
1247       Init_Size_Align              (T_Name);
1248       Set_Directly_Designated_Type (T_Name, Desig_Type);
1249
1250       --  Ada 2005 (AI-231): Propagate the null-excluding attribute
1251
1252       Set_Can_Never_Be_Null (T_Name, Null_Exclusion_Present (T_Def));
1253
1254       Check_Restriction (No_Access_Subprograms, T_Def);
1255    end Access_Subprogram_Declaration;
1256
1257    ----------------------------
1258    -- Access_Type_Declaration --
1259    ----------------------------
1260
1261    procedure Access_Type_Declaration (T : Entity_Id; Def : Node_Id) is
1262       S : constant Node_Id := Subtype_Indication (Def);
1263       P : constant Node_Id := Parent (Def);
1264    begin
1265       --  Check for permissible use of incomplete type
1266
1267       if Nkind (S) /= N_Subtype_Indication then
1268          Analyze (S);
1269
1270          if Ekind (Root_Type (Entity (S))) = E_Incomplete_Type then
1271             Set_Directly_Designated_Type (T, Entity (S));
1272          else
1273             Set_Directly_Designated_Type (T,
1274               Process_Subtype (S, P, T, 'P'));
1275          end if;
1276
1277       else
1278          Set_Directly_Designated_Type (T,
1279            Process_Subtype (S, P, T, 'P'));
1280       end if;
1281
1282       if All_Present (Def) or Constant_Present (Def) then
1283          Set_Ekind (T, E_General_Access_Type);
1284       else
1285          Set_Ekind (T, E_Access_Type);
1286       end if;
1287
1288       if Base_Type (Designated_Type (T)) = T then
1289          Error_Msg_N ("access type cannot designate itself", S);
1290
1291       --  In Ada 2005, the type may have a limited view through some unit
1292       --  in its own context, allowing the following circularity that cannot
1293       --  be detected earlier
1294
1295       elsif Is_Class_Wide_Type (Designated_Type (T))
1296         and then Etype (Designated_Type (T)) = T
1297       then
1298          Error_Msg_N
1299            ("access type cannot designate its own classwide type", S);
1300
1301          --  Clean up indication of tagged status to prevent cascaded errors
1302
1303          Set_Is_Tagged_Type (T, False);
1304       end if;
1305
1306       Set_Etype (T, T);
1307
1308       --  If the type has appeared already in a with_type clause, it is
1309       --  frozen and the pointer size is already set. Else, initialize.
1310
1311       if not From_With_Type (T) then
1312          Init_Size_Align (T);
1313       end if;
1314
1315       --  Note that Has_Task is always false, since the access type itself
1316       --  is not a task type. See Einfo for more description on this point.
1317       --  Exactly the same consideration applies to Has_Controlled_Component.
1318
1319       Set_Has_Task (T, False);
1320       Set_Has_Controlled_Component (T, False);
1321
1322       --  Initialize Associated_Final_Chain explicitly to Empty, to avoid
1323       --  problems where an incomplete view of this entity has been previously
1324       --  established by a limited with and an overlaid version of this field
1325       --  (Stored_Constraint) was initialized for the incomplete view.
1326
1327       Set_Associated_Final_Chain (T, Empty);
1328
1329       --  Ada 2005 (AI-231): Propagate the null-excluding and access-constant
1330       --  attributes
1331
1332       Set_Can_Never_Be_Null  (T, Null_Exclusion_Present (Def));
1333       Set_Is_Access_Constant (T, Constant_Present (Def));
1334    end Access_Type_Declaration;
1335
1336    ----------------------------------
1337    -- Add_Interface_Tag_Components --
1338    ----------------------------------
1339
1340    procedure Add_Interface_Tag_Components (N : Node_Id; Typ : Entity_Id) is
1341       Loc      : constant Source_Ptr := Sloc (N);
1342       L        : List_Id;
1343       Last_Tag : Node_Id;
1344
1345       procedure Add_Tag (Iface : Entity_Id);
1346       --  Add tag for one of the progenitor interfaces
1347
1348       -------------
1349       -- Add_Tag --
1350       -------------
1351
1352       procedure Add_Tag (Iface : Entity_Id) is
1353          Decl   : Node_Id;
1354          Def    : Node_Id;
1355          Tag    : Entity_Id;
1356          Offset : Entity_Id;
1357
1358       begin
1359          pragma Assert (Is_Tagged_Type (Iface)
1360            and then Is_Interface (Iface));
1361
1362          Def :=
1363            Make_Component_Definition (Loc,
1364              Aliased_Present    => True,
1365              Subtype_Indication =>
1366                New_Occurrence_Of (RTE (RE_Interface_Tag), Loc));
1367
1368          Tag := Make_Temporary (Loc, 'V');
1369
1370          Decl :=
1371            Make_Component_Declaration (Loc,
1372              Defining_Identifier  => Tag,
1373              Component_Definition => Def);
1374
1375          Analyze_Component_Declaration (Decl);
1376
1377          Set_Analyzed (Decl);
1378          Set_Ekind               (Tag, E_Component);
1379          Set_Is_Tag              (Tag);
1380          Set_Is_Aliased          (Tag);
1381          Set_Related_Type        (Tag, Iface);
1382          Init_Component_Location (Tag);
1383
1384          pragma Assert (Is_Frozen (Iface));
1385
1386          Set_DT_Entry_Count    (Tag,
1387            DT_Entry_Count (First_Entity (Iface)));
1388
1389          if No (Last_Tag) then
1390             Prepend (Decl, L);
1391          else
1392             Insert_After (Last_Tag, Decl);
1393          end if;
1394
1395          Last_Tag := Decl;
1396
1397          --  If the ancestor has discriminants we need to give special support
1398          --  to store the offset_to_top value of the secondary dispatch tables.
1399          --  For this purpose we add a supplementary component just after the
1400          --  field that contains the tag associated with each secondary DT.
1401
1402          if Typ /= Etype (Typ)
1403            and then Has_Discriminants (Etype (Typ))
1404          then
1405             Def :=
1406               Make_Component_Definition (Loc,
1407                 Subtype_Indication =>
1408                   New_Occurrence_Of (RTE (RE_Storage_Offset), Loc));
1409
1410             Offset := Make_Temporary (Loc, 'V');
1411
1412             Decl :=
1413               Make_Component_Declaration (Loc,
1414                 Defining_Identifier  => Offset,
1415                 Component_Definition => Def);
1416
1417             Analyze_Component_Declaration (Decl);
1418
1419             Set_Analyzed (Decl);
1420             Set_Ekind               (Offset, E_Component);
1421             Set_Is_Aliased          (Offset);
1422             Set_Related_Type        (Offset, Iface);
1423             Init_Component_Location (Offset);
1424             Insert_After (Last_Tag, Decl);
1425             Last_Tag := Decl;
1426          end if;
1427       end Add_Tag;
1428
1429       --  Local variables
1430
1431       Elmt : Elmt_Id;
1432       Ext  : Node_Id;
1433       Comp : Node_Id;
1434
1435    --  Start of processing for Add_Interface_Tag_Components
1436
1437    begin
1438       if not RTE_Available (RE_Interface_Tag) then
1439          Error_Msg
1440            ("(Ada 2005) interface types not supported by this run-time!",
1441             Sloc (N));
1442          return;
1443       end if;
1444
1445       if Ekind (Typ) /= E_Record_Type
1446         or else (Is_Concurrent_Record_Type (Typ)
1447                   and then Is_Empty_List (Abstract_Interface_List (Typ)))
1448         or else (not Is_Concurrent_Record_Type (Typ)
1449                   and then No (Interfaces (Typ))
1450                   and then Is_Empty_Elmt_List (Interfaces (Typ)))
1451       then
1452          return;
1453       end if;
1454
1455       --  Find the current last tag
1456
1457       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1458          Ext := Record_Extension_Part (Type_Definition (N));
1459       else
1460          pragma Assert (Nkind (Type_Definition (N)) = N_Record_Definition);
1461          Ext := Type_Definition (N);
1462       end if;
1463
1464       Last_Tag := Empty;
1465
1466       if not (Present (Component_List (Ext))) then
1467          Set_Null_Present (Ext, False);
1468          L := New_List;
1469          Set_Component_List (Ext,
1470            Make_Component_List (Loc,
1471              Component_Items => L,
1472              Null_Present => False));
1473       else
1474          if Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
1475             L := Component_Items
1476                    (Component_List
1477                      (Record_Extension_Part
1478                        (Type_Definition (N))));
1479          else
1480             L := Component_Items
1481                    (Component_List
1482                      (Type_Definition (N)));
1483          end if;
1484
1485          --  Find the last tag component
1486
1487          Comp := First (L);
1488          while Present (Comp) loop
1489             if Nkind (Comp) = N_Component_Declaration
1490               and then Is_Tag (Defining_Identifier (Comp))
1491             then
1492                Last_Tag := Comp;
1493             end if;
1494
1495             Next (Comp);
1496          end loop;
1497       end if;
1498
1499       --  At this point L references the list of components and Last_Tag
1500       --  references the current last tag (if any). Now we add the tag
1501       --  corresponding with all the interfaces that are not implemented
1502       --  by the parent.
1503
1504       if Present (Interfaces (Typ)) then
1505          Elmt := First_Elmt (Interfaces (Typ));
1506          while Present (Elmt) loop
1507             Add_Tag (Node (Elmt));
1508             Next_Elmt (Elmt);
1509          end loop;
1510       end if;
1511    end Add_Interface_Tag_Components;
1512
1513    -------------------------------------
1514    -- Add_Internal_Interface_Entities --
1515    -------------------------------------
1516
1517    procedure Add_Internal_Interface_Entities (Tagged_Type : Entity_Id) is
1518       Elmt          : Elmt_Id;
1519       Iface         : Entity_Id;
1520       Iface_Elmt    : Elmt_Id;
1521       Iface_Prim    : Entity_Id;
1522       Ifaces_List   : Elist_Id;
1523       New_Subp      : Entity_Id := Empty;
1524       Prim          : Entity_Id;
1525       Restore_Scope : Boolean := False;
1526
1527    begin
1528       pragma Assert (Ada_Version >= Ada_2005
1529         and then Is_Record_Type (Tagged_Type)
1530         and then Is_Tagged_Type (Tagged_Type)
1531         and then Has_Interfaces (Tagged_Type)
1532         and then not Is_Interface (Tagged_Type));
1533
1534       --  Ensure that the internal entities are added to the scope of the type
1535
1536       if Scope (Tagged_Type) /= Current_Scope then
1537          Push_Scope (Scope (Tagged_Type));
1538          Restore_Scope := True;
1539       end if;
1540
1541       Collect_Interfaces (Tagged_Type, Ifaces_List);
1542
1543       Iface_Elmt := First_Elmt (Ifaces_List);
1544       while Present (Iface_Elmt) loop
1545          Iface := Node (Iface_Elmt);
1546
1547          --  Originally we excluded here from this processing interfaces that
1548          --  are parents of Tagged_Type because their primitives are located
1549          --  in the primary dispatch table (and hence no auxiliary internal
1550          --  entities are required to handle secondary dispatch tables in such
1551          --  case). However, these auxiliary entities are also required to
1552          --  handle derivations of interfaces in formals of generics (see
1553          --  Derive_Subprograms).
1554
1555          Elmt := First_Elmt (Primitive_Operations (Iface));
1556          while Present (Elmt) loop
1557             Iface_Prim := Node (Elmt);
1558
1559             if not Is_Predefined_Dispatching_Operation (Iface_Prim) then
1560                Prim :=
1561                  Find_Primitive_Covering_Interface
1562                    (Tagged_Type => Tagged_Type,
1563                     Iface_Prim  => Iface_Prim);
1564
1565                pragma Assert (Present (Prim));
1566
1567                Derive_Subprogram
1568                  (New_Subp     => New_Subp,
1569                   Parent_Subp  => Iface_Prim,
1570                   Derived_Type => Tagged_Type,
1571                   Parent_Type  => Iface);
1572
1573                --  Ada 2005 (AI-251): Decorate internal entity Iface_Subp
1574                --  associated with interface types. These entities are
1575                --  only registered in the list of primitives of its
1576                --  corresponding tagged type because they are only used
1577                --  to fill the contents of the secondary dispatch tables.
1578                --  Therefore they are removed from the homonym chains.
1579
1580                Set_Is_Hidden (New_Subp);
1581                Set_Is_Internal (New_Subp);
1582                Set_Alias (New_Subp, Prim);
1583                Set_Is_Abstract_Subprogram
1584                  (New_Subp, Is_Abstract_Subprogram (Prim));
1585                Set_Interface_Alias (New_Subp, Iface_Prim);
1586
1587                --  Internal entities associated with interface types are
1588                --  only registered in the list of primitives of the tagged
1589                --  type. They are only used to fill the contents of the
1590                --  secondary dispatch tables. Therefore they are not needed
1591                --  in the homonym chains.
1592
1593                Remove_Homonym (New_Subp);
1594
1595                --  Hidden entities associated with interfaces must have set
1596                --  the Has_Delay_Freeze attribute to ensure that, in case of
1597                --  locally defined tagged types (or compiling with static
1598                --  dispatch tables generation disabled) the corresponding
1599                --  entry of the secondary dispatch table is filled when
1600                --  such an entity is frozen.
1601
1602                Set_Has_Delayed_Freeze (New_Subp);
1603             end if;
1604
1605             Next_Elmt (Elmt);
1606          end loop;
1607
1608          Next_Elmt (Iface_Elmt);
1609       end loop;
1610
1611       if Restore_Scope then
1612          Pop_Scope;
1613       end if;
1614    end Add_Internal_Interface_Entities;
1615
1616    -----------------------------------
1617    -- Analyze_Component_Declaration --
1618    -----------------------------------
1619
1620    procedure Analyze_Component_Declaration (N : Node_Id) is
1621       Id : constant Entity_Id := Defining_Identifier (N);
1622       E  : constant Node_Id   := Expression (N);
1623       T  : Entity_Id;
1624       P  : Entity_Id;
1625
1626       function Contains_POC (Constr : Node_Id) return Boolean;
1627       --  Determines whether a constraint uses the discriminant of a record
1628       --  type thus becoming a per-object constraint (POC).
1629
1630       function Is_Known_Limited (Typ : Entity_Id) return Boolean;
1631       --  Typ is the type of the current component, check whether this type is
1632       --  a limited type. Used to validate declaration against that of
1633       --  enclosing record.
1634
1635       ------------------
1636       -- Contains_POC --
1637       ------------------
1638
1639       function Contains_POC (Constr : Node_Id) return Boolean is
1640       begin
1641          --  Prevent cascaded errors
1642
1643          if Error_Posted (Constr) then
1644             return False;
1645          end if;
1646
1647          case Nkind (Constr) is
1648             when N_Attribute_Reference =>
1649                return
1650                  Attribute_Name (Constr) = Name_Access
1651                    and then Prefix (Constr) = Scope (Entity (Prefix (Constr)));
1652
1653             when N_Discriminant_Association =>
1654                return Denotes_Discriminant (Expression (Constr));
1655
1656             when N_Identifier =>
1657                return Denotes_Discriminant (Constr);
1658
1659             when N_Index_Or_Discriminant_Constraint =>
1660                declare
1661                   IDC : Node_Id;
1662
1663                begin
1664                   IDC := First (Constraints (Constr));
1665                   while Present (IDC) loop
1666
1667                      --  One per-object constraint is sufficient
1668
1669                      if Contains_POC (IDC) then
1670                         return True;
1671                      end if;
1672
1673                      Next (IDC);
1674                   end loop;
1675
1676                   return False;
1677                end;
1678
1679             when N_Range =>
1680                return Denotes_Discriminant (Low_Bound (Constr))
1681                         or else
1682                       Denotes_Discriminant (High_Bound (Constr));
1683
1684             when N_Range_Constraint =>
1685                return Denotes_Discriminant (Range_Expression (Constr));
1686
1687             when others =>
1688                return False;
1689
1690          end case;
1691       end Contains_POC;
1692
1693       ----------------------
1694       -- Is_Known_Limited --
1695       ----------------------
1696
1697       function Is_Known_Limited (Typ : Entity_Id) return Boolean is
1698          P : constant Entity_Id := Etype (Typ);
1699          R : constant Entity_Id := Root_Type (Typ);
1700
1701       begin
1702          if Is_Limited_Record (Typ) then
1703             return True;
1704
1705          --  If the root type is limited (and not a limited interface)
1706          --  so is the current type
1707
1708          elsif Is_Limited_Record (R)
1709            and then
1710              (not Is_Interface (R)
1711                or else not Is_Limited_Interface (R))
1712          then
1713             return True;
1714
1715          --  Else the type may have a limited interface progenitor, but a
1716          --  limited record parent.
1717
1718          elsif R /= P
1719            and then Is_Limited_Record (P)
1720          then
1721             return True;
1722
1723          else
1724             return False;
1725          end if;
1726       end Is_Known_Limited;
1727
1728    --  Start of processing for Analyze_Component_Declaration
1729
1730    begin
1731       Generate_Definition (Id);
1732       Enter_Name (Id);
1733
1734       if Present (Subtype_Indication (Component_Definition (N))) then
1735          T := Find_Type_Of_Object
1736                 (Subtype_Indication (Component_Definition (N)), N);
1737
1738       --  Ada 2005 (AI-230): Access Definition case
1739
1740       else
1741          pragma Assert (Present
1742                           (Access_Definition (Component_Definition (N))));
1743
1744          T := Access_Definition
1745                 (Related_Nod => N,
1746                  N => Access_Definition (Component_Definition (N)));
1747          Set_Is_Local_Anonymous_Access (T);
1748
1749          --  Ada 2005 (AI-254)
1750
1751          if Present (Access_To_Subprogram_Definition
1752                       (Access_Definition (Component_Definition (N))))
1753            and then Protected_Present (Access_To_Subprogram_Definition
1754                                         (Access_Definition
1755                                           (Component_Definition (N))))
1756          then
1757             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
1758          end if;
1759       end if;
1760
1761       --  If the subtype is a constrained subtype of the enclosing record,
1762       --  (which must have a partial view) the back-end does not properly
1763       --  handle the recursion. Rewrite the component declaration with an
1764       --  explicit subtype indication, which is acceptable to Gigi. We can copy
1765       --  the tree directly because side effects have already been removed from
1766       --  discriminant constraints.
1767
1768       if Ekind (T) = E_Access_Subtype
1769         and then Is_Entity_Name (Subtype_Indication (Component_Definition (N)))
1770         and then Comes_From_Source (T)
1771         and then Nkind (Parent (T)) = N_Subtype_Declaration
1772         and then Etype (Directly_Designated_Type (T)) = Current_Scope
1773       then
1774          Rewrite
1775            (Subtype_Indication (Component_Definition (N)),
1776              New_Copy_Tree (Subtype_Indication (Parent (T))));
1777          T := Find_Type_Of_Object
1778                  (Subtype_Indication (Component_Definition (N)), N);
1779       end if;
1780
1781       --  If the component declaration includes a default expression, then we
1782       --  check that the component is not of a limited type (RM 3.7(5)),
1783       --  and do the special preanalysis of the expression (see section on
1784       --  "Handling of Default and Per-Object Expressions" in the spec of
1785       --  package Sem).
1786
1787       if Present (E) then
1788          Preanalyze_Spec_Expression (E, T);
1789          Check_Initialization (T, E);
1790
1791          if Ada_Version >= Ada_2005
1792            and then Ekind (T) = E_Anonymous_Access_Type
1793            and then Etype (E) /= Any_Type
1794          then
1795             --  Check RM 3.9.2(9): "if the expected type for an expression is
1796             --  an anonymous access-to-specific tagged type, then the object
1797             --  designated by the expression shall not be dynamically tagged
1798             --  unless it is a controlling operand in a call on a dispatching
1799             --  operation"
1800
1801             if Is_Tagged_Type (Directly_Designated_Type (T))
1802               and then
1803                 Ekind (Directly_Designated_Type (T)) /= E_Class_Wide_Type
1804               and then
1805                 Ekind (Directly_Designated_Type (Etype (E))) =
1806                   E_Class_Wide_Type
1807             then
1808                Error_Msg_N
1809                  ("access to specific tagged type required (RM 3.9.2(9))", E);
1810             end if;
1811
1812             --  (Ada 2005: AI-230): Accessibility check for anonymous
1813             --  components
1814
1815             if Type_Access_Level (Etype (E)) > Type_Access_Level (T) then
1816                Error_Msg_N
1817                  ("expression has deeper access level than component " &
1818                   "(RM 3.10.2 (12.2))", E);
1819             end if;
1820
1821             --  The initialization expression is a reference to an access
1822             --  discriminant. The type of the discriminant is always deeper
1823             --  than any access type.
1824
1825             if Ekind (Etype (E)) = E_Anonymous_Access_Type
1826               and then Is_Entity_Name (E)
1827               and then Ekind (Entity (E)) = E_In_Parameter
1828               and then Present (Discriminal_Link (Entity (E)))
1829             then
1830                Error_Msg_N
1831                  ("discriminant has deeper accessibility level than target",
1832                   E);
1833             end if;
1834          end if;
1835       end if;
1836
1837       --  The parent type may be a private view with unknown discriminants,
1838       --  and thus unconstrained. Regular components must be constrained.
1839
1840       if Is_Indefinite_Subtype (T) and then Chars (Id) /= Name_uParent then
1841          if Is_Class_Wide_Type (T) then
1842             Error_Msg_N
1843                ("class-wide subtype with unknown discriminants" &
1844                  " in component declaration",
1845                  Subtype_Indication (Component_Definition (N)));
1846          else
1847             Error_Msg_N
1848               ("unconstrained subtype in component declaration",
1849                Subtype_Indication (Component_Definition (N)));
1850          end if;
1851
1852       --  Components cannot be abstract, except for the special case of
1853       --  the _Parent field (case of extending an abstract tagged type)
1854
1855       elsif Is_Abstract_Type (T) and then Chars (Id) /= Name_uParent then
1856          Error_Msg_N ("type of a component cannot be abstract", N);
1857       end if;
1858
1859       Set_Etype (Id, T);
1860       Set_Is_Aliased (Id, Aliased_Present (Component_Definition (N)));
1861
1862       --  The component declaration may have a per-object constraint, set
1863       --  the appropriate flag in the defining identifier of the subtype.
1864
1865       if Present (Subtype_Indication (Component_Definition (N))) then
1866          declare
1867             Sindic : constant Node_Id :=
1868                        Subtype_Indication (Component_Definition (N));
1869          begin
1870             if Nkind (Sindic) = N_Subtype_Indication
1871               and then Present (Constraint (Sindic))
1872               and then Contains_POC (Constraint (Sindic))
1873             then
1874                Set_Has_Per_Object_Constraint (Id);
1875             end if;
1876          end;
1877       end if;
1878
1879       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
1880       --  out some static checks.
1881
1882       if Ada_Version >= Ada_2005
1883         and then Can_Never_Be_Null (T)
1884       then
1885          Null_Exclusion_Static_Checks (N);
1886       end if;
1887
1888       --  If this component is private (or depends on a private type), flag the
1889       --  record type to indicate that some operations are not available.
1890
1891       P := Private_Component (T);
1892
1893       if Present (P) then
1894
1895          --  Check for circular definitions
1896
1897          if P = Any_Type then
1898             Set_Etype (Id, Any_Type);
1899
1900          --  There is a gap in the visibility of operations only if the
1901          --  component type is not defined in the scope of the record type.
1902
1903          elsif Scope (P) = Scope (Current_Scope) then
1904             null;
1905
1906          elsif Is_Limited_Type (P) then
1907             Set_Is_Limited_Composite (Current_Scope);
1908
1909          else
1910             Set_Is_Private_Composite (Current_Scope);
1911          end if;
1912       end if;
1913
1914       if P /= Any_Type
1915         and then Is_Limited_Type (T)
1916         and then Chars (Id) /= Name_uParent
1917         and then Is_Tagged_Type (Current_Scope)
1918       then
1919          if Is_Derived_Type (Current_Scope)
1920            and then not Is_Known_Limited (Current_Scope)
1921          then
1922             Error_Msg_N
1923               ("extension of nonlimited type cannot have limited components",
1924                N);
1925
1926             if Is_Interface (Root_Type (Current_Scope)) then
1927                Error_Msg_N
1928                  ("\limitedness is not inherited from limited interface", N);
1929                Error_Msg_N ("\add LIMITED to type indication", N);
1930             end if;
1931
1932             Explain_Limited_Type (T, N);
1933             Set_Etype (Id, Any_Type);
1934             Set_Is_Limited_Composite (Current_Scope, False);
1935
1936          elsif not Is_Derived_Type (Current_Scope)
1937            and then not Is_Limited_Record (Current_Scope)
1938            and then not Is_Concurrent_Type (Current_Scope)
1939          then
1940             Error_Msg_N
1941               ("nonlimited tagged type cannot have limited components", N);
1942             Explain_Limited_Type (T, N);
1943             Set_Etype (Id, Any_Type);
1944             Set_Is_Limited_Composite (Current_Scope, False);
1945          end if;
1946       end if;
1947
1948       Set_Original_Record_Component (Id, Id);
1949       Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
1950    end Analyze_Component_Declaration;
1951
1952    --------------------------
1953    -- Analyze_Declarations --
1954    --------------------------
1955
1956    procedure Analyze_Declarations (L : List_Id) is
1957       D           : Node_Id;
1958       Freeze_From : Entity_Id := Empty;
1959       Next_Node   : Node_Id;
1960
1961       procedure Adjust_D;
1962       --  Adjust D not to include implicit label declarations, since these
1963       --  have strange Sloc values that result in elaboration check problems.
1964       --  (They have the sloc of the label as found in the source, and that
1965       --  is ahead of the current declarative part).
1966
1967       --------------
1968       -- Adjust_D --
1969       --------------
1970
1971       procedure Adjust_D is
1972       begin
1973          while Present (Prev (D))
1974            and then Nkind (D) = N_Implicit_Label_Declaration
1975          loop
1976             Prev (D);
1977          end loop;
1978       end Adjust_D;
1979
1980    --  Start of processing for Analyze_Declarations
1981
1982    begin
1983       D := First (L);
1984       while Present (D) loop
1985
1986          --  Complete analysis of declaration
1987
1988          Analyze (D);
1989          Next_Node := Next (D);
1990
1991          if No (Freeze_From) then
1992             Freeze_From := First_Entity (Current_Scope);
1993          end if;
1994
1995          --  At the end of a declarative part, freeze remaining entities
1996          --  declared in it. The end of the visible declarations of package
1997          --  specification is not the end of a declarative part if private
1998          --  declarations are present. The end of a package declaration is a
1999          --  freezing point only if it a library package. A task definition or
2000          --  protected type definition is not a freeze point either. Finally,
2001          --  we do not freeze entities in generic scopes, because there is no
2002          --  code generated for them and freeze nodes will be generated for
2003          --  the instance.
2004
2005          --  The end of a package instantiation is not a freeze point, but
2006          --  for now we make it one, because the generic body is inserted
2007          --  (currently) immediately after. Generic instantiations will not
2008          --  be a freeze point once delayed freezing of bodies is implemented.
2009          --  (This is needed in any case for early instantiations ???).
2010
2011          if No (Next_Node) then
2012             if Nkind_In (Parent (L), N_Component_List,
2013                                      N_Task_Definition,
2014                                      N_Protected_Definition)
2015             then
2016                null;
2017
2018             elsif Nkind (Parent (L)) /= N_Package_Specification then
2019                if Nkind (Parent (L)) = N_Package_Body then
2020                   Freeze_From := First_Entity (Current_Scope);
2021                end if;
2022
2023                Adjust_D;
2024                Freeze_All (Freeze_From, D);
2025                Freeze_From := Last_Entity (Current_Scope);
2026
2027             elsif Scope (Current_Scope) /= Standard_Standard
2028               and then not Is_Child_Unit (Current_Scope)
2029               and then No (Generic_Parent (Parent (L)))
2030             then
2031                null;
2032
2033             elsif L /= Visible_Declarations (Parent (L))
2034                or else No (Private_Declarations (Parent (L)))
2035                or else Is_Empty_List (Private_Declarations (Parent (L)))
2036             then
2037                Adjust_D;
2038                Freeze_All (Freeze_From, D);
2039                Freeze_From := Last_Entity (Current_Scope);
2040             end if;
2041
2042          --  If next node is a body then freeze all types before the body.
2043          --  An exception occurs for some expander-generated bodies. If these
2044          --  are generated at places where in general language rules would not
2045          --  allow a freeze point, then we assume that the expander has
2046          --  explicitly checked that all required types are properly frozen,
2047          --  and we do not cause general freezing here. This special circuit
2048          --  is used when the encountered body is marked as having already
2049          --  been analyzed.
2050
2051          --  In all other cases (bodies that come from source, and expander
2052          --  generated bodies that have not been analyzed yet), freeze all
2053          --  types now. Note that in the latter case, the expander must take
2054          --  care to attach the bodies at a proper place in the tree so as to
2055          --  not cause unwanted freezing at that point.
2056
2057          elsif not Analyzed (Next_Node)
2058            and then (Nkind_In (Next_Node, N_Subprogram_Body,
2059                                           N_Entry_Body,
2060                                           N_Package_Body,
2061                                           N_Protected_Body,
2062                                           N_Task_Body)
2063                        or else
2064                      Nkind (Next_Node) in N_Body_Stub)
2065          then
2066             Adjust_D;
2067             Freeze_All (Freeze_From, D);
2068             Freeze_From := Last_Entity (Current_Scope);
2069          end if;
2070
2071          D := Next_Node;
2072       end loop;
2073
2074       --  One more thing to do, we need to scan the declarations to check
2075       --  for any precondition/postcondition pragmas (Pre/Post aspects have
2076       --  by this stage been converted into corresponding pragmas). It is
2077       --  at this point that we analyze the expressions in such pragmas,
2078       --  to implement the delayed visibility requirement.
2079
2080       declare
2081          Decl : Node_Id;
2082          Spec : Node_Id;
2083          Sent : Entity_Id;
2084          Prag : Node_Id;
2085
2086       begin
2087          Decl := First (L);
2088          while Present (Decl) loop
2089             if Nkind (Original_Node (Decl)) = N_Subprogram_Declaration then
2090                Spec := Specification (Original_Node (Decl));
2091                Sent := Defining_Unit_Name (Spec);
2092                Prag := Spec_PPC_List (Sent);
2093                while Present (Prag) loop
2094                   Analyze_PPC_In_Decl_Part (Prag, Sent);
2095                   Prag := Next_Pragma (Prag);
2096                end loop;
2097             end if;
2098
2099             Next (Decl);
2100          end loop;
2101       end;
2102    end Analyze_Declarations;
2103
2104    -----------------------------------
2105    -- Analyze_Full_Type_Declaration --
2106    -----------------------------------
2107
2108    procedure Analyze_Full_Type_Declaration (N : Node_Id) is
2109       Def    : constant Node_Id   := Type_Definition (N);
2110       Def_Id : constant Entity_Id := Defining_Identifier (N);
2111       T      : Entity_Id;
2112       Prev   : Entity_Id;
2113
2114       Is_Remote : constant Boolean :=
2115                     (Is_Remote_Types (Current_Scope)
2116                        or else Is_Remote_Call_Interface (Current_Scope))
2117                     and then not (In_Private_Part (Current_Scope)
2118                                     or else In_Package_Body (Current_Scope));
2119
2120       procedure Check_Ops_From_Incomplete_Type;
2121       --  If there is a tagged incomplete partial view of the type, transfer
2122       --  its operations to the full view, and indicate that the type of the
2123       --  controlling parameter (s) is this full view.
2124
2125       ------------------------------------
2126       -- Check_Ops_From_Incomplete_Type --
2127       ------------------------------------
2128
2129       procedure Check_Ops_From_Incomplete_Type is
2130          Elmt   : Elmt_Id;
2131          Formal : Entity_Id;
2132          Op     : Entity_Id;
2133
2134       begin
2135          if Prev /= T
2136            and then Ekind (Prev) = E_Incomplete_Type
2137            and then Is_Tagged_Type (Prev)
2138            and then Is_Tagged_Type (T)
2139          then
2140             Elmt := First_Elmt (Primitive_Operations (Prev));
2141             while Present (Elmt) loop
2142                Op := Node (Elmt);
2143                Prepend_Elmt (Op, Primitive_Operations (T));
2144
2145                Formal := First_Formal (Op);
2146                while Present (Formal) loop
2147                   if Etype (Formal) = Prev then
2148                      Set_Etype (Formal, T);
2149                   end if;
2150
2151                   Next_Formal (Formal);
2152                end loop;
2153
2154                if Etype (Op) = Prev then
2155                   Set_Etype (Op, T);
2156                end if;
2157
2158                Next_Elmt (Elmt);
2159             end loop;
2160          end if;
2161       end Check_Ops_From_Incomplete_Type;
2162
2163    --  Start of processing for Analyze_Full_Type_Declaration
2164
2165    begin
2166       Prev := Find_Type_Name (N);
2167
2168       --  The full view, if present, now points to the current type
2169
2170       --  Ada 2005 (AI-50217): If the type was previously decorated when
2171       --  imported through a LIMITED WITH clause, it appears as incomplete
2172       --  but has no full view.
2173
2174       --  If the incomplete view is tagged, a class_wide type has been
2175       --  created already. Use it for the full view as well, to prevent
2176       --  multiple incompatible class-wide types that may be  created for
2177       --  self-referential anonymous access components.
2178
2179       if Ekind (Prev) = E_Incomplete_Type
2180         and then Present (Full_View (Prev))
2181       then
2182          T := Full_View (Prev);
2183
2184          if Is_Tagged_Type (Prev)
2185            and then Present (Class_Wide_Type (Prev))
2186          then
2187             Set_Ekind (T, Ekind (Prev));         --  will be reset later
2188             Set_Class_Wide_Type (T, Class_Wide_Type (Prev));
2189             Set_Etype (Class_Wide_Type (T), T);
2190          end if;
2191
2192       else
2193          T := Prev;
2194       end if;
2195
2196       Set_Is_Pure (T, Is_Pure (Current_Scope));
2197
2198       --  We set the flag Is_First_Subtype here. It is needed to set the
2199       --  corresponding flag for the Implicit class-wide-type created
2200       --  during tagged types processing.
2201
2202       Set_Is_First_Subtype (T, True);
2203
2204       --  Only composite types other than array types are allowed to have
2205       --  discriminants.
2206
2207       case Nkind (Def) is
2208
2209          --  For derived types, the rule will be checked once we've figured
2210          --  out the parent type.
2211
2212          when N_Derived_Type_Definition =>
2213             null;
2214
2215          --  For record types, discriminants are allowed
2216
2217          when N_Record_Definition =>
2218             null;
2219
2220          when others =>
2221             if Present (Discriminant_Specifications (N)) then
2222                Error_Msg_N
2223                  ("elementary or array type cannot have discriminants",
2224                   Defining_Identifier
2225                   (First (Discriminant_Specifications (N))));
2226             end if;
2227       end case;
2228
2229       --  Elaborate the type definition according to kind, and generate
2230       --  subsidiary (implicit) subtypes where needed. We skip this if it was
2231       --  already done (this happens during the reanalysis that follows a call
2232       --  to the high level optimizer).
2233
2234       if not Analyzed (T) then
2235          Set_Analyzed (T);
2236
2237          case Nkind (Def) is
2238
2239             when N_Access_To_Subprogram_Definition =>
2240                Access_Subprogram_Declaration (T, Def);
2241
2242                --  If this is a remote access to subprogram, we must create the
2243                --  equivalent fat pointer type, and related subprograms.
2244
2245                if Is_Remote then
2246                   Process_Remote_AST_Declaration (N);
2247                end if;
2248
2249                --  Validate categorization rule against access type declaration
2250                --  usually a violation in Pure unit, Shared_Passive unit.
2251
2252                Validate_Access_Type_Declaration (T, N);
2253
2254             when N_Access_To_Object_Definition =>
2255                Access_Type_Declaration (T, Def);
2256
2257                --  Validate categorization rule against access type declaration
2258                --  usually a violation in Pure unit, Shared_Passive unit.
2259
2260                Validate_Access_Type_Declaration (T, N);
2261
2262                --  If we are in a Remote_Call_Interface package and define a
2263                --  RACW, then calling stubs and specific stream attributes
2264                --  must be added.
2265
2266                if Is_Remote
2267                  and then Is_Remote_Access_To_Class_Wide_Type (Def_Id)
2268                then
2269                   Add_RACW_Features (Def_Id);
2270                end if;
2271
2272                --  Set no strict aliasing flag if config pragma seen
2273
2274                if Opt.No_Strict_Aliasing then
2275                   Set_No_Strict_Aliasing (Base_Type (Def_Id));
2276                end if;
2277
2278             when N_Array_Type_Definition =>
2279                Array_Type_Declaration (T, Def);
2280
2281             when N_Derived_Type_Definition =>
2282                Derived_Type_Declaration (T, N, T /= Def_Id);
2283
2284             when N_Enumeration_Type_Definition =>
2285                Enumeration_Type_Declaration (T, Def);
2286
2287             when N_Floating_Point_Definition =>
2288                Floating_Point_Type_Declaration (T, Def);
2289
2290             when N_Decimal_Fixed_Point_Definition =>
2291                Decimal_Fixed_Point_Type_Declaration (T, Def);
2292
2293             when N_Ordinary_Fixed_Point_Definition =>
2294                Ordinary_Fixed_Point_Type_Declaration (T, Def);
2295
2296             when N_Signed_Integer_Type_Definition =>
2297                Signed_Integer_Type_Declaration (T, Def);
2298
2299             when N_Modular_Type_Definition =>
2300                Modular_Type_Declaration (T, Def);
2301
2302             when N_Record_Definition =>
2303                Record_Type_Declaration (T, N, Prev);
2304
2305             --  If declaration has a parse error, nothing to elaborate.
2306
2307             when N_Error =>
2308                null;
2309
2310             when others =>
2311                raise Program_Error;
2312
2313          end case;
2314       end if;
2315
2316       if Etype (T) = Any_Type then
2317          goto Leave;
2318       end if;
2319
2320       --  Some common processing for all types
2321
2322       Set_Depends_On_Private (T, Has_Private_Component (T));
2323       Check_Ops_From_Incomplete_Type;
2324
2325       --  Both the declared entity, and its anonymous base type if one
2326       --  was created, need freeze nodes allocated.
2327
2328       declare
2329          B : constant Entity_Id := Base_Type (T);
2330
2331       begin
2332          --  In the case where the base type differs from the first subtype, we
2333          --  pre-allocate a freeze node, and set the proper link to the first
2334          --  subtype. Freeze_Entity will use this preallocated freeze node when
2335          --  it freezes the entity.
2336
2337          --  This does not apply if the base type is a generic type, whose
2338          --  declaration is independent of the current derived definition.
2339
2340          if B /= T and then not Is_Generic_Type (B) then
2341             Ensure_Freeze_Node (B);
2342             Set_First_Subtype_Link (Freeze_Node (B), T);
2343          end if;
2344
2345          --  A type that is imported through a limited_with clause cannot
2346          --  generate any code, and thus need not be frozen. However, an access
2347          --  type with an imported designated type needs a finalization list,
2348          --  which may be referenced in some other package that has non-limited
2349          --  visibility on the designated type. Thus we must create the
2350          --  finalization list at the point the access type is frozen, to
2351          --  prevent unsatisfied references at link time.
2352
2353          if not From_With_Type (T) or else Is_Access_Type (T) then
2354             Set_Has_Delayed_Freeze (T);
2355          end if;
2356       end;
2357
2358       --  Case where T is the full declaration of some private type which has
2359       --  been swapped in Defining_Identifier (N).
2360
2361       if T /= Def_Id and then Is_Private_Type (Def_Id) then
2362          Process_Full_View (N, T, Def_Id);
2363
2364          --  Record the reference. The form of this is a little strange, since
2365          --  the full declaration has been swapped in. So the first parameter
2366          --  here represents the entity to which a reference is made which is
2367          --  the "real" entity, i.e. the one swapped in, and the second
2368          --  parameter provides the reference location.
2369
2370          --  Also, we want to kill Has_Pragma_Unreferenced temporarily here
2371          --  since we don't want a complaint about the full type being an
2372          --  unwanted reference to the private type
2373
2374          declare
2375             B : constant Boolean := Has_Pragma_Unreferenced (T);
2376          begin
2377             Set_Has_Pragma_Unreferenced (T, False);
2378             Generate_Reference (T, T, 'c');
2379             Set_Has_Pragma_Unreferenced (T, B);
2380          end;
2381
2382          Set_Completion_Referenced (Def_Id);
2383
2384       --  For completion of incomplete type, process incomplete dependents
2385       --  and always mark the full type as referenced (it is the incomplete
2386       --  type that we get for any real reference).
2387
2388       elsif Ekind (Prev) = E_Incomplete_Type then
2389          Process_Incomplete_Dependents (N, T, Prev);
2390          Generate_Reference (Prev, Def_Id, 'c');
2391          Set_Completion_Referenced (Def_Id);
2392
2393       --  If not private type or incomplete type completion, this is a real
2394       --  definition of a new entity, so record it.
2395
2396       else
2397          Generate_Definition (Def_Id);
2398       end if;
2399
2400       if Chars (Scope (Def_Id)) = Name_System
2401         and then Chars (Def_Id) = Name_Address
2402         and then Is_Predefined_File_Name (Unit_File_Name (Get_Source_Unit (N)))
2403       then
2404          Set_Is_Descendent_Of_Address (Def_Id);
2405          Set_Is_Descendent_Of_Address (Base_Type (Def_Id));
2406          Set_Is_Descendent_Of_Address (Prev);
2407       end if;
2408
2409       Set_Optimize_Alignment_Flags (Def_Id);
2410       Check_Eliminated (Def_Id);
2411
2412       <<Leave>>
2413          Analyze_Aspect_Specifications (N, Def_Id, Aspect_Specifications (N));
2414    end Analyze_Full_Type_Declaration;
2415
2416    ----------------------------------
2417    -- Analyze_Incomplete_Type_Decl --
2418    ----------------------------------
2419
2420    procedure Analyze_Incomplete_Type_Decl (N : Node_Id) is
2421       F : constant Boolean := Is_Pure (Current_Scope);
2422       T : Entity_Id;
2423
2424    begin
2425       Generate_Definition (Defining_Identifier (N));
2426
2427       --  Process an incomplete declaration. The identifier must not have been
2428       --  declared already in the scope. However, an incomplete declaration may
2429       --  appear in the private part of a package, for a private type that has
2430       --  already been declared.
2431
2432       --  In this case, the discriminants (if any) must match
2433
2434       T := Find_Type_Name (N);
2435
2436       Set_Ekind (T, E_Incomplete_Type);
2437       Init_Size_Align (T);
2438       Set_Is_First_Subtype (T, True);
2439       Set_Etype (T, T);
2440
2441       --  Ada 2005 (AI-326): Minimum decoration to give support to tagged
2442       --  incomplete types.
2443
2444       if Tagged_Present (N) then
2445          Set_Is_Tagged_Type (T);
2446          Make_Class_Wide_Type (T);
2447          Set_Direct_Primitive_Operations (T, New_Elmt_List);
2448       end if;
2449
2450       Push_Scope (T);
2451
2452       Set_Stored_Constraint (T, No_Elist);
2453
2454       if Present (Discriminant_Specifications (N)) then
2455          Process_Discriminants (N);
2456       end if;
2457
2458       End_Scope;
2459
2460       --  If the type has discriminants, non-trivial subtypes may be
2461       --  declared before the full view of the type. The full views of those
2462       --  subtypes will be built after the full view of the type.
2463
2464       Set_Private_Dependents (T, New_Elmt_List);
2465       Set_Is_Pure (T, F);
2466    end Analyze_Incomplete_Type_Decl;
2467
2468    -----------------------------------
2469    -- Analyze_Interface_Declaration --
2470    -----------------------------------
2471
2472    procedure Analyze_Interface_Declaration (T : Entity_Id; Def : Node_Id) is
2473       CW : constant Entity_Id := Class_Wide_Type (T);
2474
2475    begin
2476       Set_Is_Tagged_Type (T);
2477
2478       Set_Is_Limited_Record (T, Limited_Present (Def)
2479                                   or else Task_Present (Def)
2480                                   or else Protected_Present (Def)
2481                                   or else Synchronized_Present (Def));
2482
2483       --  Type is abstract if full declaration carries keyword, or if previous
2484       --  partial view did.
2485
2486       Set_Is_Abstract_Type (T);
2487       Set_Is_Interface (T);
2488
2489       --  Type is a limited interface if it includes the keyword limited, task,
2490       --  protected, or synchronized.
2491
2492       Set_Is_Limited_Interface
2493         (T, Limited_Present (Def)
2494               or else Protected_Present (Def)
2495               or else Synchronized_Present (Def)
2496               or else Task_Present (Def));
2497
2498       Set_Interfaces (T, New_Elmt_List);
2499       Set_Direct_Primitive_Operations (T, New_Elmt_List);
2500
2501       --  Complete the decoration of the class-wide entity if it was already
2502       --  built (i.e. during the creation of the limited view)
2503
2504       if Present (CW) then
2505          Set_Is_Interface (CW);
2506          Set_Is_Limited_Interface      (CW, Is_Limited_Interface (T));
2507       end if;
2508
2509       --  Check runtime support for synchronized interfaces
2510
2511       if VM_Target = No_VM
2512         and then (Is_Task_Interface (T)
2513                     or else Is_Protected_Interface (T)
2514                     or else Is_Synchronized_Interface (T))
2515         and then not RTE_Available (RE_Select_Specific_Data)
2516       then
2517          Error_Msg_CRT ("synchronized interfaces", T);
2518       end if;
2519    end Analyze_Interface_Declaration;
2520
2521    -----------------------------
2522    -- Analyze_Itype_Reference --
2523    -----------------------------
2524
2525    --  Nothing to do. This node is placed in the tree only for the benefit of
2526    --  back end processing, and has no effect on the semantic processing.
2527
2528    procedure Analyze_Itype_Reference (N : Node_Id) is
2529    begin
2530       pragma Assert (Is_Itype (Itype (N)));
2531       null;
2532    end Analyze_Itype_Reference;
2533
2534    --------------------------------
2535    -- Analyze_Number_Declaration --
2536    --------------------------------
2537
2538    procedure Analyze_Number_Declaration (N : Node_Id) is
2539       Id    : constant Entity_Id := Defining_Identifier (N);
2540       E     : constant Node_Id   := Expression (N);
2541       T     : Entity_Id;
2542       Index : Interp_Index;
2543       It    : Interp;
2544
2545    begin
2546       Generate_Definition (Id);
2547       Enter_Name (Id);
2548
2549       --  This is an optimization of a common case of an integer literal
2550
2551       if Nkind (E) = N_Integer_Literal then
2552          Set_Is_Static_Expression (E, True);
2553          Set_Etype                (E, Universal_Integer);
2554
2555          Set_Etype     (Id, Universal_Integer);
2556          Set_Ekind     (Id, E_Named_Integer);
2557          Set_Is_Frozen (Id, True);
2558          return;
2559       end if;
2560
2561       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2562
2563       --  Process expression, replacing error by integer zero, to avoid
2564       --  cascaded errors or aborts further along in the processing
2565
2566       --  Replace Error by integer zero, which seems least likely to
2567       --  cause cascaded errors.
2568
2569       if E = Error then
2570          Rewrite (E, Make_Integer_Literal (Sloc (E), Uint_0));
2571          Set_Error_Posted (E);
2572       end if;
2573
2574       Analyze (E);
2575
2576       --  Verify that the expression is static and numeric. If
2577       --  the expression is overloaded, we apply the preference
2578       --  rule that favors root numeric types.
2579
2580       if not Is_Overloaded (E) then
2581          T := Etype (E);
2582
2583       else
2584          T := Any_Type;
2585
2586          Get_First_Interp (E, Index, It);
2587          while Present (It.Typ) loop
2588             if (Is_Integer_Type (It.Typ)
2589                  or else Is_Real_Type (It.Typ))
2590               and then (Scope (Base_Type (It.Typ))) = Standard_Standard
2591             then
2592                if T = Any_Type then
2593                   T := It.Typ;
2594
2595                elsif It.Typ = Universal_Real
2596                  or else It.Typ = Universal_Integer
2597                then
2598                   --  Choose universal interpretation over any other
2599
2600                   T := It.Typ;
2601                   exit;
2602                end if;
2603             end if;
2604
2605             Get_Next_Interp (Index, It);
2606          end loop;
2607       end if;
2608
2609       if Is_Integer_Type (T)  then
2610          Resolve (E, T);
2611          Set_Etype (Id, Universal_Integer);
2612          Set_Ekind (Id, E_Named_Integer);
2613
2614       elsif Is_Real_Type (T) then
2615
2616          --  Because the real value is converted to universal_real, this is a
2617          --  legal context for a universal fixed expression.
2618
2619          if T = Universal_Fixed then
2620             declare
2621                Loc  : constant Source_Ptr := Sloc (N);
2622                Conv : constant Node_Id := Make_Type_Conversion (Loc,
2623                         Subtype_Mark =>
2624                           New_Occurrence_Of (Universal_Real, Loc),
2625                         Expression => Relocate_Node (E));
2626
2627             begin
2628                Rewrite (E, Conv);
2629                Analyze (E);
2630             end;
2631
2632          elsif T = Any_Fixed then
2633             Error_Msg_N ("illegal context for mixed mode operation", E);
2634
2635             --  Expression is of the form : universal_fixed * integer. Try to
2636             --  resolve as universal_real.
2637
2638             T := Universal_Real;
2639             Set_Etype (E, T);
2640          end if;
2641
2642          Resolve (E, T);
2643          Set_Etype (Id, Universal_Real);
2644          Set_Ekind (Id, E_Named_Real);
2645
2646       else
2647          Wrong_Type (E, Any_Numeric);
2648          Resolve (E, T);
2649
2650          Set_Etype               (Id, T);
2651          Set_Ekind               (Id, E_Constant);
2652          Set_Never_Set_In_Source (Id, True);
2653          Set_Is_True_Constant    (Id, True);
2654          return;
2655       end if;
2656
2657       if Nkind_In (E, N_Integer_Literal, N_Real_Literal) then
2658          Set_Etype (E, Etype (Id));
2659       end if;
2660
2661       if not Is_OK_Static_Expression (E) then
2662          Flag_Non_Static_Expr
2663            ("non-static expression used in number declaration!", E);
2664          Rewrite (E, Make_Integer_Literal (Sloc (N), 1));
2665          Set_Etype (E, Any_Type);
2666       end if;
2667    end Analyze_Number_Declaration;
2668
2669    --------------------------------
2670    -- Analyze_Object_Declaration --
2671    --------------------------------
2672
2673    procedure Analyze_Object_Declaration (N : Node_Id) is
2674       Loc   : constant Source_Ptr := Sloc (N);
2675       Id    : constant Entity_Id  := Defining_Identifier (N);
2676       T     : Entity_Id;
2677       Act_T : Entity_Id;
2678
2679       E : Node_Id := Expression (N);
2680       --  E is set to Expression (N) throughout this routine. When
2681       --  Expression (N) is modified, E is changed accordingly.
2682
2683       Prev_Entity : Entity_Id := Empty;
2684
2685       function Count_Tasks (T : Entity_Id) return Uint;
2686       --  This function is called when a non-generic library level object of a
2687       --  task type is declared. Its function is to count the static number of
2688       --  tasks declared within the type (it is only called if Has_Tasks is set
2689       --  for T). As a side effect, if an array of tasks with non-static bounds
2690       --  or a variant record type is encountered, Check_Restrictions is called
2691       --  indicating the count is unknown.
2692
2693       -----------------
2694       -- Count_Tasks --
2695       -----------------
2696
2697       function Count_Tasks (T : Entity_Id) return Uint is
2698          C : Entity_Id;
2699          X : Node_Id;
2700          V : Uint;
2701
2702       begin
2703          if Is_Task_Type (T) then
2704             return Uint_1;
2705
2706          elsif Is_Record_Type (T) then
2707             if Has_Discriminants (T) then
2708                Check_Restriction (Max_Tasks, N);
2709                return Uint_0;
2710
2711             else
2712                V := Uint_0;
2713                C := First_Component (T);
2714                while Present (C) loop
2715                   V := V + Count_Tasks (Etype (C));
2716                   Next_Component (C);
2717                end loop;
2718
2719                return V;
2720             end if;
2721
2722          elsif Is_Array_Type (T) then
2723             X := First_Index (T);
2724             V := Count_Tasks (Component_Type (T));
2725             while Present (X) loop
2726                C := Etype (X);
2727
2728                if not Is_Static_Subtype (C) then
2729                   Check_Restriction (Max_Tasks, N);
2730                   return Uint_0;
2731                else
2732                   V := V * (UI_Max (Uint_0,
2733                                     Expr_Value (Type_High_Bound (C)) -
2734                                     Expr_Value (Type_Low_Bound (C)) + Uint_1));
2735                end if;
2736
2737                Next_Index (X);
2738             end loop;
2739
2740             return V;
2741
2742          else
2743             return Uint_0;
2744          end if;
2745       end Count_Tasks;
2746
2747    --  Start of processing for Analyze_Object_Declaration
2748
2749    begin
2750       --  There are three kinds of implicit types generated by an
2751       --  object declaration:
2752
2753       --   1. Those for generated by the original Object Definition
2754
2755       --   2. Those generated by the Expression
2756
2757       --   3. Those used to constrained the Object Definition with the
2758       --       expression constraints when it is unconstrained
2759
2760       --  They must be generated in this order to avoid order of elaboration
2761       --  issues. Thus the first step (after entering the name) is to analyze
2762       --  the object definition.
2763
2764       if Constant_Present (N) then
2765          Prev_Entity := Current_Entity_In_Scope (Id);
2766
2767          if Present (Prev_Entity)
2768            and then
2769              --  If the homograph is an implicit subprogram, it is overridden
2770              --  by the current declaration.
2771
2772              ((Is_Overloadable (Prev_Entity)
2773                 and then Is_Inherited_Operation (Prev_Entity))
2774
2775                --  The current object is a discriminal generated for an entry
2776                --  family index. Even though the index is a constant, in this
2777                --  particular context there is no true constant redeclaration.
2778                --  Enter_Name will handle the visibility.
2779
2780                or else
2781                 (Is_Discriminal (Id)
2782                    and then Ekind (Discriminal_Link (Id)) =
2783                               E_Entry_Index_Parameter)
2784
2785                --  The current object is the renaming for a generic declared
2786                --  within the instance.
2787
2788                or else
2789                 (Ekind (Prev_Entity) = E_Package
2790                   and then Nkind (Parent (Prev_Entity)) =
2791                                          N_Package_Renaming_Declaration
2792                   and then not Comes_From_Source (Prev_Entity)
2793                   and then Is_Generic_Instance (Renamed_Entity (Prev_Entity))))
2794          then
2795             Prev_Entity := Empty;
2796          end if;
2797       end if;
2798
2799       if Present (Prev_Entity) then
2800          Constant_Redeclaration (Id, N, T);
2801
2802          Generate_Reference (Prev_Entity, Id, 'c');
2803          Set_Completion_Referenced (Id);
2804
2805          if Error_Posted (N) then
2806
2807             --  Type mismatch or illegal redeclaration, Do not analyze
2808             --  expression to avoid cascaded errors.
2809
2810             T := Find_Type_Of_Object (Object_Definition (N), N);
2811             Set_Etype (Id, T);
2812             Set_Ekind (Id, E_Variable);
2813             goto Leave;
2814          end if;
2815
2816       --  In the normal case, enter identifier at the start to catch premature
2817       --  usage in the initialization expression.
2818
2819       else
2820          Generate_Definition (Id);
2821          Enter_Name (Id);
2822
2823          Mark_Coextensions (N, Object_Definition (N));
2824
2825          T := Find_Type_Of_Object (Object_Definition (N), N);
2826
2827          if Nkind (Object_Definition (N)) = N_Access_Definition
2828            and then Present
2829              (Access_To_Subprogram_Definition (Object_Definition (N)))
2830            and then Protected_Present
2831              (Access_To_Subprogram_Definition (Object_Definition (N)))
2832          then
2833             T := Replace_Anonymous_Access_To_Protected_Subprogram (N);
2834          end if;
2835
2836          if Error_Posted (Id) then
2837             Set_Etype (Id, T);
2838             Set_Ekind (Id, E_Variable);
2839             goto Leave;
2840          end if;
2841       end if;
2842
2843       --  Ada 2005 (AI-231): Propagate the null-excluding attribute and carry
2844       --  out some static checks
2845
2846       if Ada_Version >= Ada_2005
2847         and then Can_Never_Be_Null (T)
2848       then
2849          --  In case of aggregates we must also take care of the correct
2850          --  initialization of nested aggregates bug this is done at the
2851          --  point of the analysis of the aggregate (see sem_aggr.adb)
2852
2853          if Present (Expression (N))
2854            and then Nkind (Expression (N)) = N_Aggregate
2855          then
2856             null;
2857
2858          else
2859             declare
2860                Save_Typ : constant Entity_Id := Etype (Id);
2861             begin
2862                Set_Etype (Id, T); --  Temp. decoration for static checks
2863                Null_Exclusion_Static_Checks (N);
2864                Set_Etype (Id, Save_Typ);
2865             end;
2866          end if;
2867       end if;
2868
2869       Set_Is_Pure (Id, Is_Pure (Current_Scope));
2870
2871       --  If deferred constant, make sure context is appropriate. We detect
2872       --  a deferred constant as a constant declaration with no expression.
2873       --  A deferred constant can appear in a package body if its completion
2874       --  is by means of an interface pragma.
2875
2876       if Constant_Present (N)
2877         and then No (E)
2878       then
2879          --  A deferred constant may appear in the declarative part of the
2880          --  following constructs:
2881
2882          --     blocks
2883          --     entry bodies
2884          --     extended return statements
2885          --     package specs
2886          --     package bodies
2887          --     subprogram bodies
2888          --     task bodies
2889
2890          --  When declared inside a package spec, a deferred constant must be
2891          --  completed by a full constant declaration or pragma Import. In all
2892          --  other cases, the only proper completion is pragma Import. Extended
2893          --  return statements are flagged as invalid contexts because they do
2894          --  not have a declarative part and so cannot accommodate the pragma.
2895
2896          if Ekind (Current_Scope) = E_Return_Statement then
2897             Error_Msg_N
2898               ("invalid context for deferred constant declaration (RM 7.4)",
2899                N);
2900             Error_Msg_N
2901               ("\declaration requires an initialization expression",
2902                 N);
2903             Set_Constant_Present (N, False);
2904
2905          --  In Ada 83, deferred constant must be of private type
2906
2907          elsif not Is_Private_Type (T) then
2908             if Ada_Version = Ada_83 and then Comes_From_Source (N) then
2909                Error_Msg_N
2910                  ("(Ada 83) deferred constant must be private type", N);
2911             end if;
2912          end if;
2913
2914       --  If not a deferred constant, then object declaration freezes its type
2915
2916       else
2917          Check_Fully_Declared (T, N);
2918          Freeze_Before (N, T);
2919       end if;
2920
2921       --  If the object was created by a constrained array definition, then
2922       --  set the link in both the anonymous base type and anonymous subtype
2923       --  that are built to represent the array type to point to the object.
2924
2925       if Nkind (Object_Definition (Declaration_Node (Id))) =
2926                         N_Constrained_Array_Definition
2927       then
2928          Set_Related_Array_Object (T, Id);
2929          Set_Related_Array_Object (Base_Type (T), Id);
2930       end if;
2931
2932       --  Special checks for protected objects not at library level
2933
2934       if Is_Protected_Type (T)
2935         and then not Is_Library_Level_Entity (Id)
2936       then
2937          Check_Restriction (No_Local_Protected_Objects, Id);
2938
2939          --  Protected objects with interrupt handlers must be at library level
2940
2941          --  Ada 2005: this test is not needed (and the corresponding clause
2942          --  in the RM is removed) because accessibility checks are sufficient
2943          --  to make handlers not at the library level illegal.
2944
2945          if Has_Interrupt_Handler (T)
2946            and then Ada_Version < Ada_2005
2947          then
2948             Error_Msg_N
2949               ("interrupt object can only be declared at library level", Id);
2950          end if;
2951       end if;
2952
2953       --  The actual subtype of the object is the nominal subtype, unless
2954       --  the nominal one is unconstrained and obtained from the expression.
2955
2956       Act_T := T;
2957
2958       --  Process initialization expression if present and not in error
2959
2960       if Present (E) and then E /= Error then
2961
2962          --  Generate an error in case of CPP class-wide object initialization.
2963          --  Required because otherwise the expansion of the class-wide
2964          --  assignment would try to use 'size to initialize the object
2965          --  (primitive that is not available in CPP tagged types).
2966
2967          if Is_Class_Wide_Type (Act_T)
2968            and then
2969              (Is_CPP_Class (Root_Type (Etype (Act_T)))
2970                or else
2971                  (Present (Full_View (Root_Type (Etype (Act_T))))
2972                     and then
2973                       Is_CPP_Class (Full_View (Root_Type (Etype (Act_T))))))
2974          then
2975             Error_Msg_N
2976               ("predefined assignment not available for 'C'P'P tagged types",
2977                E);
2978          end if;
2979
2980          Mark_Coextensions (N, E);
2981          Analyze (E);
2982
2983          --  In case of errors detected in the analysis of the expression,
2984          --  decorate it with the expected type to avoid cascaded errors
2985
2986          if No (Etype (E)) then
2987             Set_Etype (E, T);
2988          end if;
2989
2990          --  If an initialization expression is present, then we set the
2991          --  Is_True_Constant flag. It will be reset if this is a variable
2992          --  and it is indeed modified.
2993
2994          Set_Is_True_Constant (Id, True);
2995
2996          --  If we are analyzing a constant declaration, set its completion
2997          --  flag after analyzing and resolving the expression.
2998
2999          if Constant_Present (N) then
3000             Set_Has_Completion (Id);
3001          end if;
3002
3003          --  Set type and resolve (type may be overridden later on)
3004
3005          Set_Etype (Id, T);
3006          Resolve (E, T);
3007
3008          --  If E is null and has been replaced by an N_Raise_Constraint_Error
3009          --  node (which was marked already-analyzed), we need to set the type
3010          --  to something other than Any_Access in order to keep gigi happy.
3011
3012          if Etype (E) = Any_Access then
3013             Set_Etype (E, T);
3014          end if;
3015
3016          --  If the object is an access to variable, the initialization
3017          --  expression cannot be an access to constant.
3018
3019          if Is_Access_Type (T)
3020            and then not Is_Access_Constant (T)
3021            and then Is_Access_Type (Etype (E))
3022            and then Is_Access_Constant (Etype (E))
3023          then
3024             Error_Msg_N
3025               ("access to variable cannot be initialized "
3026                & "with an access-to-constant expression", E);
3027          end if;
3028
3029          if not Assignment_OK (N) then
3030             Check_Initialization (T, E);
3031          end if;
3032
3033          Check_Unset_Reference (E);
3034
3035          --  If this is a variable, then set current value. If this is a
3036          --  declared constant of a scalar type with a static expression,
3037          --  indicate that it is always valid.
3038
3039          if not Constant_Present (N) then
3040             if Compile_Time_Known_Value (E) then
3041                Set_Current_Value (Id, E);
3042             end if;
3043
3044          elsif Is_Scalar_Type (T)
3045            and then Is_OK_Static_Expression (E)
3046          then
3047             Set_Is_Known_Valid (Id);
3048          end if;
3049
3050          --  Deal with setting of null flags
3051
3052          if Is_Access_Type (T) then
3053             if Known_Non_Null (E) then
3054                Set_Is_Known_Non_Null (Id, True);
3055             elsif Known_Null (E)
3056               and then not Can_Never_Be_Null (Id)
3057             then
3058                Set_Is_Known_Null (Id, True);
3059             end if;
3060          end if;
3061
3062          --  Check incorrect use of dynamically tagged expressions.
3063
3064          if Is_Tagged_Type (T) then
3065             Check_Dynamically_Tagged_Expression
3066               (Expr        => E,
3067                Typ         => T,
3068                Related_Nod => N);
3069          end if;
3070
3071          Apply_Scalar_Range_Check (E, T);
3072          Apply_Static_Length_Check (E, T);
3073       end if;
3074
3075       --  If the No_Streams restriction is set, check that the type of the
3076       --  object is not, and does not contain, any subtype derived from
3077       --  Ada.Streams.Root_Stream_Type. Note that we guard the call to
3078       --  Has_Stream just for efficiency reasons. There is no point in
3079       --  spending time on a Has_Stream check if the restriction is not set.
3080
3081       if Restriction_Check_Required (No_Streams) then
3082          if Has_Stream (T) then
3083             Check_Restriction (No_Streams, N);
3084          end if;
3085       end if;
3086
3087       --  Case of unconstrained type
3088
3089       if Is_Indefinite_Subtype (T) then
3090
3091          --  Nothing to do in deferred constant case
3092
3093          if Constant_Present (N) and then No (E) then
3094             null;
3095
3096          --  Case of no initialization present
3097
3098          elsif No (E) then
3099             if No_Initialization (N) then
3100                null;
3101
3102             elsif Is_Class_Wide_Type (T) then
3103                Error_Msg_N
3104                  ("initialization required in class-wide declaration ", N);
3105
3106             else
3107                Error_Msg_N
3108                  ("unconstrained subtype not allowed (need initialization)",
3109                   Object_Definition (N));
3110
3111                if Is_Record_Type (T) and then Has_Discriminants (T) then
3112                   Error_Msg_N
3113                     ("\provide initial value or explicit discriminant values",
3114                      Object_Definition (N));
3115
3116                   Error_Msg_NE
3117                     ("\or give default discriminant values for type&",
3118                      Object_Definition (N), T);
3119
3120                elsif Is_Array_Type (T) then
3121                   Error_Msg_N
3122                     ("\provide initial value or explicit array bounds",
3123                      Object_Definition (N));
3124                end if;
3125             end if;
3126
3127          --  Case of initialization present but in error. Set initial
3128          --  expression as absent (but do not make above complaints)
3129
3130          elsif E = Error then
3131             Set_Expression (N, Empty);
3132             E := Empty;
3133
3134          --  Case of initialization present
3135
3136          else
3137             --  Not allowed in Ada 83
3138
3139             if not Constant_Present (N) then
3140                if Ada_Version = Ada_83
3141                  and then Comes_From_Source (Object_Definition (N))
3142                then
3143                   Error_Msg_N
3144                     ("(Ada 83) unconstrained variable not allowed",
3145                      Object_Definition (N));
3146                end if;
3147             end if;
3148
3149             --  Now we constrain the variable from the initializing expression
3150
3151             --  If the expression is an aggregate, it has been expanded into
3152             --  individual assignments. Retrieve the actual type from the
3153             --  expanded construct.
3154
3155             if Is_Array_Type (T)
3156               and then No_Initialization (N)
3157               and then Nkind (Original_Node (E)) = N_Aggregate
3158             then
3159                Act_T := Etype (E);
3160
3161             --  In case of class-wide interface object declarations we delay
3162             --  the generation of the equivalent record type declarations until
3163             --  its expansion because there are cases in they are not required.
3164
3165             elsif Is_Interface (T) then
3166                null;
3167
3168             else
3169                Expand_Subtype_From_Expr (N, T, Object_Definition (N), E);
3170                Act_T := Find_Type_Of_Object (Object_Definition (N), N);
3171             end if;
3172
3173             Set_Is_Constr_Subt_For_U_Nominal (Act_T);
3174
3175             if Aliased_Present (N) then
3176                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3177             end if;
3178
3179             Freeze_Before (N, Act_T);
3180             Freeze_Before (N, T);
3181          end if;
3182
3183       elsif Is_Array_Type (T)
3184         and then No_Initialization (N)
3185         and then Nkind (Original_Node (E)) = N_Aggregate
3186       then
3187          if not Is_Entity_Name (Object_Definition (N)) then
3188             Act_T := Etype (E);
3189             Check_Compile_Time_Size (Act_T);
3190
3191             if Aliased_Present (N) then
3192                Set_Is_Constr_Subt_For_UN_Aliased (Act_T);
3193             end if;
3194          end if;
3195
3196          --  When the given object definition and the aggregate are specified
3197          --  independently, and their lengths might differ do a length check.
3198          --  This cannot happen if the aggregate is of the form (others =>...)
3199
3200          if not Is_Constrained (T) then
3201             null;
3202
3203          elsif Nkind (E) = N_Raise_Constraint_Error then
3204
3205             --  Aggregate is statically illegal. Place back in declaration
3206
3207             Set_Expression (N, E);
3208             Set_No_Initialization (N, False);
3209
3210          elsif T = Etype (E) then
3211             null;
3212
3213          elsif Nkind (E) = N_Aggregate
3214            and then Present (Component_Associations (E))
3215            and then Present (Choices (First (Component_Associations (E))))
3216            and then Nkind (First
3217             (Choices (First (Component_Associations (E))))) = N_Others_Choice
3218          then
3219             null;
3220
3221          else
3222             Apply_Length_Check (E, T);
3223          end if;
3224
3225       --  If the type is limited unconstrained with defaulted discriminants and
3226       --  there is no expression, then the object is constrained by the
3227       --  defaults, so it is worthwhile building the corresponding subtype.
3228
3229       elsif (Is_Limited_Record (T) or else Is_Concurrent_Type (T))
3230         and then not Is_Constrained (T)
3231         and then Has_Discriminants (T)
3232       then
3233          if No (E) then
3234             Act_T := Build_Default_Subtype (T, N);
3235          else
3236             --  Ada 2005:  a limited object may be initialized by means of an
3237             --  aggregate. If the type has default discriminants it has an
3238             --  unconstrained nominal type, Its actual subtype will be obtained
3239             --  from the aggregate, and not from the default discriminants.
3240
3241             Act_T := Etype (E);
3242          end if;
3243
3244          Rewrite (Object_Definition (N), New_Occurrence_Of (Act_T, Loc));
3245
3246       elsif Present (Underlying_Type (T))
3247         and then not Is_Constrained (Underlying_Type (T))
3248         and then Has_Discriminants (Underlying_Type (T))
3249         and then Nkind (E) = N_Function_Call
3250         and then Constant_Present (N)
3251       then
3252          --  The back-end has problems with constants of a discriminated type
3253          --  with defaults, if the initial value is a function call. We
3254          --  generate an intermediate temporary for the result of the call.
3255          --  It is unclear why this should make it acceptable to gcc. ???
3256
3257          Remove_Side_Effects (E);
3258       end if;
3259
3260       --  Check No_Wide_Characters restriction
3261
3262       Check_Wide_Character_Restriction (T, Object_Definition (N));
3263
3264       --  Indicate this is not set in source. Certainly true for constants,
3265       --  and true for variables so far (will be reset for a variable if and
3266       --  when we encounter a modification in the source).
3267
3268       Set_Never_Set_In_Source (Id, True);
3269
3270       --  Now establish the proper kind and type of the object
3271
3272       if Constant_Present (N) then
3273          Set_Ekind            (Id, E_Constant);
3274          Set_Is_True_Constant (Id, True);
3275
3276       else
3277          Set_Ekind (Id, E_Variable);
3278
3279          --  A variable is set as shared passive if it appears in a shared
3280          --  passive package, and is at the outer level. This is not done
3281          --  for entities generated during expansion, because those are
3282          --  always manipulated locally.
3283
3284          if Is_Shared_Passive (Current_Scope)
3285            and then Is_Library_Level_Entity (Id)
3286            and then Comes_From_Source (Id)
3287          then
3288             Set_Is_Shared_Passive (Id);
3289             Check_Shared_Var (Id, T, N);
3290          end if;
3291
3292          --  Set Has_Initial_Value if initializing expression present. Note
3293          --  that if there is no initializing expression, we leave the state
3294          --  of this flag unchanged (usually it will be False, but notably in
3295          --  the case of exception choice variables, it will already be true).
3296
3297          if Present (E) then
3298             Set_Has_Initial_Value (Id, True);
3299          end if;
3300       end if;
3301
3302       --  Initialize alignment and size and capture alignment setting
3303
3304       Init_Alignment               (Id);
3305       Init_Esize                   (Id);
3306       Set_Optimize_Alignment_Flags (Id);
3307
3308       --  Deal with aliased case
3309
3310       if Aliased_Present (N) then
3311          Set_Is_Aliased (Id);
3312
3313          --  If the object is aliased and the type is unconstrained with
3314          --  defaulted discriminants and there is no expression, then the
3315          --  object is constrained by the defaults, so it is worthwhile
3316          --  building the corresponding subtype.
3317
3318          --  Ada 2005 (AI-363): If the aliased object is discriminated and
3319          --  unconstrained, then only establish an actual subtype if the
3320          --  nominal subtype is indefinite. In definite cases the object is
3321          --  unconstrained in Ada 2005.
3322
3323          if No (E)
3324            and then Is_Record_Type (T)
3325            and then not Is_Constrained (T)
3326            and then Has_Discriminants (T)
3327            and then (Ada_Version < Ada_2005 or else Is_Indefinite_Subtype (T))
3328          then
3329             Set_Actual_Subtype (Id, Build_Default_Subtype (T, N));
3330          end if;
3331       end if;
3332
3333       --  Now we can set the type of the object
3334
3335       Set_Etype (Id, Act_T);
3336
3337       --  Deal with controlled types
3338
3339       if Has_Controlled_Component (Etype (Id))
3340         or else Is_Controlled (Etype (Id))
3341       then
3342          if not Is_Library_Level_Entity (Id) then
3343             Check_Restriction (No_Nested_Finalization, N);
3344          else
3345             Validate_Controlled_Object (Id);
3346          end if;
3347
3348          --  Generate a warning when an initialization causes an obvious ABE
3349          --  violation. If the init expression is a simple aggregate there
3350          --  shouldn't be any initialize/adjust call generated. This will be
3351          --  true as soon as aggregates are built in place when possible.
3352
3353          --  ??? at the moment we do not generate warnings for temporaries
3354          --  created for those aggregates although Program_Error might be
3355          --  generated if compiled with -gnato.
3356
3357          if Is_Controlled (Etype (Id))
3358             and then Comes_From_Source (Id)
3359          then
3360             declare
3361                BT : constant Entity_Id := Base_Type (Etype (Id));
3362
3363                Implicit_Call : Entity_Id;
3364                pragma Warnings (Off, Implicit_Call);
3365                --  ??? what is this for (never referenced!)
3366
3367                function Is_Aggr (N : Node_Id) return Boolean;
3368                --  Check that N is an aggregate
3369
3370                -------------
3371                -- Is_Aggr --
3372                -------------
3373
3374                function Is_Aggr (N : Node_Id) return Boolean is
3375                begin
3376                   case Nkind (Original_Node (N)) is
3377                      when N_Aggregate | N_Extension_Aggregate =>
3378                         return True;
3379
3380                      when N_Qualified_Expression |
3381                           N_Type_Conversion      |
3382                           N_Unchecked_Type_Conversion =>
3383                         return Is_Aggr (Expression (Original_Node (N)));
3384
3385                      when others =>
3386                         return False;
3387                   end case;
3388                end Is_Aggr;
3389
3390             begin
3391                --  If no underlying type, we already are in an error situation.
3392                --  Do not try to add a warning since we do not have access to
3393                --  prim-op list.
3394
3395                if No (Underlying_Type (BT)) then
3396                   Implicit_Call := Empty;
3397
3398                --  A generic type does not have usable primitive operators.
3399                --  Initialization calls are built for instances.
3400
3401                elsif Is_Generic_Type (BT) then
3402                   Implicit_Call := Empty;
3403
3404                --  If the init expression is not an aggregate, an adjust call
3405                --  will be generated
3406
3407                elsif Present (E) and then not Is_Aggr (E) then
3408                   Implicit_Call := Find_Prim_Op (BT, Name_Adjust);
3409
3410                --  If no init expression and we are not in the deferred
3411                --  constant case, an Initialize call will be generated
3412
3413                elsif No (E) and then not Constant_Present (N) then
3414                   Implicit_Call := Find_Prim_Op (BT, Name_Initialize);
3415
3416                else
3417                   Implicit_Call := Empty;
3418                end if;
3419             end;
3420          end if;
3421       end if;
3422
3423       if Has_Task (Etype (Id)) then
3424          Check_Restriction (No_Tasking, N);
3425
3426          --  Deal with counting max tasks
3427
3428          --  Nothing to do if inside a generic
3429
3430          if Inside_A_Generic then
3431             null;
3432
3433          --  If library level entity, then count tasks
3434
3435          elsif Is_Library_Level_Entity (Id) then
3436             Check_Restriction (Max_Tasks, N, Count_Tasks (Etype (Id)));
3437
3438          --  If not library level entity, then indicate we don't know max
3439          --  tasks and also check task hierarchy restriction and blocking
3440          --  operation (since starting a task is definitely blocking!)
3441
3442          else
3443             Check_Restriction (Max_Tasks, N);
3444             Check_Restriction (No_Task_Hierarchy, N);
3445             Check_Potentially_Blocking_Operation (N);
3446          end if;
3447
3448          --  A rather specialized test. If we see two tasks being declared
3449          --  of the same type in the same object declaration, and the task
3450          --  has an entry with an address clause, we know that program error
3451          --  will be raised at run time since we can't have two tasks with
3452          --  entries at the same address.
3453
3454          if Is_Task_Type (Etype (Id)) and then More_Ids (N) then
3455             declare
3456                E : Entity_Id;
3457
3458             begin
3459                E := First_Entity (Etype (Id));
3460                while Present (E) loop
3461                   if Ekind (E) = E_Entry
3462                     and then Present (Get_Attribute_Definition_Clause
3463                                         (E, Attribute_Address))
3464                   then
3465                      Error_Msg_N
3466                        ("?more than one task with same entry address", N);
3467                      Error_Msg_N
3468                        ("\?Program_Error will be raised at run time", N);
3469                      Insert_Action (N,
3470                        Make_Raise_Program_Error (Loc,
3471                          Reason => PE_Duplicated_Entry_Address));
3472                      exit;
3473                   end if;
3474
3475                   Next_Entity (E);
3476                end loop;
3477             end;
3478          end if;
3479       end if;
3480
3481       --  Some simple constant-propagation: if the expression is a constant
3482       --  string initialized with a literal, share the literal. This avoids
3483       --  a run-time copy.
3484
3485       if Present (E)
3486         and then Is_Entity_Name (E)
3487         and then Ekind (Entity (E)) = E_Constant
3488         and then Base_Type (Etype (E)) = Standard_String
3489       then
3490          declare
3491             Val : constant Node_Id := Constant_Value (Entity (E));
3492          begin
3493             if Present (Val)
3494               and then Nkind (Val) = N_String_Literal
3495             then
3496                Rewrite (E, New_Copy (Val));
3497             end if;
3498          end;
3499       end if;
3500
3501       --  Another optimization: if the nominal subtype is unconstrained and
3502       --  the expression is a function call that returns an unconstrained
3503       --  type, rewrite the declaration as a renaming of the result of the
3504       --  call. The exceptions below are cases where the copy is expected,
3505       --  either by the back end (Aliased case) or by the semantics, as for
3506       --  initializing controlled types or copying tags for classwide types.
3507
3508       if Present (E)
3509         and then Nkind (E) = N_Explicit_Dereference
3510         and then Nkind (Original_Node (E)) = N_Function_Call
3511         and then not Is_Library_Level_Entity (Id)
3512         and then not Is_Constrained (Underlying_Type (T))
3513         and then not Is_Aliased (Id)
3514         and then not Is_Class_Wide_Type (T)
3515         and then not Is_Controlled (T)
3516         and then not Has_Controlled_Component (Base_Type (T))
3517         and then Expander_Active
3518       then
3519          Rewrite (N,
3520            Make_Object_Renaming_Declaration (Loc,
3521              Defining_Identifier => Id,
3522              Access_Definition   => Empty,
3523              Subtype_Mark        => New_Occurrence_Of
3524                                       (Base_Type (Etype (Id)), Loc),
3525              Name                => E));
3526
3527          Set_Renamed_Object (Id, E);
3528
3529          --  Force generation of debugging information for the constant and for
3530          --  the renamed function call.
3531
3532          Set_Debug_Info_Needed (Id);
3533          Set_Debug_Info_Needed (Entity (Prefix (E)));
3534       end if;
3535
3536       if Present (Prev_Entity)
3537         and then Is_Frozen (Prev_Entity)
3538         and then not Error_Posted (Id)
3539       then
3540          Error_Msg_N ("full constant declaration appears too late", N);
3541       end if;
3542
3543       Check_Eliminated (Id);
3544
3545       --  Deal with setting In_Private_Part flag if in private part
3546
3547       if Ekind (Scope (Id)) = E_Package
3548         and then In_Private_Part (Scope (Id))
3549       then
3550          Set_In_Private_Part (Id);
3551       end if;
3552
3553       --  Check for violation of No_Local_Timing_Events
3554
3555       if Is_RTE (Etype (Id), RE_Timing_Event)
3556         and then not Is_Library_Level_Entity (Id)
3557       then
3558          Check_Restriction (No_Local_Timing_Events, N);
3559       end if;
3560
3561       <<Leave>>
3562          Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
3563    end Analyze_Object_Declaration;
3564
3565    ---------------------------
3566    -- Analyze_Others_Choice --
3567    ---------------------------
3568
3569    --  Nothing to do for the others choice node itself, the semantic analysis
3570    --  of the others choice will occur as part of the processing of the parent
3571
3572    procedure Analyze_Others_Choice (N : Node_Id) is
3573       pragma Warnings (Off, N);
3574    begin
3575       null;
3576    end Analyze_Others_Choice;
3577
3578    -------------------------------------------
3579    -- Analyze_Private_Extension_Declaration --
3580    -------------------------------------------
3581
3582    procedure Analyze_Private_Extension_Declaration (N : Node_Id) is
3583       T           : constant Entity_Id := Defining_Identifier (N);
3584       Indic       : constant Node_Id   := Subtype_Indication (N);
3585       Parent_Type : Entity_Id;
3586       Parent_Base : Entity_Id;
3587
3588    begin
3589       --  Ada 2005 (AI-251): Decorate all names in list of ancestor interfaces
3590
3591       if Is_Non_Empty_List (Interface_List (N)) then
3592          declare
3593             Intf : Node_Id;
3594             T    : Entity_Id;
3595
3596          begin
3597             Intf := First (Interface_List (N));
3598             while Present (Intf) loop
3599                T := Find_Type_Of_Subtype_Indic (Intf);
3600
3601                Diagnose_Interface (Intf, T);
3602                Next (Intf);
3603             end loop;
3604          end;
3605       end if;
3606
3607       Generate_Definition (T);
3608       Enter_Name (T);
3609
3610       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
3611       Parent_Base := Base_Type (Parent_Type);
3612
3613       if Parent_Type = Any_Type
3614         or else Etype (Parent_Type) = Any_Type
3615       then
3616          Set_Ekind (T, Ekind (Parent_Type));
3617          Set_Etype (T, Any_Type);
3618          goto Leave;
3619
3620       elsif not Is_Tagged_Type (Parent_Type) then
3621          Error_Msg_N
3622            ("parent of type extension must be a tagged type ", Indic);
3623          goto Leave;
3624
3625       elsif Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
3626          Error_Msg_N ("premature derivation of incomplete type", Indic);
3627          goto Leave;
3628
3629       elsif Is_Concurrent_Type (Parent_Type) then
3630          Error_Msg_N
3631            ("parent type of a private extension cannot be "
3632             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
3633
3634          Set_Etype              (T, Any_Type);
3635          Set_Ekind              (T, E_Limited_Private_Type);
3636          Set_Private_Dependents (T, New_Elmt_List);
3637          Set_Error_Posted       (T);
3638          goto Leave;
3639       end if;
3640
3641       --  Perhaps the parent type should be changed to the class-wide type's
3642       --  specific type in this case to prevent cascading errors ???
3643
3644       if Is_Class_Wide_Type (Parent_Type) then
3645          Error_Msg_N
3646            ("parent of type extension must not be a class-wide type", Indic);
3647          goto Leave;
3648       end if;
3649
3650       if (not Is_Package_Or_Generic_Package (Current_Scope)
3651            and then Nkind (Parent (N)) /= N_Generic_Subprogram_Declaration)
3652         or else In_Private_Part (Current_Scope)
3653
3654       then
3655          Error_Msg_N ("invalid context for private extension", N);
3656       end if;
3657
3658       --  Set common attributes
3659
3660       Set_Is_Pure          (T, Is_Pure (Current_Scope));
3661       Set_Scope            (T, Current_Scope);
3662       Set_Ekind            (T, E_Record_Type_With_Private);
3663       Init_Size_Align      (T);
3664
3665       Set_Etype            (T,            Parent_Base);
3666       Set_Has_Task         (T, Has_Task  (Parent_Base));
3667
3668       Set_Convention       (T, Convention     (Parent_Type));
3669       Set_First_Rep_Item   (T, First_Rep_Item (Parent_Type));
3670       Set_Is_First_Subtype (T);
3671       Make_Class_Wide_Type (T);
3672
3673       if Unknown_Discriminants_Present (N) then
3674          Set_Discriminant_Constraint (T, No_Elist);
3675       end if;
3676
3677       Build_Derived_Record_Type (N, Parent_Type, T);
3678
3679       --  Ada 2005 (AI-443): Synchronized private extension or a rewritten
3680       --  synchronized formal derived type.
3681
3682       if Ada_Version >= Ada_2005
3683         and then Synchronized_Present (N)
3684       then
3685          Set_Is_Limited_Record (T);
3686
3687          --  Formal derived type case
3688
3689          if Is_Generic_Type (T) then
3690
3691             --  The parent must be a tagged limited type or a synchronized
3692             --  interface.
3693
3694             if (not Is_Tagged_Type (Parent_Type)
3695                   or else not Is_Limited_Type (Parent_Type))
3696               and then
3697                (not Is_Interface (Parent_Type)
3698                   or else not Is_Synchronized_Interface (Parent_Type))
3699             then
3700                Error_Msg_NE ("parent type of & must be tagged limited " &
3701                              "or synchronized", N, T);
3702             end if;
3703
3704             --  The progenitors (if any) must be limited or synchronized
3705             --  interfaces.
3706
3707             if Present (Interfaces (T)) then
3708                declare
3709                   Iface      : Entity_Id;
3710                   Iface_Elmt : Elmt_Id;
3711
3712                begin
3713                   Iface_Elmt := First_Elmt (Interfaces (T));
3714                   while Present (Iface_Elmt) loop
3715                      Iface := Node (Iface_Elmt);
3716
3717                      if not Is_Limited_Interface (Iface)
3718                        and then not Is_Synchronized_Interface (Iface)
3719                      then
3720                         Error_Msg_NE ("progenitor & must be limited " &
3721                                       "or synchronized", N, Iface);
3722                      end if;
3723
3724                      Next_Elmt (Iface_Elmt);
3725                   end loop;
3726                end;
3727             end if;
3728
3729          --  Regular derived extension, the parent must be a limited or
3730          --  synchronized interface.
3731
3732          else
3733             if not Is_Interface (Parent_Type)
3734               or else (not Is_Limited_Interface (Parent_Type)
3735                          and then
3736                        not Is_Synchronized_Interface (Parent_Type))
3737             then
3738                Error_Msg_NE
3739                  ("parent type of & must be limited interface", N, T);
3740             end if;
3741          end if;
3742
3743       --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
3744       --  extension with a synchronized parent must be explicitly declared
3745       --  synchronized, because the full view will be a synchronized type.
3746       --  This must be checked before the check for limited types below,
3747       --  to ensure that types declared limited are not allowed to extend
3748       --  synchronized interfaces.
3749
3750       elsif Is_Interface (Parent_Type)
3751         and then Is_Synchronized_Interface (Parent_Type)
3752         and then not Synchronized_Present (N)
3753       then
3754          Error_Msg_NE
3755            ("private extension of& must be explicitly synchronized",
3756              N, Parent_Type);
3757
3758       elsif Limited_Present (N) then
3759          Set_Is_Limited_Record (T);
3760
3761          if not Is_Limited_Type (Parent_Type)
3762            and then
3763              (not Is_Interface (Parent_Type)
3764                or else not Is_Limited_Interface (Parent_Type))
3765          then
3766             Error_Msg_NE ("parent type& of limited extension must be limited",
3767               N, Parent_Type);
3768          end if;
3769       end if;
3770
3771       <<Leave>>
3772          Analyze_Aspect_Specifications (N, T, Aspect_Specifications (N));
3773    end Analyze_Private_Extension_Declaration;
3774
3775    ---------------------------------
3776    -- Analyze_Subtype_Declaration --
3777    ---------------------------------
3778
3779    procedure Analyze_Subtype_Declaration
3780      (N    : Node_Id;
3781       Skip : Boolean := False)
3782    is
3783       Id       : constant Entity_Id := Defining_Identifier (N);
3784       T        : Entity_Id;
3785       R_Checks : Check_Result;
3786
3787    begin
3788       Generate_Definition (Id);
3789       Set_Is_Pure (Id, Is_Pure (Current_Scope));
3790       Init_Size_Align (Id);
3791
3792       --  The following guard condition on Enter_Name is to handle cases where
3793       --  the defining identifier has already been entered into the scope but
3794       --  the declaration as a whole needs to be analyzed.
3795
3796       --  This case in particular happens for derived enumeration types. The
3797       --  derived enumeration type is processed as an inserted enumeration type
3798       --  declaration followed by a rewritten subtype declaration. The defining
3799       --  identifier, however, is entered into the name scope very early in the
3800       --  processing of the original type declaration and therefore needs to be
3801       --  avoided here, when the created subtype declaration is analyzed. (See
3802       --  Build_Derived_Types)
3803
3804       --  This also happens when the full view of a private type is derived
3805       --  type with constraints. In this case the entity has been introduced
3806       --  in the private declaration.
3807
3808       if Skip
3809         or else (Present (Etype (Id))
3810                    and then (Is_Private_Type (Etype (Id))
3811                                or else Is_Task_Type (Etype (Id))
3812                                or else Is_Rewrite_Substitution (N)))
3813       then
3814          null;
3815
3816       else
3817          Enter_Name (Id);
3818       end if;
3819
3820       T := Process_Subtype (Subtype_Indication (N), N, Id, 'P');
3821
3822       --  Inherit common attributes
3823
3824       Set_Is_Generic_Type   (Id, Is_Generic_Type   (Base_Type (T)));
3825       Set_Is_Volatile       (Id, Is_Volatile       (T));
3826       Set_Treat_As_Volatile (Id, Treat_As_Volatile (T));
3827       Set_Is_Atomic         (Id, Is_Atomic         (T));
3828       Set_Is_Ada_2005_Only  (Id, Is_Ada_2005_Only  (T));
3829       Set_Is_Ada_2012_Only  (Id, Is_Ada_2012_Only  (T));
3830       Set_Convention        (Id, Convention        (T));
3831
3832       --  In the case where there is no constraint given in the subtype
3833       --  indication, Process_Subtype just returns the Subtype_Mark, so its
3834       --  semantic attributes must be established here.
3835
3836       if Nkind (Subtype_Indication (N)) /= N_Subtype_Indication then
3837          Set_Etype (Id, Base_Type (T));
3838
3839          case Ekind (T) is
3840             when Array_Kind =>
3841                Set_Ekind                       (Id, E_Array_Subtype);
3842                Copy_Array_Subtype_Attributes   (Id, T);
3843
3844             when Decimal_Fixed_Point_Kind =>
3845                Set_Ekind                (Id, E_Decimal_Fixed_Point_Subtype);
3846                Set_Digits_Value         (Id, Digits_Value       (T));
3847                Set_Delta_Value          (Id, Delta_Value        (T));
3848                Set_Scale_Value          (Id, Scale_Value        (T));
3849                Set_Small_Value          (Id, Small_Value        (T));
3850                Set_Scalar_Range         (Id, Scalar_Range       (T));
3851                Set_Machine_Radix_10     (Id, Machine_Radix_10   (T));
3852                Set_Is_Constrained       (Id, Is_Constrained     (T));
3853                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3854                Set_RM_Size              (Id, RM_Size            (T));
3855
3856             when Enumeration_Kind =>
3857                Set_Ekind                (Id, E_Enumeration_Subtype);
3858                Set_First_Literal        (Id, First_Literal (Base_Type (T)));
3859                Set_Scalar_Range         (Id, Scalar_Range       (T));
3860                Set_Is_Character_Type    (Id, Is_Character_Type  (T));
3861                Set_Is_Constrained       (Id, Is_Constrained     (T));
3862                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3863                Set_RM_Size              (Id, RM_Size            (T));
3864
3865             when Ordinary_Fixed_Point_Kind =>
3866                Set_Ekind                (Id, E_Ordinary_Fixed_Point_Subtype);
3867                Set_Scalar_Range         (Id, Scalar_Range       (T));
3868                Set_Small_Value          (Id, Small_Value        (T));
3869                Set_Delta_Value          (Id, Delta_Value        (T));
3870                Set_Is_Constrained       (Id, Is_Constrained     (T));
3871                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3872                Set_RM_Size              (Id, RM_Size            (T));
3873
3874             when Float_Kind =>
3875                Set_Ekind                (Id, E_Floating_Point_Subtype);
3876                Set_Scalar_Range         (Id, Scalar_Range       (T));
3877                Set_Digits_Value         (Id, Digits_Value       (T));
3878                Set_Is_Constrained       (Id, Is_Constrained     (T));
3879
3880             when Signed_Integer_Kind =>
3881                Set_Ekind                (Id, E_Signed_Integer_Subtype);
3882                Set_Scalar_Range         (Id, Scalar_Range       (T));
3883                Set_Is_Constrained       (Id, Is_Constrained     (T));
3884                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3885                Set_RM_Size              (Id, RM_Size            (T));
3886
3887             when Modular_Integer_Kind =>
3888                Set_Ekind                (Id, E_Modular_Integer_Subtype);
3889                Set_Scalar_Range         (Id, Scalar_Range       (T));
3890                Set_Is_Constrained       (Id, Is_Constrained     (T));
3891                Set_Is_Known_Valid       (Id, Is_Known_Valid     (T));
3892                Set_RM_Size              (Id, RM_Size            (T));
3893
3894             when Class_Wide_Kind =>
3895                Set_Ekind                (Id, E_Class_Wide_Subtype);
3896                Set_First_Entity         (Id, First_Entity       (T));
3897                Set_Last_Entity          (Id, Last_Entity        (T));
3898                Set_Class_Wide_Type      (Id, Class_Wide_Type    (T));
3899                Set_Cloned_Subtype       (Id, T);
3900                Set_Is_Tagged_Type       (Id, True);
3901                Set_Has_Unknown_Discriminants
3902                                         (Id, True);
3903
3904                if Ekind (T) = E_Class_Wide_Subtype then
3905                   Set_Equivalent_Type   (Id, Equivalent_Type    (T));
3906                end if;
3907
3908             when E_Record_Type | E_Record_Subtype =>
3909                Set_Ekind                (Id, E_Record_Subtype);
3910
3911                if Ekind (T) = E_Record_Subtype
3912                  and then Present (Cloned_Subtype (T))
3913                then
3914                   Set_Cloned_Subtype    (Id, Cloned_Subtype (T));
3915                else
3916                   Set_Cloned_Subtype    (Id, T);
3917                end if;
3918
3919                Set_First_Entity         (Id, First_Entity       (T));
3920                Set_Last_Entity          (Id, Last_Entity        (T));
3921                Set_Has_Discriminants    (Id, Has_Discriminants  (T));
3922                Set_Is_Constrained       (Id, Is_Constrained     (T));
3923                Set_Is_Limited_Record    (Id, Is_Limited_Record  (T));
3924                Set_Has_Unknown_Discriminants
3925                                         (Id, Has_Unknown_Discriminants (T));
3926
3927                if Has_Discriminants (T) then
3928                   Set_Discriminant_Constraint
3929                                         (Id, Discriminant_Constraint (T));
3930                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3931
3932                elsif Has_Unknown_Discriminants (Id) then
3933                   Set_Discriminant_Constraint (Id, No_Elist);
3934                end if;
3935
3936                if Is_Tagged_Type (T) then
3937                   Set_Is_Tagged_Type    (Id);
3938                   Set_Is_Abstract_Type  (Id, Is_Abstract_Type (T));
3939                   Set_Direct_Primitive_Operations
3940                                         (Id, Direct_Primitive_Operations (T));
3941                   Set_Class_Wide_Type   (Id, Class_Wide_Type (T));
3942
3943                   if Is_Interface (T) then
3944                      Set_Is_Interface (Id);
3945                      Set_Is_Limited_Interface (Id, Is_Limited_Interface (T));
3946                   end if;
3947                end if;
3948
3949             when Private_Kind =>
3950                Set_Ekind              (Id, Subtype_Kind (Ekind   (T)));
3951                Set_Has_Discriminants  (Id, Has_Discriminants     (T));
3952                Set_Is_Constrained     (Id, Is_Constrained        (T));
3953                Set_First_Entity       (Id, First_Entity          (T));
3954                Set_Last_Entity        (Id, Last_Entity           (T));
3955                Set_Private_Dependents (Id, New_Elmt_List);
3956                Set_Is_Limited_Record  (Id, Is_Limited_Record     (T));
3957                Set_Has_Unknown_Discriminants
3958                                       (Id, Has_Unknown_Discriminants (T));
3959                Set_Known_To_Have_Preelab_Init
3960                                       (Id, Known_To_Have_Preelab_Init (T));
3961
3962                if Is_Tagged_Type (T) then
3963                   Set_Is_Tagged_Type              (Id);
3964                   Set_Is_Abstract_Type            (Id, Is_Abstract_Type (T));
3965                   Set_Class_Wide_Type             (Id, Class_Wide_Type (T));
3966                   Set_Direct_Primitive_Operations (Id,
3967                     Direct_Primitive_Operations (T));
3968                end if;
3969
3970                --  In general the attributes of the subtype of a private type
3971                --  are the attributes of the partial view of parent. However,
3972                --  the full view may be a discriminated type, and the subtype
3973                --  must share the discriminant constraint to generate correct
3974                --  calls to initialization procedures.
3975
3976                if Has_Discriminants (T) then
3977                   Set_Discriminant_Constraint
3978                                      (Id, Discriminant_Constraint (T));
3979                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3980
3981                elsif Present (Full_View (T))
3982                  and then Has_Discriminants (Full_View (T))
3983                then
3984                   Set_Discriminant_Constraint
3985                                (Id, Discriminant_Constraint (Full_View (T)));
3986                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
3987
3988                   --  This would seem semantically correct, but apparently
3989                   --  confuses the back-end. To be explained and checked with
3990                   --  current version ???
3991
3992                   --  Set_Has_Discriminants (Id);
3993                end if;
3994
3995                Prepare_Private_Subtype_Completion (Id, N);
3996
3997             when Access_Kind =>
3998                Set_Ekind             (Id, E_Access_Subtype);
3999                Set_Is_Constrained    (Id, Is_Constrained        (T));
4000                Set_Is_Access_Constant
4001                                      (Id, Is_Access_Constant    (T));
4002                Set_Directly_Designated_Type
4003                                      (Id, Designated_Type       (T));
4004                Set_Can_Never_Be_Null (Id, Can_Never_Be_Null     (T));
4005
4006                --  A Pure library_item must not contain the declaration of a
4007                --  named access type, except within a subprogram, generic
4008                --  subprogram, task unit, or protected unit, or if it has
4009                --  a specified Storage_Size of zero (RM05-10.2.1(15.4-15.5)).
4010
4011                if Comes_From_Source (Id)
4012                  and then In_Pure_Unit
4013                  and then not In_Subprogram_Task_Protected_Unit
4014                  and then not No_Pool_Assigned (Id)
4015                then
4016                   Error_Msg_N
4017                     ("named access types not allowed in pure unit", N);
4018                end if;
4019
4020             when Concurrent_Kind =>
4021                Set_Ekind                (Id, Subtype_Kind (Ekind   (T)));
4022                Set_Corresponding_Record_Type (Id,
4023                                          Corresponding_Record_Type (T));
4024                Set_First_Entity         (Id, First_Entity          (T));
4025                Set_First_Private_Entity (Id, First_Private_Entity  (T));
4026                Set_Has_Discriminants    (Id, Has_Discriminants     (T));
4027                Set_Is_Constrained       (Id, Is_Constrained        (T));
4028                Set_Is_Tagged_Type       (Id, Is_Tagged_Type        (T));
4029                Set_Last_Entity          (Id, Last_Entity           (T));
4030
4031                if Has_Discriminants (T) then
4032                   Set_Discriminant_Constraint (Id,
4033                                            Discriminant_Constraint (T));
4034                   Set_Stored_Constraint_From_Discriminant_Constraint (Id);
4035                end if;
4036
4037             when E_Incomplete_Type =>
4038                if Ada_Version >= Ada_2005 then
4039                   Set_Ekind (Id, E_Incomplete_Subtype);
4040
4041                   --  Ada 2005 (AI-412): Decorate an incomplete subtype
4042                   --  of an incomplete type visible through a limited
4043                   --  with clause.
4044
4045                   if From_With_Type (T)
4046                     and then Present (Non_Limited_View (T))
4047                   then
4048                      Set_From_With_Type   (Id);
4049                      Set_Non_Limited_View (Id, Non_Limited_View (T));
4050
4051                   --  Ada 2005 (AI-412): Add the regular incomplete subtype
4052                   --  to the private dependents of the original incomplete
4053                   --  type for future transformation.
4054
4055                   else
4056                      Append_Elmt (Id, Private_Dependents (T));
4057                   end if;
4058
4059                --  If the subtype name denotes an incomplete type an error
4060                --  was already reported by Process_Subtype.
4061
4062                else
4063                   Set_Etype (Id, Any_Type);
4064                end if;
4065
4066             when others =>
4067                raise Program_Error;
4068          end case;
4069       end if;
4070
4071       if Etype (Id) = Any_Type then
4072          goto Leave;
4073       end if;
4074
4075       --  Some common processing on all types
4076
4077       Set_Size_Info      (Id,                 T);
4078       Set_First_Rep_Item (Id, First_Rep_Item (T));
4079
4080       T := Etype (Id);
4081
4082       Set_Is_Immediately_Visible   (Id, True);
4083       Set_Depends_On_Private       (Id, Has_Private_Component (T));
4084       Set_Is_Descendent_Of_Address (Id, Is_Descendent_Of_Address (T));
4085
4086       if Is_Interface (T) then
4087          Set_Is_Interface (Id);
4088       end if;
4089
4090       if Present (Generic_Parent_Type (N))
4091         and then
4092           (Nkind
4093             (Parent (Generic_Parent_Type (N))) /= N_Formal_Type_Declaration
4094             or else Nkind
4095               (Formal_Type_Definition (Parent (Generic_Parent_Type (N))))
4096                 /= N_Formal_Private_Type_Definition)
4097       then
4098          if Is_Tagged_Type (Id) then
4099
4100             --  If this is a generic actual subtype for a synchronized type,
4101             --  the primitive operations are those of the corresponding record
4102             --  for which there is a separate subtype declaration.
4103
4104             if Is_Concurrent_Type (Id) then
4105                null;
4106             elsif Is_Class_Wide_Type (Id) then
4107                Derive_Subprograms (Generic_Parent_Type (N), Id, Etype (T));
4108             else
4109                Derive_Subprograms (Generic_Parent_Type (N), Id, T);
4110             end if;
4111
4112          elsif Scope (Etype (Id)) /= Standard_Standard then
4113             Derive_Subprograms (Generic_Parent_Type (N), Id);
4114          end if;
4115       end if;
4116
4117       if Is_Private_Type (T)
4118         and then Present (Full_View (T))
4119       then
4120          Conditional_Delay (Id, Full_View (T));
4121
4122       --  The subtypes of components or subcomponents of protected types
4123       --  do not need freeze nodes, which would otherwise appear in the
4124       --  wrong scope (before the freeze node for the protected type). The
4125       --  proper subtypes are those of the subcomponents of the corresponding
4126       --  record.
4127
4128       elsif Ekind (Scope (Id)) /= E_Protected_Type
4129         and then Present (Scope (Scope (Id))) -- error defense!
4130         and then Ekind (Scope (Scope (Id))) /= E_Protected_Type
4131       then
4132          Conditional_Delay (Id, T);
4133       end if;
4134
4135       --  Check that constraint_error is raised for a scalar subtype
4136       --  indication when the lower or upper bound of a non-null range
4137       --  lies outside the range of the type mark.
4138
4139       if Nkind (Subtype_Indication (N)) = N_Subtype_Indication then
4140          if Is_Scalar_Type (Etype (Id))
4141             and then Scalar_Range (Id) /=
4142                      Scalar_Range (Etype (Subtype_Mark
4143                                            (Subtype_Indication (N))))
4144          then
4145             Apply_Range_Check
4146               (Scalar_Range (Id),
4147                Etype (Subtype_Mark (Subtype_Indication (N))));
4148
4149          elsif Is_Array_Type (Etype (Id))
4150            and then Present (First_Index (Id))
4151          then
4152             --  This really should be a subprogram that finds the indications
4153             --  to check???
4154
4155             if ((Nkind (First_Index (Id)) = N_Identifier
4156                    and then Ekind (Entity (First_Index (Id))) in Scalar_Kind)
4157                  or else Nkind (First_Index (Id)) = N_Subtype_Indication)
4158               and then
4159                 Nkind (Scalar_Range (Etype (First_Index (Id)))) = N_Range
4160             then
4161                declare
4162                   Target_Typ : constant Entity_Id :=
4163                                  Etype
4164                                    (First_Index (Etype
4165                                      (Subtype_Mark (Subtype_Indication (N)))));
4166                begin
4167                   R_Checks :=
4168                     Get_Range_Checks
4169                       (Scalar_Range (Etype (First_Index (Id))),
4170                        Target_Typ,
4171                        Etype (First_Index (Id)),
4172                        Defining_Identifier (N));
4173
4174                   Insert_Range_Checks
4175                     (R_Checks,
4176                      N,
4177                      Target_Typ,
4178                      Sloc (Defining_Identifier (N)));
4179                end;
4180             end if;
4181          end if;
4182       end if;
4183
4184       --  Make sure that generic actual types are properly frozen. The subtype
4185       --  is marked as a generic actual type when the enclosing instance is
4186       --  analyzed, so here we identify the subtype from the tree structure.
4187
4188       if Expander_Active
4189         and then Is_Generic_Actual_Type (Id)
4190         and then In_Instance
4191         and then not Comes_From_Source (N)
4192         and then Nkind (Subtype_Indication (N)) /= N_Subtype_Indication
4193         and then Is_Frozen (T)
4194       then
4195          Freeze_Before (N, Id);
4196       end if;
4197
4198       Set_Optimize_Alignment_Flags (Id);
4199       Check_Eliminated (Id);
4200
4201       <<Leave>>
4202          Analyze_Aspect_Specifications (N, Id, Aspect_Specifications (N));
4203    end Analyze_Subtype_Declaration;
4204
4205    --------------------------------
4206    -- Analyze_Subtype_Indication --
4207    --------------------------------
4208
4209    procedure Analyze_Subtype_Indication (N : Node_Id) is
4210       T : constant Entity_Id := Subtype_Mark (N);
4211       R : constant Node_Id   := Range_Expression (Constraint (N));
4212
4213    begin
4214       Analyze (T);
4215
4216       if R /= Error then
4217          Analyze (R);
4218          Set_Etype (N, Etype (R));
4219          Resolve (R, Entity (T));
4220       else
4221          Set_Error_Posted (R);
4222          Set_Error_Posted (T);
4223       end if;
4224    end Analyze_Subtype_Indication;
4225
4226    --------------------------
4227    -- Analyze_Variant_Part --
4228    --------------------------
4229
4230    procedure Analyze_Variant_Part (N : Node_Id) is
4231
4232       procedure Non_Static_Choice_Error (Choice : Node_Id);
4233       --  Error routine invoked by the generic instantiation below when the
4234       --  variant part has a non static choice.
4235
4236       procedure Process_Declarations (Variant : Node_Id);
4237       --  Analyzes all the declarations associated with a Variant. Needed by
4238       --  the generic instantiation below.
4239
4240       package Variant_Choices_Processing is new
4241         Generic_Choices_Processing
4242           (Get_Alternatives          => Variants,
4243            Get_Choices               => Discrete_Choices,
4244            Process_Empty_Choice      => No_OP,
4245            Process_Non_Static_Choice => Non_Static_Choice_Error,
4246            Process_Associated_Node   => Process_Declarations);
4247       use Variant_Choices_Processing;
4248       --  Instantiation of the generic choice processing package
4249
4250       -----------------------------
4251       -- Non_Static_Choice_Error --
4252       -----------------------------
4253
4254       procedure Non_Static_Choice_Error (Choice : Node_Id) is
4255       begin
4256          Flag_Non_Static_Expr
4257            ("choice given in variant part is not static!", Choice);
4258       end Non_Static_Choice_Error;
4259
4260       --------------------------
4261       -- Process_Declarations --
4262       --------------------------
4263
4264       procedure Process_Declarations (Variant : Node_Id) is
4265       begin
4266          if not Null_Present (Component_List (Variant)) then
4267             Analyze_Declarations (Component_Items (Component_List (Variant)));
4268
4269             if Present (Variant_Part (Component_List (Variant))) then
4270                Analyze (Variant_Part (Component_List (Variant)));
4271             end if;
4272          end if;
4273       end Process_Declarations;
4274
4275       --  Local Variables
4276
4277       Discr_Name : Node_Id;
4278       Discr_Type : Entity_Id;
4279
4280       Case_Table     : Choice_Table_Type (1 .. Number_Of_Choices (N));
4281       Last_Choice    : Nat;
4282       Dont_Care      : Boolean;
4283       Others_Present : Boolean := False;
4284
4285       pragma Warnings (Off, Case_Table);
4286       pragma Warnings (Off, Last_Choice);
4287       pragma Warnings (Off, Dont_Care);
4288       pragma Warnings (Off, Others_Present);
4289       --  We don't care about the assigned values of any of these
4290
4291    --  Start of processing for Analyze_Variant_Part
4292
4293    begin
4294       Discr_Name := Name (N);
4295       Analyze (Discr_Name);
4296
4297       --  If Discr_Name bad, get out (prevent cascaded errors)
4298
4299       if Etype (Discr_Name) = Any_Type then
4300          return;
4301       end if;
4302
4303       --  Check invalid discriminant in variant part
4304
4305       if Ekind (Entity (Discr_Name)) /= E_Discriminant then
4306          Error_Msg_N ("invalid discriminant name in variant part", Discr_Name);
4307       end if;
4308
4309       Discr_Type := Etype (Entity (Discr_Name));
4310
4311       if not Is_Discrete_Type (Discr_Type) then
4312          Error_Msg_N
4313            ("discriminant in a variant part must be of a discrete type",
4314              Name (N));
4315          return;
4316       end if;
4317
4318       --  Call the instantiated Analyze_Choices which does the rest of the work
4319
4320       Analyze_Choices
4321         (N, Discr_Type, Case_Table, Last_Choice, Dont_Care, Others_Present);
4322    end Analyze_Variant_Part;
4323
4324    ----------------------------
4325    -- Array_Type_Declaration --
4326    ----------------------------
4327
4328    procedure Array_Type_Declaration (T : in out Entity_Id; Def : Node_Id) is
4329       Component_Def : constant Node_Id := Component_Definition (Def);
4330       Element_Type  : Entity_Id;
4331       Implicit_Base : Entity_Id;
4332       Index         : Node_Id;
4333       Related_Id    : Entity_Id := Empty;
4334       Nb_Index      : Nat;
4335       P             : constant Node_Id := Parent (Def);
4336       Priv          : Entity_Id;
4337
4338    begin
4339       if Nkind (Def) = N_Constrained_Array_Definition then
4340          Index := First (Discrete_Subtype_Definitions (Def));
4341       else
4342          Index := First (Subtype_Marks (Def));
4343       end if;
4344
4345       --  Find proper names for the implicit types which may be public. In case
4346       --  of anonymous arrays we use the name of the first object of that type
4347       --  as prefix.
4348
4349       if No (T) then
4350          Related_Id :=  Defining_Identifier (P);
4351       else
4352          Related_Id := T;
4353       end if;
4354
4355       Nb_Index := 1;
4356       while Present (Index) loop
4357          Analyze (Index);
4358
4359          --  Add a subtype declaration for each index of private array type
4360          --  declaration whose etype is also private. For example:
4361
4362          --     package Pkg is
4363          --        type Index is private;
4364          --     private
4365          --        type Table is array (Index) of ...
4366          --     end;
4367
4368          --  This is currently required by the expander for the internally
4369          --  generated equality subprogram of records with variant parts in
4370          --  which the etype of some component is such private type.
4371
4372          if Ekind (Current_Scope) = E_Package
4373            and then In_Private_Part (Current_Scope)
4374            and then Has_Private_Declaration (Etype (Index))
4375          then
4376             declare
4377                Loc   : constant Source_Ptr := Sloc (Def);
4378                New_E : Entity_Id;
4379                Decl  : Entity_Id;
4380
4381             begin
4382                New_E := Make_Temporary (Loc, 'T');
4383                Set_Is_Internal (New_E);
4384
4385                Decl :=
4386                  Make_Subtype_Declaration (Loc,
4387                    Defining_Identifier => New_E,
4388                    Subtype_Indication  =>
4389                      New_Occurrence_Of (Etype (Index), Loc));
4390
4391                Insert_Before (Parent (Def), Decl);
4392                Analyze (Decl);
4393                Set_Etype (Index, New_E);
4394
4395                --  If the index is a range the Entity attribute is not
4396                --  available. Example:
4397
4398                --     package Pkg is
4399                --        type T is private;
4400                --     private
4401                --        type T is new Natural;
4402                --        Table : array (T(1) .. T(10)) of Boolean;
4403                --     end Pkg;
4404
4405                if Nkind (Index) /= N_Range then
4406                   Set_Entity (Index, New_E);
4407                end if;
4408             end;
4409          end if;
4410
4411          Make_Index (Index, P, Related_Id, Nb_Index);
4412          Next_Index (Index);
4413          Nb_Index := Nb_Index + 1;
4414       end loop;
4415
4416       --  Process subtype indication if one is present
4417
4418       if Present (Subtype_Indication (Component_Def)) then
4419          Element_Type :=
4420            Process_Subtype
4421              (Subtype_Indication (Component_Def), P, Related_Id, 'C');
4422
4423       --  Ada 2005 (AI-230): Access Definition case
4424
4425       else pragma Assert (Present (Access_Definition (Component_Def)));
4426
4427          --  Indicate that the anonymous access type is created by the
4428          --  array type declaration.
4429
4430          Element_Type := Access_Definition
4431                            (Related_Nod => P,
4432                             N           => Access_Definition (Component_Def));
4433          Set_Is_Local_Anonymous_Access (Element_Type);
4434
4435          --  Propagate the parent. This field is needed if we have to generate
4436          --  the master_id associated with an anonymous access to task type
4437          --  component (see Expand_N_Full_Type_Declaration.Build_Master)
4438
4439          Set_Parent (Element_Type, Parent (T));
4440
4441          --  Ada 2005 (AI-230): In case of components that are anonymous access
4442          --  types the level of accessibility depends on the enclosing type
4443          --  declaration
4444
4445          Set_Scope (Element_Type, Current_Scope); -- Ada 2005 (AI-230)
4446
4447          --  Ada 2005 (AI-254)
4448
4449          declare
4450             CD : constant Node_Id :=
4451                    Access_To_Subprogram_Definition
4452                      (Access_Definition (Component_Def));
4453          begin
4454             if Present (CD) and then Protected_Present (CD) then
4455                Element_Type :=
4456                  Replace_Anonymous_Access_To_Protected_Subprogram (Def);
4457             end if;
4458          end;
4459       end if;
4460
4461       --  Constrained array case
4462
4463       if No (T) then
4464          T := Create_Itype (E_Void, P, Related_Id, 'T');
4465       end if;
4466
4467       if Nkind (Def) = N_Constrained_Array_Definition then
4468
4469          --  Establish Implicit_Base as unconstrained base type
4470
4471          Implicit_Base := Create_Itype (E_Array_Type, P, Related_Id, 'B');
4472
4473          Set_Etype              (Implicit_Base, Implicit_Base);
4474          Set_Scope              (Implicit_Base, Current_Scope);
4475          Set_Has_Delayed_Freeze (Implicit_Base);
4476
4477          --  The constrained array type is a subtype of the unconstrained one
4478
4479          Set_Ekind          (T, E_Array_Subtype);
4480          Init_Size_Align    (T);
4481          Set_Etype          (T, Implicit_Base);
4482          Set_Scope          (T, Current_Scope);
4483          Set_Is_Constrained (T, True);
4484          Set_First_Index    (T, First (Discrete_Subtype_Definitions (Def)));
4485          Set_Has_Delayed_Freeze (T);
4486
4487          --  Complete setup of implicit base type
4488
4489          Set_First_Index       (Implicit_Base, First_Index (T));
4490          Set_Component_Type    (Implicit_Base, Element_Type);
4491          Set_Has_Task          (Implicit_Base, Has_Task (Element_Type));
4492          Set_Component_Size    (Implicit_Base, Uint_0);
4493          Set_Packed_Array_Type (Implicit_Base, Empty);
4494          Set_Has_Controlled_Component
4495                                (Implicit_Base, Has_Controlled_Component
4496                                                         (Element_Type)
4497                                                  or else Is_Controlled
4498                                                         (Element_Type));
4499          Set_Finalize_Storage_Only
4500                                (Implicit_Base, Finalize_Storage_Only
4501                                                         (Element_Type));
4502
4503       --  Unconstrained array case
4504
4505       else
4506          Set_Ekind                    (T, E_Array_Type);
4507          Init_Size_Align              (T);
4508          Set_Etype                    (T, T);
4509          Set_Scope                    (T, Current_Scope);
4510          Set_Component_Size           (T, Uint_0);
4511          Set_Is_Constrained           (T, False);
4512          Set_First_Index              (T, First (Subtype_Marks (Def)));
4513          Set_Has_Delayed_Freeze       (T, True);
4514          Set_Has_Task                 (T, Has_Task      (Element_Type));
4515          Set_Has_Controlled_Component (T, Has_Controlled_Component
4516                                                         (Element_Type)
4517                                             or else
4518                                           Is_Controlled (Element_Type));
4519          Set_Finalize_Storage_Only    (T, Finalize_Storage_Only
4520                                                         (Element_Type));
4521       end if;
4522
4523       --  Common attributes for both cases
4524
4525       Set_Component_Type (Base_Type (T), Element_Type);
4526       Set_Packed_Array_Type (T, Empty);
4527
4528       if Aliased_Present (Component_Definition (Def)) then
4529          Set_Has_Aliased_Components (Etype (T));
4530       end if;
4531
4532       --  Ada 2005 (AI-231): Propagate the null-excluding attribute to the
4533       --  array type to ensure that objects of this type are initialized.
4534
4535       if Ada_Version >= Ada_2005
4536         and then Can_Never_Be_Null (Element_Type)
4537       then
4538          Set_Can_Never_Be_Null (T);
4539
4540          if Null_Exclusion_Present (Component_Definition (Def))
4541
4542             --  No need to check itypes because in their case this check was
4543             --  done at their point of creation
4544
4545            and then not Is_Itype (Element_Type)
4546          then
4547             Error_Msg_N
4548               ("`NOT NULL` not allowed (null already excluded)",
4549                Subtype_Indication (Component_Definition (Def)));
4550          end if;
4551       end if;
4552
4553       Priv := Private_Component (Element_Type);
4554
4555       if Present (Priv) then
4556
4557          --  Check for circular definitions
4558
4559          if Priv = Any_Type then
4560             Set_Component_Type (Etype (T), Any_Type);
4561
4562          --  There is a gap in the visibility of operations on the composite
4563          --  type only if the component type is defined in a different scope.
4564
4565          elsif Scope (Priv) = Current_Scope then
4566             null;
4567
4568          elsif Is_Limited_Type (Priv) then
4569             Set_Is_Limited_Composite (Etype (T));
4570             Set_Is_Limited_Composite (T);
4571          else
4572             Set_Is_Private_Composite (Etype (T));
4573             Set_Is_Private_Composite (T);
4574          end if;
4575       end if;
4576
4577       --  A syntax error in the declaration itself may lead to an empty index
4578       --  list, in which case do a minimal patch.
4579
4580       if No (First_Index (T)) then
4581          Error_Msg_N ("missing index definition in array type declaration", T);
4582
4583          declare
4584             Indices : constant List_Id :=
4585                         New_List (New_Occurrence_Of (Any_Id, Sloc (T)));
4586          begin
4587             Set_Discrete_Subtype_Definitions (Def, Indices);
4588             Set_First_Index (T, First (Indices));
4589             return;
4590          end;
4591       end if;
4592
4593       --  Create a concatenation operator for the new type. Internal array
4594       --  types created for packed entities do not need such, they are
4595       --  compatible with the user-defined type.
4596
4597       if Number_Dimensions (T) = 1
4598          and then not Is_Packed_Array_Type (T)
4599       then
4600          New_Concatenation_Op (T);
4601       end if;
4602
4603       --  In the case of an unconstrained array the parser has already verified
4604       --  that all the indices are unconstrained but we still need to make sure
4605       --  that the element type is constrained.
4606
4607       if Is_Indefinite_Subtype (Element_Type) then
4608          Error_Msg_N
4609            ("unconstrained element type in array declaration",
4610             Subtype_Indication (Component_Def));
4611
4612       elsif Is_Abstract_Type (Element_Type) then
4613          Error_Msg_N
4614            ("the type of a component cannot be abstract",
4615             Subtype_Indication (Component_Def));
4616       end if;
4617    end Array_Type_Declaration;
4618
4619    ------------------------------------------------------
4620    -- Replace_Anonymous_Access_To_Protected_Subprogram --
4621    ------------------------------------------------------
4622
4623    function Replace_Anonymous_Access_To_Protected_Subprogram
4624      (N : Node_Id) return Entity_Id
4625    is
4626       Loc : constant Source_Ptr := Sloc (N);
4627
4628       Curr_Scope : constant Scope_Stack_Entry :=
4629                      Scope_Stack.Table (Scope_Stack.Last);
4630
4631       Anon : constant Entity_Id := Make_Temporary (Loc, 'S');
4632       Acc  : Node_Id;
4633       Comp : Node_Id;
4634       Decl : Node_Id;
4635       P    : Node_Id;
4636
4637    begin
4638       Set_Is_Internal (Anon);
4639
4640       case Nkind (N) is
4641          when N_Component_Declaration       |
4642            N_Unconstrained_Array_Definition |
4643            N_Constrained_Array_Definition   =>
4644             Comp := Component_Definition (N);
4645             Acc  := Access_Definition (Comp);
4646
4647          when N_Discriminant_Specification =>
4648             Comp := Discriminant_Type (N);
4649             Acc  := Comp;
4650
4651          when N_Parameter_Specification =>
4652             Comp := Parameter_Type (N);
4653             Acc  := Comp;
4654
4655          when N_Access_Function_Definition  =>
4656             Comp := Result_Definition (N);
4657             Acc  := Comp;
4658
4659          when N_Object_Declaration  =>
4660             Comp := Object_Definition (N);
4661             Acc  := Comp;
4662
4663          when N_Function_Specification =>
4664             Comp := Result_Definition (N);
4665             Acc  := Comp;
4666
4667          when others =>
4668             raise Program_Error;
4669       end case;
4670
4671       Decl := Make_Full_Type_Declaration (Loc,
4672                 Defining_Identifier => Anon,
4673                 Type_Definition   =>
4674                   Copy_Separate_Tree (Access_To_Subprogram_Definition (Acc)));
4675
4676       Mark_Rewrite_Insertion (Decl);
4677
4678       --  Insert the new declaration in the nearest enclosing scope. If the
4679       --  node is a body and N is its return type, the declaration belongs in
4680       --  the enclosing scope.
4681
4682       P := Parent (N);
4683
4684       if Nkind (P) = N_Subprogram_Body
4685         and then Nkind (N) = N_Function_Specification
4686       then
4687          P := Parent (P);
4688       end if;
4689
4690       while Present (P) and then not Has_Declarations (P) loop
4691          P := Parent (P);
4692       end loop;
4693
4694       pragma Assert (Present (P));
4695
4696       if Nkind (P) = N_Package_Specification then
4697          Prepend (Decl, Visible_Declarations (P));
4698       else
4699          Prepend (Decl, Declarations (P));
4700       end if;
4701
4702       --  Replace the anonymous type with an occurrence of the new declaration.
4703       --  In all cases the rewritten node does not have the null-exclusion
4704       --  attribute because (if present) it was already inherited by the
4705       --  anonymous entity (Anon). Thus, in case of components we do not
4706       --  inherit this attribute.
4707
4708       if Nkind (N) = N_Parameter_Specification then
4709          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4710          Set_Etype (Defining_Identifier (N), Anon);
4711          Set_Null_Exclusion_Present (N, False);
4712
4713       elsif Nkind (N) = N_Object_Declaration then
4714          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4715          Set_Etype (Defining_Identifier (N), Anon);
4716
4717       elsif Nkind (N) = N_Access_Function_Definition then
4718          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4719
4720       elsif Nkind (N) = N_Function_Specification then
4721          Rewrite (Comp, New_Occurrence_Of (Anon, Loc));
4722          Set_Etype (Defining_Unit_Name (N), Anon);
4723
4724       else
4725          Rewrite (Comp,
4726            Make_Component_Definition (Loc,
4727              Subtype_Indication => New_Occurrence_Of (Anon, Loc)));
4728       end if;
4729
4730       Mark_Rewrite_Insertion (Comp);
4731
4732       if Nkind_In (N, N_Object_Declaration, N_Access_Function_Definition) then
4733          Analyze (Decl);
4734
4735       else
4736          --  Temporarily remove the current scope (record or subprogram) from
4737          --  the stack to add the new declarations to the enclosing scope.
4738
4739          Scope_Stack.Decrement_Last;
4740          Analyze (Decl);
4741          Set_Is_Itype (Anon);
4742          Scope_Stack.Append (Curr_Scope);
4743       end if;
4744
4745       Set_Ekind (Anon, E_Anonymous_Access_Protected_Subprogram_Type);
4746       Set_Can_Use_Internal_Rep (Anon, not Always_Compatible_Rep_On_Target);
4747       return Anon;
4748    end Replace_Anonymous_Access_To_Protected_Subprogram;
4749
4750    -------------------------------
4751    -- Build_Derived_Access_Type --
4752    -------------------------------
4753
4754    procedure Build_Derived_Access_Type
4755      (N            : Node_Id;
4756       Parent_Type  : Entity_Id;
4757       Derived_Type : Entity_Id)
4758    is
4759       S : constant Node_Id := Subtype_Indication (Type_Definition (N));
4760
4761       Desig_Type      : Entity_Id;
4762       Discr           : Entity_Id;
4763       Discr_Con_Elist : Elist_Id;
4764       Discr_Con_El    : Elmt_Id;
4765       Subt            : Entity_Id;
4766
4767    begin
4768       --  Set the designated type so it is available in case this is an access
4769       --  to a self-referential type, e.g. a standard list type with a next
4770       --  pointer. Will be reset after subtype is built.
4771
4772       Set_Directly_Designated_Type
4773         (Derived_Type, Designated_Type (Parent_Type));
4774
4775       Subt := Process_Subtype (S, N);
4776
4777       if Nkind (S) /= N_Subtype_Indication
4778         and then Subt /= Base_Type (Subt)
4779       then
4780          Set_Ekind (Derived_Type, E_Access_Subtype);
4781       end if;
4782
4783       if Ekind (Derived_Type) = E_Access_Subtype then
4784          declare
4785             Pbase      : constant Entity_Id := Base_Type (Parent_Type);
4786             Ibase      : constant Entity_Id :=
4787                            Create_Itype (Ekind (Pbase), N, Derived_Type, 'B');
4788             Svg_Chars  : constant Name_Id   := Chars (Ibase);
4789             Svg_Next_E : constant Entity_Id := Next_Entity (Ibase);
4790
4791          begin
4792             Copy_Node (Pbase, Ibase);
4793
4794             Set_Chars             (Ibase, Svg_Chars);
4795             Set_Next_Entity       (Ibase, Svg_Next_E);
4796             Set_Sloc              (Ibase, Sloc (Derived_Type));
4797             Set_Scope             (Ibase, Scope (Derived_Type));
4798             Set_Freeze_Node       (Ibase, Empty);
4799             Set_Is_Frozen         (Ibase, False);
4800             Set_Comes_From_Source (Ibase, False);
4801             Set_Is_First_Subtype  (Ibase, False);
4802
4803             Set_Etype (Ibase, Pbase);
4804             Set_Etype (Derived_Type, Ibase);
4805          end;
4806       end if;
4807
4808       Set_Directly_Designated_Type
4809         (Derived_Type, Designated_Type (Subt));
4810
4811       Set_Is_Constrained     (Derived_Type, Is_Constrained (Subt));
4812       Set_Is_Access_Constant (Derived_Type, Is_Access_Constant (Parent_Type));
4813       Set_Size_Info          (Derived_Type,                     Parent_Type);
4814       Set_RM_Size            (Derived_Type, RM_Size            (Parent_Type));
4815       Set_Depends_On_Private (Derived_Type,
4816                               Has_Private_Component (Derived_Type));
4817       Conditional_Delay      (Derived_Type, Subt);
4818
4819       --  Ada 2005 (AI-231): Set the null-exclusion attribute, and verify
4820       --  that it is not redundant.
4821
4822       if Null_Exclusion_Present (Type_Definition (N)) then
4823          Set_Can_Never_Be_Null (Derived_Type);
4824
4825          if Can_Never_Be_Null (Parent_Type)
4826            and then False
4827          then
4828             Error_Msg_NE
4829               ("`NOT NULL` not allowed (& already excludes null)",
4830                 N, Parent_Type);
4831          end if;
4832
4833       elsif Can_Never_Be_Null (Parent_Type) then
4834          Set_Can_Never_Be_Null (Derived_Type);
4835       end if;
4836
4837       --  Note: we do not copy the Storage_Size_Variable, since we always go to
4838       --  the root type for this information.
4839
4840       --  Apply range checks to discriminants for derived record case
4841       --  ??? THIS CODE SHOULD NOT BE HERE REALLY.
4842
4843       Desig_Type := Designated_Type (Derived_Type);
4844       if Is_Composite_Type (Desig_Type)
4845         and then (not Is_Array_Type (Desig_Type))
4846         and then Has_Discriminants (Desig_Type)
4847         and then Base_Type (Desig_Type) /= Desig_Type
4848       then
4849          Discr_Con_Elist := Discriminant_Constraint (Desig_Type);
4850          Discr_Con_El := First_Elmt (Discr_Con_Elist);
4851
4852          Discr := First_Discriminant (Base_Type (Desig_Type));
4853          while Present (Discr_Con_El) loop
4854             Apply_Range_Check (Node (Discr_Con_El), Etype (Discr));
4855             Next_Elmt (Discr_Con_El);
4856             Next_Discriminant (Discr);
4857          end loop;
4858       end if;
4859    end Build_Derived_Access_Type;
4860
4861    ------------------------------
4862    -- Build_Derived_Array_Type --
4863    ------------------------------
4864
4865    procedure Build_Derived_Array_Type
4866      (N            : Node_Id;
4867       Parent_Type  : Entity_Id;
4868       Derived_Type : Entity_Id)
4869    is
4870       Loc           : constant Source_Ptr := Sloc (N);
4871       Tdef          : constant Node_Id    := Type_Definition (N);
4872       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
4873       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
4874       Implicit_Base : Entity_Id;
4875       New_Indic     : Node_Id;
4876
4877       procedure Make_Implicit_Base;
4878       --  If the parent subtype is constrained, the derived type is a subtype
4879       --  of an implicit base type derived from the parent base.
4880
4881       ------------------------
4882       -- Make_Implicit_Base --
4883       ------------------------
4884
4885       procedure Make_Implicit_Base is
4886       begin
4887          Implicit_Base :=
4888            Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
4889
4890          Set_Ekind (Implicit_Base, Ekind (Parent_Base));
4891          Set_Etype (Implicit_Base, Parent_Base);
4892
4893          Copy_Array_Subtype_Attributes   (Implicit_Base, Parent_Base);
4894          Copy_Array_Base_Type_Attributes (Implicit_Base, Parent_Base);
4895
4896          Set_Has_Delayed_Freeze (Implicit_Base, True);
4897       end Make_Implicit_Base;
4898
4899    --  Start of processing for Build_Derived_Array_Type
4900
4901    begin
4902       if not Is_Constrained (Parent_Type) then
4903          if Nkind (Indic) /= N_Subtype_Indication then
4904             Set_Ekind (Derived_Type, E_Array_Type);
4905
4906             Copy_Array_Subtype_Attributes   (Derived_Type, Parent_Type);
4907             Copy_Array_Base_Type_Attributes (Derived_Type, Parent_Type);
4908
4909             Set_Has_Delayed_Freeze (Derived_Type, True);
4910
4911          else
4912             Make_Implicit_Base;
4913             Set_Etype (Derived_Type, Implicit_Base);
4914
4915             New_Indic :=
4916               Make_Subtype_Declaration (Loc,
4917                 Defining_Identifier => Derived_Type,
4918                 Subtype_Indication  =>
4919                   Make_Subtype_Indication (Loc,
4920                     Subtype_Mark => New_Reference_To (Implicit_Base, Loc),
4921                     Constraint => Constraint (Indic)));
4922
4923             Rewrite (N, New_Indic);
4924             Analyze (N);
4925          end if;
4926
4927       else
4928          if Nkind (Indic) /= N_Subtype_Indication then
4929             Make_Implicit_Base;
4930
4931             Set_Ekind             (Derived_Type, Ekind (Parent_Type));
4932             Set_Etype             (Derived_Type, Implicit_Base);
4933             Copy_Array_Subtype_Attributes (Derived_Type, Parent_Type);
4934
4935          else
4936             Error_Msg_N ("illegal constraint on constrained type", Indic);
4937          end if;
4938       end if;
4939
4940       --  If parent type is not a derived type itself, and is declared in
4941       --  closed scope (e.g. a subprogram), then we must explicitly introduce
4942       --  the new type's concatenation operator since Derive_Subprograms
4943       --  will not inherit the parent's operator. If the parent type is
4944       --  unconstrained, the operator is of the unconstrained base type.
4945
4946       if Number_Dimensions (Parent_Type) = 1
4947         and then not Is_Limited_Type (Parent_Type)
4948         and then not Is_Derived_Type (Parent_Type)
4949         and then not Is_Package_Or_Generic_Package
4950                        (Scope (Base_Type (Parent_Type)))
4951       then
4952          if not Is_Constrained (Parent_Type)
4953            and then Is_Constrained (Derived_Type)
4954          then
4955             New_Concatenation_Op (Implicit_Base);
4956          else
4957             New_Concatenation_Op (Derived_Type);
4958          end if;
4959       end if;
4960    end Build_Derived_Array_Type;
4961
4962    -----------------------------------
4963    -- Build_Derived_Concurrent_Type --
4964    -----------------------------------
4965
4966    procedure Build_Derived_Concurrent_Type
4967      (N            : Node_Id;
4968       Parent_Type  : Entity_Id;
4969       Derived_Type : Entity_Id)
4970    is
4971       Loc : constant Source_Ptr := Sloc (N);
4972
4973       Corr_Record      : constant Entity_Id := Make_Temporary (Loc, 'C');
4974       Corr_Decl        : Node_Id;
4975       Corr_Decl_Needed : Boolean;
4976       --  If the derived type has fewer discriminants than its parent, the
4977       --  corresponding record is also a derived type, in order to account for
4978       --  the bound discriminants. We create a full type declaration for it in
4979       --  this case.
4980
4981       Constraint_Present : constant Boolean :=
4982                              Nkind (Subtype_Indication (Type_Definition (N))) =
4983                                                           N_Subtype_Indication;
4984
4985       D_Constraint   : Node_Id;
4986       New_Constraint : Elist_Id;
4987       Old_Disc       : Entity_Id;
4988       New_Disc       : Entity_Id;
4989       New_N          : Node_Id;
4990
4991    begin
4992       Set_Stored_Constraint (Derived_Type, No_Elist);
4993       Corr_Decl_Needed := False;
4994       Old_Disc := Empty;
4995
4996       if Present (Discriminant_Specifications (N))
4997         and then Constraint_Present
4998       then
4999          Old_Disc := First_Discriminant (Parent_Type);
5000          New_Disc := First (Discriminant_Specifications (N));
5001          while Present (New_Disc) and then Present (Old_Disc) loop
5002             Next_Discriminant (Old_Disc);
5003             Next (New_Disc);
5004          end loop;
5005       end if;
5006
5007       if Present (Old_Disc) then
5008
5009          --  The new type has fewer discriminants, so we need to create a new
5010          --  corresponding record, which is derived from the corresponding
5011          --  record of the parent, and has a stored constraint that captures
5012          --  the values of the discriminant constraints.
5013
5014          --  The type declaration for the derived corresponding record has
5015          --  the same discriminant part and constraints as the current
5016          --  declaration. Copy the unanalyzed tree to build declaration.
5017
5018          Corr_Decl_Needed := True;
5019          New_N := Copy_Separate_Tree (N);
5020
5021          Corr_Decl :=
5022            Make_Full_Type_Declaration (Loc,
5023              Defining_Identifier => Corr_Record,
5024              Discriminant_Specifications =>
5025                 Discriminant_Specifications (New_N),
5026              Type_Definition =>
5027                Make_Derived_Type_Definition (Loc,
5028                  Subtype_Indication =>
5029                    Make_Subtype_Indication (Loc,
5030                      Subtype_Mark =>
5031                         New_Occurrence_Of
5032                           (Corresponding_Record_Type (Parent_Type), Loc),
5033                      Constraint =>
5034                        Constraint
5035                          (Subtype_Indication (Type_Definition (New_N))))));
5036       end if;
5037
5038       --  Copy Storage_Size and Relative_Deadline variables if task case
5039
5040       if Is_Task_Type (Parent_Type) then
5041          Set_Storage_Size_Variable (Derived_Type,
5042            Storage_Size_Variable (Parent_Type));
5043          Set_Relative_Deadline_Variable (Derived_Type,
5044            Relative_Deadline_Variable (Parent_Type));
5045       end if;
5046
5047       if Present (Discriminant_Specifications (N)) then
5048          Push_Scope (Derived_Type);
5049          Check_Or_Process_Discriminants (N, Derived_Type);
5050
5051          if Constraint_Present then
5052             New_Constraint :=
5053               Expand_To_Stored_Constraint
5054                 (Parent_Type,
5055                  Build_Discriminant_Constraints
5056                    (Parent_Type,
5057                     Subtype_Indication (Type_Definition (N)), True));
5058          end if;
5059
5060          End_Scope;
5061
5062       elsif Constraint_Present then
5063
5064          --  Build constrained subtype and derive from it
5065
5066          declare
5067             Loc  : constant Source_Ptr := Sloc (N);
5068             Anon : constant Entity_Id :=
5069                      Make_Defining_Identifier (Loc,
5070                        New_External_Name (Chars (Derived_Type), 'T'));
5071             Decl : Node_Id;
5072
5073          begin
5074             Decl :=
5075               Make_Subtype_Declaration (Loc,
5076                 Defining_Identifier => Anon,
5077                 Subtype_Indication =>
5078                   Subtype_Indication (Type_Definition (N)));
5079             Insert_Before (N, Decl);
5080             Analyze (Decl);
5081
5082             Rewrite (Subtype_Indication (Type_Definition (N)),
5083               New_Occurrence_Of (Anon, Loc));
5084             Set_Analyzed (Derived_Type, False);
5085             Analyze (N);
5086             return;
5087          end;
5088       end if;
5089
5090       --  By default, operations and private data are inherited from parent.
5091       --  However, in the presence of bound discriminants, a new corresponding
5092       --  record will be created, see below.
5093
5094       Set_Has_Discriminants
5095         (Derived_Type, Has_Discriminants         (Parent_Type));
5096       Set_Corresponding_Record_Type
5097         (Derived_Type, Corresponding_Record_Type (Parent_Type));
5098
5099       --  Is_Constrained is set according the parent subtype, but is set to
5100       --  False if the derived type is declared with new discriminants.
5101
5102       Set_Is_Constrained
5103         (Derived_Type,
5104          (Is_Constrained (Parent_Type) or else Constraint_Present)
5105            and then not Present (Discriminant_Specifications (N)));
5106
5107       if Constraint_Present then
5108          if not Has_Discriminants (Parent_Type) then
5109             Error_Msg_N ("untagged parent must have discriminants", N);
5110
5111          elsif Present (Discriminant_Specifications (N)) then
5112
5113             --  Verify that new discriminants are used to constrain old ones
5114
5115             D_Constraint :=
5116               First
5117                 (Constraints
5118                   (Constraint (Subtype_Indication (Type_Definition (N)))));
5119
5120             Old_Disc := First_Discriminant (Parent_Type);
5121
5122             while Present (D_Constraint) loop
5123                if Nkind (D_Constraint) /= N_Discriminant_Association then
5124
5125                   --  Positional constraint. If it is a reference to a new
5126                   --  discriminant, it constrains the corresponding old one.
5127
5128                   if Nkind (D_Constraint) = N_Identifier then
5129                      New_Disc := First_Discriminant (Derived_Type);
5130                      while Present (New_Disc) loop
5131                         exit when Chars (New_Disc) = Chars (D_Constraint);
5132                         Next_Discriminant (New_Disc);
5133                      end loop;
5134
5135                      if Present (New_Disc) then
5136                         Set_Corresponding_Discriminant (New_Disc, Old_Disc);
5137                      end if;
5138                   end if;
5139
5140                   Next_Discriminant (Old_Disc);
5141
5142                   --  if this is a named constraint, search by name for the old
5143                   --  discriminants constrained by the new one.
5144
5145                elsif Nkind (Expression (D_Constraint)) = N_Identifier then
5146
5147                   --  Find new discriminant with that name
5148
5149                   New_Disc := First_Discriminant (Derived_Type);
5150                   while Present (New_Disc) loop
5151                      exit when
5152                        Chars (New_Disc) = Chars (Expression (D_Constraint));
5153                      Next_Discriminant (New_Disc);
5154                   end loop;
5155
5156                   if Present (New_Disc) then
5157
5158                      --  Verify that new discriminant renames some discriminant
5159                      --  of the parent type, and associate the new discriminant
5160                      --  with one or more old ones that it renames.
5161
5162                      declare
5163                         Selector : Node_Id;
5164
5165                      begin
5166                         Selector := First (Selector_Names (D_Constraint));
5167                         while Present (Selector) loop
5168                            Old_Disc := First_Discriminant (Parent_Type);
5169                            while Present (Old_Disc) loop
5170                               exit when Chars (Old_Disc) = Chars (Selector);
5171                               Next_Discriminant (Old_Disc);
5172                            end loop;
5173
5174                            if Present (Old_Disc) then
5175                               Set_Corresponding_Discriminant
5176                                 (New_Disc, Old_Disc);
5177                            end if;
5178
5179                            Next (Selector);
5180                         end loop;
5181                      end;
5182                   end if;
5183                end if;
5184
5185                Next (D_Constraint);
5186             end loop;
5187
5188             New_Disc := First_Discriminant (Derived_Type);
5189             while Present (New_Disc) loop
5190                if No (Corresponding_Discriminant (New_Disc)) then
5191                   Error_Msg_NE
5192                     ("new discriminant& must constrain old one", N, New_Disc);
5193
5194                elsif not
5195                  Subtypes_Statically_Compatible
5196                    (Etype (New_Disc),
5197                     Etype (Corresponding_Discriminant (New_Disc)))
5198                then
5199                   Error_Msg_NE
5200                     ("& not statically compatible with parent discriminant",
5201                       N, New_Disc);
5202                end if;
5203
5204                Next_Discriminant (New_Disc);
5205             end loop;
5206          end if;
5207
5208       elsif Present (Discriminant_Specifications (N)) then
5209          Error_Msg_N
5210            ("missing discriminant constraint in untagged derivation", N);
5211       end if;
5212
5213       --  The entity chain of the derived type includes the new discriminants
5214       --  but shares operations with the parent.
5215
5216       if Present (Discriminant_Specifications (N)) then
5217          Old_Disc := First_Discriminant (Parent_Type);
5218          while Present (Old_Disc) loop
5219             if No (Next_Entity (Old_Disc))
5220               or else Ekind (Next_Entity (Old_Disc)) /= E_Discriminant
5221             then
5222                Set_Next_Entity
5223                  (Last_Entity (Derived_Type), Next_Entity (Old_Disc));
5224                exit;
5225             end if;
5226
5227             Next_Discriminant (Old_Disc);
5228          end loop;
5229
5230       else
5231          Set_First_Entity (Derived_Type, First_Entity (Parent_Type));
5232          if Has_Discriminants (Parent_Type) then
5233             Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5234             Set_Discriminant_Constraint (
5235               Derived_Type, Discriminant_Constraint (Parent_Type));
5236          end if;
5237       end if;
5238
5239       Set_Last_Entity  (Derived_Type, Last_Entity  (Parent_Type));
5240
5241       Set_Has_Completion (Derived_Type);
5242
5243       if Corr_Decl_Needed then
5244          Set_Stored_Constraint (Derived_Type, New_Constraint);
5245          Insert_After (N, Corr_Decl);
5246          Analyze (Corr_Decl);
5247          Set_Corresponding_Record_Type (Derived_Type, Corr_Record);
5248       end if;
5249    end Build_Derived_Concurrent_Type;
5250
5251    ------------------------------------
5252    -- Build_Derived_Enumeration_Type --
5253    ------------------------------------
5254
5255    procedure Build_Derived_Enumeration_Type
5256      (N            : Node_Id;
5257       Parent_Type  : Entity_Id;
5258       Derived_Type : Entity_Id)
5259    is
5260       Loc           : constant Source_Ptr := Sloc (N);
5261       Def           : constant Node_Id    := Type_Definition (N);
5262       Indic         : constant Node_Id    := Subtype_Indication (Def);
5263       Implicit_Base : Entity_Id;
5264       Literal       : Entity_Id;
5265       New_Lit       : Entity_Id;
5266       Literals_List : List_Id;
5267       Type_Decl     : Node_Id;
5268       Hi, Lo        : Node_Id;
5269       Rang_Expr     : Node_Id;
5270
5271    begin
5272       --  Since types Standard.Character and Standard.[Wide_]Wide_Character do
5273       --  not have explicit literals lists we need to process types derived
5274       --  from them specially. This is handled by Derived_Standard_Character.
5275       --  If the parent type is a generic type, there are no literals either,
5276       --  and we construct the same skeletal representation as for the generic
5277       --  parent type.
5278
5279       if Is_Standard_Character_Type (Parent_Type) then
5280          Derived_Standard_Character (N, Parent_Type, Derived_Type);
5281
5282       elsif Is_Generic_Type (Root_Type (Parent_Type)) then
5283          declare
5284             Lo : Node_Id;
5285             Hi : Node_Id;
5286
5287          begin
5288             if Nkind (Indic) /= N_Subtype_Indication then
5289                Lo :=
5290                   Make_Attribute_Reference (Loc,
5291                     Attribute_Name => Name_First,
5292                     Prefix         => New_Reference_To (Derived_Type, Loc));
5293                Set_Etype (Lo, Derived_Type);
5294
5295                Hi :=
5296                   Make_Attribute_Reference (Loc,
5297                     Attribute_Name => Name_Last,
5298                     Prefix         => New_Reference_To (Derived_Type, Loc));
5299                Set_Etype (Hi, Derived_Type);
5300
5301                Set_Scalar_Range (Derived_Type,
5302                   Make_Range (Loc,
5303                     Low_Bound  => Lo,
5304                     High_Bound => Hi));
5305             else
5306
5307                --   Analyze subtype indication and verify compatibility
5308                --   with parent type.
5309
5310                if Base_Type (Process_Subtype (Indic, N)) /=
5311                   Base_Type (Parent_Type)
5312                then
5313                   Error_Msg_N
5314                     ("illegal constraint for formal discrete type", N);
5315                end if;
5316             end if;
5317          end;
5318
5319       else
5320          --  If a constraint is present, analyze the bounds to catch
5321          --  premature usage of the derived literals.
5322
5323          if Nkind (Indic) = N_Subtype_Indication
5324            and then Nkind (Range_Expression (Constraint (Indic))) = N_Range
5325          then
5326             Analyze (Low_Bound  (Range_Expression (Constraint (Indic))));
5327             Analyze (High_Bound (Range_Expression (Constraint (Indic))));
5328          end if;
5329
5330          --  Introduce an implicit base type for the derived type even if there
5331          --  is no constraint attached to it, since this seems closer to the
5332          --  Ada semantics. Build a full type declaration tree for the derived
5333          --  type using the implicit base type as the defining identifier. The
5334          --  build a subtype declaration tree which applies the constraint (if
5335          --  any) have it replace the derived type declaration.
5336
5337          Literal := First_Literal (Parent_Type);
5338          Literals_List := New_List;
5339          while Present (Literal)
5340            and then Ekind (Literal) = E_Enumeration_Literal
5341          loop
5342             --  Literals of the derived type have the same representation as
5343             --  those of the parent type, but this representation can be
5344             --  overridden by an explicit representation clause. Indicate
5345             --  that there is no explicit representation given yet. These
5346             --  derived literals are implicit operations of the new type,
5347             --  and can be overridden by explicit ones.
5348
5349             if Nkind (Literal) = N_Defining_Character_Literal then
5350                New_Lit :=
5351                  Make_Defining_Character_Literal (Loc, Chars (Literal));
5352             else
5353                New_Lit := Make_Defining_Identifier (Loc, Chars (Literal));
5354             end if;
5355
5356             Set_Ekind                (New_Lit, E_Enumeration_Literal);
5357             Set_Enumeration_Pos      (New_Lit, Enumeration_Pos (Literal));
5358             Set_Enumeration_Rep      (New_Lit, Enumeration_Rep (Literal));
5359             Set_Enumeration_Rep_Expr (New_Lit, Empty);
5360             Set_Alias                (New_Lit, Literal);
5361             Set_Is_Known_Valid       (New_Lit, True);
5362
5363             Append (New_Lit, Literals_List);
5364             Next_Literal (Literal);
5365          end loop;
5366
5367          Implicit_Base :=
5368            Make_Defining_Identifier (Sloc (Derived_Type),
5369              New_External_Name (Chars (Derived_Type), 'B'));
5370
5371          --  Indicate the proper nature of the derived type. This must be done
5372          --  before analysis of the literals, to recognize cases when a literal
5373          --  may be hidden by a previous explicit function definition (cf.
5374          --  c83031a).
5375
5376          Set_Ekind (Derived_Type, E_Enumeration_Subtype);
5377          Set_Etype (Derived_Type, Implicit_Base);
5378
5379          Type_Decl :=
5380            Make_Full_Type_Declaration (Loc,
5381              Defining_Identifier => Implicit_Base,
5382              Discriminant_Specifications => No_List,
5383              Type_Definition =>
5384                Make_Enumeration_Type_Definition (Loc, Literals_List));
5385
5386          Mark_Rewrite_Insertion (Type_Decl);
5387          Insert_Before (N, Type_Decl);
5388          Analyze (Type_Decl);
5389
5390          --  After the implicit base is analyzed its Etype needs to be changed
5391          --  to reflect the fact that it is derived from the parent type which
5392          --  was ignored during analysis. We also set the size at this point.
5393
5394          Set_Etype (Implicit_Base, Parent_Type);
5395
5396          Set_Size_Info      (Implicit_Base,                 Parent_Type);
5397          Set_RM_Size        (Implicit_Base, RM_Size        (Parent_Type));
5398          Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Type));
5399
5400          --  Copy other flags from parent type
5401
5402          Set_Has_Non_Standard_Rep
5403                             (Implicit_Base, Has_Non_Standard_Rep
5404                                                            (Parent_Type));
5405          Set_Has_Pragma_Ordered
5406                             (Implicit_Base, Has_Pragma_Ordered
5407                                                            (Parent_Type));
5408          Set_Has_Delayed_Freeze (Implicit_Base);
5409
5410          --  Process the subtype indication including a validation check on the
5411          --  constraint, if any. If a constraint is given, its bounds must be
5412          --  implicitly converted to the new type.
5413
5414          if Nkind (Indic) = N_Subtype_Indication then
5415             declare
5416                R : constant Node_Id :=
5417                      Range_Expression (Constraint (Indic));
5418
5419             begin
5420                if Nkind (R) = N_Range then
5421                   Hi := Build_Scalar_Bound
5422                           (High_Bound (R), Parent_Type, Implicit_Base);
5423                   Lo := Build_Scalar_Bound
5424                           (Low_Bound  (R), Parent_Type, Implicit_Base);
5425
5426                else
5427                   --  Constraint is a Range attribute. Replace with explicit
5428                   --  mention of the bounds of the prefix, which must be a
5429                   --  subtype.
5430
5431                   Analyze (Prefix (R));
5432                   Hi :=
5433                     Convert_To (Implicit_Base,
5434                       Make_Attribute_Reference (Loc,
5435                         Attribute_Name => Name_Last,
5436                         Prefix =>
5437                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5438
5439                   Lo :=
5440                     Convert_To (Implicit_Base,
5441                       Make_Attribute_Reference (Loc,
5442                         Attribute_Name => Name_First,
5443                         Prefix =>
5444                           New_Occurrence_Of (Entity (Prefix (R)), Loc)));
5445                end if;
5446             end;
5447
5448          else
5449             Hi :=
5450               Build_Scalar_Bound
5451                 (Type_High_Bound (Parent_Type),
5452                  Parent_Type, Implicit_Base);
5453             Lo :=
5454                Build_Scalar_Bound
5455                  (Type_Low_Bound (Parent_Type),
5456                   Parent_Type, Implicit_Base);
5457          end if;
5458
5459          Rang_Expr :=
5460            Make_Range (Loc,
5461              Low_Bound  => Lo,
5462              High_Bound => Hi);
5463
5464          --  If we constructed a default range for the case where no range
5465          --  was given, then the expressions in the range must not freeze
5466          --  since they do not correspond to expressions in the source.
5467
5468          if Nkind (Indic) /= N_Subtype_Indication then
5469             Set_Must_Not_Freeze (Lo);
5470             Set_Must_Not_Freeze (Hi);
5471             Set_Must_Not_Freeze (Rang_Expr);
5472          end if;
5473
5474          Rewrite (N,
5475            Make_Subtype_Declaration (Loc,
5476              Defining_Identifier => Derived_Type,
5477              Subtype_Indication =>
5478                Make_Subtype_Indication (Loc,
5479                  Subtype_Mark => New_Occurrence_Of (Implicit_Base, Loc),
5480                  Constraint =>
5481                    Make_Range_Constraint (Loc,
5482                      Range_Expression => Rang_Expr))));
5483
5484          Analyze (N);
5485
5486          --  If pragma Discard_Names applies on the first subtype of the parent
5487          --  type, then it must be applied on this subtype as well.
5488
5489          if Einfo.Discard_Names (First_Subtype (Parent_Type)) then
5490             Set_Discard_Names (Derived_Type);
5491          end if;
5492
5493          --  Apply a range check. Since this range expression doesn't have an
5494          --  Etype, we have to specifically pass the Source_Typ parameter. Is
5495          --  this right???
5496
5497          if Nkind (Indic) = N_Subtype_Indication then
5498             Apply_Range_Check (Range_Expression (Constraint (Indic)),
5499                                Parent_Type,
5500                                Source_Typ => Entity (Subtype_Mark (Indic)));
5501          end if;
5502       end if;
5503    end Build_Derived_Enumeration_Type;
5504
5505    --------------------------------
5506    -- Build_Derived_Numeric_Type --
5507    --------------------------------
5508
5509    procedure Build_Derived_Numeric_Type
5510      (N            : Node_Id;
5511       Parent_Type  : Entity_Id;
5512       Derived_Type : Entity_Id)
5513    is
5514       Loc           : constant Source_Ptr := Sloc (N);
5515       Tdef          : constant Node_Id    := Type_Definition (N);
5516       Indic         : constant Node_Id    := Subtype_Indication (Tdef);
5517       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
5518       No_Constraint : constant Boolean    := Nkind (Indic) /=
5519                                                   N_Subtype_Indication;
5520       Implicit_Base : Entity_Id;
5521
5522       Lo : Node_Id;
5523       Hi : Node_Id;
5524
5525    begin
5526       --  Process the subtype indication including a validation check on
5527       --  the constraint if any.
5528
5529       Discard_Node (Process_Subtype (Indic, N));
5530
5531       --  Introduce an implicit base type for the derived type even if there
5532       --  is no constraint attached to it, since this seems closer to the Ada
5533       --  semantics.
5534
5535       Implicit_Base :=
5536         Create_Itype (Ekind (Parent_Base), N, Derived_Type, 'B');
5537
5538       Set_Etype          (Implicit_Base, Parent_Base);
5539       Set_Ekind          (Implicit_Base, Ekind          (Parent_Base));
5540       Set_Size_Info      (Implicit_Base,                 Parent_Base);
5541       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Parent_Base));
5542       Set_Parent         (Implicit_Base, Parent (Derived_Type));
5543       Set_Is_Known_Valid (Implicit_Base, Is_Known_Valid (Parent_Base));
5544
5545       --  Set RM Size for discrete type or decimal fixed-point type
5546       --  Ordinary fixed-point is excluded, why???
5547
5548       if Is_Discrete_Type (Parent_Base)
5549         or else Is_Decimal_Fixed_Point_Type (Parent_Base)
5550       then
5551          Set_RM_Size (Implicit_Base, RM_Size (Parent_Base));
5552       end if;
5553
5554       Set_Has_Delayed_Freeze (Implicit_Base);
5555
5556       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
5557       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
5558
5559       Set_Scalar_Range (Implicit_Base,
5560         Make_Range (Loc,
5561           Low_Bound  => Lo,
5562           High_Bound => Hi));
5563
5564       if Has_Infinities (Parent_Base) then
5565          Set_Includes_Infinities (Scalar_Range (Implicit_Base));
5566       end if;
5567
5568       --  The Derived_Type, which is the entity of the declaration, is a
5569       --  subtype of the implicit base. Its Ekind is a subtype, even in the
5570       --  absence of an explicit constraint.
5571
5572       Set_Etype (Derived_Type, Implicit_Base);
5573
5574       --  If we did not have a constraint, then the Ekind is set from the
5575       --  parent type (otherwise Process_Subtype has set the bounds)
5576
5577       if No_Constraint then
5578          Set_Ekind (Derived_Type, Subtype_Kind (Ekind (Parent_Type)));
5579       end if;
5580
5581       --  If we did not have a range constraint, then set the range from the
5582       --  parent type. Otherwise, the Process_Subtype call has set the bounds.
5583
5584       if No_Constraint
5585         or else not Has_Range_Constraint (Indic)
5586       then
5587          Set_Scalar_Range (Derived_Type,
5588            Make_Range (Loc,
5589              Low_Bound  => New_Copy_Tree (Type_Low_Bound  (Parent_Type)),
5590              High_Bound => New_Copy_Tree (Type_High_Bound (Parent_Type))));
5591          Set_Is_Constrained (Derived_Type, Is_Constrained (Parent_Type));
5592
5593          if Has_Infinities (Parent_Type) then
5594             Set_Includes_Infinities (Scalar_Range (Derived_Type));
5595          end if;
5596
5597          Set_Is_Known_Valid (Derived_Type, Is_Known_Valid (Parent_Type));
5598       end if;
5599
5600       Set_Is_Descendent_Of_Address (Derived_Type,
5601         Is_Descendent_Of_Address (Parent_Type));
5602       Set_Is_Descendent_Of_Address (Implicit_Base,
5603         Is_Descendent_Of_Address (Parent_Type));
5604
5605       --  Set remaining type-specific fields, depending on numeric type
5606
5607       if Is_Modular_Integer_Type (Parent_Type) then
5608          Set_Modulus (Implicit_Base, Modulus (Parent_Base));
5609
5610          Set_Non_Binary_Modulus
5611            (Implicit_Base, Non_Binary_Modulus (Parent_Base));
5612
5613          Set_Is_Known_Valid
5614            (Implicit_Base, Is_Known_Valid (Parent_Base));
5615
5616       elsif Is_Floating_Point_Type (Parent_Type) then
5617
5618          --  Digits of base type is always copied from the digits value of
5619          --  the parent base type, but the digits of the derived type will
5620          --  already have been set if there was a constraint present.
5621
5622          Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5623          Set_Vax_Float    (Implicit_Base, Vax_Float    (Parent_Base));
5624
5625          if No_Constraint then
5626             Set_Digits_Value (Derived_Type, Digits_Value (Parent_Type));
5627          end if;
5628
5629       elsif Is_Fixed_Point_Type (Parent_Type) then
5630
5631          --  Small of base type and derived type are always copied from the
5632          --  parent base type, since smalls never change. The delta of the
5633          --  base type is also copied from the parent base type. However the
5634          --  delta of the derived type will have been set already if a
5635          --  constraint was present.
5636
5637          Set_Small_Value (Derived_Type,  Small_Value (Parent_Base));
5638          Set_Small_Value (Implicit_Base, Small_Value (Parent_Base));
5639          Set_Delta_Value (Implicit_Base, Delta_Value (Parent_Base));
5640
5641          if No_Constraint then
5642             Set_Delta_Value (Derived_Type,  Delta_Value (Parent_Type));
5643          end if;
5644
5645          --  The scale and machine radix in the decimal case are always
5646          --  copied from the parent base type.
5647
5648          if Is_Decimal_Fixed_Point_Type (Parent_Type) then
5649             Set_Scale_Value (Derived_Type,  Scale_Value (Parent_Base));
5650             Set_Scale_Value (Implicit_Base, Scale_Value (Parent_Base));
5651
5652             Set_Machine_Radix_10
5653               (Derived_Type,  Machine_Radix_10 (Parent_Base));
5654             Set_Machine_Radix_10
5655               (Implicit_Base, Machine_Radix_10 (Parent_Base));
5656
5657             Set_Digits_Value (Implicit_Base, Digits_Value (Parent_Base));
5658
5659             if No_Constraint then
5660                Set_Digits_Value (Derived_Type, Digits_Value (Parent_Base));
5661
5662             else
5663                --  the analysis of the subtype_indication sets the
5664                --  digits value of the derived type.
5665
5666                null;
5667             end if;
5668          end if;
5669       end if;
5670
5671       --  The type of the bounds is that of the parent type, and they
5672       --  must be converted to the derived type.
5673
5674       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
5675
5676       --  The implicit_base should be frozen when the derived type is frozen,
5677       --  but note that it is used in the conversions of the bounds. For fixed
5678       --  types we delay the determination of the bounds until the proper
5679       --  freezing point. For other numeric types this is rejected by GCC, for
5680       --  reasons that are currently unclear (???), so we choose to freeze the
5681       --  implicit base now. In the case of integers and floating point types
5682       --  this is harmless because subsequent representation clauses cannot
5683       --  affect anything, but it is still baffling that we cannot use the
5684       --  same mechanism for all derived numeric types.
5685
5686       --  There is a further complication: actually *some* representation
5687       --  clauses can affect the implicit base type. Namely, attribute
5688       --  definition clauses for stream-oriented attributes need to set the
5689       --  corresponding TSS entries on the base type, and this normally cannot
5690       --  be done after the base type is frozen, so the circuitry in
5691       --  Sem_Ch13.New_Stream_Subprogram must account for this possibility and
5692       --  not use Set_TSS in this case.
5693
5694       if Is_Fixed_Point_Type (Parent_Type) then
5695          Conditional_Delay (Implicit_Base, Parent_Type);
5696       else
5697          Freeze_Before (N, Implicit_Base);
5698       end if;
5699    end Build_Derived_Numeric_Type;
5700
5701    --------------------------------
5702    -- Build_Derived_Private_Type --
5703    --------------------------------
5704
5705    procedure Build_Derived_Private_Type
5706      (N             : Node_Id;
5707       Parent_Type   : Entity_Id;
5708       Derived_Type  : Entity_Id;
5709       Is_Completion : Boolean;
5710       Derive_Subps  : Boolean := True)
5711    is
5712       Loc         : constant Source_Ptr := Sloc (N);
5713       Der_Base    : Entity_Id;
5714       Discr       : Entity_Id;
5715       Full_Decl   : Node_Id := Empty;
5716       Full_Der    : Entity_Id;
5717       Full_P      : Entity_Id;
5718       Last_Discr  : Entity_Id;
5719       Par_Scope   : constant Entity_Id := Scope (Base_Type (Parent_Type));
5720       Swapped     : Boolean := False;
5721
5722       procedure Copy_And_Build;
5723       --  Copy derived type declaration, replace parent with its full view,
5724       --  and analyze new declaration.
5725
5726       --------------------
5727       -- Copy_And_Build --
5728       --------------------
5729
5730       procedure Copy_And_Build is
5731          Full_N : Node_Id;
5732
5733       begin
5734          if Ekind (Parent_Type) in Record_Kind
5735            or else
5736              (Ekind (Parent_Type) in Enumeration_Kind
5737                and then not Is_Standard_Character_Type (Parent_Type)
5738                and then not Is_Generic_Type (Root_Type (Parent_Type)))
5739          then
5740             Full_N := New_Copy_Tree (N);
5741             Insert_After (N, Full_N);
5742             Build_Derived_Type (
5743               Full_N, Parent_Type, Full_Der, True, Derive_Subps => False);
5744
5745          else
5746             Build_Derived_Type (
5747               N, Parent_Type, Full_Der, True, Derive_Subps => False);
5748          end if;
5749       end Copy_And_Build;
5750
5751    --  Start of processing for Build_Derived_Private_Type
5752
5753    begin
5754       if Is_Tagged_Type (Parent_Type) then
5755          Full_P := Full_View (Parent_Type);
5756
5757          --  A type extension of a type with unknown discriminants is an
5758          --  indefinite type that the back-end cannot handle directly.
5759          --  We treat it as a private type, and build a completion that is
5760          --  derived from the full view of the parent, and hopefully has
5761          --  known discriminants.
5762
5763          --  If the full view of the parent type has an underlying record view,
5764          --  use it to generate the underlying record view of this derived type
5765          --  (required for chains of derivations with unknown discriminants).
5766
5767          --  Minor optimization: we avoid the generation of useless underlying
5768          --  record view entities if the private type declaration has unknown
5769          --  discriminants but its corresponding full view has no
5770          --  discriminants.
5771
5772          if Has_Unknown_Discriminants (Parent_Type)
5773            and then Present (Full_P)
5774            and then (Has_Discriminants (Full_P)
5775                       or else Present (Underlying_Record_View (Full_P)))
5776            and then not In_Open_Scopes (Par_Scope)
5777            and then Expander_Active
5778          then
5779             declare
5780                Full_Der : constant Entity_Id := Make_Temporary (Loc, 'T');
5781                New_Ext  : constant Node_Id :=
5782                             Copy_Separate_Tree
5783                               (Record_Extension_Part (Type_Definition (N)));
5784                Decl     : Node_Id;
5785
5786             begin
5787                Build_Derived_Record_Type
5788                  (N, Parent_Type, Derived_Type, Derive_Subps);
5789
5790                --  Build anonymous completion, as a derivation from the full
5791                --  view of the parent. This is not a completion in the usual
5792                --  sense, because the current type is not private.
5793
5794                Decl :=
5795                  Make_Full_Type_Declaration (Loc,
5796                    Defining_Identifier => Full_Der,
5797                    Type_Definition     =>
5798                      Make_Derived_Type_Definition (Loc,
5799                        Subtype_Indication =>
5800                          New_Copy_Tree
5801                            (Subtype_Indication (Type_Definition (N))),
5802                        Record_Extension_Part => New_Ext));
5803
5804                --  If the parent type has an underlying record view, use it
5805                --  here to build the new underlying record view.
5806
5807                if Present (Underlying_Record_View (Full_P)) then
5808                   pragma Assert
5809                     (Nkind (Subtype_Indication (Type_Definition (Decl)))
5810                        = N_Identifier);
5811                   Set_Entity (Subtype_Indication (Type_Definition (Decl)),
5812                     Underlying_Record_View (Full_P));
5813                end if;
5814
5815                Install_Private_Declarations (Par_Scope);
5816                Install_Visible_Declarations (Par_Scope);
5817                Insert_Before (N, Decl);
5818
5819                --  Mark entity as an underlying record view before analysis,
5820                --  to avoid generating the list of its primitive operations
5821                --  (which is not really required for this entity) and thus
5822                --  prevent spurious errors associated with missing overriding
5823                --  of abstract primitives (overridden only for Derived_Type).
5824
5825                Set_Ekind (Full_Der, E_Record_Type);
5826                Set_Is_Underlying_Record_View (Full_Der);
5827
5828                Analyze (Decl);
5829
5830                pragma Assert (Has_Discriminants (Full_Der)
5831                  and then not Has_Unknown_Discriminants (Full_Der));
5832
5833                Uninstall_Declarations (Par_Scope);
5834
5835                --  Freeze the underlying record view, to prevent generation of
5836                --  useless dispatching information, which is simply shared with
5837                --  the real derived type.
5838
5839                Set_Is_Frozen (Full_Der);
5840
5841                --  Set up links between real entity and underlying record view
5842
5843                Set_Underlying_Record_View (Derived_Type, Base_Type (Full_Der));
5844                Set_Underlying_Record_View (Base_Type (Full_Der), Derived_Type);
5845             end;
5846
5847          --  If discriminants are known, build derived record
5848
5849          else
5850             Build_Derived_Record_Type
5851               (N, Parent_Type, Derived_Type, Derive_Subps);
5852          end if;
5853
5854          return;
5855
5856       elsif Has_Discriminants (Parent_Type) then
5857          if Present (Full_View (Parent_Type)) then
5858             if not Is_Completion then
5859
5860                --  Copy declaration for subsequent analysis, to provide a
5861                --  completion for what is a private declaration. Indicate that
5862                --  the full type is internally generated.
5863
5864                Full_Decl := New_Copy_Tree (N);
5865                Full_Der  := New_Copy (Derived_Type);
5866                Set_Comes_From_Source (Full_Decl, False);
5867                Set_Comes_From_Source (Full_Der, False);
5868                Set_Parent (Full_Der, Full_Decl);
5869
5870                Insert_After (N, Full_Decl);
5871
5872             else
5873                --  If this is a completion, the full view being built is itself
5874                --  private. We build a subtype of the parent with the same
5875                --  constraints as this full view, to convey to the back end the
5876                --  constrained components and the size of this subtype. If the
5877                --  parent is constrained, its full view can serve as the
5878                --  underlying full view of the derived type.
5879
5880                if No (Discriminant_Specifications (N)) then
5881                   if Nkind (Subtype_Indication (Type_Definition (N))) =
5882                                                         N_Subtype_Indication
5883                   then
5884                      Build_Underlying_Full_View (N, Derived_Type, Parent_Type);
5885
5886                   elsif Is_Constrained (Full_View (Parent_Type)) then
5887                      Set_Underlying_Full_View
5888                        (Derived_Type, Full_View (Parent_Type));
5889                   end if;
5890
5891                else
5892                   --  If there are new discriminants, the parent subtype is
5893                   --  constrained by them, but it is not clear how to build
5894                   --  the Underlying_Full_View in this case???
5895
5896                   null;
5897                end if;
5898             end if;
5899          end if;
5900
5901          --  Build partial view of derived type from partial view of parent
5902
5903          Build_Derived_Record_Type
5904            (N, Parent_Type, Derived_Type, Derive_Subps);
5905
5906          if Present (Full_View (Parent_Type)) and then not Is_Completion then
5907             if not In_Open_Scopes (Par_Scope)
5908               or else not In_Same_Source_Unit (N, Parent_Type)
5909             then
5910                --  Swap partial and full views temporarily
5911
5912                Install_Private_Declarations (Par_Scope);
5913                Install_Visible_Declarations (Par_Scope);
5914                Swapped := True;
5915             end if;
5916
5917             --  Build full view of derived type from full view of parent which
5918             --  is now installed. Subprograms have been derived on the partial
5919             --  view, the completion does not derive them anew.
5920
5921             if not Is_Tagged_Type (Parent_Type) then
5922
5923                --  If the parent is itself derived from another private type,
5924                --  installing the private declarations has not affected its
5925                --  privacy status, so use its own full view explicitly.
5926
5927                if Is_Private_Type (Parent_Type) then
5928                   Build_Derived_Record_Type
5929                     (Full_Decl, Full_View (Parent_Type), Full_Der, False);
5930                else
5931                   Build_Derived_Record_Type
5932                     (Full_Decl, Parent_Type, Full_Der, False);
5933                end if;
5934
5935             else
5936                --  If full view of parent is tagged, the completion inherits
5937                --  the proper primitive operations.
5938
5939                Set_Defining_Identifier (Full_Decl, Full_Der);
5940                Build_Derived_Record_Type
5941                  (Full_Decl, Parent_Type, Full_Der, Derive_Subps);
5942             end if;
5943
5944             --  The full declaration has been introduced into the tree and
5945             --  processed in the step above. It should not be analyzed again
5946             --  (when encountered later in the current list of declarations)
5947             --  to prevent spurious name conflicts. The full entity remains
5948             --  invisible.
5949
5950             Set_Analyzed (Full_Decl);
5951
5952             if Swapped then
5953                Uninstall_Declarations (Par_Scope);
5954
5955                if In_Open_Scopes (Par_Scope) then
5956                   Install_Visible_Declarations (Par_Scope);
5957                end if;
5958             end if;
5959
5960             Der_Base := Base_Type (Derived_Type);
5961             Set_Full_View (Derived_Type, Full_Der);
5962             Set_Full_View (Der_Base, Base_Type (Full_Der));
5963
5964             --  Copy the discriminant list from full view to the partial views
5965             --  (base type and its subtype). Gigi requires that the partial and
5966             --  full views have the same discriminants.
5967
5968             --  Note that since the partial view is pointing to discriminants
5969             --  in the full view, their scope will be that of the full view.
5970             --  This might cause some front end problems and need adjustment???
5971
5972             Discr := First_Discriminant (Base_Type (Full_Der));
5973             Set_First_Entity (Der_Base, Discr);
5974
5975             loop
5976                Last_Discr := Discr;
5977                Next_Discriminant (Discr);
5978                exit when No (Discr);
5979             end loop;
5980
5981             Set_Last_Entity (Der_Base, Last_Discr);
5982
5983             Set_First_Entity (Derived_Type, First_Entity (Der_Base));
5984             Set_Last_Entity  (Derived_Type, Last_Entity  (Der_Base));
5985             Set_Stored_Constraint (Full_Der, Stored_Constraint (Derived_Type));
5986
5987          else
5988             --  If this is a completion, the derived type stays private and
5989             --  there is no need to create a further full view, except in the
5990             --  unusual case when the derivation is nested within a child unit,
5991             --  see below.
5992
5993             null;
5994          end if;
5995
5996       elsif Present (Full_View (Parent_Type))
5997         and then  Has_Discriminants (Full_View (Parent_Type))
5998       then
5999          if Has_Unknown_Discriminants (Parent_Type)
6000            and then Nkind (Subtype_Indication (Type_Definition (N))) =
6001                                                          N_Subtype_Indication
6002          then
6003             Error_Msg_N
6004               ("cannot constrain type with unknown discriminants",
6005                Subtype_Indication (Type_Definition (N)));
6006             return;
6007          end if;
6008
6009          --  If full view of parent is a record type, build full view as a
6010          --  derivation from the parent's full view. Partial view remains
6011          --  private. For code generation and linking, the full view must have
6012          --  the same public status as the partial one. This full view is only
6013          --  needed if the parent type is in an enclosing scope, so that the
6014          --  full view may actually become visible, e.g. in a child unit. This
6015          --  is both more efficient, and avoids order of freezing problems with
6016          --  the added entities.
6017
6018          if not Is_Private_Type (Full_View (Parent_Type))
6019            and then (In_Open_Scopes (Scope (Parent_Type)))
6020          then
6021             Full_Der := Make_Defining_Identifier (Sloc (Derived_Type),
6022                                               Chars (Derived_Type));
6023             Set_Is_Itype (Full_Der);
6024             Set_Has_Private_Declaration (Full_Der);
6025             Set_Has_Private_Declaration (Derived_Type);
6026             Set_Associated_Node_For_Itype (Full_Der, N);
6027             Set_Parent (Full_Der, Parent (Derived_Type));
6028             Set_Full_View (Derived_Type, Full_Der);
6029             Set_Is_Public (Full_Der, Is_Public (Derived_Type));
6030             Full_P := Full_View (Parent_Type);
6031             Exchange_Declarations (Parent_Type);
6032             Copy_And_Build;
6033             Exchange_Declarations (Full_P);
6034
6035          else
6036             Build_Derived_Record_Type
6037               (N, Full_View (Parent_Type), Derived_Type,
6038                 Derive_Subps => False);
6039          end if;
6040
6041          --  In any case, the primitive operations are inherited from the
6042          --  parent type, not from the internal full view.
6043
6044          Set_Etype (Base_Type (Derived_Type), Base_Type (Parent_Type));
6045
6046          if Derive_Subps then
6047             Derive_Subprograms (Parent_Type, Derived_Type);
6048          end if;
6049
6050       else
6051          --  Untagged type, No discriminants on either view
6052
6053          if Nkind (Subtype_Indication (Type_Definition (N))) =
6054                                                    N_Subtype_Indication
6055          then
6056             Error_Msg_N
6057               ("illegal constraint on type without discriminants", N);
6058          end if;
6059
6060          if Present (Discriminant_Specifications (N))
6061            and then Present (Full_View (Parent_Type))
6062            and then not Is_Tagged_Type (Full_View (Parent_Type))
6063          then
6064             Error_Msg_N ("cannot add discriminants to untagged type", N);
6065          end if;
6066
6067          Set_Stored_Constraint (Derived_Type, No_Elist);
6068          Set_Is_Constrained    (Derived_Type, Is_Constrained (Parent_Type));
6069          Set_Is_Controlled     (Derived_Type, Is_Controlled  (Parent_Type));
6070          Set_Has_Controlled_Component
6071                                (Derived_Type, Has_Controlled_Component
6072                                                              (Parent_Type));
6073
6074          --  Direct controlled types do not inherit Finalize_Storage_Only flag
6075
6076          if not Is_Controlled  (Parent_Type) then
6077             Set_Finalize_Storage_Only
6078               (Base_Type (Derived_Type), Finalize_Storage_Only (Parent_Type));
6079          end if;
6080
6081          --  Construct the implicit full view by deriving from full view of the
6082          --  parent type. In order to get proper visibility, we install the
6083          --  parent scope and its declarations.
6084
6085          --  ??? If the parent is untagged private and its completion is
6086          --  tagged, this mechanism will not work because we cannot derive from
6087          --  the tagged full view unless we have an extension.
6088
6089          if Present (Full_View (Parent_Type))
6090            and then not Is_Tagged_Type (Full_View (Parent_Type))
6091            and then not Is_Completion
6092          then
6093             Full_Der :=
6094               Make_Defining_Identifier (Sloc (Derived_Type),
6095                 Chars => Chars (Derived_Type));
6096             Set_Is_Itype (Full_Der);
6097             Set_Has_Private_Declaration (Full_Der);
6098             Set_Has_Private_Declaration (Derived_Type);
6099             Set_Associated_Node_For_Itype (Full_Der, N);
6100             Set_Parent (Full_Der, Parent (Derived_Type));
6101             Set_Full_View (Derived_Type, Full_Der);
6102
6103             if not In_Open_Scopes (Par_Scope) then
6104                Install_Private_Declarations (Par_Scope);
6105                Install_Visible_Declarations (Par_Scope);
6106                Copy_And_Build;
6107                Uninstall_Declarations (Par_Scope);
6108
6109             --  If parent scope is open and in another unit, and parent has a
6110             --  completion, then the derivation is taking place in the visible
6111             --  part of a child unit. In that case retrieve the full view of
6112             --  the parent momentarily.
6113
6114             elsif not In_Same_Source_Unit (N, Parent_Type) then
6115                Full_P := Full_View (Parent_Type);
6116                Exchange_Declarations (Parent_Type);
6117                Copy_And_Build;
6118                Exchange_Declarations (Full_P);
6119
6120             --  Otherwise it is a local derivation
6121
6122             else
6123                Copy_And_Build;
6124             end if;
6125
6126             Set_Scope                (Full_Der, Current_Scope);
6127             Set_Is_First_Subtype     (Full_Der,
6128                                        Is_First_Subtype (Derived_Type));
6129             Set_Has_Size_Clause      (Full_Der, False);
6130             Set_Has_Alignment_Clause (Full_Der, False);
6131             Set_Next_Entity          (Full_Der, Empty);
6132             Set_Has_Delayed_Freeze   (Full_Der);
6133             Set_Is_Frozen            (Full_Der, False);
6134             Set_Freeze_Node          (Full_Der, Empty);
6135             Set_Depends_On_Private   (Full_Der,
6136                                        Has_Private_Component (Full_Der));
6137             Set_Public_Status        (Full_Der);
6138          end if;
6139       end if;
6140
6141       Set_Has_Unknown_Discriminants (Derived_Type,
6142         Has_Unknown_Discriminants (Parent_Type));
6143
6144       if Is_Private_Type (Derived_Type) then
6145          Set_Private_Dependents (Derived_Type, New_Elmt_List);
6146       end if;
6147
6148       if Is_Private_Type (Parent_Type)
6149         and then Base_Type (Parent_Type) = Parent_Type
6150         and then In_Open_Scopes (Scope (Parent_Type))
6151       then
6152          Append_Elmt (Derived_Type, Private_Dependents (Parent_Type));
6153
6154          if Is_Child_Unit (Scope (Current_Scope))
6155            and then Is_Completion
6156            and then In_Private_Part (Current_Scope)
6157            and then Scope (Parent_Type) /= Current_Scope
6158          then
6159             --  This is the unusual case where a type completed by a private
6160             --  derivation occurs within a package nested in a child unit, and
6161             --  the parent is declared in an ancestor. In this case, the full
6162             --  view of the parent type will become visible in the body of
6163             --  the enclosing child, and only then will the current type be
6164             --  possibly non-private. We build a underlying full view that
6165             --  will be installed when the enclosing child body is compiled.
6166
6167             Full_Der :=
6168               Make_Defining_Identifier (Sloc (Derived_Type),
6169                 Chars => Chars (Derived_Type));
6170             Set_Is_Itype (Full_Der);
6171             Build_Itype_Reference (Full_Der, N);
6172
6173             --  The full view will be used to swap entities on entry/exit to
6174             --  the body, and must appear in the entity list for the package.
6175
6176             Append_Entity (Full_Der, Scope (Derived_Type));
6177             Set_Has_Private_Declaration (Full_Der);
6178             Set_Has_Private_Declaration (Derived_Type);
6179             Set_Associated_Node_For_Itype (Full_Der, N);
6180             Set_Parent (Full_Der, Parent (Derived_Type));
6181             Full_P := Full_View (Parent_Type);
6182             Exchange_Declarations (Parent_Type);
6183             Copy_And_Build;
6184             Exchange_Declarations (Full_P);
6185             Set_Underlying_Full_View (Derived_Type, Full_Der);
6186          end if;
6187       end if;
6188    end Build_Derived_Private_Type;
6189
6190    -------------------------------
6191    -- Build_Derived_Record_Type --
6192    -------------------------------
6193
6194    --  1. INTRODUCTION
6195
6196    --  Ideally we would like to use the same model of type derivation for
6197    --  tagged and untagged record types. Unfortunately this is not quite
6198    --  possible because the semantics of representation clauses is different
6199    --  for tagged and untagged records under inheritance. Consider the
6200    --  following:
6201
6202    --     type R (...) is [tagged] record ... end record;
6203    --     type T (...) is new R (...) [with ...];
6204
6205    --  The representation clauses for T can specify a completely different
6206    --  record layout from R's. Hence the same component can be placed in two
6207    --  very different positions in objects of type T and R. If R and T are
6208    --  tagged types, representation clauses for T can only specify the layout
6209    --  of non inherited components, thus components that are common in R and T
6210    --  have the same position in objects of type R and T.
6211
6212    --  This has two implications. The first is that the entire tree for R's
6213    --  declaration needs to be copied for T in the untagged case, so that T
6214    --  can be viewed as a record type of its own with its own representation
6215    --  clauses. The second implication is the way we handle discriminants.
6216    --  Specifically, in the untagged case we need a way to communicate to Gigi
6217    --  what are the real discriminants in the record, while for the semantics
6218    --  we need to consider those introduced by the user to rename the
6219    --  discriminants in the parent type. This is handled by introducing the
6220    --  notion of stored discriminants. See below for more.
6221
6222    --  Fortunately the way regular components are inherited can be handled in
6223    --  the same way in tagged and untagged types.
6224
6225    --  To complicate things a bit more the private view of a private extension
6226    --  cannot be handled in the same way as the full view (for one thing the
6227    --  semantic rules are somewhat different). We will explain what differs
6228    --  below.
6229
6230    --  2. DISCRIMINANTS UNDER INHERITANCE
6231
6232    --  The semantic rules governing the discriminants of derived types are
6233    --  quite subtle.
6234
6235    --   type Derived_Type_Name [KNOWN_DISCRIMINANT_PART] is new
6236    --      [abstract] Parent_Type_Name [CONSTRAINT] [RECORD_EXTENSION_PART]
6237
6238    --  If parent type has discriminants, then the discriminants that are
6239    --  declared in the derived type are [3.4 (11)]:
6240
6241    --  o The discriminants specified by a new KNOWN_DISCRIMINANT_PART, if
6242    --    there is one;
6243
6244    --  o Otherwise, each discriminant of the parent type (implicitly declared
6245    --    in the same order with the same specifications). In this case, the
6246    --    discriminants are said to be "inherited", or if unknown in the parent
6247    --    are also unknown in the derived type.
6248
6249    --  Furthermore if a KNOWN_DISCRIMINANT_PART is provided, then [3.7(13-18)]:
6250
6251    --  o The parent subtype shall be constrained;
6252
6253    --  o If the parent type is not a tagged type, then each discriminant of
6254    --    the derived type shall be used in the constraint defining a parent
6255    --    subtype. [Implementation note: This ensures that the new discriminant
6256    --    can share storage with an existing discriminant.]
6257
6258    --  For the derived type each discriminant of the parent type is either
6259    --  inherited, constrained to equal some new discriminant of the derived
6260    --  type, or constrained to the value of an expression.
6261
6262    --  When inherited or constrained to equal some new discriminant, the
6263    --  parent discriminant and the discriminant of the derived type are said
6264    --  to "correspond".
6265
6266    --  If a discriminant of the parent type is constrained to a specific value
6267    --  in the derived type definition, then the discriminant is said to be
6268    --  "specified" by that derived type definition.
6269
6270    --  3. DISCRIMINANTS IN DERIVED UNTAGGED RECORD TYPES
6271
6272    --  We have spoken about stored discriminants in point 1 (introduction)
6273    --  above. There are two sort of stored discriminants: implicit and
6274    --  explicit. As long as the derived type inherits the same discriminants as
6275    --  the root record type, stored discriminants are the same as regular
6276    --  discriminants, and are said to be implicit. However, if any discriminant
6277    --  in the root type was renamed in the derived type, then the derived
6278    --  type will contain explicit stored discriminants. Explicit stored
6279    --  discriminants are discriminants in addition to the semantically visible
6280    --  discriminants defined for the derived type. Stored discriminants are
6281    --  used by Gigi to figure out what are the physical discriminants in
6282    --  objects of the derived type (see precise definition in einfo.ads).
6283    --  As an example, consider the following:
6284
6285    --           type R  (D1, D2, D3 : Int) is record ... end record;
6286    --           type T1 is new R;
6287    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1);
6288    --           type T3 is new T2;
6289    --           type T4 (Y : Int) is new T3 (Y, 99);
6290
6291    --  The following table summarizes the discriminants and stored
6292    --  discriminants in R and T1 through T4.
6293
6294    --   Type      Discrim     Stored Discrim  Comment
6295    --    R      (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in R
6296    --    T1     (D1, D2, D3)   (D1, D2, D3)   Girder discrims implicit in T1
6297    --    T2     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T2
6298    --    T3     (X1, X2)       (D1, D2, D3)   Girder discrims EXPLICIT in T3
6299    --    T4     (Y)            (D1, D2, D3)   Girder discrims EXPLICIT in T4
6300
6301    --  Field Corresponding_Discriminant (abbreviated CD below) allows us to
6302    --  find the corresponding discriminant in the parent type, while
6303    --  Original_Record_Component (abbreviated ORC below), the actual physical
6304    --  component that is renamed. Finally the field Is_Completely_Hidden
6305    --  (abbreviated ICH below) is set for all explicit stored discriminants
6306    --  (see einfo.ads for more info). For the above example this gives:
6307
6308    --                 Discrim     CD        ORC     ICH
6309    --                 ^^^^^^^     ^^        ^^^     ^^^
6310    --                 D1 in R    empty     itself    no
6311    --                 D2 in R    empty     itself    no
6312    --                 D3 in R    empty     itself    no
6313
6314    --                 D1 in T1  D1 in R    itself    no
6315    --                 D2 in T1  D2 in R    itself    no
6316    --                 D3 in T1  D3 in R    itself    no
6317
6318    --                 X1 in T2  D3 in T1  D3 in T2   no
6319    --                 X2 in T2  D1 in T1  D1 in T2   no
6320    --                 D1 in T2   empty    itself    yes
6321    --                 D2 in T2   empty    itself    yes
6322    --                 D3 in T2   empty    itself    yes
6323
6324    --                 X1 in T3  X1 in T2  D3 in T3   no
6325    --                 X2 in T3  X2 in T2  D1 in T3   no
6326    --                 D1 in T3   empty    itself    yes
6327    --                 D2 in T3   empty    itself    yes
6328    --                 D3 in T3   empty    itself    yes
6329
6330    --                 Y  in T4  X1 in T3  D3 in T3   no
6331    --                 D1 in T3   empty    itself    yes
6332    --                 D2 in T3   empty    itself    yes
6333    --                 D3 in T3   empty    itself    yes
6334
6335    --  4. DISCRIMINANTS IN DERIVED TAGGED RECORD TYPES
6336
6337    --  Type derivation for tagged types is fairly straightforward. If no
6338    --  discriminants are specified by the derived type, these are inherited
6339    --  from the parent. No explicit stored discriminants are ever necessary.
6340    --  The only manipulation that is done to the tree is that of adding a
6341    --  _parent field with parent type and constrained to the same constraint
6342    --  specified for the parent in the derived type definition. For instance:
6343
6344    --           type R  (D1, D2, D3 : Int) is tagged record ... end record;
6345    --           type T1 is new R with null record;
6346    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with null record;
6347
6348    --  are changed into:
6349
6350    --           type T1 (D1, D2, D3 : Int) is new R (D1, D2, D3) with record
6351    --              _parent : R (D1, D2, D3);
6352    --           end record;
6353
6354    --           type T2 (X1, X2: Int) is new T1 (X2, 88, X1) with record
6355    --              _parent : T1 (X2, 88, X1);
6356    --           end record;
6357
6358    --  The discriminants actually present in R, T1 and T2 as well as their CD,
6359    --  ORC and ICH fields are:
6360
6361    --                 Discrim     CD        ORC     ICH
6362    --                 ^^^^^^^     ^^        ^^^     ^^^
6363    --                 D1 in R    empty     itself    no
6364    --                 D2 in R    empty     itself    no
6365    --                 D3 in R    empty     itself    no
6366
6367    --                 D1 in T1  D1 in R    D1 in R   no
6368    --                 D2 in T1  D2 in R    D2 in R   no
6369    --                 D3 in T1  D3 in R    D3 in R   no
6370
6371    --                 X1 in T2  D3 in T1   D3 in R   no
6372    --                 X2 in T2  D1 in T1   D1 in R   no
6373
6374    --  5. FIRST TRANSFORMATION FOR DERIVED RECORDS
6375    --
6376    --  Regardless of whether we dealing with a tagged or untagged type
6377    --  we will transform all derived type declarations of the form
6378    --
6379    --               type T is new R (...) [with ...];
6380    --  or
6381    --               subtype S is R (...);
6382    --               type T is new S [with ...];
6383    --  into
6384    --               type BT is new R [with ...];
6385    --               subtype T is BT (...);
6386    --
6387    --  That is, the base derived type is constrained only if it has no
6388    --  discriminants. The reason for doing this is that GNAT's semantic model
6389    --  assumes that a base type with discriminants is unconstrained.
6390    --
6391    --  Note that, strictly speaking, the above transformation is not always
6392    --  correct. Consider for instance the following excerpt from ACVC b34011a:
6393    --
6394    --       procedure B34011A is
6395    --          type REC (D : integer := 0) is record
6396    --             I : Integer;
6397    --          end record;
6398
6399    --          package P is
6400    --             type T6 is new Rec;
6401    --             function F return T6;
6402    --          end P;
6403
6404    --          use P;
6405    --          package Q6 is
6406    --             type U is new T6 (Q6.F.I);                   -- ERROR: Q6.F.
6407    --          end Q6;
6408    --
6409    --  The definition of Q6.U is illegal. However transforming Q6.U into
6410
6411    --             type BaseU is new T6;
6412    --             subtype U is BaseU (Q6.F.I)
6413
6414    --  turns U into a legal subtype, which is incorrect. To avoid this problem
6415    --  we always analyze the constraint (in this case (Q6.F.I)) before applying
6416    --  the transformation described above.
6417
6418    --  There is another instance where the above transformation is incorrect.
6419    --  Consider:
6420
6421    --          package Pack is
6422    --             type Base (D : Integer) is tagged null record;
6423    --             procedure P (X : Base);
6424
6425    --             type Der is new Base (2) with null record;
6426    --             procedure P (X : Der);
6427    --          end Pack;
6428
6429    --  Then the above transformation turns this into
6430
6431    --             type Der_Base is new Base with null record;
6432    --             --  procedure P (X : Base) is implicitly inherited here
6433    --             --  as procedure P (X : Der_Base).
6434
6435    --             subtype Der is Der_Base (2);
6436    --             procedure P (X : Der);
6437    --             --  The overriding of P (X : Der_Base) is illegal since we
6438    --             --  have a parameter conformance problem.
6439
6440    --  To get around this problem, after having semantically processed Der_Base
6441    --  and the rewritten subtype declaration for Der, we copy Der_Base field
6442    --  Discriminant_Constraint from Der so that when parameter conformance is
6443    --  checked when P is overridden, no semantic errors are flagged.
6444
6445    --  6. SECOND TRANSFORMATION FOR DERIVED RECORDS
6446
6447    --  Regardless of whether we are dealing with a tagged or untagged type
6448    --  we will transform all derived type declarations of the form
6449
6450    --               type R (D1, .., Dn : ...) is [tagged] record ...;
6451    --               type T is new R [with ...];
6452    --  into
6453    --               type T (D1, .., Dn : ...) is new R (D1, .., Dn) [with ...];
6454
6455    --  The reason for such transformation is that it allows us to implement a
6456    --  very clean form of component inheritance as explained below.
6457
6458    --  Note that this transformation is not achieved by direct tree rewriting
6459    --  and manipulation, but rather by redoing the semantic actions that the
6460    --  above transformation will entail. This is done directly in routine
6461    --  Inherit_Components.
6462
6463    --  7. TYPE DERIVATION AND COMPONENT INHERITANCE
6464
6465    --  In both tagged and untagged derived types, regular non discriminant
6466    --  components are inherited in the derived type from the parent type. In
6467    --  the absence of discriminants component, inheritance is straightforward
6468    --  as components can simply be copied from the parent.
6469
6470    --  If the parent has discriminants, inheriting components constrained with
6471    --  these discriminants requires caution. Consider the following example:
6472
6473    --      type R  (D1, D2 : Positive) is [tagged] record
6474    --         S : String (D1 .. D2);
6475    --      end record;
6476
6477    --      type T1                is new R        [with null record];
6478    --      type T2 (X : positive) is new R (1, X) [with null record];
6479
6480    --  As explained in 6. above, T1 is rewritten as
6481    --      type T1 (D1, D2 : Positive) is new R (D1, D2) [with null record];
6482    --  which makes the treatment for T1 and T2 identical.
6483
6484    --  What we want when inheriting S, is that references to D1 and D2 in R are
6485    --  replaced with references to their correct constraints, i.e. D1 and D2 in
6486    --  T1 and 1 and X in T2. So all R's discriminant references are replaced
6487    --  with either discriminant references in the derived type or expressions.
6488    --  This replacement is achieved as follows: before inheriting R's
6489    --  components, a subtype R (D1, D2) for T1 (resp. R (1, X) for T2) is
6490    --  created in the scope of T1 (resp. scope of T2) so that discriminants D1
6491    --  and D2 of T1 are visible (resp. discriminant X of T2 is visible).
6492    --  For T2, for instance, this has the effect of replacing String (D1 .. D2)
6493    --  by String (1 .. X).
6494
6495    --  8. TYPE DERIVATION IN PRIVATE TYPE EXTENSIONS
6496
6497    --  We explain here the rules governing private type extensions relevant to
6498    --  type derivation. These rules are explained on the following example:
6499
6500    --      type D [(...)] is new A [(...)] with private;      <-- partial view
6501    --      type D [(...)] is new P [(...)] with null record;  <-- full view
6502
6503    --  Type A is called the ancestor subtype of the private extension.
6504    --  Type P is the parent type of the full view of the private extension. It
6505    --  must be A or a type derived from A.
6506
6507    --  The rules concerning the discriminants of private type extensions are
6508    --  [7.3(10-13)]:
6509
6510    --  o If a private extension inherits known discriminants from the ancestor
6511    --    subtype, then the full view shall also inherit its discriminants from
6512    --    the ancestor subtype and the parent subtype of the full view shall be
6513    --    constrained if and only if the ancestor subtype is constrained.
6514
6515    --  o If a partial view has unknown discriminants, then the full view may
6516    --    define a definite or an indefinite subtype, with or without
6517    --    discriminants.
6518
6519    --  o If a partial view has neither known nor unknown discriminants, then
6520    --    the full view shall define a definite subtype.
6521
6522    --  o If the ancestor subtype of a private extension has constrained
6523    --    discriminants, then the parent subtype of the full view shall impose a
6524    --    statically matching constraint on those discriminants.
6525
6526    --  This means that only the following forms of private extensions are
6527    --  allowed:
6528
6529    --      type D is new A with private;      <-- partial view
6530    --      type D is new P with null record;  <-- full view
6531
6532    --  If A has no discriminants than P has no discriminants, otherwise P must
6533    --  inherit A's discriminants.
6534
6535    --      type D is new A (...) with private;      <-- partial view
6536    --      type D is new P (:::) with null record;  <-- full view
6537
6538    --  P must inherit A's discriminants and (...) and (:::) must statically
6539    --  match.
6540
6541    --      subtype A is R (...);
6542    --      type D is new A with private;      <-- partial view
6543    --      type D is new P with null record;  <-- full view
6544
6545    --  P must have inherited R's discriminants and must be derived from A or
6546    --  any of its subtypes.
6547
6548    --      type D (..) is new A with private;              <-- partial view
6549    --      type D (..) is new P [(:::)] with null record;  <-- full view
6550
6551    --  No specific constraints on P's discriminants or constraint (:::).
6552    --  Note that A can be unconstrained, but the parent subtype P must either
6553    --  be constrained or (:::) must be present.
6554
6555    --      type D (..) is new A [(...)] with private;      <-- partial view
6556    --      type D (..) is new P [(:::)] with null record;  <-- full view
6557
6558    --  P's constraints on A's discriminants must statically match those
6559    --  imposed by (...).
6560
6561    --  9. IMPLEMENTATION OF TYPE DERIVATION FOR PRIVATE EXTENSIONS
6562
6563    --  The full view of a private extension is handled exactly as described
6564    --  above. The model chose for the private view of a private extension is
6565    --  the same for what concerns discriminants (i.e. they receive the same
6566    --  treatment as in the tagged case). However, the private view of the
6567    --  private extension always inherits the components of the parent base,
6568    --  without replacing any discriminant reference. Strictly speaking this is
6569    --  incorrect. However, Gigi never uses this view to generate code so this
6570    --  is a purely semantic issue. In theory, a set of transformations similar
6571    --  to those given in 5. and 6. above could be applied to private views of
6572    --  private extensions to have the same model of component inheritance as
6573    --  for non private extensions. However, this is not done because it would
6574    --  further complicate private type processing. Semantically speaking, this
6575    --  leaves us in an uncomfortable situation. As an example consider:
6576
6577    --          package Pack is
6578    --             type R (D : integer) is tagged record
6579    --                S : String (1 .. D);
6580    --             end record;
6581    --             procedure P (X : R);
6582    --             type T is new R (1) with private;
6583    --          private
6584    --             type T is new R (1) with null record;
6585    --          end;
6586
6587    --  This is transformed into:
6588
6589    --          package Pack is
6590    --             type R (D : integer) is tagged record
6591    --                S : String (1 .. D);
6592    --             end record;
6593    --             procedure P (X : R);
6594    --             type T is new R (1) with private;
6595    --          private
6596    --             type BaseT is new R with null record;
6597    --             subtype  T is BaseT (1);
6598    --          end;
6599
6600    --  (strictly speaking the above is incorrect Ada)
6601
6602    --  From the semantic standpoint the private view of private extension T
6603    --  should be flagged as constrained since one can clearly have
6604    --
6605    --             Obj : T;
6606    --
6607    --  in a unit withing Pack. However, when deriving subprograms for the
6608    --  private view of private extension T, T must be seen as unconstrained
6609    --  since T has discriminants (this is a constraint of the current
6610    --  subprogram derivation model). Thus, when processing the private view of
6611    --  a private extension such as T, we first mark T as unconstrained, we
6612    --  process it, we perform program derivation and just before returning from
6613    --  Build_Derived_Record_Type we mark T as constrained.
6614
6615    --  ??? Are there are other uncomfortable cases that we will have to
6616    --      deal with.
6617
6618    --  10. RECORD_TYPE_WITH_PRIVATE complications
6619
6620    --  Types that are derived from a visible record type and have a private
6621    --  extension present other peculiarities. They behave mostly like private
6622    --  types, but if they have primitive operations defined, these will not
6623    --  have the proper signatures for further inheritance, because other
6624    --  primitive operations will use the implicit base that we define for
6625    --  private derivations below. This affect subprogram inheritance (see
6626    --  Derive_Subprograms for details). We also derive the implicit base from
6627    --  the base type of the full view, so that the implicit base is a record
6628    --  type and not another private type, This avoids infinite loops.
6629
6630    procedure Build_Derived_Record_Type
6631      (N            : Node_Id;
6632       Parent_Type  : Entity_Id;
6633       Derived_Type : Entity_Id;
6634       Derive_Subps : Boolean := True)
6635    is
6636       Loc          : constant Source_Ptr := Sloc (N);
6637       Parent_Base  : Entity_Id;
6638       Type_Def     : Node_Id;
6639       Indic        : Node_Id;
6640       Discrim      : Entity_Id;
6641       Last_Discrim : Entity_Id;
6642       Constrs      : Elist_Id;
6643
6644       Discs : Elist_Id := New_Elmt_List;
6645       --  An empty Discs list means that there were no constraints in the
6646       --  subtype indication or that there was an error processing it.
6647
6648       Assoc_List : Elist_Id;
6649       New_Discrs : Elist_Id;
6650       New_Base   : Entity_Id;
6651       New_Decl   : Node_Id;
6652       New_Indic  : Node_Id;
6653
6654       Is_Tagged          : constant Boolean := Is_Tagged_Type (Parent_Type);
6655       Discriminant_Specs : constant Boolean :=
6656                              Present (Discriminant_Specifications (N));
6657       Private_Extension  : constant Boolean :=
6658                              Nkind (N) = N_Private_Extension_Declaration;
6659
6660       Constraint_Present : Boolean;
6661       Inherit_Discrims   : Boolean := False;
6662       Save_Etype         : Entity_Id;
6663       Save_Discr_Constr  : Elist_Id;
6664       Save_Next_Entity   : Entity_Id;
6665
6666    begin
6667       if Ekind (Parent_Type) = E_Record_Type_With_Private
6668         and then Present (Full_View (Parent_Type))
6669         and then Has_Discriminants (Parent_Type)
6670       then
6671          Parent_Base := Base_Type (Full_View (Parent_Type));
6672       else
6673          Parent_Base := Base_Type (Parent_Type);
6674       end if;
6675
6676       --  Before we start the previously documented transformations, here is
6677       --  little fix for size and alignment of tagged types. Normally when we
6678       --  derive type D from type P, we copy the size and alignment of P as the
6679       --  default for D, and in the absence of explicit representation clauses
6680       --  for D, the size and alignment are indeed the same as the parent.
6681
6682       --  But this is wrong for tagged types, since fields may be added, and
6683       --  the default size may need to be larger, and the default alignment may
6684       --  need to be larger.
6685
6686       --  We therefore reset the size and alignment fields in the tagged case.
6687       --  Note that the size and alignment will in any case be at least as
6688       --  large as the parent type (since the derived type has a copy of the
6689       --  parent type in the _parent field)
6690
6691       --  The type is also marked as being tagged here, which is needed when
6692       --  processing components with a self-referential anonymous access type
6693       --  in the call to Check_Anonymous_Access_Components below. Note that
6694       --  this flag is also set later on for completeness.
6695
6696       if Is_Tagged then
6697          Set_Is_Tagged_Type (Derived_Type);
6698          Init_Size_Align    (Derived_Type);
6699       end if;
6700
6701       --  STEP 0a: figure out what kind of derived type declaration we have
6702
6703       if Private_Extension then
6704          Type_Def := N;
6705          Set_Ekind (Derived_Type, E_Record_Type_With_Private);
6706
6707       else
6708          Type_Def := Type_Definition (N);
6709
6710          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
6711          --  Parent_Base can be a private type or private extension. However,
6712          --  for tagged types with an extension the newly added fields are
6713          --  visible and hence the Derived_Type is always an E_Record_Type.
6714          --  (except that the parent may have its own private fields).
6715          --  For untagged types we preserve the Ekind of the Parent_Base.
6716
6717          if Present (Record_Extension_Part (Type_Def)) then
6718             Set_Ekind (Derived_Type, E_Record_Type);
6719
6720             --  Create internal access types for components with anonymous
6721             --  access types.
6722
6723             if Ada_Version >= Ada_2005 then
6724                Check_Anonymous_Access_Components
6725                  (N, Derived_Type, Derived_Type,
6726                    Component_List (Record_Extension_Part (Type_Def)));
6727             end if;
6728
6729          else
6730             Set_Ekind (Derived_Type, Ekind (Parent_Base));
6731          end if;
6732       end if;
6733
6734       --  Indic can either be an N_Identifier if the subtype indication
6735       --  contains no constraint or an N_Subtype_Indication if the subtype
6736       --  indication has a constraint.
6737
6738       Indic := Subtype_Indication (Type_Def);
6739       Constraint_Present := (Nkind (Indic) = N_Subtype_Indication);
6740
6741       --  Check that the type has visible discriminants. The type may be
6742       --  a private type with unknown discriminants whose full view has
6743       --  discriminants which are invisible.
6744
6745       if Constraint_Present then
6746          if not Has_Discriminants (Parent_Base)
6747            or else
6748              (Has_Unknown_Discriminants (Parent_Base)
6749                 and then Is_Private_Type (Parent_Base))
6750          then
6751             Error_Msg_N
6752               ("invalid constraint: type has no discriminant",
6753                  Constraint (Indic));
6754
6755             Constraint_Present := False;
6756             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6757
6758          elsif Is_Constrained (Parent_Type) then
6759             Error_Msg_N
6760                ("invalid constraint: parent type is already constrained",
6761                   Constraint (Indic));
6762
6763             Constraint_Present := False;
6764             Rewrite (Indic, New_Copy_Tree (Subtype_Mark (Indic)));
6765          end if;
6766       end if;
6767
6768       --  STEP 0b: If needed, apply transformation given in point 5. above
6769
6770       if not Private_Extension
6771         and then Has_Discriminants (Parent_Type)
6772         and then not Discriminant_Specs
6773         and then (Is_Constrained (Parent_Type) or else Constraint_Present)
6774       then
6775          --  First, we must analyze the constraint (see comment in point 5.)
6776
6777          if Constraint_Present then
6778             New_Discrs := Build_Discriminant_Constraints (Parent_Type, Indic);
6779
6780             if Has_Discriminants (Derived_Type)
6781               and then Has_Private_Declaration (Derived_Type)
6782               and then Present (Discriminant_Constraint (Derived_Type))
6783             then
6784                --  Verify that constraints of the full view statically match
6785                --  those given in the partial view.
6786
6787                declare
6788                   C1, C2 : Elmt_Id;
6789
6790                begin
6791                   C1 := First_Elmt (New_Discrs);
6792                   C2 := First_Elmt (Discriminant_Constraint (Derived_Type));
6793                   while Present (C1) and then Present (C2) loop
6794                      if Fully_Conformant_Expressions (Node (C1), Node (C2))
6795                        or else
6796                          (Is_OK_Static_Expression (Node (C1))
6797                             and then
6798                           Is_OK_Static_Expression (Node (C2))
6799                             and then
6800                           Expr_Value (Node (C1)) = Expr_Value (Node (C2)))
6801                      then
6802                         null;
6803
6804                      else
6805                         Error_Msg_N (
6806                           "constraint not conformant to previous declaration",
6807                              Node (C1));
6808                      end if;
6809
6810                      Next_Elmt (C1);
6811                      Next_Elmt (C2);
6812                   end loop;
6813                end;
6814             end if;
6815          end if;
6816
6817          --  Insert and analyze the declaration for the unconstrained base type
6818
6819          New_Base := Create_Itype (Ekind (Derived_Type), N, Derived_Type, 'B');
6820
6821          New_Decl :=
6822            Make_Full_Type_Declaration (Loc,
6823               Defining_Identifier => New_Base,
6824               Type_Definition     =>
6825                 Make_Derived_Type_Definition (Loc,
6826                   Abstract_Present      => Abstract_Present (Type_Def),
6827                   Limited_Present       => Limited_Present (Type_Def),
6828                   Subtype_Indication    =>
6829                     New_Occurrence_Of (Parent_Base, Loc),
6830                   Record_Extension_Part =>
6831                     Relocate_Node (Record_Extension_Part (Type_Def)),
6832                   Interface_List        => Interface_List (Type_Def)));
6833
6834          Set_Parent (New_Decl, Parent (N));
6835          Mark_Rewrite_Insertion (New_Decl);
6836          Insert_Before (N, New_Decl);
6837
6838          --  In the extension case, make sure ancestor is frozen appropriately
6839          --  (see also non-discriminated case below).
6840
6841          if Present (Record_Extension_Part (Type_Def))
6842            or else Is_Interface (Parent_Base)
6843          then
6844             Freeze_Before (New_Decl, Parent_Type);
6845          end if;
6846
6847          --  Note that this call passes False for the Derive_Subps parameter
6848          --  because subprogram derivation is deferred until after creating
6849          --  the subtype (see below).
6850
6851          Build_Derived_Type
6852            (New_Decl, Parent_Base, New_Base,
6853             Is_Completion => True, Derive_Subps => False);
6854
6855          --  ??? This needs re-examination to determine whether the
6856          --  above call can simply be replaced by a call to Analyze.
6857
6858          Set_Analyzed (New_Decl);
6859
6860          --  Insert and analyze the declaration for the constrained subtype
6861
6862          if Constraint_Present then
6863             New_Indic :=
6864               Make_Subtype_Indication (Loc,
6865                 Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6866                 Constraint   => Relocate_Node (Constraint (Indic)));
6867
6868          else
6869             declare
6870                Constr_List : constant List_Id := New_List;
6871                C           : Elmt_Id;
6872                Expr        : Node_Id;
6873
6874             begin
6875                C := First_Elmt (Discriminant_Constraint (Parent_Type));
6876                while Present (C) loop
6877                   Expr := Node (C);
6878
6879                   --  It is safe here to call New_Copy_Tree since
6880                   --  Force_Evaluation was called on each constraint in
6881                   --  Build_Discriminant_Constraints.
6882
6883                   Append (New_Copy_Tree (Expr), To => Constr_List);
6884
6885                   Next_Elmt (C);
6886                end loop;
6887
6888                New_Indic :=
6889                  Make_Subtype_Indication (Loc,
6890                    Subtype_Mark => New_Occurrence_Of (New_Base, Loc),
6891                    Constraint   =>
6892                      Make_Index_Or_Discriminant_Constraint (Loc, Constr_List));
6893             end;
6894          end if;
6895
6896          Rewrite (N,
6897            Make_Subtype_Declaration (Loc,
6898              Defining_Identifier => Derived_Type,
6899              Subtype_Indication  => New_Indic));
6900
6901          Analyze (N);
6902
6903          --  Derivation of subprograms must be delayed until the full subtype
6904          --  has been established to ensure proper overriding of subprograms
6905          --  inherited by full types. If the derivations occurred as part of
6906          --  the call to Build_Derived_Type above, then the check for type
6907          --  conformance would fail because earlier primitive subprograms
6908          --  could still refer to the full type prior the change to the new
6909          --  subtype and hence would not match the new base type created here.
6910
6911          Derive_Subprograms (Parent_Type, Derived_Type);
6912
6913          --  For tagged types the Discriminant_Constraint of the new base itype
6914          --  is inherited from the first subtype so that no subtype conformance
6915          --  problem arise when the first subtype overrides primitive
6916          --  operations inherited by the implicit base type.
6917
6918          if Is_Tagged then
6919             Set_Discriminant_Constraint
6920               (New_Base, Discriminant_Constraint (Derived_Type));
6921          end if;
6922
6923          return;
6924       end if;
6925
6926       --  If we get here Derived_Type will have no discriminants or it will be
6927       --  a discriminated unconstrained base type.
6928
6929       --  STEP 1a: perform preliminary actions/checks for derived tagged types
6930
6931       if Is_Tagged then
6932
6933          --  The parent type is frozen for non-private extensions (RM 13.14(7))
6934          --  The declaration of a specific descendant of an interface type
6935          --  freezes the interface type (RM 13.14).
6936
6937          if not Private_Extension or else Is_Interface (Parent_Base) then
6938             Freeze_Before (N, Parent_Type);
6939          end if;
6940
6941          --  In Ada 2005 (AI-344), the restriction that a derived tagged type
6942          --  cannot be declared at a deeper level than its parent type is
6943          --  removed. The check on derivation within a generic body is also
6944          --  relaxed, but there's a restriction that a derived tagged type
6945          --  cannot be declared in a generic body if it's derived directly
6946          --  or indirectly from a formal type of that generic.
6947
6948          if Ada_Version >= Ada_2005 then
6949             if Present (Enclosing_Generic_Body (Derived_Type)) then
6950                declare
6951                   Ancestor_Type : Entity_Id;
6952
6953                begin
6954                   --  Check to see if any ancestor of the derived type is a
6955                   --  formal type.
6956
6957                   Ancestor_Type := Parent_Type;
6958                   while not Is_Generic_Type (Ancestor_Type)
6959                     and then Etype (Ancestor_Type) /= Ancestor_Type
6960                   loop
6961                      Ancestor_Type := Etype (Ancestor_Type);
6962                   end loop;
6963
6964                   --  If the derived type does have a formal type as an
6965                   --  ancestor, then it's an error if the derived type is
6966                   --  declared within the body of the generic unit that
6967                   --  declares the formal type in its generic formal part. It's
6968                   --  sufficient to check whether the ancestor type is declared
6969                   --  inside the same generic body as the derived type (such as
6970                   --  within a nested generic spec), in which case the
6971                   --  derivation is legal. If the formal type is declared
6972                   --  outside of that generic body, then it's guaranteed that
6973                   --  the derived type is declared within the generic body of
6974                   --  the generic unit declaring the formal type.
6975
6976                   if Is_Generic_Type (Ancestor_Type)
6977                     and then Enclosing_Generic_Body (Ancestor_Type) /=
6978                                Enclosing_Generic_Body (Derived_Type)
6979                   then
6980                      Error_Msg_NE
6981                        ("parent type of& must not be descendant of formal type"
6982                           & " of an enclosing generic body",
6983                             Indic, Derived_Type);
6984                   end if;
6985                end;
6986             end if;
6987
6988          elsif Type_Access_Level (Derived_Type) /=
6989                  Type_Access_Level (Parent_Type)
6990            and then not Is_Generic_Type (Derived_Type)
6991          then
6992             if Is_Controlled (Parent_Type) then
6993                Error_Msg_N
6994                  ("controlled type must be declared at the library level",
6995                   Indic);
6996             else
6997                Error_Msg_N
6998                  ("type extension at deeper accessibility level than parent",
6999                   Indic);
7000             end if;
7001
7002          else
7003             declare
7004                GB : constant Node_Id := Enclosing_Generic_Body (Derived_Type);
7005
7006             begin
7007                if Present (GB)
7008                  and then GB /= Enclosing_Generic_Body (Parent_Base)
7009                then
7010                   Error_Msg_NE
7011                     ("parent type of& must not be outside generic body"
7012                        & " (RM 3.9.1(4))",
7013                          Indic, Derived_Type);
7014                end if;
7015             end;
7016          end if;
7017       end if;
7018
7019       --  Ada 2005 (AI-251)
7020
7021       if Ada_Version >= Ada_2005 and then Is_Tagged then
7022
7023          --  "The declaration of a specific descendant of an interface type
7024          --  freezes the interface type" (RM 13.14).
7025
7026          declare
7027             Iface : Node_Id;
7028          begin
7029             if Is_Non_Empty_List (Interface_List (Type_Def)) then
7030                Iface := First (Interface_List (Type_Def));
7031                while Present (Iface) loop
7032                   Freeze_Before (N, Etype (Iface));
7033                   Next (Iface);
7034                end loop;
7035             end if;
7036          end;
7037       end if;
7038
7039       --  STEP 1b : preliminary cleanup of the full view of private types
7040
7041       --  If the type is already marked as having discriminants, then it's the
7042       --  completion of a private type or private extension and we need to
7043       --  retain the discriminants from the partial view if the current
7044       --  declaration has Discriminant_Specifications so that we can verify
7045       --  conformance. However, we must remove any existing components that
7046       --  were inherited from the parent (and attached in Copy_And_Swap)
7047       --  because the full type inherits all appropriate components anyway, and
7048       --  we do not want the partial view's components interfering.
7049
7050       if Has_Discriminants (Derived_Type) and then Discriminant_Specs then
7051          Discrim := First_Discriminant (Derived_Type);
7052          loop
7053             Last_Discrim := Discrim;
7054             Next_Discriminant (Discrim);
7055             exit when No (Discrim);
7056          end loop;
7057
7058          Set_Last_Entity (Derived_Type, Last_Discrim);
7059
7060       --  In all other cases wipe out the list of inherited components (even
7061       --  inherited discriminants), it will be properly rebuilt here.
7062
7063       else
7064          Set_First_Entity (Derived_Type, Empty);
7065          Set_Last_Entity  (Derived_Type, Empty);
7066       end if;
7067
7068       --  STEP 1c: Initialize some flags for the Derived_Type
7069
7070       --  The following flags must be initialized here so that
7071       --  Process_Discriminants can check that discriminants of tagged types do
7072       --  not have a default initial value and that access discriminants are
7073       --  only specified for limited records. For completeness, these flags are
7074       --  also initialized along with all the other flags below.
7075
7076       --  AI-419: Limitedness is not inherited from an interface parent, so to
7077       --  be limited in that case the type must be explicitly declared as
7078       --  limited. However, task and protected interfaces are always limited.
7079
7080       if Limited_Present (Type_Def) then
7081          Set_Is_Limited_Record (Derived_Type);
7082
7083       elsif Is_Limited_Record (Parent_Type)
7084         or else (Present (Full_View (Parent_Type))
7085                    and then Is_Limited_Record (Full_View (Parent_Type)))
7086       then
7087          if not Is_Interface (Parent_Type)
7088            or else Is_Synchronized_Interface (Parent_Type)
7089            or else Is_Protected_Interface (Parent_Type)
7090            or else Is_Task_Interface (Parent_Type)
7091          then
7092             Set_Is_Limited_Record (Derived_Type);
7093          end if;
7094       end if;
7095
7096       --  STEP 2a: process discriminants of derived type if any
7097
7098       Push_Scope (Derived_Type);
7099
7100       if Discriminant_Specs then
7101          Set_Has_Unknown_Discriminants (Derived_Type, False);
7102
7103          --  The following call initializes fields Has_Discriminants and
7104          --  Discriminant_Constraint, unless we are processing the completion
7105          --  of a private type declaration.
7106
7107          Check_Or_Process_Discriminants (N, Derived_Type);
7108
7109          --  For untagged types, the constraint on the Parent_Type must be
7110          --  present and is used to rename the discriminants.
7111
7112          if not Is_Tagged and then not Has_Discriminants (Parent_Type) then
7113             Error_Msg_N ("untagged parent must have discriminants", Indic);
7114
7115          elsif not Is_Tagged and then not Constraint_Present then
7116             Error_Msg_N
7117               ("discriminant constraint needed for derived untagged records",
7118                Indic);
7119
7120          --  Otherwise the parent subtype must be constrained unless we have a
7121          --  private extension.
7122
7123          elsif not Constraint_Present
7124            and then not Private_Extension
7125            and then not Is_Constrained (Parent_Type)
7126          then
7127             Error_Msg_N
7128               ("unconstrained type not allowed in this context", Indic);
7129
7130          elsif Constraint_Present then
7131             --  The following call sets the field Corresponding_Discriminant
7132             --  for the discriminants in the Derived_Type.
7133
7134             Discs := Build_Discriminant_Constraints (Parent_Type, Indic, True);
7135
7136             --  For untagged types all new discriminants must rename
7137             --  discriminants in the parent. For private extensions new
7138             --  discriminants cannot rename old ones (implied by [7.3(13)]).
7139
7140             Discrim := First_Discriminant (Derived_Type);
7141             while Present (Discrim) loop
7142                if not Is_Tagged
7143                  and then No (Corresponding_Discriminant (Discrim))
7144                then
7145                   Error_Msg_N
7146                     ("new discriminants must constrain old ones", Discrim);
7147
7148                elsif Private_Extension
7149                  and then Present (Corresponding_Discriminant (Discrim))
7150                then
7151                   Error_Msg_N
7152                     ("only static constraints allowed for parent"
7153                      & " discriminants in the partial view", Indic);
7154                   exit;
7155                end if;
7156
7157                --  If a new discriminant is used in the constraint, then its
7158                --  subtype must be statically compatible with the parent
7159                --  discriminant's subtype (3.7(15)).
7160
7161                if Present (Corresponding_Discriminant (Discrim))
7162                  and then
7163                    not Subtypes_Statically_Compatible
7164                          (Etype (Discrim),
7165                           Etype (Corresponding_Discriminant (Discrim)))
7166                then
7167                   Error_Msg_N
7168                     ("subtype must be compatible with parent discriminant",
7169                      Discrim);
7170                end if;
7171
7172                Next_Discriminant (Discrim);
7173             end loop;
7174
7175             --  Check whether the constraints of the full view statically
7176             --  match those imposed by the parent subtype [7.3(13)].
7177
7178             if Present (Stored_Constraint (Derived_Type)) then
7179                declare
7180                   C1, C2 : Elmt_Id;
7181
7182                begin
7183                   C1 := First_Elmt (Discs);
7184                   C2 := First_Elmt (Stored_Constraint (Derived_Type));
7185                   while Present (C1) and then Present (C2) loop
7186                      if not
7187                        Fully_Conformant_Expressions (Node (C1), Node (C2))
7188                      then
7189                         Error_Msg_N
7190                           ("not conformant with previous declaration",
7191                            Node (C1));
7192                      end if;
7193
7194                      Next_Elmt (C1);
7195                      Next_Elmt (C2);
7196                   end loop;
7197                end;
7198             end if;
7199          end if;
7200
7201       --  STEP 2b: No new discriminants, inherit discriminants if any
7202
7203       else
7204          if Private_Extension then
7205             Set_Has_Unknown_Discriminants
7206               (Derived_Type,
7207                Has_Unknown_Discriminants (Parent_Type)
7208                  or else Unknown_Discriminants_Present (N));
7209
7210          --  The partial view of the parent may have unknown discriminants,
7211          --  but if the full view has discriminants and the parent type is
7212          --  in scope they must be inherited.
7213
7214          elsif Has_Unknown_Discriminants (Parent_Type)
7215            and then
7216             (not Has_Discriminants (Parent_Type)
7217               or else not In_Open_Scopes (Scope (Parent_Type)))
7218          then
7219             Set_Has_Unknown_Discriminants (Derived_Type);
7220          end if;
7221
7222          if not Has_Unknown_Discriminants (Derived_Type)
7223            and then not Has_Unknown_Discriminants (Parent_Base)
7224            and then Has_Discriminants (Parent_Type)
7225          then
7226             Inherit_Discrims := True;
7227             Set_Has_Discriminants
7228               (Derived_Type, True);
7229             Set_Discriminant_Constraint
7230               (Derived_Type, Discriminant_Constraint (Parent_Base));
7231          end if;
7232
7233          --  The following test is true for private types (remember
7234          --  transformation 5. is not applied to those) and in an error
7235          --  situation.
7236
7237          if Constraint_Present then
7238             Discs := Build_Discriminant_Constraints (Parent_Type, Indic);
7239          end if;
7240
7241          --  For now mark a new derived type as constrained only if it has no
7242          --  discriminants. At the end of Build_Derived_Record_Type we properly
7243          --  set this flag in the case of private extensions. See comments in
7244          --  point 9. just before body of Build_Derived_Record_Type.
7245
7246          Set_Is_Constrained
7247            (Derived_Type,
7248             not (Inherit_Discrims
7249                    or else Has_Unknown_Discriminants (Derived_Type)));
7250       end if;
7251
7252       --  STEP 3: initialize fields of derived type
7253
7254       Set_Is_Tagged_Type    (Derived_Type, Is_Tagged);
7255       Set_Stored_Constraint (Derived_Type, No_Elist);
7256
7257       --  Ada 2005 (AI-251): Private type-declarations can implement interfaces
7258       --  but cannot be interfaces
7259
7260       if not Private_Extension
7261          and then Ekind (Derived_Type) /= E_Private_Type
7262          and then Ekind (Derived_Type) /= E_Limited_Private_Type
7263       then
7264          if Interface_Present (Type_Def) then
7265             Analyze_Interface_Declaration (Derived_Type, Type_Def);
7266          end if;
7267
7268          Set_Interfaces (Derived_Type, No_Elist);
7269       end if;
7270
7271       --  Fields inherited from the Parent_Type
7272
7273       Set_Discard_Names
7274         (Derived_Type, Einfo.Discard_Names  (Parent_Type));
7275       Set_Has_Specified_Layout
7276         (Derived_Type, Has_Specified_Layout (Parent_Type));
7277       Set_Is_Limited_Composite
7278         (Derived_Type, Is_Limited_Composite (Parent_Type));
7279       Set_Is_Private_Composite
7280         (Derived_Type, Is_Private_Composite (Parent_Type));
7281
7282       --  Fields inherited from the Parent_Base
7283
7284       Set_Has_Controlled_Component
7285         (Derived_Type, Has_Controlled_Component (Parent_Base));
7286       Set_Has_Non_Standard_Rep
7287         (Derived_Type, Has_Non_Standard_Rep     (Parent_Base));
7288       Set_Has_Primitive_Operations
7289         (Derived_Type, Has_Primitive_Operations (Parent_Base));
7290
7291       --  Fields inherited from the Parent_Base in the non-private case
7292
7293       if Ekind (Derived_Type) = E_Record_Type then
7294          Set_Has_Complex_Representation
7295            (Derived_Type, Has_Complex_Representation (Parent_Base));
7296       end if;
7297
7298       --  Fields inherited from the Parent_Base for record types
7299
7300       if Is_Record_Type (Derived_Type) then
7301
7302          --  Ekind (Parent_Base) is not necessarily E_Record_Type since
7303          --  Parent_Base can be a private type or private extension.
7304
7305          if Present (Full_View (Parent_Base)) then
7306             Set_OK_To_Reorder_Components
7307               (Derived_Type,
7308                OK_To_Reorder_Components (Full_View (Parent_Base)));
7309             Set_Reverse_Bit_Order
7310               (Derived_Type, Reverse_Bit_Order (Full_View (Parent_Base)));
7311          else
7312             Set_OK_To_Reorder_Components
7313               (Derived_Type, OK_To_Reorder_Components (Parent_Base));
7314             Set_Reverse_Bit_Order
7315               (Derived_Type, Reverse_Bit_Order (Parent_Base));
7316          end if;
7317       end if;
7318
7319       --  Direct controlled types do not inherit Finalize_Storage_Only flag
7320
7321       if not Is_Controlled (Parent_Type) then
7322          Set_Finalize_Storage_Only
7323            (Derived_Type, Finalize_Storage_Only (Parent_Type));
7324       end if;
7325
7326       --  Set fields for private derived types
7327
7328       if Is_Private_Type (Derived_Type) then
7329          Set_Depends_On_Private (Derived_Type, True);
7330          Set_Private_Dependents (Derived_Type, New_Elmt_List);
7331
7332       --  Inherit fields from non private record types. If this is the
7333       --  completion of a derivation from a private type, the parent itself
7334       --  is private, and the attributes come from its full view, which must
7335       --  be present.
7336
7337       else
7338          if Is_Private_Type (Parent_Base)
7339            and then not Is_Record_Type (Parent_Base)
7340          then
7341             Set_Component_Alignment
7342               (Derived_Type, Component_Alignment (Full_View (Parent_Base)));
7343             Set_C_Pass_By_Copy
7344               (Derived_Type, C_Pass_By_Copy      (Full_View (Parent_Base)));
7345          else
7346             Set_Component_Alignment
7347               (Derived_Type, Component_Alignment (Parent_Base));
7348             Set_C_Pass_By_Copy
7349               (Derived_Type, C_Pass_By_Copy      (Parent_Base));
7350          end if;
7351       end if;
7352
7353       --  Set fields for tagged types
7354
7355       if Is_Tagged then
7356          Set_Direct_Primitive_Operations (Derived_Type, New_Elmt_List);
7357
7358          --  All tagged types defined in Ada.Finalization are controlled
7359
7360          if Chars (Scope (Derived_Type)) = Name_Finalization
7361            and then Chars (Scope (Scope (Derived_Type))) = Name_Ada
7362            and then Scope (Scope (Scope (Derived_Type))) = Standard_Standard
7363          then
7364             Set_Is_Controlled (Derived_Type);
7365          else
7366             Set_Is_Controlled (Derived_Type, Is_Controlled (Parent_Base));
7367          end if;
7368
7369          --  Minor optimization: there is no need to generate the class-wide
7370          --  entity associated with an underlying record view.
7371
7372          if not Is_Underlying_Record_View (Derived_Type) then
7373             Make_Class_Wide_Type (Derived_Type);
7374          end if;
7375
7376          Set_Is_Abstract_Type (Derived_Type, Abstract_Present (Type_Def));
7377
7378          if Has_Discriminants (Derived_Type)
7379            and then Constraint_Present
7380          then
7381             Set_Stored_Constraint
7382               (Derived_Type, Expand_To_Stored_Constraint (Parent_Base, Discs));
7383          end if;
7384
7385          if Ada_Version >= Ada_2005 then
7386             declare
7387                Ifaces_List : Elist_Id;
7388
7389             begin
7390                --  Checks rules 3.9.4 (13/2 and 14/2)
7391
7392                if Comes_From_Source (Derived_Type)
7393                  and then not Is_Private_Type (Derived_Type)
7394                  and then Is_Interface (Parent_Type)
7395                  and then not Is_Interface (Derived_Type)
7396                then
7397                   if Is_Task_Interface (Parent_Type) then
7398                      Error_Msg_N
7399                        ("(Ada 2005) task type required (RM 3.9.4 (13.2))",
7400                         Derived_Type);
7401
7402                   elsif Is_Protected_Interface (Parent_Type) then
7403                      Error_Msg_N
7404                        ("(Ada 2005) protected type required (RM 3.9.4 (14.2))",
7405                         Derived_Type);
7406                   end if;
7407                end if;
7408
7409                --  Check ARM rules 3.9.4 (15/2), 9.1 (9.d/2) and 9.4 (11.d/2)
7410
7411                Check_Interfaces (N, Type_Def);
7412
7413                --  Ada 2005 (AI-251): Collect the list of progenitors that are
7414                --  not already in the parents.
7415
7416                Collect_Interfaces
7417                  (T               => Derived_Type,
7418                   Ifaces_List     => Ifaces_List,
7419                   Exclude_Parents => True);
7420
7421                Set_Interfaces (Derived_Type, Ifaces_List);
7422
7423                --  If the derived type is the anonymous type created for
7424                --  a declaration whose parent has a constraint, propagate
7425                --  the interface list to the source type. This must be done
7426                --  prior to the completion of the analysis of the source type
7427                --  because the components in the extension may contain current
7428                --  instances whose legality depends on some ancestor.
7429
7430                if Is_Itype (Derived_Type) then
7431                   declare
7432                      Def : constant Node_Id :=
7433                        Associated_Node_For_Itype (Derived_Type);
7434                   begin
7435                      if Present (Def)
7436                        and then Nkind (Def) = N_Full_Type_Declaration
7437                      then
7438                         Set_Interfaces
7439                           (Defining_Identifier (Def), Ifaces_List);
7440                      end if;
7441                   end;
7442                end if;
7443             end;
7444          end if;
7445
7446       else
7447          Set_Is_Packed (Derived_Type, Is_Packed (Parent_Base));
7448          Set_Has_Non_Standard_Rep
7449                        (Derived_Type, Has_Non_Standard_Rep (Parent_Base));
7450       end if;
7451
7452       --  STEP 4: Inherit components from the parent base and constrain them.
7453       --          Apply the second transformation described in point 6. above.
7454
7455       if (not Is_Empty_Elmt_List (Discs) or else Inherit_Discrims)
7456         or else not Has_Discriminants (Parent_Type)
7457         or else not Is_Constrained (Parent_Type)
7458       then
7459          Constrs := Discs;
7460       else
7461          Constrs := Discriminant_Constraint (Parent_Type);
7462       end if;
7463
7464       Assoc_List :=
7465         Inherit_Components
7466           (N, Parent_Base, Derived_Type, Is_Tagged, Inherit_Discrims, Constrs);
7467
7468       --  STEP 5a: Copy the parent record declaration for untagged types
7469
7470       if not Is_Tagged then
7471
7472          --  Discriminant_Constraint (Derived_Type) has been properly
7473          --  constructed. Save it and temporarily set it to Empty because we
7474          --  do not want the call to New_Copy_Tree below to mess this list.
7475
7476          if Has_Discriminants (Derived_Type) then
7477             Save_Discr_Constr := Discriminant_Constraint (Derived_Type);
7478             Set_Discriminant_Constraint (Derived_Type, No_Elist);
7479          else
7480             Save_Discr_Constr := No_Elist;
7481          end if;
7482
7483          --  Save the Etype field of Derived_Type. It is correctly set now,
7484          --  but the call to New_Copy tree may remap it to point to itself,
7485          --  which is not what we want. Ditto for the Next_Entity field.
7486
7487          Save_Etype       := Etype (Derived_Type);
7488          Save_Next_Entity := Next_Entity (Derived_Type);
7489
7490          --  Assoc_List maps all stored discriminants in the Parent_Base to
7491          --  stored discriminants in the Derived_Type. It is fundamental that
7492          --  no types or itypes with discriminants other than the stored
7493          --  discriminants appear in the entities declared inside
7494          --  Derived_Type, since the back end cannot deal with it.
7495
7496          New_Decl :=
7497            New_Copy_Tree
7498              (Parent (Parent_Base), Map => Assoc_List, New_Sloc => Loc);
7499
7500          --  Restore the fields saved prior to the New_Copy_Tree call
7501          --  and compute the stored constraint.
7502
7503          Set_Etype       (Derived_Type, Save_Etype);
7504          Set_Next_Entity (Derived_Type, Save_Next_Entity);
7505
7506          if Has_Discriminants (Derived_Type) then
7507             Set_Discriminant_Constraint
7508               (Derived_Type, Save_Discr_Constr);
7509             Set_Stored_Constraint
7510               (Derived_Type, Expand_To_Stored_Constraint (Parent_Type, Discs));
7511             Replace_Components (Derived_Type, New_Decl);
7512          end if;
7513
7514          --  Insert the new derived type declaration
7515
7516          Rewrite (N, New_Decl);
7517
7518       --  STEP 5b: Complete the processing for record extensions in generics
7519
7520       --  There is no completion for record extensions declared in the
7521       --  parameter part of a generic, so we need to complete processing for
7522       --  these generic record extensions here. The Record_Type_Definition call
7523       --  will change the Ekind of the components from E_Void to E_Component.
7524
7525       elsif Private_Extension and then Is_Generic_Type (Derived_Type) then
7526          Record_Type_Definition (Empty, Derived_Type);
7527
7528       --  STEP 5c: Process the record extension for non private tagged types
7529
7530       elsif not Private_Extension then
7531
7532          --  Add the _parent field in the derived type
7533
7534          Expand_Record_Extension (Derived_Type, Type_Def);
7535
7536          --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
7537          --  implemented interfaces if we are in expansion mode
7538
7539          if Expander_Active
7540            and then Has_Interfaces (Derived_Type)
7541          then
7542             Add_Interface_Tag_Components (N, Derived_Type);
7543          end if;
7544
7545          --  Analyze the record extension
7546
7547          Record_Type_Definition
7548            (Record_Extension_Part (Type_Def), Derived_Type);
7549       end if;
7550
7551       End_Scope;
7552
7553       --  Nothing else to do if there is an error in the derivation.
7554       --  An unusual case: the full view may be derived from a type in an
7555       --  instance, when the partial view was used illegally as an actual
7556       --  in that instance, leading to a circular definition.
7557
7558       if Etype (Derived_Type) = Any_Type
7559         or else Etype (Parent_Type) = Derived_Type
7560       then
7561          return;
7562       end if;
7563
7564       --  Set delayed freeze and then derive subprograms, we need to do
7565       --  this in this order so that derived subprograms inherit the
7566       --  derived freeze if necessary.
7567
7568       Set_Has_Delayed_Freeze (Derived_Type);
7569
7570       if Derive_Subps then
7571          Derive_Subprograms (Parent_Type, Derived_Type);
7572       end if;
7573
7574       --  If we have a private extension which defines a constrained derived
7575       --  type mark as constrained here after we have derived subprograms. See
7576       --  comment on point 9. just above the body of Build_Derived_Record_Type.
7577
7578       if Private_Extension and then Inherit_Discrims then
7579          if Constraint_Present and then not Is_Empty_Elmt_List (Discs) then
7580             Set_Is_Constrained          (Derived_Type, True);
7581             Set_Discriminant_Constraint (Derived_Type, Discs);
7582
7583          elsif Is_Constrained (Parent_Type) then
7584             Set_Is_Constrained
7585               (Derived_Type, True);
7586             Set_Discriminant_Constraint
7587               (Derived_Type, Discriminant_Constraint (Parent_Type));
7588          end if;
7589       end if;
7590
7591       --  Update the class-wide type, which shares the now-completed entity
7592       --  list with its specific type. In case of underlying record views,
7593       --  we do not generate the corresponding class wide entity.
7594
7595       if Is_Tagged
7596         and then not Is_Underlying_Record_View (Derived_Type)
7597       then
7598          Set_First_Entity
7599            (Class_Wide_Type (Derived_Type), First_Entity (Derived_Type));
7600          Set_Last_Entity
7601            (Class_Wide_Type (Derived_Type), Last_Entity (Derived_Type));
7602       end if;
7603
7604       --  Update the scope of anonymous access types of discriminants and other
7605       --  components, to prevent scope anomalies in gigi, when the derivation
7606       --  appears in a scope nested within that of the parent.
7607
7608       declare
7609          D : Entity_Id;
7610
7611       begin
7612          D := First_Entity (Derived_Type);
7613          while Present (D) loop
7614             if Ekind_In (D, E_Discriminant, E_Component) then
7615                if Is_Itype (Etype (D))
7616                   and then Ekind (Etype (D)) = E_Anonymous_Access_Type
7617                then
7618                   Set_Scope (Etype (D), Current_Scope);
7619                end if;
7620             end if;
7621
7622             Next_Entity (D);
7623          end loop;
7624       end;
7625    end Build_Derived_Record_Type;
7626
7627    ------------------------
7628    -- Build_Derived_Type --
7629    ------------------------
7630
7631    procedure Build_Derived_Type
7632      (N             : Node_Id;
7633       Parent_Type   : Entity_Id;
7634       Derived_Type  : Entity_Id;
7635       Is_Completion : Boolean;
7636       Derive_Subps  : Boolean := True)
7637    is
7638       Parent_Base : constant Entity_Id := Base_Type (Parent_Type);
7639
7640    begin
7641       --  Set common attributes
7642
7643       Set_Scope         (Derived_Type, Current_Scope);
7644
7645       Set_Ekind         (Derived_Type, Ekind    (Parent_Base));
7646       Set_Etype         (Derived_Type,           Parent_Base);
7647       Set_Has_Task      (Derived_Type, Has_Task (Parent_Base));
7648
7649       Set_Size_Info      (Derived_Type,                 Parent_Type);
7650       Set_RM_Size        (Derived_Type, RM_Size        (Parent_Type));
7651       Set_Convention     (Derived_Type, Convention     (Parent_Type));
7652       Set_Is_Controlled  (Derived_Type, Is_Controlled  (Parent_Type));
7653       Set_Is_Tagged_Type (Derived_Type, Is_Tagged_Type (Parent_Type));
7654
7655       --  The derived type inherits the representation clauses of the parent.
7656       --  However, for a private type that is completed by a derivation, there
7657       --  may be operation attributes that have been specified already (stream
7658       --  attributes and External_Tag) and those must be provided. Finally,
7659       --  if the partial view is a private extension, the representation items
7660       --  of the parent have been inherited already, and should not be chained
7661       --  twice to the derived type.
7662
7663       if Is_Tagged_Type (Parent_Type)
7664         and then Present (First_Rep_Item (Derived_Type))
7665       then
7666          --  The existing items are either operational items or items inherited
7667          --  from a private extension declaration.
7668
7669          declare
7670             Rep : Node_Id;
7671             --  Used to iterate over representation items of the derived type
7672
7673             Last_Rep : Node_Id;
7674             --  Last representation item of the (non-empty) representation
7675             --  item list of the derived type.
7676
7677             Found : Boolean := False;
7678
7679          begin
7680             Rep      := First_Rep_Item (Derived_Type);
7681             Last_Rep := Rep;
7682             while Present (Rep) loop
7683                if Rep = First_Rep_Item (Parent_Type) then
7684                   Found := True;
7685                   exit;
7686
7687                else
7688                   Rep := Next_Rep_Item (Rep);
7689
7690                   if Present (Rep) then
7691                      Last_Rep := Rep;
7692                   end if;
7693                end if;
7694             end loop;
7695
7696             --  Here if we either encountered the parent type's first rep
7697             --  item on the derived type's rep item list (in which case
7698             --  Found is True, and we have nothing else to do), or if we
7699             --  reached the last rep item of the derived type, which is
7700             --  Last_Rep, in which case we further chain the parent type's
7701             --  rep items to those of the derived type.
7702
7703             if not Found then
7704                Set_Next_Rep_Item (Last_Rep, First_Rep_Item (Parent_Type));
7705             end if;
7706          end;
7707
7708       else
7709          Set_First_Rep_Item (Derived_Type, First_Rep_Item (Parent_Type));
7710       end if;
7711
7712       case Ekind (Parent_Type) is
7713          when Numeric_Kind =>
7714             Build_Derived_Numeric_Type (N, Parent_Type, Derived_Type);
7715
7716          when Array_Kind =>
7717             Build_Derived_Array_Type (N, Parent_Type,  Derived_Type);
7718
7719          when E_Record_Type
7720             | E_Record_Subtype
7721             | Class_Wide_Kind  =>
7722             Build_Derived_Record_Type
7723               (N, Parent_Type, Derived_Type, Derive_Subps);
7724             return;
7725
7726          when Enumeration_Kind =>
7727             Build_Derived_Enumeration_Type (N, Parent_Type, Derived_Type);
7728
7729          when Access_Kind =>
7730             Build_Derived_Access_Type (N, Parent_Type, Derived_Type);
7731
7732          when Incomplete_Or_Private_Kind =>
7733             Build_Derived_Private_Type
7734               (N, Parent_Type, Derived_Type, Is_Completion, Derive_Subps);
7735
7736             --  For discriminated types, the derivation includes deriving
7737             --  primitive operations. For others it is done below.
7738
7739             if Is_Tagged_Type (Parent_Type)
7740               or else Has_Discriminants (Parent_Type)
7741               or else (Present (Full_View (Parent_Type))
7742                         and then Has_Discriminants (Full_View (Parent_Type)))
7743             then
7744                return;
7745             end if;
7746
7747          when Concurrent_Kind =>
7748             Build_Derived_Concurrent_Type (N, Parent_Type, Derived_Type);
7749
7750          when others =>
7751             raise Program_Error;
7752       end case;
7753
7754       if Etype (Derived_Type) = Any_Type then
7755          return;
7756       end if;
7757
7758       --  Set delayed freeze and then derive subprograms, we need to do this
7759       --  in this order so that derived subprograms inherit the derived freeze
7760       --  if necessary.
7761
7762       Set_Has_Delayed_Freeze (Derived_Type);
7763       if Derive_Subps then
7764          Derive_Subprograms (Parent_Type, Derived_Type);
7765       end if;
7766
7767       Set_Has_Primitive_Operations
7768         (Base_Type (Derived_Type), Has_Primitive_Operations (Parent_Type));
7769    end Build_Derived_Type;
7770
7771    -----------------------
7772    -- Build_Discriminal --
7773    -----------------------
7774
7775    procedure Build_Discriminal (Discrim : Entity_Id) is
7776       D_Minal : Entity_Id;
7777       CR_Disc : Entity_Id;
7778
7779    begin
7780       --  A discriminal has the same name as the discriminant
7781
7782       D_Minal :=
7783         Make_Defining_Identifier (Sloc (Discrim),
7784           Chars => Chars (Discrim));
7785
7786       Set_Ekind     (D_Minal, E_In_Parameter);
7787       Set_Mechanism (D_Minal, Default_Mechanism);
7788       Set_Etype     (D_Minal, Etype (Discrim));
7789       Set_Scope     (D_Minal, Current_Scope);
7790
7791       Set_Discriminal (Discrim, D_Minal);
7792       Set_Discriminal_Link (D_Minal, Discrim);
7793
7794       --  For task types, build at once the discriminants of the corresponding
7795       --  record, which are needed if discriminants are used in entry defaults
7796       --  and in family bounds.
7797
7798       if Is_Concurrent_Type (Current_Scope)
7799         or else Is_Limited_Type (Current_Scope)
7800       then
7801          CR_Disc := Make_Defining_Identifier (Sloc (Discrim), Chars (Discrim));
7802
7803          Set_Ekind            (CR_Disc, E_In_Parameter);
7804          Set_Mechanism        (CR_Disc, Default_Mechanism);
7805          Set_Etype            (CR_Disc, Etype (Discrim));
7806          Set_Scope            (CR_Disc, Current_Scope);
7807          Set_Discriminal_Link (CR_Disc, Discrim);
7808          Set_CR_Discriminant  (Discrim, CR_Disc);
7809       end if;
7810    end Build_Discriminal;
7811
7812    ------------------------------------
7813    -- Build_Discriminant_Constraints --
7814    ------------------------------------
7815
7816    function Build_Discriminant_Constraints
7817      (T           : Entity_Id;
7818       Def         : Node_Id;
7819       Derived_Def : Boolean := False) return Elist_Id
7820    is
7821       C        : constant Node_Id := Constraint (Def);
7822       Nb_Discr : constant Nat     := Number_Discriminants (T);
7823
7824       Discr_Expr : array (1 .. Nb_Discr) of Node_Id := (others => Empty);
7825       --  Saves the expression corresponding to a given discriminant in T
7826
7827       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat;
7828       --  Return the Position number within array Discr_Expr of a discriminant
7829       --  D within the discriminant list of the discriminated type T.
7830
7831       ------------------
7832       -- Pos_Of_Discr --
7833       ------------------
7834
7835       function Pos_Of_Discr (T : Entity_Id; D : Entity_Id) return Nat is
7836          Disc : Entity_Id;
7837
7838       begin
7839          Disc := First_Discriminant (T);
7840          for J in Discr_Expr'Range loop
7841             if Disc = D then
7842                return J;
7843             end if;
7844
7845             Next_Discriminant (Disc);
7846          end loop;
7847
7848          --  Note: Since this function is called on discriminants that are
7849          --  known to belong to the discriminated type, falling through the
7850          --  loop with no match signals an internal compiler error.
7851
7852          raise Program_Error;
7853       end Pos_Of_Discr;
7854
7855       --  Declarations local to Build_Discriminant_Constraints
7856
7857       Discr : Entity_Id;
7858       E     : Entity_Id;
7859       Elist : constant Elist_Id := New_Elmt_List;
7860
7861       Constr   : Node_Id;
7862       Expr     : Node_Id;
7863       Id       : Node_Id;
7864       Position : Nat;
7865       Found    : Boolean;
7866
7867       Discrim_Present : Boolean := False;
7868
7869    --  Start of processing for Build_Discriminant_Constraints
7870
7871    begin
7872       --  The following loop will process positional associations only.
7873       --  For a positional association, the (single) discriminant is
7874       --  implicitly specified by position, in textual order (RM 3.7.2).
7875
7876       Discr  := First_Discriminant (T);
7877       Constr := First (Constraints (C));
7878       for D in Discr_Expr'Range loop
7879          exit when Nkind (Constr) = N_Discriminant_Association;
7880
7881          if No (Constr) then
7882             Error_Msg_N ("too few discriminants given in constraint", C);
7883             return New_Elmt_List;
7884
7885          elsif Nkind (Constr) = N_Range
7886            or else (Nkind (Constr) = N_Attribute_Reference
7887                      and then
7888                     Attribute_Name (Constr) = Name_Range)
7889          then
7890             Error_Msg_N
7891               ("a range is not a valid discriminant constraint", Constr);
7892             Discr_Expr (D) := Error;
7893
7894          else
7895             Analyze_And_Resolve (Constr, Base_Type (Etype (Discr)));
7896             Discr_Expr (D) := Constr;
7897          end if;
7898
7899          Next_Discriminant (Discr);
7900          Next (Constr);
7901       end loop;
7902
7903       if No (Discr) and then Present (Constr) then
7904          Error_Msg_N ("too many discriminants given in constraint", Constr);
7905          return New_Elmt_List;
7906       end if;
7907
7908       --  Named associations can be given in any order, but if both positional
7909       --  and named associations are used in the same discriminant constraint,
7910       --  then positional associations must occur first, at their normal
7911       --  position. Hence once a named association is used, the rest of the
7912       --  discriminant constraint must use only named associations.
7913
7914       while Present (Constr) loop
7915
7916          --  Positional association forbidden after a named association
7917
7918          if Nkind (Constr) /= N_Discriminant_Association then
7919             Error_Msg_N ("positional association follows named one", Constr);
7920             return New_Elmt_List;
7921
7922          --  Otherwise it is a named association
7923
7924          else
7925             --  E records the type of the discriminants in the named
7926             --  association. All the discriminants specified in the same name
7927             --  association must have the same type.
7928
7929             E := Empty;
7930
7931             --  Search the list of discriminants in T to see if the simple name
7932             --  given in the constraint matches any of them.
7933
7934             Id := First (Selector_Names (Constr));
7935             while Present (Id) loop
7936                Found := False;
7937
7938                --  If Original_Discriminant is present, we are processing a
7939                --  generic instantiation and this is an instance node. We need
7940                --  to find the name of the corresponding discriminant in the
7941                --  actual record type T and not the name of the discriminant in
7942                --  the generic formal. Example:
7943
7944                --    generic
7945                --       type G (D : int) is private;
7946                --    package P is
7947                --       subtype W is G (D => 1);
7948                --    end package;
7949                --    type Rec (X : int) is record ... end record;
7950                --    package Q is new P (G => Rec);
7951
7952                --  At the point of the instantiation, formal type G is Rec
7953                --  and therefore when reanalyzing "subtype W is G (D => 1);"
7954                --  which really looks like "subtype W is Rec (D => 1);" at
7955                --  the point of instantiation, we want to find the discriminant
7956                --  that corresponds to D in Rec, i.e. X.
7957
7958                if Present (Original_Discriminant (Id)) then
7959                   Discr := Find_Corresponding_Discriminant (Id, T);
7960                   Found := True;
7961
7962                else
7963                   Discr := First_Discriminant (T);
7964                   while Present (Discr) loop
7965                      if Chars (Discr) = Chars (Id) then
7966                         Found := True;
7967                         exit;
7968                      end if;
7969
7970                      Next_Discriminant (Discr);
7971                   end loop;
7972
7973                   if not Found then
7974                      Error_Msg_N ("& does not match any discriminant", Id);
7975                      return New_Elmt_List;
7976
7977                   --  The following is only useful for the benefit of generic
7978                   --  instances but it does not interfere with other
7979                   --  processing for the non-generic case so we do it in all
7980                   --  cases (for generics this statement is executed when
7981                   --  processing the generic definition, see comment at the
7982                   --  beginning of this if statement).
7983
7984                   else
7985                      Set_Original_Discriminant (Id, Discr);
7986                   end if;
7987                end if;
7988
7989                Position := Pos_Of_Discr (T, Discr);
7990
7991                if Present (Discr_Expr (Position)) then
7992                   Error_Msg_N ("duplicate constraint for discriminant&", Id);
7993
7994                else
7995                   --  Each discriminant specified in the same named association
7996                   --  must be associated with a separate copy of the
7997                   --  corresponding expression.
7998
7999                   if Present (Next (Id)) then
8000                      Expr := New_Copy_Tree (Expression (Constr));
8001                      Set_Parent (Expr, Parent (Expression (Constr)));
8002                   else
8003                      Expr := Expression (Constr);
8004                   end if;
8005
8006                   Discr_Expr (Position) := Expr;
8007                   Analyze_And_Resolve (Expr, Base_Type (Etype (Discr)));
8008                end if;
8009
8010                --  A discriminant association with more than one discriminant
8011                --  name is only allowed if the named discriminants are all of
8012                --  the same type (RM 3.7.1(8)).
8013
8014                if E = Empty then
8015                   E := Base_Type (Etype (Discr));
8016
8017                elsif Base_Type (Etype (Discr)) /= E then
8018                   Error_Msg_N
8019                     ("all discriminants in an association " &
8020                      "must have the same type", Id);
8021                end if;
8022
8023                Next (Id);
8024             end loop;
8025          end if;
8026
8027          Next (Constr);
8028       end loop;
8029
8030       --  A discriminant constraint must provide exactly one value for each
8031       --  discriminant of the type (RM 3.7.1(8)).
8032
8033       for J in Discr_Expr'Range loop
8034          if No (Discr_Expr (J)) then
8035             Error_Msg_N ("too few discriminants given in constraint", C);
8036             return New_Elmt_List;
8037          end if;
8038       end loop;
8039
8040       --  Determine if there are discriminant expressions in the constraint
8041
8042       for J in Discr_Expr'Range loop
8043          if Denotes_Discriminant
8044               (Discr_Expr (J), Check_Concurrent => True)
8045          then
8046             Discrim_Present := True;
8047          end if;
8048       end loop;
8049
8050       --  Build an element list consisting of the expressions given in the
8051       --  discriminant constraint and apply the appropriate checks. The list
8052       --  is constructed after resolving any named discriminant associations
8053       --  and therefore the expressions appear in the textual order of the
8054       --  discriminants.
8055
8056       Discr := First_Discriminant (T);
8057       for J in Discr_Expr'Range loop
8058          if Discr_Expr (J) /= Error then
8059             Append_Elmt (Discr_Expr (J), Elist);
8060
8061             --  If any of the discriminant constraints is given by a
8062             --  discriminant and we are in a derived type declaration we
8063             --  have a discriminant renaming. Establish link between new
8064             --  and old discriminant.
8065
8066             if Denotes_Discriminant (Discr_Expr (J)) then
8067                if Derived_Def then
8068                   Set_Corresponding_Discriminant
8069                     (Entity (Discr_Expr (J)), Discr);
8070                end if;
8071
8072             --  Force the evaluation of non-discriminant expressions.
8073             --  If we have found a discriminant in the constraint 3.4(26)
8074             --  and 3.8(18) demand that no range checks are performed are
8075             --  after evaluation. If the constraint is for a component
8076             --  definition that has a per-object constraint, expressions are
8077             --  evaluated but not checked either. In all other cases perform
8078             --  a range check.
8079
8080             else
8081                if Discrim_Present then
8082                   null;
8083
8084                elsif Nkind (Parent (Parent (Def))) = N_Component_Declaration
8085                  and then
8086                    Has_Per_Object_Constraint
8087                      (Defining_Identifier (Parent (Parent (Def))))
8088                then
8089                   null;
8090
8091                elsif Is_Access_Type (Etype (Discr)) then
8092                   Apply_Constraint_Check (Discr_Expr (J), Etype (Discr));
8093
8094                else
8095                   Apply_Range_Check (Discr_Expr (J), Etype (Discr));
8096                end if;
8097
8098                Force_Evaluation (Discr_Expr (J));
8099             end if;
8100
8101             --  Check that the designated type of an access discriminant's
8102             --  expression is not a class-wide type unless the discriminant's
8103             --  designated type is also class-wide.
8104
8105             if Ekind (Etype (Discr)) = E_Anonymous_Access_Type
8106               and then not Is_Class_Wide_Type
8107                          (Designated_Type (Etype (Discr)))
8108               and then Etype (Discr_Expr (J)) /= Any_Type
8109               and then Is_Class_Wide_Type
8110                          (Designated_Type (Etype (Discr_Expr (J))))
8111             then
8112                Wrong_Type (Discr_Expr (J), Etype (Discr));
8113
8114             elsif Is_Access_Type (Etype (Discr))
8115               and then not Is_Access_Constant (Etype (Discr))
8116               and then Is_Access_Type (Etype (Discr_Expr (J)))
8117               and then Is_Access_Constant (Etype (Discr_Expr (J)))
8118             then
8119                Error_Msg_NE
8120                  ("constraint for discriminant& must be access to variable",
8121                     Def, Discr);
8122             end if;
8123          end if;
8124
8125          Next_Discriminant (Discr);
8126       end loop;
8127
8128       return Elist;
8129    end Build_Discriminant_Constraints;
8130
8131    ---------------------------------
8132    -- Build_Discriminated_Subtype --
8133    ---------------------------------
8134
8135    procedure Build_Discriminated_Subtype
8136      (T           : Entity_Id;
8137       Def_Id      : Entity_Id;
8138       Elist       : Elist_Id;
8139       Related_Nod : Node_Id;
8140       For_Access  : Boolean := False)
8141    is
8142       Has_Discrs  : constant Boolean := Has_Discriminants (T);
8143       Constrained : constant Boolean :=
8144                       (Has_Discrs
8145                          and then not Is_Empty_Elmt_List (Elist)
8146                          and then not Is_Class_Wide_Type (T))
8147                         or else Is_Constrained (T);
8148
8149    begin
8150       if Ekind (T) = E_Record_Type then
8151          if For_Access then
8152             Set_Ekind (Def_Id, E_Private_Subtype);
8153             Set_Is_For_Access_Subtype (Def_Id, True);
8154          else
8155             Set_Ekind (Def_Id, E_Record_Subtype);
8156          end if;
8157
8158          --  Inherit preelaboration flag from base, for types for which it
8159          --  may have been set: records, private types, protected types.
8160
8161          Set_Known_To_Have_Preelab_Init
8162            (Def_Id, Known_To_Have_Preelab_Init (T));
8163
8164       elsif Ekind (T) = E_Task_Type then
8165          Set_Ekind (Def_Id, E_Task_Subtype);
8166
8167       elsif Ekind (T) = E_Protected_Type then
8168          Set_Ekind (Def_Id, E_Protected_Subtype);
8169          Set_Known_To_Have_Preelab_Init
8170            (Def_Id, Known_To_Have_Preelab_Init (T));
8171
8172       elsif Is_Private_Type (T) then
8173          Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
8174          Set_Known_To_Have_Preelab_Init
8175            (Def_Id, Known_To_Have_Preelab_Init (T));
8176
8177       elsif Is_Class_Wide_Type (T) then
8178          Set_Ekind (Def_Id, E_Class_Wide_Subtype);
8179
8180       else
8181          --  Incomplete type. Attach subtype to list of dependents, to be
8182          --  completed with full view of parent type,  unless is it the
8183          --  designated subtype of a record component within an init_proc.
8184          --  This last case arises for a component of an access type whose
8185          --  designated type is incomplete (e.g. a Taft Amendment type).
8186          --  The designated subtype is within an inner scope, and needs no
8187          --  elaboration, because only the access type is needed in the
8188          --  initialization procedure.
8189
8190          Set_Ekind (Def_Id, Ekind (T));
8191
8192          if For_Access and then Within_Init_Proc then
8193             null;
8194          else
8195             Append_Elmt (Def_Id, Private_Dependents (T));
8196          end if;
8197       end if;
8198
8199       Set_Etype             (Def_Id, T);
8200       Init_Size_Align       (Def_Id);
8201       Set_Has_Discriminants (Def_Id, Has_Discrs);
8202       Set_Is_Constrained    (Def_Id, Constrained);
8203
8204       Set_First_Entity      (Def_Id, First_Entity   (T));
8205       Set_Last_Entity       (Def_Id, Last_Entity    (T));
8206
8207       --  If the subtype is the completion of a private declaration, there may
8208       --  have been representation clauses for the partial view, and they must
8209       --  be preserved. Build_Derived_Type chains the inherited clauses with
8210       --  the ones appearing on the extension. If this comes from a subtype
8211       --  declaration, all clauses are inherited.
8212
8213       if No (First_Rep_Item (Def_Id)) then
8214          Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
8215       end if;
8216
8217       if Is_Tagged_Type (T) then
8218          Set_Is_Tagged_Type  (Def_Id);
8219          Make_Class_Wide_Type (Def_Id);
8220       end if;
8221
8222       Set_Stored_Constraint (Def_Id, No_Elist);
8223
8224       if Has_Discrs then
8225          Set_Discriminant_Constraint (Def_Id, Elist);
8226          Set_Stored_Constraint_From_Discriminant_Constraint (Def_Id);
8227       end if;
8228
8229       if Is_Tagged_Type (T) then
8230
8231          --  Ada 2005 (AI-251): In case of concurrent types we inherit the
8232          --  concurrent record type (which has the list of primitive
8233          --  operations).
8234
8235          if Ada_Version >= Ada_2005
8236            and then Is_Concurrent_Type (T)
8237          then
8238             Set_Corresponding_Record_Type (Def_Id,
8239                Corresponding_Record_Type (T));
8240          else
8241             Set_Direct_Primitive_Operations (Def_Id,
8242               Direct_Primitive_Operations (T));
8243          end if;
8244
8245          Set_Is_Abstract_Type (Def_Id, Is_Abstract_Type (T));
8246       end if;
8247
8248       --  Subtypes introduced by component declarations do not need to be
8249       --  marked as delayed, and do not get freeze nodes, because the semantics
8250       --  verifies that the parents of the subtypes are frozen before the
8251       --  enclosing record is frozen.
8252
8253       if not Is_Type (Scope (Def_Id)) then
8254          Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
8255
8256          if Is_Private_Type (T)
8257            and then Present (Full_View (T))
8258          then
8259             Conditional_Delay (Def_Id, Full_View (T));
8260          else
8261             Conditional_Delay (Def_Id, T);
8262          end if;
8263       end if;
8264
8265       if Is_Record_Type (T) then
8266          Set_Is_Limited_Record (Def_Id, Is_Limited_Record (T));
8267
8268          if Has_Discrs
8269             and then not Is_Empty_Elmt_List (Elist)
8270             and then not For_Access
8271          then
8272             Create_Constrained_Components (Def_Id, Related_Nod, T, Elist);
8273          elsif not For_Access then
8274             Set_Cloned_Subtype (Def_Id, T);
8275          end if;
8276       end if;
8277    end Build_Discriminated_Subtype;
8278
8279    ---------------------------
8280    -- Build_Itype_Reference --
8281    ---------------------------
8282
8283    procedure Build_Itype_Reference
8284      (Ityp : Entity_Id;
8285       Nod  : Node_Id)
8286    is
8287       IR : constant Node_Id := Make_Itype_Reference (Sloc (Nod));
8288    begin
8289       Set_Itype (IR, Ityp);
8290       Insert_After (Nod, IR);
8291    end Build_Itype_Reference;
8292
8293    ------------------------
8294    -- Build_Scalar_Bound --
8295    ------------------------
8296
8297    function Build_Scalar_Bound
8298      (Bound : Node_Id;
8299       Par_T : Entity_Id;
8300       Der_T : Entity_Id) return Node_Id
8301    is
8302       New_Bound : Entity_Id;
8303
8304    begin
8305       --  Note: not clear why this is needed, how can the original bound
8306       --  be unanalyzed at this point? and if it is, what business do we
8307       --  have messing around with it? and why is the base type of the
8308       --  parent type the right type for the resolution. It probably is
8309       --  not! It is OK for the new bound we are creating, but not for
8310       --  the old one??? Still if it never happens, no problem!
8311
8312       Analyze_And_Resolve (Bound, Base_Type (Par_T));
8313
8314       if Nkind_In (Bound, N_Integer_Literal, N_Real_Literal) then
8315          New_Bound := New_Copy (Bound);
8316          Set_Etype (New_Bound, Der_T);
8317          Set_Analyzed (New_Bound);
8318
8319       elsif Is_Entity_Name (Bound) then
8320          New_Bound := OK_Convert_To (Der_T, New_Copy (Bound));
8321
8322       --  The following is almost certainly wrong. What business do we have
8323       --  relocating a node (Bound) that is presumably still attached to
8324       --  the tree elsewhere???
8325
8326       else
8327          New_Bound := OK_Convert_To (Der_T, Relocate_Node (Bound));
8328       end if;
8329
8330       Set_Etype (New_Bound, Der_T);
8331       return New_Bound;
8332    end Build_Scalar_Bound;
8333
8334    --------------------------------
8335    -- Build_Underlying_Full_View --
8336    --------------------------------
8337
8338    procedure Build_Underlying_Full_View
8339      (N   : Node_Id;
8340       Typ : Entity_Id;
8341       Par : Entity_Id)
8342    is
8343       Loc  : constant Source_Ptr := Sloc (N);
8344       Subt : constant Entity_Id :=
8345                Make_Defining_Identifier
8346                  (Loc, New_External_Name (Chars (Typ), 'S'));
8347
8348       Constr : Node_Id;
8349       Indic  : Node_Id;
8350       C      : Node_Id;
8351       Id     : Node_Id;
8352
8353       procedure Set_Discriminant_Name (Id : Node_Id);
8354       --  If the derived type has discriminants, they may rename discriminants
8355       --  of the parent. When building the full view of the parent, we need to
8356       --  recover the names of the original discriminants if the constraint is
8357       --  given by named associations.
8358
8359       ---------------------------
8360       -- Set_Discriminant_Name --
8361       ---------------------------
8362
8363       procedure Set_Discriminant_Name (Id : Node_Id) is
8364          Disc : Entity_Id;
8365
8366       begin
8367          Set_Original_Discriminant (Id, Empty);
8368
8369          if Has_Discriminants (Typ) then
8370             Disc := First_Discriminant (Typ);
8371             while Present (Disc) loop
8372                if Chars (Disc) = Chars (Id)
8373                  and then Present (Corresponding_Discriminant (Disc))
8374                then
8375                   Set_Chars (Id, Chars (Corresponding_Discriminant (Disc)));
8376                end if;
8377                Next_Discriminant (Disc);
8378             end loop;
8379          end if;
8380       end Set_Discriminant_Name;
8381
8382    --  Start of processing for Build_Underlying_Full_View
8383
8384    begin
8385       if Nkind (N) = N_Full_Type_Declaration then
8386          Constr := Constraint (Subtype_Indication (Type_Definition (N)));
8387
8388       elsif Nkind (N) = N_Subtype_Declaration then
8389          Constr := New_Copy_Tree (Constraint (Subtype_Indication (N)));
8390
8391       elsif Nkind (N) = N_Component_Declaration then
8392          Constr :=
8393            New_Copy_Tree
8394              (Constraint (Subtype_Indication (Component_Definition (N))));
8395
8396       else
8397          raise Program_Error;
8398       end if;
8399
8400       C := First (Constraints (Constr));
8401       while Present (C) loop
8402          if Nkind (C) = N_Discriminant_Association then
8403             Id := First (Selector_Names (C));
8404             while Present (Id) loop
8405                Set_Discriminant_Name (Id);
8406                Next (Id);
8407             end loop;
8408          end if;
8409
8410          Next (C);
8411       end loop;
8412
8413       Indic :=
8414         Make_Subtype_Declaration (Loc,
8415           Defining_Identifier => Subt,
8416           Subtype_Indication  =>
8417             Make_Subtype_Indication (Loc,
8418               Subtype_Mark => New_Reference_To (Par, Loc),
8419               Constraint   => New_Copy_Tree (Constr)));
8420
8421       --  If this is a component subtype for an outer itype, it is not
8422       --  a list member, so simply set the parent link for analysis: if
8423       --  the enclosing type does not need to be in a declarative list,
8424       --  neither do the components.
8425
8426       if Is_List_Member (N)
8427         and then Nkind (N) /= N_Component_Declaration
8428       then
8429          Insert_Before (N, Indic);
8430       else
8431          Set_Parent (Indic, Parent (N));
8432       end if;
8433
8434       Analyze (Indic);
8435       Set_Underlying_Full_View (Typ, Full_View (Subt));
8436    end Build_Underlying_Full_View;
8437
8438    -------------------------------
8439    -- Check_Abstract_Overriding --
8440    -------------------------------
8441
8442    procedure Check_Abstract_Overriding (T : Entity_Id) is
8443       Alias_Subp : Entity_Id;
8444       Elmt       : Elmt_Id;
8445       Op_List    : Elist_Id;
8446       Subp       : Entity_Id;
8447       Type_Def   : Node_Id;
8448
8449       procedure Check_Pragma_Implemented (Subp : Entity_Id);
8450       --  Ada 2012 (AI05-0030): Subprogram Subp overrides an interface routine
8451       --  which has pragma Implemented already set. Check whether Subp's entity
8452       --  kind conforms to the implementation kind of the overridden routine.
8453
8454       procedure Check_Pragma_Implemented
8455         (Subp       : Entity_Id;
8456          Iface_Subp : Entity_Id);
8457       --  Ada 2012 (AI05-0030): Subprogram Subp overrides interface routine
8458       --  Iface_Subp and both entities have pragma Implemented already set on
8459       --  them. Check whether the two implementation kinds are conforming.
8460
8461       procedure Inherit_Pragma_Implemented
8462         (Subp       : Entity_Id;
8463          Iface_Subp : Entity_Id);
8464       --  Ada 2012 (AI05-0030): Interface primitive Subp overrides interface
8465       --  subprogram Iface_Subp which has been marked by pragma Implemented.
8466       --  Propagate the implementation kind of Iface_Subp to Subp.
8467
8468       ------------------------------
8469       -- Check_Pragma_Implemented --
8470       ------------------------------
8471
8472       procedure Check_Pragma_Implemented (Subp : Entity_Id) is
8473          Iface_Alias : constant Entity_Id := Interface_Alias (Subp);
8474          Impl_Kind   : constant Name_Id   := Implementation_Kind (Iface_Alias);
8475          Contr_Typ   : Entity_Id;
8476
8477       begin
8478          --  Subp must have an alias since it is a hidden entity used to link
8479          --  an interface subprogram to its overriding counterpart.
8480
8481          pragma Assert (Present (Alias (Subp)));
8482
8483          --  Extract the type of the controlling formal
8484
8485          Contr_Typ := Etype (First_Formal (Alias (Subp)));
8486
8487          if Is_Concurrent_Record_Type (Contr_Typ) then
8488             Contr_Typ := Corresponding_Concurrent_Type (Contr_Typ);
8489          end if;
8490
8491          --  An interface subprogram whose implementation kind is By_Entry must
8492          --  be implemented by an entry.
8493
8494          if Impl_Kind = Name_By_Entry
8495            and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Entry
8496          then
8497             Error_Msg_Node_2 := Iface_Alias;
8498             Error_Msg_NE
8499               ("type & must implement abstract subprogram & with an entry",
8500                Alias (Subp), Contr_Typ);
8501
8502          elsif Impl_Kind = Name_By_Protected_Procedure then
8503
8504             --  An interface subprogram whose implementation kind is By_
8505             --  Protected_Procedure cannot be implemented by a primitive
8506             --  procedure of a task type.
8507
8508             if Ekind (Contr_Typ) /= E_Protected_Type then
8509                Error_Msg_Node_2 := Contr_Typ;
8510                Error_Msg_NE
8511                  ("interface subprogram & cannot be implemented by a " &
8512                   "primitive procedure of task type &", Alias (Subp),
8513                   Iface_Alias);
8514
8515             --  An interface subprogram whose implementation kind is By_
8516             --  Protected_Procedure must be implemented by a procedure.
8517
8518             elsif Is_Primitive_Wrapper (Alias (Subp))
8519               and then Ekind (Wrapped_Entity (Alias (Subp))) /= E_Procedure
8520             then
8521                Error_Msg_Node_2 := Iface_Alias;
8522                Error_Msg_NE
8523                  ("type & must implement abstract subprogram & with a " &
8524                   "procedure", Alias (Subp), Contr_Typ);
8525             end if;
8526          end if;
8527       end Check_Pragma_Implemented;
8528
8529       ------------------------------
8530       -- Check_Pragma_Implemented --
8531       ------------------------------
8532
8533       procedure Check_Pragma_Implemented
8534         (Subp       : Entity_Id;
8535          Iface_Subp : Entity_Id)
8536       is
8537          Iface_Kind : constant Name_Id := Implementation_Kind (Iface_Subp);
8538          Subp_Kind  : constant Name_Id := Implementation_Kind (Subp);
8539
8540       begin
8541          --  Ada 2012 (AI05-0030): The implementation kinds of an overridden
8542          --  and overriding subprogram are different. In general this is an
8543          --  error except when the implementation kind of the overridden
8544          --  subprograms is By_Any.
8545
8546          if Iface_Kind /= Subp_Kind
8547            and then Iface_Kind /= Name_By_Any
8548          then
8549             if Iface_Kind = Name_By_Entry then
8550                Error_Msg_N
8551                  ("incompatible implementation kind, overridden subprogram " &
8552                   "is marked By_Entry", Subp);
8553             else
8554                Error_Msg_N
8555                  ("incompatible implementation kind, overridden subprogram " &
8556                   "is marked By_Protected_Procedure", Subp);
8557             end if;
8558          end if;
8559       end Check_Pragma_Implemented;
8560
8561       --------------------------------
8562       -- Inherit_Pragma_Implemented --
8563       --------------------------------
8564
8565       procedure Inherit_Pragma_Implemented
8566         (Subp       : Entity_Id;
8567          Iface_Subp : Entity_Id)
8568       is
8569          Iface_Kind : constant Name_Id    := Implementation_Kind (Iface_Subp);
8570          Loc        : constant Source_Ptr := Sloc (Subp);
8571          Impl_Prag  : Node_Id;
8572
8573       begin
8574          --  Since the implementation kind is stored as a representation item
8575          --  rather than a flag, create a pragma node.
8576
8577          Impl_Prag :=
8578            Make_Pragma (Loc,
8579              Chars => Name_Implemented,
8580              Pragma_Argument_Associations => New_List (
8581                Make_Pragma_Argument_Association (Loc,
8582                  Expression =>
8583                    New_Reference_To (Subp, Loc)),
8584
8585                Make_Pragma_Argument_Association (Loc,
8586                  Expression =>
8587                    Make_Identifier (Loc, Iface_Kind))));
8588
8589          --  The pragma doesn't need to be analyzed because it is internaly
8590          --  build. It is safe to directly register it as a rep item since we
8591          --  are only interested in the characters of the implementation kind.
8592
8593          Record_Rep_Item (Subp, Impl_Prag);
8594       end Inherit_Pragma_Implemented;
8595
8596    --  Start of processing for Check_Abstract_Overriding
8597
8598    begin
8599       Op_List := Primitive_Operations (T);
8600
8601       --  Loop to check primitive operations
8602
8603       Elmt := First_Elmt (Op_List);
8604       while Present (Elmt) loop
8605          Subp := Node (Elmt);
8606          Alias_Subp := Alias (Subp);
8607
8608          --  Inherited subprograms are identified by the fact that they do not
8609          --  come from source, and the associated source location is the
8610          --  location of the first subtype of the derived type.
8611
8612          --  Ada 2005 (AI-228): Apply the rules of RM-3.9.3(6/2) for
8613          --  subprograms that "require overriding".
8614
8615          --  Special exception, do not complain about failure to override the
8616          --  stream routines _Input and _Output, as well as the primitive
8617          --  operations used in dispatching selects since we always provide
8618          --  automatic overridings for these subprograms.
8619
8620          --  Also ignore this rule for convention CIL since .NET libraries
8621          --  do bizarre things with interfaces???
8622
8623          --  The partial view of T may have been a private extension, for
8624          --  which inherited functions dispatching on result are abstract.
8625          --  If the full view is a null extension, there is no need for
8626          --  overriding in Ada2005, but wrappers need to be built for them
8627          --  (see exp_ch3, Build_Controlling_Function_Wrappers).
8628
8629          if Is_Null_Extension (T)
8630            and then Has_Controlling_Result (Subp)
8631            and then Ada_Version >= Ada_2005
8632            and then Present (Alias_Subp)
8633            and then not Comes_From_Source (Subp)
8634            and then not Is_Abstract_Subprogram (Alias_Subp)
8635            and then not Is_Access_Type (Etype (Subp))
8636          then
8637             null;
8638
8639          --  Ada 2005 (AI-251): Internal entities of interfaces need no
8640          --  processing because this check is done with the aliased
8641          --  entity
8642
8643          elsif Present (Interface_Alias (Subp)) then
8644             null;
8645
8646          elsif (Is_Abstract_Subprogram (Subp)
8647                  or else Requires_Overriding (Subp)
8648                  or else
8649                    (Has_Controlling_Result (Subp)
8650                      and then Present (Alias_Subp)
8651                      and then not Comes_From_Source (Subp)
8652                      and then Sloc (Subp) = Sloc (First_Subtype (T))))
8653            and then not Is_TSS (Subp, TSS_Stream_Input)
8654            and then not Is_TSS (Subp, TSS_Stream_Output)
8655            and then not Is_Abstract_Type (T)
8656            and then Convention (T) /= Convention_CIL
8657            and then not Is_Predefined_Interface_Primitive (Subp)
8658
8659             --  Ada 2005 (AI-251): Do not consider hidden entities associated
8660             --  with abstract interface types because the check will be done
8661             --  with the aliased entity (otherwise we generate a duplicated
8662             --  error message).
8663
8664            and then not Present (Interface_Alias (Subp))
8665          then
8666             if Present (Alias_Subp) then
8667
8668                --  Only perform the check for a derived subprogram when the
8669                --  type has an explicit record extension. This avoids incorrect
8670                --  flagging of abstract subprograms for the case of a type
8671                --  without an extension that is derived from a formal type
8672                --  with a tagged actual (can occur within a private part).
8673
8674                --  Ada 2005 (AI-391): In the case of an inherited function with
8675                --  a controlling result of the type, the rule does not apply if
8676                --  the type is a null extension (unless the parent function
8677                --  itself is abstract, in which case the function must still be
8678                --  be overridden). The expander will generate an overriding
8679                --  wrapper function calling the parent subprogram (see
8680                --  Exp_Ch3.Make_Controlling_Wrapper_Functions).
8681
8682                Type_Def := Type_Definition (Parent (T));
8683
8684                if Nkind (Type_Def) = N_Derived_Type_Definition
8685                  and then Present (Record_Extension_Part (Type_Def))
8686                  and then
8687                    (Ada_Version < Ada_2005
8688                       or else not Is_Null_Extension (T)
8689                       or else Ekind (Subp) = E_Procedure
8690                       or else not Has_Controlling_Result (Subp)
8691                       or else Is_Abstract_Subprogram (Alias_Subp)
8692                       or else Requires_Overriding (Subp)
8693                       or else Is_Access_Type (Etype (Subp)))
8694                then
8695                   --  Avoid reporting error in case of abstract predefined
8696                   --  primitive inherited from interface type because the
8697                   --  body of internally generated predefined primitives
8698                   --  of tagged types are generated later by Freeze_Type
8699
8700                   if Is_Interface (Root_Type (T))
8701                     and then Is_Abstract_Subprogram (Subp)
8702                     and then Is_Predefined_Dispatching_Operation (Subp)
8703                     and then not Comes_From_Source (Ultimate_Alias (Subp))
8704                   then
8705                      null;
8706
8707                   else
8708                      Error_Msg_NE
8709                        ("type must be declared abstract or & overridden",
8710                         T, Subp);
8711
8712                      --  Traverse the whole chain of aliased subprograms to
8713                      --  complete the error notification. This is especially
8714                      --  useful for traceability of the chain of entities when
8715                      --  the subprogram corresponds with an interface
8716                      --  subprogram (which may be defined in another package).
8717
8718                      if Present (Alias_Subp) then
8719                         declare
8720                            E : Entity_Id;
8721
8722                         begin
8723                            E := Subp;
8724                            while Present (Alias (E)) loop
8725                               Error_Msg_Sloc := Sloc (E);
8726                               Error_Msg_NE
8727                                 ("\& has been inherited #", T, Subp);
8728                               E := Alias (E);
8729                            end loop;
8730
8731                            Error_Msg_Sloc := Sloc (E);
8732                            Error_Msg_NE
8733                              ("\& has been inherited from subprogram #",
8734                               T, Subp);
8735                         end;
8736                      end if;
8737                   end if;
8738
8739                --  Ada 2005 (AI-345): Protected or task type implementing
8740                --  abstract interfaces.
8741
8742                elsif Is_Concurrent_Record_Type (T)
8743                  and then Present (Interfaces (T))
8744                then
8745                   --  The controlling formal of Subp must be of mode "out",
8746                   --  "in out" or an access-to-variable to be overridden.
8747
8748                   --  Error message below needs rewording (remember comma
8749                   --  in -gnatj mode) ???
8750
8751                   if Ekind (First_Formal (Subp)) = E_In_Parameter
8752                     and then Ekind (Subp) /= E_Function
8753                   then
8754                      if not Is_Predefined_Dispatching_Operation (Subp) then
8755                         Error_Msg_NE
8756                           ("first formal of & must be of mode `OUT`, " &
8757                            "`IN OUT` or access-to-variable", T, Subp);
8758                         Error_Msg_N
8759                           ("\to be overridden by protected procedure or " &
8760                            "entry (RM 9.4(11.9/2))", T);
8761                      end if;
8762
8763                   --  Some other kind of overriding failure
8764
8765                   else
8766                      Error_Msg_NE
8767                        ("interface subprogram & must be overridden",
8768                         T, Subp);
8769
8770                      --  Examine primitive operations of synchronized type,
8771                      --  to find homonyms that have the wrong profile.
8772
8773                      declare
8774                         Prim : Entity_Id;
8775
8776                      begin
8777                         Prim :=
8778                           First_Entity (Corresponding_Concurrent_Type (T));
8779                         while Present (Prim) loop
8780                            if Chars (Prim) = Chars (Subp) then
8781                               Error_Msg_NE
8782                                 ("profile is not type conformant with "
8783                                    & "prefixed view profile of "
8784                                    & "inherited operation&", Prim, Subp);
8785                            end if;
8786
8787                            Next_Entity (Prim);
8788                         end loop;
8789                      end;
8790                   end if;
8791                end if;
8792
8793             else
8794                Error_Msg_Node_2 := T;
8795                Error_Msg_N
8796                  ("abstract subprogram& not allowed for type&", Subp);
8797
8798                --  Also post unconditional warning on the type (unconditional
8799                --  so that if there are more than one of these cases, we get
8800                --  them all, and not just the first one).
8801
8802                Error_Msg_Node_2 := Subp;
8803                Error_Msg_N ("nonabstract type& has abstract subprogram&!", T);
8804             end if;
8805          end if;
8806
8807          --  Ada 2012 (AI05-0030): Perform some checks related to pragma
8808          --  Implemented
8809
8810          --  Subp is an expander-generated procedure which maps an interface
8811          --  alias to a protected wrapper. The interface alias is flagged by
8812          --  pragma Implemented. Ensure that Subp is a procedure when the
8813          --  implementation kind is By_Protected_Procedure or an entry when
8814          --  By_Entry.
8815
8816          if Ada_Version >= Ada_2012
8817            and then Is_Hidden (Subp)
8818            and then Present (Interface_Alias (Subp))
8819            and then Has_Rep_Pragma (Interface_Alias (Subp), Name_Implemented)
8820          then
8821             Check_Pragma_Implemented (Subp);
8822          end if;
8823
8824          --  Subp is an interface primitive which overrides another interface
8825          --  primitive marked with pragma Implemented.
8826
8827          if Ada_Version >= Ada_2012
8828            and then Is_Overriding_Operation (Subp)
8829            and then Present (Overridden_Operation (Subp))
8830            and then Has_Rep_Pragma
8831                       (Overridden_Operation (Subp), Name_Implemented)
8832          then
8833             --  If the overriding routine is also marked by Implemented, check
8834             --  that the two implementation kinds are conforming.
8835
8836             if Has_Rep_Pragma (Subp, Name_Implemented) then
8837                Check_Pragma_Implemented
8838                  (Subp       => Subp,
8839                   Iface_Subp => Overridden_Operation (Subp));
8840
8841             --  Otherwise the overriding routine inherits the implementation
8842             --  kind from the overridden subprogram.
8843
8844             else
8845                Inherit_Pragma_Implemented
8846                  (Subp       => Subp,
8847                   Iface_Subp => Overridden_Operation (Subp));
8848             end if;
8849          end if;
8850
8851          Next_Elmt (Elmt);
8852       end loop;
8853    end Check_Abstract_Overriding;
8854
8855    ------------------------------------------------
8856    -- Check_Access_Discriminant_Requires_Limited --
8857    ------------------------------------------------
8858
8859    procedure Check_Access_Discriminant_Requires_Limited
8860      (D   : Node_Id;
8861       Loc : Node_Id)
8862    is
8863    begin
8864       --  A discriminant_specification for an access discriminant shall appear
8865       --  only in the declaration for a task or protected type, or for a type
8866       --  with the reserved word 'limited' in its definition or in one of its
8867       --  ancestors (RM 3.7(10)).
8868
8869       --  AI-0063: The proper condition is that type must be immutably limited,
8870       --  or else be a partial view.
8871
8872       if Nkind (Discriminant_Type (D)) = N_Access_Definition then
8873          if Is_Immutably_Limited_Type (Current_Scope)
8874            or else
8875              (Nkind (Parent (Current_Scope)) = N_Private_Type_Declaration
8876                and then Limited_Present (Parent (Current_Scope)))
8877          then
8878             null;
8879
8880          else
8881             Error_Msg_N
8882               ("access discriminants allowed only for limited types", Loc);
8883          end if;
8884       end if;
8885    end Check_Access_Discriminant_Requires_Limited;
8886
8887    -----------------------------------
8888    -- Check_Aliased_Component_Types --
8889    -----------------------------------
8890
8891    procedure Check_Aliased_Component_Types (T : Entity_Id) is
8892       C : Entity_Id;
8893
8894    begin
8895       --  ??? Also need to check components of record extensions, but not
8896       --  components of protected types (which are always limited).
8897
8898       --  Ada 2005: AI-363 relaxes this rule, to allow heap objects of such
8899       --  types to be unconstrained. This is safe because it is illegal to
8900       --  create access subtypes to such types with explicit discriminant
8901       --  constraints.
8902
8903       if not Is_Limited_Type (T) then
8904          if Ekind (T) = E_Record_Type then
8905             C := First_Component (T);
8906             while Present (C) loop
8907                if Is_Aliased (C)
8908                  and then Has_Discriminants (Etype (C))
8909                  and then not Is_Constrained (Etype (C))
8910                  and then not In_Instance_Body
8911                  and then Ada_Version < Ada_2005
8912                then
8913                   Error_Msg_N
8914                     ("aliased component must be constrained (RM 3.6(11))",
8915                       C);
8916                end if;
8917
8918                Next_Component (C);
8919             end loop;
8920
8921          elsif Ekind (T) = E_Array_Type then
8922             if Has_Aliased_Components (T)
8923               and then Has_Discriminants (Component_Type (T))
8924               and then not Is_Constrained (Component_Type (T))
8925               and then not In_Instance_Body
8926               and then Ada_Version < Ada_2005
8927             then
8928                Error_Msg_N
8929                  ("aliased component type must be constrained (RM 3.6(11))",
8930                     T);
8931             end if;
8932          end if;
8933       end if;
8934    end Check_Aliased_Component_Types;
8935
8936    ----------------------
8937    -- Check_Completion --
8938    ----------------------
8939
8940    procedure Check_Completion (Body_Id : Node_Id := Empty) is
8941       E : Entity_Id;
8942
8943       procedure Post_Error;
8944       --  Post error message for lack of completion for entity E
8945
8946       ----------------
8947       -- Post_Error --
8948       ----------------
8949
8950       procedure Post_Error is
8951
8952          procedure Missing_Body;
8953          --  Output missing body message
8954
8955          ------------------
8956          -- Missing_Body --
8957          ------------------
8958
8959          procedure Missing_Body is
8960          begin
8961             --  Spec is in same unit, so we can post on spec
8962
8963             if In_Same_Source_Unit (Body_Id, E) then
8964                Error_Msg_N ("missing body for &", E);
8965
8966             --  Spec is in a separate unit, so we have to post on the body
8967
8968             else
8969                Error_Msg_NE ("missing body for & declared#!", Body_Id, E);
8970             end if;
8971          end Missing_Body;
8972
8973       --  Start of processing for Post_Error
8974
8975       begin
8976          if not Comes_From_Source (E) then
8977
8978             if Ekind_In (E, E_Task_Type, E_Protected_Type) then
8979                --  It may be an anonymous protected type created for a
8980                --  single variable. Post error on variable, if present.
8981
8982                declare
8983                   Var : Entity_Id;
8984
8985                begin
8986                   Var := First_Entity (Current_Scope);
8987                   while Present (Var) loop
8988                      exit when Etype (Var) = E
8989                        and then Comes_From_Source (Var);
8990
8991                      Next_Entity (Var);
8992                   end loop;
8993
8994                   if Present (Var) then
8995                      E := Var;
8996                   end if;
8997                end;
8998             end if;
8999          end if;
9000
9001          --  If a generated entity has no completion, then either previous
9002          --  semantic errors have disabled the expansion phase, or else we had
9003          --  missing subunits, or else we are compiling without expansion,
9004          --  or else something is very wrong.
9005
9006          if not Comes_From_Source (E) then
9007             pragma Assert
9008               (Serious_Errors_Detected > 0
9009                 or else Configurable_Run_Time_Violations > 0
9010                 or else Subunits_Missing
9011                 or else not Expander_Active);
9012             return;
9013
9014          --  Here for source entity
9015
9016          else
9017             --  Here if no body to post the error message, so we post the error
9018             --  on the declaration that has no completion. This is not really
9019             --  the right place to post it, think about this later ???
9020
9021             if No (Body_Id) then
9022                if Is_Type (E) then
9023                   Error_Msg_NE
9024                     ("missing full declaration for }", Parent (E), E);
9025                else
9026                   Error_Msg_NE ("missing body for &", Parent (E), E);
9027                end if;
9028
9029             --  Package body has no completion for a declaration that appears
9030             --  in the corresponding spec. Post error on the body, with a
9031             --  reference to the non-completed declaration.
9032
9033             else
9034                Error_Msg_Sloc := Sloc (E);
9035
9036                if Is_Type (E) then
9037                   Error_Msg_NE ("missing full declaration for }!", Body_Id, E);
9038
9039                elsif Is_Overloadable (E)
9040                  and then Current_Entity_In_Scope (E) /= E
9041                then
9042                   --  It may be that the completion is mistyped and appears as
9043                   --  a distinct overloading of the entity.
9044
9045                   declare
9046                      Candidate : constant Entity_Id :=
9047                                    Current_Entity_In_Scope (E);
9048                      Decl      : constant Node_Id :=
9049                                    Unit_Declaration_Node (Candidate);
9050
9051                   begin
9052                      if Is_Overloadable (Candidate)
9053                        and then Ekind (Candidate) = Ekind (E)
9054                        and then Nkind (Decl) = N_Subprogram_Body
9055                        and then Acts_As_Spec (Decl)
9056                      then
9057                         Check_Type_Conformant (Candidate, E);
9058
9059                      else
9060                         Missing_Body;
9061                      end if;
9062                   end;
9063
9064                else
9065                   Missing_Body;
9066                end if;
9067             end if;
9068          end if;
9069       end Post_Error;
9070
9071    --  Start of processing for Check_Completion
9072
9073    begin
9074       E := First_Entity (Current_Scope);
9075       while Present (E) loop
9076          if Is_Intrinsic_Subprogram (E) then
9077             null;
9078
9079          --  The following situation requires special handling: a child unit
9080          --  that appears in the context clause of the body of its parent:
9081
9082          --    procedure Parent.Child (...);
9083
9084          --    with Parent.Child;
9085          --    package body Parent is
9086
9087          --  Here Parent.Child appears as a local entity, but should not be
9088          --  flagged as requiring completion, because it is a compilation
9089          --  unit.
9090
9091          --  Ignore missing completion for a subprogram that does not come from
9092          --  source (including the _Call primitive operation of RAS types,
9093          --  which has to have the flag Comes_From_Source for other purposes):
9094          --  we assume that the expander will provide the missing completion.
9095          --  In case of previous errors, other expansion actions that provide
9096          --  bodies for null procedures with not be invoked, so inhibit message
9097          --  in those cases.
9098          --  Note that E_Operator is not in the list that follows, because
9099          --  this kind is reserved for predefined operators, that are
9100          --  intrinsic and do not need completion.
9101
9102          elsif     Ekind (E) = E_Function
9103            or else Ekind (E) = E_Procedure
9104            or else Ekind (E) = E_Generic_Function
9105            or else Ekind (E) = E_Generic_Procedure
9106          then
9107             if Has_Completion (E) then
9108                null;
9109
9110             elsif Is_Subprogram (E) and then Is_Abstract_Subprogram (E) then
9111                null;
9112
9113             elsif Is_Subprogram (E)
9114               and then (not Comes_From_Source (E)
9115                           or else Chars (E) = Name_uCall)
9116             then
9117                null;
9118
9119             elsif
9120                Nkind (Parent (Unit_Declaration_Node (E))) = N_Compilation_Unit
9121             then
9122                null;
9123
9124             elsif Nkind (Parent (E)) = N_Procedure_Specification
9125               and then Null_Present (Parent (E))
9126               and then Serious_Errors_Detected > 0
9127             then
9128                null;
9129
9130             else
9131                Post_Error;
9132             end if;
9133
9134          elsif Is_Entry (E) then
9135             if not Has_Completion (E) and then
9136               (Ekind (Scope (E)) = E_Protected_Object
9137                 or else Ekind (Scope (E)) = E_Protected_Type)
9138             then
9139                Post_Error;
9140             end if;
9141
9142          elsif Is_Package_Or_Generic_Package (E) then
9143             if Unit_Requires_Body (E) then
9144                if not Has_Completion (E)
9145                  and then Nkind (Parent (Unit_Declaration_Node (E))) /=
9146                                                        N_Compilation_Unit
9147                then
9148                   Post_Error;
9149                end if;
9150
9151             elsif not Is_Child_Unit (E) then
9152                May_Need_Implicit_Body (E);
9153             end if;
9154
9155          elsif Ekind (E) = E_Incomplete_Type
9156            and then No (Underlying_Type (E))
9157          then
9158             Post_Error;
9159
9160          elsif (Ekind (E) = E_Task_Type or else
9161                 Ekind (E) = E_Protected_Type)
9162            and then not Has_Completion (E)
9163          then
9164             Post_Error;
9165
9166          --  A single task declared in the current scope is a constant, verify
9167          --  that the body of its anonymous type is in the same scope. If the
9168          --  task is defined elsewhere, this may be a renaming declaration for
9169          --  which no completion is needed.
9170
9171          elsif Ekind (E) = E_Constant
9172            and then Ekind (Etype (E)) = E_Task_Type
9173            and then not Has_Completion (Etype (E))
9174            and then Scope (Etype (E)) = Current_Scope
9175          then
9176             Post_Error;
9177
9178          elsif Ekind (E) = E_Protected_Object
9179            and then not Has_Completion (Etype (E))
9180          then
9181             Post_Error;
9182
9183          elsif Ekind (E) = E_Record_Type then
9184             if Is_Tagged_Type (E) then
9185                Check_Abstract_Overriding (E);
9186                Check_Conventions (E);
9187             end if;
9188
9189             Check_Aliased_Component_Types (E);
9190
9191          elsif Ekind (E) = E_Array_Type then
9192             Check_Aliased_Component_Types (E);
9193
9194          end if;
9195
9196          Next_Entity (E);
9197       end loop;
9198    end Check_Completion;
9199
9200    ----------------------------
9201    -- Check_Delta_Expression --
9202    ----------------------------
9203
9204    procedure Check_Delta_Expression (E : Node_Id) is
9205    begin
9206       if not (Is_Real_Type (Etype (E))) then
9207          Wrong_Type (E, Any_Real);
9208
9209       elsif not Is_OK_Static_Expression (E) then
9210          Flag_Non_Static_Expr
9211            ("non-static expression used for delta value!", E);
9212
9213       elsif not UR_Is_Positive (Expr_Value_R (E)) then
9214          Error_Msg_N ("delta expression must be positive", E);
9215
9216       else
9217          return;
9218       end if;
9219
9220       --  If any of above errors occurred, then replace the incorrect
9221       --  expression by the real 0.1, which should prevent further errors.
9222
9223       Rewrite (E,
9224         Make_Real_Literal (Sloc (E), Ureal_Tenth));
9225       Analyze_And_Resolve (E, Standard_Float);
9226    end Check_Delta_Expression;
9227
9228    -----------------------------
9229    -- Check_Digits_Expression --
9230    -----------------------------
9231
9232    procedure Check_Digits_Expression (E : Node_Id) is
9233    begin
9234       if not (Is_Integer_Type (Etype (E))) then
9235          Wrong_Type (E, Any_Integer);
9236
9237       elsif not Is_OK_Static_Expression (E) then
9238          Flag_Non_Static_Expr
9239            ("non-static expression used for digits value!", E);
9240
9241       elsif Expr_Value (E) <= 0 then
9242          Error_Msg_N ("digits value must be greater than zero", E);
9243
9244       else
9245          return;
9246       end if;
9247
9248       --  If any of above errors occurred, then replace the incorrect
9249       --  expression by the integer 1, which should prevent further errors.
9250
9251       Rewrite (E, Make_Integer_Literal (Sloc (E), 1));
9252       Analyze_And_Resolve (E, Standard_Integer);
9253
9254    end Check_Digits_Expression;
9255
9256    --------------------------
9257    -- Check_Initialization --
9258    --------------------------
9259
9260    procedure Check_Initialization (T : Entity_Id; Exp : Node_Id) is
9261    begin
9262       if Is_Limited_Type (T)
9263         and then not In_Instance
9264         and then not In_Inlined_Body
9265       then
9266          if not OK_For_Limited_Init (T, Exp) then
9267
9268             --  In GNAT mode, this is just a warning, to allow it to be evilly
9269             --  turned off. Otherwise it is a real error.
9270
9271             if GNAT_Mode then
9272                Error_Msg_N
9273                  ("?cannot initialize entities of limited type!", Exp);
9274
9275             elsif Ada_Version < Ada_2005 then
9276                Error_Msg_N
9277                  ("cannot initialize entities of limited type", Exp);
9278                Explain_Limited_Type (T, Exp);
9279
9280             else
9281                --  Specialize error message according to kind of illegal
9282                --  initial expression.
9283
9284                if Nkind (Exp) = N_Type_Conversion
9285                  and then Nkind (Expression (Exp)) = N_Function_Call
9286                then
9287                   Error_Msg_N
9288                     ("illegal context for call"
9289                       & " to function with limited result", Exp);
9290
9291                else
9292                   Error_Msg_N
9293                     ("initialization of limited object requires aggregate "
9294                       & "or function call",  Exp);
9295                end if;
9296             end if;
9297          end if;
9298       end if;
9299    end Check_Initialization;
9300
9301    ----------------------
9302    -- Check_Interfaces --
9303    ----------------------
9304
9305    procedure Check_Interfaces (N : Node_Id; Def : Node_Id) is
9306       Parent_Type : constant Entity_Id := Etype (Defining_Identifier (N));
9307
9308       Iface       : Node_Id;
9309       Iface_Def   : Node_Id;
9310       Iface_Typ   : Entity_Id;
9311       Parent_Node : Node_Id;
9312
9313       Is_Task : Boolean := False;
9314       --  Set True if parent type or any progenitor is a task interface
9315
9316       Is_Protected : Boolean := False;
9317       --  Set True if parent type or any progenitor is a protected interface
9318
9319       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id);
9320       --  Check that a progenitor is compatible with declaration.
9321       --  Error is posted on Error_Node.
9322
9323       ------------------
9324       -- Check_Ifaces --
9325       ------------------
9326
9327       procedure Check_Ifaces (Iface_Def : Node_Id; Error_Node : Node_Id) is
9328          Iface_Id : constant Entity_Id :=
9329                       Defining_Identifier (Parent (Iface_Def));
9330          Type_Def : Node_Id;
9331
9332       begin
9333          if Nkind (N) = N_Private_Extension_Declaration then
9334             Type_Def := N;
9335          else
9336             Type_Def := Type_Definition (N);
9337          end if;
9338
9339          if Is_Task_Interface (Iface_Id) then
9340             Is_Task := True;
9341
9342          elsif Is_Protected_Interface (Iface_Id) then
9343             Is_Protected := True;
9344          end if;
9345
9346          if Is_Synchronized_Interface (Iface_Id) then
9347
9348             --  A consequence of 3.9.4 (6/2) and 7.3 (7.2/2) is that a private
9349             --  extension derived from a synchronized interface must explicitly
9350             --  be declared synchronized, because the full view will be a
9351             --  synchronized type.
9352
9353             if Nkind (N) = N_Private_Extension_Declaration then
9354                if not Synchronized_Present (N) then
9355                   Error_Msg_NE
9356                     ("private extension of& must be explicitly synchronized",
9357                       N, Iface_Id);
9358                end if;
9359
9360             --  However, by 3.9.4(16/2), a full type that is a record extension
9361             --  is never allowed to derive from a synchronized interface (note
9362             --  that interfaces must be excluded from this check, because those
9363             --  are represented by derived type definitions in some cases).
9364
9365             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9366               and then not Interface_Present (Type_Definition (N))
9367             then
9368                Error_Msg_N ("record extension cannot derive from synchronized"
9369                              & " interface", Error_Node);
9370             end if;
9371          end if;
9372
9373          --  Check that the characteristics of the progenitor are compatible
9374          --  with the explicit qualifier in the declaration.
9375          --  The check only applies to qualifiers that come from source.
9376          --  Limited_Present also appears in the declaration of corresponding
9377          --  records, and the check does not apply to them.
9378
9379          if Limited_Present (Type_Def)
9380            and then not
9381              Is_Concurrent_Record_Type (Defining_Identifier (N))
9382          then
9383             if Is_Limited_Interface (Parent_Type)
9384               and then not Is_Limited_Interface (Iface_Id)
9385             then
9386                Error_Msg_NE
9387                  ("progenitor& must be limited interface",
9388                    Error_Node, Iface_Id);
9389
9390             elsif
9391               (Task_Present (Iface_Def)
9392                 or else Protected_Present (Iface_Def)
9393                 or else Synchronized_Present (Iface_Def))
9394               and then Nkind (N) /= N_Private_Extension_Declaration
9395               and then not Error_Posted (N)
9396             then
9397                Error_Msg_NE
9398                  ("progenitor& must be limited interface",
9399                    Error_Node, Iface_Id);
9400             end if;
9401
9402          --  Protected interfaces can only inherit from limited, synchronized
9403          --  or protected interfaces.
9404
9405          elsif Nkind (N) = N_Full_Type_Declaration
9406            and then  Protected_Present (Type_Def)
9407          then
9408             if Limited_Present (Iface_Def)
9409               or else Synchronized_Present (Iface_Def)
9410               or else Protected_Present (Iface_Def)
9411             then
9412                null;
9413
9414             elsif Task_Present (Iface_Def) then
9415                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9416                             & " from task interface", Error_Node);
9417
9418             else
9419                Error_Msg_N ("(Ada 2005) protected interface cannot inherit"
9420                             & " from non-limited interface", Error_Node);
9421             end if;
9422
9423          --  Ada 2005 (AI-345): Synchronized interfaces can only inherit from
9424          --  limited and synchronized.
9425
9426          elsif Synchronized_Present (Type_Def) then
9427             if Limited_Present (Iface_Def)
9428               or else Synchronized_Present (Iface_Def)
9429             then
9430                null;
9431
9432             elsif Protected_Present (Iface_Def)
9433               and then Nkind (N) /= N_Private_Extension_Declaration
9434             then
9435                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9436                             & " from protected interface", Error_Node);
9437
9438             elsif Task_Present (Iface_Def)
9439               and then Nkind (N) /= N_Private_Extension_Declaration
9440             then
9441                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9442                             & " from task interface", Error_Node);
9443
9444             elsif not Is_Limited_Interface (Iface_Id) then
9445                Error_Msg_N ("(Ada 2005) synchronized interface cannot inherit"
9446                             & " from non-limited interface", Error_Node);
9447             end if;
9448
9449          --  Ada 2005 (AI-345): Task interfaces can only inherit from limited,
9450          --  synchronized or task interfaces.
9451
9452          elsif Nkind (N) = N_Full_Type_Declaration
9453            and then Task_Present (Type_Def)
9454          then
9455             if Limited_Present (Iface_Def)
9456               or else Synchronized_Present (Iface_Def)
9457               or else Task_Present (Iface_Def)
9458             then
9459                null;
9460
9461             elsif Protected_Present (Iface_Def) then
9462                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9463                             & " protected interface", Error_Node);
9464
9465             else
9466                Error_Msg_N ("(Ada 2005) task interface cannot inherit from"
9467                             & " non-limited interface", Error_Node);
9468             end if;
9469          end if;
9470       end Check_Ifaces;
9471
9472    --  Start of processing for Check_Interfaces
9473
9474    begin
9475       if Is_Interface (Parent_Type) then
9476          if Is_Task_Interface (Parent_Type) then
9477             Is_Task := True;
9478
9479          elsif Is_Protected_Interface (Parent_Type) then
9480             Is_Protected := True;
9481          end if;
9482       end if;
9483
9484       if Nkind (N) = N_Private_Extension_Declaration then
9485
9486          --  Check that progenitors are compatible with declaration
9487
9488          Iface := First (Interface_List (Def));
9489          while Present (Iface) loop
9490             Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9491
9492             Parent_Node := Parent (Base_Type (Iface_Typ));
9493             Iface_Def   := Type_Definition (Parent_Node);
9494
9495             if not Is_Interface (Iface_Typ) then
9496                Diagnose_Interface (Iface, Iface_Typ);
9497
9498             else
9499                Check_Ifaces (Iface_Def, Iface);
9500             end if;
9501
9502             Next (Iface);
9503          end loop;
9504
9505          if Is_Task and Is_Protected then
9506             Error_Msg_N
9507               ("type cannot derive from task and protected interface", N);
9508          end if;
9509
9510          return;
9511       end if;
9512
9513       --  Full type declaration of derived type.
9514       --  Check compatibility with parent if it is interface type
9515
9516       if Nkind (Type_Definition (N)) = N_Derived_Type_Definition
9517         and then Is_Interface (Parent_Type)
9518       then
9519          Parent_Node := Parent (Parent_Type);
9520
9521          --  More detailed checks for interface varieties
9522
9523          Check_Ifaces
9524            (Iface_Def  => Type_Definition (Parent_Node),
9525             Error_Node => Subtype_Indication (Type_Definition (N)));
9526       end if;
9527
9528       Iface := First (Interface_List (Def));
9529       while Present (Iface) loop
9530          Iface_Typ := Find_Type_Of_Subtype_Indic (Iface);
9531
9532          Parent_Node := Parent (Base_Type (Iface_Typ));
9533          Iface_Def   := Type_Definition (Parent_Node);
9534
9535          if not Is_Interface (Iface_Typ) then
9536             Diagnose_Interface (Iface, Iface_Typ);
9537
9538          else
9539             --  "The declaration of a specific descendant of an interface
9540             --   type freezes the interface type" RM 13.14
9541
9542             Freeze_Before (N, Iface_Typ);
9543             Check_Ifaces (Iface_Def, Error_Node => Iface);
9544          end if;
9545
9546          Next (Iface);
9547       end loop;
9548
9549       if Is_Task and Is_Protected then
9550          Error_Msg_N
9551            ("type cannot derive from task and protected interface", N);
9552       end if;
9553    end Check_Interfaces;
9554
9555    ------------------------------------
9556    -- Check_Or_Process_Discriminants --
9557    ------------------------------------
9558
9559    --  If an incomplete or private type declaration was already given for the
9560    --  type, the discriminants may have already been processed if they were
9561    --  present on the incomplete declaration. In this case a full conformance
9562    --  check is performed otherwise just process them.
9563
9564    procedure Check_Or_Process_Discriminants
9565      (N    : Node_Id;
9566       T    : Entity_Id;
9567       Prev : Entity_Id := Empty)
9568    is
9569    begin
9570       if Has_Discriminants (T) then
9571
9572          --  Make the discriminants visible to component declarations
9573
9574          declare
9575             D    : Entity_Id;
9576             Prev : Entity_Id;
9577
9578          begin
9579             D := First_Discriminant (T);
9580             while Present (D) loop
9581                Prev := Current_Entity (D);
9582                Set_Current_Entity (D);
9583                Set_Is_Immediately_Visible (D);
9584                Set_Homonym (D, Prev);
9585
9586                --  Ada 2005 (AI-230): Access discriminant allowed in
9587                --  non-limited record types.
9588
9589                if Ada_Version < Ada_2005 then
9590
9591                   --  This restriction gets applied to the full type here. It
9592                   --  has already been applied earlier to the partial view.
9593
9594                   Check_Access_Discriminant_Requires_Limited (Parent (D), N);
9595                end if;
9596
9597                Next_Discriminant (D);
9598             end loop;
9599          end;
9600
9601       elsif Present (Discriminant_Specifications (N)) then
9602          Process_Discriminants (N, Prev);
9603       end if;
9604    end Check_Or_Process_Discriminants;
9605
9606    ----------------------
9607    -- Check_Real_Bound --
9608    ----------------------
9609
9610    procedure Check_Real_Bound (Bound : Node_Id) is
9611    begin
9612       if not Is_Real_Type (Etype (Bound)) then
9613          Error_Msg_N
9614            ("bound in real type definition must be of real type", Bound);
9615
9616       elsif not Is_OK_Static_Expression (Bound) then
9617          Flag_Non_Static_Expr
9618            ("non-static expression used for real type bound!", Bound);
9619
9620       else
9621          return;
9622       end if;
9623
9624       Rewrite
9625         (Bound, Make_Real_Literal (Sloc (Bound), Ureal_0));
9626       Analyze (Bound);
9627       Resolve (Bound, Standard_Float);
9628    end Check_Real_Bound;
9629
9630    ------------------------------
9631    -- Complete_Private_Subtype --
9632    ------------------------------
9633
9634    procedure Complete_Private_Subtype
9635      (Priv        : Entity_Id;
9636       Full        : Entity_Id;
9637       Full_Base   : Entity_Id;
9638       Related_Nod : Node_Id)
9639    is
9640       Save_Next_Entity : Entity_Id;
9641       Save_Homonym     : Entity_Id;
9642
9643    begin
9644       --  Set semantic attributes for (implicit) private subtype completion.
9645       --  If the full type has no discriminants, then it is a copy of the full
9646       --  view of the base. Otherwise, it is a subtype of the base with a
9647       --  possible discriminant constraint. Save and restore the original
9648       --  Next_Entity field of full to ensure that the calls to Copy_Node
9649       --  do not corrupt the entity chain.
9650
9651       --  Note that the type of the full view is the same entity as the type of
9652       --  the partial view. In this fashion, the subtype has access to the
9653       --  correct view of the parent.
9654
9655       Save_Next_Entity := Next_Entity (Full);
9656       Save_Homonym     := Homonym (Priv);
9657
9658       case Ekind (Full_Base) is
9659          when E_Record_Type    |
9660               E_Record_Subtype |
9661               Class_Wide_Kind  |
9662               Private_Kind     |
9663               Task_Kind        |
9664               Protected_Kind   =>
9665             Copy_Node (Priv, Full);
9666
9667             Set_Has_Discriminants  (Full, Has_Discriminants (Full_Base));
9668             Set_First_Entity       (Full, First_Entity (Full_Base));
9669             Set_Last_Entity        (Full, Last_Entity (Full_Base));
9670
9671          when others =>
9672             Copy_Node (Full_Base, Full);
9673             Set_Chars          (Full, Chars (Priv));
9674             Conditional_Delay  (Full, Priv);
9675             Set_Sloc           (Full, Sloc (Priv));
9676       end case;
9677
9678       Set_Next_Entity (Full, Save_Next_Entity);
9679       Set_Homonym     (Full, Save_Homonym);
9680       Set_Associated_Node_For_Itype (Full, Related_Nod);
9681
9682       --  Set common attributes for all subtypes
9683
9684       Set_Ekind (Full, Subtype_Kind (Ekind (Full_Base)));
9685
9686       --  The Etype of the full view is inconsistent. Gigi needs to see the
9687       --  structural full view,  which is what the current scheme gives:
9688       --  the Etype of the full view is the etype of the full base. However,
9689       --  if the full base is a derived type, the full view then looks like
9690       --  a subtype of the parent, not a subtype of the full base. If instead
9691       --  we write:
9692
9693       --       Set_Etype (Full, Full_Base);
9694
9695       --  then we get inconsistencies in the front-end (confusion between
9696       --  views). Several outstanding bugs are related to this ???
9697
9698       Set_Is_First_Subtype (Full, False);
9699       Set_Scope            (Full, Scope (Priv));
9700       Set_Size_Info        (Full, Full_Base);
9701       Set_RM_Size          (Full, RM_Size (Full_Base));
9702       Set_Is_Itype         (Full);
9703
9704       --  A subtype of a private-type-without-discriminants, whose full-view
9705       --  has discriminants with default expressions, is not constrained!
9706
9707       if not Has_Discriminants (Priv) then
9708          Set_Is_Constrained (Full, Is_Constrained (Full_Base));
9709
9710          if Has_Discriminants (Full_Base) then
9711             Set_Discriminant_Constraint
9712               (Full, Discriminant_Constraint (Full_Base));
9713
9714             --  The partial view may have been indefinite, the full view
9715             --  might not be.
9716
9717             Set_Has_Unknown_Discriminants
9718               (Full, Has_Unknown_Discriminants (Full_Base));
9719          end if;
9720       end if;
9721
9722       Set_First_Rep_Item     (Full, First_Rep_Item (Full_Base));
9723       Set_Depends_On_Private (Full, Has_Private_Component (Full));
9724
9725       --  Freeze the private subtype entity if its parent is delayed, and not
9726       --  already frozen. We skip this processing if the type is an anonymous
9727       --  subtype of a record component, or is the corresponding record of a
9728       --  protected type, since ???
9729
9730       if not Is_Type (Scope (Full)) then
9731          Set_Has_Delayed_Freeze (Full,
9732            Has_Delayed_Freeze (Full_Base)
9733              and then (not Is_Frozen (Full_Base)));
9734       end if;
9735
9736       Set_Freeze_Node (Full, Empty);
9737       Set_Is_Frozen (Full, False);
9738       Set_Full_View (Priv, Full);
9739
9740       if Has_Discriminants (Full) then
9741          Set_Stored_Constraint_From_Discriminant_Constraint (Full);
9742          Set_Stored_Constraint (Priv, Stored_Constraint (Full));
9743
9744          if Has_Unknown_Discriminants (Full) then
9745             Set_Discriminant_Constraint (Full, No_Elist);
9746          end if;
9747       end if;
9748
9749       if Ekind (Full_Base) = E_Record_Type
9750         and then Has_Discriminants (Full_Base)
9751         and then Has_Discriminants (Priv) -- might not, if errors
9752         and then not Has_Unknown_Discriminants (Priv)
9753         and then not Is_Empty_Elmt_List (Discriminant_Constraint (Priv))
9754       then
9755          Create_Constrained_Components
9756            (Full, Related_Nod, Full_Base, Discriminant_Constraint (Priv));
9757
9758       --  If the full base is itself derived from private, build a congruent
9759       --  subtype of its underlying type, for use by the back end. For a
9760       --  constrained record component, the declaration cannot be placed on
9761       --  the component list, but it must nevertheless be built an analyzed, to
9762       --  supply enough information for Gigi to compute the size of component.
9763
9764       elsif Ekind (Full_Base) in Private_Kind
9765         and then Is_Derived_Type (Full_Base)
9766         and then Has_Discriminants (Full_Base)
9767         and then (Ekind (Current_Scope) /= E_Record_Subtype)
9768       then
9769          if not Is_Itype (Priv)
9770            and then
9771              Nkind (Subtype_Indication (Parent (Priv))) = N_Subtype_Indication
9772          then
9773             Build_Underlying_Full_View
9774               (Parent (Priv), Full, Etype (Full_Base));
9775
9776          elsif Nkind (Related_Nod) = N_Component_Declaration then
9777             Build_Underlying_Full_View (Related_Nod, Full, Etype (Full_Base));
9778          end if;
9779
9780       elsif Is_Record_Type (Full_Base) then
9781
9782          --  Show Full is simply a renaming of Full_Base
9783
9784          Set_Cloned_Subtype (Full, Full_Base);
9785       end if;
9786
9787       --  It is unsafe to share to bounds of a scalar type, because the Itype
9788       --  is elaborated on demand, and if a bound is non-static then different
9789       --  orders of elaboration in different units will lead to different
9790       --  external symbols.
9791
9792       if Is_Scalar_Type (Full_Base) then
9793          Set_Scalar_Range (Full,
9794            Make_Range (Sloc (Related_Nod),
9795              Low_Bound  =>
9796                Duplicate_Subexpr_No_Checks (Type_Low_Bound  (Full_Base)),
9797              High_Bound =>
9798                Duplicate_Subexpr_No_Checks (Type_High_Bound (Full_Base))));
9799
9800          --  This completion inherits the bounds of the full parent, but if
9801          --  the parent is an unconstrained floating point type, so is the
9802          --  completion.
9803
9804          if Is_Floating_Point_Type (Full_Base) then
9805             Set_Includes_Infinities
9806              (Scalar_Range (Full), Has_Infinities (Full_Base));
9807          end if;
9808       end if;
9809
9810       --  ??? It seems that a lot of fields are missing that should be copied
9811       --  from Full_Base to Full. Here are some that are introduced in a
9812       --  non-disruptive way but a cleanup is necessary.
9813
9814       if Is_Tagged_Type (Full_Base) then
9815          Set_Is_Tagged_Type (Full);
9816          Set_Direct_Primitive_Operations (Full,
9817            Direct_Primitive_Operations (Full_Base));
9818
9819          --  Inherit class_wide type of full_base in case the partial view was
9820          --  not tagged. Otherwise it has already been created when the private
9821          --  subtype was analyzed.
9822
9823          if No (Class_Wide_Type (Full)) then
9824             Set_Class_Wide_Type (Full, Class_Wide_Type (Full_Base));
9825          end if;
9826
9827       --  If this is a subtype of a protected or task type, constrain its
9828       --  corresponding record, unless this is a subtype without constraints,
9829       --  i.e. a simple renaming as with an actual subtype in an instance.
9830
9831       elsif Is_Concurrent_Type (Full_Base) then
9832          if Has_Discriminants (Full)
9833            and then Present (Corresponding_Record_Type (Full_Base))
9834            and then
9835              not Is_Empty_Elmt_List (Discriminant_Constraint (Full))
9836          then
9837             Set_Corresponding_Record_Type (Full,
9838               Constrain_Corresponding_Record
9839                 (Full, Corresponding_Record_Type (Full_Base),
9840                   Related_Nod, Full_Base));
9841
9842          else
9843             Set_Corresponding_Record_Type (Full,
9844               Corresponding_Record_Type (Full_Base));
9845          end if;
9846       end if;
9847    end Complete_Private_Subtype;
9848
9849    ----------------------------
9850    -- Constant_Redeclaration --
9851    ----------------------------
9852
9853    procedure Constant_Redeclaration
9854      (Id : Entity_Id;
9855       N  : Node_Id;
9856       T  : out Entity_Id)
9857    is
9858       Prev    : constant Entity_Id := Current_Entity_In_Scope (Id);
9859       Obj_Def : constant Node_Id := Object_Definition (N);
9860       New_T   : Entity_Id;
9861
9862       procedure Check_Possible_Deferred_Completion
9863         (Prev_Id      : Entity_Id;
9864          Prev_Obj_Def : Node_Id;
9865          Curr_Obj_Def : Node_Id);
9866       --  Determine whether the two object definitions describe the partial
9867       --  and the full view of a constrained deferred constant. Generate
9868       --  a subtype for the full view and verify that it statically matches
9869       --  the subtype of the partial view.
9870
9871       procedure Check_Recursive_Declaration (Typ : Entity_Id);
9872       --  If deferred constant is an access type initialized with an allocator,
9873       --  check whether there is an illegal recursion in the definition,
9874       --  through a default value of some record subcomponent. This is normally
9875       --  detected when generating init procs, but requires this additional
9876       --  mechanism when expansion is disabled.
9877
9878       ----------------------------------------
9879       -- Check_Possible_Deferred_Completion --
9880       ----------------------------------------
9881
9882       procedure Check_Possible_Deferred_Completion
9883         (Prev_Id      : Entity_Id;
9884          Prev_Obj_Def : Node_Id;
9885          Curr_Obj_Def : Node_Id)
9886       is
9887       begin
9888          if Nkind (Prev_Obj_Def) = N_Subtype_Indication
9889            and then Present (Constraint (Prev_Obj_Def))
9890            and then Nkind (Curr_Obj_Def) = N_Subtype_Indication
9891            and then Present (Constraint (Curr_Obj_Def))
9892          then
9893             declare
9894                Loc    : constant Source_Ptr := Sloc (N);
9895                Def_Id : constant Entity_Id  := Make_Temporary (Loc, 'S');
9896                Decl   : constant Node_Id    :=
9897                           Make_Subtype_Declaration (Loc,
9898                             Defining_Identifier => Def_Id,
9899                             Subtype_Indication  =>
9900                               Relocate_Node (Curr_Obj_Def));
9901
9902             begin
9903                Insert_Before_And_Analyze (N, Decl);
9904                Set_Etype (Id, Def_Id);
9905
9906                if not Subtypes_Statically_Match (Etype (Prev_Id), Def_Id) then
9907                   Error_Msg_Sloc := Sloc (Prev_Id);
9908                   Error_Msg_N ("subtype does not statically match deferred " &
9909                                "declaration#", N);
9910                end if;
9911             end;
9912          end if;
9913       end Check_Possible_Deferred_Completion;
9914
9915       ---------------------------------
9916       -- Check_Recursive_Declaration --
9917       ---------------------------------
9918
9919       procedure Check_Recursive_Declaration (Typ : Entity_Id) is
9920          Comp : Entity_Id;
9921
9922       begin
9923          if Is_Record_Type (Typ) then
9924             Comp := First_Component (Typ);
9925             while Present (Comp) loop
9926                if Comes_From_Source (Comp) then
9927                   if Present (Expression (Parent (Comp)))
9928                     and then Is_Entity_Name (Expression (Parent (Comp)))
9929                     and then Entity (Expression (Parent (Comp))) = Prev
9930                   then
9931                      Error_Msg_Sloc := Sloc (Parent (Comp));
9932                      Error_Msg_NE
9933                        ("illegal circularity with declaration for&#",
9934                          N, Comp);
9935                      return;
9936
9937                   elsif Is_Record_Type (Etype (Comp)) then
9938                      Check_Recursive_Declaration (Etype (Comp));
9939                   end if;
9940                end if;
9941
9942                Next_Component (Comp);
9943             end loop;
9944          end if;
9945       end Check_Recursive_Declaration;
9946
9947    --  Start of processing for Constant_Redeclaration
9948
9949    begin
9950       if Nkind (Parent (Prev)) = N_Object_Declaration then
9951          if Nkind (Object_Definition
9952                      (Parent (Prev))) = N_Subtype_Indication
9953          then
9954             --  Find type of new declaration. The constraints of the two
9955             --  views must match statically, but there is no point in
9956             --  creating an itype for the full view.
9957
9958             if Nkind (Obj_Def) = N_Subtype_Indication then
9959                Find_Type (Subtype_Mark (Obj_Def));
9960                New_T := Entity (Subtype_Mark (Obj_Def));
9961
9962             else
9963                Find_Type (Obj_Def);
9964                New_T := Entity (Obj_Def);
9965             end if;
9966
9967             T := Etype (Prev);
9968
9969          else
9970             --  The full view may impose a constraint, even if the partial
9971             --  view does not, so construct the subtype.
9972
9973             New_T := Find_Type_Of_Object (Obj_Def, N);
9974             T     := New_T;
9975          end if;
9976
9977       else
9978          --  Current declaration is illegal, diagnosed below in Enter_Name
9979
9980          T := Empty;
9981          New_T := Any_Type;
9982       end if;
9983
9984       --  If previous full declaration or a renaming declaration exists, or if
9985       --  a homograph is present, let Enter_Name handle it, either with an
9986       --  error or with the removal of an overridden implicit subprogram.
9987
9988       if Ekind (Prev) /= E_Constant
9989         or else Nkind (Parent (Prev)) = N_Object_Renaming_Declaration
9990         or else Present (Expression (Parent (Prev)))
9991         or else Present (Full_View (Prev))
9992       then
9993          Enter_Name (Id);
9994
9995       --  Verify that types of both declarations match, or else that both types
9996       --  are anonymous access types whose designated subtypes statically match
9997       --  (as allowed in Ada 2005 by AI-385).
9998
9999       elsif Base_Type (Etype (Prev)) /= Base_Type (New_T)
10000         and then
10001           (Ekind (Etype (Prev)) /= E_Anonymous_Access_Type
10002              or else Ekind (Etype (New_T)) /= E_Anonymous_Access_Type
10003              or else Is_Access_Constant (Etype (New_T)) /=
10004                      Is_Access_Constant (Etype (Prev))
10005              or else Can_Never_Be_Null (Etype (New_T)) /=
10006                      Can_Never_Be_Null (Etype (Prev))
10007              or else Null_Exclusion_Present (Parent (Prev)) /=
10008                      Null_Exclusion_Present (Parent (Id))
10009              or else not Subtypes_Statically_Match
10010                            (Designated_Type (Etype (Prev)),
10011                             Designated_Type (Etype (New_T))))
10012       then
10013          Error_Msg_Sloc := Sloc (Prev);
10014          Error_Msg_N ("type does not match declaration#", N);
10015          Set_Full_View (Prev, Id);
10016          Set_Etype (Id, Any_Type);
10017
10018       elsif
10019         Null_Exclusion_Present (Parent (Prev))
10020           and then not Null_Exclusion_Present (N)
10021       then
10022          Error_Msg_Sloc := Sloc (Prev);
10023          Error_Msg_N ("null-exclusion does not match declaration#", N);
10024          Set_Full_View (Prev, Id);
10025          Set_Etype (Id, Any_Type);
10026
10027       --  If so, process the full constant declaration
10028
10029       else
10030          --  RM 7.4 (6): If the subtype defined by the subtype_indication in
10031          --  the deferred declaration is constrained, then the subtype defined
10032          --  by the subtype_indication in the full declaration shall match it
10033          --  statically.
10034
10035          Check_Possible_Deferred_Completion
10036            (Prev_Id      => Prev,
10037             Prev_Obj_Def => Object_Definition (Parent (Prev)),
10038             Curr_Obj_Def => Obj_Def);
10039
10040          Set_Full_View (Prev, Id);
10041          Set_Is_Public (Id, Is_Public (Prev));
10042          Set_Is_Internal (Id);
10043          Append_Entity (Id, Current_Scope);
10044
10045          --  Check ALIASED present if present before (RM 7.4(7))
10046
10047          if Is_Aliased (Prev)
10048            and then not Aliased_Present (N)
10049          then
10050             Error_Msg_Sloc := Sloc (Prev);
10051             Error_Msg_N ("ALIASED required (see declaration#)", N);
10052          end if;
10053
10054          --  Check that placement is in private part and that the incomplete
10055          --  declaration appeared in the visible part.
10056
10057          if Ekind (Current_Scope) = E_Package
10058            and then not In_Private_Part (Current_Scope)
10059          then
10060             Error_Msg_Sloc := Sloc (Prev);
10061             Error_Msg_N
10062               ("full constant for declaration#"
10063                & " must be in private part", N);
10064
10065          elsif Ekind (Current_Scope) = E_Package
10066            and then
10067              List_Containing (Parent (Prev)) /=
10068                Visible_Declarations
10069                  (Specification (Unit_Declaration_Node (Current_Scope)))
10070          then
10071             Error_Msg_N
10072               ("deferred constant must be declared in visible part",
10073                  Parent (Prev));
10074          end if;
10075
10076          if Is_Access_Type (T)
10077            and then Nkind (Expression (N)) = N_Allocator
10078          then
10079             Check_Recursive_Declaration (Designated_Type (T));
10080          end if;
10081       end if;
10082    end Constant_Redeclaration;
10083
10084    ----------------------
10085    -- Constrain_Access --
10086    ----------------------
10087
10088    procedure Constrain_Access
10089      (Def_Id      : in out Entity_Id;
10090       S           : Node_Id;
10091       Related_Nod : Node_Id)
10092    is
10093       T             : constant Entity_Id := Entity (Subtype_Mark (S));
10094       Desig_Type    : constant Entity_Id := Designated_Type (T);
10095       Desig_Subtype : Entity_Id := Create_Itype (E_Void, Related_Nod);
10096       Constraint_OK : Boolean := True;
10097
10098       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean;
10099       --  Simple predicate to test for defaulted discriminants
10100       --  Shouldn't this be in sem_util???
10101
10102       ---------------------------------
10103       -- Has_Defaulted_Discriminants --
10104       ---------------------------------
10105
10106       function Has_Defaulted_Discriminants (Typ : Entity_Id) return Boolean is
10107       begin
10108          return Has_Discriminants (Typ)
10109           and then Present (First_Discriminant (Typ))
10110           and then Present
10111             (Discriminant_Default_Value (First_Discriminant (Typ)));
10112       end Has_Defaulted_Discriminants;
10113
10114    --  Start of processing for Constrain_Access
10115
10116    begin
10117       if Is_Array_Type (Desig_Type) then
10118          Constrain_Array (Desig_Subtype, S, Related_Nod, Def_Id, 'P');
10119
10120       elsif (Is_Record_Type (Desig_Type)
10121               or else Is_Incomplete_Or_Private_Type (Desig_Type))
10122         and then not Is_Constrained (Desig_Type)
10123       then
10124          --  ??? The following code is a temporary kludge to ignore a
10125          --  discriminant constraint on access type if it is constraining
10126          --  the current record. Avoid creating the implicit subtype of the
10127          --  record we are currently compiling since right now, we cannot
10128          --  handle these. For now, just return the access type itself.
10129
10130          if Desig_Type = Current_Scope
10131            and then No (Def_Id)
10132          then
10133             Set_Ekind (Desig_Subtype, E_Record_Subtype);
10134             Def_Id := Entity (Subtype_Mark (S));
10135
10136             --  This call added to ensure that the constraint is analyzed
10137             --  (needed for a B test). Note that we still return early from
10138             --  this procedure to avoid recursive processing. ???
10139
10140             Constrain_Discriminated_Type
10141               (Desig_Subtype, S, Related_Nod, For_Access => True);
10142             return;
10143          end if;
10144
10145          if (Ekind (T) = E_General_Access_Type
10146               or else Ada_Version >= Ada_2005)
10147            and then Has_Private_Declaration (Desig_Type)
10148            and then In_Open_Scopes (Scope (Desig_Type))
10149            and then Has_Discriminants (Desig_Type)
10150          then
10151             --  Enforce rule that the constraint is illegal if there is
10152             --  an unconstrained view of the designated type. This means
10153             --  that the partial view (either a private type declaration or
10154             --  a derivation from a private type) has no discriminants.
10155             --  (Defect Report 8652/0008, Technical Corrigendum 1, checked
10156             --  by ACATS B371001).
10157
10158             --  Rule updated for Ada 2005: the private type is said to have
10159             --  a constrained partial view, given that objects of the type
10160             --  can be declared. Furthermore, the rule applies to all access
10161             --  types, unlike the rule concerning default discriminants.
10162
10163             declare
10164                Pack  : constant Node_Id :=
10165                          Unit_Declaration_Node (Scope (Desig_Type));
10166                Decls : List_Id;
10167                Decl  : Node_Id;
10168
10169             begin
10170                if Nkind (Pack) = N_Package_Declaration then
10171                   Decls := Visible_Declarations (Specification (Pack));
10172                   Decl := First (Decls);
10173                   while Present (Decl) loop
10174                      if (Nkind (Decl) = N_Private_Type_Declaration
10175                           and then
10176                             Chars (Defining_Identifier (Decl)) =
10177                                                      Chars (Desig_Type))
10178
10179                        or else
10180                         (Nkind (Decl) = N_Full_Type_Declaration
10181                           and then
10182                             Chars (Defining_Identifier (Decl)) =
10183                                                      Chars (Desig_Type)
10184                           and then Is_Derived_Type (Desig_Type)
10185                           and then
10186                             Has_Private_Declaration (Etype (Desig_Type)))
10187                      then
10188                         if No (Discriminant_Specifications (Decl)) then
10189                            Error_Msg_N
10190                             ("cannot constrain general access type if " &
10191                                "designated type has constrained partial view",
10192                                 S);
10193                         end if;
10194
10195                         exit;
10196                      end if;
10197
10198                      Next (Decl);
10199                   end loop;
10200                end if;
10201             end;
10202          end if;
10203
10204          Constrain_Discriminated_Type (Desig_Subtype, S, Related_Nod,
10205            For_Access => True);
10206
10207       elsif (Is_Task_Type (Desig_Type)
10208               or else Is_Protected_Type (Desig_Type))
10209         and then not Is_Constrained (Desig_Type)
10210       then
10211          Constrain_Concurrent
10212            (Desig_Subtype, S, Related_Nod, Desig_Type, ' ');
10213
10214       else
10215          Error_Msg_N ("invalid constraint on access type", S);
10216          Desig_Subtype := Desig_Type; -- Ignore invalid constraint.
10217          Constraint_OK := False;
10218       end if;
10219
10220       if No (Def_Id) then
10221          Def_Id := Create_Itype (E_Access_Subtype, Related_Nod);
10222       else
10223          Set_Ekind (Def_Id, E_Access_Subtype);
10224       end if;
10225
10226       if Constraint_OK then
10227          Set_Etype (Def_Id, Base_Type (T));
10228
10229          if Is_Private_Type (Desig_Type) then
10230             Prepare_Private_Subtype_Completion (Desig_Subtype, Related_Nod);
10231          end if;
10232       else
10233          Set_Etype (Def_Id, Any_Type);
10234       end if;
10235
10236       Set_Size_Info                (Def_Id, T);
10237       Set_Is_Constrained           (Def_Id, Constraint_OK);
10238       Set_Directly_Designated_Type (Def_Id, Desig_Subtype);
10239       Set_Depends_On_Private       (Def_Id, Has_Private_Component (Def_Id));
10240       Set_Is_Access_Constant       (Def_Id, Is_Access_Constant (T));
10241
10242       Conditional_Delay (Def_Id, T);
10243
10244       --  AI-363 : Subtypes of general access types whose designated types have
10245       --  default discriminants are disallowed. In instances, the rule has to
10246       --  be checked against the actual, of which T is the subtype. In a
10247       --  generic body, the rule is checked assuming that the actual type has
10248       --  defaulted discriminants.
10249
10250       if Ada_Version >= Ada_2005 or else Warn_On_Ada_2005_Compatibility then
10251          if Ekind (Base_Type (T)) = E_General_Access_Type
10252            and then Has_Defaulted_Discriminants (Desig_Type)
10253          then
10254             if Ada_Version < Ada_2005 then
10255                Error_Msg_N
10256                  ("access subtype of general access type would not " &
10257                   "be allowed in Ada 2005?", S);
10258             else
10259                Error_Msg_N
10260                  ("access subype of general access type not allowed", S);
10261             end if;
10262
10263             Error_Msg_N ("\discriminants have defaults", S);
10264
10265          elsif Is_Access_Type (T)
10266            and then Is_Generic_Type (Desig_Type)
10267            and then Has_Discriminants (Desig_Type)
10268            and then In_Package_Body (Current_Scope)
10269          then
10270             if Ada_Version < Ada_2005 then
10271                Error_Msg_N
10272                  ("access subtype would not be allowed in generic body " &
10273                   "in Ada 2005?", S);
10274             else
10275                Error_Msg_N
10276                  ("access subtype not allowed in generic body", S);
10277             end if;
10278
10279             Error_Msg_N
10280               ("\designated type is a discriminated formal", S);
10281          end if;
10282       end if;
10283    end Constrain_Access;
10284
10285    ---------------------
10286    -- Constrain_Array --
10287    ---------------------
10288
10289    procedure Constrain_Array
10290      (Def_Id      : in out Entity_Id;
10291       SI          : Node_Id;
10292       Related_Nod : Node_Id;
10293       Related_Id  : Entity_Id;
10294       Suffix      : Character)
10295    is
10296       C                     : constant Node_Id := Constraint (SI);
10297       Number_Of_Constraints : Nat := 0;
10298       Index                 : Node_Id;
10299       S, T                  : Entity_Id;
10300       Constraint_OK         : Boolean := True;
10301
10302    begin
10303       T := Entity (Subtype_Mark (SI));
10304
10305       if Ekind (T) in Access_Kind then
10306          T := Designated_Type (T);
10307       end if;
10308
10309       --  If an index constraint follows a subtype mark in a subtype indication
10310       --  then the type or subtype denoted by the subtype mark must not already
10311       --  impose an index constraint. The subtype mark must denote either an
10312       --  unconstrained array type or an access type whose designated type
10313       --  is such an array type... (RM 3.6.1)
10314
10315       if Is_Constrained (T) then
10316          Error_Msg_N ("array type is already constrained", Subtype_Mark (SI));
10317          Constraint_OK := False;
10318
10319       else
10320          S := First (Constraints (C));
10321          while Present (S) loop
10322             Number_Of_Constraints := Number_Of_Constraints + 1;
10323             Next (S);
10324          end loop;
10325
10326          --  In either case, the index constraint must provide a discrete
10327          --  range for each index of the array type and the type of each
10328          --  discrete range must be the same as that of the corresponding
10329          --  index. (RM 3.6.1)
10330
10331          if Number_Of_Constraints /= Number_Dimensions (T) then
10332             Error_Msg_NE ("incorrect number of index constraints for }", C, T);
10333             Constraint_OK := False;
10334
10335          else
10336             S := First (Constraints (C));
10337             Index := First_Index (T);
10338             Analyze (Index);
10339
10340             --  Apply constraints to each index type
10341
10342             for J in 1 .. Number_Of_Constraints loop
10343                Constrain_Index (Index, S, Related_Nod, Related_Id, Suffix, J);
10344                Next (Index);
10345                Next (S);
10346             end loop;
10347
10348          end if;
10349       end if;
10350
10351       if No (Def_Id) then
10352          Def_Id :=
10353            Create_Itype (E_Array_Subtype, Related_Nod, Related_Id, Suffix);
10354          Set_Parent (Def_Id, Related_Nod);
10355
10356       else
10357          Set_Ekind (Def_Id, E_Array_Subtype);
10358       end if;
10359
10360       Set_Size_Info      (Def_Id,                (T));
10361       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
10362       Set_Etype          (Def_Id, Base_Type      (T));
10363
10364       if Constraint_OK then
10365          Set_First_Index (Def_Id, First (Constraints (C)));
10366       else
10367          Set_First_Index (Def_Id, First_Index (T));
10368       end if;
10369
10370       Set_Is_Constrained     (Def_Id, True);
10371       Set_Is_Aliased         (Def_Id, Is_Aliased (T));
10372       Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10373
10374       Set_Is_Private_Composite (Def_Id, Is_Private_Composite (T));
10375       Set_Is_Limited_Composite (Def_Id, Is_Limited_Composite (T));
10376
10377       --  A subtype does not inherit the packed_array_type of is parent. We
10378       --  need to initialize the attribute because if Def_Id is previously
10379       --  analyzed through a limited_with clause, it will have the attributes
10380       --  of an incomplete type, one of which is an Elist that overlaps the
10381       --  Packed_Array_Type field.
10382
10383       Set_Packed_Array_Type (Def_Id, Empty);
10384
10385       --  Build a freeze node if parent still needs one. Also make sure that
10386       --  the Depends_On_Private status is set because the subtype will need
10387       --  reprocessing at the time the base type does, and also we must set a
10388       --  conditional delay.
10389
10390       Set_Depends_On_Private (Def_Id, Depends_On_Private (T));
10391       Conditional_Delay (Def_Id, T);
10392    end Constrain_Array;
10393
10394    ------------------------------
10395    -- Constrain_Component_Type --
10396    ------------------------------
10397
10398    function Constrain_Component_Type
10399      (Comp            : Entity_Id;
10400       Constrained_Typ : Entity_Id;
10401       Related_Node    : Node_Id;
10402       Typ             : Entity_Id;
10403       Constraints     : Elist_Id) return Entity_Id
10404    is
10405       Loc         : constant Source_Ptr := Sloc (Constrained_Typ);
10406       Compon_Type : constant Entity_Id := Etype (Comp);
10407
10408       function Build_Constrained_Array_Type
10409         (Old_Type : Entity_Id) return Entity_Id;
10410       --  If Old_Type is an array type, one of whose indices is constrained
10411       --  by a discriminant, build an Itype whose constraint replaces the
10412       --  discriminant with its value in the constraint.
10413
10414       function Build_Constrained_Discriminated_Type
10415         (Old_Type : Entity_Id) return Entity_Id;
10416       --  Ditto for record components
10417
10418       function Build_Constrained_Access_Type
10419         (Old_Type : Entity_Id) return Entity_Id;
10420       --  Ditto for access types. Makes use of previous two functions, to
10421       --  constrain designated type.
10422
10423       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id;
10424       --  T is an array or discriminated type, C is a list of constraints
10425       --  that apply to T. This routine builds the constrained subtype.
10426
10427       function Is_Discriminant (Expr : Node_Id) return Boolean;
10428       --  Returns True if Expr is a discriminant
10429
10430       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id;
10431       --  Find the value of discriminant Discrim in Constraint
10432
10433       -----------------------------------
10434       -- Build_Constrained_Access_Type --
10435       -----------------------------------
10436
10437       function Build_Constrained_Access_Type
10438         (Old_Type : Entity_Id) return Entity_Id
10439       is
10440          Desig_Type    : constant Entity_Id := Designated_Type (Old_Type);
10441          Itype         : Entity_Id;
10442          Desig_Subtype : Entity_Id;
10443          Scop          : Entity_Id;
10444
10445       begin
10446          --  if the original access type was not embedded in the enclosing
10447          --  type definition, there is no need to produce a new access
10448          --  subtype. In fact every access type with an explicit constraint
10449          --  generates an itype whose scope is the enclosing record.
10450
10451          if not Is_Type (Scope (Old_Type)) then
10452             return Old_Type;
10453
10454          elsif Is_Array_Type (Desig_Type) then
10455             Desig_Subtype := Build_Constrained_Array_Type (Desig_Type);
10456
10457          elsif Has_Discriminants (Desig_Type) then
10458
10459             --  This may be an access type to an enclosing record type for
10460             --  which we are constructing the constrained components. Return
10461             --  the enclosing record subtype. This is not always correct,
10462             --  but avoids infinite recursion. ???
10463
10464             Desig_Subtype := Any_Type;
10465
10466             for J in reverse 0 .. Scope_Stack.Last loop
10467                Scop := Scope_Stack.Table (J).Entity;
10468
10469                if Is_Type (Scop)
10470                  and then Base_Type (Scop) = Base_Type (Desig_Type)
10471                then
10472                   Desig_Subtype := Scop;
10473                end if;
10474
10475                exit when not Is_Type (Scop);
10476             end loop;
10477
10478             if Desig_Subtype = Any_Type then
10479                Desig_Subtype :=
10480                  Build_Constrained_Discriminated_Type (Desig_Type);
10481             end if;
10482
10483          else
10484             return Old_Type;
10485          end if;
10486
10487          if Desig_Subtype /= Desig_Type then
10488
10489             --  The Related_Node better be here or else we won't be able
10490             --  to attach new itypes to a node in the tree.
10491
10492             pragma Assert (Present (Related_Node));
10493
10494             Itype := Create_Itype (E_Access_Subtype, Related_Node);
10495
10496             Set_Etype                    (Itype, Base_Type      (Old_Type));
10497             Set_Size_Info                (Itype,                (Old_Type));
10498             Set_Directly_Designated_Type (Itype, Desig_Subtype);
10499             Set_Depends_On_Private       (Itype, Has_Private_Component
10500                                                                 (Old_Type));
10501             Set_Is_Access_Constant       (Itype, Is_Access_Constant
10502                                                                 (Old_Type));
10503
10504             --  The new itype needs freezing when it depends on a not frozen
10505             --  type and the enclosing subtype needs freezing.
10506
10507             if Has_Delayed_Freeze (Constrained_Typ)
10508               and then not Is_Frozen (Constrained_Typ)
10509             then
10510                Conditional_Delay (Itype, Base_Type (Old_Type));
10511             end if;
10512
10513             return Itype;
10514
10515          else
10516             return Old_Type;
10517          end if;
10518       end Build_Constrained_Access_Type;
10519
10520       ----------------------------------
10521       -- Build_Constrained_Array_Type --
10522       ----------------------------------
10523
10524       function Build_Constrained_Array_Type
10525         (Old_Type : Entity_Id) return Entity_Id
10526       is
10527          Lo_Expr     : Node_Id;
10528          Hi_Expr     : Node_Id;
10529          Old_Index   : Node_Id;
10530          Range_Node  : Node_Id;
10531          Constr_List : List_Id;
10532
10533          Need_To_Create_Itype : Boolean := False;
10534
10535       begin
10536          Old_Index := First_Index (Old_Type);
10537          while Present (Old_Index) loop
10538             Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10539
10540             if Is_Discriminant (Lo_Expr)
10541               or else Is_Discriminant (Hi_Expr)
10542             then
10543                Need_To_Create_Itype := True;
10544             end if;
10545
10546             Next_Index (Old_Index);
10547          end loop;
10548
10549          if Need_To_Create_Itype then
10550             Constr_List := New_List;
10551
10552             Old_Index := First_Index (Old_Type);
10553             while Present (Old_Index) loop
10554                Get_Index_Bounds (Old_Index, Lo_Expr, Hi_Expr);
10555
10556                if Is_Discriminant (Lo_Expr) then
10557                   Lo_Expr := Get_Discr_Value (Lo_Expr);
10558                end if;
10559
10560                if Is_Discriminant (Hi_Expr) then
10561                   Hi_Expr := Get_Discr_Value (Hi_Expr);
10562                end if;
10563
10564                Range_Node :=
10565                  Make_Range
10566                    (Loc, New_Copy_Tree (Lo_Expr), New_Copy_Tree (Hi_Expr));
10567
10568                Append (Range_Node, To => Constr_List);
10569
10570                Next_Index (Old_Index);
10571             end loop;
10572
10573             return Build_Subtype (Old_Type, Constr_List);
10574
10575          else
10576             return Old_Type;
10577          end if;
10578       end Build_Constrained_Array_Type;
10579
10580       ------------------------------------------
10581       -- Build_Constrained_Discriminated_Type --
10582       ------------------------------------------
10583
10584       function Build_Constrained_Discriminated_Type
10585         (Old_Type : Entity_Id) return Entity_Id
10586       is
10587          Expr           : Node_Id;
10588          Constr_List    : List_Id;
10589          Old_Constraint : Elmt_Id;
10590
10591          Need_To_Create_Itype : Boolean := False;
10592
10593       begin
10594          Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10595          while Present (Old_Constraint) loop
10596             Expr := Node (Old_Constraint);
10597
10598             if Is_Discriminant (Expr) then
10599                Need_To_Create_Itype := True;
10600             end if;
10601
10602             Next_Elmt (Old_Constraint);
10603          end loop;
10604
10605          if Need_To_Create_Itype then
10606             Constr_List := New_List;
10607
10608             Old_Constraint := First_Elmt (Discriminant_Constraint (Old_Type));
10609             while Present (Old_Constraint) loop
10610                Expr := Node (Old_Constraint);
10611
10612                if Is_Discriminant (Expr) then
10613                   Expr := Get_Discr_Value (Expr);
10614                end if;
10615
10616                Append (New_Copy_Tree (Expr), To => Constr_List);
10617
10618                Next_Elmt (Old_Constraint);
10619             end loop;
10620
10621             return Build_Subtype (Old_Type, Constr_List);
10622
10623          else
10624             return Old_Type;
10625          end if;
10626       end Build_Constrained_Discriminated_Type;
10627
10628       -------------------
10629       -- Build_Subtype --
10630       -------------------
10631
10632       function Build_Subtype (T : Entity_Id; C : List_Id) return Entity_Id is
10633          Indic       : Node_Id;
10634          Subtyp_Decl : Node_Id;
10635          Def_Id      : Entity_Id;
10636          Btyp        : Entity_Id := Base_Type (T);
10637
10638       begin
10639          --  The Related_Node better be here or else we won't be able to
10640          --  attach new itypes to a node in the tree.
10641
10642          pragma Assert (Present (Related_Node));
10643
10644          --  If the view of the component's type is incomplete or private
10645          --  with unknown discriminants, then the constraint must be applied
10646          --  to the full type.
10647
10648          if Has_Unknown_Discriminants (Btyp)
10649            and then Present (Underlying_Type (Btyp))
10650          then
10651             Btyp := Underlying_Type (Btyp);
10652          end if;
10653
10654          Indic :=
10655            Make_Subtype_Indication (Loc,
10656              Subtype_Mark => New_Occurrence_Of (Btyp, Loc),
10657              Constraint   => Make_Index_Or_Discriminant_Constraint (Loc, C));
10658
10659          Def_Id := Create_Itype (Ekind (T), Related_Node);
10660
10661          Subtyp_Decl :=
10662            Make_Subtype_Declaration (Loc,
10663              Defining_Identifier => Def_Id,
10664              Subtype_Indication  => Indic);
10665
10666          Set_Parent (Subtyp_Decl, Parent (Related_Node));
10667
10668          --  Itypes must be analyzed with checks off (see package Itypes)
10669
10670          Analyze (Subtyp_Decl, Suppress => All_Checks);
10671
10672          return Def_Id;
10673       end Build_Subtype;
10674
10675       ---------------------
10676       -- Get_Discr_Value --
10677       ---------------------
10678
10679       function Get_Discr_Value (Discrim : Entity_Id) return Node_Id is
10680          D : Entity_Id;
10681          E : Elmt_Id;
10682
10683       begin
10684          --  The discriminant may be declared for the type, in which case we
10685          --  find it by iterating over the list of discriminants. If the
10686          --  discriminant is inherited from a parent type, it appears as the
10687          --  corresponding discriminant of the current type. This will be the
10688          --  case when constraining an inherited component whose constraint is
10689          --  given by a discriminant of the parent.
10690
10691          D := First_Discriminant (Typ);
10692          E := First_Elmt (Constraints);
10693
10694          while Present (D) loop
10695             if D = Entity (Discrim)
10696               or else D = CR_Discriminant (Entity (Discrim))
10697               or else Corresponding_Discriminant (D) = Entity (Discrim)
10698             then
10699                return Node (E);
10700             end if;
10701
10702             Next_Discriminant (D);
10703             Next_Elmt (E);
10704          end loop;
10705
10706          --  The corresponding_Discriminant mechanism is incomplete, because
10707          --  the correspondence between new and old discriminants is not one
10708          --  to one: one new discriminant can constrain several old ones. In
10709          --  that case, scan sequentially the stored_constraint, the list of
10710          --  discriminants of the parents, and the constraints.
10711          --  Previous code checked for the present of the Stored_Constraint
10712          --  list for the derived type, but did not use it at all. Should it
10713          --  be present when the component is a discriminated task type?
10714
10715          if Is_Derived_Type (Typ)
10716            and then Scope (Entity (Discrim)) = Etype (Typ)
10717          then
10718             D := First_Discriminant (Etype (Typ));
10719             E := First_Elmt (Constraints);
10720             while Present (D) loop
10721                if D = Entity (Discrim) then
10722                   return Node (E);
10723                end if;
10724
10725                Next_Discriminant (D);
10726                Next_Elmt (E);
10727             end loop;
10728          end if;
10729
10730          --  Something is wrong if we did not find the value
10731
10732          raise Program_Error;
10733       end Get_Discr_Value;
10734
10735       ---------------------
10736       -- Is_Discriminant --
10737       ---------------------
10738
10739       function Is_Discriminant (Expr : Node_Id) return Boolean is
10740          Discrim_Scope : Entity_Id;
10741
10742       begin
10743          if Denotes_Discriminant (Expr) then
10744             Discrim_Scope := Scope (Entity (Expr));
10745
10746             --  Either we have a reference to one of Typ's discriminants,
10747
10748             pragma Assert (Discrim_Scope = Typ
10749
10750                --  or to the discriminants of the parent type, in the case
10751                --  of a derivation of a tagged type with variants.
10752
10753                or else Discrim_Scope = Etype (Typ)
10754                or else Full_View (Discrim_Scope) = Etype (Typ)
10755
10756                --  or same as above for the case where the discriminants
10757                --  were declared in Typ's private view.
10758
10759                or else (Is_Private_Type (Discrim_Scope)
10760                         and then Chars (Discrim_Scope) = Chars (Typ))
10761
10762                --  or else we are deriving from the full view and the
10763                --  discriminant is declared in the private entity.
10764
10765                or else (Is_Private_Type (Typ)
10766                          and then Chars (Discrim_Scope) = Chars (Typ))
10767
10768                --  Or we are constrained the corresponding record of a
10769                --  synchronized type that completes a private declaration.
10770
10771                or else (Is_Concurrent_Record_Type (Typ)
10772                          and then
10773                            Corresponding_Concurrent_Type (Typ) = Discrim_Scope)
10774
10775                --  or we have a class-wide type, in which case make sure the
10776                --  discriminant found belongs to the root type.
10777
10778                or else (Is_Class_Wide_Type (Typ)
10779                          and then Etype (Typ) = Discrim_Scope));
10780
10781             return True;
10782          end if;
10783
10784          --  In all other cases we have something wrong
10785
10786          return False;
10787       end Is_Discriminant;
10788
10789    --  Start of processing for Constrain_Component_Type
10790
10791    begin
10792       if Nkind (Parent (Comp)) = N_Component_Declaration
10793         and then Comes_From_Source (Parent (Comp))
10794         and then Comes_From_Source
10795           (Subtype_Indication (Component_Definition (Parent (Comp))))
10796         and then
10797           Is_Entity_Name
10798             (Subtype_Indication (Component_Definition (Parent (Comp))))
10799       then
10800          return Compon_Type;
10801
10802       elsif Is_Array_Type (Compon_Type) then
10803          return Build_Constrained_Array_Type (Compon_Type);
10804
10805       elsif Has_Discriminants (Compon_Type) then
10806          return Build_Constrained_Discriminated_Type (Compon_Type);
10807
10808       elsif Is_Access_Type (Compon_Type) then
10809          return Build_Constrained_Access_Type (Compon_Type);
10810
10811       else
10812          return Compon_Type;
10813       end if;
10814    end Constrain_Component_Type;
10815
10816    --------------------------
10817    -- Constrain_Concurrent --
10818    --------------------------
10819
10820    --  For concurrent types, the associated record value type carries the same
10821    --  discriminants, so when we constrain a concurrent type, we must constrain
10822    --  the corresponding record type as well.
10823
10824    procedure Constrain_Concurrent
10825      (Def_Id      : in out Entity_Id;
10826       SI          : Node_Id;
10827       Related_Nod : Node_Id;
10828       Related_Id  : Entity_Id;
10829       Suffix      : Character)
10830    is
10831       T_Ent : Entity_Id := Entity (Subtype_Mark (SI));
10832       T_Val : Entity_Id;
10833
10834    begin
10835       if Ekind (T_Ent) in Access_Kind then
10836          T_Ent := Designated_Type (T_Ent);
10837       end if;
10838
10839       T_Val := Corresponding_Record_Type (T_Ent);
10840
10841       if Present (T_Val) then
10842
10843          if No (Def_Id) then
10844             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
10845          end if;
10846
10847          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
10848
10849          Set_Depends_On_Private (Def_Id, Has_Private_Component (Def_Id));
10850          Set_Corresponding_Record_Type (Def_Id,
10851            Constrain_Corresponding_Record
10852              (Def_Id, T_Val, Related_Nod, Related_Id));
10853
10854       else
10855          --  If there is no associated record, expansion is disabled and this
10856          --  is a generic context. Create a subtype in any case, so that
10857          --  semantic analysis can proceed.
10858
10859          if No (Def_Id) then
10860             Def_Id := Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
10861          end if;
10862
10863          Constrain_Discriminated_Type (Def_Id, SI, Related_Nod);
10864       end if;
10865    end Constrain_Concurrent;
10866
10867    ------------------------------------
10868    -- Constrain_Corresponding_Record --
10869    ------------------------------------
10870
10871    function Constrain_Corresponding_Record
10872      (Prot_Subt   : Entity_Id;
10873       Corr_Rec    : Entity_Id;
10874       Related_Nod : Node_Id;
10875       Related_Id  : Entity_Id) return Entity_Id
10876    is
10877       T_Sub : constant Entity_Id :=
10878                 Create_Itype (E_Record_Subtype, Related_Nod, Related_Id, 'V');
10879
10880    begin
10881       Set_Etype             (T_Sub, Corr_Rec);
10882       Set_Has_Discriminants (T_Sub, Has_Discriminants (Prot_Subt));
10883       Set_Is_Constrained    (T_Sub, True);
10884       Set_First_Entity      (T_Sub, First_Entity (Corr_Rec));
10885       Set_Last_Entity       (T_Sub, Last_Entity  (Corr_Rec));
10886
10887       --  As elsewhere, we do not want to create a freeze node for this itype
10888       --  if it is created for a constrained component of an enclosing record
10889       --  because references to outer discriminants will appear out of scope.
10890
10891       if Ekind (Scope (Prot_Subt)) /= E_Record_Type then
10892          Conditional_Delay (T_Sub, Corr_Rec);
10893       else
10894          Set_Is_Frozen (T_Sub);
10895       end if;
10896
10897       if Has_Discriminants (Prot_Subt) then -- False only if errors.
10898          Set_Discriminant_Constraint
10899            (T_Sub, Discriminant_Constraint (Prot_Subt));
10900          Set_Stored_Constraint_From_Discriminant_Constraint (T_Sub);
10901          Create_Constrained_Components
10902            (T_Sub, Related_Nod, Corr_Rec, Discriminant_Constraint (T_Sub));
10903       end if;
10904
10905       Set_Depends_On_Private      (T_Sub, Has_Private_Component (T_Sub));
10906
10907       return T_Sub;
10908    end Constrain_Corresponding_Record;
10909
10910    -----------------------
10911    -- Constrain_Decimal --
10912    -----------------------
10913
10914    procedure Constrain_Decimal (Def_Id : Node_Id; S : Node_Id) is
10915       T           : constant Entity_Id  := Entity (Subtype_Mark (S));
10916       C           : constant Node_Id    := Constraint (S);
10917       Loc         : constant Source_Ptr := Sloc (C);
10918       Range_Expr  : Node_Id;
10919       Digits_Expr : Node_Id;
10920       Digits_Val  : Uint;
10921       Bound_Val   : Ureal;
10922
10923    begin
10924       Set_Ekind (Def_Id, E_Decimal_Fixed_Point_Subtype);
10925
10926       if Nkind (C) = N_Range_Constraint then
10927          Range_Expr := Range_Expression (C);
10928          Digits_Val := Digits_Value (T);
10929
10930       else
10931          pragma Assert (Nkind (C) = N_Digits_Constraint);
10932          Digits_Expr := Digits_Expression (C);
10933          Analyze_And_Resolve (Digits_Expr, Any_Integer);
10934
10935          Check_Digits_Expression (Digits_Expr);
10936          Digits_Val := Expr_Value (Digits_Expr);
10937
10938          if Digits_Val > Digits_Value (T) then
10939             Error_Msg_N
10940                ("digits expression is incompatible with subtype", C);
10941             Digits_Val := Digits_Value (T);
10942          end if;
10943
10944          if Present (Range_Constraint (C)) then
10945             Range_Expr := Range_Expression (Range_Constraint (C));
10946          else
10947             Range_Expr := Empty;
10948          end if;
10949       end if;
10950
10951       Set_Etype            (Def_Id, Base_Type        (T));
10952       Set_Size_Info        (Def_Id,                  (T));
10953       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
10954       Set_Delta_Value      (Def_Id, Delta_Value      (T));
10955       Set_Scale_Value      (Def_Id, Scale_Value      (T));
10956       Set_Small_Value      (Def_Id, Small_Value      (T));
10957       Set_Machine_Radix_10 (Def_Id, Machine_Radix_10 (T));
10958       Set_Digits_Value     (Def_Id, Digits_Val);
10959
10960       --  Manufacture range from given digits value if no range present
10961
10962       if No (Range_Expr) then
10963          Bound_Val := (Ureal_10 ** Digits_Val - Ureal_1) * Small_Value (T);
10964          Range_Expr :=
10965            Make_Range (Loc,
10966              Low_Bound =>
10967                Convert_To (T, Make_Real_Literal (Loc, (-Bound_Val))),
10968              High_Bound =>
10969                Convert_To (T, Make_Real_Literal (Loc, Bound_Val)));
10970       end if;
10971
10972       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expr, T);
10973       Set_Discrete_RM_Size (Def_Id);
10974
10975       --  Unconditionally delay the freeze, since we cannot set size
10976       --  information in all cases correctly until the freeze point.
10977
10978       Set_Has_Delayed_Freeze (Def_Id);
10979    end Constrain_Decimal;
10980
10981    ----------------------------------
10982    -- Constrain_Discriminated_Type --
10983    ----------------------------------
10984
10985    procedure Constrain_Discriminated_Type
10986      (Def_Id      : Entity_Id;
10987       S           : Node_Id;
10988       Related_Nod : Node_Id;
10989       For_Access  : Boolean := False)
10990    is
10991       E     : constant Entity_Id := Entity (Subtype_Mark (S));
10992       T     : Entity_Id;
10993       C     : Node_Id;
10994       Elist : Elist_Id := New_Elmt_List;
10995
10996       procedure Fixup_Bad_Constraint;
10997       --  This is called after finding a bad constraint, and after having
10998       --  posted an appropriate error message. The mission is to leave the
10999       --  entity T in as reasonable state as possible!
11000
11001       --------------------------
11002       -- Fixup_Bad_Constraint --
11003       --------------------------
11004
11005       procedure Fixup_Bad_Constraint is
11006       begin
11007          --  Set a reasonable Ekind for the entity. For an incomplete type,
11008          --  we can't do much, but for other types, we can set the proper
11009          --  corresponding subtype kind.
11010
11011          if Ekind (T) = E_Incomplete_Type then
11012             Set_Ekind (Def_Id, Ekind (T));
11013          else
11014             Set_Ekind (Def_Id, Subtype_Kind (Ekind (T)));
11015          end if;
11016
11017          --  Set Etype to the known type, to reduce chances of cascaded errors
11018
11019          Set_Etype (Def_Id, E);
11020          Set_Error_Posted (Def_Id);
11021       end Fixup_Bad_Constraint;
11022
11023    --  Start of processing for Constrain_Discriminated_Type
11024
11025    begin
11026       C := Constraint (S);
11027
11028       --  A discriminant constraint is only allowed in a subtype indication,
11029       --  after a subtype mark. This subtype mark must denote either a type
11030       --  with discriminants, or an access type whose designated type is a
11031       --  type with discriminants. A discriminant constraint specifies the
11032       --  values of these discriminants (RM 3.7.2(5)).
11033
11034       T := Base_Type (Entity (Subtype_Mark (S)));
11035
11036       if Ekind (T) in Access_Kind then
11037          T := Designated_Type (T);
11038       end if;
11039
11040       --  Ada 2005 (AI-412): Constrained incomplete subtypes are illegal.
11041       --  Avoid generating an error for access-to-incomplete subtypes.
11042
11043       if Ada_Version >= Ada_2005
11044         and then Ekind (T) = E_Incomplete_Type
11045         and then Nkind (Parent (S)) = N_Subtype_Declaration
11046         and then not Is_Itype (Def_Id)
11047       then
11048          --  A little sanity check, emit an error message if the type
11049          --  has discriminants to begin with. Type T may be a regular
11050          --  incomplete type or imported via a limited with clause.
11051
11052          if Has_Discriminants (T)
11053            or else
11054              (From_With_Type (T)
11055                 and then Present (Non_Limited_View (T))
11056                 and then Nkind (Parent (Non_Limited_View (T))) =
11057                            N_Full_Type_Declaration
11058                 and then Present (Discriminant_Specifications
11059                           (Parent (Non_Limited_View (T)))))
11060          then
11061             Error_Msg_N
11062               ("(Ada 2005) incomplete subtype may not be constrained", C);
11063          else
11064             Error_Msg_N ("invalid constraint: type has no discriminant", C);
11065          end if;
11066
11067          Fixup_Bad_Constraint;
11068          return;
11069
11070       --  Check that the type has visible discriminants. The type may be
11071       --  a private type with unknown discriminants whose full view has
11072       --  discriminants which are invisible.
11073
11074       elsif not Has_Discriminants (T)
11075         or else
11076           (Has_Unknown_Discriminants (T)
11077              and then Is_Private_Type (T))
11078       then
11079          Error_Msg_N ("invalid constraint: type has no discriminant", C);
11080          Fixup_Bad_Constraint;
11081          return;
11082
11083       elsif Is_Constrained (E)
11084         or else (Ekind (E) = E_Class_Wide_Subtype
11085                   and then Present (Discriminant_Constraint (E)))
11086       then
11087          Error_Msg_N ("type is already constrained", Subtype_Mark (S));
11088          Fixup_Bad_Constraint;
11089          return;
11090       end if;
11091
11092       --  T may be an unconstrained subtype (e.g. a generic actual).
11093       --  Constraint applies to the base type.
11094
11095       T := Base_Type (T);
11096
11097       Elist := Build_Discriminant_Constraints (T, S);
11098
11099       --  If the list returned was empty we had an error in building the
11100       --  discriminant constraint. We have also already signalled an error
11101       --  in the incomplete type case
11102
11103       if Is_Empty_Elmt_List (Elist) then
11104          Fixup_Bad_Constraint;
11105          return;
11106       end if;
11107
11108       Build_Discriminated_Subtype (T, Def_Id, Elist, Related_Nod, For_Access);
11109    end Constrain_Discriminated_Type;
11110
11111    ---------------------------
11112    -- Constrain_Enumeration --
11113    ---------------------------
11114
11115    procedure Constrain_Enumeration (Def_Id : Node_Id; S : Node_Id) is
11116       T : constant Entity_Id := Entity (Subtype_Mark (S));
11117       C : constant Node_Id   := Constraint (S);
11118
11119    begin
11120       Set_Ekind (Def_Id, E_Enumeration_Subtype);
11121
11122       Set_First_Literal     (Def_Id, First_Literal (Base_Type (T)));
11123
11124       Set_Etype             (Def_Id, Base_Type         (T));
11125       Set_Size_Info         (Def_Id,                   (T));
11126       Set_First_Rep_Item    (Def_Id, First_Rep_Item    (T));
11127       Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11128
11129       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11130
11131       Set_Discrete_RM_Size (Def_Id);
11132    end Constrain_Enumeration;
11133
11134    ----------------------
11135    -- Constrain_Float --
11136    ----------------------
11137
11138    procedure Constrain_Float (Def_Id : Node_Id; S : Node_Id) is
11139       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11140       C    : Node_Id;
11141       D    : Node_Id;
11142       Rais : Node_Id;
11143
11144    begin
11145       Set_Ekind (Def_Id, E_Floating_Point_Subtype);
11146
11147       Set_Etype          (Def_Id, Base_Type      (T));
11148       Set_Size_Info      (Def_Id,                (T));
11149       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11150
11151       --  Process the constraint
11152
11153       C := Constraint (S);
11154
11155       --  Digits constraint present
11156
11157       if Nkind (C) = N_Digits_Constraint then
11158          Check_Restriction (No_Obsolescent_Features, C);
11159
11160          if Warn_On_Obsolescent_Feature then
11161             Error_Msg_N
11162               ("subtype digits constraint is an " &
11163                "obsolescent feature (RM J.3(8))?", C);
11164          end if;
11165
11166          D := Digits_Expression (C);
11167          Analyze_And_Resolve (D, Any_Integer);
11168          Check_Digits_Expression (D);
11169          Set_Digits_Value (Def_Id, Expr_Value (D));
11170
11171          --  Check that digits value is in range. Obviously we can do this
11172          --  at compile time, but it is strictly a runtime check, and of
11173          --  course there is an ACVC test that checks this!
11174
11175          if Digits_Value (Def_Id) > Digits_Value (T) then
11176             Error_Msg_Uint_1 := Digits_Value (T);
11177             Error_Msg_N ("?digits value is too large, maximum is ^", D);
11178             Rais :=
11179               Make_Raise_Constraint_Error (Sloc (D),
11180                 Reason => CE_Range_Check_Failed);
11181             Insert_Action (Declaration_Node (Def_Id), Rais);
11182          end if;
11183
11184          C := Range_Constraint (C);
11185
11186       --  No digits constraint present
11187
11188       else
11189          Set_Digits_Value (Def_Id, Digits_Value (T));
11190       end if;
11191
11192       --  Range constraint present
11193
11194       if Nkind (C) = N_Range_Constraint then
11195          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11196
11197       --  No range constraint present
11198
11199       else
11200          pragma Assert (No (C));
11201          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11202       end if;
11203
11204       Set_Is_Constrained (Def_Id);
11205    end Constrain_Float;
11206
11207    ---------------------
11208    -- Constrain_Index --
11209    ---------------------
11210
11211    procedure Constrain_Index
11212      (Index        : Node_Id;
11213       S            : Node_Id;
11214       Related_Nod  : Node_Id;
11215       Related_Id   : Entity_Id;
11216       Suffix       : Character;
11217       Suffix_Index : Nat)
11218    is
11219       Def_Id : Entity_Id;
11220       R      : Node_Id := Empty;
11221       T      : constant Entity_Id := Etype (Index);
11222
11223    begin
11224       if Nkind (S) = N_Range
11225         or else
11226           (Nkind (S) = N_Attribute_Reference
11227             and then Attribute_Name (S) = Name_Range)
11228       then
11229          --  A Range attribute will transformed into N_Range by Resolve
11230
11231          Analyze (S);
11232          Set_Etype (S, T);
11233          R := S;
11234
11235          Process_Range_Expr_In_Decl (R, T, Empty_List);
11236
11237          if not Error_Posted (S)
11238            and then
11239              (Nkind (S) /= N_Range
11240                or else not Covers (T, (Etype (Low_Bound (S))))
11241                or else not Covers (T, (Etype (High_Bound (S)))))
11242          then
11243             if Base_Type (T) /= Any_Type
11244               and then Etype (Low_Bound (S)) /= Any_Type
11245               and then Etype (High_Bound (S)) /= Any_Type
11246             then
11247                Error_Msg_N ("range expected", S);
11248             end if;
11249          end if;
11250
11251       elsif Nkind (S) = N_Subtype_Indication then
11252
11253          --  The parser has verified that this is a discrete indication
11254
11255          Resolve_Discrete_Subtype_Indication (S, T);
11256          R := Range_Expression (Constraint (S));
11257
11258       elsif Nkind (S) = N_Discriminant_Association then
11259
11260          --  Syntactically valid in subtype indication
11261
11262          Error_Msg_N ("invalid index constraint", S);
11263          Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11264          return;
11265
11266       --  Subtype_Mark case, no anonymous subtypes to construct
11267
11268       else
11269          Analyze (S);
11270
11271          if Is_Entity_Name (S) then
11272             if not Is_Type (Entity (S)) then
11273                Error_Msg_N ("expect subtype mark for index constraint", S);
11274
11275             elsif Base_Type (Entity (S)) /= Base_Type (T) then
11276                Wrong_Type (S, Base_Type (T));
11277             end if;
11278
11279             return;
11280
11281          else
11282             Error_Msg_N ("invalid index constraint", S);
11283             Rewrite (S, New_Occurrence_Of (T, Sloc (S)));
11284             return;
11285          end if;
11286       end if;
11287
11288       Def_Id :=
11289         Create_Itype (E_Void, Related_Nod, Related_Id, Suffix, Suffix_Index);
11290
11291       Set_Etype (Def_Id, Base_Type (T));
11292
11293       if Is_Modular_Integer_Type (T) then
11294          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11295
11296       elsif Is_Integer_Type (T) then
11297          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11298
11299       else
11300          Set_Ekind (Def_Id, E_Enumeration_Subtype);
11301          Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
11302          Set_First_Literal     (Def_Id, First_Literal (T));
11303       end if;
11304
11305       Set_Size_Info      (Def_Id,                (T));
11306       Set_RM_Size        (Def_Id, RM_Size        (T));
11307       Set_First_Rep_Item (Def_Id, First_Rep_Item (T));
11308
11309       Set_Scalar_Range   (Def_Id, R);
11310
11311       Set_Etype (S, Def_Id);
11312       Set_Discrete_RM_Size (Def_Id);
11313    end Constrain_Index;
11314
11315    -----------------------
11316    -- Constrain_Integer --
11317    -----------------------
11318
11319    procedure Constrain_Integer (Def_Id : Node_Id; S : Node_Id) is
11320       T : constant Entity_Id := Entity (Subtype_Mark (S));
11321       C : constant Node_Id   := Constraint (S);
11322
11323    begin
11324       Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11325
11326       if Is_Modular_Integer_Type (T) then
11327          Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
11328       else
11329          Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
11330       end if;
11331
11332       Set_Etype            (Def_Id, Base_Type        (T));
11333       Set_Size_Info        (Def_Id,                  (T));
11334       Set_First_Rep_Item   (Def_Id, First_Rep_Item   (T));
11335       Set_Discrete_RM_Size (Def_Id);
11336    end Constrain_Integer;
11337
11338    ------------------------------
11339    -- Constrain_Ordinary_Fixed --
11340    ------------------------------
11341
11342    procedure Constrain_Ordinary_Fixed (Def_Id : Node_Id; S : Node_Id) is
11343       T    : constant Entity_Id := Entity (Subtype_Mark (S));
11344       C    : Node_Id;
11345       D    : Node_Id;
11346       Rais : Node_Id;
11347
11348    begin
11349       Set_Ekind          (Def_Id, E_Ordinary_Fixed_Point_Subtype);
11350       Set_Etype          (Def_Id, Base_Type        (T));
11351       Set_Size_Info      (Def_Id,                  (T));
11352       Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
11353       Set_Small_Value    (Def_Id, Small_Value      (T));
11354
11355       --  Process the constraint
11356
11357       C := Constraint (S);
11358
11359       --  Delta constraint present
11360
11361       if Nkind (C) = N_Delta_Constraint then
11362          Check_Restriction (No_Obsolescent_Features, C);
11363
11364          if Warn_On_Obsolescent_Feature then
11365             Error_Msg_S
11366               ("subtype delta constraint is an " &
11367                "obsolescent feature (RM J.3(7))?");
11368          end if;
11369
11370          D := Delta_Expression (C);
11371          Analyze_And_Resolve (D, Any_Real);
11372          Check_Delta_Expression (D);
11373          Set_Delta_Value (Def_Id, Expr_Value_R (D));
11374
11375          --  Check that delta value is in range. Obviously we can do this
11376          --  at compile time, but it is strictly a runtime check, and of
11377          --  course there is an ACVC test that checks this!
11378
11379          if Delta_Value (Def_Id) < Delta_Value (T) then
11380             Error_Msg_N ("?delta value is too small", D);
11381             Rais :=
11382               Make_Raise_Constraint_Error (Sloc (D),
11383                 Reason => CE_Range_Check_Failed);
11384             Insert_Action (Declaration_Node (Def_Id), Rais);
11385          end if;
11386
11387          C := Range_Constraint (C);
11388
11389       --  No delta constraint present
11390
11391       else
11392          Set_Delta_Value (Def_Id, Delta_Value (T));
11393       end if;
11394
11395       --  Range constraint present
11396
11397       if Nkind (C) = N_Range_Constraint then
11398          Set_Scalar_Range_For_Subtype (Def_Id, Range_Expression (C), T);
11399
11400       --  No range constraint present
11401
11402       else
11403          pragma Assert (No (C));
11404          Set_Scalar_Range (Def_Id, Scalar_Range (T));
11405
11406       end if;
11407
11408       Set_Discrete_RM_Size (Def_Id);
11409
11410       --  Unconditionally delay the freeze, since we cannot set size
11411       --  information in all cases correctly until the freeze point.
11412
11413       Set_Has_Delayed_Freeze (Def_Id);
11414    end Constrain_Ordinary_Fixed;
11415
11416    -----------------------
11417    -- Contain_Interface --
11418    -----------------------
11419
11420    function Contain_Interface
11421      (Iface  : Entity_Id;
11422       Ifaces : Elist_Id) return Boolean
11423    is
11424       Iface_Elmt : Elmt_Id;
11425
11426    begin
11427       if Present (Ifaces) then
11428          Iface_Elmt := First_Elmt (Ifaces);
11429          while Present (Iface_Elmt) loop
11430             if Node (Iface_Elmt) = Iface then
11431                return True;
11432             end if;
11433
11434             Next_Elmt (Iface_Elmt);
11435          end loop;
11436       end if;
11437
11438       return False;
11439    end Contain_Interface;
11440
11441    ---------------------------
11442    -- Convert_Scalar_Bounds --
11443    ---------------------------
11444
11445    procedure Convert_Scalar_Bounds
11446      (N            : Node_Id;
11447       Parent_Type  : Entity_Id;
11448       Derived_Type : Entity_Id;
11449       Loc          : Source_Ptr)
11450    is
11451       Implicit_Base : constant Entity_Id := Base_Type (Derived_Type);
11452
11453       Lo  : Node_Id;
11454       Hi  : Node_Id;
11455       Rng : Node_Id;
11456
11457    begin
11458       --  Defend against previous errors
11459
11460       if No (Scalar_Range (Derived_Type)) then
11461          return;
11462       end if;
11463
11464       Lo := Build_Scalar_Bound
11465               (Type_Low_Bound (Derived_Type),
11466                Parent_Type, Implicit_Base);
11467
11468       Hi := Build_Scalar_Bound
11469               (Type_High_Bound (Derived_Type),
11470                Parent_Type, Implicit_Base);
11471
11472       Rng :=
11473         Make_Range (Loc,
11474           Low_Bound  => Lo,
11475           High_Bound => Hi);
11476
11477       Set_Includes_Infinities (Rng, Has_Infinities (Derived_Type));
11478
11479       Set_Parent (Rng, N);
11480       Set_Scalar_Range (Derived_Type, Rng);
11481
11482       --  Analyze the bounds
11483
11484       Analyze_And_Resolve (Lo, Implicit_Base);
11485       Analyze_And_Resolve (Hi, Implicit_Base);
11486
11487       --  Analyze the range itself, except that we do not analyze it if
11488       --  the bounds are real literals, and we have a fixed-point type.
11489       --  The reason for this is that we delay setting the bounds in this
11490       --  case till we know the final Small and Size values (see circuit
11491       --  in Freeze.Freeze_Fixed_Point_Type for further details).
11492
11493       if Is_Fixed_Point_Type (Parent_Type)
11494         and then Nkind (Lo) = N_Real_Literal
11495         and then Nkind (Hi) = N_Real_Literal
11496       then
11497          return;
11498
11499       --  Here we do the analysis of the range
11500
11501       --  Note: we do this manually, since if we do a normal Analyze and
11502       --  Resolve call, there are problems with the conversions used for
11503       --  the derived type range.
11504
11505       else
11506          Set_Etype    (Rng, Implicit_Base);
11507          Set_Analyzed (Rng, True);
11508       end if;
11509    end Convert_Scalar_Bounds;
11510
11511    -------------------
11512    -- Copy_And_Swap --
11513    -------------------
11514
11515    procedure Copy_And_Swap (Priv, Full : Entity_Id) is
11516    begin
11517       --  Initialize new full declaration entity by copying the pertinent
11518       --  fields of the corresponding private declaration entity.
11519
11520       --  We temporarily set Ekind to a value appropriate for a type to
11521       --  avoid assert failures in Einfo from checking for setting type
11522       --  attributes on something that is not a type. Ekind (Priv) is an
11523       --  appropriate choice, since it allowed the attributes to be set
11524       --  in the first place. This Ekind value will be modified later.
11525
11526       Set_Ekind (Full, Ekind (Priv));
11527
11528       --  Also set Etype temporarily to Any_Type, again, in the absence
11529       --  of errors, it will be properly reset, and if there are errors,
11530       --  then we want a value of Any_Type to remain.
11531
11532       Set_Etype (Full, Any_Type);
11533
11534       --  Now start copying attributes
11535
11536       Set_Has_Discriminants          (Full, Has_Discriminants       (Priv));
11537
11538       if Has_Discriminants (Full) then
11539          Set_Discriminant_Constraint (Full, Discriminant_Constraint (Priv));
11540          Set_Stored_Constraint       (Full, Stored_Constraint       (Priv));
11541       end if;
11542
11543       Set_First_Rep_Item             (Full, First_Rep_Item          (Priv));
11544       Set_Homonym                    (Full, Homonym                 (Priv));
11545       Set_Is_Immediately_Visible     (Full, Is_Immediately_Visible  (Priv));
11546       Set_Is_Public                  (Full, Is_Public               (Priv));
11547       Set_Is_Pure                    (Full, Is_Pure                 (Priv));
11548       Set_Is_Tagged_Type             (Full, Is_Tagged_Type          (Priv));
11549       Set_Has_Pragma_Unmodified      (Full, Has_Pragma_Unmodified   (Priv));
11550       Set_Has_Pragma_Unreferenced    (Full, Has_Pragma_Unreferenced (Priv));
11551       Set_Has_Pragma_Unreferenced_Objects
11552                                      (Full, Has_Pragma_Unreferenced_Objects
11553                                                                     (Priv));
11554
11555       Conditional_Delay              (Full,                          Priv);
11556
11557       if Is_Tagged_Type (Full) then
11558          Set_Direct_Primitive_Operations (Full,
11559            Direct_Primitive_Operations (Priv));
11560
11561          if Priv = Base_Type (Priv) then
11562             Set_Class_Wide_Type      (Full, Class_Wide_Type         (Priv));
11563          end if;
11564       end if;
11565
11566       Set_Is_Volatile                (Full, Is_Volatile             (Priv));
11567       Set_Treat_As_Volatile          (Full, Treat_As_Volatile       (Priv));
11568       Set_Scope                      (Full, Scope                   (Priv));
11569       Set_Next_Entity                (Full, Next_Entity             (Priv));
11570       Set_First_Entity               (Full, First_Entity            (Priv));
11571       Set_Last_Entity                (Full, Last_Entity             (Priv));
11572
11573       --  If access types have been recorded for later handling, keep them in
11574       --  the full view so that they get handled when the full view freeze
11575       --  node is expanded.
11576
11577       if Present (Freeze_Node (Priv))
11578         and then Present (Access_Types_To_Process (Freeze_Node (Priv)))
11579       then
11580          Ensure_Freeze_Node (Full);
11581          Set_Access_Types_To_Process
11582            (Freeze_Node (Full),
11583             Access_Types_To_Process (Freeze_Node (Priv)));
11584       end if;
11585
11586       --  Swap the two entities. Now Privat is the full type entity and Full is
11587       --  the private one. They will be swapped back at the end of the private
11588       --  part. This swapping ensures that the entity that is visible in the
11589       --  private part is the full declaration.
11590
11591       Exchange_Entities (Priv, Full);
11592       Append_Entity (Full, Scope (Full));
11593    end Copy_And_Swap;
11594
11595    -------------------------------------
11596    -- Copy_Array_Base_Type_Attributes --
11597    -------------------------------------
11598
11599    procedure Copy_Array_Base_Type_Attributes (T1, T2 : Entity_Id) is
11600    begin
11601       Set_Component_Alignment      (T1, Component_Alignment      (T2));
11602       Set_Component_Type           (T1, Component_Type           (T2));
11603       Set_Component_Size           (T1, Component_Size           (T2));
11604       Set_Has_Controlled_Component (T1, Has_Controlled_Component (T2));
11605       Set_Finalize_Storage_Only    (T1, Finalize_Storage_Only    (T2));
11606       Set_Has_Non_Standard_Rep     (T1, Has_Non_Standard_Rep     (T2));
11607       Set_Has_Task                 (T1, Has_Task                 (T2));
11608       Set_Is_Packed                (T1, Is_Packed                (T2));
11609       Set_Has_Aliased_Components   (T1, Has_Aliased_Components   (T2));
11610       Set_Has_Atomic_Components    (T1, Has_Atomic_Components    (T2));
11611       Set_Has_Volatile_Components  (T1, Has_Volatile_Components  (T2));
11612    end Copy_Array_Base_Type_Attributes;
11613
11614    -----------------------------------
11615    -- Copy_Array_Subtype_Attributes --
11616    -----------------------------------
11617
11618    procedure Copy_Array_Subtype_Attributes (T1, T2 : Entity_Id) is
11619    begin
11620       Set_Size_Info (T1, T2);
11621
11622       Set_First_Index          (T1, First_Index           (T2));
11623       Set_Is_Aliased           (T1, Is_Aliased            (T2));
11624       Set_Is_Atomic            (T1, Is_Atomic             (T2));
11625       Set_Is_Volatile          (T1, Is_Volatile           (T2));
11626       Set_Treat_As_Volatile    (T1, Treat_As_Volatile     (T2));
11627       Set_Is_Constrained       (T1, Is_Constrained        (T2));
11628       Set_Depends_On_Private   (T1, Has_Private_Component (T2));
11629       Set_First_Rep_Item       (T1, First_Rep_Item        (T2));
11630       Set_Convention           (T1, Convention            (T2));
11631       Set_Is_Limited_Composite (T1, Is_Limited_Composite  (T2));
11632       Set_Is_Private_Composite (T1, Is_Private_Composite  (T2));
11633       Set_Packed_Array_Type    (T1, Packed_Array_Type     (T2));
11634    end Copy_Array_Subtype_Attributes;
11635
11636    -----------------------------------
11637    -- Create_Constrained_Components --
11638    -----------------------------------
11639
11640    procedure Create_Constrained_Components
11641      (Subt        : Entity_Id;
11642       Decl_Node   : Node_Id;
11643       Typ         : Entity_Id;
11644       Constraints : Elist_Id)
11645    is
11646       Loc         : constant Source_Ptr := Sloc (Subt);
11647       Comp_List   : constant Elist_Id   := New_Elmt_List;
11648       Parent_Type : constant Entity_Id  := Etype (Typ);
11649       Assoc_List  : constant List_Id    := New_List;
11650       Discr_Val   : Elmt_Id;
11651       Errors      : Boolean;
11652       New_C       : Entity_Id;
11653       Old_C       : Entity_Id;
11654       Is_Static   : Boolean := True;
11655
11656       procedure Collect_Fixed_Components (Typ : Entity_Id);
11657       --  Collect parent type components that do not appear in a variant part
11658
11659       procedure Create_All_Components;
11660       --  Iterate over Comp_List to create the components of the subtype
11661
11662       function Create_Component (Old_Compon : Entity_Id) return Entity_Id;
11663       --  Creates a new component from Old_Compon, copying all the fields from
11664       --  it, including its Etype, inserts the new component in the Subt entity
11665       --  chain and returns the new component.
11666
11667       function Is_Variant_Record (T : Entity_Id) return Boolean;
11668       --  If true, and discriminants are static, collect only components from
11669       --  variants selected by discriminant values.
11670
11671       ------------------------------
11672       -- Collect_Fixed_Components --
11673       ------------------------------
11674
11675       procedure Collect_Fixed_Components (Typ : Entity_Id) is
11676       begin
11677       --  Build association list for discriminants, and find components of the
11678       --  variant part selected by the values of the discriminants.
11679
11680          Old_C := First_Discriminant (Typ);
11681          Discr_Val := First_Elmt (Constraints);
11682          while Present (Old_C) loop
11683             Append_To (Assoc_List,
11684               Make_Component_Association (Loc,
11685                  Choices    => New_List (New_Occurrence_Of (Old_C, Loc)),
11686                  Expression => New_Copy (Node (Discr_Val))));
11687
11688             Next_Elmt (Discr_Val);
11689             Next_Discriminant (Old_C);
11690          end loop;
11691
11692          --  The tag, and the possible parent and controller components
11693          --  are unconditionally in the subtype.
11694
11695          if Is_Tagged_Type (Typ)
11696            or else Has_Controlled_Component (Typ)
11697          then
11698             Old_C := First_Component (Typ);
11699             while Present (Old_C) loop
11700                if Chars ((Old_C)) = Name_uTag
11701                  or else Chars ((Old_C)) = Name_uParent
11702                  or else Chars ((Old_C)) = Name_uController
11703                then
11704                   Append_Elmt (Old_C, Comp_List);
11705                end if;
11706
11707                Next_Component (Old_C);
11708             end loop;
11709          end if;
11710       end Collect_Fixed_Components;
11711
11712       ---------------------------
11713       -- Create_All_Components --
11714       ---------------------------
11715
11716       procedure Create_All_Components is
11717          Comp : Elmt_Id;
11718
11719       begin
11720          Comp := First_Elmt (Comp_List);
11721          while Present (Comp) loop
11722             Old_C := Node (Comp);
11723             New_C := Create_Component (Old_C);
11724
11725             Set_Etype
11726               (New_C,
11727                Constrain_Component_Type
11728                  (Old_C, Subt, Decl_Node, Typ, Constraints));
11729             Set_Is_Public (New_C, Is_Public (Subt));
11730
11731             Next_Elmt (Comp);
11732          end loop;
11733       end Create_All_Components;
11734
11735       ----------------------
11736       -- Create_Component --
11737       ----------------------
11738
11739       function Create_Component (Old_Compon : Entity_Id) return Entity_Id is
11740          New_Compon : constant Entity_Id := New_Copy (Old_Compon);
11741
11742       begin
11743          if Ekind (Old_Compon) = E_Discriminant
11744            and then Is_Completely_Hidden (Old_Compon)
11745          then
11746             --  This is a shadow discriminant created for a discriminant of
11747             --  the parent type, which needs to be present in the subtype.
11748             --  Give the shadow discriminant an internal name that cannot
11749             --  conflict with that of visible components.
11750
11751             Set_Chars (New_Compon, New_Internal_Name ('C'));
11752          end if;
11753
11754          --  Set the parent so we have a proper link for freezing etc. This is
11755          --  not a real parent pointer, since of course our parent does not own
11756          --  up to us and reference us, we are an illegitimate child of the
11757          --  original parent!
11758
11759          Set_Parent (New_Compon, Parent (Old_Compon));
11760
11761          --  If the old component's Esize was already determined and is a
11762          --  static value, then the new component simply inherits it. Otherwise
11763          --  the old component's size may require run-time determination, but
11764          --  the new component's size still might be statically determinable
11765          --  (if, for example it has a static constraint). In that case we want
11766          --  Layout_Type to recompute the component's size, so we reset its
11767          --  size and positional fields.
11768
11769          if Frontend_Layout_On_Target
11770            and then not Known_Static_Esize (Old_Compon)
11771          then
11772             Set_Esize (New_Compon, Uint_0);
11773             Init_Normalized_First_Bit    (New_Compon);
11774             Init_Normalized_Position     (New_Compon);
11775             Init_Normalized_Position_Max (New_Compon);
11776          end if;
11777
11778          --  We do not want this node marked as Comes_From_Source, since
11779          --  otherwise it would get first class status and a separate cross-
11780          --  reference line would be generated. Illegitimate children do not
11781          --  rate such recognition.
11782
11783          Set_Comes_From_Source (New_Compon, False);
11784
11785          --  But it is a real entity, and a birth certificate must be properly
11786          --  registered by entering it into the entity list.
11787
11788          Enter_Name (New_Compon);
11789
11790          return New_Compon;
11791       end Create_Component;
11792
11793       -----------------------
11794       -- Is_Variant_Record --
11795       -----------------------
11796
11797       function Is_Variant_Record (T : Entity_Id) return Boolean is
11798       begin
11799          return Nkind (Parent (T)) = N_Full_Type_Declaration
11800            and then Nkind (Type_Definition (Parent (T))) = N_Record_Definition
11801            and then Present (Component_List (Type_Definition (Parent (T))))
11802            and then
11803              Present
11804                (Variant_Part (Component_List (Type_Definition (Parent (T)))));
11805       end Is_Variant_Record;
11806
11807    --  Start of processing for Create_Constrained_Components
11808
11809    begin
11810       pragma Assert (Subt /= Base_Type (Subt));
11811       pragma Assert (Typ = Base_Type (Typ));
11812
11813       Set_First_Entity (Subt, Empty);
11814       Set_Last_Entity  (Subt, Empty);
11815
11816       --  Check whether constraint is fully static, in which case we can
11817       --  optimize the list of components.
11818
11819       Discr_Val := First_Elmt (Constraints);
11820       while Present (Discr_Val) loop
11821          if not Is_OK_Static_Expression (Node (Discr_Val)) then
11822             Is_Static := False;
11823             exit;
11824          end if;
11825
11826          Next_Elmt (Discr_Val);
11827       end loop;
11828
11829       Set_Has_Static_Discriminants (Subt, Is_Static);
11830
11831       Push_Scope (Subt);
11832
11833       --  Inherit the discriminants of the parent type
11834
11835       Add_Discriminants : declare
11836          Num_Disc : Int;
11837          Num_Gird : Int;
11838
11839       begin
11840          Num_Disc := 0;
11841          Old_C := First_Discriminant (Typ);
11842
11843          while Present (Old_C) loop
11844             Num_Disc := Num_Disc + 1;
11845             New_C := Create_Component (Old_C);
11846             Set_Is_Public (New_C, Is_Public (Subt));
11847             Next_Discriminant (Old_C);
11848          end loop;
11849
11850          --  For an untagged derived subtype, the number of discriminants may
11851          --  be smaller than the number of inherited discriminants, because
11852          --  several of them may be renamed by a single new discriminant or
11853          --  constrained. In this case, add the hidden discriminants back into
11854          --  the subtype, because they need to be present if the optimizer of
11855          --  the GCC 4.x back-end decides to break apart assignments between
11856          --  objects using the parent view into member-wise assignments.
11857
11858          Num_Gird := 0;
11859
11860          if Is_Derived_Type (Typ)
11861            and then not Is_Tagged_Type (Typ)
11862          then
11863             Old_C := First_Stored_Discriminant (Typ);
11864
11865             while Present (Old_C) loop
11866                Num_Gird := Num_Gird + 1;
11867                Next_Stored_Discriminant (Old_C);
11868             end loop;
11869          end if;
11870
11871          if Num_Gird > Num_Disc then
11872
11873             --  Find out multiple uses of new discriminants, and add hidden
11874             --  components for the extra renamed discriminants. We recognize
11875             --  multiple uses through the Corresponding_Discriminant of a
11876             --  new discriminant: if it constrains several old discriminants,
11877             --  this field points to the last one in the parent type. The
11878             --  stored discriminants of the derived type have the same name
11879             --  as those of the parent.
11880
11881             declare
11882                Constr    : Elmt_Id;
11883                New_Discr : Entity_Id;
11884                Old_Discr : Entity_Id;
11885
11886             begin
11887                Constr    := First_Elmt (Stored_Constraint (Typ));
11888                Old_Discr := First_Stored_Discriminant (Typ);
11889                while Present (Constr) loop
11890                   if Is_Entity_Name (Node (Constr))
11891                     and then Ekind (Entity (Node (Constr))) = E_Discriminant
11892                   then
11893                      New_Discr := Entity (Node (Constr));
11894
11895                      if Chars (Corresponding_Discriminant (New_Discr)) /=
11896                         Chars (Old_Discr)
11897                      then
11898                         --  The new discriminant has been used to rename a
11899                         --  subsequent old discriminant. Introduce a shadow
11900                         --  component for the current old discriminant.
11901
11902                         New_C := Create_Component (Old_Discr);
11903                         Set_Original_Record_Component (New_C, Old_Discr);
11904                      end if;
11905
11906                   else
11907                      --  The constraint has eliminated the old discriminant.
11908                      --  Introduce a shadow component.
11909
11910                      New_C := Create_Component (Old_Discr);
11911                      Set_Original_Record_Component (New_C, Old_Discr);
11912                   end if;
11913
11914                   Next_Elmt (Constr);
11915                   Next_Stored_Discriminant (Old_Discr);
11916                end loop;
11917             end;
11918          end if;
11919       end Add_Discriminants;
11920
11921       if Is_Static
11922         and then Is_Variant_Record (Typ)
11923       then
11924          Collect_Fixed_Components (Typ);
11925
11926          Gather_Components (
11927            Typ,
11928            Component_List (Type_Definition (Parent (Typ))),
11929            Governed_By   => Assoc_List,
11930            Into          => Comp_List,
11931            Report_Errors => Errors);
11932          pragma Assert (not Errors);
11933
11934          Create_All_Components;
11935
11936       --  If the subtype declaration is created for a tagged type derivation
11937       --  with constraints, we retrieve the record definition of the parent
11938       --  type to select the components of the proper variant.
11939
11940       elsif Is_Static
11941         and then Is_Tagged_Type (Typ)
11942         and then Nkind (Parent (Typ)) = N_Full_Type_Declaration
11943         and then
11944           Nkind (Type_Definition (Parent (Typ))) = N_Derived_Type_Definition
11945         and then Is_Variant_Record (Parent_Type)
11946       then
11947          Collect_Fixed_Components (Typ);
11948
11949          Gather_Components (
11950            Typ,
11951            Component_List (Type_Definition (Parent (Parent_Type))),
11952            Governed_By   => Assoc_List,
11953            Into          => Comp_List,
11954            Report_Errors => Errors);
11955          pragma Assert (not Errors);
11956
11957          --  If the tagged derivation has a type extension, collect all the
11958          --  new components therein.
11959
11960          if Present
11961               (Record_Extension_Part (Type_Definition (Parent (Typ))))
11962          then
11963             Old_C := First_Component (Typ);
11964             while Present (Old_C) loop
11965                if Original_Record_Component (Old_C) = Old_C
11966                 and then Chars (Old_C) /= Name_uTag
11967                 and then Chars (Old_C) /= Name_uParent
11968                 and then Chars (Old_C) /= Name_uController
11969                then
11970                   Append_Elmt (Old_C, Comp_List);
11971                end if;
11972
11973                Next_Component (Old_C);
11974             end loop;
11975          end if;
11976
11977          Create_All_Components;
11978
11979       else
11980          --  If discriminants are not static, or if this is a multi-level type
11981          --  extension, we have to include all components of the parent type.
11982
11983          Old_C := First_Component (Typ);
11984          while Present (Old_C) loop
11985             New_C := Create_Component (Old_C);
11986
11987             Set_Etype
11988               (New_C,
11989                Constrain_Component_Type
11990                  (Old_C, Subt, Decl_Node, Typ, Constraints));
11991             Set_Is_Public (New_C, Is_Public (Subt));
11992
11993             Next_Component (Old_C);
11994          end loop;
11995       end if;
11996
11997       End_Scope;
11998    end Create_Constrained_Components;
11999
12000    ------------------------------------------
12001    -- Decimal_Fixed_Point_Type_Declaration --
12002    ------------------------------------------
12003
12004    procedure Decimal_Fixed_Point_Type_Declaration
12005      (T   : Entity_Id;
12006       Def : Node_Id)
12007    is
12008       Loc           : constant Source_Ptr := Sloc (Def);
12009       Digs_Expr     : constant Node_Id    := Digits_Expression (Def);
12010       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
12011       Implicit_Base : Entity_Id;
12012       Digs_Val      : Uint;
12013       Delta_Val     : Ureal;
12014       Scale_Val     : Uint;
12015       Bound_Val     : Ureal;
12016
12017    begin
12018       Check_Restriction (No_Fixed_Point, Def);
12019
12020       --  Create implicit base type
12021
12022       Implicit_Base :=
12023         Create_Itype (E_Decimal_Fixed_Point_Type, Parent (Def), T, 'B');
12024       Set_Etype (Implicit_Base, Implicit_Base);
12025
12026       --  Analyze and process delta expression
12027
12028       Analyze_And_Resolve (Delta_Expr, Universal_Real);
12029
12030       Check_Delta_Expression (Delta_Expr);
12031       Delta_Val := Expr_Value_R (Delta_Expr);
12032
12033       --  Check delta is power of 10, and determine scale value from it
12034
12035       declare
12036          Val : Ureal;
12037
12038       begin
12039          Scale_Val := Uint_0;
12040          Val := Delta_Val;
12041
12042          if Val < Ureal_1 then
12043             while Val < Ureal_1 loop
12044                Val := Val * Ureal_10;
12045                Scale_Val := Scale_Val + 1;
12046             end loop;
12047
12048             if Scale_Val > 18 then
12049                Error_Msg_N ("scale exceeds maximum value of 18", Def);
12050                Scale_Val := UI_From_Int (+18);
12051             end if;
12052
12053          else
12054             while Val > Ureal_1 loop
12055                Val := Val / Ureal_10;
12056                Scale_Val := Scale_Val - 1;
12057             end loop;
12058
12059             if Scale_Val < -18 then
12060                Error_Msg_N ("scale is less than minimum value of -18", Def);
12061                Scale_Val := UI_From_Int (-18);
12062             end if;
12063          end if;
12064
12065          if Val /= Ureal_1 then
12066             Error_Msg_N ("delta expression must be a power of 10", Def);
12067             Delta_Val := Ureal_10 ** (-Scale_Val);
12068          end if;
12069       end;
12070
12071       --  Set delta, scale and small (small = delta for decimal type)
12072
12073       Set_Delta_Value (Implicit_Base, Delta_Val);
12074       Set_Scale_Value (Implicit_Base, Scale_Val);
12075       Set_Small_Value (Implicit_Base, Delta_Val);
12076
12077       --  Analyze and process digits expression
12078
12079       Analyze_And_Resolve (Digs_Expr, Any_Integer);
12080       Check_Digits_Expression (Digs_Expr);
12081       Digs_Val := Expr_Value (Digs_Expr);
12082
12083       if Digs_Val > 18 then
12084          Digs_Val := UI_From_Int (+18);
12085          Error_Msg_N ("digits value out of range, maximum is 18", Digs_Expr);
12086       end if;
12087
12088       Set_Digits_Value (Implicit_Base, Digs_Val);
12089       Bound_Val := UR_From_Uint (10 ** Digs_Val - 1) * Delta_Val;
12090
12091       --  Set range of base type from digits value for now. This will be
12092       --  expanded to represent the true underlying base range by Freeze.
12093
12094       Set_Fixed_Range (Implicit_Base, Loc, -Bound_Val, Bound_Val);
12095
12096       --  Note: We leave size as zero for now, size will be set at freeze
12097       --  time. We have to do this for ordinary fixed-point, because the size
12098       --  depends on the specified small, and we might as well do the same for
12099       --  decimal fixed-point.
12100
12101       pragma Assert (Esize (Implicit_Base) = Uint_0);
12102
12103       --  If there are bounds given in the declaration use them as the
12104       --  bounds of the first named subtype.
12105
12106       if Present (Real_Range_Specification (Def)) then
12107          declare
12108             RRS      : constant Node_Id := Real_Range_Specification (Def);
12109             Low      : constant Node_Id := Low_Bound (RRS);
12110             High     : constant Node_Id := High_Bound (RRS);
12111             Low_Val  : Ureal;
12112             High_Val : Ureal;
12113
12114          begin
12115             Analyze_And_Resolve (Low, Any_Real);
12116             Analyze_And_Resolve (High, Any_Real);
12117             Check_Real_Bound (Low);
12118             Check_Real_Bound (High);
12119             Low_Val := Expr_Value_R (Low);
12120             High_Val := Expr_Value_R (High);
12121
12122             if Low_Val < (-Bound_Val) then
12123                Error_Msg_N
12124                  ("range low bound too small for digits value", Low);
12125                Low_Val := -Bound_Val;
12126             end if;
12127
12128             if High_Val > Bound_Val then
12129                Error_Msg_N
12130                  ("range high bound too large for digits value", High);
12131                High_Val := Bound_Val;
12132             end if;
12133
12134             Set_Fixed_Range (T, Loc, Low_Val, High_Val);
12135          end;
12136
12137       --  If no explicit range, use range that corresponds to given
12138       --  digits value. This will end up as the final range for the
12139       --  first subtype.
12140
12141       else
12142          Set_Fixed_Range (T, Loc, -Bound_Val, Bound_Val);
12143       end if;
12144
12145       --  Complete entity for first subtype
12146
12147       Set_Ekind          (T, E_Decimal_Fixed_Point_Subtype);
12148       Set_Etype          (T, Implicit_Base);
12149       Set_Size_Info      (T, Implicit_Base);
12150       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
12151       Set_Digits_Value   (T, Digs_Val);
12152       Set_Delta_Value    (T, Delta_Val);
12153       Set_Small_Value    (T, Delta_Val);
12154       Set_Scale_Value    (T, Scale_Val);
12155       Set_Is_Constrained (T);
12156    end Decimal_Fixed_Point_Type_Declaration;
12157
12158    -----------------------------------
12159    -- Derive_Progenitor_Subprograms --
12160    -----------------------------------
12161
12162    procedure Derive_Progenitor_Subprograms
12163      (Parent_Type : Entity_Id;
12164       Tagged_Type : Entity_Id)
12165    is
12166       E          : Entity_Id;
12167       Elmt       : Elmt_Id;
12168       Iface      : Entity_Id;
12169       Iface_Elmt : Elmt_Id;
12170       Iface_Subp : Entity_Id;
12171       New_Subp   : Entity_Id := Empty;
12172       Prim_Elmt  : Elmt_Id;
12173       Subp       : Entity_Id;
12174       Typ        : Entity_Id;
12175
12176    begin
12177       pragma Assert (Ada_Version >= Ada_2005
12178         and then Is_Record_Type (Tagged_Type)
12179         and then Is_Tagged_Type (Tagged_Type)
12180         and then Has_Interfaces (Tagged_Type));
12181
12182       --  Step 1: Transfer to the full-view primitives associated with the
12183       --  partial-view that cover interface primitives. Conceptually this
12184       --  work should be done later by Process_Full_View; done here to
12185       --  simplify its implementation at later stages. It can be safely
12186       --  done here because interfaces must be visible in the partial and
12187       --  private view (RM 7.3(7.3/2)).
12188
12189       --  Small optimization: This work is only required if the parent is
12190       --  abstract. If the tagged type is not abstract, it cannot have
12191       --  abstract primitives (the only entities in the list of primitives of
12192       --  non-abstract tagged types that can reference abstract primitives
12193       --  through its Alias attribute are the internal entities that have
12194       --  attribute Interface_Alias, and these entities are generated later
12195       --  by Add_Internal_Interface_Entities).
12196
12197       if In_Private_Part (Current_Scope)
12198         and then Is_Abstract_Type (Parent_Type)
12199       then
12200          Elmt := First_Elmt (Primitive_Operations (Tagged_Type));
12201          while Present (Elmt) loop
12202             Subp := Node (Elmt);
12203
12204             --  At this stage it is not possible to have entities in the list
12205             --  of primitives that have attribute Interface_Alias
12206
12207             pragma Assert (No (Interface_Alias (Subp)));
12208
12209             Typ := Find_Dispatching_Type (Ultimate_Alias (Subp));
12210
12211             if Is_Interface (Typ) then
12212                E := Find_Primitive_Covering_Interface
12213                       (Tagged_Type => Tagged_Type,
12214                        Iface_Prim  => Subp);
12215
12216                if Present (E)
12217                  and then Find_Dispatching_Type (Ultimate_Alias (E)) /= Typ
12218                then
12219                   Replace_Elmt (Elmt, E);
12220                   Remove_Homonym (Subp);
12221                end if;
12222             end if;
12223
12224             Next_Elmt (Elmt);
12225          end loop;
12226       end if;
12227
12228       --  Step 2: Add primitives of progenitors that are not implemented by
12229       --  parents of Tagged_Type
12230
12231       if Present (Interfaces (Base_Type (Tagged_Type))) then
12232          Iface_Elmt := First_Elmt (Interfaces (Base_Type (Tagged_Type)));
12233          while Present (Iface_Elmt) loop
12234             Iface := Node (Iface_Elmt);
12235
12236             Prim_Elmt := First_Elmt (Primitive_Operations (Iface));
12237             while Present (Prim_Elmt) loop
12238                Iface_Subp := Node (Prim_Elmt);
12239
12240                --  Exclude derivation of predefined primitives except those
12241                --  that come from source. Required to catch declarations of
12242                --  equality operators of interfaces. For example:
12243
12244                --     type Iface is interface;
12245                --     function "=" (Left, Right : Iface) return Boolean;
12246
12247                if not Is_Predefined_Dispatching_Operation (Iface_Subp)
12248                  or else Comes_From_Source (Iface_Subp)
12249                then
12250                   E := Find_Primitive_Covering_Interface
12251                          (Tagged_Type => Tagged_Type,
12252                           Iface_Prim  => Iface_Subp);
12253
12254                   --  If not found we derive a new primitive leaving its alias
12255                   --  attribute referencing the interface primitive
12256
12257                   if No (E) then
12258                      Derive_Subprogram
12259                        (New_Subp, Iface_Subp, Tagged_Type, Iface);
12260
12261                   --  Propagate to the full view interface entities associated
12262                   --  with the partial view
12263
12264                   elsif In_Private_Part (Current_Scope)
12265                     and then Present (Alias (E))
12266                     and then Alias (E) = Iface_Subp
12267                     and then
12268                       List_Containing (Parent (E)) /=
12269                         Private_Declarations
12270                           (Specification
12271                             (Unit_Declaration_Node (Current_Scope)))
12272                   then
12273                      Append_Elmt (E, Primitive_Operations (Tagged_Type));
12274                   end if;
12275                end if;
12276
12277                Next_Elmt (Prim_Elmt);
12278             end loop;
12279
12280             Next_Elmt (Iface_Elmt);
12281          end loop;
12282       end if;
12283    end Derive_Progenitor_Subprograms;
12284
12285    -----------------------
12286    -- Derive_Subprogram --
12287    -----------------------
12288
12289    procedure Derive_Subprogram
12290      (New_Subp     : in out Entity_Id;
12291       Parent_Subp  : Entity_Id;
12292       Derived_Type : Entity_Id;
12293       Parent_Type  : Entity_Id;
12294       Actual_Subp  : Entity_Id := Empty)
12295    is
12296       Formal : Entity_Id;
12297       --  Formal parameter of parent primitive operation
12298
12299       Formal_Of_Actual : Entity_Id;
12300       --  Formal parameter of actual operation, when the derivation is to
12301       --  create a renaming for a primitive operation of an actual in an
12302       --  instantiation.
12303
12304       New_Formal : Entity_Id;
12305       --  Formal of inherited operation
12306
12307       Visible_Subp : Entity_Id := Parent_Subp;
12308
12309       function Is_Private_Overriding return Boolean;
12310       --  If Subp is a private overriding of a visible operation, the inherited
12311       --  operation derives from the overridden op (even though its body is the
12312       --  overriding one) and the inherited operation is visible now. See
12313       --  sem_disp to see the full details of the handling of the overridden
12314       --  subprogram, which is removed from the list of primitive operations of
12315       --  the type. The overridden subprogram is saved locally in Visible_Subp,
12316       --  and used to diagnose abstract operations that need overriding in the
12317       --  derived type.
12318
12319       procedure Replace_Type (Id, New_Id : Entity_Id);
12320       --  When the type is an anonymous access type, create a new access type
12321       --  designating the derived type.
12322
12323       procedure Set_Derived_Name;
12324       --  This procedure sets the appropriate Chars name for New_Subp. This
12325       --  is normally just a copy of the parent name. An exception arises for
12326       --  type support subprograms, where the name is changed to reflect the
12327       --  name of the derived type, e.g. if type foo is derived from type bar,
12328       --  then a procedure barDA is derived with a name fooDA.
12329
12330       ---------------------------
12331       -- Is_Private_Overriding --
12332       ---------------------------
12333
12334       function Is_Private_Overriding return Boolean is
12335          Prev : Entity_Id;
12336
12337       begin
12338          --  If the parent is not a dispatching operation there is no
12339          --  need to investigate overridings
12340
12341          if not Is_Dispatching_Operation (Parent_Subp) then
12342             return False;
12343          end if;
12344
12345          --  The visible operation that is overridden is a homonym of the
12346          --  parent subprogram. We scan the homonym chain to find the one
12347          --  whose alias is the subprogram we are deriving.
12348
12349          Prev := Current_Entity (Parent_Subp);
12350          while Present (Prev) loop
12351             if Ekind (Prev) = Ekind (Parent_Subp)
12352               and then Alias (Prev) = Parent_Subp
12353               and then Scope (Parent_Subp) = Scope (Prev)
12354               and then not Is_Hidden (Prev)
12355             then
12356                Visible_Subp := Prev;
12357                return True;
12358             end if;
12359
12360             Prev := Homonym (Prev);
12361          end loop;
12362
12363          return False;
12364       end Is_Private_Overriding;
12365
12366       ------------------
12367       -- Replace_Type --
12368       ------------------
12369
12370       procedure Replace_Type (Id, New_Id : Entity_Id) is
12371          Acc_Type : Entity_Id;
12372          Par      : constant Node_Id := Parent (Derived_Type);
12373
12374       begin
12375          --  When the type is an anonymous access type, create a new access
12376          --  type designating the derived type. This itype must be elaborated
12377          --  at the point of the derivation, not on subsequent calls that may
12378          --  be out of the proper scope for Gigi, so we insert a reference to
12379          --  it after the derivation.
12380
12381          if Ekind (Etype (Id)) = E_Anonymous_Access_Type then
12382             declare
12383                Desig_Typ : Entity_Id := Designated_Type (Etype (Id));
12384
12385             begin
12386                if Ekind (Desig_Typ) = E_Record_Type_With_Private
12387                  and then Present (Full_View (Desig_Typ))
12388                  and then not Is_Private_Type (Parent_Type)
12389                then
12390                   Desig_Typ := Full_View (Desig_Typ);
12391                end if;
12392
12393                if Base_Type (Desig_Typ) = Base_Type (Parent_Type)
12394
12395                   --  Ada 2005 (AI-251): Handle also derivations of abstract
12396                   --  interface primitives.
12397
12398                  or else (Is_Interface (Desig_Typ)
12399                           and then not Is_Class_Wide_Type (Desig_Typ))
12400                then
12401                   Acc_Type := New_Copy (Etype (Id));
12402                   Set_Etype (Acc_Type, Acc_Type);
12403                   Set_Scope (Acc_Type, New_Subp);
12404
12405                   --  Compute size of anonymous access type
12406
12407                   if Is_Array_Type (Desig_Typ)
12408                     and then not Is_Constrained (Desig_Typ)
12409                   then
12410                      Init_Size (Acc_Type, 2 * System_Address_Size);
12411                   else
12412                      Init_Size (Acc_Type, System_Address_Size);
12413                   end if;
12414
12415                   Init_Alignment (Acc_Type);
12416                   Set_Directly_Designated_Type (Acc_Type, Derived_Type);
12417
12418                   Set_Etype (New_Id, Acc_Type);
12419                   Set_Scope (New_Id, New_Subp);
12420
12421                   --  Create a reference to it
12422                   Build_Itype_Reference (Acc_Type, Parent (Derived_Type));
12423
12424                else
12425                   Set_Etype (New_Id, Etype (Id));
12426                end if;
12427             end;
12428
12429          elsif Base_Type (Etype (Id)) = Base_Type (Parent_Type)
12430            or else
12431              (Ekind (Etype (Id)) = E_Record_Type_With_Private
12432                and then Present (Full_View (Etype (Id)))
12433                and then
12434                  Base_Type (Full_View (Etype (Id))) = Base_Type (Parent_Type))
12435          then
12436             --  Constraint checks on formals are generated during expansion,
12437             --  based on the signature of the original subprogram. The bounds
12438             --  of the derived type are not relevant, and thus we can use
12439             --  the base type for the formals. However, the return type may be
12440             --  used in a context that requires that the proper static bounds
12441             --  be used (a case statement, for example)  and for those cases
12442             --  we must use the derived type (first subtype), not its base.
12443
12444             --  If the derived_type_definition has no constraints, we know that
12445             --  the derived type has the same constraints as the first subtype
12446             --  of the parent, and we can also use it rather than its base,
12447             --  which can lead to more efficient code.
12448
12449             if Etype (Id) = Parent_Type then
12450                if Is_Scalar_Type (Parent_Type)
12451                  and then
12452                    Subtypes_Statically_Compatible (Parent_Type, Derived_Type)
12453                then
12454                   Set_Etype (New_Id, Derived_Type);
12455
12456                elsif Nkind (Par) = N_Full_Type_Declaration
12457                  and then
12458                    Nkind (Type_Definition (Par)) = N_Derived_Type_Definition
12459                  and then
12460                    Is_Entity_Name
12461                      (Subtype_Indication (Type_Definition (Par)))
12462                then
12463                   Set_Etype (New_Id, Derived_Type);
12464
12465                else
12466                   Set_Etype (New_Id, Base_Type (Derived_Type));
12467                end if;
12468
12469             else
12470                Set_Etype (New_Id, Base_Type (Derived_Type));
12471             end if;
12472
12473          else
12474             Set_Etype (New_Id, Etype (Id));
12475          end if;
12476       end Replace_Type;
12477
12478       ----------------------
12479       -- Set_Derived_Name --
12480       ----------------------
12481
12482       procedure Set_Derived_Name is
12483          Nm : constant TSS_Name_Type := Get_TSS_Name (Parent_Subp);
12484       begin
12485          if Nm = TSS_Null then
12486             Set_Chars (New_Subp, Chars (Parent_Subp));
12487          else
12488             Set_Chars (New_Subp, Make_TSS_Name (Base_Type (Derived_Type), Nm));
12489          end if;
12490       end Set_Derived_Name;
12491
12492    --  Start of processing for Derive_Subprogram
12493
12494    begin
12495       New_Subp :=
12496          New_Entity (Nkind (Parent_Subp), Sloc (Derived_Type));
12497       Set_Ekind (New_Subp, Ekind (Parent_Subp));
12498
12499       --  Check whether the inherited subprogram is a private operation that
12500       --  should be inherited but not yet made visible. Such subprograms can
12501       --  become visible at a later point (e.g., the private part of a public
12502       --  child unit) via Declare_Inherited_Private_Subprograms. If the
12503       --  following predicate is true, then this is not such a private
12504       --  operation and the subprogram simply inherits the name of the parent
12505       --  subprogram. Note the special check for the names of controlled
12506       --  operations, which are currently exempted from being inherited with
12507       --  a hidden name because they must be findable for generation of
12508       --  implicit run-time calls.
12509
12510       if not Is_Hidden (Parent_Subp)
12511         or else Is_Internal (Parent_Subp)
12512         or else Is_Private_Overriding
12513         or else Is_Internal_Name (Chars (Parent_Subp))
12514         or else Chars (Parent_Subp) = Name_Initialize
12515         or else Chars (Parent_Subp) = Name_Adjust
12516         or else Chars (Parent_Subp) = Name_Finalize
12517       then
12518          Set_Derived_Name;
12519
12520       --  An inherited dispatching equality will be overridden by an internally
12521       --  generated one, or by an explicit one, so preserve its name and thus
12522       --  its entry in the dispatch table. Otherwise, if Parent_Subp is a
12523       --  private operation it may become invisible if the full view has
12524       --  progenitors, and the dispatch table will be malformed.
12525       --  We check that the type is limited to handle the anomalous declaration
12526       --  of Limited_Controlled, which is derived from a non-limited type, and
12527       --  which is handled specially elsewhere as well.
12528
12529       elsif Chars (Parent_Subp) = Name_Op_Eq
12530         and then Is_Dispatching_Operation (Parent_Subp)
12531         and then Etype (Parent_Subp) = Standard_Boolean
12532         and then not Is_Limited_Type (Etype (First_Formal (Parent_Subp)))
12533         and then
12534           Etype (First_Formal (Parent_Subp)) =
12535             Etype (Next_Formal (First_Formal (Parent_Subp)))
12536       then
12537          Set_Derived_Name;
12538
12539       --  If parent is hidden, this can be a regular derivation if the
12540       --  parent is immediately visible in a non-instantiating context,
12541       --  or if we are in the private part of an instance. This test
12542       --  should still be refined ???
12543
12544       --  The test for In_Instance_Not_Visible avoids inheriting the derived
12545       --  operation as a non-visible operation in cases where the parent
12546       --  subprogram might not be visible now, but was visible within the
12547       --  original generic, so it would be wrong to make the inherited
12548       --  subprogram non-visible now. (Not clear if this test is fully
12549       --  correct; are there any cases where we should declare the inherited
12550       --  operation as not visible to avoid it being overridden, e.g., when
12551       --  the parent type is a generic actual with private primitives ???)
12552
12553       --  (they should be treated the same as other private inherited
12554       --  subprograms, but it's not clear how to do this cleanly). ???
12555
12556       elsif (In_Open_Scopes (Scope (Base_Type (Parent_Type)))
12557               and then Is_Immediately_Visible (Parent_Subp)
12558               and then not In_Instance)
12559         or else In_Instance_Not_Visible
12560       then
12561          Set_Derived_Name;
12562
12563       --  Ada 2005 (AI-251): Regular derivation if the parent subprogram
12564       --  overrides an interface primitive because interface primitives
12565       --  must be visible in the partial view of the parent (RM 7.3 (7.3/2))
12566
12567       elsif Ada_Version >= Ada_2005
12568          and then Is_Dispatching_Operation (Parent_Subp)
12569          and then Covers_Some_Interface (Parent_Subp)
12570       then
12571          Set_Derived_Name;
12572
12573       --  Otherwise, the type is inheriting a private operation, so enter
12574       --  it with a special name so it can't be overridden.
12575
12576       else
12577          Set_Chars (New_Subp, New_External_Name (Chars (Parent_Subp), 'P'));
12578       end if;
12579
12580       Set_Parent (New_Subp, Parent (Derived_Type));
12581
12582       if Present (Actual_Subp) then
12583          Replace_Type (Actual_Subp, New_Subp);
12584       else
12585          Replace_Type (Parent_Subp, New_Subp);
12586       end if;
12587
12588       Conditional_Delay (New_Subp, Parent_Subp);
12589
12590       --  If we are creating a renaming for a primitive operation of an
12591       --  actual of a generic derived type, we must examine the signature
12592       --  of the actual primitive, not that of the generic formal, which for
12593       --  example may be an interface. However the name and initial value
12594       --  of the inherited operation are those of the formal primitive.
12595
12596       Formal := First_Formal (Parent_Subp);
12597
12598       if Present (Actual_Subp) then
12599          Formal_Of_Actual := First_Formal (Actual_Subp);
12600       else
12601          Formal_Of_Actual := Empty;
12602       end if;
12603
12604       while Present (Formal) loop
12605          New_Formal := New_Copy (Formal);
12606
12607          --  Normally we do not go copying parents, but in the case of
12608          --  formals, we need to link up to the declaration (which is the
12609          --  parameter specification), and it is fine to link up to the
12610          --  original formal's parameter specification in this case.
12611
12612          Set_Parent (New_Formal, Parent (Formal));
12613          Append_Entity (New_Formal, New_Subp);
12614
12615          if Present (Formal_Of_Actual) then
12616             Replace_Type (Formal_Of_Actual, New_Formal);
12617             Next_Formal (Formal_Of_Actual);
12618          else
12619             Replace_Type (Formal, New_Formal);
12620          end if;
12621
12622          Next_Formal (Formal);
12623       end loop;
12624
12625       --  If this derivation corresponds to a tagged generic actual, then
12626       --  primitive operations rename those of the actual. Otherwise the
12627       --  primitive operations rename those of the parent type, If the parent
12628       --  renames an intrinsic operator, so does the new subprogram. We except
12629       --  concatenation, which is always properly typed, and does not get
12630       --  expanded as other intrinsic operations.
12631
12632       if No (Actual_Subp) then
12633          if Is_Intrinsic_Subprogram (Parent_Subp) then
12634             Set_Is_Intrinsic_Subprogram (New_Subp);
12635
12636             if Present (Alias (Parent_Subp))
12637               and then Chars (Parent_Subp) /= Name_Op_Concat
12638             then
12639                Set_Alias (New_Subp, Alias (Parent_Subp));
12640             else
12641                Set_Alias (New_Subp, Parent_Subp);
12642             end if;
12643
12644          else
12645             Set_Alias (New_Subp, Parent_Subp);
12646          end if;
12647
12648       else
12649          Set_Alias (New_Subp, Actual_Subp);
12650       end if;
12651
12652       --  Derived subprograms of a tagged type must inherit the convention
12653       --  of the parent subprogram (a requirement of AI-117). Derived
12654       --  subprograms of untagged types simply get convention Ada by default.
12655
12656       if Is_Tagged_Type (Derived_Type) then
12657          Set_Convention (New_Subp, Convention (Parent_Subp));
12658       end if;
12659
12660       --  Predefined controlled operations retain their name even if the parent
12661       --  is hidden (see above), but they are not primitive operations if the
12662       --  ancestor is not visible, for example if the parent is a private
12663       --  extension completed with a controlled extension. Note that a full
12664       --  type that is controlled can break privacy: the flag Is_Controlled is
12665       --  set on both views of the type.
12666
12667       if Is_Controlled (Parent_Type)
12668         and then
12669           (Chars (Parent_Subp) = Name_Initialize
12670             or else Chars (Parent_Subp) = Name_Adjust
12671             or else Chars (Parent_Subp) = Name_Finalize)
12672         and then Is_Hidden (Parent_Subp)
12673         and then not Is_Visibly_Controlled (Parent_Type)
12674       then
12675          Set_Is_Hidden (New_Subp);
12676       end if;
12677
12678       Set_Is_Imported (New_Subp, Is_Imported (Parent_Subp));
12679       Set_Is_Exported (New_Subp, Is_Exported (Parent_Subp));
12680
12681       if Ekind (Parent_Subp) = E_Procedure then
12682          Set_Is_Valued_Procedure
12683            (New_Subp, Is_Valued_Procedure (Parent_Subp));
12684       else
12685          Set_Has_Controlling_Result
12686            (New_Subp, Has_Controlling_Result (Parent_Subp));
12687       end if;
12688
12689       --  No_Return must be inherited properly. If this is overridden in the
12690       --  case of a dispatching operation, then a check is made in Sem_Disp
12691       --  that the overriding operation is also No_Return (no such check is
12692       --  required for the case of non-dispatching operation.
12693
12694       Set_No_Return (New_Subp, No_Return (Parent_Subp));
12695
12696       --  A derived function with a controlling result is abstract. If the
12697       --  Derived_Type is a nonabstract formal generic derived type, then
12698       --  inherited operations are not abstract: the required check is done at
12699       --  instantiation time. If the derivation is for a generic actual, the
12700       --  function is not abstract unless the actual is.
12701
12702       if Is_Generic_Type (Derived_Type)
12703         and then not Is_Abstract_Type (Derived_Type)
12704       then
12705          null;
12706
12707       --  Ada 2005 (AI-228): Calculate the "require overriding" and "abstract"
12708       --  properties of the subprogram, as defined in RM-3.9.3(4/2-6/2).
12709
12710       elsif Ada_Version >= Ada_2005
12711         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12712                    or else (Is_Tagged_Type (Derived_Type)
12713                             and then Etype (New_Subp) = Derived_Type
12714                             and then not Is_Null_Extension (Derived_Type))
12715                    or else (Is_Tagged_Type (Derived_Type)
12716                             and then Ekind (Etype (New_Subp)) =
12717                                                        E_Anonymous_Access_Type
12718                             and then Designated_Type (Etype (New_Subp)) =
12719                                                        Derived_Type
12720                             and then not Is_Null_Extension (Derived_Type)))
12721         and then No (Actual_Subp)
12722       then
12723          if not Is_Tagged_Type (Derived_Type)
12724            or else Is_Abstract_Type (Derived_Type)
12725            or else Is_Abstract_Subprogram (Alias (New_Subp))
12726          then
12727             Set_Is_Abstract_Subprogram (New_Subp);
12728          else
12729             Set_Requires_Overriding (New_Subp);
12730          end if;
12731
12732       elsif Ada_Version < Ada_2005
12733         and then (Is_Abstract_Subprogram (Alias (New_Subp))
12734                    or else (Is_Tagged_Type (Derived_Type)
12735                              and then Etype (New_Subp) = Derived_Type
12736                              and then No (Actual_Subp)))
12737       then
12738          Set_Is_Abstract_Subprogram (New_Subp);
12739
12740       --  AI05-0097 : an inherited operation that dispatches on result is
12741       --  abstract if the derived type is abstract, even if the parent type
12742       --  is concrete and the derived type is a null extension.
12743
12744       elsif Has_Controlling_Result (Alias (New_Subp))
12745         and then Is_Abstract_Type (Etype (New_Subp))
12746       then
12747          Set_Is_Abstract_Subprogram (New_Subp);
12748
12749       --  Finally, if the parent type is abstract we must verify that all
12750       --  inherited operations are either non-abstract or overridden, or that
12751       --  the derived type itself is abstract (this check is performed at the
12752       --  end of a package declaration, in Check_Abstract_Overriding). A
12753       --  private overriding in the parent type will not be visible in the
12754       --  derivation if we are not in an inner package or in a child unit of
12755       --  the parent type, in which case the abstractness of the inherited
12756       --  operation is carried to the new subprogram.
12757
12758       elsif Is_Abstract_Type (Parent_Type)
12759         and then not In_Open_Scopes (Scope (Parent_Type))
12760         and then Is_Private_Overriding
12761         and then Is_Abstract_Subprogram (Visible_Subp)
12762       then
12763          if No (Actual_Subp) then
12764             Set_Alias (New_Subp, Visible_Subp);
12765             Set_Is_Abstract_Subprogram (New_Subp, True);
12766
12767          else
12768             --  If this is a derivation for an instance of a formal derived
12769             --  type, abstractness comes from the primitive operation of the
12770             --  actual, not from the operation inherited from the ancestor.
12771
12772             Set_Is_Abstract_Subprogram
12773               (New_Subp, Is_Abstract_Subprogram (Actual_Subp));
12774          end if;
12775       end if;
12776
12777       New_Overloaded_Entity (New_Subp, Derived_Type);
12778
12779       --  Check for case of a derived subprogram for the instantiation of a
12780       --  formal derived tagged type, if so mark the subprogram as dispatching
12781       --  and inherit the dispatching attributes of the parent subprogram. The
12782       --  derived subprogram is effectively renaming of the actual subprogram,
12783       --  so it needs to have the same attributes as the actual.
12784
12785       if Present (Actual_Subp)
12786         and then Is_Dispatching_Operation (Parent_Subp)
12787       then
12788          Set_Is_Dispatching_Operation (New_Subp);
12789
12790          if Present (DTC_Entity (Parent_Subp)) then
12791             Set_DTC_Entity (New_Subp, DTC_Entity (Parent_Subp));
12792             Set_DT_Position (New_Subp, DT_Position (Parent_Subp));
12793          end if;
12794       end if;
12795
12796       --  Indicate that a derived subprogram does not require a body and that
12797       --  it does not require processing of default expressions.
12798
12799       Set_Has_Completion (New_Subp);
12800       Set_Default_Expressions_Processed (New_Subp);
12801
12802       if Ekind (New_Subp) = E_Function then
12803          Set_Mechanism (New_Subp, Mechanism (Parent_Subp));
12804       end if;
12805    end Derive_Subprogram;
12806
12807    ------------------------
12808    -- Derive_Subprograms --
12809    ------------------------
12810
12811    procedure Derive_Subprograms
12812      (Parent_Type    : Entity_Id;
12813       Derived_Type   : Entity_Id;
12814       Generic_Actual : Entity_Id := Empty)
12815    is
12816       Op_List : constant Elist_Id :=
12817                   Collect_Primitive_Operations (Parent_Type);
12818
12819       function Check_Derived_Type return Boolean;
12820       --  Check that all primitive inherited from Parent_Type are found in
12821       --  the list of primitives of Derived_Type exactly in the same order.
12822
12823       function Check_Derived_Type return Boolean is
12824          E        : Entity_Id;
12825          Elmt     : Elmt_Id;
12826          List     : Elist_Id;
12827          New_Subp : Entity_Id;
12828          Op_Elmt  : Elmt_Id;
12829          Subp     : Entity_Id;
12830
12831       begin
12832          --  Traverse list of entities in the current scope searching for
12833          --  an incomplete type whose full-view is derived type
12834
12835          E := First_Entity (Scope (Derived_Type));
12836          while Present (E)
12837            and then E /= Derived_Type
12838          loop
12839             if Ekind (E) = E_Incomplete_Type
12840               and then Present (Full_View (E))
12841               and then Full_View (E) = Derived_Type
12842             then
12843                --  Disable this test if Derived_Type completes an incomplete
12844                --  type because in such case more primitives can be added
12845                --  later to the list of primitives of Derived_Type by routine
12846                --  Process_Incomplete_Dependents
12847
12848                return True;
12849             end if;
12850
12851             E := Next_Entity (E);
12852          end loop;
12853
12854          List := Collect_Primitive_Operations (Derived_Type);
12855          Elmt := First_Elmt (List);
12856
12857          Op_Elmt := First_Elmt (Op_List);
12858          while Present (Op_Elmt) loop
12859             Subp     := Node (Op_Elmt);
12860             New_Subp := Node (Elmt);
12861
12862             --  At this early stage Derived_Type has no entities with attribute
12863             --  Interface_Alias. In addition, such primitives are always
12864             --  located at the end of the list of primitives of Parent_Type.
12865             --  Therefore, if found we can safely stop processing pending
12866             --  entities.
12867
12868             exit when Present (Interface_Alias (Subp));
12869
12870             --  Handle hidden entities
12871
12872             if not Is_Predefined_Dispatching_Operation (Subp)
12873               and then Is_Hidden (Subp)
12874             then
12875                if Present (New_Subp)
12876                  and then Primitive_Names_Match (Subp, New_Subp)
12877                then
12878                   Next_Elmt (Elmt);
12879                end if;
12880
12881             else
12882                if not Present (New_Subp)
12883                  or else Ekind (Subp) /= Ekind (New_Subp)
12884                  or else not Primitive_Names_Match (Subp, New_Subp)
12885                then
12886                   return False;
12887                end if;
12888
12889                Next_Elmt (Elmt);
12890             end if;
12891
12892             Next_Elmt (Op_Elmt);
12893          end loop;
12894
12895          return True;
12896       end Check_Derived_Type;
12897
12898       --  Local variables
12899
12900       Alias_Subp   : Entity_Id;
12901       Act_List     : Elist_Id;
12902       Act_Elmt     : Elmt_Id   := No_Elmt;
12903       Act_Subp     : Entity_Id := Empty;
12904       Elmt         : Elmt_Id;
12905       Need_Search  : Boolean   := False;
12906       New_Subp     : Entity_Id := Empty;
12907       Parent_Base  : Entity_Id;
12908       Subp         : Entity_Id;
12909
12910    --  Start of processing for Derive_Subprograms
12911
12912    begin
12913       if Ekind (Parent_Type) = E_Record_Type_With_Private
12914         and then Has_Discriminants (Parent_Type)
12915         and then Present (Full_View (Parent_Type))
12916       then
12917          Parent_Base := Full_View (Parent_Type);
12918       else
12919          Parent_Base := Parent_Type;
12920       end if;
12921
12922       if Present (Generic_Actual) then
12923          Act_List := Collect_Primitive_Operations (Generic_Actual);
12924          Act_Elmt := First_Elmt (Act_List);
12925       end if;
12926
12927       --  Derive primitives inherited from the parent. Note that if the generic
12928       --  actual is present, this is not really a type derivation, it is a
12929       --  completion within an instance.
12930
12931       --  Case 1: Derived_Type does not implement interfaces
12932
12933       if not Is_Tagged_Type (Derived_Type)
12934         or else (not Has_Interfaces (Derived_Type)
12935                   and then not (Present (Generic_Actual)
12936                                   and then
12937                                 Has_Interfaces (Generic_Actual)))
12938       then
12939          Elmt := First_Elmt (Op_List);
12940          while Present (Elmt) loop
12941             Subp := Node (Elmt);
12942
12943             --  Literals are derived earlier in the process of building the
12944             --  derived type, and are skipped here.
12945
12946             if Ekind (Subp) = E_Enumeration_Literal then
12947                null;
12948
12949             --  The actual is a direct descendant and the common primitive
12950             --  operations appear in the same order.
12951
12952             --  If the generic parent type is present, the derived type is an
12953             --  instance of a formal derived type, and within the instance its
12954             --  operations are those of the actual. We derive from the formal
12955             --  type but make the inherited operations aliases of the
12956             --  corresponding operations of the actual.
12957
12958             else
12959                pragma Assert (No (Node (Act_Elmt))
12960                  or else (Primitive_Names_Match (Subp, Node (Act_Elmt))
12961                             and then
12962                           Type_Conformant (Subp, Node (Act_Elmt),
12963                                            Skip_Controlling_Formals => True)));
12964
12965                Derive_Subprogram
12966                  (New_Subp, Subp, Derived_Type, Parent_Base, Node (Act_Elmt));
12967
12968                if Present (Act_Elmt) then
12969                   Next_Elmt (Act_Elmt);
12970                end if;
12971             end if;
12972
12973             Next_Elmt (Elmt);
12974          end loop;
12975
12976       --  Case 2: Derived_Type implements interfaces
12977
12978       else
12979          --  If the parent type has no predefined primitives we remove
12980          --  predefined primitives from the list of primitives of generic
12981          --  actual to simplify the complexity of this algorithm.
12982
12983          if Present (Generic_Actual) then
12984             declare
12985                Has_Predefined_Primitives : Boolean := False;
12986
12987             begin
12988                --  Check if the parent type has predefined primitives
12989
12990                Elmt := First_Elmt (Op_List);
12991                while Present (Elmt) loop
12992                   Subp := Node (Elmt);
12993
12994                   if Is_Predefined_Dispatching_Operation (Subp)
12995                     and then not Comes_From_Source (Ultimate_Alias (Subp))
12996                   then
12997                      Has_Predefined_Primitives := True;
12998                      exit;
12999                   end if;
13000
13001                   Next_Elmt (Elmt);
13002                end loop;
13003
13004                --  Remove predefined primitives of Generic_Actual. We must use
13005                --  an auxiliary list because in case of tagged types the value
13006                --  returned by Collect_Primitive_Operations is the value stored
13007                --  in its Primitive_Operations attribute (and we don't want to
13008                --  modify its current contents).
13009
13010                if not Has_Predefined_Primitives then
13011                   declare
13012                      Aux_List : constant Elist_Id := New_Elmt_List;
13013
13014                   begin
13015                      Elmt := First_Elmt (Act_List);
13016                      while Present (Elmt) loop
13017                         Subp := Node (Elmt);
13018
13019                         if not Is_Predefined_Dispatching_Operation (Subp)
13020                           or else Comes_From_Source (Subp)
13021                         then
13022                            Append_Elmt (Subp, Aux_List);
13023                         end if;
13024
13025                         Next_Elmt (Elmt);
13026                      end loop;
13027
13028                      Act_List := Aux_List;
13029                   end;
13030                end if;
13031
13032                Act_Elmt := First_Elmt (Act_List);
13033                Act_Subp := Node (Act_Elmt);
13034             end;
13035          end if;
13036
13037          --  Stage 1: If the generic actual is not present we derive the
13038          --  primitives inherited from the parent type. If the generic parent
13039          --  type is present, the derived type is an instance of a formal
13040          --  derived type, and within the instance its operations are those of
13041          --  the actual. We derive from the formal type but make the inherited
13042          --  operations aliases of the corresponding operations of the actual.
13043
13044          Elmt := First_Elmt (Op_List);
13045          while Present (Elmt) loop
13046             Subp       := Node (Elmt);
13047             Alias_Subp := Ultimate_Alias (Subp);
13048
13049             --  Do not derive internal entities of the parent that link
13050             --  interface primitives and its covering primitive. These
13051             --  entities will be added to this type when frozen.
13052
13053             if Present (Interface_Alias (Subp)) then
13054                goto Continue;
13055             end if;
13056
13057             --  If the generic actual is present find the corresponding
13058             --  operation in the generic actual. If the parent type is a
13059             --  direct ancestor of the derived type then, even if it is an
13060             --  interface, the operations are inherited from the primary
13061             --  dispatch table and are in the proper order. If we detect here
13062             --  that primitives are not in the same order we traverse the list
13063             --  of primitive operations of the actual to find the one that
13064             --  implements the interface primitive.
13065
13066             if Need_Search
13067               or else
13068                 (Present (Generic_Actual)
13069                   and then Present (Act_Subp)
13070                   and then not
13071                     (Primitive_Names_Match (Subp, Act_Subp)
13072                        and then
13073                      Type_Conformant (Subp, Act_Subp,
13074                                       Skip_Controlling_Formals => True)))
13075             then
13076                pragma Assert (not Is_Ancestor (Parent_Base, Generic_Actual));
13077
13078                --  Remember that we need searching for all pending primitives
13079
13080                Need_Search := True;
13081
13082                --  Handle entities associated with interface primitives
13083
13084                if Present (Alias_Subp)
13085                  and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13086                  and then not Is_Predefined_Dispatching_Operation (Subp)
13087                then
13088                   --  Search for the primitive in the homonym chain
13089
13090                   Act_Subp :=
13091                     Find_Primitive_Covering_Interface
13092                       (Tagged_Type => Generic_Actual,
13093                        Iface_Prim  => Alias_Subp);
13094
13095                   --  Previous search may not locate primitives covering
13096                   --  interfaces defined in generics units or instantiations.
13097                   --  (it fails if the covering primitive has formals whose
13098                   --  type is also defined in generics or instantiations).
13099                   --  In such case we search in the list of primitives of the
13100                   --  generic actual for the internal entity that links the
13101                   --  interface primitive and the covering primitive.
13102
13103                   if No (Act_Subp)
13104                     and then Is_Generic_Type (Parent_Type)
13105                   then
13106                      --  This code has been designed to handle only generic
13107                      --  formals that implement interfaces that are defined
13108                      --  in a generic unit or instantiation. If this code is
13109                      --  needed for other cases we must review it because
13110                      --  (given that it relies on Original_Location to locate
13111                      --  the primitive of Generic_Actual that covers the
13112                      --  interface) it could leave linked through attribute
13113                      --  Alias entities of unrelated instantiations).
13114
13115                      pragma Assert
13116                        (Is_Generic_Unit
13117                           (Scope (Find_Dispatching_Type (Alias_Subp)))
13118                        or else
13119                         Instantiation_Depth
13120                           (Sloc (Find_Dispatching_Type (Alias_Subp))) > 0);
13121
13122                      declare
13123                         Iface_Prim_Loc : constant Source_Ptr :=
13124                                          Original_Location (Sloc (Alias_Subp));
13125                         Elmt      : Elmt_Id;
13126                         Prim      : Entity_Id;
13127                      begin
13128                         Elmt :=
13129                           First_Elmt (Primitive_Operations (Generic_Actual));
13130
13131                         Search : while Present (Elmt) loop
13132                            Prim := Node (Elmt);
13133
13134                            if Present (Interface_Alias (Prim))
13135                              and then Original_Location
13136                                         (Sloc (Interface_Alias (Prim)))
13137                                        = Iface_Prim_Loc
13138                            then
13139                               Act_Subp := Alias (Prim);
13140                               exit Search;
13141                            end if;
13142
13143                            Next_Elmt (Elmt);
13144                         end loop Search;
13145                      end;
13146                   end if;
13147
13148                   pragma Assert (Present (Act_Subp)
13149                     or else Is_Abstract_Type (Generic_Actual)
13150                     or else Serious_Errors_Detected > 0);
13151
13152                --  Handle predefined primitives plus the rest of user-defined
13153                --  primitives
13154
13155                else
13156                   Act_Elmt := First_Elmt (Act_List);
13157                   while Present (Act_Elmt) loop
13158                      Act_Subp := Node (Act_Elmt);
13159
13160                      exit when Primitive_Names_Match (Subp, Act_Subp)
13161                        and then Type_Conformant
13162                                   (Subp, Act_Subp,
13163                                    Skip_Controlling_Formals => True)
13164                        and then No (Interface_Alias (Act_Subp));
13165
13166                      Next_Elmt (Act_Elmt);
13167                   end loop;
13168
13169                   if No (Act_Elmt) then
13170                      Act_Subp := Empty;
13171                   end if;
13172                end if;
13173             end if;
13174
13175             --   Case 1: If the parent is a limited interface then it has the
13176             --   predefined primitives of synchronized interfaces. However, the
13177             --   actual type may be a non-limited type and hence it does not
13178             --   have such primitives.
13179
13180             if Present (Generic_Actual)
13181               and then not Present (Act_Subp)
13182               and then Is_Limited_Interface (Parent_Base)
13183               and then Is_Predefined_Interface_Primitive (Subp)
13184             then
13185                null;
13186
13187             --  Case 2: Inherit entities associated with interfaces that were
13188             --  not covered by the parent type. We exclude here null interface
13189             --  primitives because they do not need special management.
13190
13191             --  We also exclude interface operations that are renamings. If the
13192             --  subprogram is an explicit renaming of an interface primitive,
13193             --  it is a regular primitive operation, and the presence of its
13194             --  alias is not relevant: it has to be derived like any other
13195             --  primitive.
13196
13197             elsif Present (Alias (Subp))
13198               and then Nkind (Unit_Declaration_Node (Subp)) /=
13199                                             N_Subprogram_Renaming_Declaration
13200               and then Is_Interface (Find_Dispatching_Type (Alias_Subp))
13201               and then not
13202                 (Nkind (Parent (Alias_Subp)) = N_Procedure_Specification
13203                   and then Null_Present (Parent (Alias_Subp)))
13204             then
13205                Derive_Subprogram
13206                  (New_Subp     => New_Subp,
13207                   Parent_Subp  => Alias_Subp,
13208                   Derived_Type => Derived_Type,
13209                   Parent_Type  => Find_Dispatching_Type (Alias_Subp),
13210                   Actual_Subp  => Act_Subp);
13211
13212                if No (Generic_Actual) then
13213                   Set_Alias (New_Subp, Subp);
13214                end if;
13215
13216             --  Case 3: Common derivation
13217
13218             else
13219                Derive_Subprogram
13220                  (New_Subp     => New_Subp,
13221                   Parent_Subp  => Subp,
13222                   Derived_Type => Derived_Type,
13223                   Parent_Type  => Parent_Base,
13224                   Actual_Subp  => Act_Subp);
13225             end if;
13226
13227             --  No need to update Act_Elm if we must search for the
13228             --  corresponding operation in the generic actual
13229
13230             if not Need_Search
13231               and then Present (Act_Elmt)
13232             then
13233                Next_Elmt (Act_Elmt);
13234                Act_Subp := Node (Act_Elmt);
13235             end if;
13236
13237             <<Continue>>
13238             Next_Elmt (Elmt);
13239          end loop;
13240
13241          --  Inherit additional operations from progenitors. If the derived
13242          --  type is a generic actual, there are not new primitive operations
13243          --  for the type because it has those of the actual, and therefore
13244          --  nothing needs to be done. The renamings generated above are not
13245          --  primitive operations, and their purpose is simply to make the
13246          --  proper operations visible within an instantiation.
13247
13248          if No (Generic_Actual) then
13249             Derive_Progenitor_Subprograms (Parent_Base, Derived_Type);
13250          end if;
13251       end if;
13252
13253       --  Final check: Direct descendants must have their primitives in the
13254       --  same order. We exclude from this test untagged types and instances
13255       --  of formal derived types. We skip this test if we have already
13256       --  reported serious errors in the sources.
13257
13258       pragma Assert (not Is_Tagged_Type (Derived_Type)
13259         or else Present (Generic_Actual)
13260         or else Serious_Errors_Detected > 0
13261         or else Check_Derived_Type);
13262    end Derive_Subprograms;
13263
13264    --------------------------------
13265    -- Derived_Standard_Character --
13266    --------------------------------
13267
13268    procedure Derived_Standard_Character
13269      (N            : Node_Id;
13270       Parent_Type  : Entity_Id;
13271       Derived_Type : Entity_Id)
13272    is
13273       Loc           : constant Source_Ptr := Sloc (N);
13274       Def           : constant Node_Id    := Type_Definition (N);
13275       Indic         : constant Node_Id    := Subtype_Indication (Def);
13276       Parent_Base   : constant Entity_Id  := Base_Type (Parent_Type);
13277       Implicit_Base : constant Entity_Id  :=
13278                         Create_Itype
13279                           (E_Enumeration_Type, N, Derived_Type, 'B');
13280
13281       Lo : Node_Id;
13282       Hi : Node_Id;
13283
13284    begin
13285       Discard_Node (Process_Subtype (Indic, N));
13286
13287       Set_Etype     (Implicit_Base, Parent_Base);
13288       Set_Size_Info (Implicit_Base, Root_Type (Parent_Type));
13289       Set_RM_Size   (Implicit_Base, RM_Size (Root_Type (Parent_Type)));
13290
13291       Set_Is_Character_Type  (Implicit_Base, True);
13292       Set_Has_Delayed_Freeze (Implicit_Base);
13293
13294       --  The bounds of the implicit base are the bounds of the parent base.
13295       --  Note that their type is the parent base.
13296
13297       Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Base));
13298       Hi := New_Copy_Tree (Type_High_Bound (Parent_Base));
13299
13300       Set_Scalar_Range (Implicit_Base,
13301         Make_Range (Loc,
13302           Low_Bound  => Lo,
13303           High_Bound => Hi));
13304
13305       Conditional_Delay (Derived_Type, Parent_Type);
13306
13307       Set_Ekind (Derived_Type, E_Enumeration_Subtype);
13308       Set_Etype (Derived_Type, Implicit_Base);
13309       Set_Size_Info         (Derived_Type, Parent_Type);
13310
13311       if Unknown_RM_Size (Derived_Type) then
13312          Set_RM_Size (Derived_Type, RM_Size (Parent_Type));
13313       end if;
13314
13315       Set_Is_Character_Type (Derived_Type, True);
13316
13317       if Nkind (Indic) /= N_Subtype_Indication then
13318
13319          --  If no explicit constraint, the bounds are those
13320          --  of the parent type.
13321
13322          Lo := New_Copy_Tree (Type_Low_Bound  (Parent_Type));
13323          Hi := New_Copy_Tree (Type_High_Bound (Parent_Type));
13324          Set_Scalar_Range (Derived_Type, Make_Range (Loc, Lo, Hi));
13325       end if;
13326
13327       Convert_Scalar_Bounds (N, Parent_Type, Derived_Type, Loc);
13328
13329       --  Because the implicit base is used in the conversion of the bounds, we
13330       --  have to freeze it now. This is similar to what is done for numeric
13331       --  types, and it equally suspicious, but otherwise a non-static bound
13332       --  will have a reference to an unfrozen type, which is rejected by Gigi
13333       --  (???). This requires specific care for definition of stream
13334       --  attributes. For details, see comments at the end of
13335       --  Build_Derived_Numeric_Type.
13336
13337       Freeze_Before (N, Implicit_Base);
13338    end Derived_Standard_Character;
13339
13340    ------------------------------
13341    -- Derived_Type_Declaration --
13342    ------------------------------
13343
13344    procedure Derived_Type_Declaration
13345      (T             : Entity_Id;
13346       N             : Node_Id;
13347       Is_Completion : Boolean)
13348    is
13349       Parent_Type  : Entity_Id;
13350
13351       function Comes_From_Generic (Typ : Entity_Id) return Boolean;
13352       --  Check whether the parent type is a generic formal, or derives
13353       --  directly or indirectly from one.
13354
13355       ------------------------
13356       -- Comes_From_Generic --
13357       ------------------------
13358
13359       function Comes_From_Generic (Typ : Entity_Id) return Boolean is
13360       begin
13361          if Is_Generic_Type (Typ) then
13362             return True;
13363
13364          elsif Is_Generic_Type (Root_Type (Parent_Type)) then
13365             return True;
13366
13367          elsif Is_Private_Type (Typ)
13368            and then Present (Full_View (Typ))
13369            and then Is_Generic_Type (Root_Type (Full_View (Typ)))
13370          then
13371             return True;
13372
13373          elsif Is_Generic_Actual_Type (Typ) then
13374             return True;
13375
13376          else
13377             return False;
13378          end if;
13379       end Comes_From_Generic;
13380
13381       --  Local variables
13382
13383       Def          : constant Node_Id := Type_Definition (N);
13384       Iface_Def    : Node_Id;
13385       Indic        : constant Node_Id := Subtype_Indication (Def);
13386       Extension    : constant Node_Id := Record_Extension_Part (Def);
13387       Parent_Node  : Node_Id;
13388       Parent_Scope : Entity_Id;
13389       Taggd        : Boolean;
13390
13391    --  Start of processing for Derived_Type_Declaration
13392
13393    begin
13394       Parent_Type := Find_Type_Of_Subtype_Indic (Indic);
13395
13396       --  Ada 2005 (AI-251): In case of interface derivation check that the
13397       --  parent is also an interface.
13398
13399       if Interface_Present (Def) then
13400          if not Is_Interface (Parent_Type) then
13401             Diagnose_Interface (Indic, Parent_Type);
13402
13403          else
13404             Parent_Node := Parent (Base_Type (Parent_Type));
13405             Iface_Def   := Type_Definition (Parent_Node);
13406
13407             --  Ada 2005 (AI-251): Limited interfaces can only inherit from
13408             --  other limited interfaces.
13409
13410             if Limited_Present (Def) then
13411                if Limited_Present (Iface_Def) then
13412                   null;
13413
13414                elsif Protected_Present (Iface_Def) then
13415                   Error_Msg_NE
13416                     ("descendant of& must be declared"
13417                        & " as a protected interface",
13418                          N, Parent_Type);
13419
13420                elsif Synchronized_Present (Iface_Def) then
13421                   Error_Msg_NE
13422                     ("descendant of& must be declared"
13423                        & " as a synchronized interface",
13424                          N, Parent_Type);
13425
13426                elsif Task_Present (Iface_Def) then
13427                   Error_Msg_NE
13428                     ("descendant of& must be declared as a task interface",
13429                        N, Parent_Type);
13430
13431                else
13432                   Error_Msg_N
13433                     ("(Ada 2005) limited interface cannot "
13434                      & "inherit from non-limited interface", Indic);
13435                end if;
13436
13437             --  Ada 2005 (AI-345): Non-limited interfaces can only inherit
13438             --  from non-limited or limited interfaces.
13439
13440             elsif not Protected_Present (Def)
13441               and then not Synchronized_Present (Def)
13442               and then not Task_Present (Def)
13443             then
13444                if Limited_Present (Iface_Def) then
13445                   null;
13446
13447                elsif Protected_Present (Iface_Def) then
13448                   Error_Msg_NE
13449                     ("descendant of& must be declared"
13450                        & " as a protected interface",
13451                          N, Parent_Type);
13452
13453                elsif Synchronized_Present (Iface_Def) then
13454                   Error_Msg_NE
13455                     ("descendant of& must be declared"
13456                        & " as a synchronized interface",
13457                          N, Parent_Type);
13458
13459                elsif Task_Present (Iface_Def) then
13460                   Error_Msg_NE
13461                     ("descendant of& must be declared as a task interface",
13462                        N, Parent_Type);
13463                else
13464                   null;
13465                end if;
13466             end if;
13467          end if;
13468       end if;
13469
13470       if Is_Tagged_Type (Parent_Type)
13471         and then Is_Concurrent_Type (Parent_Type)
13472         and then not Is_Interface (Parent_Type)
13473       then
13474          Error_Msg_N
13475            ("parent type of a record extension cannot be "
13476             & "a synchronized tagged type (RM 3.9.1 (3/1))", N);
13477          Set_Etype (T, Any_Type);
13478          return;
13479       end if;
13480
13481       --  Ada 2005 (AI-251): Decorate all the names in the list of ancestor
13482       --  interfaces
13483
13484       if Is_Tagged_Type (Parent_Type)
13485         and then Is_Non_Empty_List (Interface_List (Def))
13486       then
13487          declare
13488             Intf : Node_Id;
13489             T    : Entity_Id;
13490
13491          begin
13492             Intf := First (Interface_List (Def));
13493             while Present (Intf) loop
13494                T := Find_Type_Of_Subtype_Indic (Intf);
13495
13496                if not Is_Interface (T) then
13497                   Diagnose_Interface (Intf, T);
13498
13499                --  Check the rules of 3.9.4(12/2) and 7.5(2/2) that disallow
13500                --  a limited type from having a nonlimited progenitor.
13501
13502                elsif (Limited_Present (Def)
13503                        or else (not Is_Interface (Parent_Type)
13504                                  and then Is_Limited_Type (Parent_Type)))
13505                  and then not Is_Limited_Interface (T)
13506                then
13507                   Error_Msg_NE
13508                    ("progenitor interface& of limited type must be limited",
13509                      N, T);
13510                end if;
13511
13512                Next (Intf);
13513             end loop;
13514          end;
13515       end if;
13516
13517       if Parent_Type = Any_Type
13518         or else Etype (Parent_Type) = Any_Type
13519         or else (Is_Class_Wide_Type (Parent_Type)
13520                    and then Etype (Parent_Type) = T)
13521       then
13522          --  If Parent_Type is undefined or illegal, make new type into a
13523          --  subtype of Any_Type, and set a few attributes to prevent cascaded
13524          --  errors. If this is a self-definition, emit error now.
13525
13526          if T = Parent_Type
13527            or else T = Etype (Parent_Type)
13528          then
13529             Error_Msg_N ("type cannot be used in its own definition", Indic);
13530          end if;
13531
13532          Set_Ekind        (T, Ekind (Parent_Type));
13533          Set_Etype        (T, Any_Type);
13534          Set_Scalar_Range (T, Scalar_Range (Any_Type));
13535
13536          if Is_Tagged_Type (T)
13537            and then Is_Record_Type (T)
13538          then
13539             Set_Direct_Primitive_Operations (T, New_Elmt_List);
13540          end if;
13541
13542          return;
13543       end if;
13544
13545       --  Ada 2005 (AI-251): The case in which the parent of the full-view is
13546       --  an interface is special because the list of interfaces in the full
13547       --  view can be given in any order. For example:
13548
13549       --     type A is interface;
13550       --     type B is interface and A;
13551       --     type D is new B with private;
13552       --   private
13553       --     type D is new A and B with null record; -- 1 --
13554
13555       --  In this case we perform the following transformation of -1-:
13556
13557       --     type D is new B and A with null record;
13558
13559       --  If the parent of the full-view covers the parent of the partial-view
13560       --  we have two possible cases:
13561
13562       --     1) They have the same parent
13563       --     2) The parent of the full-view implements some further interfaces
13564
13565       --  In both cases we do not need to perform the transformation. In the
13566       --  first case the source program is correct and the transformation is
13567       --  not needed; in the second case the source program does not fulfill
13568       --  the no-hidden interfaces rule (AI-396) and the error will be reported
13569       --  later.
13570
13571       --  This transformation not only simplifies the rest of the analysis of
13572       --  this type declaration but also simplifies the correct generation of
13573       --  the object layout to the expander.
13574
13575       if In_Private_Part (Current_Scope)
13576         and then Is_Interface (Parent_Type)
13577       then
13578          declare
13579             Iface               : Node_Id;
13580             Partial_View        : Entity_Id;
13581             Partial_View_Parent : Entity_Id;
13582             New_Iface           : Node_Id;
13583
13584          begin
13585             --  Look for the associated private type declaration
13586
13587             Partial_View := First_Entity (Current_Scope);
13588             loop
13589                exit when No (Partial_View)
13590                  or else (Has_Private_Declaration (Partial_View)
13591                            and then Full_View (Partial_View) = T);
13592
13593                Next_Entity (Partial_View);
13594             end loop;
13595
13596             --  If the partial view was not found then the source code has
13597             --  errors and the transformation is not needed.
13598
13599             if Present (Partial_View) then
13600                Partial_View_Parent := Etype (Partial_View);
13601
13602                --  If the parent of the full-view covers the parent of the
13603                --  partial-view we have nothing else to do.
13604
13605                if Interface_Present_In_Ancestor
13606                     (Parent_Type, Partial_View_Parent)
13607                then
13608                   null;
13609
13610                --  Traverse the list of interfaces of the full-view to look
13611                --  for the parent of the partial-view and perform the tree
13612                --  transformation.
13613
13614                else
13615                   Iface := First (Interface_List (Def));
13616                   while Present (Iface) loop
13617                      if Etype (Iface) = Etype (Partial_View) then
13618                         Rewrite (Subtype_Indication (Def),
13619                           New_Copy (Subtype_Indication
13620                                      (Parent (Partial_View))));
13621
13622                         New_Iface := Make_Identifier (Sloc (N),
13623                                        Chars (Parent_Type));
13624                         Append (New_Iface, Interface_List (Def));
13625
13626                         --  Analyze the transformed code
13627
13628                         Derived_Type_Declaration (T, N, Is_Completion);
13629                         return;
13630                      end if;
13631
13632                      Next (Iface);
13633                   end loop;
13634                end if;
13635             end if;
13636          end;
13637       end if;
13638
13639       --  Only composite types other than array types are allowed to have
13640       --  discriminants.
13641
13642       if Present (Discriminant_Specifications (N))
13643         and then (Is_Elementary_Type (Parent_Type)
13644                   or else Is_Array_Type (Parent_Type))
13645         and then not Error_Posted (N)
13646       then
13647          Error_Msg_N
13648            ("elementary or array type cannot have discriminants",
13649             Defining_Identifier (First (Discriminant_Specifications (N))));
13650          Set_Has_Discriminants (T, False);
13651       end if;
13652
13653       --  In Ada 83, a derived type defined in a package specification cannot
13654       --  be used for further derivation until the end of its visible part.
13655       --  Note that derivation in the private part of the package is allowed.
13656
13657       if Ada_Version = Ada_83
13658         and then Is_Derived_Type (Parent_Type)
13659         and then In_Visible_Part (Scope (Parent_Type))
13660       then
13661          if Ada_Version = Ada_83 and then Comes_From_Source (Indic) then
13662             Error_Msg_N
13663               ("(Ada 83): premature use of type for derivation", Indic);
13664          end if;
13665       end if;
13666
13667       --  Check for early use of incomplete or private type
13668
13669       if Ekind_In (Parent_Type, E_Void, E_Incomplete_Type) then
13670          Error_Msg_N ("premature derivation of incomplete type", Indic);
13671          return;
13672
13673       elsif (Is_Incomplete_Or_Private_Type (Parent_Type)
13674               and then not Comes_From_Generic (Parent_Type))
13675         or else Has_Private_Component (Parent_Type)
13676       then
13677          --  The ancestor type of a formal type can be incomplete, in which
13678          --  case only the operations of the partial view are available in
13679          --  the generic. Subsequent checks may be required when the full
13680          --  view is analyzed, to verify that derivation from a tagged type
13681          --  has an extension.
13682
13683          if Nkind (Original_Node (N)) = N_Formal_Type_Declaration then
13684             null;
13685
13686          elsif No (Underlying_Type (Parent_Type))
13687            or else Has_Private_Component (Parent_Type)
13688          then
13689             Error_Msg_N
13690               ("premature derivation of derived or private type", Indic);
13691
13692             --  Flag the type itself as being in error, this prevents some
13693             --  nasty problems with subsequent uses of the malformed type.
13694
13695             Set_Error_Posted (T);
13696
13697          --  Check that within the immediate scope of an untagged partial
13698          --  view it's illegal to derive from the partial view if the
13699          --  full view is tagged. (7.3(7))
13700
13701          --  We verify that the Parent_Type is a partial view by checking
13702          --  that it is not a Full_Type_Declaration (i.e. a private type or
13703          --  private extension declaration), to distinguish a partial view
13704          --  from  a derivation from a private type which also appears as
13705          --  E_Private_Type.
13706
13707          elsif Present (Full_View (Parent_Type))
13708            and then Nkind (Parent (Parent_Type)) /= N_Full_Type_Declaration
13709            and then not Is_Tagged_Type (Parent_Type)
13710            and then Is_Tagged_Type (Full_View (Parent_Type))
13711          then
13712             Parent_Scope := Scope (T);
13713             while Present (Parent_Scope)
13714               and then Parent_Scope /= Standard_Standard
13715             loop
13716                if Parent_Scope = Scope (Parent_Type) then
13717                   Error_Msg_N
13718                     ("premature derivation from type with tagged full view",
13719                      Indic);
13720                end if;
13721
13722                Parent_Scope := Scope (Parent_Scope);
13723             end loop;
13724          end if;
13725       end if;
13726
13727       --  Check that form of derivation is appropriate
13728
13729       Taggd := Is_Tagged_Type (Parent_Type);
13730
13731       --  Perhaps the parent type should be changed to the class-wide type's
13732       --  specific type in this case to prevent cascading errors ???
13733
13734       if Present (Extension) and then Is_Class_Wide_Type (Parent_Type) then
13735          Error_Msg_N ("parent type must not be a class-wide type", Indic);
13736          return;
13737       end if;
13738
13739       if Present (Extension) and then not Taggd then
13740          Error_Msg_N
13741            ("type derived from untagged type cannot have extension", Indic);
13742
13743       elsif No (Extension) and then Taggd then
13744
13745          --  If this declaration is within a private part (or body) of a
13746          --  generic instantiation then the derivation is allowed (the parent
13747          --  type can only appear tagged in this case if it's a generic actual
13748          --  type, since it would otherwise have been rejected in the analysis
13749          --  of the generic template).
13750
13751          if not Is_Generic_Actual_Type (Parent_Type)
13752            or else In_Visible_Part (Scope (Parent_Type))
13753          then
13754             if Is_Class_Wide_Type (Parent_Type) then
13755                Error_Msg_N
13756                  ("parent type must not be a class-wide type", Indic);
13757
13758                --  Use specific type to prevent cascaded errors.
13759
13760                Parent_Type := Etype (Parent_Type);
13761
13762             else
13763                Error_Msg_N
13764                  ("type derived from tagged type must have extension", Indic);
13765             end if;
13766          end if;
13767       end if;
13768
13769       --  AI-443: Synchronized formal derived types require a private
13770       --  extension. There is no point in checking the ancestor type or
13771       --  the progenitors since the construct is wrong to begin with.
13772
13773       if Ada_Version >= Ada_2005
13774         and then Is_Generic_Type (T)
13775         and then Present (Original_Node (N))
13776       then
13777          declare
13778             Decl : constant Node_Id := Original_Node (N);
13779
13780          begin
13781             if Nkind (Decl) = N_Formal_Type_Declaration
13782               and then Nkind (Formal_Type_Definition (Decl)) =
13783                          N_Formal_Derived_Type_Definition
13784               and then Synchronized_Present (Formal_Type_Definition (Decl))
13785               and then No (Extension)
13786
13787                --  Avoid emitting a duplicate error message
13788
13789               and then not Error_Posted (Indic)
13790             then
13791                Error_Msg_N
13792                  ("synchronized derived type must have extension", N);
13793             end if;
13794          end;
13795       end if;
13796
13797       if Null_Exclusion_Present (Def)
13798         and then not Is_Access_Type (Parent_Type)
13799       then
13800          Error_Msg_N ("null exclusion can only apply to an access type", N);
13801       end if;
13802
13803       --  Avoid deriving parent primitives of underlying record views
13804
13805       Build_Derived_Type (N, Parent_Type, T, Is_Completion,
13806         Derive_Subps => not Is_Underlying_Record_View (T));
13807
13808       --  AI-419: The parent type of an explicitly limited derived type must
13809       --  be a limited type or a limited interface.
13810
13811       if Limited_Present (Def) then
13812          Set_Is_Limited_Record (T);
13813
13814          if Is_Interface (T) then
13815             Set_Is_Limited_Interface (T);
13816          end if;
13817
13818          if not Is_Limited_Type (Parent_Type)
13819            and then
13820              (not Is_Interface (Parent_Type)
13821                or else not Is_Limited_Interface (Parent_Type))
13822          then
13823             --  AI05-0096: a derivation in the private part of an instance is
13824             --  legal if the generic formal is untagged limited, and the actual
13825             --  is non-limited.
13826
13827             if Is_Generic_Actual_Type (Parent_Type)
13828               and then In_Private_Part (Current_Scope)
13829               and then
13830                 not Is_Tagged_Type
13831                       (Generic_Parent_Type (Parent (Parent_Type)))
13832             then
13833                null;
13834
13835             else
13836                Error_Msg_NE
13837                  ("parent type& of limited type must be limited",
13838                   N, Parent_Type);
13839             end if;
13840          end if;
13841       end if;
13842    end Derived_Type_Declaration;
13843
13844    ------------------------
13845    -- Diagnose_Interface --
13846    ------------------------
13847
13848    procedure Diagnose_Interface (N : Node_Id;  E : Entity_Id) is
13849    begin
13850       if not Is_Interface (E)
13851         and then  E /= Any_Type
13852       then
13853          Error_Msg_NE ("(Ada 2005) & must be an interface", N, E);
13854       end if;
13855    end Diagnose_Interface;
13856
13857    ----------------------------------
13858    -- Enumeration_Type_Declaration --
13859    ----------------------------------
13860
13861    procedure Enumeration_Type_Declaration (T : Entity_Id; Def : Node_Id) is
13862       Ev     : Uint;
13863       L      : Node_Id;
13864       R_Node : Node_Id;
13865       B_Node : Node_Id;
13866
13867    begin
13868       --  Create identifier node representing lower bound
13869
13870       B_Node := New_Node (N_Identifier, Sloc (Def));
13871       L := First (Literals (Def));
13872       Set_Chars (B_Node, Chars (L));
13873       Set_Entity (B_Node,  L);
13874       Set_Etype (B_Node, T);
13875       Set_Is_Static_Expression (B_Node, True);
13876
13877       R_Node := New_Node (N_Range, Sloc (Def));
13878       Set_Low_Bound  (R_Node, B_Node);
13879
13880       Set_Ekind (T, E_Enumeration_Type);
13881       Set_First_Literal (T, L);
13882       Set_Etype (T, T);
13883       Set_Is_Constrained (T);
13884
13885       Ev := Uint_0;
13886
13887       --  Loop through literals of enumeration type setting pos and rep values
13888       --  except that if the Ekind is already set, then it means the literal
13889       --  was already constructed (case of a derived type declaration and we
13890       --  should not disturb the Pos and Rep values.
13891
13892       while Present (L) loop
13893          if Ekind (L) /= E_Enumeration_Literal then
13894             Set_Ekind (L, E_Enumeration_Literal);
13895             Set_Enumeration_Pos (L, Ev);
13896             Set_Enumeration_Rep (L, Ev);
13897             Set_Is_Known_Valid  (L, True);
13898          end if;
13899
13900          Set_Etype (L, T);
13901          New_Overloaded_Entity (L);
13902          Generate_Definition (L);
13903          Set_Convention (L, Convention_Intrinsic);
13904
13905          --  Case of character literal
13906
13907          if Nkind (L) = N_Defining_Character_Literal then
13908             Set_Is_Character_Type (T, True);
13909
13910             --  Check violation of No_Wide_Characters
13911
13912             if Restriction_Check_Required (No_Wide_Characters) then
13913                Get_Name_String (Chars (L));
13914
13915                if Name_Len >= 3 and then Name_Buffer (1 .. 2) = "QW" then
13916                   Check_Restriction (No_Wide_Characters, L);
13917                end if;
13918             end if;
13919          end if;
13920
13921          Ev := Ev + 1;
13922          Next (L);
13923       end loop;
13924
13925       --  Now create a node representing upper bound
13926
13927       B_Node := New_Node (N_Identifier, Sloc (Def));
13928       Set_Chars (B_Node, Chars (Last (Literals (Def))));
13929       Set_Entity (B_Node,  Last (Literals (Def)));
13930       Set_Etype (B_Node, T);
13931       Set_Is_Static_Expression (B_Node, True);
13932
13933       Set_High_Bound (R_Node, B_Node);
13934
13935       --  Initialize various fields of the type. Some of this information
13936       --  may be overwritten later through rep.clauses.
13937
13938       Set_Scalar_Range    (T, R_Node);
13939       Set_RM_Size         (T, UI_From_Int (Minimum_Size (T)));
13940       Set_Enum_Esize      (T);
13941       Set_Enum_Pos_To_Rep (T, Empty);
13942
13943       --  Set Discard_Names if configuration pragma set, or if there is
13944       --  a parameterless pragma in the current declarative region
13945
13946       if Global_Discard_Names
13947         or else Discard_Names (Scope (T))
13948       then
13949          Set_Discard_Names (T);
13950       end if;
13951
13952       --  Process end label if there is one
13953
13954       if Present (Def) then
13955          Process_End_Label (Def, 'e', T);
13956       end if;
13957    end Enumeration_Type_Declaration;
13958
13959    ---------------------------------
13960    -- Expand_To_Stored_Constraint --
13961    ---------------------------------
13962
13963    function Expand_To_Stored_Constraint
13964      (Typ        : Entity_Id;
13965       Constraint : Elist_Id) return Elist_Id
13966    is
13967       Explicitly_Discriminated_Type : Entity_Id;
13968       Expansion    : Elist_Id;
13969       Discriminant : Entity_Id;
13970
13971       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id;
13972       --  Find the nearest type that actually specifies discriminants
13973
13974       ---------------------------------
13975       -- Type_With_Explicit_Discrims --
13976       ---------------------------------
13977
13978       function Type_With_Explicit_Discrims (Id : Entity_Id) return Entity_Id is
13979          Typ : constant E := Base_Type (Id);
13980
13981       begin
13982          if Ekind (Typ) in Incomplete_Or_Private_Kind then
13983             if Present (Full_View (Typ)) then
13984                return Type_With_Explicit_Discrims (Full_View (Typ));
13985             end if;
13986
13987          else
13988             if Has_Discriminants (Typ) then
13989                return Typ;
13990             end if;
13991          end if;
13992
13993          if Etype (Typ) = Typ then
13994             return Empty;
13995          elsif Has_Discriminants (Typ) then
13996             return Typ;
13997          else
13998             return Type_With_Explicit_Discrims (Etype (Typ));
13999          end if;
14000
14001       end Type_With_Explicit_Discrims;
14002
14003    --  Start of processing for Expand_To_Stored_Constraint
14004
14005    begin
14006       if No (Constraint)
14007         or else Is_Empty_Elmt_List (Constraint)
14008       then
14009          return No_Elist;
14010       end if;
14011
14012       Explicitly_Discriminated_Type := Type_With_Explicit_Discrims (Typ);
14013
14014       if No (Explicitly_Discriminated_Type) then
14015          return No_Elist;
14016       end if;
14017
14018       Expansion := New_Elmt_List;
14019
14020       Discriminant :=
14021          First_Stored_Discriminant (Explicitly_Discriminated_Type);
14022       while Present (Discriminant) loop
14023          Append_Elmt (
14024            Get_Discriminant_Value (
14025              Discriminant, Explicitly_Discriminated_Type, Constraint),
14026            Expansion);
14027          Next_Stored_Discriminant (Discriminant);
14028       end loop;
14029
14030       return Expansion;
14031    end Expand_To_Stored_Constraint;
14032
14033    ---------------------------
14034    -- Find_Hidden_Interface --
14035    ---------------------------
14036
14037    function Find_Hidden_Interface
14038      (Src  : Elist_Id;
14039       Dest : Elist_Id) return Entity_Id
14040    is
14041       Iface      : Entity_Id;
14042       Iface_Elmt : Elmt_Id;
14043
14044    begin
14045       if Present (Src) and then Present (Dest) then
14046          Iface_Elmt := First_Elmt (Src);
14047          while Present (Iface_Elmt) loop
14048             Iface := Node (Iface_Elmt);
14049
14050             if Is_Interface (Iface)
14051               and then not Contain_Interface (Iface, Dest)
14052             then
14053                return Iface;
14054             end if;
14055
14056             Next_Elmt (Iface_Elmt);
14057          end loop;
14058       end if;
14059
14060       return Empty;
14061    end Find_Hidden_Interface;
14062
14063    --------------------
14064    -- Find_Type_Name --
14065    --------------------
14066
14067    function Find_Type_Name (N : Node_Id) return Entity_Id is
14068       Id       : constant Entity_Id := Defining_Identifier (N);
14069       Prev     : Entity_Id;
14070       New_Id   : Entity_Id;
14071       Prev_Par : Node_Id;
14072
14073       procedure Tag_Mismatch;
14074       --  Diagnose a tagged partial view whose full view is untagged.
14075       --  We post the message on the full view, with a reference to
14076       --  the previous partial view. The partial view can be private
14077       --  or incomplete, and these are handled in a different manner,
14078       --  so we determine the position of the error message from the
14079       --  respective slocs of both.
14080
14081       ------------------
14082       -- Tag_Mismatch --
14083       ------------------
14084
14085       procedure Tag_Mismatch is
14086       begin
14087          if Sloc (Prev) < Sloc (Id) then
14088             Error_Msg_NE
14089               ("full declaration of } must be a tagged type ", Id, Prev);
14090          else
14091             Error_Msg_NE
14092               ("full declaration of } must be a tagged type ", Prev, Id);
14093          end if;
14094       end Tag_Mismatch;
14095
14096    --  Start of processing for Find_Type_Name
14097
14098    begin
14099       --  Find incomplete declaration, if one was given
14100
14101       Prev := Current_Entity_In_Scope (Id);
14102
14103       if Present (Prev) then
14104
14105          --  Previous declaration exists. Error if not incomplete/private case
14106          --  except if previous declaration is implicit, etc. Enter_Name will
14107          --  emit error if appropriate.
14108
14109          Prev_Par := Parent (Prev);
14110
14111          if not Is_Incomplete_Or_Private_Type (Prev) then
14112             Enter_Name (Id);
14113             New_Id := Id;
14114
14115          elsif not Nkind_In (N, N_Full_Type_Declaration,
14116                                 N_Task_Type_Declaration,
14117                                 N_Protected_Type_Declaration)
14118          then
14119             --  Completion must be a full type declarations (RM 7.3(4))
14120
14121             Error_Msg_Sloc := Sloc (Prev);
14122             Error_Msg_NE ("invalid completion of }", Id, Prev);
14123
14124             --  Set scope of Id to avoid cascaded errors. Entity is never
14125             --  examined again, except when saving globals in generics.
14126
14127             Set_Scope (Id, Current_Scope);
14128             New_Id := Id;
14129
14130             --  If this is a repeated incomplete declaration, no further
14131             --  checks are possible.
14132
14133             if Nkind (N) = N_Incomplete_Type_Declaration then
14134                return Prev;
14135             end if;
14136
14137          --  Case of full declaration of incomplete type
14138
14139          elsif Ekind (Prev) = E_Incomplete_Type then
14140
14141             --  Indicate that the incomplete declaration has a matching full
14142             --  declaration. The defining occurrence of the incomplete
14143             --  declaration remains the visible one, and the procedure
14144             --  Get_Full_View dereferences it whenever the type is used.
14145
14146             if Present (Full_View (Prev)) then
14147                Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14148             end if;
14149
14150             Set_Full_View (Prev,  Id);
14151             Append_Entity (Id, Current_Scope);
14152             Set_Is_Public (Id, Is_Public (Prev));
14153             Set_Is_Internal (Id);
14154             New_Id := Prev;
14155
14156          --  Case of full declaration of private type
14157
14158          else
14159             if Nkind (Parent (Prev)) /= N_Private_Extension_Declaration then
14160                if Etype (Prev) /= Prev then
14161
14162                   --  Prev is a private subtype or a derived type, and needs
14163                   --  no completion.
14164
14165                   Error_Msg_NE ("invalid redeclaration of }", Id, Prev);
14166                   New_Id := Id;
14167
14168                elsif Ekind (Prev) = E_Private_Type
14169                  and then Nkind_In (N, N_Task_Type_Declaration,
14170                                        N_Protected_Type_Declaration)
14171                then
14172                   Error_Msg_N
14173                    ("completion of nonlimited type cannot be limited", N);
14174
14175                elsif Ekind (Prev) = E_Record_Type_With_Private
14176                  and then Nkind_In (N, N_Task_Type_Declaration,
14177                                        N_Protected_Type_Declaration)
14178                then
14179                   if not Is_Limited_Record (Prev) then
14180                      Error_Msg_N
14181                         ("completion of nonlimited type cannot be limited", N);
14182
14183                   elsif No (Interface_List (N)) then
14184                      Error_Msg_N
14185                         ("completion of tagged private type must be tagged",
14186                          N);
14187                   end if;
14188
14189                elsif Nkind (N) = N_Full_Type_Declaration
14190                  and then
14191                    Nkind (Type_Definition (N)) = N_Record_Definition
14192                  and then Interface_Present (Type_Definition (N))
14193                then
14194                   Error_Msg_N
14195                     ("completion of private type cannot be an interface", N);
14196                end if;
14197
14198             --  Ada 2005 (AI-251): Private extension declaration of a task
14199             --  type or a protected type. This case arises when covering
14200             --  interface types.
14201
14202             elsif Nkind_In (N, N_Task_Type_Declaration,
14203                                N_Protected_Type_Declaration)
14204             then
14205                null;
14206
14207             elsif Nkind (N) /= N_Full_Type_Declaration
14208               or else Nkind (Type_Definition (N)) /= N_Derived_Type_Definition
14209             then
14210                Error_Msg_N
14211                  ("full view of private extension must be an extension", N);
14212
14213             elsif not (Abstract_Present (Parent (Prev)))
14214               and then Abstract_Present (Type_Definition (N))
14215             then
14216                Error_Msg_N
14217                  ("full view of non-abstract extension cannot be abstract", N);
14218             end if;
14219
14220             if not In_Private_Part (Current_Scope) then
14221                Error_Msg_N
14222                  ("declaration of full view must appear in private part", N);
14223             end if;
14224
14225             Copy_And_Swap (Prev, Id);
14226             Set_Has_Private_Declaration (Prev);
14227             Set_Has_Private_Declaration (Id);
14228
14229             --  If no error, propagate freeze_node from private to full view.
14230             --  It may have been generated for an early operational item.
14231
14232             if Present (Freeze_Node (Id))
14233               and then Serious_Errors_Detected = 0
14234               and then No (Full_View (Id))
14235             then
14236                Set_Freeze_Node (Prev, Freeze_Node (Id));
14237                Set_Freeze_Node (Id, Empty);
14238                Set_First_Rep_Item (Prev, First_Rep_Item (Id));
14239             end if;
14240
14241             Set_Full_View (Id, Prev);
14242             New_Id := Prev;
14243          end if;
14244
14245          --  Verify that full declaration conforms to partial one
14246
14247          if Is_Incomplete_Or_Private_Type (Prev)
14248            and then Present (Discriminant_Specifications (Prev_Par))
14249          then
14250             if Present (Discriminant_Specifications (N)) then
14251                if Ekind (Prev) = E_Incomplete_Type then
14252                   Check_Discriminant_Conformance (N, Prev, Prev);
14253                else
14254                   Check_Discriminant_Conformance (N, Prev, Id);
14255                end if;
14256
14257             else
14258                Error_Msg_N
14259                  ("missing discriminants in full type declaration", N);
14260
14261                --  To avoid cascaded errors on subsequent use, share the
14262                --  discriminants of the partial view.
14263
14264                Set_Discriminant_Specifications (N,
14265                  Discriminant_Specifications (Prev_Par));
14266             end if;
14267          end if;
14268
14269          --  A prior untagged partial view can have an associated class-wide
14270          --  type due to use of the class attribute, and in this case the full
14271          --  type must also be tagged. This Ada 95 usage is deprecated in favor
14272          --  of incomplete tagged declarations, but we check for it.
14273
14274          if Is_Type (Prev)
14275            and then (Is_Tagged_Type (Prev)
14276                       or else Present (Class_Wide_Type (Prev)))
14277          then
14278             --  The full declaration is either a tagged type (including
14279             --  a synchronized type that implements interfaces) or a
14280             --  type extension, otherwise this is an error.
14281
14282             if Nkind_In (N, N_Task_Type_Declaration,
14283                             N_Protected_Type_Declaration)
14284             then
14285                if No (Interface_List (N))
14286                  and then not Error_Posted (N)
14287                then
14288                   Tag_Mismatch;
14289                end if;
14290
14291             elsif Nkind (Type_Definition (N)) = N_Record_Definition then
14292
14293                --  Indicate that the previous declaration (tagged incomplete
14294                --  or private declaration) requires the same on the full one.
14295
14296                if not Tagged_Present (Type_Definition (N)) then
14297                   Tag_Mismatch;
14298                   Set_Is_Tagged_Type (Id);
14299                end if;
14300
14301             elsif Nkind (Type_Definition (N)) = N_Derived_Type_Definition then
14302                if No (Record_Extension_Part (Type_Definition (N))) then
14303                   Error_Msg_NE
14304                     ("full declaration of } must be a record extension",
14305                      Prev, Id);
14306
14307                   --  Set some attributes to produce a usable full view
14308
14309                   Set_Is_Tagged_Type (Id);
14310                end if;
14311
14312             else
14313                Tag_Mismatch;
14314             end if;
14315          end if;
14316
14317          return New_Id;
14318
14319       else
14320          --  New type declaration
14321
14322          Enter_Name (Id);
14323          return Id;
14324       end if;
14325    end Find_Type_Name;
14326
14327    -------------------------
14328    -- Find_Type_Of_Object --
14329    -------------------------
14330
14331    function Find_Type_Of_Object
14332      (Obj_Def     : Node_Id;
14333       Related_Nod : Node_Id) return Entity_Id
14334    is
14335       Def_Kind : constant Node_Kind := Nkind (Obj_Def);
14336       P        : Node_Id := Parent (Obj_Def);
14337       T        : Entity_Id;
14338       Nam      : Name_Id;
14339
14340    begin
14341       --  If the parent is a component_definition node we climb to the
14342       --  component_declaration node
14343
14344       if Nkind (P) = N_Component_Definition then
14345          P := Parent (P);
14346       end if;
14347
14348       --  Case of an anonymous array subtype
14349
14350       if Nkind_In (Def_Kind, N_Constrained_Array_Definition,
14351                              N_Unconstrained_Array_Definition)
14352       then
14353          T := Empty;
14354          Array_Type_Declaration (T, Obj_Def);
14355
14356       --  Create an explicit subtype whenever possible
14357
14358       elsif Nkind (P) /= N_Component_Declaration
14359         and then Def_Kind = N_Subtype_Indication
14360       then
14361          --  Base name of subtype on object name, which will be unique in
14362          --  the current scope.
14363
14364          --  If this is a duplicate declaration, return base type, to avoid
14365          --  generating duplicate anonymous types.
14366
14367          if Error_Posted (P) then
14368             Analyze (Subtype_Mark (Obj_Def));
14369             return Entity (Subtype_Mark (Obj_Def));
14370          end if;
14371
14372          Nam :=
14373             New_External_Name
14374              (Chars (Defining_Identifier (Related_Nod)), 'S', 0, 'T');
14375
14376          T := Make_Defining_Identifier (Sloc (P), Nam);
14377
14378          Insert_Action (Obj_Def,
14379            Make_Subtype_Declaration (Sloc (P),
14380              Defining_Identifier => T,
14381              Subtype_Indication  => Relocate_Node (Obj_Def)));
14382
14383          --  This subtype may need freezing, and this will not be done
14384          --  automatically if the object declaration is not in declarative
14385          --  part. Since this is an object declaration, the type cannot always
14386          --  be frozen here. Deferred constants do not freeze their type
14387          --  (which often enough will be private).
14388
14389          if Nkind (P) = N_Object_Declaration
14390            and then Constant_Present (P)
14391            and then No (Expression (P))
14392          then
14393             null;
14394          else
14395             Insert_Actions (Obj_Def, Freeze_Entity (T, P));
14396          end if;
14397
14398       --  Ada 2005 AI-406: the object definition in an object declaration
14399       --  can be an access definition.
14400
14401       elsif Def_Kind = N_Access_Definition then
14402          T := Access_Definition (Related_Nod, Obj_Def);
14403          Set_Is_Local_Anonymous_Access (T);
14404
14405       --  Otherwise, the object definition is just a subtype_mark
14406
14407       else
14408          T := Process_Subtype (Obj_Def, Related_Nod);
14409       end if;
14410
14411       return T;
14412    end Find_Type_Of_Object;
14413
14414    --------------------------------
14415    -- Find_Type_Of_Subtype_Indic --
14416    --------------------------------
14417
14418    function Find_Type_Of_Subtype_Indic (S : Node_Id) return Entity_Id is
14419       Typ : Entity_Id;
14420
14421    begin
14422       --  Case of subtype mark with a constraint
14423
14424       if Nkind (S) = N_Subtype_Indication then
14425          Find_Type (Subtype_Mark (S));
14426          Typ := Entity (Subtype_Mark (S));
14427
14428          if not
14429            Is_Valid_Constraint_Kind (Ekind (Typ), Nkind (Constraint (S)))
14430          then
14431             Error_Msg_N
14432               ("incorrect constraint for this kind of type", Constraint (S));
14433             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
14434          end if;
14435
14436       --  Otherwise we have a subtype mark without a constraint
14437
14438       elsif Error_Posted (S) then
14439          Rewrite (S, New_Occurrence_Of (Any_Id, Sloc (S)));
14440          return Any_Type;
14441
14442       else
14443          Find_Type (S);
14444          Typ := Entity (S);
14445       end if;
14446
14447       --  Check No_Wide_Characters restriction
14448
14449       Check_Wide_Character_Restriction (Typ, S);
14450
14451       return Typ;
14452    end Find_Type_Of_Subtype_Indic;
14453
14454    -------------------------------------
14455    -- Floating_Point_Type_Declaration --
14456    -------------------------------------
14457
14458    procedure Floating_Point_Type_Declaration (T : Entity_Id; Def : Node_Id) is
14459       Digs          : constant Node_Id := Digits_Expression (Def);
14460       Digs_Val      : Uint;
14461       Base_Typ      : Entity_Id;
14462       Implicit_Base : Entity_Id;
14463       Bound         : Node_Id;
14464
14465       function Can_Derive_From (E : Entity_Id) return Boolean;
14466       --  Find if given digits value allows derivation from specified type
14467
14468       ---------------------
14469       -- Can_Derive_From --
14470       ---------------------
14471
14472       function Can_Derive_From (E : Entity_Id) return Boolean is
14473          Spec : constant Entity_Id := Real_Range_Specification (Def);
14474
14475       begin
14476          if Digs_Val > Digits_Value (E) then
14477             return False;
14478          end if;
14479
14480          if Present (Spec) then
14481             if Expr_Value_R (Type_Low_Bound (E)) >
14482                Expr_Value_R (Low_Bound (Spec))
14483             then
14484                return False;
14485             end if;
14486
14487             if Expr_Value_R (Type_High_Bound (E)) <
14488                Expr_Value_R (High_Bound (Spec))
14489             then
14490                return False;
14491             end if;
14492          end if;
14493
14494          return True;
14495       end Can_Derive_From;
14496
14497    --  Start of processing for Floating_Point_Type_Declaration
14498
14499    begin
14500       Check_Restriction (No_Floating_Point, Def);
14501
14502       --  Create an implicit base type
14503
14504       Implicit_Base :=
14505         Create_Itype (E_Floating_Point_Type, Parent (Def), T, 'B');
14506
14507       --  Analyze and verify digits value
14508
14509       Analyze_And_Resolve (Digs, Any_Integer);
14510       Check_Digits_Expression (Digs);
14511       Digs_Val := Expr_Value (Digs);
14512
14513       --  Process possible range spec and find correct type to derive from
14514
14515       Process_Real_Range_Specification (Def);
14516
14517       if Can_Derive_From (Standard_Short_Float) then
14518          Base_Typ := Standard_Short_Float;
14519       elsif Can_Derive_From (Standard_Float) then
14520          Base_Typ := Standard_Float;
14521       elsif Can_Derive_From (Standard_Long_Float) then
14522          Base_Typ := Standard_Long_Float;
14523       elsif Can_Derive_From (Standard_Long_Long_Float) then
14524          Base_Typ := Standard_Long_Long_Float;
14525
14526       --  If we can't derive from any existing type, use long_long_float
14527       --  and give appropriate message explaining the problem.
14528
14529       else
14530          Base_Typ := Standard_Long_Long_Float;
14531
14532          if Digs_Val >= Digits_Value (Standard_Long_Long_Float) then
14533             Error_Msg_Uint_1 := Digits_Value (Standard_Long_Long_Float);
14534             Error_Msg_N ("digits value out of range, maximum is ^", Digs);
14535
14536          else
14537             Error_Msg_N
14538               ("range too large for any predefined type",
14539                Real_Range_Specification (Def));
14540          end if;
14541       end if;
14542
14543       --  If there are bounds given in the declaration use them as the bounds
14544       --  of the type, otherwise use the bounds of the predefined base type
14545       --  that was chosen based on the Digits value.
14546
14547       if Present (Real_Range_Specification (Def)) then
14548          Set_Scalar_Range (T, Real_Range_Specification (Def));
14549          Set_Is_Constrained (T);
14550
14551          --  The bounds of this range must be converted to machine numbers
14552          --  in accordance with RM 4.9(38).
14553
14554          Bound := Type_Low_Bound (T);
14555
14556          if Nkind (Bound) = N_Real_Literal then
14557             Set_Realval
14558               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14559             Set_Is_Machine_Number (Bound);
14560          end if;
14561
14562          Bound := Type_High_Bound (T);
14563
14564          if Nkind (Bound) = N_Real_Literal then
14565             Set_Realval
14566               (Bound, Machine (Base_Typ, Realval (Bound), Round, Bound));
14567             Set_Is_Machine_Number (Bound);
14568          end if;
14569
14570       else
14571          Set_Scalar_Range (T, Scalar_Range (Base_Typ));
14572       end if;
14573
14574       --  Complete definition of implicit base and declared first subtype
14575
14576       Set_Etype          (Implicit_Base, Base_Typ);
14577
14578       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
14579       Set_Size_Info      (Implicit_Base,                (Base_Typ));
14580       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
14581       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
14582       Set_Digits_Value   (Implicit_Base, Digits_Value   (Base_Typ));
14583       Set_Vax_Float      (Implicit_Base, Vax_Float      (Base_Typ));
14584
14585       Set_Ekind          (T, E_Floating_Point_Subtype);
14586       Set_Etype          (T, Implicit_Base);
14587
14588       Set_Size_Info      (T,                (Implicit_Base));
14589       Set_RM_Size        (T, RM_Size        (Implicit_Base));
14590       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
14591       Set_Digits_Value   (T, Digs_Val);
14592    end Floating_Point_Type_Declaration;
14593
14594    ----------------------------
14595    -- Get_Discriminant_Value --
14596    ----------------------------
14597
14598    --  This is the situation:
14599
14600    --  There is a non-derived type
14601
14602    --       type T0 (Dx, Dy, Dz...)
14603
14604    --  There are zero or more levels of derivation, with each derivation
14605    --  either purely inheriting the discriminants, or defining its own.
14606
14607    --       type Ti      is new Ti-1
14608    --  or
14609    --       type Ti (Dw) is new Ti-1(Dw, 1, X+Y)
14610    --  or
14611    --       subtype Ti is ...
14612
14613    --  The subtype issue is avoided by the use of Original_Record_Component,
14614    --  and the fact that derived subtypes also derive the constraints.
14615
14616    --  This chain leads back from
14617
14618    --       Typ_For_Constraint
14619
14620    --  Typ_For_Constraint has discriminants, and the value for each
14621    --  discriminant is given by its corresponding Elmt of Constraints.
14622
14623    --  Discriminant is some discriminant in this hierarchy
14624
14625    --  We need to return its value
14626
14627    --  We do this by recursively searching each level, and looking for
14628    --  Discriminant. Once we get to the bottom, we start backing up
14629    --  returning the value for it which may in turn be a discriminant
14630    --  further up, so on the backup we continue the substitution.
14631
14632    function Get_Discriminant_Value
14633      (Discriminant       : Entity_Id;
14634       Typ_For_Constraint : Entity_Id;
14635       Constraint         : Elist_Id) return Node_Id
14636    is
14637       function Search_Derivation_Levels
14638         (Ti                    : Entity_Id;
14639          Discrim_Values        : Elist_Id;
14640          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id;
14641       --  This is the routine that performs the recursive search of levels
14642       --  as described above.
14643
14644       ------------------------------
14645       -- Search_Derivation_Levels --
14646       ------------------------------
14647
14648       function Search_Derivation_Levels
14649         (Ti                    : Entity_Id;
14650          Discrim_Values        : Elist_Id;
14651          Stored_Discrim_Values : Boolean) return Node_Or_Entity_Id
14652       is
14653          Assoc          : Elmt_Id;
14654          Disc           : Entity_Id;
14655          Result         : Node_Or_Entity_Id;
14656          Result_Entity  : Node_Id;
14657
14658       begin
14659          --  If inappropriate type, return Error, this happens only in
14660          --  cascaded error situations, and we want to avoid a blow up.
14661
14662          if not Is_Composite_Type (Ti) or else Is_Array_Type (Ti) then
14663             return Error;
14664          end if;
14665
14666          --  Look deeper if possible. Use Stored_Constraints only for
14667          --  untagged types. For tagged types use the given constraint.
14668          --  This asymmetry needs explanation???
14669
14670          if not Stored_Discrim_Values
14671            and then Present (Stored_Constraint (Ti))
14672            and then not Is_Tagged_Type (Ti)
14673          then
14674             Result :=
14675               Search_Derivation_Levels (Ti, Stored_Constraint (Ti), True);
14676          else
14677             declare
14678                Td : constant Entity_Id := Etype (Ti);
14679
14680             begin
14681                if Td = Ti then
14682                   Result := Discriminant;
14683
14684                else
14685                   if Present (Stored_Constraint (Ti)) then
14686                      Result :=
14687                         Search_Derivation_Levels
14688                           (Td, Stored_Constraint (Ti), True);
14689                   else
14690                      Result :=
14691                         Search_Derivation_Levels
14692                           (Td, Discrim_Values, Stored_Discrim_Values);
14693                   end if;
14694                end if;
14695             end;
14696          end if;
14697
14698          --  Extra underlying places to search, if not found above. For
14699          --  concurrent types, the relevant discriminant appears in the
14700          --  corresponding record. For a type derived from a private type
14701          --  without discriminant, the full view inherits the discriminants
14702          --  of the full view of the parent.
14703
14704          if Result = Discriminant then
14705             if Is_Concurrent_Type (Ti)
14706               and then Present (Corresponding_Record_Type (Ti))
14707             then
14708                Result :=
14709                  Search_Derivation_Levels (
14710                    Corresponding_Record_Type (Ti),
14711                    Discrim_Values,
14712                    Stored_Discrim_Values);
14713
14714             elsif Is_Private_Type (Ti)
14715               and then not Has_Discriminants (Ti)
14716               and then Present (Full_View (Ti))
14717               and then Etype (Full_View (Ti)) /= Ti
14718             then
14719                Result :=
14720                  Search_Derivation_Levels (
14721                    Full_View (Ti),
14722                    Discrim_Values,
14723                    Stored_Discrim_Values);
14724             end if;
14725          end if;
14726
14727          --  If Result is not a (reference to a) discriminant, return it,
14728          --  otherwise set Result_Entity to the discriminant.
14729
14730          if Nkind (Result) = N_Defining_Identifier then
14731             pragma Assert (Result = Discriminant);
14732             Result_Entity := Result;
14733
14734          else
14735             if not Denotes_Discriminant (Result) then
14736                return Result;
14737             end if;
14738
14739             Result_Entity := Entity (Result);
14740          end if;
14741
14742          --  See if this level of derivation actually has discriminants
14743          --  because tagged derivations can add them, hence the lower
14744          --  levels need not have any.
14745
14746          if not Has_Discriminants (Ti) then
14747             return Result;
14748          end if;
14749
14750          --  Scan Ti's discriminants for Result_Entity,
14751          --  and return its corresponding value, if any.
14752
14753          Result_Entity := Original_Record_Component (Result_Entity);
14754
14755          Assoc := First_Elmt (Discrim_Values);
14756
14757          if Stored_Discrim_Values then
14758             Disc := First_Stored_Discriminant (Ti);
14759          else
14760             Disc := First_Discriminant (Ti);
14761          end if;
14762
14763          while Present (Disc) loop
14764             pragma Assert (Present (Assoc));
14765
14766             if Original_Record_Component (Disc) = Result_Entity then
14767                return Node (Assoc);
14768             end if;
14769
14770             Next_Elmt (Assoc);
14771
14772             if Stored_Discrim_Values then
14773                Next_Stored_Discriminant (Disc);
14774             else
14775                Next_Discriminant (Disc);
14776             end if;
14777          end loop;
14778
14779          --  Could not find it
14780          --
14781          return Result;
14782       end Search_Derivation_Levels;
14783
14784       --  Local Variables
14785
14786       Result : Node_Or_Entity_Id;
14787
14788    --  Start of processing for Get_Discriminant_Value
14789
14790    begin
14791       --  ??? This routine is a gigantic mess and will be deleted. For the
14792       --  time being just test for the trivial case before calling recurse.
14793
14794       if Base_Type (Scope (Discriminant)) = Base_Type (Typ_For_Constraint) then
14795          declare
14796             D : Entity_Id;
14797             E : Elmt_Id;
14798
14799          begin
14800             D := First_Discriminant (Typ_For_Constraint);
14801             E := First_Elmt (Constraint);
14802             while Present (D) loop
14803                if Chars (D) = Chars (Discriminant) then
14804                   return Node (E);
14805                end if;
14806
14807                Next_Discriminant (D);
14808                Next_Elmt (E);
14809             end loop;
14810          end;
14811       end if;
14812
14813       Result := Search_Derivation_Levels
14814         (Typ_For_Constraint, Constraint, False);
14815
14816       --  ??? hack to disappear when this routine is gone
14817
14818       if  Nkind (Result) = N_Defining_Identifier then
14819          declare
14820             D : Entity_Id;
14821             E : Elmt_Id;
14822
14823          begin
14824             D := First_Discriminant (Typ_For_Constraint);
14825             E := First_Elmt (Constraint);
14826             while Present (D) loop
14827                if Corresponding_Discriminant (D) = Discriminant then
14828                   return Node (E);
14829                end if;
14830
14831                Next_Discriminant (D);
14832                Next_Elmt (E);
14833             end loop;
14834          end;
14835       end if;
14836
14837       pragma Assert (Nkind (Result) /= N_Defining_Identifier);
14838       return Result;
14839    end Get_Discriminant_Value;
14840
14841    --------------------------
14842    -- Has_Range_Constraint --
14843    --------------------------
14844
14845    function Has_Range_Constraint (N : Node_Id) return Boolean is
14846       C : constant Node_Id := Constraint (N);
14847
14848    begin
14849       if Nkind (C) = N_Range_Constraint then
14850          return True;
14851
14852       elsif Nkind (C) = N_Digits_Constraint then
14853          return
14854             Is_Decimal_Fixed_Point_Type (Entity (Subtype_Mark (N)))
14855               or else
14856             Present (Range_Constraint (C));
14857
14858       elsif Nkind (C) = N_Delta_Constraint then
14859          return Present (Range_Constraint (C));
14860
14861       else
14862          return False;
14863       end if;
14864    end Has_Range_Constraint;
14865
14866    ------------------------
14867    -- Inherit_Components --
14868    ------------------------
14869
14870    function Inherit_Components
14871      (N             : Node_Id;
14872       Parent_Base   : Entity_Id;
14873       Derived_Base  : Entity_Id;
14874       Is_Tagged     : Boolean;
14875       Inherit_Discr : Boolean;
14876       Discs         : Elist_Id) return Elist_Id
14877    is
14878       Assoc_List : constant Elist_Id := New_Elmt_List;
14879
14880       procedure Inherit_Component
14881         (Old_C          : Entity_Id;
14882          Plain_Discrim  : Boolean := False;
14883          Stored_Discrim : Boolean := False);
14884       --  Inherits component Old_C from Parent_Base to the Derived_Base. If
14885       --  Plain_Discrim is True, Old_C is a discriminant. If Stored_Discrim is
14886       --  True, Old_C is a stored discriminant. If they are both false then
14887       --  Old_C is a regular component.
14888
14889       -----------------------
14890       -- Inherit_Component --
14891       -----------------------
14892
14893       procedure Inherit_Component
14894         (Old_C          : Entity_Id;
14895          Plain_Discrim  : Boolean := False;
14896          Stored_Discrim : Boolean := False)
14897       is
14898          New_C : constant Entity_Id := New_Copy (Old_C);
14899
14900          Discrim      : Entity_Id;
14901          Corr_Discrim : Entity_Id;
14902
14903       begin
14904          pragma Assert (not Is_Tagged or else not Stored_Discrim);
14905
14906          Set_Parent (New_C, Parent (Old_C));
14907
14908          --  Regular discriminants and components must be inserted in the scope
14909          --  of the Derived_Base. Do it here.
14910
14911          if not Stored_Discrim then
14912             Enter_Name (New_C);
14913          end if;
14914
14915          --  For tagged types the Original_Record_Component must point to
14916          --  whatever this field was pointing to in the parent type. This has
14917          --  already been achieved by the call to New_Copy above.
14918
14919          if not Is_Tagged then
14920             Set_Original_Record_Component (New_C, New_C);
14921          end if;
14922
14923          --  If we have inherited a component then see if its Etype contains
14924          --  references to Parent_Base discriminants. In this case, replace
14925          --  these references with the constraints given in Discs. We do not
14926          --  do this for the partial view of private types because this is
14927          --  not needed (only the components of the full view will be used
14928          --  for code generation) and cause problem. We also avoid this
14929          --  transformation in some error situations.
14930
14931          if Ekind (New_C) = E_Component then
14932             if (Is_Private_Type (Derived_Base)
14933                  and then not Is_Generic_Type (Derived_Base))
14934               or else (Is_Empty_Elmt_List (Discs)
14935                         and then  not Expander_Active)
14936             then
14937                Set_Etype (New_C, Etype (Old_C));
14938
14939             else
14940                --  The current component introduces a circularity of the
14941                --  following kind:
14942
14943                --     limited with Pack_2;
14944                --     package Pack_1 is
14945                --        type T_1 is tagged record
14946                --           Comp : access Pack_2.T_2;
14947                --           ...
14948                --        end record;
14949                --     end Pack_1;
14950
14951                --     with Pack_1;
14952                --     package Pack_2 is
14953                --        type T_2 is new Pack_1.T_1 with ...;
14954                --     end Pack_2;
14955
14956                Set_Etype
14957                  (New_C,
14958                   Constrain_Component_Type
14959                   (Old_C, Derived_Base, N, Parent_Base, Discs));
14960             end if;
14961          end if;
14962
14963          --  In derived tagged types it is illegal to reference a non
14964          --  discriminant component in the parent type. To catch this, mark
14965          --  these components with an Ekind of E_Void. This will be reset in
14966          --  Record_Type_Definition after processing the record extension of
14967          --  the derived type.
14968
14969          --  If the declaration is a private extension, there is no further
14970          --  record extension to process, and the components retain their
14971          --  current kind, because they are visible at this point.
14972
14973          if Is_Tagged and then Ekind (New_C) = E_Component
14974            and then Nkind (N) /= N_Private_Extension_Declaration
14975          then
14976             Set_Ekind (New_C, E_Void);
14977          end if;
14978
14979          if Plain_Discrim then
14980             Set_Corresponding_Discriminant (New_C, Old_C);
14981             Build_Discriminal (New_C);
14982
14983          --  If we are explicitly inheriting a stored discriminant it will be
14984          --  completely hidden.
14985
14986          elsif Stored_Discrim then
14987             Set_Corresponding_Discriminant (New_C, Empty);
14988             Set_Discriminal (New_C, Empty);
14989             Set_Is_Completely_Hidden (New_C);
14990
14991             --  Set the Original_Record_Component of each discriminant in the
14992             --  derived base to point to the corresponding stored that we just
14993             --  created.
14994
14995             Discrim := First_Discriminant (Derived_Base);
14996             while Present (Discrim) loop
14997                Corr_Discrim := Corresponding_Discriminant (Discrim);
14998
14999                --  Corr_Discrim could be missing in an error situation
15000
15001                if Present (Corr_Discrim)
15002                  and then Original_Record_Component (Corr_Discrim) = Old_C
15003                then
15004                   Set_Original_Record_Component (Discrim, New_C);
15005                end if;
15006
15007                Next_Discriminant (Discrim);
15008             end loop;
15009
15010             Append_Entity (New_C, Derived_Base);
15011          end if;
15012
15013          if not Is_Tagged then
15014             Append_Elmt (Old_C, Assoc_List);
15015             Append_Elmt (New_C, Assoc_List);
15016          end if;
15017       end Inherit_Component;
15018
15019       --  Variables local to Inherit_Component
15020
15021       Loc : constant Source_Ptr := Sloc (N);
15022
15023       Parent_Discrim : Entity_Id;
15024       Stored_Discrim : Entity_Id;
15025       D              : Entity_Id;
15026       Component      : Entity_Id;
15027
15028    --  Start of processing for Inherit_Components
15029
15030    begin
15031       if not Is_Tagged then
15032          Append_Elmt (Parent_Base,  Assoc_List);
15033          Append_Elmt (Derived_Base, Assoc_List);
15034       end if;
15035
15036       --  Inherit parent discriminants if needed
15037
15038       if Inherit_Discr then
15039          Parent_Discrim := First_Discriminant (Parent_Base);
15040          while Present (Parent_Discrim) loop
15041             Inherit_Component (Parent_Discrim, Plain_Discrim => True);
15042             Next_Discriminant (Parent_Discrim);
15043          end loop;
15044       end if;
15045
15046       --  Create explicit stored discrims for untagged types when necessary
15047
15048       if not Has_Unknown_Discriminants (Derived_Base)
15049         and then Has_Discriminants (Parent_Base)
15050         and then not Is_Tagged
15051         and then
15052           (not Inherit_Discr
15053              or else First_Discriminant (Parent_Base) /=
15054                      First_Stored_Discriminant (Parent_Base))
15055       then
15056          Stored_Discrim := First_Stored_Discriminant (Parent_Base);
15057          while Present (Stored_Discrim) loop
15058             Inherit_Component (Stored_Discrim, Stored_Discrim => True);
15059             Next_Stored_Discriminant (Stored_Discrim);
15060          end loop;
15061       end if;
15062
15063       --  See if we can apply the second transformation for derived types, as
15064       --  explained in point 6. in the comments above Build_Derived_Record_Type
15065       --  This is achieved by appending Derived_Base discriminants into Discs,
15066       --  which has the side effect of returning a non empty Discs list to the
15067       --  caller of Inherit_Components, which is what we want. This must be
15068       --  done for private derived types if there are explicit stored
15069       --  discriminants, to ensure that we can retrieve the values of the
15070       --  constraints provided in the ancestors.
15071
15072       if Inherit_Discr
15073         and then Is_Empty_Elmt_List (Discs)
15074         and then Present (First_Discriminant (Derived_Base))
15075         and then
15076           (not Is_Private_Type (Derived_Base)
15077              or else Is_Completely_Hidden
15078                (First_Stored_Discriminant (Derived_Base))
15079              or else Is_Generic_Type (Derived_Base))
15080       then
15081          D := First_Discriminant (Derived_Base);
15082          while Present (D) loop
15083             Append_Elmt (New_Reference_To (D, Loc), Discs);
15084             Next_Discriminant (D);
15085          end loop;
15086       end if;
15087
15088       --  Finally, inherit non-discriminant components unless they are not
15089       --  visible because defined or inherited from the full view of the
15090       --  parent. Don't inherit the _parent field of the parent type.
15091
15092       Component := First_Entity (Parent_Base);
15093       while Present (Component) loop
15094
15095          --  Ada 2005 (AI-251): Do not inherit components associated with
15096          --  secondary tags of the parent.
15097
15098          if Ekind (Component) = E_Component
15099            and then Present (Related_Type (Component))
15100          then
15101             null;
15102
15103          elsif Ekind (Component) /= E_Component
15104            or else Chars (Component) = Name_uParent
15105          then
15106             null;
15107
15108          --  If the derived type is within the parent type's declarative
15109          --  region, then the components can still be inherited even though
15110          --  they aren't visible at this point. This can occur for cases
15111          --  such as within public child units where the components must
15112          --  become visible upon entering the child unit's private part.
15113
15114          elsif not Is_Visible_Component (Component)
15115            and then not In_Open_Scopes (Scope (Parent_Base))
15116          then
15117             null;
15118
15119          elsif Ekind_In (Derived_Base, E_Private_Type,
15120                                        E_Limited_Private_Type)
15121          then
15122             null;
15123
15124          else
15125             Inherit_Component (Component);
15126          end if;
15127
15128          Next_Entity (Component);
15129       end loop;
15130
15131       --  For tagged derived types, inherited discriminants cannot be used in
15132       --  component declarations of the record extension part. To achieve this
15133       --  we mark the inherited discriminants as not visible.
15134
15135       if Is_Tagged and then Inherit_Discr then
15136          D := First_Discriminant (Derived_Base);
15137          while Present (D) loop
15138             Set_Is_Immediately_Visible (D, False);
15139             Next_Discriminant (D);
15140          end loop;
15141       end if;
15142
15143       return Assoc_List;
15144    end Inherit_Components;
15145
15146    -----------------------
15147    -- Is_Null_Extension --
15148    -----------------------
15149
15150    function Is_Null_Extension (T : Entity_Id) return Boolean is
15151       Type_Decl : constant Node_Id := Parent (Base_Type (T));
15152       Comp_List : Node_Id;
15153       Comp      : Node_Id;
15154
15155    begin
15156       if Nkind (Type_Decl) /= N_Full_Type_Declaration
15157         or else not Is_Tagged_Type (T)
15158         or else Nkind (Type_Definition (Type_Decl)) /=
15159                                               N_Derived_Type_Definition
15160         or else No (Record_Extension_Part (Type_Definition (Type_Decl)))
15161       then
15162          return False;
15163       end if;
15164
15165       Comp_List :=
15166         Component_List (Record_Extension_Part (Type_Definition (Type_Decl)));
15167
15168       if Present (Discriminant_Specifications (Type_Decl)) then
15169          return False;
15170
15171       elsif Present (Comp_List)
15172         and then Is_Non_Empty_List (Component_Items (Comp_List))
15173       then
15174          Comp := First (Component_Items (Comp_List));
15175
15176          --  Only user-defined components are relevant. The component list
15177          --  may also contain a parent component and internal components
15178          --  corresponding to secondary tags, but these do not determine
15179          --  whether this is a null extension.
15180
15181          while Present (Comp) loop
15182             if Comes_From_Source (Comp) then
15183                return False;
15184             end if;
15185
15186             Next (Comp);
15187          end loop;
15188
15189          return True;
15190       else
15191          return True;
15192       end if;
15193    end Is_Null_Extension;
15194
15195    ------------------------------
15196    -- Is_Valid_Constraint_Kind --
15197    ------------------------------
15198
15199    function Is_Valid_Constraint_Kind
15200      (T_Kind          : Type_Kind;
15201       Constraint_Kind : Node_Kind) return Boolean
15202    is
15203    begin
15204       case T_Kind is
15205          when Enumeration_Kind |
15206               Integer_Kind =>
15207             return Constraint_Kind = N_Range_Constraint;
15208
15209          when Decimal_Fixed_Point_Kind =>
15210             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
15211                                               N_Range_Constraint);
15212
15213          when Ordinary_Fixed_Point_Kind =>
15214             return Nkind_In (Constraint_Kind, N_Delta_Constraint,
15215                                               N_Range_Constraint);
15216
15217          when Float_Kind =>
15218             return Nkind_In (Constraint_Kind, N_Digits_Constraint,
15219                                               N_Range_Constraint);
15220
15221          when Access_Kind       |
15222               Array_Kind        |
15223               E_Record_Type     |
15224               E_Record_Subtype  |
15225               Class_Wide_Kind   |
15226               E_Incomplete_Type |
15227               Private_Kind      |
15228               Concurrent_Kind  =>
15229             return Constraint_Kind = N_Index_Or_Discriminant_Constraint;
15230
15231          when others =>
15232             return True; -- Error will be detected later
15233       end case;
15234    end Is_Valid_Constraint_Kind;
15235
15236    --------------------------
15237    -- Is_Visible_Component --
15238    --------------------------
15239
15240    function Is_Visible_Component (C : Entity_Id) return Boolean is
15241       Original_Comp  : Entity_Id := Empty;
15242       Original_Scope : Entity_Id;
15243       Type_Scope     : Entity_Id;
15244
15245       function Is_Local_Type (Typ : Entity_Id) return Boolean;
15246       --  Check whether parent type of inherited component is declared locally,
15247       --  possibly within a nested package or instance. The current scope is
15248       --  the derived record itself.
15249
15250       -------------------
15251       -- Is_Local_Type --
15252       -------------------
15253
15254       function Is_Local_Type (Typ : Entity_Id) return Boolean is
15255          Scop : Entity_Id;
15256
15257       begin
15258          Scop := Scope (Typ);
15259          while Present (Scop)
15260            and then Scop /= Standard_Standard
15261          loop
15262             if Scop = Scope (Current_Scope) then
15263                return True;
15264             end if;
15265
15266             Scop := Scope (Scop);
15267          end loop;
15268
15269          return False;
15270       end Is_Local_Type;
15271
15272    --  Start of processing for Is_Visible_Component
15273
15274    begin
15275       if Ekind_In (C, E_Component, E_Discriminant) then
15276          Original_Comp := Original_Record_Component (C);
15277       end if;
15278
15279       if No (Original_Comp) then
15280
15281          --  Premature usage, or previous error
15282
15283          return False;
15284
15285       else
15286          Original_Scope := Scope (Original_Comp);
15287          Type_Scope     := Scope (Base_Type (Scope (C)));
15288       end if;
15289
15290       --  This test only concerns tagged types
15291
15292       if not Is_Tagged_Type (Original_Scope) then
15293          return True;
15294
15295       --  If it is _Parent or _Tag, there is no visibility issue
15296
15297       elsif not Comes_From_Source (Original_Comp) then
15298          return True;
15299
15300       --  If we are in the body of an instantiation, the component is visible
15301       --  even when the parent type (possibly defined in an enclosing unit or
15302       --  in a parent unit) might not.
15303
15304       elsif In_Instance_Body then
15305          return True;
15306
15307       --  Discriminants are always visible
15308
15309       elsif Ekind (Original_Comp) = E_Discriminant
15310         and then not Has_Unknown_Discriminants (Original_Scope)
15311       then
15312          return True;
15313
15314       --  If the component has been declared in an ancestor which is currently
15315       --  a private type, then it is not visible. The same applies if the
15316       --  component's containing type is not in an open scope and the original
15317       --  component's enclosing type is a visible full view of a private type
15318       --  (which can occur in cases where an attempt is being made to reference
15319       --  a component in a sibling package that is inherited from a visible
15320       --  component of a type in an ancestor package; the component in the
15321       --  sibling package should not be visible even though the component it
15322       --  inherited from is visible). This does not apply however in the case
15323       --  where the scope of the type is a private child unit, or when the
15324       --  parent comes from a local package in which the ancestor is currently
15325       --  visible. The latter suppression of visibility is needed for cases
15326       --  that are tested in B730006.
15327
15328       elsif Is_Private_Type (Original_Scope)
15329         or else
15330           (not Is_Private_Descendant (Type_Scope)
15331             and then not In_Open_Scopes (Type_Scope)
15332             and then Has_Private_Declaration (Original_Scope))
15333       then
15334          --  If the type derives from an entity in a formal package, there
15335          --  are no additional visible components.
15336
15337          if Nkind (Original_Node (Unit_Declaration_Node (Type_Scope))) =
15338             N_Formal_Package_Declaration
15339          then
15340             return False;
15341
15342          --  if we are not in the private part of the current package, there
15343          --  are no additional visible components.
15344
15345          elsif Ekind (Scope (Current_Scope)) = E_Package
15346            and then not In_Private_Part (Scope (Current_Scope))
15347          then
15348             return False;
15349          else
15350             return
15351               Is_Child_Unit (Cunit_Entity (Current_Sem_Unit))
15352                 and then In_Open_Scopes (Scope (Original_Scope))
15353                 and then Is_Local_Type (Type_Scope);
15354          end if;
15355
15356       --  There is another weird way in which a component may be invisible
15357       --  when the private and the full view are not derived from the same
15358       --  ancestor. Here is an example :
15359
15360       --       type A1 is tagged      record F1 : integer; end record;
15361       --       type A2 is new A1 with record F2 : integer; end record;
15362       --       type T is new A1 with private;
15363       --     private
15364       --       type T is new A2 with null record;
15365
15366       --  In this case, the full view of T inherits F1 and F2 but the private
15367       --  view inherits only F1
15368
15369       else
15370          declare
15371             Ancestor : Entity_Id := Scope (C);
15372
15373          begin
15374             loop
15375                if Ancestor = Original_Scope then
15376                   return True;
15377                elsif Ancestor = Etype (Ancestor) then
15378                   return False;
15379                end if;
15380
15381                Ancestor := Etype (Ancestor);
15382             end loop;
15383          end;
15384       end if;
15385    end Is_Visible_Component;
15386
15387    --------------------------
15388    -- Make_Class_Wide_Type --
15389    --------------------------
15390
15391    procedure Make_Class_Wide_Type (T : Entity_Id) is
15392       CW_Type : Entity_Id;
15393       CW_Name : Name_Id;
15394       Next_E  : Entity_Id;
15395
15396    begin
15397       --  The class wide type can have been defined by the partial view, in
15398       --  which case everything is already done.
15399
15400       if Present (Class_Wide_Type (T)) then
15401          return;
15402       end if;
15403
15404       CW_Type :=
15405         New_External_Entity (E_Void, Scope (T), Sloc (T), T, 'C', 0, 'T');
15406
15407       --  Inherit root type characteristics
15408
15409       CW_Name := Chars (CW_Type);
15410       Next_E  := Next_Entity (CW_Type);
15411       Copy_Node (T, CW_Type);
15412       Set_Comes_From_Source (CW_Type, False);
15413       Set_Chars (CW_Type, CW_Name);
15414       Set_Parent (CW_Type, Parent (T));
15415       Set_Next_Entity (CW_Type, Next_E);
15416
15417       --  Ensure we have a new freeze node for the class-wide type. The partial
15418       --  view may have freeze action of its own, requiring a proper freeze
15419       --  node, and the same freeze node cannot be shared between the two
15420       --  types.
15421
15422       Set_Has_Delayed_Freeze (CW_Type);
15423       Set_Freeze_Node (CW_Type, Empty);
15424
15425       --  Customize the class-wide type: It has no prim. op., it cannot be
15426       --  abstract and its Etype points back to the specific root type.
15427
15428       Set_Ekind                       (CW_Type, E_Class_Wide_Type);
15429       Set_Is_Tagged_Type              (CW_Type, True);
15430       Set_Direct_Primitive_Operations (CW_Type, New_Elmt_List);
15431       Set_Is_Abstract_Type            (CW_Type, False);
15432       Set_Is_Constrained              (CW_Type, False);
15433       Set_Is_First_Subtype            (CW_Type, Is_First_Subtype (T));
15434
15435       if Ekind (T) = E_Class_Wide_Subtype then
15436          Set_Etype             (CW_Type, Etype (Base_Type (T)));
15437       else
15438          Set_Etype             (CW_Type, T);
15439       end if;
15440
15441       --  If this is the class_wide type of a constrained subtype, it does
15442       --  not have discriminants.
15443
15444       Set_Has_Discriminants (CW_Type,
15445         Has_Discriminants (T) and then not Is_Constrained (T));
15446
15447       Set_Has_Unknown_Discriminants (CW_Type, True);
15448       Set_Class_Wide_Type (T, CW_Type);
15449       Set_Equivalent_Type (CW_Type, Empty);
15450
15451       --  The class-wide type of a class-wide type is itself (RM 3.9(14))
15452
15453       Set_Class_Wide_Type (CW_Type, CW_Type);
15454    end Make_Class_Wide_Type;
15455
15456    ----------------
15457    -- Make_Index --
15458    ----------------
15459
15460    procedure Make_Index
15461      (I            : Node_Id;
15462       Related_Nod  : Node_Id;
15463       Related_Id   : Entity_Id := Empty;
15464       Suffix_Index : Nat := 1)
15465    is
15466       R      : Node_Id;
15467       T      : Entity_Id;
15468       Def_Id : Entity_Id := Empty;
15469       Found  : Boolean := False;
15470
15471    begin
15472       --  For a discrete range used in a constrained array definition and
15473       --  defined by a range, an implicit conversion to the predefined type
15474       --  INTEGER is assumed if each bound is either a numeric literal, a named
15475       --  number, or an attribute, and the type of both bounds (prior to the
15476       --  implicit conversion) is the type universal_integer. Otherwise, both
15477       --  bounds must be of the same discrete type, other than universal
15478       --  integer; this type must be determinable independently of the
15479       --  context, but using the fact that the type must be discrete and that
15480       --  both bounds must have the same type.
15481
15482       --  Character literals also have a universal type in the absence of
15483       --  of additional context,  and are resolved to Standard_Character.
15484
15485       if Nkind (I) = N_Range then
15486
15487          --  The index is given by a range constraint. The bounds are known
15488          --  to be of a consistent type.
15489
15490          if not Is_Overloaded (I) then
15491             T := Etype (I);
15492
15493             --  For universal bounds, choose the specific predefined type
15494
15495             if T = Universal_Integer then
15496                T := Standard_Integer;
15497
15498             elsif T = Any_Character then
15499                Ambiguous_Character (Low_Bound (I));
15500
15501                T := Standard_Character;
15502             end if;
15503
15504          --  The node may be overloaded because some user-defined operators
15505          --  are available, but if a universal interpretation exists it is
15506          --  also the selected one.
15507
15508          elsif Universal_Interpretation (I) = Universal_Integer then
15509             T := Standard_Integer;
15510
15511          else
15512             T := Any_Type;
15513
15514             declare
15515                Ind : Interp_Index;
15516                It  : Interp;
15517
15518             begin
15519                Get_First_Interp (I, Ind, It);
15520                while Present (It.Typ) loop
15521                   if Is_Discrete_Type (It.Typ) then
15522
15523                      if Found
15524                        and then not Covers (It.Typ, T)
15525                        and then not Covers (T, It.Typ)
15526                      then
15527                         Error_Msg_N ("ambiguous bounds in discrete range", I);
15528                         exit;
15529                      else
15530                         T := It.Typ;
15531                         Found := True;
15532                      end if;
15533                   end if;
15534
15535                   Get_Next_Interp (Ind, It);
15536                end loop;
15537
15538                if T = Any_Type then
15539                   Error_Msg_N ("discrete type required for range", I);
15540                   Set_Etype (I, Any_Type);
15541                   return;
15542
15543                elsif T = Universal_Integer then
15544                   T := Standard_Integer;
15545                end if;
15546             end;
15547          end if;
15548
15549          if not Is_Discrete_Type (T) then
15550             Error_Msg_N ("discrete type required for range", I);
15551             Set_Etype (I, Any_Type);
15552             return;
15553          end if;
15554
15555          if Nkind (Low_Bound (I)) = N_Attribute_Reference
15556            and then Attribute_Name (Low_Bound (I)) = Name_First
15557            and then Is_Entity_Name (Prefix (Low_Bound (I)))
15558            and then Is_Type (Entity (Prefix (Low_Bound (I))))
15559            and then Is_Discrete_Type (Entity (Prefix (Low_Bound (I))))
15560          then
15561             --  The type of the index will be the type of the prefix, as long
15562             --  as the upper bound is 'Last of the same type.
15563
15564             Def_Id := Entity (Prefix (Low_Bound (I)));
15565
15566             if Nkind (High_Bound (I)) /= N_Attribute_Reference
15567               or else Attribute_Name (High_Bound (I)) /= Name_Last
15568               or else not Is_Entity_Name (Prefix (High_Bound (I)))
15569               or else Entity (Prefix (High_Bound (I))) /= Def_Id
15570             then
15571                Def_Id := Empty;
15572             end if;
15573          end if;
15574
15575          R := I;
15576          Process_Range_Expr_In_Decl (R, T);
15577
15578       elsif Nkind (I) = N_Subtype_Indication then
15579
15580          --  The index is given by a subtype with a range constraint
15581
15582          T :=  Base_Type (Entity (Subtype_Mark (I)));
15583
15584          if not Is_Discrete_Type (T) then
15585             Error_Msg_N ("discrete type required for range", I);
15586             Set_Etype (I, Any_Type);
15587             return;
15588          end if;
15589
15590          R := Range_Expression (Constraint (I));
15591
15592          Resolve (R, T);
15593          Process_Range_Expr_In_Decl (R, Entity (Subtype_Mark (I)));
15594
15595       elsif Nkind (I) = N_Attribute_Reference then
15596
15597          --  The parser guarantees that the attribute is a RANGE attribute
15598
15599          --  If the node denotes the range of a type mark, that is also the
15600          --  resulting type, and we do no need to create an Itype for it.
15601
15602          if Is_Entity_Name (Prefix (I))
15603            and then Comes_From_Source (I)
15604            and then Is_Type (Entity (Prefix (I)))
15605            and then Is_Discrete_Type (Entity (Prefix (I)))
15606          then
15607             Def_Id := Entity (Prefix (I));
15608          end if;
15609
15610          Analyze_And_Resolve (I);
15611          T := Etype (I);
15612          R := I;
15613
15614       --  If none of the above, must be a subtype. We convert this to a
15615       --  range attribute reference because in the case of declared first
15616       --  named subtypes, the types in the range reference can be different
15617       --  from the type of the entity. A range attribute normalizes the
15618       --  reference and obtains the correct types for the bounds.
15619
15620       --  This transformation is in the nature of an expansion, is only
15621       --  done if expansion is active. In particular, it is not done on
15622       --  formal generic types,  because we need to retain the name of the
15623       --  original index for instantiation purposes.
15624
15625       else
15626          if not Is_Entity_Name (I) or else not Is_Type (Entity (I)) then
15627             Error_Msg_N ("invalid subtype mark in discrete range ", I);
15628             Set_Etype (I, Any_Integer);
15629             return;
15630
15631          else
15632             --  The type mark may be that of an incomplete type. It is only
15633             --  now that we can get the full view, previous analysis does
15634             --  not look specifically for a type mark.
15635
15636             Set_Entity (I, Get_Full_View (Entity (I)));
15637             Set_Etype  (I, Entity (I));
15638             Def_Id := Entity (I);
15639
15640             if not Is_Discrete_Type (Def_Id) then
15641                Error_Msg_N ("discrete type required for index", I);
15642                Set_Etype (I, Any_Type);
15643                return;
15644             end if;
15645          end if;
15646
15647          if Expander_Active then
15648             Rewrite (I,
15649               Make_Attribute_Reference (Sloc (I),
15650                 Attribute_Name => Name_Range,
15651                 Prefix         => Relocate_Node (I)));
15652
15653             --  The original was a subtype mark that does not freeze. This
15654             --  means that the rewritten version must not freeze either.
15655
15656             Set_Must_Not_Freeze (I);
15657             Set_Must_Not_Freeze (Prefix (I));
15658
15659             --  Is order critical??? if so, document why, if not
15660             --  use Analyze_And_Resolve
15661
15662             Analyze_And_Resolve (I);
15663             T := Etype (I);
15664             R := I;
15665
15666          --  If expander is inactive, type is legal, nothing else to construct
15667
15668          else
15669             return;
15670          end if;
15671       end if;
15672
15673       if not Is_Discrete_Type (T) then
15674          Error_Msg_N ("discrete type required for range", I);
15675          Set_Etype (I, Any_Type);
15676          return;
15677
15678       elsif T = Any_Type then
15679          Set_Etype (I, Any_Type);
15680          return;
15681       end if;
15682
15683       --  We will now create the appropriate Itype to describe the range, but
15684       --  first a check. If we originally had a subtype, then we just label
15685       --  the range with this subtype. Not only is there no need to construct
15686       --  a new subtype, but it is wrong to do so for two reasons:
15687
15688       --    1. A legality concern, if we have a subtype, it must not freeze,
15689       --       and the Itype would cause freezing incorrectly
15690
15691       --    2. An efficiency concern, if we created an Itype, it would not be
15692       --       recognized as the same type for the purposes of eliminating
15693       --       checks in some circumstances.
15694
15695       --  We signal this case by setting the subtype entity in Def_Id
15696
15697       if No (Def_Id) then
15698          Def_Id :=
15699            Create_Itype (E_Void, Related_Nod, Related_Id, 'D', Suffix_Index);
15700          Set_Etype (Def_Id, Base_Type (T));
15701
15702          if Is_Signed_Integer_Type (T) then
15703             Set_Ekind (Def_Id, E_Signed_Integer_Subtype);
15704
15705          elsif Is_Modular_Integer_Type (T) then
15706             Set_Ekind (Def_Id, E_Modular_Integer_Subtype);
15707
15708          else
15709             Set_Ekind             (Def_Id, E_Enumeration_Subtype);
15710             Set_Is_Character_Type (Def_Id, Is_Character_Type (T));
15711             Set_First_Literal     (Def_Id, First_Literal (T));
15712          end if;
15713
15714          Set_Size_Info      (Def_Id,                  (T));
15715          Set_RM_Size        (Def_Id, RM_Size          (T));
15716          Set_First_Rep_Item (Def_Id, First_Rep_Item   (T));
15717
15718          Set_Scalar_Range   (Def_Id, R);
15719          Conditional_Delay  (Def_Id, T);
15720
15721          --  In the subtype indication case, if the immediate parent of the
15722          --  new subtype is non-static, then the subtype we create is non-
15723          --  static, even if its bounds are static.
15724
15725          if Nkind (I) = N_Subtype_Indication
15726            and then not Is_Static_Subtype (Entity (Subtype_Mark (I)))
15727          then
15728             Set_Is_Non_Static_Subtype (Def_Id);
15729          end if;
15730       end if;
15731
15732       --  Final step is to label the index with this constructed type
15733
15734       Set_Etype (I, Def_Id);
15735    end Make_Index;
15736
15737    ------------------------------
15738    -- Modular_Type_Declaration --
15739    ------------------------------
15740
15741    procedure Modular_Type_Declaration (T : Entity_Id; Def : Node_Id) is
15742       Mod_Expr : constant Node_Id := Expression (Def);
15743       M_Val    : Uint;
15744
15745       procedure Set_Modular_Size (Bits : Int);
15746       --  Sets RM_Size to Bits, and Esize to normal word size above this
15747
15748       ----------------------
15749       -- Set_Modular_Size --
15750       ----------------------
15751
15752       procedure Set_Modular_Size (Bits : Int) is
15753       begin
15754          Set_RM_Size (T, UI_From_Int (Bits));
15755
15756          if Bits <= 8 then
15757             Init_Esize (T, 8);
15758
15759          elsif Bits <= 16 then
15760             Init_Esize (T, 16);
15761
15762          elsif Bits <= 32 then
15763             Init_Esize (T, 32);
15764
15765          else
15766             Init_Esize (T, System_Max_Binary_Modulus_Power);
15767          end if;
15768
15769          if not Non_Binary_Modulus (T)
15770            and then Esize (T) = RM_Size (T)
15771          then
15772             Set_Is_Known_Valid (T);
15773          end if;
15774       end Set_Modular_Size;
15775
15776    --  Start of processing for Modular_Type_Declaration
15777
15778    begin
15779       Analyze_And_Resolve (Mod_Expr, Any_Integer);
15780       Set_Etype (T, T);
15781       Set_Ekind (T, E_Modular_Integer_Type);
15782       Init_Alignment (T);
15783       Set_Is_Constrained (T);
15784
15785       if not Is_OK_Static_Expression (Mod_Expr) then
15786          Flag_Non_Static_Expr
15787            ("non-static expression used for modular type bound!", Mod_Expr);
15788          M_Val := 2 ** System_Max_Binary_Modulus_Power;
15789       else
15790          M_Val := Expr_Value (Mod_Expr);
15791       end if;
15792
15793       if M_Val < 1 then
15794          Error_Msg_N ("modulus value must be positive", Mod_Expr);
15795          M_Val := 2 ** System_Max_Binary_Modulus_Power;
15796       end if;
15797
15798       Set_Modulus (T, M_Val);
15799
15800       --   Create bounds for the modular type based on the modulus given in
15801       --   the type declaration and then analyze and resolve those bounds.
15802
15803       Set_Scalar_Range (T,
15804         Make_Range (Sloc (Mod_Expr),
15805           Low_Bound  =>
15806             Make_Integer_Literal (Sloc (Mod_Expr), 0),
15807           High_Bound =>
15808             Make_Integer_Literal (Sloc (Mod_Expr), M_Val - 1)));
15809
15810       --  Properly analyze the literals for the range. We do this manually
15811       --  because we can't go calling Resolve, since we are resolving these
15812       --  bounds with the type, and this type is certainly not complete yet!
15813
15814       Set_Etype (Low_Bound  (Scalar_Range (T)), T);
15815       Set_Etype (High_Bound (Scalar_Range (T)), T);
15816       Set_Is_Static_Expression (Low_Bound  (Scalar_Range (T)));
15817       Set_Is_Static_Expression (High_Bound (Scalar_Range (T)));
15818
15819       --  Loop through powers of two to find number of bits required
15820
15821       for Bits in Int range 0 .. System_Max_Binary_Modulus_Power loop
15822
15823          --  Binary case
15824
15825          if M_Val = 2 ** Bits then
15826             Set_Modular_Size (Bits);
15827             return;
15828
15829          --  Non-binary case
15830
15831          elsif M_Val < 2 ** Bits then
15832             Set_Non_Binary_Modulus (T);
15833
15834             if Bits > System_Max_Nonbinary_Modulus_Power then
15835                Error_Msg_Uint_1 :=
15836                  UI_From_Int (System_Max_Nonbinary_Modulus_Power);
15837                Error_Msg_F
15838                  ("nonbinary modulus exceeds limit (2 '*'*^ - 1)", Mod_Expr);
15839                Set_Modular_Size (System_Max_Binary_Modulus_Power);
15840                return;
15841
15842             else
15843                --  In the non-binary case, set size as per RM 13.3(55)
15844
15845                Set_Modular_Size (Bits);
15846                return;
15847             end if;
15848          end if;
15849
15850       end loop;
15851
15852       --  If we fall through, then the size exceed System.Max_Binary_Modulus
15853       --  so we just signal an error and set the maximum size.
15854
15855       Error_Msg_Uint_1 := UI_From_Int (System_Max_Binary_Modulus_Power);
15856       Error_Msg_F ("modulus exceeds limit (2 '*'*^)", Mod_Expr);
15857
15858       Set_Modular_Size (System_Max_Binary_Modulus_Power);
15859       Init_Alignment (T);
15860
15861    end Modular_Type_Declaration;
15862
15863    --------------------------
15864    -- New_Concatenation_Op --
15865    --------------------------
15866
15867    procedure New_Concatenation_Op (Typ : Entity_Id) is
15868       Loc : constant Source_Ptr := Sloc (Typ);
15869       Op  : Entity_Id;
15870
15871       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id;
15872       --  Create abbreviated declaration for the formal of a predefined
15873       --  Operator 'Op' of type 'Typ'
15874
15875       --------------------
15876       -- Make_Op_Formal --
15877       --------------------
15878
15879       function Make_Op_Formal (Typ, Op : Entity_Id) return Entity_Id is
15880          Formal : Entity_Id;
15881       begin
15882          Formal := New_Internal_Entity (E_In_Parameter, Op, Loc, 'P');
15883          Set_Etype (Formal, Typ);
15884          Set_Mechanism (Formal, Default_Mechanism);
15885          return Formal;
15886       end Make_Op_Formal;
15887
15888    --  Start of processing for New_Concatenation_Op
15889
15890    begin
15891       Op := Make_Defining_Operator_Symbol (Loc, Name_Op_Concat);
15892
15893       Set_Ekind                   (Op, E_Operator);
15894       Set_Scope                   (Op, Current_Scope);
15895       Set_Etype                   (Op, Typ);
15896       Set_Homonym                 (Op, Get_Name_Entity_Id (Name_Op_Concat));
15897       Set_Is_Immediately_Visible  (Op);
15898       Set_Is_Intrinsic_Subprogram (Op);
15899       Set_Has_Completion          (Op);
15900       Append_Entity               (Op, Current_Scope);
15901
15902       Set_Name_Entity_Id (Name_Op_Concat, Op);
15903
15904       Append_Entity (Make_Op_Formal (Typ, Op), Op);
15905       Append_Entity (Make_Op_Formal (Typ, Op), Op);
15906    end New_Concatenation_Op;
15907
15908    -------------------------
15909    -- OK_For_Limited_Init --
15910    -------------------------
15911
15912    --  ???Check all calls of this, and compare the conditions under which it's
15913    --  called.
15914
15915    function OK_For_Limited_Init
15916      (Typ : Entity_Id;
15917       Exp : Node_Id) return Boolean
15918    is
15919    begin
15920       return Is_CPP_Constructor_Call (Exp)
15921         or else (Ada_Version >= Ada_2005
15922                   and then not Debug_Flag_Dot_L
15923                   and then OK_For_Limited_Init_In_05 (Typ, Exp));
15924    end OK_For_Limited_Init;
15925
15926    -------------------------------
15927    -- OK_For_Limited_Init_In_05 --
15928    -------------------------------
15929
15930    function OK_For_Limited_Init_In_05
15931      (Typ : Entity_Id;
15932       Exp : Node_Id) return Boolean
15933    is
15934    begin
15935       --  An object of a limited interface type can be initialized with any
15936       --  expression of a nonlimited descendant type.
15937
15938       if Is_Class_Wide_Type (Typ)
15939         and then Is_Limited_Interface (Typ)
15940         and then not Is_Limited_Type (Etype (Exp))
15941       then
15942          return True;
15943       end if;
15944
15945       --  Ada 2005 (AI-287, AI-318): Relax the strictness of the front end in
15946       --  case of limited aggregates (including extension aggregates), and
15947       --  function calls. The function call may have been give in prefixed
15948       --  notation, in which case the original node is an indexed component.
15949
15950       case Nkind (Original_Node (Exp)) is
15951          when N_Aggregate | N_Extension_Aggregate | N_Function_Call | N_Op =>
15952             return True;
15953
15954          when N_Qualified_Expression =>
15955             return
15956               OK_For_Limited_Init_In_05
15957                 (Typ, Expression (Original_Node (Exp)));
15958
15959          --  Ada 2005 (AI-251): If a class-wide interface object is initialized
15960          --  with a function call, the expander has rewritten the call into an
15961          --  N_Type_Conversion node to force displacement of the pointer to
15962          --  reference the component containing the secondary dispatch table.
15963          --  Otherwise a type conversion is not a legal context.
15964          --  A return statement for a build-in-place function returning a
15965          --  synchronized type also introduces an unchecked conversion.
15966
15967          when N_Type_Conversion | N_Unchecked_Type_Conversion =>
15968             return not Comes_From_Source (Exp)
15969               and then
15970                 OK_For_Limited_Init_In_05
15971                   (Typ, Expression (Original_Node (Exp)));
15972
15973          when N_Indexed_Component | N_Selected_Component  =>
15974             return Nkind (Exp) = N_Function_Call;
15975
15976          --  A use of 'Input is a function call, hence allowed. Normally the
15977          --  attribute will be changed to a call, but the attribute by itself
15978          --  can occur with -gnatc.
15979
15980          when N_Attribute_Reference =>
15981             return Attribute_Name (Original_Node (Exp)) = Name_Input;
15982
15983          when others =>
15984             return False;
15985       end case;
15986    end OK_For_Limited_Init_In_05;
15987
15988    -------------------------------------------
15989    -- Ordinary_Fixed_Point_Type_Declaration --
15990    -------------------------------------------
15991
15992    procedure Ordinary_Fixed_Point_Type_Declaration
15993      (T   : Entity_Id;
15994       Def : Node_Id)
15995    is
15996       Loc           : constant Source_Ptr := Sloc (Def);
15997       Delta_Expr    : constant Node_Id    := Delta_Expression (Def);
15998       RRS           : constant Node_Id    := Real_Range_Specification (Def);
15999       Implicit_Base : Entity_Id;
16000       Delta_Val     : Ureal;
16001       Small_Val     : Ureal;
16002       Low_Val       : Ureal;
16003       High_Val      : Ureal;
16004
16005    begin
16006       Check_Restriction (No_Fixed_Point, Def);
16007
16008       --  Create implicit base type
16009
16010       Implicit_Base :=
16011         Create_Itype (E_Ordinary_Fixed_Point_Type, Parent (Def), T, 'B');
16012       Set_Etype (Implicit_Base, Implicit_Base);
16013
16014       --  Analyze and process delta expression
16015
16016       Analyze_And_Resolve (Delta_Expr, Any_Real);
16017
16018       Check_Delta_Expression (Delta_Expr);
16019       Delta_Val := Expr_Value_R (Delta_Expr);
16020
16021       Set_Delta_Value (Implicit_Base, Delta_Val);
16022
16023       --  Compute default small from given delta, which is the largest power
16024       --  of two that does not exceed the given delta value.
16025
16026       declare
16027          Tmp   : Ureal;
16028          Scale : Int;
16029
16030       begin
16031          Tmp := Ureal_1;
16032          Scale := 0;
16033
16034          if Delta_Val < Ureal_1 then
16035             while Delta_Val < Tmp loop
16036                Tmp := Tmp / Ureal_2;
16037                Scale := Scale + 1;
16038             end loop;
16039
16040          else
16041             loop
16042                Tmp := Tmp * Ureal_2;
16043                exit when Tmp > Delta_Val;
16044                Scale := Scale - 1;
16045             end loop;
16046          end if;
16047
16048          Small_Val := UR_From_Components (Uint_1, UI_From_Int (Scale), 2);
16049       end;
16050
16051       Set_Small_Value (Implicit_Base, Small_Val);
16052
16053       --  If no range was given, set a dummy range
16054
16055       if RRS <= Empty_Or_Error then
16056          Low_Val  := -Small_Val;
16057          High_Val := Small_Val;
16058
16059       --  Otherwise analyze and process given range
16060
16061       else
16062          declare
16063             Low  : constant Node_Id := Low_Bound  (RRS);
16064             High : constant Node_Id := High_Bound (RRS);
16065
16066          begin
16067             Analyze_And_Resolve (Low, Any_Real);
16068             Analyze_And_Resolve (High, Any_Real);
16069             Check_Real_Bound (Low);
16070             Check_Real_Bound (High);
16071
16072             --  Obtain and set the range
16073
16074             Low_Val  := Expr_Value_R (Low);
16075             High_Val := Expr_Value_R (High);
16076
16077             if Low_Val > High_Val then
16078                Error_Msg_NE ("?fixed point type& has null range", Def, T);
16079             end if;
16080          end;
16081       end if;
16082
16083       --  The range for both the implicit base and the declared first subtype
16084       --  cannot be set yet, so we use the special routine Set_Fixed_Range to
16085       --  set a temporary range in place. Note that the bounds of the base
16086       --  type will be widened to be symmetrical and to fill the available
16087       --  bits when the type is frozen.
16088
16089       --  We could do this with all discrete types, and probably should, but
16090       --  we absolutely have to do it for fixed-point, since the end-points
16091       --  of the range and the size are determined by the small value, which
16092       --  could be reset before the freeze point.
16093
16094       Set_Fixed_Range (Implicit_Base, Loc, Low_Val, High_Val);
16095       Set_Fixed_Range (T, Loc, Low_Val, High_Val);
16096
16097       --  Complete definition of first subtype
16098
16099       Set_Ekind          (T, E_Ordinary_Fixed_Point_Subtype);
16100       Set_Etype          (T, Implicit_Base);
16101       Init_Size_Align    (T);
16102       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
16103       Set_Small_Value    (T, Small_Val);
16104       Set_Delta_Value    (T, Delta_Val);
16105       Set_Is_Constrained (T);
16106
16107    end Ordinary_Fixed_Point_Type_Declaration;
16108
16109    ----------------------------------------
16110    -- Prepare_Private_Subtype_Completion --
16111    ----------------------------------------
16112
16113    procedure Prepare_Private_Subtype_Completion
16114      (Id          : Entity_Id;
16115       Related_Nod : Node_Id)
16116    is
16117       Id_B   : constant Entity_Id := Base_Type (Id);
16118       Full_B : constant Entity_Id := Full_View (Id_B);
16119       Full   : Entity_Id;
16120
16121    begin
16122       if Present (Full_B) then
16123
16124          --  The Base_Type is already completed, we can complete the subtype
16125          --  now. We have to create a new entity with the same name, Thus we
16126          --  can't use Create_Itype.
16127
16128          --  This is messy, should be fixed ???
16129
16130          Full := Make_Defining_Identifier (Sloc (Id), Chars (Id));
16131          Set_Is_Itype (Full);
16132          Set_Associated_Node_For_Itype (Full, Related_Nod);
16133          Complete_Private_Subtype (Id, Full, Full_B, Related_Nod);
16134       end if;
16135
16136       --  The parent subtype may be private, but the base might not, in some
16137       --  nested instances. In that case, the subtype does not need to be
16138       --  exchanged. It would still be nice to make private subtypes and their
16139       --  bases consistent at all times ???
16140
16141       if Is_Private_Type (Id_B) then
16142          Append_Elmt (Id, Private_Dependents (Id_B));
16143       end if;
16144
16145    end Prepare_Private_Subtype_Completion;
16146
16147    ---------------------------
16148    -- Process_Discriminants --
16149    ---------------------------
16150
16151    procedure Process_Discriminants
16152      (N    : Node_Id;
16153       Prev : Entity_Id := Empty)
16154    is
16155       Elist               : constant Elist_Id := New_Elmt_List;
16156       Id                  : Node_Id;
16157       Discr               : Node_Id;
16158       Discr_Number        : Uint;
16159       Discr_Type          : Entity_Id;
16160       Default_Present     : Boolean := False;
16161       Default_Not_Present : Boolean := False;
16162
16163    begin
16164       --  A composite type other than an array type can have discriminants.
16165       --  On entry, the current scope is the composite type.
16166
16167       --  The discriminants are initially entered into the scope of the type
16168       --  via Enter_Name with the default Ekind of E_Void to prevent premature
16169       --  use, as explained at the end of this procedure.
16170
16171       Discr := First (Discriminant_Specifications (N));
16172       while Present (Discr) loop
16173          Enter_Name (Defining_Identifier (Discr));
16174
16175          --  For navigation purposes we add a reference to the discriminant
16176          --  in the entity for the type. If the current declaration is a
16177          --  completion, place references on the partial view. Otherwise the
16178          --  type is the current scope.
16179
16180          if Present (Prev) then
16181
16182             --  The references go on the partial view, if present. If the
16183             --  partial view has discriminants, the references have been
16184             --  generated already.
16185
16186             if not Has_Discriminants (Prev) then
16187                Generate_Reference (Prev, Defining_Identifier (Discr), 'd');
16188             end if;
16189          else
16190             Generate_Reference
16191               (Current_Scope, Defining_Identifier (Discr), 'd');
16192          end if;
16193
16194          if Nkind (Discriminant_Type (Discr)) = N_Access_Definition then
16195             Discr_Type := Access_Definition (Discr, Discriminant_Type (Discr));
16196
16197             --  Ada 2005 (AI-254)
16198
16199             if Present (Access_To_Subprogram_Definition
16200                          (Discriminant_Type (Discr)))
16201               and then Protected_Present (Access_To_Subprogram_Definition
16202                                            (Discriminant_Type (Discr)))
16203             then
16204                Discr_Type :=
16205                  Replace_Anonymous_Access_To_Protected_Subprogram (Discr);
16206             end if;
16207
16208          else
16209             Find_Type (Discriminant_Type (Discr));
16210             Discr_Type := Etype (Discriminant_Type (Discr));
16211
16212             if Error_Posted (Discriminant_Type (Discr)) then
16213                Discr_Type := Any_Type;
16214             end if;
16215          end if;
16216
16217          if Is_Access_Type (Discr_Type) then
16218
16219             --  Ada 2005 (AI-230): Access discriminant allowed in non-limited
16220             --  record types
16221
16222             if Ada_Version < Ada_2005 then
16223                Check_Access_Discriminant_Requires_Limited
16224                  (Discr, Discriminant_Type (Discr));
16225             end if;
16226
16227             if Ada_Version = Ada_83 and then Comes_From_Source (Discr) then
16228                Error_Msg_N
16229                  ("(Ada 83) access discriminant not allowed", Discr);
16230             end if;
16231
16232          elsif not Is_Discrete_Type (Discr_Type) then
16233             Error_Msg_N ("discriminants must have a discrete or access type",
16234               Discriminant_Type (Discr));
16235          end if;
16236
16237          Set_Etype (Defining_Identifier (Discr), Discr_Type);
16238
16239          --  If a discriminant specification includes the assignment compound
16240          --  delimiter followed by an expression, the expression is the default
16241          --  expression of the discriminant; the default expression must be of
16242          --  the type of the discriminant. (RM 3.7.1) Since this expression is
16243          --  a default expression, we do the special preanalysis, since this
16244          --  expression does not freeze (see "Handling of Default and Per-
16245          --  Object Expressions" in spec of package Sem).
16246
16247          if Present (Expression (Discr)) then
16248             Preanalyze_Spec_Expression (Expression (Discr), Discr_Type);
16249
16250             if Nkind (N) = N_Formal_Type_Declaration then
16251                Error_Msg_N
16252                  ("discriminant defaults not allowed for formal type",
16253                   Expression (Discr));
16254
16255             --  Tagged types declarations cannot have defaulted discriminants,
16256             --  but an untagged private type with defaulted discriminants can
16257             --  have a tagged completion.
16258
16259             elsif Is_Tagged_Type (Current_Scope)
16260               and then Comes_From_Source (N)
16261             then
16262                Error_Msg_N
16263                  ("discriminants of tagged type cannot have defaults",
16264                   Expression (Discr));
16265
16266             else
16267                Default_Present := True;
16268                Append_Elmt (Expression (Discr), Elist);
16269
16270                --  Tag the defining identifiers for the discriminants with
16271                --  their corresponding default expressions from the tree.
16272
16273                Set_Discriminant_Default_Value
16274                  (Defining_Identifier (Discr), Expression (Discr));
16275             end if;
16276
16277          else
16278             Default_Not_Present := True;
16279          end if;
16280
16281          --  Ada 2005 (AI-231): Create an Itype that is a duplicate of
16282          --  Discr_Type but with the null-exclusion attribute
16283
16284          if Ada_Version >= Ada_2005 then
16285
16286             --  Ada 2005 (AI-231): Static checks
16287
16288             if Can_Never_Be_Null (Discr_Type) then
16289                Null_Exclusion_Static_Checks (Discr);
16290
16291             elsif Is_Access_Type (Discr_Type)
16292               and then Null_Exclusion_Present (Discr)
16293
16294                --  No need to check itypes because in their case this check
16295                --  was done at their point of creation
16296
16297               and then not Is_Itype (Discr_Type)
16298             then
16299                if Can_Never_Be_Null (Discr_Type) then
16300                   Error_Msg_NE
16301                     ("`NOT NULL` not allowed (& already excludes null)",
16302                      Discr,
16303                      Discr_Type);
16304                end if;
16305
16306                Set_Etype (Defining_Identifier (Discr),
16307                  Create_Null_Excluding_Itype
16308                    (T           => Discr_Type,
16309                     Related_Nod => Discr));
16310
16311             --  Check for improper null exclusion if the type is otherwise
16312             --  legal for a discriminant.
16313
16314             elsif Null_Exclusion_Present (Discr)
16315               and then Is_Discrete_Type (Discr_Type)
16316             then
16317                Error_Msg_N
16318                  ("null exclusion can only apply to an access type", Discr);
16319             end if;
16320
16321             --  Ada 2005 (AI-402): access discriminants of nonlimited types
16322             --  can't have defaults. Synchronized types, or types that are
16323             --  explicitly limited are fine, but special tests apply to derived
16324             --  types in generics: in a generic body we have to assume the
16325             --  worst, and therefore defaults are not allowed if the parent is
16326             --  a generic formal private type (see ACATS B370001).
16327
16328             if Is_Access_Type (Discr_Type) then
16329                if Ekind (Discr_Type) /= E_Anonymous_Access_Type
16330                  or else not Default_Present
16331                  or else Is_Limited_Record (Current_Scope)
16332                  or else Is_Concurrent_Type (Current_Scope)
16333                  or else Is_Concurrent_Record_Type (Current_Scope)
16334                  or else Ekind (Current_Scope) = E_Limited_Private_Type
16335                then
16336                   if not Is_Derived_Type (Current_Scope)
16337                     or else not Is_Generic_Type (Etype (Current_Scope))
16338                     or else not In_Package_Body (Scope (Etype (Current_Scope)))
16339                     or else Limited_Present
16340                               (Type_Definition (Parent (Current_Scope)))
16341                   then
16342                      null;
16343
16344                   else
16345                      Error_Msg_N ("access discriminants of nonlimited types",
16346                          Expression (Discr));
16347                      Error_Msg_N ("\cannot have defaults", Expression (Discr));
16348                   end if;
16349
16350                elsif Present (Expression (Discr)) then
16351                   Error_Msg_N
16352                     ("(Ada 2005) access discriminants of nonlimited types",
16353                      Expression (Discr));
16354                   Error_Msg_N ("\cannot have defaults", Expression (Discr));
16355                end if;
16356             end if;
16357          end if;
16358
16359          Next (Discr);
16360       end loop;
16361
16362       --  An element list consisting of the default expressions of the
16363       --  discriminants is constructed in the above loop and used to set
16364       --  the Discriminant_Constraint attribute for the type. If an object
16365       --  is declared of this (record or task) type without any explicit
16366       --  discriminant constraint given, this element list will form the
16367       --  actual parameters for the corresponding initialization procedure
16368       --  for the type.
16369
16370       Set_Discriminant_Constraint (Current_Scope, Elist);
16371       Set_Stored_Constraint (Current_Scope, No_Elist);
16372
16373       --  Default expressions must be provided either for all or for none
16374       --  of the discriminants of a discriminant part. (RM 3.7.1)
16375
16376       if Default_Present and then Default_Not_Present then
16377          Error_Msg_N
16378            ("incomplete specification of defaults for discriminants", N);
16379       end if;
16380
16381       --  The use of the name of a discriminant is not allowed in default
16382       --  expressions of a discriminant part if the specification of the
16383       --  discriminant is itself given in the discriminant part. (RM 3.7.1)
16384
16385       --  To detect this, the discriminant names are entered initially with an
16386       --  Ekind of E_Void (which is the default Ekind given by Enter_Name). Any
16387       --  attempt to use a void entity (for example in an expression that is
16388       --  type-checked) produces the error message: premature usage. Now after
16389       --  completing the semantic analysis of the discriminant part, we can set
16390       --  the Ekind of all the discriminants appropriately.
16391
16392       Discr := First (Discriminant_Specifications (N));
16393       Discr_Number := Uint_1;
16394       while Present (Discr) loop
16395          Id := Defining_Identifier (Discr);
16396          Set_Ekind (Id, E_Discriminant);
16397          Init_Component_Location (Id);
16398          Init_Esize (Id);
16399          Set_Discriminant_Number (Id, Discr_Number);
16400
16401          --  Make sure this is always set, even in illegal programs
16402
16403          Set_Corresponding_Discriminant (Id, Empty);
16404
16405          --  Initialize the Original_Record_Component to the entity itself.
16406          --  Inherit_Components will propagate the right value to
16407          --  discriminants in derived record types.
16408
16409          Set_Original_Record_Component (Id, Id);
16410
16411          --  Create the discriminal for the discriminant
16412
16413          Build_Discriminal (Id);
16414
16415          Next (Discr);
16416          Discr_Number := Discr_Number + 1;
16417       end loop;
16418
16419       Set_Has_Discriminants (Current_Scope);
16420    end Process_Discriminants;
16421
16422    -----------------------
16423    -- Process_Full_View --
16424    -----------------------
16425
16426    procedure Process_Full_View (N : Node_Id; Full_T, Priv_T : Entity_Id) is
16427       Priv_Parent : Entity_Id;
16428       Full_Parent : Entity_Id;
16429       Full_Indic  : Node_Id;
16430
16431       procedure Collect_Implemented_Interfaces
16432         (Typ    : Entity_Id;
16433          Ifaces : Elist_Id);
16434       --  Ada 2005: Gather all the interfaces that Typ directly or
16435       --  inherently implements. Duplicate entries are not added to
16436       --  the list Ifaces.
16437
16438       ------------------------------------
16439       -- Collect_Implemented_Interfaces --
16440       ------------------------------------
16441
16442       procedure Collect_Implemented_Interfaces
16443         (Typ    : Entity_Id;
16444          Ifaces : Elist_Id)
16445       is
16446          Iface      : Entity_Id;
16447          Iface_Elmt : Elmt_Id;
16448
16449       begin
16450          --  Abstract interfaces are only associated with tagged record types
16451
16452          if not Is_Tagged_Type (Typ)
16453            or else not Is_Record_Type (Typ)
16454          then
16455             return;
16456          end if;
16457
16458          --  Recursively climb to the ancestors
16459
16460          if Etype (Typ) /= Typ
16461
16462             --  Protect the frontend against wrong cyclic declarations like:
16463
16464             --     type B is new A with private;
16465             --     type C is new A with private;
16466             --  private
16467             --     type B is new C with null record;
16468             --     type C is new B with null record;
16469
16470            and then Etype (Typ) /= Priv_T
16471            and then Etype (Typ) /= Full_T
16472          then
16473             --  Keep separate the management of private type declarations
16474
16475             if Ekind (Typ) = E_Record_Type_With_Private then
16476
16477                --  Handle the following erronous case:
16478                --      type Private_Type is tagged private;
16479                --   private
16480                --      type Private_Type is new Type_Implementing_Iface;
16481
16482                if Present (Full_View (Typ))
16483                  and then Etype (Typ) /= Full_View (Typ)
16484                then
16485                   if Is_Interface (Etype (Typ)) then
16486                      Append_Unique_Elmt (Etype (Typ), Ifaces);
16487                   end if;
16488
16489                   Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16490                end if;
16491
16492             --  Non-private types
16493
16494             else
16495                if Is_Interface (Etype (Typ)) then
16496                   Append_Unique_Elmt (Etype (Typ), Ifaces);
16497                end if;
16498
16499                Collect_Implemented_Interfaces (Etype (Typ), Ifaces);
16500             end if;
16501          end if;
16502
16503          --  Handle entities in the list of abstract interfaces
16504
16505          if Present (Interfaces (Typ)) then
16506             Iface_Elmt := First_Elmt (Interfaces (Typ));
16507             while Present (Iface_Elmt) loop
16508                Iface := Node (Iface_Elmt);
16509
16510                pragma Assert (Is_Interface (Iface));
16511
16512                if not Contain_Interface (Iface, Ifaces) then
16513                   Append_Elmt (Iface, Ifaces);
16514                   Collect_Implemented_Interfaces (Iface, Ifaces);
16515                end if;
16516
16517                Next_Elmt (Iface_Elmt);
16518             end loop;
16519          end if;
16520       end Collect_Implemented_Interfaces;
16521
16522    --  Start of processing for Process_Full_View
16523
16524    begin
16525       --  First some sanity checks that must be done after semantic
16526       --  decoration of the full view and thus cannot be placed with other
16527       --  similar checks in Find_Type_Name
16528
16529       if not Is_Limited_Type (Priv_T)
16530         and then (Is_Limited_Type (Full_T)
16531                    or else Is_Limited_Composite (Full_T))
16532       then
16533          Error_Msg_N
16534            ("completion of nonlimited type cannot be limited", Full_T);
16535          Explain_Limited_Type (Full_T, Full_T);
16536
16537       elsif Is_Abstract_Type (Full_T)
16538         and then not Is_Abstract_Type (Priv_T)
16539       then
16540          Error_Msg_N
16541            ("completion of nonabstract type cannot be abstract", Full_T);
16542
16543       elsif Is_Tagged_Type (Priv_T)
16544         and then Is_Limited_Type (Priv_T)
16545         and then not Is_Limited_Type (Full_T)
16546       then
16547          --  If pragma CPP_Class was applied to the private declaration
16548          --  propagate the limitedness to the full-view
16549
16550          if Is_CPP_Class (Priv_T) then
16551             Set_Is_Limited_Record (Full_T);
16552
16553          --  GNAT allow its own definition of Limited_Controlled to disobey
16554          --  this rule in order in ease the implementation. The next test is
16555          --  safe because Root_Controlled is defined in a private system child
16556
16557          elsif Etype (Full_T) = Full_View (RTE (RE_Root_Controlled)) then
16558             Set_Is_Limited_Composite (Full_T);
16559          else
16560             Error_Msg_N
16561               ("completion of limited tagged type must be limited", Full_T);
16562          end if;
16563
16564       elsif Is_Generic_Type (Priv_T) then
16565          Error_Msg_N ("generic type cannot have a completion", Full_T);
16566       end if;
16567
16568       --  Check that ancestor interfaces of private and full views are
16569       --  consistent. We omit this check for synchronized types because
16570       --  they are performed on the corresponding record type when frozen.
16571
16572       if Ada_Version >= Ada_2005
16573         and then Is_Tagged_Type (Priv_T)
16574         and then Is_Tagged_Type (Full_T)
16575         and then not Is_Concurrent_Type (Full_T)
16576       then
16577          declare
16578             Iface         : Entity_Id;
16579             Priv_T_Ifaces : constant Elist_Id := New_Elmt_List;
16580             Full_T_Ifaces : constant Elist_Id := New_Elmt_List;
16581
16582          begin
16583             Collect_Implemented_Interfaces (Priv_T, Priv_T_Ifaces);
16584             Collect_Implemented_Interfaces (Full_T, Full_T_Ifaces);
16585
16586             --  Ada 2005 (AI-251): The partial view shall be a descendant of
16587             --  an interface type if and only if the full type is descendant
16588             --  of the interface type (AARM 7.3 (7.3/2).
16589
16590             Iface := Find_Hidden_Interface (Priv_T_Ifaces, Full_T_Ifaces);
16591
16592             if Present (Iface) then
16593                Error_Msg_NE
16594                  ("interface & not implemented by full type " &
16595                   "(RM-2005 7.3 (7.3/2))", Priv_T, Iface);
16596             end if;
16597
16598             Iface := Find_Hidden_Interface (Full_T_Ifaces, Priv_T_Ifaces);
16599
16600             if Present (Iface) then
16601                Error_Msg_NE
16602                  ("interface & not implemented by partial view " &
16603                   "(RM-2005 7.3 (7.3/2))", Full_T, Iface);
16604             end if;
16605          end;
16606       end if;
16607
16608       if Is_Tagged_Type (Priv_T)
16609         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16610         and then Is_Derived_Type (Full_T)
16611       then
16612          Priv_Parent := Etype (Priv_T);
16613
16614          --  The full view of a private extension may have been transformed
16615          --  into an unconstrained derived type declaration and a subtype
16616          --  declaration (see build_derived_record_type for details).
16617
16618          if Nkind (N) = N_Subtype_Declaration then
16619             Full_Indic  := Subtype_Indication (N);
16620             Full_Parent := Etype (Base_Type (Full_T));
16621          else
16622             Full_Indic  := Subtype_Indication (Type_Definition (N));
16623             Full_Parent := Etype (Full_T);
16624          end if;
16625
16626          --  Check that the parent type of the full type is a descendant of
16627          --  the ancestor subtype given in the private extension. If either
16628          --  entity has an Etype equal to Any_Type then we had some previous
16629          --  error situation [7.3(8)].
16630
16631          if Priv_Parent = Any_Type or else Full_Parent = Any_Type then
16632             return;
16633
16634          --  Ada 2005 (AI-251): Interfaces in the full-typ can be given in
16635          --  any order. Therefore we don't have to check that its parent must
16636          --  be a descendant of the parent of the private type declaration.
16637
16638          elsif Is_Interface (Priv_Parent)
16639            and then Is_Interface (Full_Parent)
16640          then
16641             null;
16642
16643          --  Ada 2005 (AI-251): If the parent of the private type declaration
16644          --  is an interface there is no need to check that it is an ancestor
16645          --  of the associated full type declaration. The required tests for
16646          --  this case are performed by Build_Derived_Record_Type.
16647
16648          elsif not Is_Interface (Base_Type (Priv_Parent))
16649            and then not Is_Ancestor (Base_Type (Priv_Parent), Full_Parent)
16650          then
16651             Error_Msg_N
16652               ("parent of full type must descend from parent"
16653                   & " of private extension", Full_Indic);
16654
16655          --  Check the rules of 7.3(10): if the private extension inherits
16656          --  known discriminants, then the full type must also inherit those
16657          --  discriminants from the same (ancestor) type, and the parent
16658          --  subtype of the full type must be constrained if and only if
16659          --  the ancestor subtype of the private extension is constrained.
16660
16661          elsif No (Discriminant_Specifications (Parent (Priv_T)))
16662            and then not Has_Unknown_Discriminants (Priv_T)
16663            and then Has_Discriminants (Base_Type (Priv_Parent))
16664          then
16665             declare
16666                Priv_Indic  : constant Node_Id :=
16667                                Subtype_Indication (Parent (Priv_T));
16668
16669                Priv_Constr : constant Boolean :=
16670                                Is_Constrained (Priv_Parent)
16671                                  or else
16672                                    Nkind (Priv_Indic) = N_Subtype_Indication
16673                                  or else Is_Constrained (Entity (Priv_Indic));
16674
16675                Full_Constr : constant Boolean :=
16676                                Is_Constrained (Full_Parent)
16677                                  or else
16678                                    Nkind (Full_Indic) = N_Subtype_Indication
16679                                  or else Is_Constrained (Entity (Full_Indic));
16680
16681                Priv_Discr : Entity_Id;
16682                Full_Discr : Entity_Id;
16683
16684             begin
16685                Priv_Discr := First_Discriminant (Priv_Parent);
16686                Full_Discr := First_Discriminant (Full_Parent);
16687                while Present (Priv_Discr) and then Present (Full_Discr) loop
16688                   if Original_Record_Component (Priv_Discr) =
16689                      Original_Record_Component (Full_Discr)
16690                     or else
16691                      Corresponding_Discriminant (Priv_Discr) =
16692                      Corresponding_Discriminant (Full_Discr)
16693                   then
16694                      null;
16695                   else
16696                      exit;
16697                   end if;
16698
16699                   Next_Discriminant (Priv_Discr);
16700                   Next_Discriminant (Full_Discr);
16701                end loop;
16702
16703                if Present (Priv_Discr) or else Present (Full_Discr) then
16704                   Error_Msg_N
16705                     ("full view must inherit discriminants of the parent type"
16706                      & " used in the private extension", Full_Indic);
16707
16708                elsif Priv_Constr and then not Full_Constr then
16709                   Error_Msg_N
16710                     ("parent subtype of full type must be constrained",
16711                      Full_Indic);
16712
16713                elsif Full_Constr and then not Priv_Constr then
16714                   Error_Msg_N
16715                     ("parent subtype of full type must be unconstrained",
16716                      Full_Indic);
16717                end if;
16718             end;
16719
16720          --  Check the rules of 7.3(12): if a partial view has neither known
16721          --  or unknown discriminants, then the full type declaration shall
16722          --  define a definite subtype.
16723
16724          elsif      not Has_Unknown_Discriminants (Priv_T)
16725            and then not Has_Discriminants (Priv_T)
16726            and then not Is_Constrained (Full_T)
16727          then
16728             Error_Msg_N
16729               ("full view must define a constrained type if partial view"
16730                 & " has no discriminants", Full_T);
16731          end if;
16732
16733          --  ??????? Do we implement the following properly ?????
16734          --  If the ancestor subtype of a private extension has constrained
16735          --  discriminants, then the parent subtype of the full view shall
16736          --  impose a statically matching constraint on those discriminants
16737          --  [7.3(13)].
16738
16739       else
16740          --  For untagged types, verify that a type without discriminants
16741          --  is not completed with an unconstrained type.
16742
16743          if not Is_Indefinite_Subtype (Priv_T)
16744            and then Is_Indefinite_Subtype (Full_T)
16745          then
16746             Error_Msg_N ("full view of type must be definite subtype", Full_T);
16747          end if;
16748       end if;
16749
16750       --  AI-419: verify that the use of "limited" is consistent
16751
16752       declare
16753          Orig_Decl : constant Node_Id := Original_Node (N);
16754
16755       begin
16756          if Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16757            and then not Limited_Present (Parent (Priv_T))
16758            and then not Synchronized_Present (Parent (Priv_T))
16759            and then Nkind (Orig_Decl) = N_Full_Type_Declaration
16760            and then Nkind
16761              (Type_Definition (Orig_Decl)) = N_Derived_Type_Definition
16762            and then Limited_Present (Type_Definition (Orig_Decl))
16763          then
16764             Error_Msg_N
16765               ("full view of non-limited extension cannot be limited", N);
16766          end if;
16767       end;
16768
16769       --  Ada 2005 (AI-443): A synchronized private extension must be
16770       --  completed by a task or protected type.
16771
16772       if Ada_Version >= Ada_2005
16773         and then Nkind (Parent (Priv_T)) = N_Private_Extension_Declaration
16774         and then Synchronized_Present (Parent (Priv_T))
16775         and then not Is_Concurrent_Type (Full_T)
16776       then
16777          Error_Msg_N ("full view of synchronized extension must " &
16778                       "be synchronized type", N);
16779       end if;
16780
16781       --  Ada 2005 AI-363: if the full view has discriminants with
16782       --  defaults, it is illegal to declare constrained access subtypes
16783       --  whose designated type is the current type. This allows objects
16784       --  of the type that are declared in the heap to be unconstrained.
16785
16786       if not Has_Unknown_Discriminants (Priv_T)
16787         and then not Has_Discriminants (Priv_T)
16788         and then Has_Discriminants (Full_T)
16789         and then
16790           Present (Discriminant_Default_Value (First_Discriminant (Full_T)))
16791       then
16792          Set_Has_Constrained_Partial_View (Full_T);
16793          Set_Has_Constrained_Partial_View (Priv_T);
16794       end if;
16795
16796       --  Create a full declaration for all its subtypes recorded in
16797       --  Private_Dependents and swap them similarly to the base type. These
16798       --  are subtypes that have been define before the full declaration of
16799       --  the private type. We also swap the entry in Private_Dependents list
16800       --  so we can properly restore the private view on exit from the scope.
16801
16802       declare
16803          Priv_Elmt : Elmt_Id;
16804          Priv      : Entity_Id;
16805          Full      : Entity_Id;
16806
16807       begin
16808          Priv_Elmt := First_Elmt (Private_Dependents (Priv_T));
16809          while Present (Priv_Elmt) loop
16810             Priv := Node (Priv_Elmt);
16811
16812             if Ekind_In (Priv, E_Private_Subtype,
16813                                E_Limited_Private_Subtype,
16814                                E_Record_Subtype_With_Private)
16815             then
16816                Full := Make_Defining_Identifier (Sloc (Priv), Chars (Priv));
16817                Set_Is_Itype (Full);
16818                Set_Parent (Full, Parent (Priv));
16819                Set_Associated_Node_For_Itype (Full, N);
16820
16821                --  Now we need to complete the private subtype, but since the
16822                --  base type has already been swapped, we must also swap the
16823                --  subtypes (and thus, reverse the arguments in the call to
16824                --  Complete_Private_Subtype).
16825
16826                Copy_And_Swap (Priv, Full);
16827                Complete_Private_Subtype (Full, Priv, Full_T, N);
16828                Replace_Elmt (Priv_Elmt, Full);
16829             end if;
16830
16831             Next_Elmt (Priv_Elmt);
16832          end loop;
16833       end;
16834
16835       --  If the private view was tagged, copy the new primitive operations
16836       --  from the private view to the full view.
16837
16838       if Is_Tagged_Type (Full_T) then
16839          declare
16840             Disp_Typ  : Entity_Id;
16841             Full_List : Elist_Id;
16842             Prim      : Entity_Id;
16843             Prim_Elmt : Elmt_Id;
16844             Priv_List : Elist_Id;
16845
16846             function Contains
16847               (E : Entity_Id;
16848                L : Elist_Id) return Boolean;
16849             --  Determine whether list L contains element E
16850
16851             --------------
16852             -- Contains --
16853             --------------
16854
16855             function Contains
16856               (E : Entity_Id;
16857                L : Elist_Id) return Boolean
16858             is
16859                List_Elmt : Elmt_Id;
16860
16861             begin
16862                List_Elmt := First_Elmt (L);
16863                while Present (List_Elmt) loop
16864                   if Node (List_Elmt) = E then
16865                      return True;
16866                   end if;
16867
16868                   Next_Elmt (List_Elmt);
16869                end loop;
16870
16871                return False;
16872             end Contains;
16873
16874          --  Start of processing
16875
16876          begin
16877             if Is_Tagged_Type (Priv_T) then
16878                Priv_List := Primitive_Operations (Priv_T);
16879                Prim_Elmt := First_Elmt (Priv_List);
16880
16881                --  In the case of a concurrent type completing a private tagged
16882                --  type, primitives may have been declared in between the two
16883                --  views. These subprograms need to be wrapped the same way
16884                --  entries and protected procedures are handled because they
16885                --  cannot be directly shared by the two views.
16886
16887                if Is_Concurrent_Type (Full_T) then
16888                   declare
16889                      Conc_Typ  : constant Entity_Id :=
16890                                    Corresponding_Record_Type (Full_T);
16891                      Curr_Nod  : Node_Id := Parent (Conc_Typ);
16892                      Wrap_Spec : Node_Id;
16893
16894                   begin
16895                      while Present (Prim_Elmt) loop
16896                         Prim := Node (Prim_Elmt);
16897
16898                         if Comes_From_Source (Prim)
16899                           and then not Is_Abstract_Subprogram (Prim)
16900                         then
16901                            Wrap_Spec :=
16902                              Make_Subprogram_Declaration (Sloc (Prim),
16903                                Specification =>
16904                                  Build_Wrapper_Spec
16905                                    (Subp_Id => Prim,
16906                                     Obj_Typ => Conc_Typ,
16907                                     Formals =>
16908                                       Parameter_Specifications (
16909                                         Parent (Prim))));
16910
16911                            Insert_After (Curr_Nod, Wrap_Spec);
16912                            Curr_Nod := Wrap_Spec;
16913
16914                            Analyze (Wrap_Spec);
16915                         end if;
16916
16917                         Next_Elmt (Prim_Elmt);
16918                      end loop;
16919
16920                      return;
16921                   end;
16922
16923                --  For non-concurrent types, transfer explicit primitives, but
16924                --  omit those inherited from the parent of the private view
16925                --  since they will be re-inherited later on.
16926
16927                else
16928                   Full_List := Primitive_Operations (Full_T);
16929
16930                   while Present (Prim_Elmt) loop
16931                      Prim := Node (Prim_Elmt);
16932
16933                      if Comes_From_Source (Prim)
16934                        and then not Contains (Prim, Full_List)
16935                      then
16936                         Append_Elmt (Prim, Full_List);
16937                      end if;
16938
16939                      Next_Elmt (Prim_Elmt);
16940                   end loop;
16941                end if;
16942
16943             --  Untagged private view
16944
16945             else
16946                Full_List := Primitive_Operations (Full_T);
16947
16948                --  In this case the partial view is untagged, so here we locate
16949                --  all of the earlier primitives that need to be treated as
16950                --  dispatching (those that appear between the two views). Note
16951                --  that these additional operations must all be new operations
16952                --  (any earlier operations that override inherited operations
16953                --  of the full view will already have been inserted in the
16954                --  primitives list, marked by Check_Operation_From_Private_View
16955                --  as dispatching. Note that implicit "/=" operators are
16956                --  excluded from being added to the primitives list since they
16957                --  shouldn't be treated as dispatching (tagged "/=" is handled
16958                --  specially).
16959
16960                Prim := Next_Entity (Full_T);
16961                while Present (Prim) and then Prim /= Priv_T loop
16962                   if Ekind_In (Prim, E_Procedure, E_Function) then
16963                      Disp_Typ := Find_Dispatching_Type (Prim);
16964
16965                      if Disp_Typ = Full_T
16966                        and then (Chars (Prim) /= Name_Op_Ne
16967                                   or else Comes_From_Source (Prim))
16968                      then
16969                         Check_Controlling_Formals (Full_T, Prim);
16970
16971                         if not Is_Dispatching_Operation (Prim) then
16972                            Append_Elmt (Prim, Full_List);
16973                            Set_Is_Dispatching_Operation (Prim, True);
16974                            Set_DT_Position (Prim, No_Uint);
16975                         end if;
16976
16977                      elsif Is_Dispatching_Operation (Prim)
16978                        and then Disp_Typ  /= Full_T
16979                      then
16980
16981                         --  Verify that it is not otherwise controlled by a
16982                         --  formal or a return value of type T.
16983
16984                         Check_Controlling_Formals (Disp_Typ, Prim);
16985                      end if;
16986                   end if;
16987
16988                   Next_Entity (Prim);
16989                end loop;
16990             end if;
16991
16992             --  For the tagged case, the two views can share the same primitive
16993             --  operations list and the same class-wide type. Update attributes
16994             --  of the class-wide type which depend on the full declaration.
16995
16996             if Is_Tagged_Type (Priv_T) then
16997                Set_Direct_Primitive_Operations (Priv_T, Full_List);
16998                Set_Class_Wide_Type
16999                  (Base_Type (Full_T), Class_Wide_Type (Priv_T));
17000
17001                Set_Has_Task (Class_Wide_Type (Priv_T), Has_Task (Full_T));
17002             end if;
17003          end;
17004       end if;
17005
17006       --  Ada 2005 AI 161: Check preelaboratable initialization consistency
17007
17008       if Known_To_Have_Preelab_Init (Priv_T) then
17009
17010          --  Case where there is a pragma Preelaborable_Initialization. We
17011          --  always allow this in predefined units, which is a bit of a kludge,
17012          --  but it means we don't have to struggle to meet the requirements in
17013          --  the RM for having Preelaborable Initialization. Otherwise we
17014          --  require that the type meets the RM rules. But we can't check that
17015          --  yet, because of the rule about overriding Ininitialize, so we
17016          --  simply set a flag that will be checked at freeze time.
17017
17018          if not In_Predefined_Unit (Full_T) then
17019             Set_Must_Have_Preelab_Init (Full_T);
17020          end if;
17021       end if;
17022
17023       --  If pragma CPP_Class was applied to the private type declaration,
17024       --  propagate it now to the full type declaration.
17025
17026       if Is_CPP_Class (Priv_T) then
17027          Set_Is_CPP_Class (Full_T);
17028          Set_Convention   (Full_T, Convention_CPP);
17029       end if;
17030
17031       --  If the private view has user specified stream attributes, then so has
17032       --  the full view.
17033
17034       if Has_Specified_Stream_Read (Priv_T) then
17035          Set_Has_Specified_Stream_Read (Full_T);
17036       end if;
17037       if Has_Specified_Stream_Write (Priv_T) then
17038          Set_Has_Specified_Stream_Write (Full_T);
17039       end if;
17040       if Has_Specified_Stream_Input (Priv_T) then
17041          Set_Has_Specified_Stream_Input (Full_T);
17042       end if;
17043       if Has_Specified_Stream_Output (Priv_T) then
17044          Set_Has_Specified_Stream_Output (Full_T);
17045       end if;
17046    end Process_Full_View;
17047
17048    -----------------------------------
17049    -- Process_Incomplete_Dependents --
17050    -----------------------------------
17051
17052    procedure Process_Incomplete_Dependents
17053      (N      : Node_Id;
17054       Full_T : Entity_Id;
17055       Inc_T  : Entity_Id)
17056    is
17057       Inc_Elmt : Elmt_Id;
17058       Priv_Dep : Entity_Id;
17059       New_Subt : Entity_Id;
17060
17061       Disc_Constraint : Elist_Id;
17062
17063    begin
17064       if No (Private_Dependents (Inc_T)) then
17065          return;
17066       end if;
17067
17068       --  Itypes that may be generated by the completion of an incomplete
17069       --  subtype are not used by the back-end and not attached to the tree.
17070       --  They are created only for constraint-checking purposes.
17071
17072       Inc_Elmt := First_Elmt (Private_Dependents (Inc_T));
17073       while Present (Inc_Elmt) loop
17074          Priv_Dep := Node (Inc_Elmt);
17075
17076          if Ekind (Priv_Dep) = E_Subprogram_Type then
17077
17078             --  An Access_To_Subprogram type may have a return type or a
17079             --  parameter type that is incomplete. Replace with the full view.
17080
17081             if Etype (Priv_Dep) = Inc_T then
17082                Set_Etype (Priv_Dep, Full_T);
17083             end if;
17084
17085             declare
17086                Formal : Entity_Id;
17087
17088             begin
17089                Formal := First_Formal (Priv_Dep);
17090                while Present (Formal) loop
17091                   if Etype (Formal) = Inc_T then
17092                      Set_Etype (Formal, Full_T);
17093                   end if;
17094
17095                   Next_Formal (Formal);
17096                end loop;
17097             end;
17098
17099          elsif Is_Overloadable (Priv_Dep) then
17100
17101             --  A protected operation is never dispatching: only its
17102             --  wrapper operation (which has convention Ada) is.
17103
17104             if Is_Tagged_Type (Full_T)
17105               and then Convention (Priv_Dep) /= Convention_Protected
17106             then
17107
17108                --  Subprogram has an access parameter whose designated type
17109                --  was incomplete. Reexamine declaration now, because it may
17110                --  be a primitive operation of the full type.
17111
17112                Check_Operation_From_Incomplete_Type (Priv_Dep, Inc_T);
17113                Set_Is_Dispatching_Operation (Priv_Dep);
17114                Check_Controlling_Formals (Full_T, Priv_Dep);
17115             end if;
17116
17117          elsif Ekind (Priv_Dep) = E_Subprogram_Body then
17118
17119             --  Can happen during processing of a body before the completion
17120             --  of a TA type. Ignore, because spec is also on dependent list.
17121
17122             return;
17123
17124          --  Ada 2005 (AI-412): Transform a regular incomplete subtype into a
17125          --  corresponding subtype of the full view.
17126
17127          elsif Ekind (Priv_Dep) = E_Incomplete_Subtype then
17128             Set_Subtype_Indication
17129               (Parent (Priv_Dep), New_Reference_To (Full_T, Sloc (Priv_Dep)));
17130             Set_Etype (Priv_Dep, Full_T);
17131             Set_Ekind (Priv_Dep, Subtype_Kind (Ekind (Full_T)));
17132             Set_Analyzed (Parent (Priv_Dep), False);
17133
17134             --  Reanalyze the declaration, suppressing the call to
17135             --  Enter_Name to avoid duplicate names.
17136
17137             Analyze_Subtype_Declaration
17138               (N    => Parent (Priv_Dep),
17139                Skip => True);
17140
17141          --  Dependent is a subtype
17142
17143          else
17144             --  We build a new subtype indication using the full view of the
17145             --  incomplete parent. The discriminant constraints have been
17146             --  elaborated already at the point of the subtype declaration.
17147
17148             New_Subt := Create_Itype (E_Void, N);
17149
17150             if Has_Discriminants (Full_T) then
17151                Disc_Constraint := Discriminant_Constraint (Priv_Dep);
17152             else
17153                Disc_Constraint := No_Elist;
17154             end if;
17155
17156             Build_Discriminated_Subtype (Full_T, New_Subt, Disc_Constraint, N);
17157             Set_Full_View (Priv_Dep, New_Subt);
17158          end if;
17159
17160          Next_Elmt (Inc_Elmt);
17161       end loop;
17162    end Process_Incomplete_Dependents;
17163
17164    --------------------------------
17165    -- Process_Range_Expr_In_Decl --
17166    --------------------------------
17167
17168    procedure Process_Range_Expr_In_Decl
17169      (R           : Node_Id;
17170       T           : Entity_Id;
17171       Check_List  : List_Id := Empty_List;
17172       R_Check_Off : Boolean := False)
17173    is
17174       Lo, Hi    : Node_Id;
17175       R_Checks  : Check_Result;
17176       Type_Decl : Node_Id;
17177       Def_Id    : Entity_Id;
17178
17179    begin
17180       Analyze_And_Resolve (R, Base_Type (T));
17181
17182       if Nkind (R) = N_Range then
17183          Lo := Low_Bound (R);
17184          Hi := High_Bound (R);
17185
17186          --  We need to ensure validity of the bounds here, because if we
17187          --  go ahead and do the expansion, then the expanded code will get
17188          --  analyzed with range checks suppressed and we miss the check.
17189
17190          Validity_Check_Range (R);
17191
17192          --  If there were errors in the declaration, try and patch up some
17193          --  common mistakes in the bounds. The cases handled are literals
17194          --  which are Integer where the expected type is Real and vice versa.
17195          --  These corrections allow the compilation process to proceed further
17196          --  along since some basic assumptions of the format of the bounds
17197          --  are guaranteed.
17198
17199          if Etype (R) = Any_Type then
17200
17201             if Nkind (Lo) = N_Integer_Literal and then Is_Real_Type (T) then
17202                Rewrite (Lo,
17203                  Make_Real_Literal (Sloc (Lo), UR_From_Uint (Intval (Lo))));
17204
17205             elsif Nkind (Hi) = N_Integer_Literal and then Is_Real_Type (T) then
17206                Rewrite (Hi,
17207                  Make_Real_Literal (Sloc (Hi), UR_From_Uint (Intval (Hi))));
17208
17209             elsif Nkind (Lo) = N_Real_Literal and then Is_Integer_Type (T) then
17210                Rewrite (Lo,
17211                  Make_Integer_Literal (Sloc (Lo), UR_To_Uint (Realval (Lo))));
17212
17213             elsif Nkind (Hi) = N_Real_Literal and then Is_Integer_Type (T) then
17214                Rewrite (Hi,
17215                  Make_Integer_Literal (Sloc (Hi), UR_To_Uint (Realval (Hi))));
17216             end if;
17217
17218             Set_Etype (Lo, T);
17219             Set_Etype (Hi, T);
17220          end if;
17221
17222          --  If the bounds of the range have been mistakenly given as string
17223          --  literals (perhaps in place of character literals), then an error
17224          --  has already been reported, but we rewrite the string literal as a
17225          --  bound of the range's type to avoid blowups in later processing
17226          --  that looks at static values.
17227
17228          if Nkind (Lo) = N_String_Literal then
17229             Rewrite (Lo,
17230               Make_Attribute_Reference (Sloc (Lo),
17231                 Attribute_Name => Name_First,
17232                 Prefix => New_Reference_To (T, Sloc (Lo))));
17233             Analyze_And_Resolve (Lo);
17234          end if;
17235
17236          if Nkind (Hi) = N_String_Literal then
17237             Rewrite (Hi,
17238               Make_Attribute_Reference (Sloc (Hi),
17239                 Attribute_Name => Name_First,
17240                 Prefix => New_Reference_To (T, Sloc (Hi))));
17241             Analyze_And_Resolve (Hi);
17242          end if;
17243
17244          --  If bounds aren't scalar at this point then exit, avoiding
17245          --  problems with further processing of the range in this procedure.
17246
17247          if not Is_Scalar_Type (Etype (Lo)) then
17248             return;
17249          end if;
17250
17251          --  Resolve (actually Sem_Eval) has checked that the bounds are in
17252          --  then range of the base type. Here we check whether the bounds
17253          --  are in the range of the subtype itself. Note that if the bounds
17254          --  represent the null range the Constraint_Error exception should
17255          --  not be raised.
17256
17257          --  ??? The following code should be cleaned up as follows
17258
17259          --  1. The Is_Null_Range (Lo, Hi) test should disappear since it
17260          --     is done in the call to Range_Check (R, T); below
17261
17262          --  2. The use of R_Check_Off should be investigated and possibly
17263          --     removed, this would clean up things a bit.
17264
17265          if Is_Null_Range (Lo, Hi) then
17266             null;
17267
17268          else
17269             --  Capture values of bounds and generate temporaries for them
17270             --  if needed, before applying checks, since checks may cause
17271             --  duplication of the expression without forcing evaluation.
17272
17273             if Expander_Active then
17274                Force_Evaluation (Lo);
17275                Force_Evaluation (Hi);
17276             end if;
17277
17278             --  We use a flag here instead of suppressing checks on the
17279             --  type because the type we check against isn't necessarily
17280             --  the place where we put the check.
17281
17282             if not R_Check_Off then
17283                R_Checks := Get_Range_Checks (R, T);
17284
17285                --  Look up tree to find an appropriate insertion point.
17286                --  This seems really junk code, and very brittle, couldn't
17287                --  we just use an insert actions call of some kind ???
17288
17289                Type_Decl := Parent (R);
17290                while Present (Type_Decl) and then not
17291                  (Nkind_In (Type_Decl, N_Full_Type_Declaration,
17292                                        N_Subtype_Declaration,
17293                                        N_Loop_Statement,
17294                                        N_Task_Type_Declaration)
17295                     or else
17296                   Nkind_In (Type_Decl, N_Single_Task_Declaration,
17297                                        N_Protected_Type_Declaration,
17298                                        N_Single_Protected_Declaration))
17299                loop
17300                   Type_Decl := Parent (Type_Decl);
17301                end loop;
17302
17303                --  Why would Type_Decl not be present???  Without this test,
17304                --  short regression tests fail.
17305
17306                if Present (Type_Decl) then
17307
17308                   --  Case of loop statement (more comments ???)
17309
17310                   if Nkind (Type_Decl) = N_Loop_Statement then
17311                      declare
17312                         Indic : Node_Id;
17313
17314                      begin
17315                         Indic := Parent (R);
17316                         while Present (Indic)
17317                           and then Nkind (Indic) /= N_Subtype_Indication
17318                         loop
17319                            Indic := Parent (Indic);
17320                         end loop;
17321
17322                         if Present (Indic) then
17323                            Def_Id := Etype (Subtype_Mark (Indic));
17324
17325                            Insert_Range_Checks
17326                              (R_Checks,
17327                               Type_Decl,
17328                               Def_Id,
17329                               Sloc (Type_Decl),
17330                               R,
17331                               Do_Before => True);
17332                         end if;
17333                      end;
17334
17335                   --  All other cases (more comments ???)
17336
17337                   else
17338                      Def_Id := Defining_Identifier (Type_Decl);
17339
17340                      if (Ekind (Def_Id) = E_Record_Type
17341                           and then Depends_On_Discriminant (R))
17342                        or else
17343                         (Ekind (Def_Id) = E_Protected_Type
17344                           and then Has_Discriminants (Def_Id))
17345                      then
17346                         Append_Range_Checks
17347                           (R_Checks, Check_List, Def_Id, Sloc (Type_Decl), R);
17348
17349                      else
17350                         Insert_Range_Checks
17351                           (R_Checks, Type_Decl, Def_Id, Sloc (Type_Decl), R);
17352
17353                      end if;
17354                   end if;
17355                end if;
17356             end if;
17357          end if;
17358
17359       elsif Expander_Active then
17360          Get_Index_Bounds (R, Lo, Hi);
17361          Force_Evaluation (Lo);
17362          Force_Evaluation (Hi);
17363       end if;
17364    end Process_Range_Expr_In_Decl;
17365
17366    --------------------------------------
17367    -- Process_Real_Range_Specification --
17368    --------------------------------------
17369
17370    procedure Process_Real_Range_Specification (Def : Node_Id) is
17371       Spec : constant Node_Id := Real_Range_Specification (Def);
17372       Lo   : Node_Id;
17373       Hi   : Node_Id;
17374       Err  : Boolean := False;
17375
17376       procedure Analyze_Bound (N : Node_Id);
17377       --  Analyze and check one bound
17378
17379       -------------------
17380       -- Analyze_Bound --
17381       -------------------
17382
17383       procedure Analyze_Bound (N : Node_Id) is
17384       begin
17385          Analyze_And_Resolve (N, Any_Real);
17386
17387          if not Is_OK_Static_Expression (N) then
17388             Flag_Non_Static_Expr
17389               ("bound in real type definition is not static!", N);
17390             Err := True;
17391          end if;
17392       end Analyze_Bound;
17393
17394    --  Start of processing for Process_Real_Range_Specification
17395
17396    begin
17397       if Present (Spec) then
17398          Lo := Low_Bound (Spec);
17399          Hi := High_Bound (Spec);
17400          Analyze_Bound (Lo);
17401          Analyze_Bound (Hi);
17402
17403          --  If error, clear away junk range specification
17404
17405          if Err then
17406             Set_Real_Range_Specification (Def, Empty);
17407          end if;
17408       end if;
17409    end Process_Real_Range_Specification;
17410
17411    ---------------------
17412    -- Process_Subtype --
17413    ---------------------
17414
17415    function Process_Subtype
17416      (S           : Node_Id;
17417       Related_Nod : Node_Id;
17418       Related_Id  : Entity_Id := Empty;
17419       Suffix      : Character := ' ') return Entity_Id
17420    is
17421       P               : Node_Id;
17422       Def_Id          : Entity_Id;
17423       Error_Node      : Node_Id;
17424       Full_View_Id    : Entity_Id;
17425       Subtype_Mark_Id : Entity_Id;
17426
17427       May_Have_Null_Exclusion : Boolean;
17428
17429       procedure Check_Incomplete (T : Entity_Id);
17430       --  Called to verify that an incomplete type is not used prematurely
17431
17432       ----------------------
17433       -- Check_Incomplete --
17434       ----------------------
17435
17436       procedure Check_Incomplete (T : Entity_Id) is
17437       begin
17438          --  Ada 2005 (AI-412): Incomplete subtypes are legal
17439
17440          if Ekind (Root_Type (Entity (T))) = E_Incomplete_Type
17441            and then
17442              not (Ada_Version >= Ada_2005
17443                     and then
17444                        (Nkind (Parent (T)) = N_Subtype_Declaration
17445                           or else
17446                             (Nkind (Parent (T)) = N_Subtype_Indication
17447                                and then Nkind (Parent (Parent (T))) =
17448                                           N_Subtype_Declaration)))
17449          then
17450             Error_Msg_N ("invalid use of type before its full declaration", T);
17451          end if;
17452       end Check_Incomplete;
17453
17454    --  Start of processing for Process_Subtype
17455
17456    begin
17457       --  Case of no constraints present
17458
17459       if Nkind (S) /= N_Subtype_Indication then
17460          Find_Type (S);
17461          Check_Incomplete (S);
17462          P := Parent (S);
17463
17464          --  Ada 2005 (AI-231): Static check
17465
17466          if Ada_Version >= Ada_2005
17467            and then Present (P)
17468            and then Null_Exclusion_Present (P)
17469            and then Nkind (P) /= N_Access_To_Object_Definition
17470            and then not Is_Access_Type (Entity (S))
17471          then
17472             Error_Msg_N ("`NOT NULL` only allowed for an access type", S);
17473          end if;
17474
17475          --  The following is ugly, can't we have a range or even a flag???
17476
17477          May_Have_Null_Exclusion :=
17478            Nkind_In (P, N_Access_Definition,
17479                         N_Access_Function_Definition,
17480                         N_Access_Procedure_Definition,
17481                         N_Access_To_Object_Definition,
17482                         N_Allocator,
17483                         N_Component_Definition)
17484              or else
17485            Nkind_In (P, N_Derived_Type_Definition,
17486                         N_Discriminant_Specification,
17487                         N_Formal_Object_Declaration,
17488                         N_Object_Declaration,
17489                         N_Object_Renaming_Declaration,
17490                         N_Parameter_Specification,
17491                         N_Subtype_Declaration);
17492
17493          --  Create an Itype that is a duplicate of Entity (S) but with the
17494          --  null-exclusion attribute.
17495
17496          if May_Have_Null_Exclusion
17497            and then Is_Access_Type (Entity (S))
17498            and then Null_Exclusion_Present (P)
17499
17500             --  No need to check the case of an access to object definition.
17501             --  It is correct to define double not-null pointers.
17502
17503             --  Example:
17504             --     type Not_Null_Int_Ptr is not null access Integer;
17505             --     type Acc is not null access Not_Null_Int_Ptr;
17506
17507            and then Nkind (P) /= N_Access_To_Object_Definition
17508          then
17509             if Can_Never_Be_Null (Entity (S)) then
17510                case Nkind (Related_Nod) is
17511                   when N_Full_Type_Declaration =>
17512                      if Nkind (Type_Definition (Related_Nod))
17513                        in N_Array_Type_Definition
17514                      then
17515                         Error_Node :=
17516                           Subtype_Indication
17517                             (Component_Definition
17518                              (Type_Definition (Related_Nod)));
17519                      else
17520                         Error_Node :=
17521                           Subtype_Indication (Type_Definition (Related_Nod));
17522                      end if;
17523
17524                   when N_Subtype_Declaration =>
17525                      Error_Node := Subtype_Indication (Related_Nod);
17526
17527                   when N_Object_Declaration =>
17528                      Error_Node := Object_Definition (Related_Nod);
17529
17530                   when N_Component_Declaration =>
17531                      Error_Node :=
17532                        Subtype_Indication (Component_Definition (Related_Nod));
17533
17534                   when N_Allocator =>
17535                      Error_Node := Expression (Related_Nod);
17536
17537                   when others =>
17538                      pragma Assert (False);
17539                      Error_Node := Related_Nod;
17540                end case;
17541
17542                Error_Msg_NE
17543                  ("`NOT NULL` not allowed (& already excludes null)",
17544                   Error_Node,
17545                   Entity (S));
17546             end if;
17547
17548             Set_Etype  (S,
17549               Create_Null_Excluding_Itype
17550                 (T           => Entity (S),
17551                  Related_Nod => P));
17552             Set_Entity (S, Etype (S));
17553          end if;
17554
17555          return Entity (S);
17556
17557       --  Case of constraint present, so that we have an N_Subtype_Indication
17558       --  node (this node is created only if constraints are present).
17559
17560       else
17561          Find_Type (Subtype_Mark (S));
17562
17563          if Nkind (Parent (S)) /= N_Access_To_Object_Definition
17564            and then not
17565             (Nkind (Parent (S)) = N_Subtype_Declaration
17566               and then Is_Itype (Defining_Identifier (Parent (S))))
17567          then
17568             Check_Incomplete (Subtype_Mark (S));
17569          end if;
17570
17571          P := Parent (S);
17572          Subtype_Mark_Id := Entity (Subtype_Mark (S));
17573
17574          --  Explicit subtype declaration case
17575
17576          if Nkind (P) = N_Subtype_Declaration then
17577             Def_Id := Defining_Identifier (P);
17578
17579          --  Explicit derived type definition case
17580
17581          elsif Nkind (P) = N_Derived_Type_Definition then
17582             Def_Id := Defining_Identifier (Parent (P));
17583
17584          --  Implicit case, the Def_Id must be created as an implicit type.
17585          --  The one exception arises in the case of concurrent types, array
17586          --  and access types, where other subsidiary implicit types may be
17587          --  created and must appear before the main implicit type. In these
17588          --  cases we leave Def_Id set to Empty as a signal that Create_Itype
17589          --  has not yet been called to create Def_Id.
17590
17591          else
17592             if Is_Array_Type (Subtype_Mark_Id)
17593               or else Is_Concurrent_Type (Subtype_Mark_Id)
17594               or else Is_Access_Type (Subtype_Mark_Id)
17595             then
17596                Def_Id := Empty;
17597
17598             --  For the other cases, we create a new unattached Itype,
17599             --  and set the indication to ensure it gets attached later.
17600
17601             else
17602                Def_Id :=
17603                  Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
17604             end if;
17605          end if;
17606
17607          --  If the kind of constraint is invalid for this kind of type,
17608          --  then give an error, and then pretend no constraint was given.
17609
17610          if not Is_Valid_Constraint_Kind
17611                    (Ekind (Subtype_Mark_Id), Nkind (Constraint (S)))
17612          then
17613             Error_Msg_N
17614               ("incorrect constraint for this kind of type", Constraint (S));
17615
17616             Rewrite (S, New_Copy_Tree (Subtype_Mark (S)));
17617
17618             --  Set Ekind of orphan itype, to prevent cascaded errors
17619
17620             if Present (Def_Id) then
17621                Set_Ekind (Def_Id, Ekind (Any_Type));
17622             end if;
17623
17624             --  Make recursive call, having got rid of the bogus constraint
17625
17626             return Process_Subtype (S, Related_Nod, Related_Id, Suffix);
17627          end if;
17628
17629          --  Remaining processing depends on type
17630
17631          case Ekind (Subtype_Mark_Id) is
17632             when Access_Kind =>
17633                Constrain_Access (Def_Id, S, Related_Nod);
17634
17635                if Expander_Active
17636                  and then  Is_Itype (Designated_Type (Def_Id))
17637                  and then Nkind (Related_Nod) = N_Subtype_Declaration
17638                  and then not Is_Incomplete_Type (Designated_Type (Def_Id))
17639                then
17640                   Build_Itype_Reference
17641                     (Designated_Type (Def_Id), Related_Nod);
17642                end if;
17643
17644             when Array_Kind =>
17645                Constrain_Array (Def_Id, S, Related_Nod, Related_Id, Suffix);
17646
17647             when Decimal_Fixed_Point_Kind =>
17648                Constrain_Decimal (Def_Id, S);
17649
17650             when Enumeration_Kind =>
17651                Constrain_Enumeration (Def_Id, S);
17652
17653             when Ordinary_Fixed_Point_Kind =>
17654                Constrain_Ordinary_Fixed (Def_Id, S);
17655
17656             when Float_Kind =>
17657                Constrain_Float (Def_Id, S);
17658
17659             when Integer_Kind =>
17660                Constrain_Integer (Def_Id, S);
17661
17662             when E_Record_Type     |
17663                  E_Record_Subtype  |
17664                  Class_Wide_Kind   |
17665                  E_Incomplete_Type =>
17666                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
17667
17668                if Ekind (Def_Id) = E_Incomplete_Type then
17669                   Set_Private_Dependents (Def_Id, New_Elmt_List);
17670                end if;
17671
17672             when Private_Kind =>
17673                Constrain_Discriminated_Type (Def_Id, S, Related_Nod);
17674                Set_Private_Dependents (Def_Id, New_Elmt_List);
17675
17676                --  In case of an invalid constraint prevent further processing
17677                --  since the type constructed is missing expected fields.
17678
17679                if Etype (Def_Id) = Any_Type then
17680                   return Def_Id;
17681                end if;
17682
17683                --  If the full view is that of a task with discriminants,
17684                --  we must constrain both the concurrent type and its
17685                --  corresponding record type. Otherwise we will just propagate
17686                --  the constraint to the full view, if available.
17687
17688                if Present (Full_View (Subtype_Mark_Id))
17689                  and then Has_Discriminants (Subtype_Mark_Id)
17690                  and then Is_Concurrent_Type (Full_View (Subtype_Mark_Id))
17691                then
17692                   Full_View_Id :=
17693                     Create_Itype (E_Void, Related_Nod, Related_Id, Suffix);
17694
17695                   Set_Entity (Subtype_Mark (S), Full_View (Subtype_Mark_Id));
17696                   Constrain_Concurrent (Full_View_Id, S,
17697                     Related_Nod, Related_Id, Suffix);
17698                   Set_Entity (Subtype_Mark (S), Subtype_Mark_Id);
17699                   Set_Full_View (Def_Id, Full_View_Id);
17700
17701                   --  Introduce an explicit reference to the private subtype,
17702                   --  to prevent scope anomalies in gigi if first use appears
17703                   --  in a nested context, e.g. a later function body.
17704                   --  Should this be generated in other contexts than a full
17705                   --  type declaration?
17706
17707                   if Is_Itype (Def_Id)
17708                     and then
17709                       Nkind (Parent (P)) = N_Full_Type_Declaration
17710                   then
17711                      Build_Itype_Reference (Def_Id, Parent (P));
17712                   end if;
17713
17714                else
17715                   Prepare_Private_Subtype_Completion (Def_Id, Related_Nod);
17716                end if;
17717
17718             when Concurrent_Kind  =>
17719                Constrain_Concurrent (Def_Id, S,
17720                  Related_Nod, Related_Id, Suffix);
17721
17722             when others =>
17723                Error_Msg_N ("invalid subtype mark in subtype indication", S);
17724          end case;
17725
17726          --  Size and Convention are always inherited from the base type
17727
17728          Set_Size_Info  (Def_Id,            (Subtype_Mark_Id));
17729          Set_Convention (Def_Id, Convention (Subtype_Mark_Id));
17730
17731          return Def_Id;
17732       end if;
17733    end Process_Subtype;
17734
17735    ---------------------------------------
17736    -- Check_Anonymous_Access_Components --
17737    ---------------------------------------
17738
17739    procedure Check_Anonymous_Access_Components
17740       (Typ_Decl  : Node_Id;
17741        Typ       : Entity_Id;
17742        Prev      : Entity_Id;
17743        Comp_List : Node_Id)
17744    is
17745       Loc         : constant Source_Ptr := Sloc (Typ_Decl);
17746       Anon_Access : Entity_Id;
17747       Acc_Def     : Node_Id;
17748       Comp        : Node_Id;
17749       Comp_Def    : Node_Id;
17750       Decl        : Node_Id;
17751       Type_Def    : Node_Id;
17752
17753       procedure Build_Incomplete_Type_Declaration;
17754       --  If the record type contains components that include an access to the
17755       --  current record, then create an incomplete type declaration for the
17756       --  record, to be used as the designated type of the anonymous access.
17757       --  This is done only once, and only if there is no previous partial
17758       --  view of the type.
17759
17760       function Designates_T (Subt : Node_Id) return Boolean;
17761       --  Check whether a node designates the enclosing record type, or 'Class
17762       --  of that type
17763
17764       function Mentions_T (Acc_Def : Node_Id) return Boolean;
17765       --  Check whether an access definition includes a reference to
17766       --  the enclosing record type. The reference can be a subtype mark
17767       --  in the access definition itself, a 'Class attribute reference, or
17768       --  recursively a reference appearing in a parameter specification
17769       --  or result definition of an access_to_subprogram definition.
17770
17771       --------------------------------------
17772       -- Build_Incomplete_Type_Declaration --
17773       --------------------------------------
17774
17775       procedure Build_Incomplete_Type_Declaration is
17776          Decl  : Node_Id;
17777          Inc_T : Entity_Id;
17778          H     : Entity_Id;
17779
17780          --  Is_Tagged indicates whether the type is tagged. It is tagged if
17781          --  it's "is new ... with record" or else "is tagged record ...".
17782
17783          Is_Tagged : constant Boolean :=
17784              (Nkind (Type_Definition (Typ_Decl)) = N_Derived_Type_Definition
17785                  and then
17786                    Present
17787                      (Record_Extension_Part (Type_Definition (Typ_Decl))))
17788            or else
17789              (Nkind (Type_Definition (Typ_Decl)) = N_Record_Definition
17790                  and then Tagged_Present (Type_Definition (Typ_Decl)));
17791
17792       begin
17793          --  If there is a previous partial view, no need to create a new one
17794          --  If the partial view, given by Prev, is incomplete,  If Prev is
17795          --  a private declaration, full declaration is flagged accordingly.
17796
17797          if Prev /= Typ then
17798             if Is_Tagged then
17799                Make_Class_Wide_Type (Prev);
17800                Set_Class_Wide_Type (Typ, Class_Wide_Type (Prev));
17801                Set_Etype (Class_Wide_Type (Typ), Typ);
17802             end if;
17803
17804             return;
17805
17806          elsif Has_Private_Declaration (Typ) then
17807
17808             --  If we refer to T'Class inside T, and T is the completion of a
17809             --  private type, then we need to make sure the class-wide type
17810             --  exists.
17811
17812             if Is_Tagged then
17813                Make_Class_Wide_Type (Typ);
17814             end if;
17815
17816             return;
17817
17818          --  If there was a previous anonymous access type, the incomplete
17819          --  type declaration will have been created already.
17820
17821          elsif Present (Current_Entity (Typ))
17822            and then Ekind (Current_Entity (Typ)) = E_Incomplete_Type
17823            and then Full_View (Current_Entity (Typ)) = Typ
17824          then
17825             if Is_Tagged
17826               and then Comes_From_Source (Current_Entity (Typ))
17827               and then not Is_Tagged_Type (Current_Entity (Typ))
17828             then
17829                Make_Class_Wide_Type (Typ);
17830                Error_Msg_N
17831                  ("incomplete view of tagged type should be declared tagged?",
17832                   Parent (Current_Entity (Typ)));
17833             end if;
17834             return;
17835
17836          else
17837             Inc_T := Make_Defining_Identifier (Loc, Chars (Typ));
17838             Decl  := Make_Incomplete_Type_Declaration (Loc, Inc_T);
17839
17840             --  Type has already been inserted into the current scope. Remove
17841             --  it, and add incomplete declaration for type, so that subsequent
17842             --  anonymous access types can use it. The entity is unchained from
17843             --  the homonym list and from immediate visibility. After analysis,
17844             --  the entity in the incomplete declaration becomes immediately
17845             --  visible in the record declaration that follows.
17846
17847             H := Current_Entity (Typ);
17848
17849             if H = Typ then
17850                Set_Name_Entity_Id (Chars (Typ), Homonym (Typ));
17851             else
17852                while Present (H)
17853                  and then Homonym (H) /= Typ
17854                loop
17855                   H := Homonym (Typ);
17856                end loop;
17857
17858                Set_Homonym (H, Homonym (Typ));
17859             end if;
17860
17861             Insert_Before (Typ_Decl, Decl);
17862             Analyze (Decl);
17863             Set_Full_View (Inc_T, Typ);
17864
17865             if Is_Tagged then
17866
17867                --  Create a common class-wide type for both views, and set the
17868                --  Etype of the class-wide type to the full view.
17869
17870                Make_Class_Wide_Type (Inc_T);
17871                Set_Class_Wide_Type (Typ, Class_Wide_Type (Inc_T));
17872                Set_Etype (Class_Wide_Type (Typ), Typ);
17873             end if;
17874          end if;
17875       end Build_Incomplete_Type_Declaration;
17876
17877       ------------------
17878       -- Designates_T --
17879       ------------------
17880
17881       function Designates_T (Subt : Node_Id) return Boolean is
17882          Type_Id : constant Name_Id := Chars (Typ);
17883
17884          function Names_T (Nam : Node_Id) return Boolean;
17885          --  The record type has not been introduced in the current scope
17886          --  yet, so we must examine the name of the type itself, either
17887          --  an identifier T, or an expanded name of the form P.T, where
17888          --  P denotes the current scope.
17889
17890          -------------
17891          -- Names_T --
17892          -------------
17893
17894          function Names_T (Nam : Node_Id) return Boolean is
17895          begin
17896             if Nkind (Nam) = N_Identifier then
17897                return Chars (Nam) = Type_Id;
17898
17899             elsif Nkind (Nam) = N_Selected_Component then
17900                if Chars (Selector_Name (Nam)) = Type_Id then
17901                   if Nkind (Prefix (Nam)) = N_Identifier then
17902                      return Chars (Prefix (Nam)) = Chars (Current_Scope);
17903
17904                   elsif Nkind (Prefix (Nam)) = N_Selected_Component then
17905                      return Chars (Selector_Name (Prefix (Nam))) =
17906                             Chars (Current_Scope);
17907                   else
17908                      return False;
17909                   end if;
17910
17911                else
17912                   return False;
17913                end if;
17914
17915             else
17916                return False;
17917             end if;
17918          end Names_T;
17919
17920       --  Start of processing for Designates_T
17921
17922       begin
17923          if Nkind (Subt) = N_Identifier then
17924             return Chars (Subt) = Type_Id;
17925
17926             --  Reference can be through an expanded name which has not been
17927             --  analyzed yet, and which designates enclosing scopes.
17928
17929          elsif Nkind (Subt) = N_Selected_Component then
17930             if Names_T (Subt) then
17931                return True;
17932
17933             --  Otherwise it must denote an entity that is already visible.
17934             --  The access definition may name a subtype of the enclosing
17935             --  type, if there is a previous incomplete declaration for it.
17936
17937             else
17938                Find_Selected_Component (Subt);
17939                return
17940                  Is_Entity_Name (Subt)
17941                    and then Scope (Entity (Subt)) = Current_Scope
17942                    and then
17943                      (Chars (Base_Type (Entity (Subt))) = Type_Id
17944                        or else
17945                          (Is_Class_Wide_Type (Entity (Subt))
17946                            and then
17947                            Chars (Etype (Base_Type (Entity (Subt)))) =
17948                                                                   Type_Id));
17949             end if;
17950
17951          --  A reference to the current type may appear as the prefix of
17952          --  a 'Class attribute.
17953
17954          elsif Nkind (Subt) = N_Attribute_Reference
17955            and then Attribute_Name (Subt) = Name_Class
17956          then
17957             return Names_T (Prefix (Subt));
17958
17959          else
17960             return False;
17961          end if;
17962       end Designates_T;
17963
17964       ----------------
17965       -- Mentions_T --
17966       ----------------
17967
17968       function Mentions_T (Acc_Def : Node_Id) return Boolean is
17969          Param_Spec : Node_Id;
17970
17971          Acc_Subprg : constant Node_Id :=
17972                         Access_To_Subprogram_Definition (Acc_Def);
17973
17974       begin
17975          if No (Acc_Subprg) then
17976             return Designates_T (Subtype_Mark (Acc_Def));
17977          end if;
17978
17979          --  Component is an access_to_subprogram: examine its formals,
17980          --  and result definition in the case of an access_to_function.
17981
17982          Param_Spec := First (Parameter_Specifications (Acc_Subprg));
17983          while Present (Param_Spec) loop
17984             if Nkind (Parameter_Type (Param_Spec)) = N_Access_Definition
17985               and then Mentions_T (Parameter_Type (Param_Spec))
17986             then
17987                return True;
17988
17989             elsif Designates_T (Parameter_Type (Param_Spec)) then
17990                return True;
17991             end if;
17992
17993             Next (Param_Spec);
17994          end loop;
17995
17996          if Nkind (Acc_Subprg) = N_Access_Function_Definition then
17997             if Nkind (Result_Definition (Acc_Subprg)) =
17998                  N_Access_Definition
17999             then
18000                return Mentions_T (Result_Definition (Acc_Subprg));
18001             else
18002                return Designates_T (Result_Definition (Acc_Subprg));
18003             end if;
18004          end if;
18005
18006          return False;
18007       end Mentions_T;
18008
18009    --  Start of processing for Check_Anonymous_Access_Components
18010
18011    begin
18012       if No (Comp_List) then
18013          return;
18014       end if;
18015
18016       Comp := First (Component_Items (Comp_List));
18017       while Present (Comp) loop
18018          if Nkind (Comp) = N_Component_Declaration
18019            and then Present
18020              (Access_Definition (Component_Definition (Comp)))
18021            and then
18022              Mentions_T (Access_Definition (Component_Definition (Comp)))
18023          then
18024             Comp_Def := Component_Definition (Comp);
18025             Acc_Def :=
18026               Access_To_Subprogram_Definition
18027                 (Access_Definition (Comp_Def));
18028
18029             Build_Incomplete_Type_Declaration;
18030             Anon_Access := Make_Temporary (Loc, 'S');
18031
18032             --  Create a declaration for the anonymous access type: either
18033             --  an access_to_object or an access_to_subprogram.
18034
18035             if Present (Acc_Def) then
18036                if Nkind  (Acc_Def) = N_Access_Function_Definition then
18037                   Type_Def :=
18038                     Make_Access_Function_Definition (Loc,
18039                       Parameter_Specifications =>
18040                         Parameter_Specifications (Acc_Def),
18041                       Result_Definition => Result_Definition (Acc_Def));
18042                else
18043                   Type_Def :=
18044                     Make_Access_Procedure_Definition (Loc,
18045                       Parameter_Specifications =>
18046                         Parameter_Specifications (Acc_Def));
18047                end if;
18048
18049             else
18050                Type_Def :=
18051                  Make_Access_To_Object_Definition (Loc,
18052                    Subtype_Indication =>
18053                       Relocate_Node
18054                         (Subtype_Mark
18055                           (Access_Definition (Comp_Def))));
18056
18057                Set_Constant_Present
18058                  (Type_Def, Constant_Present (Access_Definition (Comp_Def)));
18059                Set_All_Present
18060                  (Type_Def, All_Present (Access_Definition (Comp_Def)));
18061             end if;
18062
18063             Set_Null_Exclusion_Present
18064               (Type_Def,
18065                Null_Exclusion_Present (Access_Definition (Comp_Def)));
18066
18067             Decl :=
18068               Make_Full_Type_Declaration (Loc,
18069                 Defining_Identifier => Anon_Access,
18070                 Type_Definition     => Type_Def);
18071
18072             Insert_Before (Typ_Decl, Decl);
18073             Analyze (Decl);
18074
18075             --  If an access to object, Preserve entity of designated type,
18076             --  for ASIS use, before rewriting the component definition.
18077
18078             if No (Acc_Def) then
18079                declare
18080                   Desig : Entity_Id;
18081
18082                begin
18083                   Desig := Entity (Subtype_Indication (Type_Def));
18084
18085                   --  If the access definition is to the current  record,
18086                   --  the visible entity at this point is an  incomplete
18087                   --  type. Retrieve the full view to simplify  ASIS queries
18088
18089                   if Ekind (Desig) = E_Incomplete_Type then
18090                      Desig := Full_View (Desig);
18091                   end if;
18092
18093                   Set_Entity
18094                     (Subtype_Mark (Access_Definition  (Comp_Def)), Desig);
18095                end;
18096             end if;
18097
18098             Rewrite (Comp_Def,
18099               Make_Component_Definition (Loc,
18100                 Subtype_Indication =>
18101                New_Occurrence_Of (Anon_Access, Loc)));
18102
18103             if Ekind (Designated_Type (Anon_Access)) = E_Subprogram_Type then
18104                Set_Ekind (Anon_Access, E_Anonymous_Access_Subprogram_Type);
18105             else
18106                Set_Ekind (Anon_Access, E_Anonymous_Access_Type);
18107             end if;
18108
18109             Set_Is_Local_Anonymous_Access (Anon_Access);
18110          end if;
18111
18112          Next (Comp);
18113       end loop;
18114
18115       if Present (Variant_Part (Comp_List)) then
18116          declare
18117             V : Node_Id;
18118          begin
18119             V := First_Non_Pragma (Variants (Variant_Part (Comp_List)));
18120             while Present (V) loop
18121                Check_Anonymous_Access_Components
18122                  (Typ_Decl, Typ, Prev, Component_List (V));
18123                Next_Non_Pragma (V);
18124             end loop;
18125          end;
18126       end if;
18127    end Check_Anonymous_Access_Components;
18128
18129    --------------------------------
18130    -- Preanalyze_Spec_Expression --
18131    --------------------------------
18132
18133    procedure Preanalyze_Spec_Expression (N : Node_Id; T : Entity_Id) is
18134       Save_In_Spec_Expression : constant Boolean := In_Spec_Expression;
18135    begin
18136       In_Spec_Expression := True;
18137       Preanalyze_And_Resolve (N, T);
18138       In_Spec_Expression := Save_In_Spec_Expression;
18139    end Preanalyze_Spec_Expression;
18140
18141    -----------------------------
18142    -- Record_Type_Declaration --
18143    -----------------------------
18144
18145    procedure Record_Type_Declaration
18146      (T    : Entity_Id;
18147       N    : Node_Id;
18148       Prev : Entity_Id)
18149    is
18150       Def       : constant Node_Id := Type_Definition (N);
18151       Is_Tagged : Boolean;
18152       Tag_Comp  : Entity_Id;
18153
18154    begin
18155       --  These flags must be initialized before calling Process_Discriminants
18156       --  because this routine makes use of them.
18157
18158       Set_Ekind             (T, E_Record_Type);
18159       Set_Etype             (T, T);
18160       Init_Size_Align       (T);
18161       Set_Interfaces        (T, No_Elist);
18162       Set_Stored_Constraint (T, No_Elist);
18163
18164       --  Normal case
18165
18166       if Ada_Version < Ada_2005
18167         or else not Interface_Present (Def)
18168       then
18169          --  The flag Is_Tagged_Type might have already been set by
18170          --  Find_Type_Name if it detected an error for declaration T. This
18171          --  arises in the case of private tagged types where the full view
18172          --  omits the word tagged.
18173
18174          Is_Tagged :=
18175            Tagged_Present (Def)
18176              or else (Serious_Errors_Detected > 0 and then Is_Tagged_Type (T));
18177
18178          Set_Is_Tagged_Type      (T, Is_Tagged);
18179          Set_Is_Limited_Record   (T, Limited_Present (Def));
18180
18181          --  Type is abstract if full declaration carries keyword, or if
18182          --  previous partial view did.
18183
18184          Set_Is_Abstract_Type    (T, Is_Abstract_Type (T)
18185                                       or else Abstract_Present (Def));
18186
18187       else
18188          Is_Tagged := True;
18189          Analyze_Interface_Declaration (T, Def);
18190
18191          if Present (Discriminant_Specifications (N)) then
18192             Error_Msg_N
18193               ("interface types cannot have discriminants",
18194                 Defining_Identifier
18195                   (First (Discriminant_Specifications (N))));
18196          end if;
18197       end if;
18198
18199       --  First pass: if there are self-referential access components,
18200       --  create the required anonymous access type declarations, and if
18201       --  need be an incomplete type declaration for T itself.
18202
18203       Check_Anonymous_Access_Components (N, T, Prev, Component_List (Def));
18204
18205       if Ada_Version >= Ada_2005
18206         and then Present (Interface_List (Def))
18207       then
18208          Check_Interfaces (N, Def);
18209
18210          declare
18211             Ifaces_List : Elist_Id;
18212
18213          begin
18214             --  Ada 2005 (AI-251): Collect the list of progenitors that are not
18215             --  already in the parents.
18216
18217             Collect_Interfaces
18218               (T               => T,
18219                Ifaces_List     => Ifaces_List,
18220                Exclude_Parents => True);
18221
18222             Set_Interfaces (T, Ifaces_List);
18223          end;
18224       end if;
18225
18226       --  Records constitute a scope for the component declarations within.
18227       --  The scope is created prior to the processing of these declarations.
18228       --  Discriminants are processed first, so that they are visible when
18229       --  processing the other components. The Ekind of the record type itself
18230       --  is set to E_Record_Type (subtypes appear as E_Record_Subtype).
18231
18232       --  Enter record scope
18233
18234       Push_Scope (T);
18235
18236       --  If an incomplete or private type declaration was already given for
18237       --  the type, then this scope already exists, and the discriminants have
18238       --  been declared within. We must verify that the full declaration
18239       --  matches the incomplete one.
18240
18241       Check_Or_Process_Discriminants (N, T, Prev);
18242
18243       Set_Is_Constrained     (T, not Has_Discriminants (T));
18244       Set_Has_Delayed_Freeze (T, True);
18245
18246       --  For tagged types add a manually analyzed component corresponding
18247       --  to the component _tag, the corresponding piece of tree will be
18248       --  expanded as part of the freezing actions if it is not a CPP_Class.
18249
18250       if Is_Tagged then
18251
18252          --  Do not add the tag unless we are in expansion mode
18253
18254          if Expander_Active then
18255             Tag_Comp := Make_Defining_Identifier (Sloc (Def), Name_uTag);
18256             Enter_Name (Tag_Comp);
18257
18258             Set_Ekind                     (Tag_Comp, E_Component);
18259             Set_Is_Tag                    (Tag_Comp);
18260             Set_Is_Aliased                (Tag_Comp);
18261             Set_Etype                     (Tag_Comp, RTE (RE_Tag));
18262             Set_DT_Entry_Count            (Tag_Comp, No_Uint);
18263             Set_Original_Record_Component (Tag_Comp, Tag_Comp);
18264             Init_Component_Location       (Tag_Comp);
18265
18266             --  Ada 2005 (AI-251): Addition of the Tag corresponding to all the
18267             --  implemented interfaces.
18268
18269             if Has_Interfaces (T) then
18270                Add_Interface_Tag_Components (N, T);
18271             end if;
18272          end if;
18273
18274          Make_Class_Wide_Type (T);
18275          Set_Direct_Primitive_Operations (T, New_Elmt_List);
18276       end if;
18277
18278       --  We must suppress range checks when processing record components in
18279       --  the presence of discriminants, since we don't want spurious checks to
18280       --  be generated during their analysis, but Suppress_Range_Checks flags
18281       --  must be reset the after processing the record definition.
18282
18283       --  Note: this is the only use of Kill_Range_Checks, and is a bit odd,
18284       --  couldn't we just use the normal range check suppression method here.
18285       --  That would seem cleaner ???
18286
18287       if Has_Discriminants (T) and then not Range_Checks_Suppressed (T) then
18288          Set_Kill_Range_Checks (T, True);
18289          Record_Type_Definition (Def, Prev);
18290          Set_Kill_Range_Checks (T, False);
18291       else
18292          Record_Type_Definition (Def, Prev);
18293       end if;
18294
18295       --  Exit from record scope
18296
18297       End_Scope;
18298
18299       --  Ada 2005 (AI-251 and AI-345): Derive the interface subprograms of all
18300       --  the implemented interfaces and associate them an aliased entity.
18301
18302       if Is_Tagged
18303         and then not Is_Empty_List (Interface_List (Def))
18304       then
18305          Derive_Progenitor_Subprograms (T, T);
18306       end if;
18307    end Record_Type_Declaration;
18308
18309    ----------------------------
18310    -- Record_Type_Definition --
18311    ----------------------------
18312
18313    procedure Record_Type_Definition (Def : Node_Id; Prev_T : Entity_Id) is
18314       Component          : Entity_Id;
18315       Ctrl_Components    : Boolean := False;
18316       Final_Storage_Only : Boolean;
18317       T                  : Entity_Id;
18318
18319    begin
18320       if Ekind (Prev_T) = E_Incomplete_Type then
18321          T := Full_View (Prev_T);
18322       else
18323          T := Prev_T;
18324       end if;
18325
18326       Final_Storage_Only := not Is_Controlled (T);
18327
18328       --  Ada 2005: check whether an explicit Limited is present in a derived
18329       --  type declaration.
18330
18331       if Nkind (Parent (Def)) = N_Derived_Type_Definition
18332         and then Limited_Present (Parent (Def))
18333       then
18334          Set_Is_Limited_Record (T);
18335       end if;
18336
18337       --  If the component list of a record type is defined by the reserved
18338       --  word null and there is no discriminant part, then the record type has
18339       --  no components and all records of the type are null records (RM 3.7)
18340       --  This procedure is also called to process the extension part of a
18341       --  record extension, in which case the current scope may have inherited
18342       --  components.
18343
18344       if No (Def)
18345         or else No (Component_List (Def))
18346         or else Null_Present (Component_List (Def))
18347       then
18348          null;
18349
18350       else
18351          Analyze_Declarations (Component_Items (Component_List (Def)));
18352
18353          if Present (Variant_Part (Component_List (Def))) then
18354             Analyze (Variant_Part (Component_List (Def)));
18355          end if;
18356       end if;
18357
18358       --  After completing the semantic analysis of the record definition,
18359       --  record components, both new and inherited, are accessible. Set their
18360       --  kind accordingly. Exclude malformed itypes from illegal declarations,
18361       --  whose Ekind may be void.
18362
18363       Component := First_Entity (Current_Scope);
18364       while Present (Component) loop
18365          if Ekind (Component) = E_Void
18366            and then not Is_Itype (Component)
18367          then
18368             Set_Ekind (Component, E_Component);
18369             Init_Component_Location (Component);
18370          end if;
18371
18372          if Has_Task (Etype (Component)) then
18373             Set_Has_Task (T);
18374          end if;
18375
18376          if Ekind (Component) /= E_Component then
18377             null;
18378
18379          --  Do not set Has_Controlled_Component on a class-wide equivalent
18380          --  type. See Make_CW_Equivalent_Type.
18381
18382          elsif not Is_Class_Wide_Equivalent_Type (T)
18383            and then (Has_Controlled_Component (Etype (Component))
18384                       or else (Chars (Component) /= Name_uParent
18385                                 and then Is_Controlled (Etype (Component))))
18386          then
18387             Set_Has_Controlled_Component (T, True);
18388             Final_Storage_Only :=
18389               Final_Storage_Only
18390                 and then Finalize_Storage_Only (Etype (Component));
18391             Ctrl_Components := True;
18392          end if;
18393
18394          Next_Entity (Component);
18395       end loop;
18396
18397       --  A Type is Finalize_Storage_Only only if all its controlled components
18398       --  are also.
18399
18400       if Ctrl_Components then
18401          Set_Finalize_Storage_Only (T, Final_Storage_Only);
18402       end if;
18403
18404       --  Place reference to end record on the proper entity, which may
18405       --  be a partial view.
18406
18407       if Present (Def) then
18408          Process_End_Label (Def, 'e', Prev_T);
18409       end if;
18410    end Record_Type_Definition;
18411
18412    ------------------------
18413    -- Replace_Components --
18414    ------------------------
18415
18416    procedure Replace_Components (Typ : Entity_Id; Decl : Node_Id) is
18417       function Process (N : Node_Id) return Traverse_Result;
18418
18419       -------------
18420       -- Process --
18421       -------------
18422
18423       function Process (N : Node_Id) return Traverse_Result is
18424          Comp : Entity_Id;
18425
18426       begin
18427          if Nkind (N) = N_Discriminant_Specification then
18428             Comp := First_Discriminant (Typ);
18429             while Present (Comp) loop
18430                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18431                   Set_Defining_Identifier (N, Comp);
18432                   exit;
18433                end if;
18434
18435                Next_Discriminant (Comp);
18436             end loop;
18437
18438          elsif Nkind (N) = N_Component_Declaration then
18439             Comp := First_Component (Typ);
18440             while Present (Comp) loop
18441                if Chars (Comp) = Chars (Defining_Identifier (N)) then
18442                   Set_Defining_Identifier (N, Comp);
18443                   exit;
18444                end if;
18445
18446                Next_Component (Comp);
18447             end loop;
18448          end if;
18449
18450          return OK;
18451       end Process;
18452
18453       procedure Replace is new Traverse_Proc (Process);
18454
18455    --  Start of processing for Replace_Components
18456
18457    begin
18458       Replace (Decl);
18459    end Replace_Components;
18460
18461    -------------------------------
18462    -- Set_Completion_Referenced --
18463    -------------------------------
18464
18465    procedure Set_Completion_Referenced (E : Entity_Id) is
18466    begin
18467       --  If in main unit, mark entity that is a completion as referenced,
18468       --  warnings go on the partial view when needed.
18469
18470       if In_Extended_Main_Source_Unit (E) then
18471          Set_Referenced (E);
18472       end if;
18473    end Set_Completion_Referenced;
18474
18475    ---------------------
18476    -- Set_Fixed_Range --
18477    ---------------------
18478
18479    --  The range for fixed-point types is complicated by the fact that we
18480    --  do not know the exact end points at the time of the declaration. This
18481    --  is true for three reasons:
18482
18483    --     A size clause may affect the fudging of the end-points
18484    --     A small clause may affect the values of the end-points
18485    --     We try to include the end-points if it does not affect the size
18486
18487    --  This means that the actual end-points must be established at the point
18488    --  when the type is frozen. Meanwhile, we first narrow the range as
18489    --  permitted (so that it will fit if necessary in a small specified size),
18490    --  and then build a range subtree with these narrowed bounds.
18491
18492    --  Set_Fixed_Range constructs the range from real literal values, and sets
18493    --  the range as the Scalar_Range of the given fixed-point type entity.
18494
18495    --  The parent of this range is set to point to the entity so that it is
18496    --  properly hooked into the tree (unlike normal Scalar_Range entries for
18497    --  other scalar types, which are just pointers to the range in the
18498    --  original tree, this would otherwise be an orphan).
18499
18500    --  The tree is left unanalyzed. When the type is frozen, the processing
18501    --  in Freeze.Freeze_Fixed_Point_Type notices that the range is not
18502    --  analyzed, and uses this as an indication that it should complete
18503    --  work on the range (it will know the final small and size values).
18504
18505    procedure Set_Fixed_Range
18506      (E   : Entity_Id;
18507       Loc : Source_Ptr;
18508       Lo  : Ureal;
18509       Hi  : Ureal)
18510    is
18511       S : constant Node_Id :=
18512             Make_Range (Loc,
18513               Low_Bound  => Make_Real_Literal (Loc, Lo),
18514               High_Bound => Make_Real_Literal (Loc, Hi));
18515    begin
18516       Set_Scalar_Range (E, S);
18517       Set_Parent (S, E);
18518    end Set_Fixed_Range;
18519
18520    ----------------------------------
18521    -- Set_Scalar_Range_For_Subtype --
18522    ----------------------------------
18523
18524    procedure Set_Scalar_Range_For_Subtype
18525      (Def_Id : Entity_Id;
18526       R      : Node_Id;
18527       Subt   : Entity_Id)
18528    is
18529       Kind : constant Entity_Kind :=  Ekind (Def_Id);
18530
18531    begin
18532       --  Defend against previous error
18533
18534       if Nkind (R) = N_Error then
18535          return;
18536       end if;
18537
18538       Set_Scalar_Range (Def_Id, R);
18539
18540       --  We need to link the range into the tree before resolving it so
18541       --  that types that are referenced, including importantly the subtype
18542       --  itself, are properly frozen (Freeze_Expression requires that the
18543       --  expression be properly linked into the tree). Of course if it is
18544       --  already linked in, then we do not disturb the current link.
18545
18546       if No (Parent (R)) then
18547          Set_Parent (R, Def_Id);
18548       end if;
18549
18550       --  Reset the kind of the subtype during analysis of the range, to
18551       --  catch possible premature use in the bounds themselves.
18552
18553       Set_Ekind (Def_Id, E_Void);
18554       Process_Range_Expr_In_Decl (R, Subt);
18555       Set_Ekind (Def_Id, Kind);
18556    end Set_Scalar_Range_For_Subtype;
18557
18558    --------------------------------------------------------
18559    -- Set_Stored_Constraint_From_Discriminant_Constraint --
18560    --------------------------------------------------------
18561
18562    procedure Set_Stored_Constraint_From_Discriminant_Constraint
18563      (E : Entity_Id)
18564    is
18565    begin
18566       --  Make sure set if encountered during Expand_To_Stored_Constraint
18567
18568       Set_Stored_Constraint (E, No_Elist);
18569
18570       --  Give it the right value
18571
18572       if Is_Constrained (E) and then Has_Discriminants (E) then
18573          Set_Stored_Constraint (E,
18574            Expand_To_Stored_Constraint (E, Discriminant_Constraint (E)));
18575       end if;
18576    end Set_Stored_Constraint_From_Discriminant_Constraint;
18577
18578    -------------------------------------
18579    -- Signed_Integer_Type_Declaration --
18580    -------------------------------------
18581
18582    procedure Signed_Integer_Type_Declaration (T : Entity_Id; Def : Node_Id) is
18583       Implicit_Base : Entity_Id;
18584       Base_Typ      : Entity_Id;
18585       Lo_Val        : Uint;
18586       Hi_Val        : Uint;
18587       Errs          : Boolean := False;
18588       Lo            : Node_Id;
18589       Hi            : Node_Id;
18590
18591       function Can_Derive_From (E : Entity_Id) return Boolean;
18592       --  Determine whether given bounds allow derivation from specified type
18593
18594       procedure Check_Bound (Expr : Node_Id);
18595       --  Check bound to make sure it is integral and static. If not, post
18596       --  appropriate error message and set Errs flag
18597
18598       ---------------------
18599       -- Can_Derive_From --
18600       ---------------------
18601
18602       --  Note we check both bounds against both end values, to deal with
18603       --  strange types like ones with a range of 0 .. -12341234.
18604
18605       function Can_Derive_From (E : Entity_Id) return Boolean is
18606          Lo : constant Uint := Expr_Value (Type_Low_Bound (E));
18607          Hi : constant Uint := Expr_Value (Type_High_Bound (E));
18608       begin
18609          return Lo <= Lo_Val and then Lo_Val <= Hi
18610                   and then
18611                 Lo <= Hi_Val and then Hi_Val <= Hi;
18612       end Can_Derive_From;
18613
18614       -----------------
18615       -- Check_Bound --
18616       -----------------
18617
18618       procedure Check_Bound (Expr : Node_Id) is
18619       begin
18620          --  If a range constraint is used as an integer type definition, each
18621          --  bound of the range must be defined by a static expression of some
18622          --  integer type, but the two bounds need not have the same integer
18623          --  type (Negative bounds are allowed.) (RM 3.5.4)
18624
18625          if not Is_Integer_Type (Etype (Expr)) then
18626             Error_Msg_N
18627               ("integer type definition bounds must be of integer type", Expr);
18628             Errs := True;
18629
18630          elsif not Is_OK_Static_Expression (Expr) then
18631             Flag_Non_Static_Expr
18632               ("non-static expression used for integer type bound!", Expr);
18633             Errs := True;
18634
18635          --  The bounds are folded into literals, and we set their type to be
18636          --  universal, to avoid typing difficulties: we cannot set the type
18637          --  of the literal to the new type, because this would be a forward
18638          --  reference for the back end,  and if the original type is user-
18639          --  defined this can lead to spurious semantic errors (e.g. 2928-003).
18640
18641          else
18642             if Is_Entity_Name (Expr) then
18643                Fold_Uint (Expr, Expr_Value (Expr), True);
18644             end if;
18645
18646             Set_Etype (Expr, Universal_Integer);
18647          end if;
18648       end Check_Bound;
18649
18650    --  Start of processing for Signed_Integer_Type_Declaration
18651
18652    begin
18653       --  Create an anonymous base type
18654
18655       Implicit_Base :=
18656         Create_Itype (E_Signed_Integer_Type, Parent (Def), T, 'B');
18657
18658       --  Analyze and check the bounds, they can be of any integer type
18659
18660       Lo := Low_Bound (Def);
18661       Hi := High_Bound (Def);
18662
18663       --  Arbitrarily use Integer as the type if either bound had an error
18664
18665       if Hi = Error or else Lo = Error then
18666          Base_Typ := Any_Integer;
18667          Set_Error_Posted (T, True);
18668
18669       --  Here both bounds are OK expressions
18670
18671       else
18672          Analyze_And_Resolve (Lo, Any_Integer);
18673          Analyze_And_Resolve (Hi, Any_Integer);
18674
18675          Check_Bound (Lo);
18676          Check_Bound (Hi);
18677
18678          if Errs then
18679             Hi := Type_High_Bound (Standard_Long_Long_Integer);
18680             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
18681          end if;
18682
18683          --  Find type to derive from
18684
18685          Lo_Val := Expr_Value (Lo);
18686          Hi_Val := Expr_Value (Hi);
18687
18688          if Can_Derive_From (Standard_Short_Short_Integer) then
18689             Base_Typ := Base_Type (Standard_Short_Short_Integer);
18690
18691          elsif Can_Derive_From (Standard_Short_Integer) then
18692             Base_Typ := Base_Type (Standard_Short_Integer);
18693
18694          elsif Can_Derive_From (Standard_Integer) then
18695             Base_Typ := Base_Type (Standard_Integer);
18696
18697          elsif Can_Derive_From (Standard_Long_Integer) then
18698             Base_Typ := Base_Type (Standard_Long_Integer);
18699
18700          elsif Can_Derive_From (Standard_Long_Long_Integer) then
18701             Base_Typ := Base_Type (Standard_Long_Long_Integer);
18702
18703          else
18704             Base_Typ := Base_Type (Standard_Long_Long_Integer);
18705             Error_Msg_N ("integer type definition bounds out of range", Def);
18706             Hi := Type_High_Bound (Standard_Long_Long_Integer);
18707             Lo := Type_Low_Bound (Standard_Long_Long_Integer);
18708          end if;
18709       end if;
18710
18711       --  Complete both implicit base and declared first subtype entities
18712
18713       Set_Etype          (Implicit_Base, Base_Typ);
18714       Set_Scalar_Range   (Implicit_Base, Scalar_Range   (Base_Typ));
18715       Set_Size_Info      (Implicit_Base,                (Base_Typ));
18716       Set_RM_Size        (Implicit_Base, RM_Size        (Base_Typ));
18717       Set_First_Rep_Item (Implicit_Base, First_Rep_Item (Base_Typ));
18718
18719       Set_Ekind          (T, E_Signed_Integer_Subtype);
18720       Set_Etype          (T, Implicit_Base);
18721
18722       Set_Size_Info      (T,                (Implicit_Base));
18723       Set_First_Rep_Item (T, First_Rep_Item (Implicit_Base));
18724       Set_Scalar_Range   (T, Def);
18725       Set_RM_Size        (T, UI_From_Int (Minimum_Size (T)));
18726       Set_Is_Constrained (T);
18727    end Signed_Integer_Type_Declaration;
18728
18729 end Sem_Ch3;